project
string | commit_id
string | target
int64 | func
string | cwe
string | big_vul_idx
string | idx
int64 | hash
string | size
float64 | message
string | dataset
string |
|---|---|---|---|---|---|---|---|---|---|---|
linux
|
efe4186e6a1b54bf38b9e05450d43b0da1fd7739
| 1
|
static void sixpack_close(struct tty_struct *tty)
{
struct sixpack *sp;
write_lock_irq(&disc_data_lock);
sp = tty->disc_data;
tty->disc_data = NULL;
write_unlock_irq(&disc_data_lock);
if (!sp)
return;
/*
* We have now ensured that nobody can start using ap from now on, but
* we have to wait for all existing users to finish.
*/
if (!refcount_dec_and_test(&sp->refcnt))
wait_for_completion(&sp->dead);
/* We must stop the queue to avoid potentially scribbling
* on the free buffers. The sp->dead completion is not sufficient
* to protect us from sp->xbuff access.
*/
netif_stop_queue(sp->dev);
del_timer_sync(&sp->tx_t);
del_timer_sync(&sp->resync_t);
unregister_netdev(sp->dev);
/* Free all 6pack frame buffers after unreg. */
kfree(sp->rbuff);
kfree(sp->xbuff);
free_netdev(sp->dev);
}
| null | null | 204,814
|
34119603289207627346986497632030740076
| 35
|
drivers: hamradio: 6pack: fix UAF bug caused by mod_timer()
When a 6pack device is detaching, the sixpack_close() will act to cleanup
necessary resources. Although del_timer_sync() in sixpack_close()
won't return if there is an active timer, one could use mod_timer() in
sp_xmit_on_air() to wake up timer again by calling userspace syscall such
as ax25_sendmsg(), ax25_connect() and ax25_ioctl().
This unexpected waked handler, sp_xmit_on_air(), realizes nothing about
the undergoing cleanup and may still call pty_write() to use driver layer
resources that have already been released.
One of the possible race conditions is shown below:
(USE) | (FREE)
ax25_sendmsg() |
ax25_queue_xmit() |
... |
sp_xmit() |
sp_encaps() | sixpack_close()
sp_xmit_on_air() | del_timer_sync(&sp->tx_t)
mod_timer(&sp->tx_t,...) | ...
| unregister_netdev()
| ...
(wait a while) | tty_release()
| tty_release_struct()
| release_tty()
sp_xmit_on_air() | tty_kref_put(tty_struct) //FREE
pty_write(tty_struct) //USE | ...
The corresponding fail log is shown below:
===============================================================
BUG: KASAN: use-after-free in __run_timers.part.0+0x170/0x470
Write of size 8 at addr ffff88800a652ab8 by task swapper/2/0
...
Call Trace:
...
queue_work_on+0x3f/0x50
pty_write+0xcd/0xe0pty_write+0xcd/0xe0
sp_xmit_on_air+0xb2/0x1f0
call_timer_fn+0x28/0x150
__run_timers.part.0+0x3c2/0x470
run_timer_softirq+0x3b/0x80
__do_softirq+0xf1/0x380
...
This patch reorders the del_timer_sync() after the unregister_netdev()
to avoid UAF bugs. Because the unregister_netdev() is well synchronized,
it flushs out any pending queues, waits the refcount of net_device
decreases to zero and removes net_device from kernel. There is not any
running routines after executing unregister_netdev(). Therefore, we could
not arouse timer from userspace again.
Signed-off-by: Duoming Zhou <[email protected]>
Reviewed-by: Lin Ma <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
|
other
|
linux
|
427215d85e8d1476da1a86b8d67aceb485eb3631
| 1
|
struct vfsmount *clone_private_mount(const struct path *path)
{
struct mount *old_mnt = real_mount(path->mnt);
struct mount *new_mnt;
if (IS_MNT_UNBINDABLE(old_mnt))
return ERR_PTR(-EINVAL);
new_mnt = clone_mnt(old_mnt, path->dentry, CL_PRIVATE);
if (IS_ERR(new_mnt))
return ERR_CAST(new_mnt);
/* Longterm mount to be removed by kern_unmount*() */
new_mnt->mnt_ns = MNT_NS_INTERNAL;
return &new_mnt->mnt;
}
| null | null | 204,830
|
94389509905056133386308491228723938372
| 17
|
ovl: prevent private clone if bind mount is not allowed
Add the following checks from __do_loopback() to clone_private_mount() as
well:
- verify that the mount is in the current namespace
- verify that there are no locked children
Reported-by: Alois Wohlschlager <[email protected]>
Fixes: c771d683a62e ("vfs: introduce clone_private_mount()")
Cc: <[email protected]> # v3.18
Signed-off-by: Miklos Szeredi <[email protected]>
|
other
|
radare2
|
153bcdc29f11cd8c90e7d639a7405450f644ddb6
| 1
|
RList *r_bin_ne_get_relocs(r_bin_ne_obj_t *bin) {
RList *segments = bin->segments;
if (!segments) {
return NULL;
}
RList *entries = bin->entries;
if (!entries) {
return NULL;
}
RList *symbols = bin->symbols;
if (!symbols) {
return NULL;
}
ut16 *modref = calloc (bin->ne_header->ModRefs, sizeof (ut16));
if (!modref) {
return NULL;
}
r_buf_read_at (bin->buf, (ut64)bin->ne_header->ModRefTable + bin->header_offset, (ut8 *)modref, bin->ne_header->ModRefs * sizeof (ut16));
RList *relocs = r_list_newf (free);
if (!relocs) {
free (modref);
return NULL;
}
RListIter *it;
RBinSection *seg;
int index = -1;
r_list_foreach (segments, it, seg) {
index++;
if (!(bin->segment_entries[index].flags & RELOCINFO)) {
continue;
}
ut32 off = seg->paddr + seg->size;
ut32 start = off;
ut16 length = r_buf_read_le16_at (bin->buf, off);
if (!length) {
continue;
}
off += 2;
// size_t buf_size = r_buf_size (bin->buf);
while (off < start + length * sizeof (NE_image_reloc_item)) {
// && off + sizeof (NE_image_reloc_item) < buf_size)
NE_image_reloc_item rel = {0};
if (r_buf_read_at (bin->buf, off, (ut8 *)&rel, sizeof (rel)) < 1) {
return NULL;
}
RBinReloc *reloc = R_NEW0 (RBinReloc);
if (!reloc) {
return NULL;
}
reloc->paddr = seg->paddr + rel.offset;
switch (rel.type) {
case LOBYTE:
reloc->type = R_BIN_RELOC_8;
break;
case SEL_16:
case OFF_16:
reloc->type = R_BIN_RELOC_16;
break;
case POI_32:
case OFF_32:
reloc->type = R_BIN_RELOC_32;
break;
case POI_48:
reloc->type = R_BIN_RELOC_64;
break;
}
ut32 offset;
if (rel.flags & (IMPORTED_ORD | IMPORTED_NAME)) {
RBinImport *imp = R_NEW0 (RBinImport);
if (!imp) {
free (reloc);
break;
}
char *name;
#if NE_BUG
if (rel.index > 0 && rel.index < bin->ne_header->ModRefs) {
offset = modref[rel.index - 1] + bin->header_offset + bin->ne_header->ImportNameTable;
name = __read_nonnull_str_at (bin->buf, offset);
} else {
name = r_str_newf ("UnknownModule%d_%x", rel.index, off); // ????
}
#else
if (rel.index > bin->ne_header->ModRefs) {
name = r_str_newf ("UnknownModule%d_%x", rel.index, off); // ????
} else {
offset = modref[rel.index - 1] + bin->header_offset + bin->ne_header->ImportNameTable;
name = __read_nonnull_str_at (bin->buf, offset);
}
#endif
if (rel.flags & IMPORTED_ORD) {
imp->ordinal = rel.func_ord;
imp->name = r_str_newf ("%s.%s", name, __func_name_from_ord(name, rel.func_ord));
} else {
offset = bin->header_offset + bin->ne_header->ImportNameTable + rel.name_off;
char *func = __read_nonnull_str_at (bin->buf, offset);
imp->name = r_str_newf ("%s.%s", name, func);
free (func);
}
free (name);
reloc->import = imp;
} else if (rel.flags & OSFIXUP) {
// TODO
} else {
if (strstr (seg->name, "FIXED")) {
RBinSection *s = r_list_get_n (segments, rel.segnum - 1);
if (s) {
offset = s->paddr + rel.segoff;
} else {
offset = -1;
}
} else {
RBinAddr *entry = r_list_get_n (entries, rel.entry_ordinal - 1);
if (entry) {
offset = entry->paddr;
} else {
offset = -1;
}
}
reloc->addend = offset;
RBinSymbol *sym = NULL;
RListIter *sit;
r_list_foreach (symbols, sit, sym) {
if (sym->paddr == reloc->addend) {
reloc->symbol = sym;
break;
}
}
}
if (rel.flags & ADDITIVE) {
reloc->additive = 1;
r_list_append (relocs, reloc);
} else {
do {
#if NE_BUG
if (reloc->paddr + 4 < r_buf_size (bin->buf)) {
break;
}
#endif
r_list_append (relocs, reloc);
offset = r_buf_read_le16_at (bin->buf, reloc->paddr);
RBinReloc *tmp = reloc;
reloc = R_NEW0 (RBinReloc);
if (!reloc) {
break;
}
*reloc = *tmp;
reloc->paddr = seg->paddr + offset;
} while (offset != 0xFFFF);
free (reloc);
}
off += sizeof (NE_image_reloc_item);
}
}
free (modref);
return relocs;
}
| null | null | 205,570
|
43335819365967830774615638271493426454
| 162
|
Fix oobread in NE parser ##crash
* Reported by @hmsec via huntr.dev
* Reproducer: necrash
* BountyID: 52b57274-0e1a-4d61-ab29-1373b555fea0/
|
other
|
ghostpdl
|
79cccf641486a6595c43f1de1cd7ade696020a31
| 1
|
gs_nulldevice(gs_gstate * pgs)
{
int code = 0;
if (pgs->device == 0 || !gx_device_is_null(pgs->device)) {
gx_device *ndev;
code = gs_copydevice(&ndev, (const gx_device *)&gs_null_device,
pgs->memory);
if (code < 0)
return code;
/*
* Internal devices have a reference count of 0, not 1,
* aside from references from graphics states.
*/
/* There is some strange use of the null device in the code. I need
to sort out how the icc profile is best handled with this device.
It seems to inherit properties from the current device if there
is one */
rc_init(ndev, pgs->memory, 0);
if (pgs->device != NULL) {
if ((code = dev_proc(pgs->device, get_profile)(pgs->device,
&(ndev->icc_struct))) < 0)
return code;
rc_increment(ndev->icc_struct);
set_dev_proc(ndev, get_profile, gx_default_get_profile);
}
if ((code = gs_setdevice_no_erase(pgs, ndev)) < 0)
gs_free_object(pgs->memory, ndev, "gs_copydevice(device)");
}
return code;
}
| null | null | 205,619
|
320988381385389776461252779550920204607
| 33
|
Bug 699654(2): preserve LockSafetyParams in the nulldevice
The nulldevice does not necessarily use the normal setpagedevice machinery,
but can be set using the nulldevice operator. In which case, we don't preserve
the settings from the original device (in the way setpagedevice does).
Since nulldevice does nothing, this is not generally a problem, but in the case
of LockSafetyParams it *is* important when we restore back to the original
device, when LockSafetyParams not being set is "preserved" into the post-
restore configuration.
We have to initialise the value to false because the nulldevice is used during
initialisation (before any other device exists), and *must* be writable for
that.
|
other
|
linux
|
32452a3eb8b64e01e2be717f518c0be046975b9d
| 1
|
static int io_rw_init_file(struct io_kiocb *req, fmode_t mode)
{
struct kiocb *kiocb = &req->rw.kiocb;
struct io_ring_ctx *ctx = req->ctx;
struct file *file = req->file;
int ret;
if (unlikely(!file || !(file->f_mode & mode)))
return -EBADF;
if (!io_req_ffs_set(req))
req->flags |= io_file_get_flags(file) << REQ_F_SUPPORT_NOWAIT_BIT;
kiocb->ki_flags = iocb_flags(file);
ret = kiocb_set_rw_flags(kiocb, req->rw.flags);
if (unlikely(ret))
return ret;
/*
* If the file is marked O_NONBLOCK, still allow retry for it if it
* supports async. Otherwise it's impossible to use O_NONBLOCK files
* reliably. If not, or it IOCB_NOWAIT is set, don't retry.
*/
if ((kiocb->ki_flags & IOCB_NOWAIT) ||
((file->f_flags & O_NONBLOCK) && !io_file_supports_nowait(req)))
req->flags |= REQ_F_NOWAIT;
if (ctx->flags & IORING_SETUP_IOPOLL) {
if (!(kiocb->ki_flags & IOCB_DIRECT) || !file->f_op->iopoll)
return -EOPNOTSUPP;
kiocb->ki_flags |= IOCB_HIPRI | IOCB_ALLOC_CACHE;
kiocb->ki_complete = io_complete_rw_iopoll;
req->iopoll_completed = 0;
} else {
if (kiocb->ki_flags & IOCB_HIPRI)
return -EINVAL;
kiocb->ki_complete = io_complete_rw;
}
return 0;
}
| null | null | 205,630
|
96047674375362496799593517379205519403
| 42
|
io_uring: fix uninitialized field in rw io_kiocb
io_rw_init_file does not initialize kiocb->private, so when iocb_bio_iopoll
reads kiocb->private it can contain uninitialized data.
Fixes: 3e08773c3841 ("block: switch polling to be bio based")
Signed-off-by: Joseph Ravichandran <[email protected]>
Signed-off-by: Jens Axboe <[email protected]>
|
other
|
linux
|
a2ef990ab5a6705a356d146dd773a3b359787497
| 1
|
static int proc_pid_permission(struct inode *inode, int mask)
{
struct pid_namespace *pid = inode->i_sb->s_fs_info;
struct task_struct *task;
bool has_perms;
task = get_proc_task(inode);
has_perms = has_pid_permissions(pid, task, 1);
put_task_struct(task);
if (!has_perms) {
if (pid->hide_pid == 2) {
/*
* Let's make getdents(), stat(), and open()
* consistent with each other. If a process
* may not stat() a file, it shouldn't be seen
* in procfs at all.
*/
return -ENOENT;
}
return -EPERM;
}
return generic_permission(inode, mask);
}
| null | null | 205,663
|
135255628387104225960874778723471285920
| 25
|
proc: fix null pointer deref in proc_pid_permission()
get_proc_task() can fail to search the task and return NULL,
put_task_struct() will then bomb the kernel with following oops:
BUG: unable to handle kernel NULL pointer dereference at 0000000000000010
IP: [<ffffffff81217d34>] proc_pid_permission+0x64/0xe0
PGD 112075067 PUD 112814067 PMD 0
Oops: 0002 [#1] PREEMPT SMP
This is a regression introduced by commit 0499680a ("procfs: add hidepid=
and gid= mount options"). The kernel should return -ESRCH if
get_proc_task() failed.
Signed-off-by: Xiaotian Feng <[email protected]>
Cc: Al Viro <[email protected]>
Cc: Vasiliy Kulikov <[email protected]>
Cc: Stephen Wilson <[email protected]>
Acked-by: David Rientjes <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
|
other
|
rizin
|
38d8006cd609ac75de82b705891d3508d2c218d5
| 1
|
static pyc_object *get_complex_object(RzBinPycObj *pyc, RzBuffer *buffer) {
pyc_object *ret = NULL;
bool error = false;
ut32 size = 0;
ut32 n1 = 0;
ut32 n2 = 0;
ret = RZ_NEW0(pyc_object);
if (!ret) {
return NULL;
}
if ((pyc->magic_int & 0xffff) <= 62061) {
n1 = get_ut8(buffer, &error);
} else {
n1 = get_st32(buffer, &error);
}
if (error) {
free(ret);
return NULL;
}
ut8 *s1 = malloc(n1 + 1);
if (!s1) {
return NULL;
}
/* object contain string representation of the number */
size = rz_buf_read(buffer, s1, n1);
if (size != n1) {
RZ_FREE(s1);
RZ_FREE(ret);
return NULL;
}
s1[n1] = '\0';
if ((pyc->magic_int & 0xffff) <= 62061) {
n2 = get_ut8(buffer, &error);
} else
n2 = get_st32(buffer, &error);
if (error) {
return NULL;
}
ut8 *s2 = malloc(n2 + 1);
if (!s2) {
return NULL;
}
/* object contain string representation of the number */
size = rz_buf_read(buffer, s2, n2);
if (size != n2) {
RZ_FREE(s1);
RZ_FREE(s2);
RZ_FREE(ret);
return NULL;
}
s2[n2] = '\0';
ret->type = TYPE_COMPLEX;
ret->data = rz_str_newf("%s+%sj", s1, s2);
RZ_FREE(s1);
RZ_FREE(s2);
if (!ret->data) {
RZ_FREE(ret);
return NULL;
}
return ret;
}
| null | null | 205,734
|
45385170421195869750980807202859649234
| 65
|
fix #2963 - oob write (1 byte) in pyc/marshal.c
|
other
|
linux
|
775c5033a0d164622d9d10dd0f0a5531639ed3ed
| 1
|
static inline void fuse_make_bad(struct inode *inode)
{
set_bit(FUSE_I_BAD, &get_fuse_inode(inode)->state);
}
| null | null | 205,736
|
307092165948896268565711171016597318269
| 4
|
fuse: fix live lock in fuse_iget()
Commit 5d069dbe8aaf ("fuse: fix bad inode") replaced make_bad_inode()
in fuse_iget() with a private implementation fuse_make_bad().
The private implementation fails to remove the bad inode from inode
cache, so the retry loop with iget5_locked() finds the same bad inode
and marks it bad forever.
kmsg snip:
[ ] rcu: INFO: rcu_sched self-detected stall on CPU
...
[ ] ? bit_wait_io+0x50/0x50
[ ] ? fuse_init_file_inode+0x70/0x70
[ ] ? find_inode.isra.32+0x60/0xb0
[ ] ? fuse_init_file_inode+0x70/0x70
[ ] ilookup5_nowait+0x65/0x90
[ ] ? fuse_init_file_inode+0x70/0x70
[ ] ilookup5.part.36+0x2e/0x80
[ ] ? fuse_init_file_inode+0x70/0x70
[ ] ? fuse_inode_eq+0x20/0x20
[ ] iget5_locked+0x21/0x80
[ ] ? fuse_inode_eq+0x20/0x20
[ ] fuse_iget+0x96/0x1b0
Fixes: 5d069dbe8aaf ("fuse: fix bad inode")
Cc: [email protected] # 5.10+
Signed-off-by: Amir Goldstein <[email protected]>
Signed-off-by: Miklos Szeredi <[email protected]>
|
other
|
linux
|
0b9111922b1f399aba6ed1e1b8f2079c3da1aed8
| 1
|
static void sixpack_close(struct tty_struct *tty)
{
struct sixpack *sp;
write_lock_irq(&disc_data_lock);
sp = tty->disc_data;
tty->disc_data = NULL;
write_unlock_irq(&disc_data_lock);
if (!sp)
return;
/*
* We have now ensured that nobody can start using ap from now on, but
* we have to wait for all existing users to finish.
*/
if (!refcount_dec_and_test(&sp->refcnt))
wait_for_completion(&sp->dead);
/* We must stop the queue to avoid potentially scribbling
* on the free buffers. The sp->dead completion is not sufficient
* to protect us from sp->xbuff access.
*/
netif_stop_queue(sp->dev);
del_timer_sync(&sp->tx_t);
del_timer_sync(&sp->resync_t);
/* Free all 6pack frame buffers. */
kfree(sp->rbuff);
kfree(sp->xbuff);
unregister_netdev(sp->dev);
}
| null | null | 205,747
|
249805018278643935871389223895747450083
| 33
|
hamradio: defer 6pack kfree after unregister_netdev
There is a possible race condition (use-after-free) like below
(USE) | (FREE)
dev_queue_xmit |
__dev_queue_xmit |
__dev_xmit_skb |
sch_direct_xmit | ...
xmit_one |
netdev_start_xmit | tty_ldisc_kill
__netdev_start_xmit | 6pack_close
sp_xmit | kfree
sp_encaps |
|
According to the patch "defer ax25 kfree after unregister_netdev", this
patch reorder the kfree after the unregister_netdev to avoid the possible
UAF as the unregister_netdev() is well synchronized and won't return if
there is a running routine.
Signed-off-by: Lin Ma <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
|
other
|
Singular
|
5f28fbf066626fa9c4a8f0e6408c0bb362fb386c
| 1
|
void sdb_edit(procinfo *pi)
{
char * filename = omStrDup("/tmp/sd000000");
sprintf(filename+7,"%d",getpid());
FILE *fp=fopen(filename,"w");
if (fp==NULL)
{
Print("cannot open %s\n",filename);
omFree(filename);
return;
}
if (pi->language!= LANG_SINGULAR)
{
Print("cannot edit type %d\n",pi->language);
fclose(fp);
fp=NULL;
}
else
{
const char *editor=getenv("EDITOR");
if (editor==NULL)
editor=getenv("VISUAL");
if (editor==NULL)
editor="vi";
editor=omStrDup(editor);
if (pi->data.s.body==NULL)
{
iiGetLibProcBuffer(pi);
if (pi->data.s.body==NULL)
{
PrintS("cannot get the procedure body\n");
fclose(fp);
si_unlink(filename);
omFree(filename);
return;
}
}
fwrite(pi->data.s.body,1,strlen(pi->data.s.body),fp);
fclose(fp);
int pid=fork();
if (pid!=0)
{
si_wait(&pid);
}
else if(pid==0)
{
if (strchr(editor,' ')==NULL)
{
execlp(editor,editor,filename,NULL);
Print("cannot exec %s\n",editor);
}
else
{
char *p=(char *)omAlloc(strlen(editor)+strlen(filename)+2);
sprintf(p,"%s %s",editor,filename);
system(p);
}
exit(0);
}
else
{
PrintS("cannot fork\n");
}
fp=fopen(filename,"r");
if (fp==NULL)
{
Print("cannot read from %s\n",filename);
}
else
{
fseek(fp,0L,SEEK_END);
long len=ftell(fp);
fseek(fp,0L,SEEK_SET);
omFree((ADDRESS)pi->data.s.body);
pi->data.s.body=(char *)omAlloc((int)len+1);
myfread( pi->data.s.body, len, 1, fp);
pi->data.s.body[len]='\0';
fclose(fp);
}
}
si_unlink(filename);
omFree(filename);
}
| null | null | 205,806
|
25730383295969775485586037725138837363
| 88
|
use mkstemp for sdb
|
other
|
date
|
376c65942bd1d81803f14d37351737df60ec4664
| 1
|
check_limit(VALUE str, VALUE opt)
{
if (NIL_P(str)) return;
StringValue(str);
size_t slen = RSTRING_LEN(str);
size_t limit = get_limit(opt);
if (slen > limit) {
rb_raise(rb_eArgError,
"string length (%"PRI_SIZE_PREFIX"u) exceeds the limit %"PRI_SIZE_PREFIX"u", slen, limit);
}
}
| null | null | 205,807
|
136825502050184594453138943655153134771
| 12
|
check_limit: also handle symbols
|
other
|
linux
|
fdac1e0697356ac212259f2147aa60c72e334861
| 1
|
static int irda_getsockopt(struct socket *sock, int level, int optname,
char __user *optval, int __user *optlen)
{
struct sock *sk = sock->sk;
struct irda_sock *self = irda_sk(sk);
struct irda_device_list list;
struct irda_device_info *discoveries;
struct irda_ias_set * ias_opt; /* IAS get/query params */
struct ias_object * ias_obj; /* Object in IAS */
struct ias_attrib * ias_attr; /* Attribute in IAS object */
int daddr = DEV_ADDR_ANY; /* Dest address for IAS queries */
int val = 0;
int len = 0;
int err = 0;
int offset, total;
IRDA_DEBUG(2, "%s(%p)\n", __func__, self);
if (level != SOL_IRLMP)
return -ENOPROTOOPT;
if (get_user(len, optlen))
return -EFAULT;
if(len < 0)
return -EINVAL;
lock_sock(sk);
switch (optname) {
case IRLMP_ENUMDEVICES:
/* Ask lmp for the current discovery log */
discoveries = irlmp_get_discoveries(&list.len, self->mask.word,
self->nslots);
/* Check if the we got some results */
if (discoveries == NULL) {
err = -EAGAIN;
goto out; /* Didn't find any devices */
}
/* Write total list length back to client */
if (copy_to_user(optval, &list,
sizeof(struct irda_device_list) -
sizeof(struct irda_device_info)))
err = -EFAULT;
/* Offset to first device entry */
offset = sizeof(struct irda_device_list) -
sizeof(struct irda_device_info);
/* Copy the list itself - watch for overflow */
if (list.len > 2048) {
err = -EINVAL;
goto bed;
}
total = offset + (list.len * sizeof(struct irda_device_info));
if (total > len)
total = len;
if (copy_to_user(optval+offset, discoveries, total - offset))
err = -EFAULT;
/* Write total number of bytes used back to client */
if (put_user(total, optlen))
err = -EFAULT;
bed:
/* Free up our buffer */
kfree(discoveries);
break;
case IRLMP_MAX_SDU_SIZE:
val = self->max_data_size;
len = sizeof(int);
if (put_user(len, optlen)) {
err = -EFAULT;
goto out;
}
if (copy_to_user(optval, &val, len)) {
err = -EFAULT;
goto out;
}
break;
case IRLMP_IAS_GET:
/* The user want an object from our local IAS database.
* We just need to query the IAS and return the value
* that we found */
/* Check that the user has allocated the right space for us */
if (len != sizeof(struct irda_ias_set)) {
err = -EINVAL;
goto out;
}
ias_opt = kmalloc(sizeof(struct irda_ias_set), GFP_ATOMIC);
if (ias_opt == NULL) {
err = -ENOMEM;
goto out;
}
/* Copy query to the driver. */
if (copy_from_user(ias_opt, optval, len)) {
kfree(ias_opt);
err = -EFAULT;
goto out;
}
/* Find the object we target.
* If the user gives us an empty string, we use the object
* associated with this socket. This will workaround
* duplicated class name - Jean II */
if(ias_opt->irda_class_name[0] == '\0')
ias_obj = self->ias_obj;
else
ias_obj = irias_find_object(ias_opt->irda_class_name);
if(ias_obj == (struct ias_object *) NULL) {
kfree(ias_opt);
err = -EINVAL;
goto out;
}
/* Find the attribute (in the object) we target */
ias_attr = irias_find_attrib(ias_obj,
ias_opt->irda_attrib_name);
if(ias_attr == (struct ias_attrib *) NULL) {
kfree(ias_opt);
err = -EINVAL;
goto out;
}
/* Translate from internal to user structure */
err = irda_extract_ias_value(ias_opt, ias_attr->value);
if(err) {
kfree(ias_opt);
goto out;
}
/* Copy reply to the user */
if (copy_to_user(optval, ias_opt,
sizeof(struct irda_ias_set))) {
kfree(ias_opt);
err = -EFAULT;
goto out;
}
/* Note : don't need to put optlen, we checked it */
kfree(ias_opt);
break;
case IRLMP_IAS_QUERY:
/* The user want an object from a remote IAS database.
* We need to use IAP to query the remote database and
* then wait for the answer to come back. */
/* Check that the user has allocated the right space for us */
if (len != sizeof(struct irda_ias_set)) {
err = -EINVAL;
goto out;
}
ias_opt = kmalloc(sizeof(struct irda_ias_set), GFP_ATOMIC);
if (ias_opt == NULL) {
err = -ENOMEM;
goto out;
}
/* Copy query to the driver. */
if (copy_from_user(ias_opt, optval, len)) {
kfree(ias_opt);
err = -EFAULT;
goto out;
}
/* At this point, there are two cases...
* 1) the socket is connected - that's the easy case, we
* just query the device we are connected to...
* 2) the socket is not connected - the user doesn't want
* to connect and/or may not have a valid service name
* (so can't create a fake connection). In this case,
* we assume that the user pass us a valid destination
* address in the requesting structure...
*/
if(self->daddr != DEV_ADDR_ANY) {
/* We are connected - reuse known daddr */
daddr = self->daddr;
} else {
/* We are not connected, we must specify a valid
* destination address */
daddr = ias_opt->daddr;
if((!daddr) || (daddr == DEV_ADDR_ANY)) {
kfree(ias_opt);
err = -EINVAL;
goto out;
}
}
/* Check that we can proceed with IAP */
if (self->iriap) {
IRDA_WARNING("%s: busy with a previous query\n",
__func__);
kfree(ias_opt);
err = -EBUSY;
goto out;
}
self->iriap = iriap_open(LSAP_ANY, IAS_CLIENT, self,
irda_getvalue_confirm);
if (self->iriap == NULL) {
kfree(ias_opt);
err = -ENOMEM;
goto out;
}
/* Treat unexpected wakeup as disconnect */
self->errno = -EHOSTUNREACH;
/* Query remote LM-IAS */
iriap_getvaluebyclass_request(self->iriap,
self->saddr, daddr,
ias_opt->irda_class_name,
ias_opt->irda_attrib_name);
/* Wait for answer, if not yet finished (or failed) */
if (wait_event_interruptible(self->query_wait,
(self->iriap == NULL))) {
/* pending request uses copy of ias_opt-content
* we can free it regardless! */
kfree(ias_opt);
/* Treat signals as disconnect */
err = -EHOSTUNREACH;
goto out;
}
/* Check what happened */
if (self->errno)
{
kfree(ias_opt);
/* Requested object/attribute doesn't exist */
if((self->errno == IAS_CLASS_UNKNOWN) ||
(self->errno == IAS_ATTRIB_UNKNOWN))
err = -EADDRNOTAVAIL;
else
err = -EHOSTUNREACH;
goto out;
}
/* Translate from internal to user structure */
err = irda_extract_ias_value(ias_opt, self->ias_result);
if (self->ias_result)
irias_delete_value(self->ias_result);
if (err) {
kfree(ias_opt);
goto out;
}
/* Copy reply to the user */
if (copy_to_user(optval, ias_opt,
sizeof(struct irda_ias_set))) {
kfree(ias_opt);
err = -EFAULT;
goto out;
}
/* Note : don't need to put optlen, we checked it */
kfree(ias_opt);
break;
case IRLMP_WAITDEVICE:
/* This function is just another way of seeing life ;-)
* IRLMP_ENUMDEVICES assumes that you have a static network,
* and that you just want to pick one of the devices present.
* On the other hand, in here we assume that no device is
* present and that at some point in the future a device will
* come into range. When this device arrive, we just wake
* up the caller, so that he has time to connect to it before
* the device goes away...
* Note : once the node has been discovered for more than a
* few second, it won't trigger this function, unless it
* goes away and come back changes its hint bits (so we
* might call it IRLMP_WAITNEWDEVICE).
*/
/* Check that the user is passing us an int */
if (len != sizeof(int)) {
err = -EINVAL;
goto out;
}
/* Get timeout in ms (max time we block the caller) */
if (get_user(val, (int __user *)optval)) {
err = -EFAULT;
goto out;
}
/* Tell IrLMP we want to be notified */
irlmp_update_client(self->ckey, self->mask.word,
irda_selective_discovery_indication,
NULL, (void *) self);
/* Do some discovery (and also return cached results) */
irlmp_discovery_request(self->nslots);
/* Wait until a node is discovered */
if (!self->cachedaddr) {
IRDA_DEBUG(1, "%s(), nothing discovered yet, going to sleep...\n", __func__);
/* Set watchdog timer to expire in <val> ms. */
self->errno = 0;
setup_timer(&self->watchdog, irda_discovery_timeout,
(unsigned long)self);
self->watchdog.expires = jiffies + (val * HZ/1000);
add_timer(&(self->watchdog));
/* Wait for IR-LMP to call us back */
__wait_event_interruptible(self->query_wait,
(self->cachedaddr != 0 || self->errno == -ETIME),
err);
/* If watchdog is still activated, kill it! */
if(timer_pending(&(self->watchdog)))
del_timer(&(self->watchdog));
IRDA_DEBUG(1, "%s(), ...waking up !\n", __func__);
if (err != 0)
goto out;
}
else
IRDA_DEBUG(1, "%s(), found immediately !\n",
__func__);
/* Tell IrLMP that we have been notified */
irlmp_update_client(self->ckey, self->mask.word,
NULL, NULL, NULL);
/* Check if the we got some results */
if (!self->cachedaddr)
return -EAGAIN; /* Didn't find any devices */
daddr = self->cachedaddr;
/* Cleanup */
self->cachedaddr = 0;
/* We return the daddr of the device that trigger the
* wakeup. As irlmp pass us only the new devices, we
* are sure that it's not an old device.
* If the user want more details, he should query
* the whole discovery log and pick one device...
*/
if (put_user(daddr, (int __user *)optval)) {
err = -EFAULT;
goto out;
}
break;
default:
err = -ENOPROTOOPT;
}
out:
release_sock(sk);
return err;
}
| null | null | 205,821
|
206723367980818827503124126810367962719
| 360
|
irda: prevent integer underflow in IRLMP_ENUMDEVICES
If the user-provided len is less than the expected offset, the
IRLMP_ENUMDEVICES getsockopt will do a copy_to_user() with a very large
size value. While this isn't be a security issue on x86 because it will
get caught by the access_ok() check, it may leak large amounts of kernel
heap on other architectures. In any event, this patch fixes it.
Signed-off-by: Dan Rosenberg <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
|
other
|
ovs
|
803ed12e31b0377c37d7aa8c94b3b92f2081e349
| 1
|
ipf_extract_frags_from_batch(struct ipf *ipf, struct dp_packet_batch *pb,
ovs_be16 dl_type, uint16_t zone, long long now,
uint32_t hash_basis)
{
const size_t pb_cnt = dp_packet_batch_size(pb);
int pb_idx; /* Index in a packet batch. */
struct dp_packet *pkt;
DP_PACKET_BATCH_REFILL_FOR_EACH (pb_idx, pb_cnt, pkt, pb) {
if (OVS_UNLIKELY((dl_type == htons(ETH_TYPE_IP) &&
ipf_is_valid_v4_frag(ipf, pkt))
||
(dl_type == htons(ETH_TYPE_IPV6) &&
ipf_is_valid_v6_frag(ipf, pkt)))) {
ovs_mutex_lock(&ipf->ipf_lock);
if (!ipf_handle_frag(ipf, pkt, dl_type, zone, now, hash_basis)) {
dp_packet_batch_refill(pb, pkt, pb_idx);
}
ovs_mutex_unlock(&ipf->ipf_lock);
} else {
dp_packet_batch_refill(pb, pkt, pb_idx);
}
}
}
| null | null | 205,823
|
7422800219328489278084315046345573051
| 25
|
ipf: release unhandled packets from the batch
Since 640d4db788ed ("ipf: Fix a use-after-free error, ...") the ipf
framework unconditionally allocates a new dp_packet to track
individual fragments. This prevents a use-after-free. However, an
additional issue was present - even when the packet buffer is cloned,
if the ip fragment handling code keeps it, the original buffer is
leaked during the refill loop. Even in the original processing code,
the hardcoded dnsteal branches would always leak a packet buffer from
the refill loop.
This can be confirmed with valgrind:
==717566== 16,672 (4,480 direct, 12,192 indirect) bytes in 8 blocks are definitely lost in loss record 390 of 390
==717566== at 0x484086F: malloc (vg_replace_malloc.c:380)
==717566== by 0x537BFD: xmalloc__ (util.c:137)
==717566== by 0x537BFD: xmalloc (util.c:172)
==717566== by 0x46DDD4: dp_packet_new (dp-packet.c:153)
==717566== by 0x46DDD4: dp_packet_new_with_headroom (dp-packet.c:163)
==717566== by 0x550AA6: netdev_linux_batch_rxq_recv_sock.constprop.0 (netdev-linux.c:1262)
==717566== by 0x5512AF: netdev_linux_rxq_recv (netdev-linux.c:1511)
==717566== by 0x4AB7E0: netdev_rxq_recv (netdev.c:727)
==717566== by 0x47F00D: dp_netdev_process_rxq_port (dpif-netdev.c:4699)
==717566== by 0x47FD13: dpif_netdev_run (dpif-netdev.c:5957)
==717566== by 0x4331D2: type_run (ofproto-dpif.c:370)
==717566== by 0x41DFD8: ofproto_type_run (ofproto.c:1768)
==717566== by 0x40A7FB: bridge_run__ (bridge.c:3245)
==717566== by 0x411269: bridge_run (bridge.c:3310)
==717566== by 0x406E6C: main (ovs-vswitchd.c:127)
The fix is to delete the original packet when it isn't able to be
reinserted into the packet batch. Subsequent valgrind runs show that
the packets are not leaked from the batch any longer.
Fixes: 640d4db788ed ("ipf: Fix a use-after-free error, and remove the 'do_not_steal' flag.")
Fixes: 4ea96698f667 ("Userspace datapath: Add fragmentation handling.")
Reported-by: Wan Junjie <[email protected]>
Reported-at: https://github.com/openvswitch/ovs-issues/issues/226
Signed-off-by: Aaron Conole <[email protected]>
Reviewed-by: David Marchand <[email protected]>
Tested-by: Wan Junjie <[email protected]>
Signed-off-by: Alin-Gabriel Serdean <[email protected]>
|
other
|
vim
|
2bdad6126778f907c0b98002bfebf0e611a3f5db
| 1
|
get_one_sourceline(source_cookie_T *sp)
{
garray_T ga;
int len;
int c;
char_u *buf;
#ifdef USE_CRNL
int has_cr; // CR-LF found
#endif
int have_read = FALSE;
// use a growarray to store the sourced line
ga_init2(&ga, 1, 250);
// Loop until there is a finished line (or end-of-file).
++sp->sourcing_lnum;
for (;;)
{
// make room to read at least 120 (more) characters
if (ga_grow(&ga, 120) == FAIL)
break;
if (sp->source_from_buf)
{
if (sp->buf_lnum >= sp->buflines.ga_len)
break; // all the lines are processed
ga_concat(&ga, ((char_u **)sp->buflines.ga_data)[sp->buf_lnum]);
sp->buf_lnum++;
buf = (char_u *)ga.ga_data;
}
else
{
buf = (char_u *)ga.ga_data;
if (fgets((char *)buf + ga.ga_len, ga.ga_maxlen - ga.ga_len,
sp->fp) == NULL)
break;
}
len = ga.ga_len + (int)STRLEN(buf + ga.ga_len);
#ifdef USE_CRNL
// Ignore a trailing CTRL-Z, when in Dos mode. Only recognize the
// CTRL-Z by its own, or after a NL.
if ( (len == 1 || (len >= 2 && buf[len - 2] == '\n'))
&& sp->fileformat == EOL_DOS
&& buf[len - 1] == Ctrl_Z)
{
buf[len - 1] = NUL;
break;
}
#endif
have_read = TRUE;
ga.ga_len = len;
// If the line was longer than the buffer, read more.
if (ga.ga_maxlen - ga.ga_len == 1 && buf[len - 1] != '\n')
continue;
if (len >= 1 && buf[len - 1] == '\n') // remove trailing NL
{
#ifdef USE_CRNL
has_cr = (len >= 2 && buf[len - 2] == '\r');
if (sp->fileformat == EOL_UNKNOWN)
{
if (has_cr)
sp->fileformat = EOL_DOS;
else
sp->fileformat = EOL_UNIX;
}
if (sp->fileformat == EOL_DOS)
{
if (has_cr) // replace trailing CR
{
buf[len - 2] = '\n';
--len;
--ga.ga_len;
}
else // lines like ":map xx yy^M" will have failed
{
if (!sp->error)
{
msg_source(HL_ATTR(HLF_W));
emsg(_("W15: Warning: Wrong line separator, ^M may be missing"));
}
sp->error = TRUE;
sp->fileformat = EOL_UNIX;
}
}
#endif
// The '\n' is escaped if there is an odd number of ^V's just
// before it, first set "c" just before the 'V's and then check
// len&c parities (is faster than ((len-c)%2 == 0)) -- Acevedo
for (c = len - 2; c >= 0 && buf[c] == Ctrl_V; c--)
;
if ((len & 1) != (c & 1)) // escaped NL, read more
{
++sp->sourcing_lnum;
continue;
}
buf[len - 1] = NUL; // remove the NL
}
// Check for ^C here now and then, so recursive :so can be broken.
line_breakcheck();
break;
}
if (have_read)
return (char_u *)ga.ga_data;
vim_free(ga.ga_data);
return NULL;
}
| null | null | 205,838
|
88460604221903194796888834018848217667
| 113
|
patch 8.2.4647: "source" can read past end of copied line
Problem: "source" can read past end of copied line.
Solution: Add a terminating NUL.
|
other
|
radare2
|
515e592b9bea0612bc63d8e93239ff35bcf645c7
| 1
|
static RList *symbols(RBinFile *bf) {
RList *res = r_list_newf ((RListFree)r_bin_symbol_free);
r_return_val_if_fail (res && bf->o && bf->o->bin_obj, res);
RCoreSymCacheElement *element = bf->o->bin_obj;
size_t i;
HtUU *hash = ht_uu_new0 ();
if (!hash) {
return res;
}
bool found = false;
for (i = 0; i < element->hdr->n_lined_symbols; i++) {
RCoreSymCacheElementSymbol *sym = (RCoreSymCacheElementSymbol *)&element->lined_symbols[i];
ht_uu_find (hash, sym->paddr, &found);
if (found) {
continue;
}
RBinSymbol *s = bin_symbol_from_symbol (element, sym);
if (s) {
r_list_append (res, s);
ht_uu_insert (hash, sym->paddr, 1);
}
}
if (element->symbols) {
for (i = 0; i < element->hdr->n_symbols; i++) {
RCoreSymCacheElementSymbol *sym = &element->symbols[i];
ht_uu_find (hash, sym->paddr, &found);
if (found) {
continue;
}
RBinSymbol *s = bin_symbol_from_symbol (element, sym);
if (s) {
r_list_append (res, s);
}
}
}
ht_uu_free (hash);
return res;
}
| null | null | 205,870
|
198849166368149647611847610342973507929
| 38
|
Fix null deref in bin.symbols ##crash
* Reported by cnitlrt via huntr.dev
|
other
|
evolution-data-server
|
5d8b92c622f6927b253762ff9310479dd3ac627d
| 1
|
gpg_ctx_add_recipient (struct _GpgCtx *gpg,
const gchar *keyid)
{
if (gpg->mode != GPG_CTX_MODE_ENCRYPT && gpg->mode != GPG_CTX_MODE_EXPORT)
return;
if (!gpg->recipients)
gpg->recipients = g_ptr_array_new ();
g_ptr_array_add (gpg->recipients, g_strdup (keyid));
}
| null | null | 206,025
|
141933283002790613862782726205564754266
| 11
|
CamelGpgContext: Enclose email addresses in brackets.
The recipient list for encrypting can be specified by either key ID or
email address. Enclose email addresses in brackets to ensure an exact
match, as per the gpg man page:
HOW TO SPECIFY A USER ID
...
By exact match on an email address.
This is indicated by enclosing the email address in the
usual way with left and right angles.
<[email protected]>
Without the brackets gpg uses a substring match, which risks selecting
the wrong recipient.
|
other
|
gimp
|
c57f9dcf1934a9ab0cd67650f2dea18cb0902270
| 1
|
load_image (const gchar *filename,
GError **error)
{
gchar *name;
gint fd;
BrushHeader bh;
guchar *brush_buf = NULL;
gint32 image_ID;
gint32 layer_ID;
GimpParasite *parasite;
GimpDrawable *drawable;
GimpPixelRgn pixel_rgn;
gint bn_size;
GimpImageBaseType base_type;
GimpImageType image_type;
gsize size;
fd = g_open (filename, O_RDONLY | _O_BINARY, 0);
if (fd == -1)
{
g_set_error (error, G_FILE_ERROR, g_file_error_from_errno (errno),
_("Could not open '%s' for reading: %s"),
gimp_filename_to_utf8 (filename), g_strerror (errno));
return -1;
}
gimp_progress_init_printf (_("Opening '%s'"),
gimp_filename_to_utf8 (filename));
if (read (fd, &bh, sizeof (BrushHeader)) != sizeof (BrushHeader))
{
close (fd);
return -1;
}
/* rearrange the bytes in each unsigned int */
bh.header_size = g_ntohl (bh.header_size);
bh.version = g_ntohl (bh.version);
bh.width = g_ntohl (bh.width);
bh.height = g_ntohl (bh.height);
bh.bytes = g_ntohl (bh.bytes);
bh.magic_number = g_ntohl (bh.magic_number);
bh.spacing = g_ntohl (bh.spacing);
/* Sanitize values */
if ((bh.width == 0) || (bh.width > GIMP_MAX_IMAGE_SIZE) ||
(bh.height == 0) || (bh.height > GIMP_MAX_IMAGE_SIZE) ||
((bh.bytes != 1) && (bh.bytes != 2) && (bh.bytes != 4) &&
(bh.bytes != 18)) ||
(G_MAXSIZE / bh.width / bh.height / bh.bytes < 1))
{
g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_FAILED,
_("Invalid header data in '%s': width=%lu, height=%lu, "
"bytes=%lu"), gimp_filename_to_utf8 (filename),
(unsigned long int)bh.width, (unsigned long int)bh.height,
(unsigned long int)bh.bytes);
return -1;
}
switch (bh.version)
{
case 1:
/* Version 1 didn't have a magic number and had no spacing */
bh.spacing = 25;
/* And we need to rewind the handle, 4 due spacing and 4 due magic */
lseek (fd, -8, SEEK_CUR);
bh.header_size += 8;
break;
case 3: /* cinepaint brush */
if (bh.bytes == 18 /* FLOAT16_GRAY_GIMAGE */)
{
bh.bytes = 2;
}
else
{
g_message (_("Unsupported brush format"));
close (fd);
return -1;
}
/* fallthrough */
case 2:
if (bh.magic_number == GBRUSH_MAGIC &&
bh.header_size > sizeof (BrushHeader))
break;
default:
g_message (_("Unsupported brush format"));
close (fd);
return -1;
}
if ((bn_size = (bh.header_size - sizeof (BrushHeader))) > 0)
{
gchar *temp = g_new (gchar, bn_size);
if ((read (fd, temp, bn_size)) < bn_size)
{
g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_FAILED,
_("Error in GIMP brush file '%s'"),
gimp_filename_to_utf8 (filename));
close (fd);
g_free (temp);
return -1;
}
name = gimp_any_to_utf8 (temp, -1,
_("Invalid UTF-8 string in brush file '%s'."),
gimp_filename_to_utf8 (filename));
g_free (temp);
}
else
{
name = g_strdup (_("Unnamed"));
}
/* Now there's just raw data left. */
size = bh.width * bh.height * bh.bytes;
brush_buf = g_malloc (size);
if (read (fd, brush_buf, size) != size)
{
close (fd);
g_free (brush_buf);
g_free (name);
return -1;
}
switch (bh.bytes)
{
case 1:
{
PatternHeader ph;
/* For backwards-compatibility, check if a pattern follows.
The obsolete .gpb format did it this way. */
if (read (fd, &ph, sizeof (PatternHeader)) == sizeof(PatternHeader))
{
/* rearrange the bytes in each unsigned int */
ph.header_size = g_ntohl (ph.header_size);
ph.version = g_ntohl (ph.version);
ph.width = g_ntohl (ph.width);
ph.height = g_ntohl (ph.height);
ph.bytes = g_ntohl (ph.bytes);
ph.magic_number = g_ntohl (ph.magic_number);
if (ph.magic_number == GPATTERN_MAGIC &&
ph.version == 1 &&
ph.header_size > sizeof (PatternHeader) &&
ph.bytes == 3 &&
ph.width == bh.width &&
ph.height == bh.height &&
lseek (fd, ph.header_size - sizeof (PatternHeader),
SEEK_CUR) > 0)
{
guchar *plain_brush = brush_buf;
gint i;
bh.bytes = 4;
brush_buf = g_malloc (4 * bh.width * bh.height);
for (i = 0; i < ph.width * ph.height; i++)
{
if (read (fd, brush_buf + i * 4, 3) != 3)
{
close (fd);
g_free (name);
g_free (plain_brush);
g_free (brush_buf);
return -1;
}
brush_buf[i * 4 + 3] = plain_brush[i];
}
g_free (plain_brush);
}
}
}
break;
case 2:
{
guint16 *buf = (guint16 *) brush_buf;
gint i;
for (i = 0; i < bh.width * bh.height; i++, buf++)
{
union
{
guint16 u[2];
gfloat f;
} short_float;
#if G_BYTE_ORDER == G_LITTLE_ENDIAN
short_float.u[0] = 0;
short_float.u[1] = GUINT16_FROM_BE (*buf);
#else
short_float.u[0] = GUINT16_FROM_BE (*buf);
short_float.u[1] = 0;
#endif
brush_buf[i] = (guchar) (short_float.f * 255.0 + 0.5);
}
bh.bytes = 1;
}
break;
default:
break;
}
/*
* Create a new image of the proper size and
* associate the filename with it.
*/
switch (bh.bytes)
{
case 1:
base_type = GIMP_GRAY;
image_type = GIMP_GRAY_IMAGE;
break;
case 4:
base_type = GIMP_RGB;
image_type = GIMP_RGBA_IMAGE;
break;
default:
g_message ("Unsupported brush depth: %d\n"
"GIMP Brushes must be GRAY or RGBA\n",
bh.bytes);
g_free (name);
return -1;
}
image_ID = gimp_image_new (bh.width, bh.height, base_type);
gimp_image_set_filename (image_ID, filename);
parasite = gimp_parasite_new ("gimp-brush-name",
GIMP_PARASITE_PERSISTENT,
strlen (name) + 1, name);
gimp_image_attach_parasite (image_ID, parasite);
gimp_parasite_free (parasite);
layer_ID = gimp_layer_new (image_ID, name, bh.width, bh.height,
image_type, 100, GIMP_NORMAL_MODE);
gimp_image_insert_layer (image_ID, layer_ID, -1, 0);
g_free (name);
drawable = gimp_drawable_get (layer_ID);
gimp_pixel_rgn_init (&pixel_rgn, drawable,
0, 0, drawable->width, drawable->height,
TRUE, FALSE);
gimp_pixel_rgn_set_rect (&pixel_rgn, brush_buf,
0, 0, bh.width, bh.height);
g_free (brush_buf);
if (image_type == GIMP_GRAY_IMAGE)
gimp_invert (layer_ID);
close (fd);
gimp_drawable_flush (drawable);
gimp_progress_update (1.0);
return image_ID;
}
| null | null | 206,043
|
221229682723113616266713040940895760659
| 274
|
Bug 790784 - (CVE-2017-17784) heap overread in gbr parser / load_image.
We were assuming the input name was well formed, hence was
nul-terminated. As any data coming from external input, this has to be
thorougly checked.
Similar to commit 06d24a79af94837d615d0024916bb95a01bf3c59 but adapted
to older gimp-2-8 code.
|
other
|
tigervnc
|
d61a767d6842b530ffb532ddd5a3d233119aad40
| 1
|
void ZRLE_DECODE (const Rect& r, rdr::InStream* is,
rdr::ZlibInStream* zis,
const PixelFormat& pf, ModifiablePixelBuffer* pb)
{
int length = is->readU32();
zis->setUnderlying(is, length);
Rect t;
PIXEL_T buf[64 * 64];
for (t.tl.y = r.tl.y; t.tl.y < r.br.y; t.tl.y += 64) {
t.br.y = __rfbmin(r.br.y, t.tl.y + 64);
for (t.tl.x = r.tl.x; t.tl.x < r.br.x; t.tl.x += 64) {
t.br.x = __rfbmin(r.br.x, t.tl.x + 64);
int mode = zis->readU8();
bool rle = mode & 128;
int palSize = mode & 127;
PIXEL_T palette[128];
for (int i = 0; i < palSize; i++) {
palette[i] = READ_PIXEL(zis);
}
if (palSize == 1) {
PIXEL_T pix = palette[0];
pb->fillRect(pf, t, &pix);
continue;
}
if (!rle) {
if (palSize == 0) {
// raw
#ifdef CPIXEL
for (PIXEL_T* ptr = buf; ptr < buf+t.area(); ptr++) {
*ptr = READ_PIXEL(zis);
}
#else
zis->readBytes(buf, t.area() * (BPP / 8));
#endif
} else {
// packed pixels
int bppp = ((palSize > 16) ? 8 :
((palSize > 4) ? 4 : ((palSize > 2) ? 2 : 1)));
PIXEL_T* ptr = buf;
for (int i = 0; i < t.height(); i++) {
PIXEL_T* eol = ptr + t.width();
rdr::U8 byte = 0;
rdr::U8 nbits = 0;
while (ptr < eol) {
if (nbits == 0) {
byte = zis->readU8();
nbits = 8;
}
nbits -= bppp;
rdr::U8 index = (byte >> nbits) & ((1 << bppp) - 1) & 127;
*ptr++ = palette[index];
}
}
}
} else {
if (palSize == 0) {
// plain RLE
PIXEL_T* ptr = buf;
PIXEL_T* end = ptr + t.area();
while (ptr < end) {
PIXEL_T pix = READ_PIXEL(zis);
int len = 1;
int b;
do {
b = zis->readU8();
len += b;
} while (b == 255);
if (end - ptr < len) {
throw Exception ("ZRLE decode error");
}
while (len-- > 0) *ptr++ = pix;
}
} else {
// palette RLE
PIXEL_T* ptr = buf;
PIXEL_T* end = ptr + t.area();
while (ptr < end) {
int index = zis->readU8();
int len = 1;
if (index & 128) {
int b;
do {
b = zis->readU8();
len += b;
} while (b == 255);
if (end - ptr < len) {
throw Exception ("ZRLE decode error");
}
}
index &= 127;
PIXEL_T pix = palette[index];
while (len-- > 0) *ptr++ = pix;
}
}
}
pb->imageRect(pf, t, buf);
}
}
zis->removeUnderlying();
}
| null | null | 206,044
|
82608106785632412803943463047285938092
| 130
|
Make ZlibInStream more robust against failures
Move the checks around to avoid missing cases where we might access
memory that is no longer valid. Also avoid touching the underlying
stream implicitly (e.g. via the destructor) as it might also no
longer be valid.
A malicious server could theoretically use this for remote code
execution in the client.
Issue found by Pavel Cheremushkin from Kaspersky Lab
|
other
|
radare2
|
1dd65336f0f0c351d6ea853efcf73cf9c0030862
| 1
|
RCoreSymCacheElement *r_coresym_cache_element_new(RBinFile *bf, RBuffer *buf, ut64 off, int bits, char * file_name) {
RCoreSymCacheElement *result = NULL;
ut8 *b = NULL;
RCoreSymCacheElementHdr *hdr = r_coresym_cache_element_header_new (buf, off, bits);
if (!hdr) {
return NULL;
}
if (hdr->version != 1) {
eprintf ("Unsupported CoreSymbolication cache version (%d)\n", hdr->version);
goto beach;
}
if (hdr->size == 0 || hdr->size > r_buf_size (buf) - off) {
eprintf ("Corrupted CoreSymbolication header: size out of bounds (0x%x)\n", hdr->size);
goto beach;
}
result = R_NEW0 (RCoreSymCacheElement);
if (!result) {
goto beach;
}
result->hdr = hdr;
b = malloc (hdr->size);
if (!b) {
goto beach;
}
if (r_buf_read_at (buf, off, b, hdr->size) != hdr->size) {
goto beach;
}
ut8 *end = b + hdr->size;
if (file_name) {
result->file_name = file_name;
} else if (hdr->file_name_off) {
result->file_name = str_dup_safe (b, b + (size_t)hdr->file_name_off, end);
}
if (hdr->version_off) {
result->binary_version = str_dup_safe (b, b + (size_t)hdr->version_off, end);
}
const size_t word_size = bits / 8;
const ut64 start_of_sections = (ut64)hdr->n_segments * R_CS_EL_SIZE_SEG + R_CS_EL_OFF_SEGS;
const ut64 sect_size = (bits == 32) ? R_CS_EL_SIZE_SECT_32 : R_CS_EL_SIZE_SECT_64;
const ut64 start_of_symbols = start_of_sections + (ut64)hdr->n_sections * sect_size;
const ut64 start_of_lined_symbols = start_of_symbols + (ut64)hdr->n_symbols * R_CS_EL_SIZE_SYM;
const ut64 start_of_line_info = start_of_lined_symbols + (ut64)hdr->n_lined_symbols * R_CS_EL_SIZE_LSYM;
const ut64 start_of_unknown_pairs = start_of_line_info + (ut64)hdr->n_line_info * R_CS_EL_SIZE_LINFO;
const ut64 start_of_strings = start_of_unknown_pairs + (ut64)hdr->n_symbols * 8;
ut64 page_zero_size = 0;
size_t page_zero_idx = 0;
if (UT32_MUL_OVFCHK (hdr->n_segments, sizeof (RCoreSymCacheElementSegment))) {
goto beach;
} else if (UT32_MUL_OVFCHK (hdr->n_sections, sizeof (RCoreSymCacheElementSection))) {
goto beach;
} else if (UT32_MUL_OVFCHK (hdr->n_symbols, sizeof (RCoreSymCacheElementSymbol))) {
goto beach;
} else if (UT32_MUL_OVFCHK (hdr->n_lined_symbols, sizeof (RCoreSymCacheElementLinedSymbol))) {
goto beach;
} else if (UT32_MUL_OVFCHK (hdr->n_line_info, sizeof (RCoreSymCacheElementLineInfo))) {
goto beach;
}
if (hdr->n_segments > 0) {
result->segments = R_NEWS0 (RCoreSymCacheElementSegment, hdr->n_segments);
if (!result->segments) {
goto beach;
}
size_t i;
ut8 *cursor = b + R_CS_EL_OFF_SEGS;
for (i = 0; i < hdr->n_segments && cursor + sizeof (RCoreSymCacheElementSegment) < end; i++) {
RCoreSymCacheElementSegment *seg = &result->segments[i];
seg->paddr = seg->vaddr = r_read_le64 (cursor);
cursor += 8;
if (cursor >= end) {
break;
}
seg->size = seg->vsize = r_read_le64 (cursor);
cursor += 8;
if (cursor >= end) {
break;
}
seg->name = str_dup_safe_fixed (b, cursor, 16, end);
cursor += 16;
if (!seg->name) {
continue;
}
if (!strcmp (seg->name, "__PAGEZERO")) {
page_zero_size = seg->size;
page_zero_idx = i;
seg->paddr = seg->vaddr = 0;
seg->size = 0;
}
}
for (i = 0; i < hdr->n_segments && page_zero_size > 0; i++) {
if (i == page_zero_idx) {
continue;
}
RCoreSymCacheElementSegment *seg = &result->segments[i];
if (seg->vaddr < page_zero_size) {
seg->vaddr += page_zero_size;
}
}
}
bool relative_to_strings = false;
ut8* string_origin;
if (hdr->n_sections > 0) {
result->sections = R_NEWS0 (RCoreSymCacheElementSection, hdr->n_sections);
if (!result->sections) {
goto beach;
}
size_t i;
ut8 *cursor = b + start_of_sections;
for (i = 0; i < hdr->n_sections && cursor < end; i++) {
ut8 *sect_start = cursor;
RCoreSymCacheElementSection *sect = &result->sections[i];
sect->vaddr = sect->paddr = r_read_ble (cursor, false, bits);
if (sect->vaddr < page_zero_size) {
sect->vaddr += page_zero_size;
}
cursor += word_size;
if (cursor >= end) {
break;
}
sect->size = r_read_ble (cursor, false, bits);
cursor += word_size;
if (cursor >= end) {
break;
}
ut64 sect_name_off = r_read_ble (cursor, false, bits);
if (!i && !sect_name_off) {
relative_to_strings = true;
}
cursor += word_size;
if (bits == 32) {
cursor += word_size;
}
string_origin = relative_to_strings? b + start_of_strings : sect_start;
sect->name = str_dup_safe (b, string_origin + (size_t)sect_name_off, end);
}
}
if (hdr->n_symbols) {
result->symbols = R_NEWS0 (RCoreSymCacheElementSymbol, hdr->n_symbols);
if (!result->symbols) {
goto beach;
}
size_t i;
ut8 *cursor = b + start_of_symbols;
for (i = 0; i < hdr->n_symbols && cursor + R_CS_EL_SIZE_SYM <= end; i++) {
RCoreSymCacheElementSymbol *sym = &result->symbols[i];
sym->paddr = r_read_le32 (cursor);
sym->size = r_read_le32 (cursor + 0x4);
sym->unk1 = r_read_le32 (cursor + 0x8);
size_t name_off = r_read_le32 (cursor + 0xc);
size_t mangled_name_off = r_read_le32 (cursor + 0x10);
sym->unk2 = (st32)r_read_le32 (cursor + 0x14);
string_origin = relative_to_strings? b + start_of_strings : cursor;
sym->name = str_dup_safe (b, string_origin + name_off, end);
if (!sym->name) {
cursor += R_CS_EL_SIZE_SYM;
continue;
}
string_origin = relative_to_strings? b + start_of_strings : cursor;
sym->mangled_name = str_dup_safe (b, string_origin + mangled_name_off, end);
if (!sym->mangled_name) {
cursor += R_CS_EL_SIZE_SYM;
continue;
}
cursor += R_CS_EL_SIZE_SYM;
}
}
if (hdr->n_lined_symbols) {
result->lined_symbols = R_NEWS0 (RCoreSymCacheElementLinedSymbol, hdr->n_lined_symbols);
if (!result->lined_symbols) {
goto beach;
}
size_t i;
ut8 *cursor = b + start_of_lined_symbols;
for (i = 0; i < hdr->n_lined_symbols && cursor + R_CS_EL_SIZE_LSYM <= end; i++) {
RCoreSymCacheElementLinedSymbol *lsym = &result->lined_symbols[i];
lsym->sym.paddr = r_read_le32 (cursor);
lsym->sym.size = r_read_le32 (cursor + 0x4);
lsym->sym.unk1 = r_read_le32 (cursor + 0x8);
size_t name_off = r_read_le32 (cursor + 0xc);
size_t mangled_name_off = r_read_le32 (cursor + 0x10);
lsym->sym.unk2 = (st32)r_read_le32 (cursor + 0x14);
size_t file_name_off = r_read_le32 (cursor + 0x18);
lsym->flc.line = r_read_le32 (cursor + 0x1c);
lsym->flc.col = r_read_le32 (cursor + 0x20);
string_origin = relative_to_strings? b + start_of_strings : cursor;
lsym->sym.name = str_dup_safe (b, string_origin + name_off, end);
if (!lsym->sym.name) {
cursor += R_CS_EL_SIZE_LSYM;
continue;
}
string_origin = relative_to_strings? b + start_of_strings : cursor;
lsym->sym.mangled_name = str_dup_safe (b, string_origin + mangled_name_off, end);
if (!lsym->sym.mangled_name) {
cursor += R_CS_EL_SIZE_LSYM;
continue;
}
string_origin = relative_to_strings? b + start_of_strings : cursor;
lsym->flc.file = str_dup_safe (b, string_origin + file_name_off, end);
if (!lsym->flc.file) {
cursor += R_CS_EL_SIZE_LSYM;
continue;
}
cursor += R_CS_EL_SIZE_LSYM;
meta_add_fileline (bf, r_coresym_cache_element_pa2va (result, lsym->sym.paddr), lsym->sym.size, &lsym->flc);
}
}
if (hdr->n_line_info) {
result->line_info = R_NEWS0 (RCoreSymCacheElementLineInfo, hdr->n_line_info);
if (!result->line_info) {
goto beach;
}
size_t i;
ut8 *cursor = b + start_of_line_info;
for (i = 0; i < hdr->n_line_info && cursor + R_CS_EL_SIZE_LINFO <= end; i++) {
RCoreSymCacheElementLineInfo *info = &result->line_info[i];
info->paddr = r_read_le32 (cursor);
info->size = r_read_le32 (cursor + 4);
size_t file_name_off = r_read_le32 (cursor + 8);
info->flc.line = r_read_le32 (cursor + 0xc);
info->flc.col = r_read_le32 (cursor + 0x10);
string_origin = relative_to_strings? b + start_of_strings : cursor;
info->flc.file = str_dup_safe (b, string_origin + file_name_off, end);
if (!info->flc.file) {
break;
}
cursor += R_CS_EL_SIZE_LINFO;
meta_add_fileline (bf, r_coresym_cache_element_pa2va (result, info->paddr), info->size, &info->flc);
}
}
/*
* TODO:
* Figure out the meaning of the 2 arrays of hdr->n_symbols
* 32-bit integers located at the end of line info.
* Those are the last info before the strings at the end.
*/
beach:
free (b);
return result;
}
| null | null | 206,123
|
257777219606277295538493654390747819137
| 242
|
Fix oobread bug in NE parser ##crash
* Reported by @cnitlrt via huntrdev
* BountyID: 02b4b563-b946-4343-9092-38d1c5cd60c9
* Reproducer: neoobread
|
other
|
vim
|
f50808ed135ab973296bca515ae4029b321afe47
| 1
|
parse_command_modifiers(
exarg_T *eap,
char **errormsg,
cmdmod_T *cmod,
int skip_only)
{
char_u *cmd_start = NULL;
char_u *p;
int starts_with_colon = FALSE;
int vim9script = in_vim9script();
int has_visual_range = FALSE;
CLEAR_POINTER(cmod);
cmod->cmod_flags = sticky_cmdmod_flags;
if (STRNCMP(eap->cmd, "'<,'>", 5) == 0)
{
// The automatically inserted Visual area range is skipped, so that
// typing ":cmdmod cmd" in Visual mode works without having to move the
// range to after the modififiers.
eap->cmd += 5;
cmd_start = eap->cmd;
has_visual_range = TRUE;
}
// Repeat until no more command modifiers are found.
for (;;)
{
while (*eap->cmd == ' ' || *eap->cmd == '\t' || *eap->cmd == ':')
{
if (*eap->cmd == ':')
starts_with_colon = TRUE;
++eap->cmd;
}
// in ex mode, an empty line works like :+
if (*eap->cmd == NUL && exmode_active
&& (getline_equal(eap->getline, eap->cookie, getexmodeline)
|| getline_equal(eap->getline, eap->cookie, getexline))
&& curwin->w_cursor.lnum < curbuf->b_ml.ml_line_count)
{
eap->cmd = (char_u *)"+";
if (!skip_only)
ex_pressedreturn = TRUE;
}
// ignore comment and empty lines
if (comment_start(eap->cmd, starts_with_colon))
{
// a comment ends at a NL
if (eap->nextcmd == NULL)
{
eap->nextcmd = vim_strchr(eap->cmd, '\n');
if (eap->nextcmd != NULL)
++eap->nextcmd;
}
if (vim9script && has_cmdmod(cmod, FALSE))
*errormsg = _(e_command_modifier_without_command);
return FAIL;
}
if (*eap->cmd == NUL)
{
if (!skip_only)
{
ex_pressedreturn = TRUE;
if (vim9script && has_cmdmod(cmod, FALSE))
*errormsg = _(e_command_modifier_without_command);
}
return FAIL;
}
p = skip_range(eap->cmd, TRUE, NULL);
// In Vim9 script a variable can shadow a command modifier:
// verbose = 123
// verbose += 123
// silent! verbose = func()
// verbose.member = 2
// verbose[expr] = 2
// But not:
// verbose [a, b] = list
if (vim9script)
{
char_u *s, *n;
for (s = eap->cmd; ASCII_ISALPHA(*s); ++s)
;
n = skipwhite(s);
if (*n == '.' || *n == '=' || (*n != NUL && n[1] == '=')
|| *s == '[')
break;
}
switch (*p)
{
// When adding an entry, also modify cmd_exists().
case 'a': if (!checkforcmd_noparen(&eap->cmd, "aboveleft", 3))
break;
cmod->cmod_split |= WSP_ABOVE;
continue;
case 'b': if (checkforcmd_noparen(&eap->cmd, "belowright", 3))
{
cmod->cmod_split |= WSP_BELOW;
continue;
}
if (checkforcmd_opt(&eap->cmd, "browse", 3, TRUE))
{
#ifdef FEAT_BROWSE_CMD
cmod->cmod_flags |= CMOD_BROWSE;
#endif
continue;
}
if (!checkforcmd_noparen(&eap->cmd, "botright", 2))
break;
cmod->cmod_split |= WSP_BOT;
continue;
case 'c': if (!checkforcmd_opt(&eap->cmd, "confirm", 4, TRUE))
break;
#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
cmod->cmod_flags |= CMOD_CONFIRM;
#endif
continue;
case 'k': if (checkforcmd_noparen(&eap->cmd, "keepmarks", 3))
{
cmod->cmod_flags |= CMOD_KEEPMARKS;
continue;
}
if (checkforcmd_noparen(&eap->cmd, "keepalt", 5))
{
cmod->cmod_flags |= CMOD_KEEPALT;
continue;
}
if (checkforcmd_noparen(&eap->cmd, "keeppatterns", 5))
{
cmod->cmod_flags |= CMOD_KEEPPATTERNS;
continue;
}
if (!checkforcmd_noparen(&eap->cmd, "keepjumps", 5))
break;
cmod->cmod_flags |= CMOD_KEEPJUMPS;
continue;
case 'f': // only accept ":filter {pat} cmd"
{
char_u *reg_pat;
char_u *nulp = NULL;
int c = 0;
if (!checkforcmd_noparen(&p, "filter", 4)
|| *p == NUL
|| (ends_excmd(*p)
#ifdef FEAT_EVAL
// in ":filter #pat# cmd" # does not
// start a comment
&& (!vim9script || VIM_ISWHITE(p[1]))
#endif
))
break;
if (*p == '!')
{
cmod->cmod_filter_force = TRUE;
p = skipwhite(p + 1);
if (*p == NUL || ends_excmd(*p))
break;
}
#ifdef FEAT_EVAL
// Avoid that "filter(arg)" is recognized.
if (vim9script && !VIM_ISWHITE(p[-1]))
break;
#endif
if (skip_only)
p = skip_vimgrep_pat(p, NULL, NULL);
else
// NOTE: This puts a NUL after the pattern.
p = skip_vimgrep_pat_ext(p, ®_pat, NULL,
&nulp, &c);
if (p == NULL || *p == NUL)
break;
if (!skip_only)
{
cmod->cmod_filter_regmatch.regprog =
vim_regcomp(reg_pat, RE_MAGIC);
if (cmod->cmod_filter_regmatch.regprog == NULL)
break;
// restore the character overwritten by NUL
if (nulp != NULL)
*nulp = c;
}
eap->cmd = p;
continue;
}
// ":hide" and ":hide | cmd" are not modifiers
case 'h': if (p != eap->cmd || !checkforcmd_noparen(&p, "hide", 3)
|| *p == NUL || ends_excmd(*p))
break;
eap->cmd = p;
cmod->cmod_flags |= CMOD_HIDE;
continue;
case 'l': if (checkforcmd_noparen(&eap->cmd, "lockmarks", 3))
{
cmod->cmod_flags |= CMOD_LOCKMARKS;
continue;
}
if (checkforcmd_noparen(&eap->cmd, "legacy", 3))
{
if (ends_excmd2(p, eap->cmd))
{
*errormsg =
_(e_legacy_must_be_followed_by_command);
return FAIL;
}
cmod->cmod_flags |= CMOD_LEGACY;
continue;
}
if (!checkforcmd_noparen(&eap->cmd, "leftabove", 5))
break;
cmod->cmod_split |= WSP_ABOVE;
continue;
case 'n': if (checkforcmd_noparen(&eap->cmd, "noautocmd", 3))
{
cmod->cmod_flags |= CMOD_NOAUTOCMD;
continue;
}
if (!checkforcmd_noparen(&eap->cmd, "noswapfile", 3))
break;
cmod->cmod_flags |= CMOD_NOSWAPFILE;
continue;
case 'r': if (!checkforcmd_noparen(&eap->cmd, "rightbelow", 6))
break;
cmod->cmod_split |= WSP_BELOW;
continue;
case 's': if (checkforcmd_noparen(&eap->cmd, "sandbox", 3))
{
cmod->cmod_flags |= CMOD_SANDBOX;
continue;
}
if (!checkforcmd_noparen(&eap->cmd, "silent", 3))
break;
cmod->cmod_flags |= CMOD_SILENT;
if (*eap->cmd == '!' && !VIM_ISWHITE(eap->cmd[-1]))
{
// ":silent!", but not "silent !cmd"
eap->cmd = skipwhite(eap->cmd + 1);
cmod->cmod_flags |= CMOD_ERRSILENT;
}
continue;
case 't': if (checkforcmd_noparen(&p, "tab", 3))
{
if (!skip_only)
{
long tabnr = get_address(eap, &eap->cmd,
ADDR_TABS, eap->skip,
skip_only, FALSE, 1);
if (tabnr == MAXLNUM)
cmod->cmod_tab = tabpage_index(curtab) + 1;
else
{
if (tabnr < 0 || tabnr > LAST_TAB_NR)
{
*errormsg = _(e_invalid_range);
return FAIL;
}
cmod->cmod_tab = tabnr + 1;
}
}
eap->cmd = p;
continue;
}
if (!checkforcmd_noparen(&eap->cmd, "topleft", 2))
break;
cmod->cmod_split |= WSP_TOP;
continue;
case 'u': if (!checkforcmd_noparen(&eap->cmd, "unsilent", 3))
break;
cmod->cmod_flags |= CMOD_UNSILENT;
continue;
case 'v': if (checkforcmd_noparen(&eap->cmd, "vertical", 4))
{
cmod->cmod_split |= WSP_VERT;
continue;
}
if (checkforcmd_noparen(&eap->cmd, "vim9cmd", 4))
{
if (ends_excmd2(p, eap->cmd))
{
*errormsg =
_(e_vim9cmd_must_be_followed_by_command);
return FAIL;
}
cmod->cmod_flags |= CMOD_VIM9CMD;
continue;
}
if (!checkforcmd_noparen(&p, "verbose", 4))
break;
if (vim_isdigit(*eap->cmd))
{
cmod->cmod_verbose = atoi((char *)eap->cmd);
if (cmod->cmod_verbose == 0)
cmod->cmod_verbose = -1;
}
else
cmod->cmod_verbose = 1;
eap->cmd = p;
continue;
}
break;
}
if (has_visual_range)
{
if (eap->cmd > cmd_start)
{
// Move the '<,'> range to after the modifiers and insert a colon.
// Since the modifiers have been parsed put the colon on top of the
// space: "'<,'>mod cmd" -> "mod:'<,'>cmd
// Put eap->cmd after the colon.
mch_memmove(cmd_start - 5, cmd_start, eap->cmd - cmd_start);
eap->cmd -= 5;
mch_memmove(eap->cmd - 1, ":'<,'>", 6);
}
else
// no modifiers, move the pointer back
eap->cmd -= 5;
}
return OK;
}
| null | null | 206,210
|
263926808274265121339372549336624390231
| 339
|
patch 8.2.4763: using invalid pointer with "V:" in Ex mode
Problem: Using invalid pointer with "V:" in Ex mode.
Solution: Correctly handle the command being changed to "+".
|
other
|
vim
|
c6fdb15d423df22e1776844811d082322475e48a
| 1
|
parse_command_modifiers(
exarg_T *eap,
char **errormsg,
cmdmod_T *cmod,
int skip_only)
{
char_u *orig_cmd = eap->cmd;
char_u *cmd_start = NULL;
int use_plus_cmd = FALSE;
int starts_with_colon = FALSE;
int vim9script = in_vim9script();
int has_visual_range = FALSE;
CLEAR_POINTER(cmod);
cmod->cmod_flags = sticky_cmdmod_flags;
if (STRNCMP(eap->cmd, "'<,'>", 5) == 0)
{
// The automatically inserted Visual area range is skipped, so that
// typing ":cmdmod cmd" in Visual mode works without having to move the
// range to after the modififiers. The command will be
// "'<,'>cmdmod cmd", parse "cmdmod cmd" and then put back "'<,'>"
// before "cmd" below.
eap->cmd += 5;
cmd_start = eap->cmd;
has_visual_range = TRUE;
}
// Repeat until no more command modifiers are found.
for (;;)
{
char_u *p;
while (*eap->cmd == ' ' || *eap->cmd == '\t' || *eap->cmd == ':')
{
if (*eap->cmd == ':')
starts_with_colon = TRUE;
++eap->cmd;
}
// in ex mode, an empty command (after modifiers) works like :+
if (*eap->cmd == NUL && exmode_active
&& (getline_equal(eap->getline, eap->cookie, getexmodeline)
|| getline_equal(eap->getline, eap->cookie, getexline))
&& curwin->w_cursor.lnum < curbuf->b_ml.ml_line_count)
{
use_plus_cmd = TRUE;
if (!skip_only)
ex_pressedreturn = TRUE;
break; // no modifiers following
}
// ignore comment and empty lines
if (comment_start(eap->cmd, starts_with_colon))
{
// a comment ends at a NL
if (eap->nextcmd == NULL)
{
eap->nextcmd = vim_strchr(eap->cmd, '\n');
if (eap->nextcmd != NULL)
++eap->nextcmd;
}
if (vim9script && has_cmdmod(cmod, FALSE))
*errormsg = _(e_command_modifier_without_command);
return FAIL;
}
if (*eap->cmd == NUL)
{
if (!skip_only)
{
ex_pressedreturn = TRUE;
if (vim9script && has_cmdmod(cmod, FALSE))
*errormsg = _(e_command_modifier_without_command);
}
return FAIL;
}
p = skip_range(eap->cmd, TRUE, NULL);
// In Vim9 script a variable can shadow a command modifier:
// verbose = 123
// verbose += 123
// silent! verbose = func()
// verbose.member = 2
// verbose[expr] = 2
// But not:
// verbose [a, b] = list
if (vim9script)
{
char_u *s, *n;
for (s = eap->cmd; ASCII_ISALPHA(*s); ++s)
;
n = skipwhite(s);
if (*n == '.' || *n == '=' || (*n != NUL && n[1] == '=')
|| *s == '[')
break;
}
switch (*p)
{
// When adding an entry, also modify cmd_exists().
case 'a': if (!checkforcmd_noparen(&eap->cmd, "aboveleft", 3))
break;
cmod->cmod_split |= WSP_ABOVE;
continue;
case 'b': if (checkforcmd_noparen(&eap->cmd, "belowright", 3))
{
cmod->cmod_split |= WSP_BELOW;
continue;
}
if (checkforcmd_opt(&eap->cmd, "browse", 3, TRUE))
{
#ifdef FEAT_BROWSE_CMD
cmod->cmod_flags |= CMOD_BROWSE;
#endif
continue;
}
if (!checkforcmd_noparen(&eap->cmd, "botright", 2))
break;
cmod->cmod_split |= WSP_BOT;
continue;
case 'c': if (!checkforcmd_opt(&eap->cmd, "confirm", 4, TRUE))
break;
#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
cmod->cmod_flags |= CMOD_CONFIRM;
#endif
continue;
case 'k': if (checkforcmd_noparen(&eap->cmd, "keepmarks", 3))
{
cmod->cmod_flags |= CMOD_KEEPMARKS;
continue;
}
if (checkforcmd_noparen(&eap->cmd, "keepalt", 5))
{
cmod->cmod_flags |= CMOD_KEEPALT;
continue;
}
if (checkforcmd_noparen(&eap->cmd, "keeppatterns", 5))
{
cmod->cmod_flags |= CMOD_KEEPPATTERNS;
continue;
}
if (!checkforcmd_noparen(&eap->cmd, "keepjumps", 5))
break;
cmod->cmod_flags |= CMOD_KEEPJUMPS;
continue;
case 'f': // only accept ":filter {pat} cmd"
{
char_u *reg_pat;
char_u *nulp = NULL;
int c = 0;
if (!checkforcmd_noparen(&p, "filter", 4)
|| *p == NUL
|| (ends_excmd(*p)
#ifdef FEAT_EVAL
// in ":filter #pat# cmd" # does not
// start a comment
&& (!vim9script || VIM_ISWHITE(p[1]))
#endif
))
break;
if (*p == '!')
{
cmod->cmod_filter_force = TRUE;
p = skipwhite(p + 1);
if (*p == NUL || ends_excmd(*p))
break;
}
#ifdef FEAT_EVAL
// Avoid that "filter(arg)" is recognized.
if (vim9script && !VIM_ISWHITE(p[-1]))
break;
#endif
if (skip_only)
p = skip_vimgrep_pat(p, NULL, NULL);
else
// NOTE: This puts a NUL after the pattern.
p = skip_vimgrep_pat_ext(p, ®_pat, NULL,
&nulp, &c);
if (p == NULL || *p == NUL)
break;
if (!skip_only)
{
cmod->cmod_filter_regmatch.regprog =
vim_regcomp(reg_pat, RE_MAGIC);
if (cmod->cmod_filter_regmatch.regprog == NULL)
break;
// restore the character overwritten by NUL
if (nulp != NULL)
*nulp = c;
}
eap->cmd = p;
continue;
}
// ":hide" and ":hide | cmd" are not modifiers
case 'h': if (p != eap->cmd || !checkforcmd_noparen(&p, "hide", 3)
|| *p == NUL || ends_excmd(*p))
break;
eap->cmd = p;
cmod->cmod_flags |= CMOD_HIDE;
continue;
case 'l': if (checkforcmd_noparen(&eap->cmd, "lockmarks", 3))
{
cmod->cmod_flags |= CMOD_LOCKMARKS;
continue;
}
if (checkforcmd_noparen(&eap->cmd, "legacy", 3))
{
if (ends_excmd2(p, eap->cmd))
{
*errormsg =
_(e_legacy_must_be_followed_by_command);
return FAIL;
}
cmod->cmod_flags |= CMOD_LEGACY;
continue;
}
if (!checkforcmd_noparen(&eap->cmd, "leftabove", 5))
break;
cmod->cmod_split |= WSP_ABOVE;
continue;
case 'n': if (checkforcmd_noparen(&eap->cmd, "noautocmd", 3))
{
cmod->cmod_flags |= CMOD_NOAUTOCMD;
continue;
}
if (!checkforcmd_noparen(&eap->cmd, "noswapfile", 3))
break;
cmod->cmod_flags |= CMOD_NOSWAPFILE;
continue;
case 'r': if (!checkforcmd_noparen(&eap->cmd, "rightbelow", 6))
break;
cmod->cmod_split |= WSP_BELOW;
continue;
case 's': if (checkforcmd_noparen(&eap->cmd, "sandbox", 3))
{
cmod->cmod_flags |= CMOD_SANDBOX;
continue;
}
if (!checkforcmd_noparen(&eap->cmd, "silent", 3))
break;
cmod->cmod_flags |= CMOD_SILENT;
if (*eap->cmd == '!' && !VIM_ISWHITE(eap->cmd[-1]))
{
// ":silent!", but not "silent !cmd"
eap->cmd = skipwhite(eap->cmd + 1);
cmod->cmod_flags |= CMOD_ERRSILENT;
}
continue;
case 't': if (checkforcmd_noparen(&p, "tab", 3))
{
if (!skip_only)
{
long tabnr = get_address(eap, &eap->cmd,
ADDR_TABS, eap->skip,
skip_only, FALSE, 1);
if (tabnr == MAXLNUM)
cmod->cmod_tab = tabpage_index(curtab) + 1;
else
{
if (tabnr < 0 || tabnr > LAST_TAB_NR)
{
*errormsg = _(e_invalid_range);
return FAIL;
}
cmod->cmod_tab = tabnr + 1;
}
}
eap->cmd = p;
continue;
}
if (!checkforcmd_noparen(&eap->cmd, "topleft", 2))
break;
cmod->cmod_split |= WSP_TOP;
continue;
case 'u': if (!checkforcmd_noparen(&eap->cmd, "unsilent", 3))
break;
cmod->cmod_flags |= CMOD_UNSILENT;
continue;
case 'v': if (checkforcmd_noparen(&eap->cmd, "vertical", 4))
{
cmod->cmod_split |= WSP_VERT;
continue;
}
if (checkforcmd_noparen(&eap->cmd, "vim9cmd", 4))
{
if (ends_excmd2(p, eap->cmd))
{
*errormsg =
_(e_vim9cmd_must_be_followed_by_command);
return FAIL;
}
cmod->cmod_flags |= CMOD_VIM9CMD;
continue;
}
if (!checkforcmd_noparen(&p, "verbose", 4))
break;
if (vim_isdigit(*eap->cmd))
{
// zero means not set, one is verbose == 0, etc.
cmod->cmod_verbose = atoi((char *)eap->cmd) + 1;
}
else
cmod->cmod_verbose = 2; // default: verbose == 1
eap->cmd = p;
continue;
}
break;
}
if (has_visual_range)
{
if (eap->cmd > cmd_start)
{
// Move the '<,'> range to after the modifiers and insert a colon.
// Since the modifiers have been parsed put the colon on top of the
// space: "'<,'>mod cmd" -> "mod:'<,'>cmd
// Put eap->cmd after the colon.
if (use_plus_cmd)
{
size_t len = STRLEN(cmd_start);
// Special case: empty command uses "+":
// "'<,'>mods" -> "mods'<,'>+
mch_memmove(orig_cmd, cmd_start, len);
STRCPY(orig_cmd + len, "'<,'>+");
}
else
{
mch_memmove(cmd_start - 5, cmd_start, eap->cmd - cmd_start);
eap->cmd -= 5;
mch_memmove(eap->cmd - 1, ":'<,'>", 6);
}
}
else
// No modifiers, move the pointer back.
// Special case: change empty command to "+".
if (use_plus_cmd)
eap->cmd = (char_u *)"'<,'>+";
else
eap->cmd = orig_cmd;
}
else if (use_plus_cmd)
eap->cmd = (char_u *)"+";
return OK;
}
| null | null | 206,262
|
23783941848142444822455321328938674747
| 362
|
patch 9.0.0025: accessing beyond allocated memory with the cmdline window
Problem: Accessing beyond allocated memory when using the cmdline window in
Ex mode.
Solution: Use "*" instead of "'<,'>" for Visual mode.
|
other
|
radare2
|
a7ce29647fcb38386d7439696375e16e093d6acb
| 1
|
static void extract_arg(RAnal *anal, RAnalFunction *fcn, RAnalOp *op, const char *reg, const char *sign, char type) {
st64 ptr = 0;
char *addr, *esil_buf = NULL;
const st64 maxstackframe = 1024 * 8;
r_return_if_fail (anal && fcn && op && reg);
size_t i;
for (i = 0; i < R_ARRAY_SIZE (op->src); i++) {
if (op->src[i] && op->src[i]->reg && op->src[i]->reg->name) {
if (!strcmp (reg, op->src[i]->reg->name)) {
st64 delta = op->src[i]->delta;
if ((delta > 0 && *sign == '+') || (delta < 0 && *sign == '-')) {
ptr = R_ABS (op->src[i]->delta);
break;
}
}
}
}
if (!ptr) {
const char *op_esil = r_strbuf_get (&op->esil);
if (!op_esil) {
return;
}
esil_buf = strdup (op_esil);
if (!esil_buf) {
return;
}
r_strf_var (esilexpr, 64, ",%s,%s,", reg, sign);
char *ptr_end = strstr (esil_buf, esilexpr);
if (!ptr_end) {
free (esil_buf);
return;
}
*ptr_end = 0;
addr = ptr_end;
while ((addr[0] != '0' || addr[1] != 'x') && addr >= esil_buf + 1 && *addr != ',') {
addr--;
}
if (strncmp (addr, "0x", 2)) {
//XXX: This is a workaround for inconsistent esil
if (!op->stackop && op->dst) {
const char *sp = r_reg_get_name (anal->reg, R_REG_NAME_SP);
const char *bp = r_reg_get_name (anal->reg, R_REG_NAME_BP);
const char *rn = op->dst->reg ? op->dst->reg->name : NULL;
if (rn && ((bp && !strcmp (bp, rn)) || (sp && !strcmp (sp, rn)))) {
if (anal->verbose) {
eprintf ("Warning: Analysis didn't fill op->stackop for instruction that alters stack at 0x%" PFMT64x ".\n", op->addr);
}
goto beach;
}
}
if (*addr == ',') {
addr++;
}
if (!op->stackop && op->type != R_ANAL_OP_TYPE_PUSH && op->type != R_ANAL_OP_TYPE_POP
&& op->type != R_ANAL_OP_TYPE_RET && r_str_isnumber (addr)) {
ptr = (st64)r_num_get (NULL, addr);
if (ptr && op->src[0] && ptr == op->src[0]->imm) {
goto beach;
}
} else if ((op->stackop == R_ANAL_STACK_SET) || (op->stackop == R_ANAL_STACK_GET)) {
if (op->ptr % 4) {
goto beach;
}
ptr = R_ABS (op->ptr);
} else {
goto beach;
}
} else {
ptr = (st64)r_num_get (NULL, addr);
}
}
if (anal->verbose && (!op->src[0] || !op->dst)) {
eprintf ("Warning: Analysis didn't fill op->src/dst at 0x%" PFMT64x ".\n", op->addr);
}
int rw = (op->direction == R_ANAL_OP_DIR_WRITE) ? R_ANAL_VAR_ACCESS_TYPE_WRITE : R_ANAL_VAR_ACCESS_TYPE_READ;
if (*sign == '+') {
const bool isarg = type == R_ANAL_VAR_KIND_SPV ? ptr >= fcn->stack : ptr >= fcn->bp_off;
const char *pfx = isarg ? ARGPREFIX : VARPREFIX;
st64 frame_off;
if (type == R_ANAL_VAR_KIND_SPV) {
frame_off = ptr - fcn->stack;
} else {
frame_off = ptr - fcn->bp_off;
}
if (maxstackframe != 0 && (frame_off > maxstackframe || frame_off < -maxstackframe)) {
goto beach;
}
RAnalVar *var = get_stack_var (fcn, frame_off);
if (var) {
r_anal_var_set_access (var, reg, op->addr, rw, ptr);
goto beach;
}
char *varname = NULL, *vartype = NULL;
if (isarg) {
const char *place = fcn->cc ? r_anal_cc_arg (anal, fcn->cc, ST32_MAX) : NULL;
bool stack_rev = place ? !strcmp (place, "stack_rev") : false;
char *fname = r_type_func_guess (anal->sdb_types, fcn->name);
if (fname) {
ut64 sum_sz = 0;
size_t from, to, i;
if (stack_rev) {
const size_t cnt = r_type_func_args_count (anal->sdb_types, fname);
from = cnt ? cnt - 1 : cnt;
to = fcn->cc ? r_anal_cc_max_arg (anal, fcn->cc) : 0;
} else {
from = fcn->cc ? r_anal_cc_max_arg (anal, fcn->cc) : 0;
to = r_type_func_args_count (anal->sdb_types, fname);
}
const int bytes = (fcn->bits ? fcn->bits : anal->bits) / 8;
for (i = from; stack_rev ? i >= to : i < to; stack_rev ? i-- : i++) {
char *tp = r_type_func_args_type (anal->sdb_types, fname, i);
if (!tp) {
break;
}
if (sum_sz == frame_off) {
vartype = tp;
varname = strdup (r_type_func_args_name (anal->sdb_types, fname, i));
break;
}
ut64 bit_sz = r_type_get_bitsize (anal->sdb_types, tp);
sum_sz += bit_sz ? bit_sz / 8 : bytes;
sum_sz = R_ROUND (sum_sz, bytes);
free (tp);
}
free (fname);
}
}
if (!varname) {
if (anal->opt.varname_stack) {
varname = r_str_newf ("%s_%" PFMT64x "h", pfx, R_ABS (frame_off));
} else {
varname = r_anal_function_autoname_var (fcn, type, pfx, ptr);
}
}
if (varname) {
#if 0
if (isarg && frame_off > 48) {
free (varname);
goto beach;
}
#endif
RAnalVar *var = r_anal_function_set_var (fcn, frame_off, type, vartype, anal->bits / 8, isarg, varname);
if (var) {
r_anal_var_set_access (var, reg, op->addr, rw, ptr);
}
free (varname);
}
free (vartype);
} else {
st64 frame_off = -(ptr + fcn->bp_off);
if (maxstackframe != 0 && (frame_off > maxstackframe || frame_off < -maxstackframe)) {
goto beach;
}
RAnalVar *var = get_stack_var (fcn, frame_off);
if (var) {
r_anal_var_set_access (var, reg, op->addr, rw, -ptr);
goto beach;
}
char *varname = anal->opt.varname_stack
? r_str_newf ("%s_%" PFMT64x "h", VARPREFIX, R_ABS (frame_off))
: r_anal_function_autoname_var (fcn, type, VARPREFIX, -ptr);
if (varname) {
RAnalVar *var = r_anal_function_set_var (fcn, frame_off, type, NULL, anal->bits / 8, false, varname);
if (var) {
r_anal_var_set_access (var, reg, op->addr, rw, -ptr);
}
free (varname);
}
}
beach:
free (esil_buf);
}
| null | null | 206,273
|
77495307470538236846309620865126244810
| 177
|
Fix UAF in aaaa on arm/thumb switching ##crash
* Reported by @peacock-doris via huntr.dev
* Reproducer tests_65185
* This is a logic fix, but not the fully safe as changes in the code
can result on UAF again, to properly protect r2 from crashing we
need to break the ABI and add refcounting to RRegItem, which can't
happen in 5.6.x because of abi-compat rules
|
other
|
vim
|
0971c7a4e537ea120a6bb2195960be8d0815e97b
| 1
|
ins_bs(
int c,
int mode,
int *inserted_space_p)
{
linenr_T lnum;
int cc;
int temp = 0; // init for GCC
colnr_T save_col;
colnr_T mincol;
int did_backspace = FALSE;
int in_indent;
int oldState;
int cpc[MAX_MCO]; // composing characters
int call_fix_indent = FALSE;
/*
* can't delete anything in an empty file
* can't backup past first character in buffer
* can't backup past starting point unless 'backspace' > 1
* can backup to a previous line if 'backspace' == 0
*/
if ( BUFEMPTY()
|| (
#ifdef FEAT_RIGHTLEFT
!revins_on &&
#endif
((curwin->w_cursor.lnum == 1 && curwin->w_cursor.col == 0)
|| (!can_bs(BS_START)
&& ((arrow_used
#ifdef FEAT_JOB_CHANNEL
&& !bt_prompt(curbuf)
#endif
) || (curwin->w_cursor.lnum == Insstart_orig.lnum
&& curwin->w_cursor.col <= Insstart_orig.col)))
|| (!can_bs(BS_INDENT) && !arrow_used && ai_col > 0
&& curwin->w_cursor.col <= ai_col)
|| (!can_bs(BS_EOL) && curwin->w_cursor.col == 0))))
{
vim_beep(BO_BS);
return FALSE;
}
if (stop_arrow() == FAIL)
return FALSE;
in_indent = inindent(0);
if (in_indent)
can_cindent = FALSE;
end_comment_pending = NUL; // After BS, don't auto-end comment
#ifdef FEAT_RIGHTLEFT
if (revins_on) // put cursor after last inserted char
inc_cursor();
#endif
// Virtualedit:
// BACKSPACE_CHAR eats a virtual space
// BACKSPACE_WORD eats all coladd
// BACKSPACE_LINE eats all coladd and keeps going
if (curwin->w_cursor.coladd > 0)
{
if (mode == BACKSPACE_CHAR)
{
--curwin->w_cursor.coladd;
return TRUE;
}
if (mode == BACKSPACE_WORD)
{
curwin->w_cursor.coladd = 0;
return TRUE;
}
curwin->w_cursor.coladd = 0;
}
/*
* Delete newline!
*/
if (curwin->w_cursor.col == 0)
{
lnum = Insstart.lnum;
if (curwin->w_cursor.lnum == lnum
#ifdef FEAT_RIGHTLEFT
|| revins_on
#endif
)
{
if (u_save((linenr_T)(curwin->w_cursor.lnum - 2),
(linenr_T)(curwin->w_cursor.lnum + 1)) == FAIL)
return FALSE;
--Insstart.lnum;
Insstart.col = (colnr_T)STRLEN(ml_get(Insstart.lnum));
}
/*
* In replace mode:
* cc < 0: NL was inserted, delete it
* cc >= 0: NL was replaced, put original characters back
*/
cc = -1;
if (State & REPLACE_FLAG)
cc = replace_pop(); // returns -1 if NL was inserted
/*
* In replace mode, in the line we started replacing, we only move the
* cursor.
*/
if ((State & REPLACE_FLAG) && curwin->w_cursor.lnum <= lnum)
{
dec_cursor();
}
else
{
if (!(State & VREPLACE_FLAG)
|| curwin->w_cursor.lnum > orig_line_count)
{
temp = gchar_cursor(); // remember current char
--curwin->w_cursor.lnum;
// When "aw" is in 'formatoptions' we must delete the space at
// the end of the line, otherwise the line will be broken
// again when auto-formatting.
if (has_format_option(FO_AUTO)
&& has_format_option(FO_WHITE_PAR))
{
char_u *ptr = ml_get_buf(curbuf, curwin->w_cursor.lnum,
TRUE);
int len;
len = (int)STRLEN(ptr);
if (len > 0 && ptr[len - 1] == ' ')
ptr[len - 1] = NUL;
}
(void)do_join(2, FALSE, FALSE, FALSE, FALSE);
if (temp == NUL && gchar_cursor() != NUL)
inc_cursor();
}
else
dec_cursor();
/*
* In MODE_REPLACE mode we have to put back the text that was
* replaced by the NL. On the replace stack is first a
* NUL-terminated sequence of characters that were deleted and then
* the characters that NL replaced.
*/
if (State & REPLACE_FLAG)
{
/*
* Do the next ins_char() in MODE_NORMAL state, to
* prevent ins_char() from replacing characters and
* avoiding showmatch().
*/
oldState = State;
State = MODE_NORMAL;
/*
* restore characters (blanks) deleted after cursor
*/
while (cc > 0)
{
save_col = curwin->w_cursor.col;
mb_replace_pop_ins(cc);
curwin->w_cursor.col = save_col;
cc = replace_pop();
}
// restore the characters that NL replaced
replace_pop_ins();
State = oldState;
}
}
did_ai = FALSE;
}
else
{
/*
* Delete character(s) before the cursor.
*/
#ifdef FEAT_RIGHTLEFT
if (revins_on) // put cursor on last inserted char
dec_cursor();
#endif
mincol = 0;
// keep indent
if (mode == BACKSPACE_LINE
&& (curbuf->b_p_ai || cindent_on())
#ifdef FEAT_RIGHTLEFT
&& !revins_on
#endif
)
{
save_col = curwin->w_cursor.col;
beginline(BL_WHITE);
if (curwin->w_cursor.col < save_col)
{
mincol = curwin->w_cursor.col;
// should now fix the indent to match with the previous line
call_fix_indent = TRUE;
}
curwin->w_cursor.col = save_col;
}
/*
* Handle deleting one 'shiftwidth' or 'softtabstop'.
*/
if ( mode == BACKSPACE_CHAR
&& ((p_sta && in_indent)
|| ((get_sts_value() != 0
#ifdef FEAT_VARTABS
|| tabstop_count(curbuf->b_p_vsts_array)
#endif
)
&& curwin->w_cursor.col > 0
&& (*(ml_get_cursor() - 1) == TAB
|| (*(ml_get_cursor() - 1) == ' '
&& (!*inserted_space_p
|| arrow_used))))))
{
int ts;
colnr_T vcol;
colnr_T want_vcol;
colnr_T start_vcol;
*inserted_space_p = FALSE;
// Compute the virtual column where we want to be. Since
// 'showbreak' may get in the way, need to get the last column of
// the previous character.
getvcol(curwin, &curwin->w_cursor, &vcol, NULL, NULL);
start_vcol = vcol;
dec_cursor();
getvcol(curwin, &curwin->w_cursor, NULL, NULL, &want_vcol);
inc_cursor();
#ifdef FEAT_VARTABS
if (p_sta && in_indent)
{
ts = (int)get_sw_value(curbuf);
want_vcol = (want_vcol / ts) * ts;
}
else
want_vcol = tabstop_start(want_vcol, get_sts_value(),
curbuf->b_p_vsts_array);
#else
if (p_sta && in_indent)
ts = (int)get_sw_value(curbuf);
else
ts = (int)get_sts_value();
want_vcol = (want_vcol / ts) * ts;
#endif
// delete characters until we are at or before want_vcol
while (vcol > want_vcol
&& (cc = *(ml_get_cursor() - 1), VIM_ISWHITE(cc)))
ins_bs_one(&vcol);
// insert extra spaces until we are at want_vcol
while (vcol < want_vcol)
{
// Remember the first char we inserted
if (curwin->w_cursor.lnum == Insstart_orig.lnum
&& curwin->w_cursor.col < Insstart_orig.col)
Insstart_orig.col = curwin->w_cursor.col;
if (State & VREPLACE_FLAG)
ins_char(' ');
else
{
ins_str((char_u *)" ");
if ((State & REPLACE_FLAG))
replace_push(NUL);
}
getvcol(curwin, &curwin->w_cursor, &vcol, NULL, NULL);
}
// If we are now back where we started delete one character. Can
// happen when using 'sts' and 'linebreak'.
if (vcol >= start_vcol)
ins_bs_one(&vcol);
}
/*
* Delete up to starting point, start of line or previous word.
*/
else
{
int cclass = 0, prev_cclass = 0;
if (has_mbyte)
cclass = mb_get_class(ml_get_cursor());
do
{
#ifdef FEAT_RIGHTLEFT
if (!revins_on) // put cursor on char to be deleted
#endif
dec_cursor();
cc = gchar_cursor();
// look multi-byte character class
if (has_mbyte)
{
prev_cclass = cclass;
cclass = mb_get_class(ml_get_cursor());
}
// start of word?
if (mode == BACKSPACE_WORD && !vim_isspace(cc))
{
mode = BACKSPACE_WORD_NOT_SPACE;
temp = vim_iswordc(cc);
}
// end of word?
else if (mode == BACKSPACE_WORD_NOT_SPACE
&& ((vim_isspace(cc) || vim_iswordc(cc) != temp)
|| prev_cclass != cclass))
{
#ifdef FEAT_RIGHTLEFT
if (!revins_on)
#endif
inc_cursor();
#ifdef FEAT_RIGHTLEFT
else if (State & REPLACE_FLAG)
dec_cursor();
#endif
break;
}
if (State & REPLACE_FLAG)
replace_do_bs(-1);
else
{
if (enc_utf8 && p_deco)
(void)utfc_ptr2char(ml_get_cursor(), cpc);
(void)del_char(FALSE);
/*
* If there are combining characters and 'delcombine' is set
* move the cursor back. Don't back up before the base
* character.
*/
if (enc_utf8 && p_deco && cpc[0] != NUL)
inc_cursor();
#ifdef FEAT_RIGHTLEFT
if (revins_chars)
{
revins_chars--;
revins_legal++;
}
if (revins_on && gchar_cursor() == NUL)
break;
#endif
}
// Just a single backspace?:
if (mode == BACKSPACE_CHAR)
break;
} while (
#ifdef FEAT_RIGHTLEFT
revins_on ||
#endif
(curwin->w_cursor.col > mincol
&& (can_bs(BS_NOSTOP)
|| (curwin->w_cursor.lnum != Insstart_orig.lnum
|| curwin->w_cursor.col != Insstart_orig.col)
)));
}
did_backspace = TRUE;
}
did_si = FALSE;
can_si = FALSE;
can_si_back = FALSE;
if (curwin->w_cursor.col <= 1)
did_ai = FALSE;
if (call_fix_indent)
fix_indent();
/*
* It's a little strange to put backspaces into the redo
* buffer, but it makes auto-indent a lot easier to deal
* with.
*/
AppendCharToRedobuff(c);
// If deleted before the insertion point, adjust it
if (curwin->w_cursor.lnum == Insstart_orig.lnum
&& curwin->w_cursor.col < Insstart_orig.col)
Insstart_orig.col = curwin->w_cursor.col;
// vi behaviour: the cursor moves backward but the character that
// was there remains visible
// Vim behaviour: the cursor moves backward and the character that
// was there is erased from the screen.
// We can emulate the vi behaviour by pretending there is a dollar
// displayed even when there isn't.
// --pkv Sun Jan 19 01:56:40 EST 2003
if (vim_strchr(p_cpo, CPO_BACKSPACE) != NULL && dollar_vcol == -1)
dollar_vcol = curwin->w_virtcol;
#ifdef FEAT_FOLDING
// When deleting a char the cursor line must never be in a closed fold.
// E.g., when 'foldmethod' is indent and deleting the first non-white
// char before a Tab.
if (did_backspace)
foldOpenCursor();
#endif
return did_backspace;
}
| null | null | 206,417
|
177296164879678018526622038270274780805
| 400
|
patch 8.2.5162: reading before the start of the line with BS in Replace mode
Problem: Reading before the start of the line with BS in Replace mode.
Solution: Check the cursor column is more than zero.
|
other
|
linux
|
7fc3b7c2981bbd1047916ade327beccb90994eee
| 1
|
int udf_expand_file_adinicb(struct inode *inode)
{
struct page *page;
char *kaddr;
struct udf_inode_info *iinfo = UDF_I(inode);
int err;
struct writeback_control udf_wbc = {
.sync_mode = WB_SYNC_NONE,
.nr_to_write = 1,
};
WARN_ON_ONCE(!inode_is_locked(inode));
if (!iinfo->i_lenAlloc) {
if (UDF_QUERY_FLAG(inode->i_sb, UDF_FLAG_USE_SHORT_AD))
iinfo->i_alloc_type = ICBTAG_FLAG_AD_SHORT;
else
iinfo->i_alloc_type = ICBTAG_FLAG_AD_LONG;
/* from now on we have normal address_space methods */
inode->i_data.a_ops = &udf_aops;
up_write(&iinfo->i_data_sem);
mark_inode_dirty(inode);
return 0;
}
/*
* Release i_data_sem so that we can lock a page - page lock ranks
* above i_data_sem. i_mutex still protects us against file changes.
*/
up_write(&iinfo->i_data_sem);
page = find_or_create_page(inode->i_mapping, 0, GFP_NOFS);
if (!page)
return -ENOMEM;
if (!PageUptodate(page)) {
kaddr = kmap_atomic(page);
memset(kaddr + iinfo->i_lenAlloc, 0x00,
PAGE_SIZE - iinfo->i_lenAlloc);
memcpy(kaddr, iinfo->i_data + iinfo->i_lenEAttr,
iinfo->i_lenAlloc);
flush_dcache_page(page);
SetPageUptodate(page);
kunmap_atomic(kaddr);
}
down_write(&iinfo->i_data_sem);
memset(iinfo->i_data + iinfo->i_lenEAttr, 0x00,
iinfo->i_lenAlloc);
iinfo->i_lenAlloc = 0;
if (UDF_QUERY_FLAG(inode->i_sb, UDF_FLAG_USE_SHORT_AD))
iinfo->i_alloc_type = ICBTAG_FLAG_AD_SHORT;
else
iinfo->i_alloc_type = ICBTAG_FLAG_AD_LONG;
/* from now on we have normal address_space methods */
inode->i_data.a_ops = &udf_aops;
up_write(&iinfo->i_data_sem);
err = inode->i_data.a_ops->writepage(page, &udf_wbc);
if (err) {
/* Restore everything back so that we don't lose data... */
lock_page(page);
down_write(&iinfo->i_data_sem);
kaddr = kmap_atomic(page);
memcpy(iinfo->i_data + iinfo->i_lenEAttr, kaddr, inode->i_size);
kunmap_atomic(kaddr);
unlock_page(page);
iinfo->i_alloc_type = ICBTAG_FLAG_AD_IN_ICB;
inode->i_data.a_ops = &udf_adinicb_aops;
up_write(&iinfo->i_data_sem);
}
put_page(page);
mark_inode_dirty(inode);
return err;
}
| null | null | 206,510
|
295537766096851531358039660611370806725
| 72
|
udf: Fix NULL ptr deref when converting from inline format
udf_expand_file_adinicb() calls directly ->writepage to write data
expanded into a page. This however misses to setup inode for writeback
properly and so we can crash on inode->i_wb dereference when submitting
page for IO like:
BUG: kernel NULL pointer dereference, address: 0000000000000158
#PF: supervisor read access in kernel mode
...
<TASK>
__folio_start_writeback+0x2ac/0x350
__block_write_full_page+0x37d/0x490
udf_expand_file_adinicb+0x255/0x400 [udf]
udf_file_write_iter+0xbe/0x1b0 [udf]
new_sync_write+0x125/0x1c0
vfs_write+0x28e/0x400
Fix the problem by marking the page dirty and going through the standard
writeback path to write the page. Strictly speaking we would not even
have to write the page but we want to catch e.g. ENOSPC errors early.
Reported-by: butt3rflyh4ck <[email protected]>
CC: [email protected]
Fixes: 52ebea749aae ("writeback: make backing_dev_info host cgroup-specific bdi_writebacks")
Reviewed-by: Christoph Hellwig <[email protected]>
Signed-off-by: Jan Kara <[email protected]>
|
other
|
php-src
|
cc08cbc84d46933c1e9e0149633f1ed5d19e45e9
| 1
|
static int dynamicGetbuf (gdIOCtxPtr ctx, void *buf, int len)
{
int rlen, remain;
dpIOCtxPtr dctx;
dynamicPtr *dp;
dctx = (dpIOCtxPtr) ctx;
dp = dctx->dp;
remain = dp->logicalSize - dp->pos;
if (remain >= len) {
rlen = len;
} else {
if (remain == 0) {
return EOF;
}
rlen = remain;
}
memcpy(buf, (void *) ((char *) dp->data + dp->pos), rlen);
dp->pos += rlen;
return rlen;
}
| null | null | 206,555
|
276412319745045670976321362892432796885
| 24
|
Fix #73280: Stack Buffer Overflow in GD dynamicGetbuf
We make sure to never pass a negative `rlen` as size to memcpy().
Cf. <https://github.com/libgd/libgd/commit/53110871>.
|
other
|
php-src
|
feba44546c27b0158f9ac20e72040a224b918c75
| 1
|
gdImageFillToBorder (gdImagePtr im, int x, int y, int border, int color)
{
int lastBorder;
/* Seek left */
int leftLimit, rightLimit;
int i;
leftLimit = (-1);
if (border < 0)
{
/* Refuse to fill to a non-solid border */
return;
}
for (i = x; (i >= 0); i--)
{
if (gdImageGetPixel (im, i, y) == border)
{
break;
}
gdImageSetPixel (im, i, y, color);
leftLimit = i;
}
if (leftLimit == (-1))
{
return;
}
/* Seek right */
rightLimit = x;
for (i = (x + 1); (i < im->sx); i++)
{
if (gdImageGetPixel (im, i, y) == border)
{
break;
}
gdImageSetPixel (im, i, y, color);
rightLimit = i;
}
/* Look at lines above and below and start paints */
/* Above */
if (y > 0)
{
lastBorder = 1;
for (i = leftLimit; (i <= rightLimit); i++)
{
int c;
c = gdImageGetPixel (im, i, y - 1);
if (lastBorder)
{
if ((c != border) && (c != color))
{
gdImageFillToBorder (im, i, y - 1,
border, color);
lastBorder = 0;
}
}
else if ((c == border) || (c == color))
{
lastBorder = 1;
}
}
}
/* Below */
if (y < ((im->sy) - 1))
{
lastBorder = 1;
for (i = leftLimit; (i <= rightLimit); i++)
{
int c;
c = gdImageGetPixel (im, i, y + 1);
if (lastBorder)
{
if ((c != border) && (c != color))
{
gdImageFillToBorder (im, i, y + 1,
border, color);
lastBorder = 0;
}
}
else if ((c == border) || (c == color))
{
lastBorder = 1;
}
}
}
}
| null | null | 206,588
|
184041259400366666213082744805348296992
| 84
|
Fixed bug #22965 (Crash in gd lib's ImageFillToBorder()).
|
other
|
raptor
|
590681e546cd9aa18d57dc2ea1858cb734a3863f
| 1
|
raptor_xml_writer_start_element_common(raptor_xml_writer* xml_writer,
raptor_xml_element* element,
int auto_empty)
{
raptor_iostream* iostr = xml_writer->iostr;
raptor_namespace_stack *nstack = xml_writer->nstack;
int depth = xml_writer->depth;
int auto_indent = XML_WRITER_AUTO_INDENT(xml_writer);
struct nsd *nspace_declarations = NULL;
size_t nspace_declarations_count = 0;
unsigned int i;
/* max is 1 per element and 1 for each attribute + size of declared */
if(nstack) {
int nspace_max_count = element->attribute_count+1;
if(element->declared_nspaces)
nspace_max_count += raptor_sequence_size(element->declared_nspaces);
if(element->xml_language)
nspace_max_count++;
nspace_declarations = RAPTOR_CALLOC(struct nsd*, nspace_max_count,
sizeof(struct nsd));
if(!nspace_declarations)
return 1;
}
if(element->name->nspace) {
if(nstack && !raptor_namespaces_namespace_in_scope(nstack, element->name->nspace)) {
nspace_declarations[0].declaration=
raptor_namespace_format_as_xml(element->name->nspace,
&nspace_declarations[0].length);
if(!nspace_declarations[0].declaration)
goto error;
nspace_declarations[0].nspace = element->name->nspace;
nspace_declarations_count++;
}
}
if(nstack && element->attributes) {
for(i = 0; i < element->attribute_count; i++) {
/* qname */
if(element->attributes[i]->nspace) {
/* Check if we need a namespace declaration attribute */
if(nstack &&
!raptor_namespaces_namespace_in_scope(nstack, element->attributes[i]->nspace) && element->attributes[i]->nspace != element->name->nspace) {
/* not in scope and not same as element (so already going to be declared)*/
unsigned int j;
int declare_me = 1;
/* check it wasn't an earlier declaration too */
for(j = 0; j < nspace_declarations_count; j++)
if(nspace_declarations[j].nspace == element->attributes[j]->nspace) {
declare_me = 0;
break;
}
if(declare_me) {
nspace_declarations[nspace_declarations_count].declaration=
raptor_namespace_format_as_xml(element->attributes[i]->nspace,
&nspace_declarations[nspace_declarations_count].length);
if(!nspace_declarations[nspace_declarations_count].declaration)
goto error;
nspace_declarations[nspace_declarations_count].nspace = element->attributes[i]->nspace;
nspace_declarations_count++;
}
}
}
/* Add the attribute + value */
nspace_declarations[nspace_declarations_count].declaration=
raptor_qname_format_as_xml(element->attributes[i],
&nspace_declarations[nspace_declarations_count].length);
if(!nspace_declarations[nspace_declarations_count].declaration)
goto error;
nspace_declarations[nspace_declarations_count].nspace = NULL;
nspace_declarations_count++;
}
}
if(nstack && element->declared_nspaces &&
raptor_sequence_size(element->declared_nspaces) > 0) {
for(i = 0; i< (unsigned int)raptor_sequence_size(element->declared_nspaces); i++) {
raptor_namespace* nspace = (raptor_namespace*)raptor_sequence_get_at(element->declared_nspaces, i);
unsigned int j;
int declare_me = 1;
/* check it wasn't an earlier declaration too */
for(j = 0; j < nspace_declarations_count; j++)
if(nspace_declarations[j].nspace == nspace) {
declare_me = 0;
break;
}
if(declare_me) {
nspace_declarations[nspace_declarations_count].declaration=
raptor_namespace_format_as_xml(nspace,
&nspace_declarations[nspace_declarations_count].length);
if(!nspace_declarations[nspace_declarations_count].declaration)
goto error;
nspace_declarations[nspace_declarations_count].nspace = nspace;
nspace_declarations_count++;
}
}
}
if(nstack && element->xml_language) {
size_t lang_len = strlen(RAPTOR_GOOD_CAST(char*, element->xml_language));
#define XML_LANG_PREFIX_LEN 10
size_t buf_length = XML_LANG_PREFIX_LEN + lang_len + 1;
unsigned char* buffer = RAPTOR_MALLOC(unsigned char*, buf_length + 1);
const char quote = '\"';
unsigned char* p;
memcpy(buffer, "xml:lang=\"", XML_LANG_PREFIX_LEN);
p = buffer + XML_LANG_PREFIX_LEN;
p += raptor_xml_escape_string(xml_writer->world,
element->xml_language, lang_len,
p, buf_length, quote);
*p++ = quote;
*p = '\0';
nspace_declarations[nspace_declarations_count].declaration = buffer;
nspace_declarations[nspace_declarations_count].length = buf_length;
nspace_declarations[nspace_declarations_count].nspace = NULL;
nspace_declarations_count++;
}
raptor_iostream_write_byte('<', iostr);
if(element->name->nspace && element->name->nspace->prefix_length > 0) {
raptor_iostream_counted_string_write((const char*)element->name->nspace->prefix,
element->name->nspace->prefix_length,
iostr);
raptor_iostream_write_byte(':', iostr);
}
raptor_iostream_counted_string_write((const char*)element->name->local_name,
element->name->local_name_length,
iostr);
/* declare namespaces and attributes */
if(nspace_declarations_count) {
int need_indent = 0;
/* sort them into the canonical order */
qsort((void*)nspace_declarations,
nspace_declarations_count, sizeof(struct nsd),
raptor_xml_writer_nsd_compare);
/* declare namespaces first */
for(i = 0; i < nspace_declarations_count; i++) {
if(!nspace_declarations[i].nspace)
continue;
if(auto_indent && need_indent) {
/* indent attributes */
raptor_xml_writer_newline(xml_writer);
xml_writer->depth++;
raptor_xml_writer_indent(xml_writer);
xml_writer->depth--;
}
raptor_iostream_write_byte(' ', iostr);
raptor_iostream_counted_string_write((const char*)nspace_declarations[i].declaration,
nspace_declarations[i].length,
iostr);
RAPTOR_FREE(char*, nspace_declarations[i].declaration);
nspace_declarations[i].declaration = NULL;
need_indent = 1;
if(raptor_namespace_stack_start_namespace(nstack,
(raptor_namespace*)nspace_declarations[i].nspace,
depth))
goto error;
}
/* declare attributes */
for(i = 0; i < nspace_declarations_count; i++) {
if(nspace_declarations[i].nspace)
continue;
if(auto_indent && need_indent) {
/* indent attributes */
raptor_xml_writer_newline(xml_writer);
xml_writer->depth++;
raptor_xml_writer_indent(xml_writer);
xml_writer->depth--;
}
raptor_iostream_write_byte(' ', iostr);
raptor_iostream_counted_string_write((const char*)nspace_declarations[i].declaration,
nspace_declarations[i].length,
iostr);
need_indent = 1;
RAPTOR_FREE(char*, nspace_declarations[i].declaration);
nspace_declarations[i].declaration = NULL;
}
}
if(!auto_empty)
raptor_iostream_write_byte('>', iostr);
if(nstack)
RAPTOR_FREE(stringarray, nspace_declarations);
return 0;
/* Clean up nspace_declarations on error */
error:
for(i = 0; i < nspace_declarations_count; i++) {
if(nspace_declarations[i].declaration)
RAPTOR_FREE(char*, nspace_declarations[i].declaration);
}
RAPTOR_FREE(stringarray, nspace_declarations);
return 1;
}
| null | null | 206,625
|
238676757986848816974955818012445883188
| 220
|
Calcualte max nspace declarations correctly for XML writer
(raptor_xml_writer_start_element_common): Calculate max including for
each attribute a potential name and value.
Fixes Issues #0000617 http://bugs.librdf.org/mantis/view.php?id=617
and #0000618 http://bugs.librdf.org/mantis/view.php?id=618
|
other
|
linux
|
e02f0d3970404bfea385b6edb86f2d936db0ea2b
| 1
|
static int nft_verdict_init(const struct nft_ctx *ctx, struct nft_data *data,
struct nft_data_desc *desc, const struct nlattr *nla)
{
u8 genmask = nft_genmask_next(ctx->net);
struct nlattr *tb[NFTA_VERDICT_MAX + 1];
struct nft_chain *chain;
int err;
err = nla_parse_nested_deprecated(tb, NFTA_VERDICT_MAX, nla,
nft_verdict_policy, NULL);
if (err < 0)
return err;
if (!tb[NFTA_VERDICT_CODE])
return -EINVAL;
data->verdict.code = ntohl(nla_get_be32(tb[NFTA_VERDICT_CODE]));
switch (data->verdict.code) {
default:
switch (data->verdict.code & NF_VERDICT_MASK) {
case NF_ACCEPT:
case NF_DROP:
case NF_QUEUE:
break;
default:
return -EINVAL;
}
fallthrough;
case NFT_CONTINUE:
case NFT_BREAK:
case NFT_RETURN:
break;
case NFT_JUMP:
case NFT_GOTO:
if (tb[NFTA_VERDICT_CHAIN]) {
chain = nft_chain_lookup(ctx->net, ctx->table,
tb[NFTA_VERDICT_CHAIN],
genmask);
} else if (tb[NFTA_VERDICT_CHAIN_ID]) {
chain = nft_chain_lookup_byid(ctx->net, ctx->table,
tb[NFTA_VERDICT_CHAIN_ID]);
if (IS_ERR(chain))
return PTR_ERR(chain);
} else {
return -EINVAL;
}
if (IS_ERR(chain))
return PTR_ERR(chain);
if (nft_is_base_chain(chain))
return -EOPNOTSUPP;
if (desc->flags & NFT_DATA_DESC_SETELEM &&
chain->flags & NFT_CHAIN_BINDING)
return -EINVAL;
chain->use++;
data->verdict.chain = chain;
break;
}
desc->len = sizeof(data->verdict);
return 0;
}
| null | null | 206,639
|
271815403301886464376637210871387795530
| 64
|
netfilter: nf_tables: disallow binding to already bound chain
Update nft_data_init() to report EINVAL if chain is already bound.
Fixes: d0e2c7de92c7 ("netfilter: nf_tables: add NFT_CHAIN_BINDING")
Reported-by: Gwangun Jung <[email protected]>
Signed-off-by: Pablo Neira Ayuso <[email protected]>
|
other
|
radare2
|
ca8d8b39f3e34a4fd943270330b80f1148129de4
| 1
|
static void parse_relocation_info(struct MACH0_(obj_t) *bin, RSkipList *relocs, ut32 offset, ut32 num) {
if (!num || !offset || (st32)num < 0) {
return;
}
ut64 total_size = num * sizeof (struct relocation_info);
if (offset > bin->size) {
return;
}
if (total_size > bin->size) {
total_size = bin->size - offset;
num = total_size /= sizeof (struct relocation_info);
}
struct relocation_info *info = calloc (num, sizeof (struct relocation_info));
if (!info) {
return;
}
if (r_buf_read_at (bin->b, offset, (ut8 *) info, total_size) < total_size) {
free (info);
return;
}
size_t i;
for (i = 0; i < num; i++) {
struct relocation_info a_info = info[i];
ut32 sym_num = a_info.r_symbolnum;
if (sym_num > bin->nsymtab) {
continue;
}
ut32 stridx = bin->symtab[sym_num].n_strx;
char *sym_name = get_name (bin, stridx, false);
if (!sym_name) {
continue;
}
struct reloc_t *reloc = R_NEW0 (struct reloc_t);
if (!reloc) {
free (info);
free (sym_name);
return;
}
reloc->addr = offset_to_vaddr (bin, a_info.r_address);
reloc->offset = a_info.r_address;
reloc->ord = sym_num;
reloc->type = a_info.r_type; // enum RelocationInfoType
reloc->external = a_info.r_extern;
reloc->pc_relative = a_info.r_pcrel;
reloc->size = a_info.r_length;
r_str_ncpy (reloc->name, sym_name, sizeof (reloc->name) - 1);
r_skiplist_insert (relocs, reloc);
free (sym_name);
}
free (info);
}
| null | null | 206,665
|
266652469078373975899292101322144867802
| 57
|
Fix oobread in the macho parser ##crash
* Reported by @Han0nly via huntr.dev
* Reproducers: heapoverflow1
* BountyID: e589bd97-4c74-4e79-93b5-0951a281facc
|
other
|
nbdkit
|
6c5faac6a37077cf2366388a80862bb00616d0d8
| 1
|
negotiate_handshake_newstyle_options (void)
{
GET_CONN;
struct nbd_new_option new_option;
size_t nr_options;
bool list_seen = false;
uint64_t version;
uint32_t option;
uint32_t optlen;
struct nbd_export_name_option_reply handshake_finish;
const char *optname;
uint64_t exportsize;
struct backend *b;
for (nr_options = MAX_NR_OPTIONS; nr_options > 0; --nr_options) {
CLEANUP_FREE char *data = NULL;
if (conn_recv_full (&new_option, sizeof new_option,
"reading option: conn->recv: %m") == -1)
return -1;
version = be64toh (new_option.version);
if (version != NBD_NEW_VERSION) {
nbdkit_error ("unknown option version %" PRIx64
", expecting %" PRIx64,
version, NBD_NEW_VERSION);
return -1;
}
/* There is a maximum option length we will accept, regardless
* of the option type.
*/
optlen = be32toh (new_option.optlen);
if (optlen > MAX_REQUEST_SIZE) {
nbdkit_error ("client option data too long (%" PRIu32 ")", optlen);
return -1;
}
data = malloc (optlen + 1); /* Allowing a trailing NUL helps some uses */
if (data == NULL) {
nbdkit_error ("malloc: %m");
return -1;
}
option = be32toh (new_option.option);
optname = name_of_nbd_opt (option);
/* If the client lacks fixed newstyle support, it should only send
* NBD_OPT_EXPORT_NAME.
*/
if (!(conn->cflags & NBD_FLAG_FIXED_NEWSTYLE) &&
option != NBD_OPT_EXPORT_NAME) {
if (send_newstyle_option_reply (option, NBD_REP_ERR_INVALID))
return -1;
continue;
}
/* In --tls=require / FORCEDTLS mode the only options allowed
* before TLS negotiation are NBD_OPT_ABORT and NBD_OPT_STARTTLS.
*/
if (tls == 2 && !conn->using_tls &&
!(option == NBD_OPT_ABORT || option == NBD_OPT_STARTTLS)) {
if (send_newstyle_option_reply (option, NBD_REP_ERR_TLS_REQD))
return -1;
continue;
}
switch (option) {
case NBD_OPT_EXPORT_NAME:
if (conn_recv_full (data, optlen,
"read: %s: %m", name_of_nbd_opt (option)) == -1)
return -1;
if (check_export_name (option, data, optlen, optlen) == -1)
return -1;
/* We have to finish the handshake by sending handshake_finish.
* On failure, we have to disconnect.
*/
if (finish_newstyle_options (&exportsize, data, optlen) == -1)
return -1;
memset (&handshake_finish, 0, sizeof handshake_finish);
handshake_finish.exportsize = htobe64 (exportsize);
handshake_finish.eflags = htobe16 (conn->eflags);
if (conn->send (&handshake_finish,
(conn->cflags & NBD_FLAG_NO_ZEROES)
? offsetof (struct nbd_export_name_option_reply, zeroes)
: sizeof handshake_finish, 0) == -1) {
nbdkit_error ("write: %s: %m", optname);
return -1;
}
break;
case NBD_OPT_ABORT:
if (send_newstyle_option_reply (option, NBD_REP_ACK) == -1)
return -1;
debug ("client sent %s to abort the connection",
name_of_nbd_opt (option));
return -1;
case NBD_OPT_LIST:
if (optlen != 0) {
if (send_newstyle_option_reply (option, NBD_REP_ERR_INVALID)
== -1)
return -1;
if (conn_recv_full (data, optlen,
"read: %s: %m", name_of_nbd_opt (option)) == -1)
return -1;
continue;
}
if (list_seen) {
debug ("newstyle negotiation: %s: export list already advertised",
name_of_nbd_opt (option));
if (send_newstyle_option_reply (option, NBD_REP_ERR_INVALID) == -1)
return -1;
continue;
}
else {
/* Send back the exportname list. */
debug ("newstyle negotiation: %s: advertising exports",
name_of_nbd_opt (option));
if (send_newstyle_option_reply_exportnames (option, &nr_options) == -1)
return -1;
list_seen = true;
}
break;
case NBD_OPT_STARTTLS:
if (optlen != 0) {
if (send_newstyle_option_reply (option, NBD_REP_ERR_INVALID)
== -1)
return -1;
if (conn_recv_full (data, optlen,
"read: %s: %m", name_of_nbd_opt (option)) == -1)
return -1;
continue;
}
if (tls == 0) { /* --tls=off (NOTLS mode). */
#ifdef HAVE_GNUTLS
#define NO_TLS_REPLY NBD_REP_ERR_POLICY
#else
#define NO_TLS_REPLY NBD_REP_ERR_UNSUP
#endif
if (send_newstyle_option_reply (option, NO_TLS_REPLY) == -1)
return -1;
}
else /* --tls=on or --tls=require */ {
/* We can't upgrade to TLS twice on the same connection. */
if (conn->using_tls) {
if (send_newstyle_option_reply (option, NBD_REP_ERR_INVALID) == -1)
return -1;
continue;
}
/* We have to send the (unencrypted) reply before starting
* the handshake.
*/
if (send_newstyle_option_reply (option, NBD_REP_ACK) == -1)
return -1;
/* Upgrade the connection to TLS. Also performs access control. */
if (crypto_negotiate_tls (conn->sockin, conn->sockout) == -1)
return -1;
conn->using_tls = true;
debug ("using TLS on this connection");
/* Wipe out any cached state. */
conn->structured_replies = false;
for_each_backend (b) {
free (conn->default_exportname[b->i]);
conn->default_exportname[b->i] = NULL;
}
}
break;
case NBD_OPT_INFO:
case NBD_OPT_GO:
if (conn_recv_full (data, optlen, "read: %s: %m", optname) == -1)
return -1;
if (optlen < 6) { /* 32 bit export length + 16 bit nr info */
debug ("newstyle negotiation: %s option length < 6", optname);
if (send_newstyle_option_reply (option, NBD_REP_ERR_INVALID)
== -1)
return -1;
continue;
}
{
uint32_t exportnamelen;
uint16_t nrinfos;
uint16_t info;
size_t i;
/* Validate the name length and number of INFO requests. */
memcpy (&exportnamelen, &data[0], 4);
exportnamelen = be32toh (exportnamelen);
if (exportnamelen > optlen-6 /* NB optlen >= 6, see above */) {
debug ("newstyle negotiation: %s: export name too long", optname);
if (send_newstyle_option_reply (option, NBD_REP_ERR_INVALID)
== -1)
return -1;
continue;
}
memcpy (&nrinfos, &data[exportnamelen+4], 2);
nrinfos = be16toh (nrinfos);
if (optlen != 4 + exportnamelen + 2 + 2*nrinfos) {
debug ("newstyle negotiation: %s: "
"number of information requests incorrect", optname);
if (send_newstyle_option_reply (option, NBD_REP_ERR_INVALID)
== -1)
return -1;
continue;
}
/* As with NBD_OPT_EXPORT_NAME we print the export name and
* save it in the connection. If an earlier
* NBD_OPT_SET_META_CONTEXT used an export name, it must match
* or else we drop the support for that context.
*/
if (check_export_name (option, &data[4], exportnamelen,
optlen - 6) == -1) {
if (send_newstyle_option_reply (option, NBD_REP_ERR_INVALID)
== -1)
return -1;
continue;
}
/* The spec is confusing, but it is required that we send back
* NBD_INFO_EXPORT, even if the client did not request it!
* qemu client in particular does not request this, but will
* fail if we don't send it. Note that if .open fails, but we
* succeed at .close, then we merely return an error to the
* client and let them try another NBD_OPT, rather than
* disconnecting.
*/
if (finish_newstyle_options (&exportsize,
&data[4], exportnamelen) == -1) {
if (conn->top_context) {
if (backend_finalize (conn->top_context) == -1)
return -1;
backend_close (conn->top_context);
conn->top_context = NULL;
}
if (send_newstyle_option_reply (option, NBD_REP_ERR_UNKNOWN) == -1)
return -1;
continue;
}
if (send_newstyle_option_reply_info_export (option,
NBD_REP_INFO,
NBD_INFO_EXPORT,
exportsize) == -1)
return -1;
/* For now we send NBD_INFO_NAME and NBD_INFO_DESCRIPTION if
* requested, and ignore all other info requests (including
* NBD_INFO_EXPORT if it was requested, because we replied
* already above).
*/
for (i = 0; i < nrinfos; ++i) {
memcpy (&info, &data[4 + exportnamelen + 2 + i*2], 2);
info = be16toh (info);
switch (info) {
case NBD_INFO_EXPORT: /* ignore - reply sent above */ break;
case NBD_INFO_NAME:
{
const char *name = &data[4];
size_t namelen = exportnamelen;
if (exportnamelen == 0) {
name = backend_default_export (top, read_only);
if (!name) {
debug ("newstyle negotiation: %s: "
"NBD_INFO_NAME: no name to send", optname);
break;
}
namelen = -1;
}
if (send_newstyle_option_reply_info_str (option,
NBD_REP_INFO,
NBD_INFO_NAME,
name, namelen) == -1)
return -1;
}
break;
case NBD_INFO_DESCRIPTION:
{
const char *desc = backend_export_description (conn->top_context);
if (!desc) {
debug ("newstyle negotiation: %s: "
"NBD_INFO_DESCRIPTION: no description to send",
optname);
break;
}
if (send_newstyle_option_reply_info_str (option,
NBD_REP_INFO,
NBD_INFO_DESCRIPTION,
desc, -1) == -1)
return -1;
}
break;
default:
debug ("newstyle negotiation: %s: "
"ignoring NBD_INFO_* request %u (%s)",
optname, (unsigned) info, name_of_nbd_info (info));
break;
}
}
}
/* Unlike NBD_OPT_EXPORT_NAME, NBD_OPT_GO sends back an ACK
* or ERROR packet. If this was NBD_OPT_LIST, call .close.
*/
if (send_newstyle_option_reply (option, NBD_REP_ACK) == -1)
return -1;
if (option == NBD_OPT_INFO) {
if (backend_finalize (conn->top_context) == -1)
return -1;
backend_close (conn->top_context);
conn->top_context = NULL;
}
break;
case NBD_OPT_STRUCTURED_REPLY:
if (optlen != 0) {
if (send_newstyle_option_reply (option, NBD_REP_ERR_INVALID)
== -1)
return -1;
if (conn_recv_full (data, optlen,
"read: %s: %m", name_of_nbd_opt (option)) == -1)
return -1;
continue;
}
debug ("newstyle negotiation: %s: client requested structured replies",
name_of_nbd_opt (option));
if (no_sr) {
/* Must fail with ERR_UNSUP for qemu 4.2 to remain happy;
* but failing with ERR_POLICY would have been nicer.
*/
if (send_newstyle_option_reply (option, NBD_REP_ERR_UNSUP) == -1)
return -1;
debug ("newstyle negotiation: %s: structured replies are disabled",
name_of_nbd_opt (option));
break;
}
if (send_newstyle_option_reply (option, NBD_REP_ACK) == -1)
return -1;
conn->structured_replies = true;
break;
case NBD_OPT_LIST_META_CONTEXT:
case NBD_OPT_SET_META_CONTEXT:
{
uint32_t opt_index;
uint32_t exportnamelen;
uint32_t nr_queries;
uint32_t querylen;
const char *what;
if (conn_recv_full (data, optlen, "read: %s: %m", optname) == -1)
return -1;
/* Note that we support base:allocation whether or not the plugin
* supports can_extents.
*/
if (!conn->structured_replies) {
if (send_newstyle_option_reply (option, NBD_REP_ERR_INVALID)
== -1)
return -1;
continue;
}
/* Minimum length of the option payload is:
* 32 bit export name length followed by empty export name
* + 32 bit number of queries followed by no queries
* = 8 bytes.
*/
what = "optlen < 8";
if (optlen < 8) {
opt_meta_invalid_option_len:
debug ("newstyle negotiation: %s: invalid option length: %s",
optname, what);
if (send_newstyle_option_reply (option, NBD_REP_ERR_INVALID)
== -1)
return -1;
continue;
}
memcpy (&exportnamelen, &data[0], 4);
exportnamelen = be32toh (exportnamelen);
what = "validating export name";
if (check_export_name (option, &data[4], exportnamelen,
optlen - 8) == -1)
goto opt_meta_invalid_option_len;
/* Remember the export name: the NBD spec says that if the client
* later uses NBD_OPT_GO on a different export, then the context
* returned here is not usable.
*/
if (option == NBD_OPT_SET_META_CONTEXT) {
conn->exportname_from_set_meta_context =
strndup (&data[4], exportnamelen);
if (conn->exportname_from_set_meta_context == NULL) {
nbdkit_error ("malloc: %m");
return -1;
}
}
opt_index = 4 + exportnamelen;
/* Read the number of queries. */
what = "reading number of queries";
if (opt_index+4 > optlen)
goto opt_meta_invalid_option_len;
memcpy (&nr_queries, &data[opt_index], 4);
nr_queries = be32toh (nr_queries);
opt_index += 4;
/* for LIST: nr_queries == 0 means return all meta contexts
* for SET: nr_queries == 0 means reset all contexts
*/
debug ("newstyle negotiation: %s: %s count: %d", optname,
option == NBD_OPT_LIST_META_CONTEXT ? "query" : "set",
nr_queries);
if (option == NBD_OPT_SET_META_CONTEXT)
conn->meta_context_base_allocation = false;
if (nr_queries == 0) {
if (option == NBD_OPT_LIST_META_CONTEXT) {
if (send_newstyle_option_reply_meta_context (option,
NBD_REP_META_CONTEXT,
0, "base:allocation")
== -1)
return -1;
}
if (send_newstyle_option_reply (option, NBD_REP_ACK) == -1)
return -1;
}
else {
/* Read and answer each query. */
while (nr_queries > 0) {
what = "reading query string length";
if (opt_index+4 > optlen)
goto opt_meta_invalid_option_len;
memcpy (&querylen, &data[opt_index], 4);
querylen = be32toh (querylen);
opt_index += 4;
what = "reading query string";
if (check_string (option, &data[opt_index], querylen,
optlen - opt_index, "meta context query") == -1)
goto opt_meta_invalid_option_len;
debug ("newstyle negotiation: %s: %s %.*s",
optname,
option == NBD_OPT_LIST_META_CONTEXT ? "query" : "set",
(int) querylen, &data[opt_index]);
/* For LIST, "base:" returns all supported contexts in the
* base namespace. We only support "base:allocation".
*/
if (option == NBD_OPT_LIST_META_CONTEXT &&
querylen == 5 &&
strncmp (&data[opt_index], "base:", 5) == 0) {
if (send_newstyle_option_reply_meta_context
(option, NBD_REP_META_CONTEXT,
0, "base:allocation") == -1)
return -1;
}
/* "base:allocation" requested by name. */
else if (querylen == 15 &&
strncmp (&data[opt_index], "base:allocation", 15) == 0) {
if (send_newstyle_option_reply_meta_context
(option, NBD_REP_META_CONTEXT,
option == NBD_OPT_SET_META_CONTEXT
? base_allocation_id : 0,
"base:allocation") == -1)
return -1;
if (option == NBD_OPT_SET_META_CONTEXT)
conn->meta_context_base_allocation = true;
}
/* Every other query must be ignored. */
opt_index += querylen;
nr_queries--;
}
if (send_newstyle_option_reply (option, NBD_REP_ACK) == -1)
return -1;
}
debug ("newstyle negotiation: %s: reply complete", optname);
}
break;
default:
/* Unknown option. */
if (send_newstyle_option_reply (option, NBD_REP_ERR_UNSUP) == -1)
return -1;
if (conn_recv_full (data, optlen,
"reading unknown option data: conn->recv: %m") == -1)
return -1;
}
/* Note, since it's not very clear from the protocol doc, that the
* client must send NBD_OPT_EXPORT_NAME or NBD_OPT_GO last, and
* that ends option negotiation.
*/
if (option == NBD_OPT_EXPORT_NAME || option == NBD_OPT_GO)
break;
}
if (nr_options == 0) {
nbdkit_error ("client spent too much time negotiating without selecting "
"an export");
return -1;
}
/* In --tls=require / FORCEDTLS mode, we must have upgraded to TLS
* by the time we finish option negotiation. If not, give up.
*/
if (tls == 2 && !conn->using_tls) {
nbdkit_error ("non-TLS client tried to connect in --tls=require mode");
return -1;
}
return 0;
}
| null | null | 206,670
|
200168996418018549739827057336110204071
| 536
|
server: reset meta context replies on starttls
Related to CVE-2021-3716, but not as severe. No compliant client will
send NBD_CMD_BLOCK_STATUS unless it first negotiates
NBD_OPT_SET_META_CONTEXT. If an attacker injects a premature
SET_META_CONTEXT, either the client will never notice (because it
never uses BLOCK_STATUS), or the client will overwrite the attacker's
attempt with the client's own SET_META_CONTEXT request after
encryption is enabled. So I don't class this as having the potential
to trigger denial-of-service due to any protocol mismatch between
compliant client and server (I don't care what happens with
non-compliant clients).
Fixes: 26455d45 (server: protocol: Implement Block Status "base:allocation".)
|
other
|
vim
|
777e7c21b7627be80961848ac560cb0a9978ff43
| 1
|
update_topline(void)
{
long line_count;
int halfheight;
int n;
linenr_T old_topline;
#ifdef FEAT_DIFF
int old_topfill;
#endif
#ifdef FEAT_FOLDING
linenr_T lnum;
#endif
int check_topline = FALSE;
int check_botline = FALSE;
long *so_ptr = curwin->w_p_so >= 0 ? &curwin->w_p_so : &p_so;
int save_so = *so_ptr;
// If there is no valid screen and when the window height is zero just use
// the cursor line.
if (!screen_valid(TRUE) || curwin->w_height == 0)
{
check_cursor_lnum();
curwin->w_topline = curwin->w_cursor.lnum;
curwin->w_botline = curwin->w_topline;
curwin->w_valid |= VALID_BOTLINE|VALID_BOTLINE_AP;
curwin->w_scbind_pos = 1;
return;
}
check_cursor_moved(curwin);
if (curwin->w_valid & VALID_TOPLINE)
return;
// When dragging with the mouse, don't scroll that quickly
if (mouse_dragging > 0)
*so_ptr = mouse_dragging - 1;
old_topline = curwin->w_topline;
#ifdef FEAT_DIFF
old_topfill = curwin->w_topfill;
#endif
/*
* If the buffer is empty, always set topline to 1.
*/
if (BUFEMPTY()) // special case - file is empty
{
if (curwin->w_topline != 1)
redraw_later(NOT_VALID);
curwin->w_topline = 1;
curwin->w_botline = 2;
curwin->w_valid |= VALID_BOTLINE|VALID_BOTLINE_AP;
curwin->w_scbind_pos = 1;
}
/*
* If the cursor is above or near the top of the window, scroll the window
* to show the line the cursor is in, with 'scrolloff' context.
*/
else
{
if (curwin->w_topline > 1)
{
// If the cursor is above topline, scrolling is always needed.
// If the cursor is far below topline and there is no folding,
// scrolling down is never needed.
if (curwin->w_cursor.lnum < curwin->w_topline)
check_topline = TRUE;
else if (check_top_offset())
check_topline = TRUE;
}
#ifdef FEAT_DIFF
// Check if there are more filler lines than allowed.
if (!check_topline && curwin->w_topfill > diff_check_fill(curwin,
curwin->w_topline))
check_topline = TRUE;
#endif
if (check_topline)
{
halfheight = curwin->w_height / 2 - 1;
if (halfheight < 2)
halfheight = 2;
#ifdef FEAT_FOLDING
if (hasAnyFolding(curwin))
{
// Count the number of logical lines between the cursor and
// topline + scrolloff (approximation of how much will be
// scrolled).
n = 0;
for (lnum = curwin->w_cursor.lnum;
lnum < curwin->w_topline + *so_ptr; ++lnum)
{
++n;
// stop at end of file or when we know we are far off
if (lnum >= curbuf->b_ml.ml_line_count || n >= halfheight)
break;
(void)hasFolding(lnum, NULL, &lnum);
}
}
else
#endif
n = curwin->w_topline + *so_ptr - curwin->w_cursor.lnum;
// If we weren't very close to begin with, we scroll to put the
// cursor in the middle of the window. Otherwise put the cursor
// near the top of the window.
if (n >= halfheight)
scroll_cursor_halfway(FALSE);
else
{
scroll_cursor_top(scrolljump_value(), FALSE);
check_botline = TRUE;
}
}
else
{
#ifdef FEAT_FOLDING
// Make sure topline is the first line of a fold.
(void)hasFolding(curwin->w_topline, &curwin->w_topline, NULL);
#endif
check_botline = TRUE;
}
}
/*
* If the cursor is below the bottom of the window, scroll the window
* to put the cursor on the window.
* When w_botline is invalid, recompute it first, to avoid a redraw later.
* If w_botline was approximated, we might need a redraw later in a few
* cases, but we don't want to spend (a lot of) time recomputing w_botline
* for every small change.
*/
if (check_botline)
{
if (!(curwin->w_valid & VALID_BOTLINE_AP))
validate_botline();
if (curwin->w_botline <= curbuf->b_ml.ml_line_count)
{
if (curwin->w_cursor.lnum < curwin->w_botline)
{
if (((long)curwin->w_cursor.lnum
>= (long)curwin->w_botline - *so_ptr
#ifdef FEAT_FOLDING
|| hasAnyFolding(curwin)
#endif
))
{
lineoff_T loff;
// Cursor is (a few lines) above botline, check if there are
// 'scrolloff' window lines below the cursor. If not, need to
// scroll.
n = curwin->w_empty_rows;
loff.lnum = curwin->w_cursor.lnum;
#ifdef FEAT_FOLDING
// In a fold go to its last line.
(void)hasFolding(loff.lnum, NULL, &loff.lnum);
#endif
#ifdef FEAT_DIFF
loff.fill = 0;
n += curwin->w_filler_rows;
#endif
loff.height = 0;
while (loff.lnum < curwin->w_botline
#ifdef FEAT_DIFF
&& (loff.lnum + 1 < curwin->w_botline || loff.fill == 0)
#endif
)
{
n += loff.height;
if (n >= *so_ptr)
break;
botline_forw(&loff);
}
if (n >= *so_ptr)
// sufficient context, no need to scroll
check_botline = FALSE;
}
else
// sufficient context, no need to scroll
check_botline = FALSE;
}
if (check_botline)
{
#ifdef FEAT_FOLDING
if (hasAnyFolding(curwin))
{
// Count the number of logical lines between the cursor and
// botline - scrolloff (approximation of how much will be
// scrolled).
line_count = 0;
for (lnum = curwin->w_cursor.lnum;
lnum >= curwin->w_botline - *so_ptr; --lnum)
{
++line_count;
// stop at end of file or when we know we are far off
if (lnum <= 0 || line_count > curwin->w_height + 1)
break;
(void)hasFolding(lnum, &lnum, NULL);
}
}
else
#endif
line_count = curwin->w_cursor.lnum - curwin->w_botline
+ 1 + *so_ptr;
if (line_count <= curwin->w_height + 1)
scroll_cursor_bot(scrolljump_value(), FALSE);
else
scroll_cursor_halfway(FALSE);
}
}
}
curwin->w_valid |= VALID_TOPLINE;
/*
* Need to redraw when topline changed.
*/
if (curwin->w_topline != old_topline
#ifdef FEAT_DIFF
|| curwin->w_topfill != old_topfill
#endif
)
{
dollar_vcol = -1;
if (curwin->w_skipcol != 0)
{
curwin->w_skipcol = 0;
redraw_later(NOT_VALID);
}
else
redraw_later(VALID);
// May need to set w_skipcol when cursor in w_topline.
if (curwin->w_cursor.lnum == curwin->w_topline)
validate_cursor();
}
*so_ptr = save_so;
}
| null | null | 206,676
|
21920694119130798358880555597268839959
| 242
|
patch 8.2.3564: invalid memory access when scrolling without valid screen
Problem: Invalid memory access when scrolling without a valid screen.
Solution: Do not set VALID_BOTLINE in w_valid.
|
other
|
vim
|
5921aeb5741fc6e84c870d68c7c35b93ad0c9f87
| 1
|
unix_expandpath(
garray_T *gap,
char_u *path,
int wildoff,
int flags, // EW_* flags
int didstar) // expanded "**" once already
{
char_u *buf;
char_u *path_end;
char_u *p, *s, *e;
int start_len = gap->ga_len;
char_u *pat;
regmatch_T regmatch;
int starts_with_dot;
int matches;
int len;
int starstar = FALSE;
static int stardepth = 0; // depth for "**" expansion
DIR *dirp;
struct dirent *dp;
// Expanding "**" may take a long time, check for CTRL-C.
if (stardepth > 0)
{
ui_breakcheck();
if (got_int)
return 0;
}
// make room for file name
buf = alloc(STRLEN(path) + BASENAMELEN + 5);
if (buf == NULL)
return 0;
/*
* Find the first part in the path name that contains a wildcard.
* When EW_ICASE is set every letter is considered to be a wildcard.
* Copy it into "buf", including the preceding characters.
*/
p = buf;
s = buf;
e = NULL;
path_end = path;
while (*path_end != NUL)
{
// May ignore a wildcard that has a backslash before it; it will
// be removed by rem_backslash() or file_pat_to_reg_pat() below.
if (path_end >= path + wildoff && rem_backslash(path_end))
*p++ = *path_end++;
else if (*path_end == '/')
{
if (e != NULL)
break;
s = p + 1;
}
else if (path_end >= path + wildoff
&& (vim_strchr((char_u *)"*?[{~$", *path_end) != NULL
|| (!p_fic && (flags & EW_ICASE)
&& isalpha(PTR2CHAR(path_end)))))
e = p;
if (has_mbyte)
{
len = (*mb_ptr2len)(path_end);
STRNCPY(p, path_end, len);
p += len;
path_end += len;
}
else
*p++ = *path_end++;
}
e = p;
*e = NUL;
// Now we have one wildcard component between "s" and "e".
// Remove backslashes between "wildoff" and the start of the wildcard
// component.
for (p = buf + wildoff; p < s; ++p)
if (rem_backslash(p))
{
STRMOVE(p, p + 1);
--e;
--s;
}
// Check for "**" between "s" and "e".
for (p = s; p < e; ++p)
if (p[0] == '*' && p[1] == '*')
starstar = TRUE;
// convert the file pattern to a regexp pattern
starts_with_dot = *s == '.';
pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
if (pat == NULL)
{
vim_free(buf);
return 0;
}
// compile the regexp into a program
if (flags & EW_ICASE)
regmatch.rm_ic = TRUE; // 'wildignorecase' set
else
regmatch.rm_ic = p_fic; // ignore case when 'fileignorecase' is set
if (flags & (EW_NOERROR | EW_NOTWILD))
++emsg_silent;
regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
if (flags & (EW_NOERROR | EW_NOTWILD))
--emsg_silent;
vim_free(pat);
if (regmatch.regprog == NULL && (flags & EW_NOTWILD) == 0)
{
vim_free(buf);
return 0;
}
// If "**" is by itself, this is the first time we encounter it and more
// is following then find matches without any directory.
if (!didstar && stardepth < 100 && starstar && e - s == 2
&& *path_end == '/')
{
STRCPY(s, path_end + 1);
++stardepth;
(void)unix_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
--stardepth;
}
// open the directory for scanning
*s = NUL;
dirp = opendir(*buf == NUL ? "." : (char *)buf);
// Find all matching entries
if (dirp != NULL)
{
for (;;)
{
dp = readdir(dirp);
if (dp == NULL)
break;
if ((dp->d_name[0] != '.' || starts_with_dot
|| ((flags & EW_DODOT)
&& dp->d_name[1] != NUL
&& (dp->d_name[1] != '.' || dp->d_name[2] != NUL)))
&& ((regmatch.regprog != NULL && vim_regexec(®match,
(char_u *)dp->d_name, (colnr_T)0))
|| ((flags & EW_NOTWILD)
&& fnamencmp(path + (s - buf), dp->d_name, e - s) == 0)))
{
STRCPY(s, dp->d_name);
len = STRLEN(buf);
if (starstar && stardepth < 100)
{
// For "**" in the pattern first go deeper in the tree to
// find matches.
STRCPY(buf + len, "/**");
STRCPY(buf + len + 3, path_end);
++stardepth;
(void)unix_expandpath(gap, buf, len + 1, flags, TRUE);
--stardepth;
}
STRCPY(buf + len, path_end);
if (mch_has_exp_wildcard(path_end)) // handle more wildcards
{
// need to expand another component of the path
// remove backslashes for the remaining components only
(void)unix_expandpath(gap, buf, len + 1, flags, FALSE);
}
else
{
stat_T sb;
// no more wildcards, check if there is a match
// remove backslashes for the remaining components only
if (*path_end != NUL)
backslash_halve(buf + len + 1);
// add existing file or symbolic link
if ((flags & EW_ALLLINKS) ? mch_lstat((char *)buf, &sb) >= 0
: mch_getperm(buf) >= 0)
{
#ifdef MACOS_CONVERT
size_t precomp_len = STRLEN(buf)+1;
char_u *precomp_buf =
mac_precompose_path(buf, precomp_len, &precomp_len);
if (precomp_buf)
{
mch_memmove(buf, precomp_buf, precomp_len);
vim_free(precomp_buf);
}
#endif
addfile(gap, buf, flags);
}
}
}
}
closedir(dirp);
}
vim_free(buf);
vim_regfree(regmatch.regprog);
matches = gap->ga_len - start_len;
if (matches > 0)
qsort(((char_u **)gap->ga_data) + start_len, matches,
sizeof(char_u *), pstrcmp);
return matches;
}
| null | null | 206,677
|
100021614777278550143078607475257899138
| 211
|
patch 8.2.4418: crash when using special multi-byte character
Problem: Crash when using special multi-byte character.
Solution: Don't use isalpha() for an arbitrary character.
|
other
|
linux
|
bb458c644a59dbba3a1fe59b27106c5e68e1c4bd
| 1
|
static struct file *path_openat(int dfd, struct filename *pathname,
struct nameidata *nd, const struct open_flags *op, int flags)
{
struct file *base = NULL;
struct file *file;
struct path path;
int opened = 0;
int error;
file = get_empty_filp();
if (IS_ERR(file))
return file;
file->f_flags = op->open_flag;
if (unlikely(file->f_flags & O_TMPFILE)) {
error = do_tmpfile(dfd, pathname, nd, flags, op, file, &opened);
goto out;
}
error = path_init(dfd, pathname->name, flags | LOOKUP_PARENT, nd, &base);
if (unlikely(error))
goto out;
current->total_link_count = 0;
error = link_path_walk(pathname->name, nd);
if (unlikely(error))
goto out;
error = do_last(nd, &path, file, op, &opened, pathname);
while (unlikely(error > 0)) { /* trailing symlink */
struct path link = path;
void *cookie;
if (!(nd->flags & LOOKUP_FOLLOW)) {
path_put_conditional(&path, nd);
path_put(&nd->path);
error = -ELOOP;
break;
}
error = may_follow_link(&link, nd);
if (unlikely(error))
break;
nd->flags |= LOOKUP_PARENT;
nd->flags &= ~(LOOKUP_OPEN|LOOKUP_CREATE|LOOKUP_EXCL);
error = follow_link(&link, nd, &cookie);
if (unlikely(error))
break;
error = do_last(nd, &path, file, op, &opened, pathname);
put_link(nd, &link, cookie);
}
out:
if (nd->root.mnt && !(nd->flags & LOOKUP_ROOT))
path_put(&nd->root);
if (base)
fput(base);
if (!(opened & FILE_OPENED)) {
BUG_ON(!error);
put_filp(file);
}
if (unlikely(error)) {
if (error == -EOPENSTALE) {
if (flags & LOOKUP_RCU)
error = -ECHILD;
else
error = -ESTALE;
}
file = ERR_PTR(error);
}
return file;
}
| null | null | 206,720
|
254660321291828395776330198697429452775
| 70
|
Safer ABI for O_TMPFILE
[suggested by Rasmus Villemoes] make O_DIRECTORY | O_RDWR part of O_TMPFILE;
that will fail on old kernels in a lot more cases than what I came up with.
And make sure O_CREAT doesn't get there...
Signed-off-by: Al Viro <[email protected]>
|
other
|
php-src
|
8f4a6d6e1b6c36259a5dc865d16f0dad76f2f2c9
| 1
|
ftp_genlist(ftpbuf_t *ftp, const char *cmd, const char *path TSRMLS_DC)
{
php_stream *tmpstream = NULL;
databuf_t *data = NULL;
char *ptr;
int ch, lastch;
int size, rcvd;
int lines;
char **ret = NULL;
char **entry;
char *text;
if ((tmpstream = php_stream_fopen_tmpfile()) == NULL) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to create temporary file. Check permissions in temporary files directory.");
return NULL;
}
if (!ftp_type(ftp, FTPTYPE_ASCII)) {
goto bail;
}
if ((data = ftp_getdata(ftp TSRMLS_CC)) == NULL) {
goto bail;
}
ftp->data = data;
if (!ftp_putcmd(ftp, cmd, path)) {
goto bail;
}
if (!ftp_getresp(ftp) || (ftp->resp != 150 && ftp->resp != 125 && ftp->resp != 226)) {
goto bail;
}
/* some servers don't open a ftp-data connection if the directory is empty */
if (ftp->resp == 226) {
ftp->data = data_close(ftp, data);
php_stream_close(tmpstream);
return ecalloc(1, sizeof(char*));
}
/* pull data buffer into tmpfile */
if ((data = data_accept(data, ftp TSRMLS_CC)) == NULL) {
goto bail;
}
size = 0;
lines = 0;
lastch = 0;
while ((rcvd = my_recv(ftp, data->fd, data->buf, FTP_BUFSIZE))) {
if (rcvd == -1) {
goto bail;
}
php_stream_write(tmpstream, data->buf, rcvd);
size += rcvd;
for (ptr = data->buf; rcvd; rcvd--, ptr++) {
if (*ptr == '\n' && lastch == '\r') {
lines++;
} else {
size++;
}
lastch = *ptr;
}
}
ftp->data = data_close(ftp, data);
php_stream_rewind(tmpstream);
ret = safe_emalloc((lines + 1), sizeof(char*), size * sizeof(char*));
entry = ret;
text = (char*) (ret + lines + 1);
*entry = text;
lastch = 0;
while ((ch = php_stream_getc(tmpstream)) != EOF) {
if (ch == '\n' && lastch == '\r') {
*(text - 1) = 0;
*++entry = text;
} else {
*text++ = ch;
}
lastch = ch;
}
*entry = NULL;
php_stream_close(tmpstream);
if (!ftp_getresp(ftp) || (ftp->resp != 226 && ftp->resp != 250)) {
efree(ret);
return NULL;
}
return ret;
bail:
ftp->data = data_close(ftp, data);
php_stream_close(tmpstream);
if (ret)
efree(ret);
return NULL;
}
| null | null | 206,736
|
302942434357671754880081705319332171860
| 102
|
Clean up this weird safe_emalloc() call
|
other
|
qcad
|
1eeffc5daf5a06cf6213ffc19e95923cdebb2eb8
| 1
|
bool DL_Dxf::handleLWPolylineData(DL_CreationInterface* /*creationInterface*/) {
// Allocate LWPolyline vertices (group code 90):
if (groupCode==90) {
maxVertices = toInt(groupValue);
if (maxVertices>0) {
if (vertices!=NULL) {
delete[] vertices;
}
vertices = new double[4*maxVertices];
for (int i=0; i<maxVertices; ++i) {
vertices[i*4] = 0.0;
vertices[i*4+1] = 0.0;
vertices[i*4+2] = 0.0;
vertices[i*4+3] = 0.0;
}
}
vertexIndex=-1;
return true;
}
// Process LWPolylines vertices (group codes 10/20/30/42):
else if (groupCode==10 || groupCode==20 ||
groupCode==30 || groupCode==42) {
if (vertexIndex<maxVertices-1 && groupCode==10) {
vertexIndex++;
}
if (groupCode<=30) {
if (vertexIndex>=0 && vertexIndex<maxVertices) {
vertices[4*vertexIndex + (groupCode/10-1)] = toReal(groupValue);
}
} else if (groupCode==42 && vertexIndex<maxVertices) {
vertices[4*vertexIndex + 3] = toReal(groupValue);
}
return true;
}
return false;
}
| null | null | 206,771
|
134344988205843061499740631870829315798
| 39
|
check vertexIndex which might be -1 for broken DXF
|
other
|
linux
|
ea8569194b43f0f01f0a84c689388542c7254a1f
| 1
|
int udf_expand_file_adinicb(struct inode *inode)
{
struct page *page;
char *kaddr;
struct udf_inode_info *iinfo = UDF_I(inode);
int err;
WARN_ON_ONCE(!inode_is_locked(inode));
if (!iinfo->i_lenAlloc) {
if (UDF_QUERY_FLAG(inode->i_sb, UDF_FLAG_USE_SHORT_AD))
iinfo->i_alloc_type = ICBTAG_FLAG_AD_SHORT;
else
iinfo->i_alloc_type = ICBTAG_FLAG_AD_LONG;
/* from now on we have normal address_space methods */
inode->i_data.a_ops = &udf_aops;
up_write(&iinfo->i_data_sem);
mark_inode_dirty(inode);
return 0;
}
/*
* Release i_data_sem so that we can lock a page - page lock ranks
* above i_data_sem. i_mutex still protects us against file changes.
*/
up_write(&iinfo->i_data_sem);
page = find_or_create_page(inode->i_mapping, 0, GFP_NOFS);
if (!page)
return -ENOMEM;
if (!PageUptodate(page)) {
kaddr = kmap_atomic(page);
memset(kaddr + iinfo->i_lenAlloc, 0x00,
PAGE_SIZE - iinfo->i_lenAlloc);
memcpy(kaddr, iinfo->i_data + iinfo->i_lenEAttr,
iinfo->i_lenAlloc);
flush_dcache_page(page);
SetPageUptodate(page);
kunmap_atomic(kaddr);
}
down_write(&iinfo->i_data_sem);
memset(iinfo->i_data + iinfo->i_lenEAttr, 0x00,
iinfo->i_lenAlloc);
iinfo->i_lenAlloc = 0;
if (UDF_QUERY_FLAG(inode->i_sb, UDF_FLAG_USE_SHORT_AD))
iinfo->i_alloc_type = ICBTAG_FLAG_AD_SHORT;
else
iinfo->i_alloc_type = ICBTAG_FLAG_AD_LONG;
/* from now on we have normal address_space methods */
inode->i_data.a_ops = &udf_aops;
set_page_dirty(page);
unlock_page(page);
up_write(&iinfo->i_data_sem);
err = filemap_fdatawrite(inode->i_mapping);
if (err) {
/* Restore everything back so that we don't lose data... */
lock_page(page);
down_write(&iinfo->i_data_sem);
kaddr = kmap_atomic(page);
memcpy(iinfo->i_data + iinfo->i_lenEAttr, kaddr, inode->i_size);
kunmap_atomic(kaddr);
unlock_page(page);
iinfo->i_alloc_type = ICBTAG_FLAG_AD_IN_ICB;
inode->i_data.a_ops = &udf_adinicb_aops;
up_write(&iinfo->i_data_sem);
}
put_page(page);
mark_inode_dirty(inode);
return err;
}
| null | null | 206,781
|
270315145277637123624366603400735225286
| 70
|
udf: Restore i_lenAlloc when inode expansion fails
When we fail to expand inode from inline format to a normal format, we
restore inode to contain the original inline formatting but we forgot to
set i_lenAlloc back. The mismatch between i_lenAlloc and i_size was then
causing further problems such as warnings and lost data down the line.
Reported-by: butt3rflyh4ck <[email protected]>
CC: [email protected]
Fixes: 7e49b6f2480c ("udf: Convert UDF to new truncate calling sequence")
Reviewed-by: Christoph Hellwig <[email protected]>
Signed-off-by: Jan Kara <[email protected]>
|
other
|
ImageMagick
|
c111ed9b035532c2c81ea569f2d22fded9517287
| 1
|
static MagickBooleanType SetGrayscaleImage(Image *image,
ExceptionInfo *exception)
{
CacheView
*image_view;
MagickBooleanType
status;
PixelInfo
*colormap;
register ssize_t
i;
ssize_t
*colormap_index,
j,
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->type != GrayscaleType)
(void) TransformImageColorspace(image,GRAYColorspace,exception);
if (image->storage_class == PseudoClass)
colormap_index=(ssize_t *) AcquireQuantumMemory(image->colors+1,
sizeof(*colormap_index));
else
colormap_index=(ssize_t *) AcquireQuantumMemory(MaxColormapSize+1,
sizeof(*colormap_index));
if (colormap_index == (ssize_t *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
if (image->storage_class != PseudoClass)
{
(void) memset(colormap_index,(-1),MaxColormapSize*
sizeof(*colormap_index));
if (AcquireImageColormap(image,MaxColormapSize,exception) == MagickFalse)
{
colormap_index=(ssize_t *) RelinquishMagickMemory(colormap_index);
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
image->colors=0;
status=MagickTrue;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
register size_t
intensity;
intensity=ScaleQuantumToMap(GetPixelRed(image,q));
if (colormap_index[intensity] < 0)
{
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_SetGrayscaleImage)
#endif
if (colormap_index[intensity] < 0)
{
colormap_index[intensity]=(ssize_t) image->colors;
image->colormap[image->colors].red=(double)
GetPixelRed(image,q);
image->colormap[image->colors].green=(double)
GetPixelGreen(image,q);
image->colormap[image->colors].blue=(double)
GetPixelBlue(image,q);
image->colors++;
}
}
SetPixelIndex(image,(Quantum) colormap_index[intensity],q);
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
}
for (i=0; i < (ssize_t) image->colors; i++)
image->colormap[i].alpha=(double) i;
qsort((void *) image->colormap,image->colors,sizeof(PixelInfo),
IntensityCompare);
colormap=(PixelInfo *) AcquireQuantumMemory(image->colors,sizeof(*colormap));
if (colormap == (PixelInfo *) NULL)
{
colormap_index=(ssize_t *) RelinquishMagickMemory(colormap_index);
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
j=0;
colormap[j]=image->colormap[0];
for (i=0; i < (ssize_t) image->colors; i++)
{
if (IsPixelInfoEquivalent(&colormap[j],&image->colormap[i]) == MagickFalse)
{
j++;
colormap[j]=image->colormap[i];
}
colormap_index[(ssize_t) image->colormap[i].alpha]=j;
}
image->colors=(size_t) (j+1);
image->colormap=(PixelInfo *) RelinquishMagickMemory(image->colormap);
image->colormap=colormap;
status=MagickTrue;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelIndex(image,(Quantum) colormap_index[ScaleQuantumToMap(
GetPixelIndex(image,q))],q);
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
colormap_index=(ssize_t *) RelinquishMagickMemory(colormap_index);
image->type=GrayscaleType;
if (SetImageMonochrome(image,exception) != MagickFalse)
image->type=BilevelType;
return(status);
}
| null | null | 206,815
|
234306727854259574245146352374101011950
| 161
|
https://github.com/ImageMagick/ImageMagick/issues/1540
|
other
|
linux
|
5934d9a0383619c14df91af8fd76261dc3de2f5f
| 1
|
static unsigned long get_ctl_id_hash(const struct snd_ctl_elem_id *id)
{
int i;
unsigned long h;
h = id->iface;
h = MULTIPLIER * h + id->device;
h = MULTIPLIER * h + id->subdevice;
for (i = 0; id->name[i] && i < SNDRV_CTL_ELEM_ID_NAME_MAXLEN; i++)
h = MULTIPLIER * h + id->name[i];
h = MULTIPLIER * h + id->index;
h &= LONG_MAX;
return h;
}
| null | null | 206,845
|
54061121856741822206519852015957604149
| 14
|
ALSA: control: Re-order bounds checking in get_ctl_id_hash()
These two checks are in the reverse order so it might read one element
beyond the end of the array. First check if the "i" is within bounds
before using it.
Fixes: 6ab55ec0a938 ("ALSA: control: Fix an out-of-bounds bug in get_ctl_id_hash()")
Signed-off-by: Dan Carpenter <[email protected]>
Link: https://lore.kernel.org/r/YwjgNh/gkG1hH7po@kili
Signed-off-by: Takashi Iwai <[email protected]>
|
other
|
jdk11u-dev
|
41825fa33d605f8501164f9296572e4378e8183b
| 1
|
void InstanceKlass::metaspace_pointers_do(MetaspaceClosure* it) {
Klass::metaspace_pointers_do(it);
if (log_is_enabled(Trace, cds)) {
ResourceMark rm;
log_trace(cds)("Iter(InstanceKlass): %p (%s)", this, external_name());
}
it->push(&_annotations);
it->push((Klass**)&_array_klasses);
it->push(&_constants);
it->push(&_inner_classes);
it->push(&_array_name);
#if INCLUDE_JVMTI
it->push(&_previous_versions);
#endif
it->push(&_methods);
it->push(&_default_methods);
it->push(&_local_interfaces);
it->push(&_transitive_interfaces);
it->push(&_method_ordering);
it->push(&_default_vtable_indices);
it->push(&_fields);
if (itable_length() > 0) {
itableOffsetEntry* ioe = (itableOffsetEntry*)start_of_itable();
int method_table_offset_in_words = ioe->offset()/wordSize;
int nof_interfaces = (method_table_offset_in_words - itable_offset_in_words())
/ itableOffsetEntry::size();
for (int i = 0; i < nof_interfaces; i ++, ioe ++) {
if (ioe->interface_klass() != NULL) {
it->push(ioe->interface_klass_addr());
itableMethodEntry* ime = ioe->first_method_entry(this);
int n = klassItable::method_count_for_interface(ioe->interface_klass());
for (int index = 0; index < n; index ++) {
it->push(ime[index].method_addr());
}
}
}
}
it->push(&_nest_members);
}
| null | null | 206,865
|
22807728774700435545631777459334663989
| 44
|
8270386: Better verification of scan methods
Reviewed-by: mbaesken
Backport-of: ac329cef45979bd0159ecd1347e36f7129bb2ce4
|
other
|
vim
|
6456fae9ba8e72c74b2c0c499eaf09974604ff30
| 1
|
regmatch(
char_u *scan, // Current node.
proftime_T *tm UNUSED, // timeout limit or NULL
int *timed_out UNUSED) // flag set on timeout or NULL
{
char_u *next; // Next node.
int op;
int c;
regitem_T *rp;
int no;
int status; // one of the RA_ values:
#ifdef FEAT_RELTIME
int tm_count = 0;
#endif
// Make "regstack" and "backpos" empty. They are allocated and freed in
// bt_regexec_both() to reduce malloc()/free() calls.
regstack.ga_len = 0;
backpos.ga_len = 0;
// Repeat until "regstack" is empty.
for (;;)
{
// Some patterns may take a long time to match, e.g., "\([a-z]\+\)\+Q".
// Allow interrupting them with CTRL-C.
fast_breakcheck();
#ifdef DEBUG
if (scan != NULL && regnarrate)
{
mch_errmsg((char *)regprop(scan));
mch_errmsg("(\n");
}
#endif
// Repeat for items that can be matched sequentially, without using the
// regstack.
for (;;)
{
if (got_int || scan == NULL)
{
status = RA_FAIL;
break;
}
#ifdef FEAT_RELTIME
// Check for timeout once in a 100 times to avoid overhead.
if (tm != NULL && ++tm_count == 100)
{
tm_count = 0;
if (profile_passed_limit(tm))
{
if (timed_out != NULL)
*timed_out = TRUE;
status = RA_FAIL;
break;
}
}
#endif
status = RA_CONT;
#ifdef DEBUG
if (regnarrate)
{
mch_errmsg((char *)regprop(scan));
mch_errmsg("...\n");
# ifdef FEAT_SYN_HL
if (re_extmatch_in != NULL)
{
int i;
mch_errmsg(_("External submatches:\n"));
for (i = 0; i < NSUBEXP; i++)
{
mch_errmsg(" \"");
if (re_extmatch_in->matches[i] != NULL)
mch_errmsg((char *)re_extmatch_in->matches[i]);
mch_errmsg("\"\n");
}
}
# endif
}
#endif
next = regnext(scan);
op = OP(scan);
// Check for character class with NL added.
if (!rex.reg_line_lbr && WITH_NL(op) && REG_MULTI
&& *rex.input == NUL && rex.lnum <= rex.reg_maxline)
{
reg_nextline();
}
else if (rex.reg_line_lbr && WITH_NL(op) && *rex.input == '\n')
{
ADVANCE_REGINPUT();
}
else
{
if (WITH_NL(op))
op -= ADD_NL;
if (has_mbyte)
c = (*mb_ptr2char)(rex.input);
else
c = *rex.input;
switch (op)
{
case BOL:
if (rex.input != rex.line)
status = RA_NOMATCH;
break;
case EOL:
if (c != NUL)
status = RA_NOMATCH;
break;
case RE_BOF:
// We're not at the beginning of the file when below the first
// line where we started, not at the start of the line or we
// didn't start at the first line of the buffer.
if (rex.lnum != 0 || rex.input != rex.line
|| (REG_MULTI && rex.reg_firstlnum > 1))
status = RA_NOMATCH;
break;
case RE_EOF:
if (rex.lnum != rex.reg_maxline || c != NUL)
status = RA_NOMATCH;
break;
case CURSOR:
// Check if the buffer is in a window and compare the
// rex.reg_win->w_cursor position to the match position.
if (rex.reg_win == NULL
|| (rex.lnum + rex.reg_firstlnum
!= rex.reg_win->w_cursor.lnum)
|| ((colnr_T)(rex.input - rex.line)
!= rex.reg_win->w_cursor.col))
status = RA_NOMATCH;
break;
case RE_MARK:
// Compare the mark position to the match position.
{
int mark = OPERAND(scan)[0];
int cmp = OPERAND(scan)[1];
pos_T *pos;
pos = getmark_buf(rex.reg_buf, mark, FALSE);
if (pos == NULL // mark doesn't exist
|| pos->lnum <= 0) // mark isn't set in reg_buf
{
status = RA_NOMATCH;
}
else
{
colnr_T pos_col = pos->lnum == rex.lnum + rex.reg_firstlnum
&& pos->col == MAXCOL
? (colnr_T)STRLEN(reg_getline(
pos->lnum - rex.reg_firstlnum))
: pos->col;
if ((pos->lnum == rex.lnum + rex.reg_firstlnum
? (pos_col == (colnr_T)(rex.input - rex.line)
? (cmp == '<' || cmp == '>')
: (pos_col < (colnr_T)(rex.input - rex.line)
? cmp != '>'
: cmp != '<'))
: (pos->lnum < rex.lnum + rex.reg_firstlnum
? cmp != '>'
: cmp != '<')))
status = RA_NOMATCH;
}
}
break;
case RE_VISUAL:
if (!reg_match_visual())
status = RA_NOMATCH;
break;
case RE_LNUM:
if (!REG_MULTI || !re_num_cmp((long_u)(rex.lnum + rex.reg_firstlnum),
scan))
status = RA_NOMATCH;
break;
case RE_COL:
if (!re_num_cmp((long_u)(rex.input - rex.line) + 1, scan))
status = RA_NOMATCH;
break;
case RE_VCOL:
if (!re_num_cmp((long_u)win_linetabsize(
rex.reg_win == NULL ? curwin : rex.reg_win,
rex.line, (colnr_T)(rex.input - rex.line)) + 1, scan))
status = RA_NOMATCH;
break;
case BOW: // \<word; rex.input points to w
if (c == NUL) // Can't match at end of line
status = RA_NOMATCH;
else if (has_mbyte)
{
int this_class;
// Get class of current and previous char (if it exists).
this_class = mb_get_class_buf(rex.input, rex.reg_buf);
if (this_class <= 1)
status = RA_NOMATCH; // not on a word at all
else if (reg_prev_class() == this_class)
status = RA_NOMATCH; // previous char is in same word
}
else
{
if (!vim_iswordc_buf(c, rex.reg_buf) || (rex.input > rex.line
&& vim_iswordc_buf(rex.input[-1], rex.reg_buf)))
status = RA_NOMATCH;
}
break;
case EOW: // word\>; rex.input points after d
if (rex.input == rex.line) // Can't match at start of line
status = RA_NOMATCH;
else if (has_mbyte)
{
int this_class, prev_class;
// Get class of current and previous char (if it exists).
this_class = mb_get_class_buf(rex.input, rex.reg_buf);
prev_class = reg_prev_class();
if (this_class == prev_class
|| prev_class == 0 || prev_class == 1)
status = RA_NOMATCH;
}
else
{
if (!vim_iswordc_buf(rex.input[-1], rex.reg_buf)
|| (rex.input[0] != NUL
&& vim_iswordc_buf(c, rex.reg_buf)))
status = RA_NOMATCH;
}
break; // Matched with EOW
case ANY:
// ANY does not match new lines.
if (c == NUL)
status = RA_NOMATCH;
else
ADVANCE_REGINPUT();
break;
case IDENT:
if (!vim_isIDc(c))
status = RA_NOMATCH;
else
ADVANCE_REGINPUT();
break;
case SIDENT:
if (VIM_ISDIGIT(*rex.input) || !vim_isIDc(c))
status = RA_NOMATCH;
else
ADVANCE_REGINPUT();
break;
case KWORD:
if (!vim_iswordp_buf(rex.input, rex.reg_buf))
status = RA_NOMATCH;
else
ADVANCE_REGINPUT();
break;
case SKWORD:
if (VIM_ISDIGIT(*rex.input)
|| !vim_iswordp_buf(rex.input, rex.reg_buf))
status = RA_NOMATCH;
else
ADVANCE_REGINPUT();
break;
case FNAME:
if (!vim_isfilec(c))
status = RA_NOMATCH;
else
ADVANCE_REGINPUT();
break;
case SFNAME:
if (VIM_ISDIGIT(*rex.input) || !vim_isfilec(c))
status = RA_NOMATCH;
else
ADVANCE_REGINPUT();
break;
case PRINT:
if (!vim_isprintc(PTR2CHAR(rex.input)))
status = RA_NOMATCH;
else
ADVANCE_REGINPUT();
break;
case SPRINT:
if (VIM_ISDIGIT(*rex.input) || !vim_isprintc(PTR2CHAR(rex.input)))
status = RA_NOMATCH;
else
ADVANCE_REGINPUT();
break;
case WHITE:
if (!VIM_ISWHITE(c))
status = RA_NOMATCH;
else
ADVANCE_REGINPUT();
break;
case NWHITE:
if (c == NUL || VIM_ISWHITE(c))
status = RA_NOMATCH;
else
ADVANCE_REGINPUT();
break;
case DIGIT:
if (!ri_digit(c))
status = RA_NOMATCH;
else
ADVANCE_REGINPUT();
break;
case NDIGIT:
if (c == NUL || ri_digit(c))
status = RA_NOMATCH;
else
ADVANCE_REGINPUT();
break;
case HEX:
if (!ri_hex(c))
status = RA_NOMATCH;
else
ADVANCE_REGINPUT();
break;
case NHEX:
if (c == NUL || ri_hex(c))
status = RA_NOMATCH;
else
ADVANCE_REGINPUT();
break;
case OCTAL:
if (!ri_octal(c))
status = RA_NOMATCH;
else
ADVANCE_REGINPUT();
break;
case NOCTAL:
if (c == NUL || ri_octal(c))
status = RA_NOMATCH;
else
ADVANCE_REGINPUT();
break;
case WORD:
if (!ri_word(c))
status = RA_NOMATCH;
else
ADVANCE_REGINPUT();
break;
case NWORD:
if (c == NUL || ri_word(c))
status = RA_NOMATCH;
else
ADVANCE_REGINPUT();
break;
case HEAD:
if (!ri_head(c))
status = RA_NOMATCH;
else
ADVANCE_REGINPUT();
break;
case NHEAD:
if (c == NUL || ri_head(c))
status = RA_NOMATCH;
else
ADVANCE_REGINPUT();
break;
case ALPHA:
if (!ri_alpha(c))
status = RA_NOMATCH;
else
ADVANCE_REGINPUT();
break;
case NALPHA:
if (c == NUL || ri_alpha(c))
status = RA_NOMATCH;
else
ADVANCE_REGINPUT();
break;
case LOWER:
if (!ri_lower(c))
status = RA_NOMATCH;
else
ADVANCE_REGINPUT();
break;
case NLOWER:
if (c == NUL || ri_lower(c))
status = RA_NOMATCH;
else
ADVANCE_REGINPUT();
break;
case UPPER:
if (!ri_upper(c))
status = RA_NOMATCH;
else
ADVANCE_REGINPUT();
break;
case NUPPER:
if (c == NUL || ri_upper(c))
status = RA_NOMATCH;
else
ADVANCE_REGINPUT();
break;
case EXACTLY:
{
int len;
char_u *opnd;
opnd = OPERAND(scan);
// Inline the first byte, for speed.
if (*opnd != *rex.input
&& (!rex.reg_ic
|| (!enc_utf8
&& MB_TOLOWER(*opnd) != MB_TOLOWER(*rex.input))))
status = RA_NOMATCH;
else if (*opnd == NUL)
{
// match empty string always works; happens when "~" is
// empty.
}
else
{
if (opnd[1] == NUL && !(enc_utf8 && rex.reg_ic))
{
len = 1; // matched a single byte above
}
else
{
// Need to match first byte again for multi-byte.
len = (int)STRLEN(opnd);
if (cstrncmp(opnd, rex.input, &len) != 0)
status = RA_NOMATCH;
}
// Check for following composing character, unless %C
// follows (skips over all composing chars).
if (status != RA_NOMATCH
&& enc_utf8
&& UTF_COMPOSINGLIKE(rex.input, rex.input + len)
&& !rex.reg_icombine
&& OP(next) != RE_COMPOSING)
{
// raaron: This code makes a composing character get
// ignored, which is the correct behavior (sometimes)
// for voweled Hebrew texts.
status = RA_NOMATCH;
}
if (status != RA_NOMATCH)
rex.input += len;
}
}
break;
case ANYOF:
case ANYBUT:
if (c == NUL)
status = RA_NOMATCH;
else if ((cstrchr(OPERAND(scan), c) == NULL) == (op == ANYOF))
status = RA_NOMATCH;
else
ADVANCE_REGINPUT();
break;
case MULTIBYTECODE:
if (has_mbyte)
{
int i, len;
char_u *opnd;
int opndc = 0, inpc;
opnd = OPERAND(scan);
// Safety check (just in case 'encoding' was changed since
// compiling the program).
if ((len = (*mb_ptr2len)(opnd)) < 2)
{
status = RA_NOMATCH;
break;
}
if (enc_utf8)
opndc = utf_ptr2char(opnd);
if (enc_utf8 && utf_iscomposing(opndc))
{
// When only a composing char is given match at any
// position where that composing char appears.
status = RA_NOMATCH;
for (i = 0; rex.input[i] != NUL;
i += utf_ptr2len(rex.input + i))
{
inpc = utf_ptr2char(rex.input + i);
if (!utf_iscomposing(inpc))
{
if (i > 0)
break;
}
else if (opndc == inpc)
{
// Include all following composing chars.
len = i + utfc_ptr2len(rex.input + i);
status = RA_MATCH;
break;
}
}
}
else
for (i = 0; i < len; ++i)
if (opnd[i] != rex.input[i])
{
status = RA_NOMATCH;
break;
}
rex.input += len;
}
else
status = RA_NOMATCH;
break;
case RE_COMPOSING:
if (enc_utf8)
{
// Skip composing characters.
while (utf_iscomposing(utf_ptr2char(rex.input)))
MB_CPTR_ADV(rex.input);
}
break;
case NOTHING:
break;
case BACK:
{
int i;
backpos_T *bp;
// When we run into BACK we need to check if we don't keep
// looping without matching any input. The second and later
// times a BACK is encountered it fails if the input is still
// at the same position as the previous time.
// The positions are stored in "backpos" and found by the
// current value of "scan", the position in the RE program.
bp = (backpos_T *)backpos.ga_data;
for (i = 0; i < backpos.ga_len; ++i)
if (bp[i].bp_scan == scan)
break;
if (i == backpos.ga_len)
{
// First time at this BACK, make room to store the pos.
if (ga_grow(&backpos, 1) == FAIL)
status = RA_FAIL;
else
{
// get "ga_data" again, it may have changed
bp = (backpos_T *)backpos.ga_data;
bp[i].bp_scan = scan;
++backpos.ga_len;
}
}
else if (reg_save_equal(&bp[i].bp_pos))
// Still at same position as last time, fail.
status = RA_NOMATCH;
if (status != RA_FAIL && status != RA_NOMATCH)
reg_save(&bp[i].bp_pos, &backpos);
}
break;
case MOPEN + 0: // Match start: \zs
case MOPEN + 1: // \(
case MOPEN + 2:
case MOPEN + 3:
case MOPEN + 4:
case MOPEN + 5:
case MOPEN + 6:
case MOPEN + 7:
case MOPEN + 8:
case MOPEN + 9:
{
no = op - MOPEN;
cleanup_subexpr();
rp = regstack_push(RS_MOPEN, scan);
if (rp == NULL)
status = RA_FAIL;
else
{
rp->rs_no = no;
save_se(&rp->rs_un.sesave, &rex.reg_startpos[no],
&rex.reg_startp[no]);
// We simply continue and handle the result when done.
}
}
break;
case NOPEN: // \%(
case NCLOSE: // \) after \%(
if (regstack_push(RS_NOPEN, scan) == NULL)
status = RA_FAIL;
// We simply continue and handle the result when done.
break;
#ifdef FEAT_SYN_HL
case ZOPEN + 1:
case ZOPEN + 2:
case ZOPEN + 3:
case ZOPEN + 4:
case ZOPEN + 5:
case ZOPEN + 6:
case ZOPEN + 7:
case ZOPEN + 8:
case ZOPEN + 9:
{
no = op - ZOPEN;
cleanup_zsubexpr();
rp = regstack_push(RS_ZOPEN, scan);
if (rp == NULL)
status = RA_FAIL;
else
{
rp->rs_no = no;
save_se(&rp->rs_un.sesave, ®_startzpos[no],
®_startzp[no]);
// We simply continue and handle the result when done.
}
}
break;
#endif
case MCLOSE + 0: // Match end: \ze
case MCLOSE + 1: // \)
case MCLOSE + 2:
case MCLOSE + 3:
case MCLOSE + 4:
case MCLOSE + 5:
case MCLOSE + 6:
case MCLOSE + 7:
case MCLOSE + 8:
case MCLOSE + 9:
{
no = op - MCLOSE;
cleanup_subexpr();
rp = regstack_push(RS_MCLOSE, scan);
if (rp == NULL)
status = RA_FAIL;
else
{
rp->rs_no = no;
save_se(&rp->rs_un.sesave, &rex.reg_endpos[no],
&rex.reg_endp[no]);
// We simply continue and handle the result when done.
}
}
break;
#ifdef FEAT_SYN_HL
case ZCLOSE + 1: // \) after \z(
case ZCLOSE + 2:
case ZCLOSE + 3:
case ZCLOSE + 4:
case ZCLOSE + 5:
case ZCLOSE + 6:
case ZCLOSE + 7:
case ZCLOSE + 8:
case ZCLOSE + 9:
{
no = op - ZCLOSE;
cleanup_zsubexpr();
rp = regstack_push(RS_ZCLOSE, scan);
if (rp == NULL)
status = RA_FAIL;
else
{
rp->rs_no = no;
save_se(&rp->rs_un.sesave, ®_endzpos[no],
®_endzp[no]);
// We simply continue and handle the result when done.
}
}
break;
#endif
case BACKREF + 1:
case BACKREF + 2:
case BACKREF + 3:
case BACKREF + 4:
case BACKREF + 5:
case BACKREF + 6:
case BACKREF + 7:
case BACKREF + 8:
case BACKREF + 9:
{
int len;
no = op - BACKREF;
cleanup_subexpr();
if (!REG_MULTI) // Single-line regexp
{
if (rex.reg_startp[no] == NULL || rex.reg_endp[no] == NULL)
{
// Backref was not set: Match an empty string.
len = 0;
}
else
{
// Compare current input with back-ref in the same
// line.
len = (int)(rex.reg_endp[no] - rex.reg_startp[no]);
if (cstrncmp(rex.reg_startp[no], rex.input, &len) != 0)
status = RA_NOMATCH;
}
}
else // Multi-line regexp
{
if (rex.reg_startpos[no].lnum < 0
|| rex.reg_endpos[no].lnum < 0)
{
// Backref was not set: Match an empty string.
len = 0;
}
else
{
if (rex.reg_startpos[no].lnum == rex.lnum
&& rex.reg_endpos[no].lnum == rex.lnum)
{
// Compare back-ref within the current line.
len = rex.reg_endpos[no].col
- rex.reg_startpos[no].col;
if (cstrncmp(rex.line + rex.reg_startpos[no].col,
rex.input, &len) != 0)
status = RA_NOMATCH;
}
else
{
// Messy situation: Need to compare between two
// lines.
int r = match_with_backref(
rex.reg_startpos[no].lnum,
rex.reg_startpos[no].col,
rex.reg_endpos[no].lnum,
rex.reg_endpos[no].col,
&len);
if (r != RA_MATCH)
status = r;
}
}
}
// Matched the backref, skip over it.
rex.input += len;
}
break;
#ifdef FEAT_SYN_HL
case ZREF + 1:
case ZREF + 2:
case ZREF + 3:
case ZREF + 4:
case ZREF + 5:
case ZREF + 6:
case ZREF + 7:
case ZREF + 8:
case ZREF + 9:
{
int len;
cleanup_zsubexpr();
no = op - ZREF;
if (re_extmatch_in != NULL
&& re_extmatch_in->matches[no] != NULL)
{
len = (int)STRLEN(re_extmatch_in->matches[no]);
if (cstrncmp(re_extmatch_in->matches[no],
rex.input, &len) != 0)
status = RA_NOMATCH;
else
rex.input += len;
}
else
{
// Backref was not set: Match an empty string.
}
}
break;
#endif
case BRANCH:
{
if (OP(next) != BRANCH) // No choice.
next = OPERAND(scan); // Avoid recursion.
else
{
rp = regstack_push(RS_BRANCH, scan);
if (rp == NULL)
status = RA_FAIL;
else
status = RA_BREAK; // rest is below
}
}
break;
case BRACE_LIMITS:
{
if (OP(next) == BRACE_SIMPLE)
{
bl_minval = OPERAND_MIN(scan);
bl_maxval = OPERAND_MAX(scan);
}
else if (OP(next) >= BRACE_COMPLEX
&& OP(next) < BRACE_COMPLEX + 10)
{
no = OP(next) - BRACE_COMPLEX;
brace_min[no] = OPERAND_MIN(scan);
brace_max[no] = OPERAND_MAX(scan);
brace_count[no] = 0;
}
else
{
internal_error("BRACE_LIMITS");
status = RA_FAIL;
}
}
break;
case BRACE_COMPLEX + 0:
case BRACE_COMPLEX + 1:
case BRACE_COMPLEX + 2:
case BRACE_COMPLEX + 3:
case BRACE_COMPLEX + 4:
case BRACE_COMPLEX + 5:
case BRACE_COMPLEX + 6:
case BRACE_COMPLEX + 7:
case BRACE_COMPLEX + 8:
case BRACE_COMPLEX + 9:
{
no = op - BRACE_COMPLEX;
++brace_count[no];
// If not matched enough times yet, try one more
if (brace_count[no] <= (brace_min[no] <= brace_max[no]
? brace_min[no] : brace_max[no]))
{
rp = regstack_push(RS_BRCPLX_MORE, scan);
if (rp == NULL)
status = RA_FAIL;
else
{
rp->rs_no = no;
reg_save(&rp->rs_un.regsave, &backpos);
next = OPERAND(scan);
// We continue and handle the result when done.
}
break;
}
// If matched enough times, may try matching some more
if (brace_min[no] <= brace_max[no])
{
// Range is the normal way around, use longest match
if (brace_count[no] <= brace_max[no])
{
rp = regstack_push(RS_BRCPLX_LONG, scan);
if (rp == NULL)
status = RA_FAIL;
else
{
rp->rs_no = no;
reg_save(&rp->rs_un.regsave, &backpos);
next = OPERAND(scan);
// We continue and handle the result when done.
}
}
}
else
{
// Range is backwards, use shortest match first
if (brace_count[no] <= brace_min[no])
{
rp = regstack_push(RS_BRCPLX_SHORT, scan);
if (rp == NULL)
status = RA_FAIL;
else
{
reg_save(&rp->rs_un.regsave, &backpos);
// We continue and handle the result when done.
}
}
}
}
break;
case BRACE_SIMPLE:
case STAR:
case PLUS:
{
regstar_T rst;
// Lookahead to avoid useless match attempts when we know
// what character comes next.
if (OP(next) == EXACTLY)
{
rst.nextb = *OPERAND(next);
if (rex.reg_ic)
{
if (MB_ISUPPER(rst.nextb))
rst.nextb_ic = MB_TOLOWER(rst.nextb);
else
rst.nextb_ic = MB_TOUPPER(rst.nextb);
}
else
rst.nextb_ic = rst.nextb;
}
else
{
rst.nextb = NUL;
rst.nextb_ic = NUL;
}
if (op != BRACE_SIMPLE)
{
rst.minval = (op == STAR) ? 0 : 1;
rst.maxval = MAX_LIMIT;
}
else
{
rst.minval = bl_minval;
rst.maxval = bl_maxval;
}
// When maxval > minval, try matching as much as possible, up
// to maxval. When maxval < minval, try matching at least the
// minimal number (since the range is backwards, that's also
// maxval!).
rst.count = regrepeat(OPERAND(scan), rst.maxval);
if (got_int)
{
status = RA_FAIL;
break;
}
if (rst.minval <= rst.maxval
? rst.count >= rst.minval : rst.count >= rst.maxval)
{
// It could match. Prepare for trying to match what
// follows. The code is below. Parameters are stored in
// a regstar_T on the regstack.
if ((long)((unsigned)regstack.ga_len >> 10) >= p_mmp)
{
emsg(_(e_pattern_uses_more_memory_than_maxmempattern));
status = RA_FAIL;
}
else if (ga_grow(®stack, sizeof(regstar_T)) == FAIL)
status = RA_FAIL;
else
{
regstack.ga_len += sizeof(regstar_T);
rp = regstack_push(rst.minval <= rst.maxval
? RS_STAR_LONG : RS_STAR_SHORT, scan);
if (rp == NULL)
status = RA_FAIL;
else
{
*(((regstar_T *)rp) - 1) = rst;
status = RA_BREAK; // skip the restore bits
}
}
}
else
status = RA_NOMATCH;
}
break;
case NOMATCH:
case MATCH:
case SUBPAT:
rp = regstack_push(RS_NOMATCH, scan);
if (rp == NULL)
status = RA_FAIL;
else
{
rp->rs_no = op;
reg_save(&rp->rs_un.regsave, &backpos);
next = OPERAND(scan);
// We continue and handle the result when done.
}
break;
case BEHIND:
case NOBEHIND:
// Need a bit of room to store extra positions.
if ((long)((unsigned)regstack.ga_len >> 10) >= p_mmp)
{
emsg(_(e_pattern_uses_more_memory_than_maxmempattern));
status = RA_FAIL;
}
else if (ga_grow(®stack, sizeof(regbehind_T)) == FAIL)
status = RA_FAIL;
else
{
regstack.ga_len += sizeof(regbehind_T);
rp = regstack_push(RS_BEHIND1, scan);
if (rp == NULL)
status = RA_FAIL;
else
{
// Need to save the subexpr to be able to restore them
// when there is a match but we don't use it.
save_subexpr(((regbehind_T *)rp) - 1);
rp->rs_no = op;
reg_save(&rp->rs_un.regsave, &backpos);
// First try if what follows matches. If it does then we
// check the behind match by looping.
}
}
break;
case BHPOS:
if (REG_MULTI)
{
if (behind_pos.rs_u.pos.col != (colnr_T)(rex.input - rex.line)
|| behind_pos.rs_u.pos.lnum != rex.lnum)
status = RA_NOMATCH;
}
else if (behind_pos.rs_u.ptr != rex.input)
status = RA_NOMATCH;
break;
case NEWL:
if ((c != NUL || !REG_MULTI || rex.lnum > rex.reg_maxline
|| rex.reg_line_lbr)
&& (c != '\n' || !rex.reg_line_lbr))
status = RA_NOMATCH;
else if (rex.reg_line_lbr)
ADVANCE_REGINPUT();
else
reg_nextline();
break;
case END:
status = RA_MATCH; // Success!
break;
default:
iemsg(_(e_corrupted_regexp_program));
#ifdef DEBUG
printf("Illegal op code %d\n", op);
#endif
status = RA_FAIL;
break;
}
}
// If we can't continue sequentially, break the inner loop.
if (status != RA_CONT)
break;
// Continue in inner loop, advance to next item.
scan = next;
} // end of inner loop
// If there is something on the regstack execute the code for the state.
// If the state is popped then loop and use the older state.
while (regstack.ga_len > 0 && status != RA_FAIL)
{
rp = (regitem_T *)((char *)regstack.ga_data + regstack.ga_len) - 1;
switch (rp->rs_state)
{
case RS_NOPEN:
// Result is passed on as-is, simply pop the state.
regstack_pop(&scan);
break;
case RS_MOPEN:
// Pop the state. Restore pointers when there is no match.
if (status == RA_NOMATCH)
restore_se(&rp->rs_un.sesave, &rex.reg_startpos[rp->rs_no],
&rex.reg_startp[rp->rs_no]);
regstack_pop(&scan);
break;
#ifdef FEAT_SYN_HL
case RS_ZOPEN:
// Pop the state. Restore pointers when there is no match.
if (status == RA_NOMATCH)
restore_se(&rp->rs_un.sesave, ®_startzpos[rp->rs_no],
®_startzp[rp->rs_no]);
regstack_pop(&scan);
break;
#endif
case RS_MCLOSE:
// Pop the state. Restore pointers when there is no match.
if (status == RA_NOMATCH)
restore_se(&rp->rs_un.sesave, &rex.reg_endpos[rp->rs_no],
&rex.reg_endp[rp->rs_no]);
regstack_pop(&scan);
break;
#ifdef FEAT_SYN_HL
case RS_ZCLOSE:
// Pop the state. Restore pointers when there is no match.
if (status == RA_NOMATCH)
restore_se(&rp->rs_un.sesave, ®_endzpos[rp->rs_no],
®_endzp[rp->rs_no]);
regstack_pop(&scan);
break;
#endif
case RS_BRANCH:
if (status == RA_MATCH)
// this branch matched, use it
regstack_pop(&scan);
else
{
if (status != RA_BREAK)
{
// After a non-matching branch: try next one.
reg_restore(&rp->rs_un.regsave, &backpos);
scan = rp->rs_scan;
}
if (scan == NULL || OP(scan) != BRANCH)
{
// no more branches, didn't find a match
status = RA_NOMATCH;
regstack_pop(&scan);
}
else
{
// Prepare to try a branch.
rp->rs_scan = regnext(scan);
reg_save(&rp->rs_un.regsave, &backpos);
scan = OPERAND(scan);
}
}
break;
case RS_BRCPLX_MORE:
// Pop the state. Restore pointers when there is no match.
if (status == RA_NOMATCH)
{
reg_restore(&rp->rs_un.regsave, &backpos);
--brace_count[rp->rs_no]; // decrement match count
}
regstack_pop(&scan);
break;
case RS_BRCPLX_LONG:
// Pop the state. Restore pointers when there is no match.
if (status == RA_NOMATCH)
{
// There was no match, but we did find enough matches.
reg_restore(&rp->rs_un.regsave, &backpos);
--brace_count[rp->rs_no];
// continue with the items after "\{}"
status = RA_CONT;
}
regstack_pop(&scan);
if (status == RA_CONT)
scan = regnext(scan);
break;
case RS_BRCPLX_SHORT:
// Pop the state. Restore pointers when there is no match.
if (status == RA_NOMATCH)
// There was no match, try to match one more item.
reg_restore(&rp->rs_un.regsave, &backpos);
regstack_pop(&scan);
if (status == RA_NOMATCH)
{
scan = OPERAND(scan);
status = RA_CONT;
}
break;
case RS_NOMATCH:
// Pop the state. If the operand matches for NOMATCH or
// doesn't match for MATCH/SUBPAT, we fail. Otherwise backup,
// except for SUBPAT, and continue with the next item.
if (status == (rp->rs_no == NOMATCH ? RA_MATCH : RA_NOMATCH))
status = RA_NOMATCH;
else
{
status = RA_CONT;
if (rp->rs_no != SUBPAT) // zero-width
reg_restore(&rp->rs_un.regsave, &backpos);
}
regstack_pop(&scan);
if (status == RA_CONT)
scan = regnext(scan);
break;
case RS_BEHIND1:
if (status == RA_NOMATCH)
{
regstack_pop(&scan);
regstack.ga_len -= sizeof(regbehind_T);
}
else
{
// The stuff after BEHIND/NOBEHIND matches. Now try if
// the behind part does (not) match before the current
// position in the input. This must be done at every
// position in the input and checking if the match ends at
// the current position.
// save the position after the found match for next
reg_save(&(((regbehind_T *)rp) - 1)->save_after, &backpos);
// Start looking for a match with operand at the current
// position. Go back one character until we find the
// result, hitting the start of the line or the previous
// line (for multi-line matching).
// Set behind_pos to where the match should end, BHPOS
// will match it. Save the current value.
(((regbehind_T *)rp) - 1)->save_behind = behind_pos;
behind_pos = rp->rs_un.regsave;
rp->rs_state = RS_BEHIND2;
reg_restore(&rp->rs_un.regsave, &backpos);
scan = OPERAND(rp->rs_scan) + 4;
}
break;
case RS_BEHIND2:
// Looping for BEHIND / NOBEHIND match.
if (status == RA_MATCH && reg_save_equal(&behind_pos))
{
// found a match that ends where "next" started
behind_pos = (((regbehind_T *)rp) - 1)->save_behind;
if (rp->rs_no == BEHIND)
reg_restore(&(((regbehind_T *)rp) - 1)->save_after,
&backpos);
else
{
// But we didn't want a match. Need to restore the
// subexpr, because what follows matched, so they have
// been set.
status = RA_NOMATCH;
restore_subexpr(((regbehind_T *)rp) - 1);
}
regstack_pop(&scan);
regstack.ga_len -= sizeof(regbehind_T);
}
else
{
long limit;
// No match or a match that doesn't end where we want it: Go
// back one character. May go to previous line once.
no = OK;
limit = OPERAND_MIN(rp->rs_scan);
if (REG_MULTI)
{
if (limit > 0
&& ((rp->rs_un.regsave.rs_u.pos.lnum
< behind_pos.rs_u.pos.lnum
? (colnr_T)STRLEN(rex.line)
: behind_pos.rs_u.pos.col)
- rp->rs_un.regsave.rs_u.pos.col >= limit))
no = FAIL;
else if (rp->rs_un.regsave.rs_u.pos.col == 0)
{
if (rp->rs_un.regsave.rs_u.pos.lnum
< behind_pos.rs_u.pos.lnum
|| reg_getline(
--rp->rs_un.regsave.rs_u.pos.lnum)
== NULL)
no = FAIL;
else
{
reg_restore(&rp->rs_un.regsave, &backpos);
rp->rs_un.regsave.rs_u.pos.col =
(colnr_T)STRLEN(rex.line);
}
}
else
{
if (has_mbyte)
{
char_u *line =
reg_getline(rp->rs_un.regsave.rs_u.pos.lnum);
rp->rs_un.regsave.rs_u.pos.col -=
(*mb_head_off)(line, line
+ rp->rs_un.regsave.rs_u.pos.col - 1) + 1;
}
else
--rp->rs_un.regsave.rs_u.pos.col;
}
}
else
{
if (rp->rs_un.regsave.rs_u.ptr == rex.line)
no = FAIL;
else
{
MB_PTR_BACK(rex.line, rp->rs_un.regsave.rs_u.ptr);
if (limit > 0 && (long)(behind_pos.rs_u.ptr
- rp->rs_un.regsave.rs_u.ptr) > limit)
no = FAIL;
}
}
if (no == OK)
{
// Advanced, prepare for finding match again.
reg_restore(&rp->rs_un.regsave, &backpos);
scan = OPERAND(rp->rs_scan) + 4;
if (status == RA_MATCH)
{
// We did match, so subexpr may have been changed,
// need to restore them for the next try.
status = RA_NOMATCH;
restore_subexpr(((regbehind_T *)rp) - 1);
}
}
else
{
// Can't advance. For NOBEHIND that's a match.
behind_pos = (((regbehind_T *)rp) - 1)->save_behind;
if (rp->rs_no == NOBEHIND)
{
reg_restore(&(((regbehind_T *)rp) - 1)->save_after,
&backpos);
status = RA_MATCH;
}
else
{
// We do want a proper match. Need to restore the
// subexpr if we had a match, because they may have
// been set.
if (status == RA_MATCH)
{
status = RA_NOMATCH;
restore_subexpr(((regbehind_T *)rp) - 1);
}
}
regstack_pop(&scan);
regstack.ga_len -= sizeof(regbehind_T);
}
}
break;
case RS_STAR_LONG:
case RS_STAR_SHORT:
{
regstar_T *rst = ((regstar_T *)rp) - 1;
if (status == RA_MATCH)
{
regstack_pop(&scan);
regstack.ga_len -= sizeof(regstar_T);
break;
}
// Tried once already, restore input pointers.
if (status != RA_BREAK)
reg_restore(&rp->rs_un.regsave, &backpos);
// Repeat until we found a position where it could match.
for (;;)
{
if (status != RA_BREAK)
{
// Tried first position already, advance.
if (rp->rs_state == RS_STAR_LONG)
{
// Trying for longest match, but couldn't or
// didn't match -- back up one char.
if (--rst->count < rst->minval)
break;
if (rex.input == rex.line)
{
// backup to last char of previous line
--rex.lnum;
rex.line = reg_getline(rex.lnum);
// Just in case regrepeat() didn't count
// right.
if (rex.line == NULL)
break;
rex.input = rex.line + STRLEN(rex.line);
fast_breakcheck();
}
else
MB_PTR_BACK(rex.line, rex.input);
}
else
{
// Range is backwards, use shortest match first.
// Careful: maxval and minval are exchanged!
// Couldn't or didn't match: try advancing one
// char.
if (rst->count == rst->minval
|| regrepeat(OPERAND(rp->rs_scan), 1L) == 0)
break;
++rst->count;
}
if (got_int)
break;
}
else
status = RA_NOMATCH;
// If it could match, try it.
if (rst->nextb == NUL || *rex.input == rst->nextb
|| *rex.input == rst->nextb_ic)
{
reg_save(&rp->rs_un.regsave, &backpos);
scan = regnext(rp->rs_scan);
status = RA_CONT;
break;
}
}
if (status != RA_CONT)
{
// Failed.
regstack_pop(&scan);
regstack.ga_len -= sizeof(regstar_T);
status = RA_NOMATCH;
}
}
break;
}
// If we want to continue the inner loop or didn't pop a state
// continue matching loop
if (status == RA_CONT || rp == (regitem_T *)
((char *)regstack.ga_data + regstack.ga_len) - 1)
break;
}
// May need to continue with the inner loop, starting at "scan".
if (status == RA_CONT)
continue;
// If the regstack is empty or something failed we are done.
if (regstack.ga_len == 0 || status == RA_FAIL)
{
if (scan == NULL)
{
// We get here only if there's trouble -- normally "case END" is
// the terminating point.
iemsg(_(e_corrupted_regexp_program));
#ifdef DEBUG
printf("Premature EOL\n");
#endif
}
return (status == RA_MATCH);
}
} // End of loop until the regstack is empty.
// NOTREACHED
}
| null | null | 206,921
|
14507096832468276355973161027739212088
| 1,481
|
patch 8.2.4440: crash with specific regexp pattern and string
Problem: Crash with specific regexp pattern and string.
Solution: Stop at the start of the string.
|
other
|
vim
|
1e56bda9048a9625bce6e660938c834c5c15b07d
| 1
|
eval_string(char_u **arg, typval_T *rettv, int evaluate, int interpolate)
{
char_u *p;
char_u *end;
int extra = interpolate ? 1 : 0;
int off = interpolate ? 0 : 1;
int len;
// Find the end of the string, skipping backslashed characters.
for (p = *arg + off; *p != NUL && *p != '"'; MB_PTR_ADV(p))
{
if (*p == '\\' && p[1] != NUL)
{
++p;
// A "\<x>" form occupies at least 4 characters, and produces up
// to 9 characters (6 for the char and 3 for a modifier):
// reserve space for 5 extra.
if (*p == '<')
extra += 5;
}
else if (interpolate && (*p == '{' || *p == '}'))
{
if (*p == '{' && p[1] != '{') // start of expression
break;
++p;
if (p[-1] == '}' && *p != '}') // single '}' is an error
{
semsg(_(e_stray_closing_curly_str), *arg);
return FAIL;
}
--extra; // "{{" becomes "{", "}}" becomes "}"
}
}
if (*p != '"' && !(interpolate && *p == '{'))
{
semsg(_(e_missing_double_quote_str), *arg);
return FAIL;
}
// If only parsing, set *arg and return here
if (!evaluate)
{
*arg = p + off;
return OK;
}
// Copy the string into allocated memory, handling backslashed
// characters.
rettv->v_type = VAR_STRING;
len = (int)(p - *arg + extra);
rettv->vval.v_string = alloc(len);
if (rettv->vval.v_string == NULL)
return FAIL;
end = rettv->vval.v_string;
for (p = *arg + off; *p != NUL && *p != '"'; )
{
if (*p == '\\')
{
switch (*++p)
{
case 'b': *end++ = BS; ++p; break;
case 'e': *end++ = ESC; ++p; break;
case 'f': *end++ = FF; ++p; break;
case 'n': *end++ = NL; ++p; break;
case 'r': *end++ = CAR; ++p; break;
case 't': *end++ = TAB; ++p; break;
case 'X': // hex: "\x1", "\x12"
case 'x':
case 'u': // Unicode: "\u0023"
case 'U':
if (vim_isxdigit(p[1]))
{
int n, nr;
int c = toupper(*p);
if (c == 'X')
n = 2;
else if (*p == 'u')
n = 4;
else
n = 8;
nr = 0;
while (--n >= 0 && vim_isxdigit(p[1]))
{
++p;
nr = (nr << 4) + hex2nr(*p);
}
++p;
// For "\u" store the number according to
// 'encoding'.
if (c != 'X')
end += (*mb_char2bytes)(nr, end);
else
*end++ = nr;
}
break;
// octal: "\1", "\12", "\123"
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7': *end = *p++ - '0';
if (*p >= '0' && *p <= '7')
{
*end = (*end << 3) + *p++ - '0';
if (*p >= '0' && *p <= '7')
*end = (*end << 3) + *p++ - '0';
}
++end;
break;
// Special key, e.g.: "\<C-W>"
case '<':
{
int flags = FSK_KEYCODE | FSK_IN_STRING;
if (p[1] != '*')
flags |= FSK_SIMPLIFY;
extra = trans_special(&p, end, flags, FALSE, NULL);
if (extra != 0)
{
end += extra;
if (end >= rettv->vval.v_string + len)
iemsg("eval_string() used more space than allocated");
break;
}
}
// FALLTHROUGH
default: MB_COPY_CHAR(p, end);
break;
}
}
else
{
if (interpolate && (*p == '{' || *p == '}'))
{
if (*p == '{' && p[1] != '{') // start of expression
break;
++p; // reduce "{{" to "{" and "}}" to "}"
}
MB_COPY_CHAR(p, end);
}
}
*end = NUL;
if (*p == '"' && !interpolate)
++p;
*arg = p;
return OK;
}
| null | null | 206,942
|
251995737585653065338836952190224629996
| 158
|
patch 9.0.0104: going beyond allocated memory when evaluating string constant
Problem: Going beyond allocated memory when evaluating string constant.
Solution: Properly skip over <Key> form.
|
other
|
jasper
|
d99636fad60629785efd1ef72da772a8ef68f54c
| 1
|
cmdopts_t *cmdopts_parse(int argc, char **argv)
{
enum {
CMDOPT_HELP = 0,
CMDOPT_VERBOSE,
CMDOPT_QUIET,
CMDOPT_INFILE,
CMDOPT_INFMT,
CMDOPT_INOPT,
CMDOPT_OUTFILE,
CMDOPT_OUTFMT,
CMDOPT_OUTOPT,
CMDOPT_VERSION,
CMDOPT_DEBUG,
CMDOPT_CMPTNO,
CMDOPT_SRGB,
CMDOPT_MAXMEM,
CMDOPT_LIST_ENABLED_CODECS,
CMDOPT_LIST_ALL_CODECS,
CMDOPT_ENABLE_FORMAT,
CMDOPT_ENABLE_ALL_FORMATS,
};
static const jas_opt_t cmdoptions[] = {
{CMDOPT_HELP, "help", 0},
{CMDOPT_VERBOSE, "verbose", 0},
{CMDOPT_QUIET, "quiet", 0},
{CMDOPT_QUIET, "q", 0},
{CMDOPT_INFILE, "input", JAS_OPT_HASARG},
{CMDOPT_INFILE, "f", JAS_OPT_HASARG},
{CMDOPT_INFMT, "input-format", JAS_OPT_HASARG},
{CMDOPT_INFMT, "t", JAS_OPT_HASARG},
{CMDOPT_INOPT, "input-option", JAS_OPT_HASARG},
{CMDOPT_INOPT, "o", JAS_OPT_HASARG},
{CMDOPT_OUTFILE, "output", JAS_OPT_HASARG},
{CMDOPT_OUTFILE, "F", JAS_OPT_HASARG},
{CMDOPT_OUTFMT, "output-format", JAS_OPT_HASARG},
{CMDOPT_OUTFMT, "T", JAS_OPT_HASARG},
{CMDOPT_OUTOPT, "output-option", JAS_OPT_HASARG},
{CMDOPT_OUTOPT, "O", JAS_OPT_HASARG},
{CMDOPT_VERSION, "version", 0},
{CMDOPT_DEBUG, "debug-level", JAS_OPT_HASARG},
{CMDOPT_CMPTNO, "cmptno", JAS_OPT_HASARG},
{CMDOPT_SRGB, "force-srgb", 0},
{CMDOPT_SRGB, "S", 0},
{CMDOPT_MAXMEM, "memory-limit", JAS_OPT_HASARG},
{CMDOPT_LIST_ENABLED_CODECS, "list-enabled-formats", 0},
{CMDOPT_LIST_ALL_CODECS, "list-all-formats", 0},
{CMDOPT_ENABLE_FORMAT, "enable-format", JAS_OPT_HASARG},
{CMDOPT_ENABLE_ALL_FORMATS, "enable-all-formats", 0},
{-1, 0, 0}
};
cmdopts_t *cmdopts;
int c;
if (!(cmdopts = malloc(sizeof(cmdopts_t)))) {
fprintf(stderr, "error: insufficient memory\n");
exit(EXIT_FAILURE);
}
cmdopts->infile = 0;
cmdopts->infmt = -1;
cmdopts->infmt_str = 0;
cmdopts->inopts = 0;
cmdopts->inoptsbuf[0] = '\0';
cmdopts->outfile = 0;
cmdopts->outfmt = -1;
cmdopts->outfmt_str = 0;
cmdopts->outopts = 0;
cmdopts->outoptsbuf[0] = '\0';
cmdopts->verbose = 0;
cmdopts->version = 0;
cmdopts->cmptno = -1;
cmdopts->debug = 0;
cmdopts->srgb = 0;
cmdopts->list_codecs = 0;
cmdopts->list_codecs_all = 0;
cmdopts->help = 0;
cmdopts->max_mem = get_default_max_mem_usage();
cmdopts->enable_format = 0;
cmdopts->enable_all_formats = 0;
while ((c = jas_getopt(argc, argv, cmdoptions)) != EOF) {
switch (c) {
case CMDOPT_HELP:
cmdopts->help = 1;
break;
case CMDOPT_VERBOSE:
cmdopts->verbose = 1;
break;
case CMDOPT_QUIET:
cmdopts->verbose = -1;
break;
case CMDOPT_VERSION:
cmdopts->version = 1;
break;
case CMDOPT_LIST_ENABLED_CODECS:
cmdopts->list_codecs = 1;
cmdopts->list_codecs_all = 0;
break;
case CMDOPT_LIST_ALL_CODECS:
cmdopts->list_codecs = 1;
cmdopts->list_codecs_all = 1;
break;
case CMDOPT_DEBUG:
cmdopts->debug = atoi(jas_optarg);
break;
case CMDOPT_INFILE:
cmdopts->infile = jas_optarg;
break;
case CMDOPT_INFMT:
cmdopts->infmt_str= jas_optarg;
break;
case CMDOPT_INOPT:
addopt(cmdopts->inoptsbuf, OPTSMAX, jas_optarg);
cmdopts->inopts = cmdopts->inoptsbuf;
break;
case CMDOPT_OUTFILE:
cmdopts->outfile = jas_optarg;
break;
case CMDOPT_OUTFMT:
cmdopts->outfmt_str = jas_optarg;
break;
case CMDOPT_OUTOPT:
addopt(cmdopts->outoptsbuf, OPTSMAX, jas_optarg);
cmdopts->outopts = cmdopts->outoptsbuf;
break;
case CMDOPT_CMPTNO:
cmdopts->cmptno = atoi(jas_optarg);
break;
case CMDOPT_SRGB:
cmdopts->srgb = 1;
break;
case CMDOPT_MAXMEM:
cmdopts->max_mem = strtoull(jas_optarg, 0, 10);
break;
case CMDOPT_ENABLE_FORMAT:
cmdopts->enable_format = jas_optarg;
break;
case CMDOPT_ENABLE_ALL_FORMATS:
cmdopts->enable_all_formats = 1;
break;
default:
badusage();
break;
}
}
while (jas_optind < argc) {
fprintf(stderr,
"warning: ignoring bogus command line argument %s\n",
argv[jas_optind]);
++jas_optind;
}
if (cmdopts->version || cmdopts->list_codecs || cmdopts->help) {
goto done;
}
if (!cmdopts->outfmt_str && !cmdopts->outfile) {
fprintf(stderr, "error: cannot determine output format\n");
badusage();
}
done:
return cmdopts;
}
| null | null | 206,946
|
258953396805315249695947632067343414397
| 168
|
fix memory leaks in function cmdopts_parse
|
other
|
flatpak
|
fb473cad801c6b61706353256cab32330557374a
| 1
|
apply_extra_data (FlatpakDir *self,
GFile *checkoutdir,
GCancellable *cancellable,
GError **error)
{
g_autoptr(GFile) metadata = NULL;
g_autofree char *metadata_contents = NULL;
gsize metadata_size;
g_autoptr(GKeyFile) metakey = NULL;
g_autofree char *id = NULL;
g_autofree char *runtime_pref = NULL;
g_autoptr(FlatpakDecomposed) runtime_ref = NULL;
g_autoptr(FlatpakDeploy) runtime_deploy = NULL;
g_autoptr(FlatpakBwrap) bwrap = NULL;
g_autoptr(GFile) app_files = NULL;
g_autoptr(GFile) apply_extra_file = NULL;
g_autoptr(GFile) app_export_file = NULL;
g_autoptr(GFile) extra_export_file = NULL;
g_autoptr(GFile) extra_files = NULL;
g_autoptr(GFile) runtime_files = NULL;
g_autoptr(FlatpakContext) app_context = NULL;
g_auto(GStrv) minimal_envp = NULL;
g_autofree char *runtime_arch = NULL;
int exit_status;
const char *group = FLATPAK_METADATA_GROUP_APPLICATION;
g_autoptr(GError) local_error = NULL;
apply_extra_file = g_file_resolve_relative_path (checkoutdir, "files/bin/apply_extra");
if (!g_file_query_exists (apply_extra_file, cancellable))
return TRUE;
metadata = g_file_get_child (checkoutdir, "metadata");
if (!g_file_load_contents (metadata, cancellable, &metadata_contents, &metadata_size, NULL, error))
return FALSE;
metakey = g_key_file_new ();
if (!g_key_file_load_from_data (metakey, metadata_contents, metadata_size, 0, error))
return FALSE;
id = g_key_file_get_string (metakey, group, FLATPAK_METADATA_KEY_NAME,
&local_error);
if (id == NULL)
{
group = FLATPAK_METADATA_GROUP_RUNTIME;
id = g_key_file_get_string (metakey, group, FLATPAK_METADATA_KEY_NAME,
NULL);
if (id == NULL)
{
g_propagate_error (error, g_steal_pointer (&local_error));
return FALSE;
}
g_clear_error (&local_error);
}
runtime_pref = g_key_file_get_string (metakey, group,
FLATPAK_METADATA_KEY_RUNTIME, error);
if (runtime_pref == NULL)
runtime_pref = g_key_file_get_string (metakey, FLATPAK_METADATA_GROUP_EXTENSION_OF,
FLATPAK_METADATA_KEY_RUNTIME, NULL);
if (runtime_pref == NULL)
return FALSE;
runtime_ref = flatpak_decomposed_new_from_pref (FLATPAK_KINDS_RUNTIME, runtime_pref, error);
if (runtime_ref == NULL)
return FALSE;
runtime_arch = flatpak_decomposed_dup_arch (runtime_ref);
if (!g_key_file_get_boolean (metakey, FLATPAK_METADATA_GROUP_EXTRA_DATA,
FLATPAK_METADATA_KEY_NO_RUNTIME, NULL))
{
/* We pass in self here so that we ensure that we find the runtime in case it only
exists in this installation (which might be custom) */
runtime_deploy = flatpak_find_deploy_for_ref (flatpak_decomposed_get_ref (runtime_ref), NULL, self, cancellable, error);
if (runtime_deploy == NULL)
return FALSE;
runtime_files = flatpak_deploy_get_files (runtime_deploy);
}
app_files = g_file_get_child (checkoutdir, "files");
app_export_file = g_file_get_child (checkoutdir, "export");
extra_files = g_file_get_child (app_files, "extra");
extra_export_file = g_file_get_child (extra_files, "export");
minimal_envp = flatpak_run_get_minimal_env (FALSE, FALSE);
bwrap = flatpak_bwrap_new (minimal_envp);
flatpak_bwrap_add_args (bwrap, flatpak_get_bwrap (), NULL);
if (runtime_files)
flatpak_bwrap_add_args (bwrap,
"--ro-bind", flatpak_file_get_path_cached (runtime_files), "/usr",
"--lock-file", "/usr/.ref",
NULL);
flatpak_bwrap_add_args (bwrap,
"--ro-bind", flatpak_file_get_path_cached (app_files), "/app",
"--bind", flatpak_file_get_path_cached (extra_files), "/app/extra",
"--chdir", "/app/extra",
/* We run as root in the system-helper case, so drop all caps */
"--cap-drop", "ALL",
NULL);
if (!flatpak_run_setup_base_argv (bwrap, runtime_files, NULL, runtime_arch,
/* Might need multiarch in apply_extra (see e.g. #3742). Should be pretty safe in this limited context */
FLATPAK_RUN_FLAG_MULTIARCH |
FLATPAK_RUN_FLAG_NO_SESSION_HELPER | FLATPAK_RUN_FLAG_NO_PROC,
error))
return FALSE;
app_context = flatpak_context_new ();
if (!flatpak_run_add_environment_args (bwrap, NULL,
FLATPAK_RUN_FLAG_NO_SESSION_BUS_PROXY |
FLATPAK_RUN_FLAG_NO_SYSTEM_BUS_PROXY |
FLATPAK_RUN_FLAG_NO_A11Y_BUS_PROXY,
id,
app_context, NULL, NULL, NULL, cancellable, error))
return FALSE;
flatpak_bwrap_add_arg (bwrap, "/app/bin/apply_extra");
flatpak_bwrap_finish (bwrap);
g_debug ("Running /app/bin/apply_extra ");
/* We run the sandbox without caps, but it can still create files owned by itself with
* arbitrary permissions, including setuid myself. This is extra risky in the case where
* this runs as root in the system helper case. We canonicalize the permissions at the
* end, but to avoid non-canonical permissions leaking out before then we make the
* toplevel dir only accessible to the user */
if (chmod (flatpak_file_get_path_cached (extra_files), 0700) != 0)
{
glnx_set_error_from_errno (error);
return FALSE;
}
if (!g_spawn_sync (NULL,
(char **) bwrap->argv->pdata,
bwrap->envp,
G_SPAWN_SEARCH_PATH,
child_setup, bwrap->fds,
NULL, NULL,
&exit_status,
error))
return FALSE;
if (!flatpak_canonicalize_permissions (AT_FDCWD, flatpak_file_get_path_cached (extra_files),
getuid () == 0 ? 0 : -1,
getuid () == 0 ? 0 : -1,
error))
return FALSE;
if (exit_status != 0)
{
g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
_("apply_extra script failed, exit status %d"), exit_status);
return FALSE;
}
if (g_file_query_exists (extra_export_file, cancellable))
{
if (!flatpak_mkdir_p (app_export_file, cancellable, error))
return FALSE;
if (!flatpak_cp_a (extra_export_file,
app_export_file,
FLATPAK_CP_FLAGS_MERGE,
cancellable, error))
return FALSE;
}
return TRUE;
}
| null | null | 206,989
|
62902606532827421827792118702945647615
| 172
|
dir: Pass environment via bwrap --setenv when running apply_extra
This means we can systematically pass the environment variables
through bwrap(1), even if it is setuid and thus is filtering out
security-sensitive environment variables. bwrap ends up being
run with an empty environment instead.
As with the previous commit, this regressed while fixing CVE-2021-21261.
Fixes: 6d1773d2 "run: Convert all environment variables into bwrap arguments"
Signed-off-by: Simon McVittie <[email protected]>
|
other
|
xorg-xserver
|
c06e27b2f6fd9f7b9f827623a48876a225264132
| 1
|
ProcXkbSetDeviceInfo(ClientPtr client)
{
DeviceIntPtr dev;
unsigned change;
char * wire;
xkbExtensionDeviceNotify ed;
REQUEST(xkbSetDeviceInfoReq);
REQUEST_AT_LEAST_SIZE(xkbSetDeviceInfoReq);
if (!(client->xkbClientFlags&_XkbClientInitialized))
return BadAccess;
change= stuff->change;
CHK_ANY_DEVICE(dev, stuff->deviceSpec, client, DixManageAccess);
CHK_MASK_LEGAL(0x01,change,XkbXI_AllFeaturesMask);
wire= (char *)&stuff[1];
if (change&XkbXI_ButtonActionsMask) {
if (!dev->button) {
client->errorValue = _XkbErrCode2(XkbErr_BadClass,ButtonClass);
return XkbKeyboardErrorCode;
}
if ((stuff->firstBtn+stuff->nBtns)>dev->button->numButtons) {
client->errorValue= _XkbErrCode4(0x02,stuff->firstBtn,stuff->nBtns,
dev->button->numButtons);
return BadMatch;
}
wire+= (stuff->nBtns*SIZEOF(xkbActionWireDesc));
}
if (stuff->change&XkbXI_IndicatorsMask) {
int status= Success;
wire= CheckSetDeviceIndicators(wire,dev,stuff->nDeviceLedFBs,
&status,client);
if (status!=Success)
return status;
}
if (((wire-((char *)stuff))/4)!=stuff->length)
return BadLength;
bzero((char *)&ed,SIZEOF(xkbExtensionDeviceNotify));
ed.deviceID= dev->id;
wire= (char *)&stuff[1];
if (change&XkbXI_ButtonActionsMask) {
int nBtns,sz,i;
XkbAction * acts;
DeviceIntPtr kbd;
nBtns= dev->button->numButtons;
acts= dev->button->xkb_acts;
if (acts==NULL) {
acts= _XkbTypedCalloc(nBtns,XkbAction);
if (!acts)
return BadAlloc;
dev->button->xkb_acts= acts;
}
sz= stuff->nBtns*SIZEOF(xkbActionWireDesc);
memcpy((char *)&acts[stuff->firstBtn],(char *)wire,sz);
wire+= sz;
ed.reason|= XkbXI_ButtonActionsMask;
ed.firstBtn= stuff->firstBtn;
ed.nBtns= stuff->nBtns;
if (dev->key) kbd= dev;
else kbd= inputInfo.keyboard;
acts= &dev->button->xkb_acts[stuff->firstBtn];
for (i=0;i<stuff->nBtns;i++,acts++) {
if (acts->type!=XkbSA_NoAction)
XkbSetActionKeyMods(kbd->key->xkbInfo->desc,acts,0);
}
}
if (stuff->change&XkbXI_IndicatorsMask) {
int status= Success;
wire= SetDeviceIndicators(wire,dev,change,stuff->nDeviceLedFBs,
&status,client,&ed);
if (status!=Success)
return status;
}
if ((stuff->change)&&(ed.reason))
XkbSendExtensionDeviceNotify(dev,client,&ed);
return client->noClientException;
}
| null | null | 206,992
|
228648490563771292194907521710038828836
| 83
|
xkb: ProcXkbSetDeviceInfo should work on all attached SDs.
If called with XkbUseCoreKbd, run through all attached SDs and replicate the
call. This way, we keep the SDs in sync with the MD as long as core clients
control the MDs.
|
other
|
linux
|
cc7a0bb058b85ea03db87169c60c7cfdd5d34678
| 1
|
static ssize_t remove_slot_store(struct kobject *kobj,
struct kobj_attribute *attr,
const char *buf, size_t nbytes)
{
char drc_name[MAX_DRC_NAME_LEN];
int rc;
char *end;
if (nbytes >= MAX_DRC_NAME_LEN)
return 0;
memcpy(drc_name, buf, nbytes);
end = strchr(drc_name, '\n');
if (!end)
end = &drc_name[nbytes];
*end = '\0';
rc = dlpar_remove_slot(drc_name);
if (rc)
return rc;
return nbytes;
}
| null | null | 207,068
|
66377107202241996731442605907157187034
| 24
|
PCI: rpadlpar: Fix potential drc_name corruption in store functions
Both add_slot_store() and remove_slot_store() try to fix up the
drc_name copied from the store buffer by placing a NUL terminator at
nbyte + 1 or in place of a '\n' if present. However, the static buffer
that we copy the drc_name data into is not zeroed and can contain
anything past the n-th byte.
This is problematic if a '\n' byte appears in that buffer after nbytes
and the string copied into the store buffer was not NUL terminated to
start with as the strchr() search for a '\n' byte will mark this
incorrectly as the end of the drc_name string resulting in a drc_name
string that contains garbage data after the n-th byte.
Additionally it will cause us to overwrite that '\n' byte on the stack
with NUL, potentially corrupting data on the stack.
The following debugging shows an example of the drmgr utility writing
"PHB 4543" to the add_slot sysfs attribute, but add_slot_store()
logging a corrupted string value.
drmgr: drmgr: -c phb -a -s PHB 4543 -d 1
add_slot_store: drc_name = PHB 4543°|<82>!, rc = -19
Fix this by using strscpy() instead of memcpy() to ensure the string
is NUL terminated when copied into the static drc_name buffer.
Further, since the string is now NUL terminated the code only needs to
change '\n' to '\0' when present.
Cc: [email protected]
Signed-off-by: Tyrel Datwyler <[email protected]>
[mpe: Reformat change log and add mention of possible stack corruption]
Signed-off-by: Michael Ellerman <[email protected]>
Link: https://lore.kernel.org/r/[email protected]
|
other
|
linux
|
cc7a0bb058b85ea03db87169c60c7cfdd5d34678
| 1
|
static ssize_t add_slot_store(struct kobject *kobj, struct kobj_attribute *attr,
const char *buf, size_t nbytes)
{
char drc_name[MAX_DRC_NAME_LEN];
char *end;
int rc;
if (nbytes >= MAX_DRC_NAME_LEN)
return 0;
memcpy(drc_name, buf, nbytes);
end = strchr(drc_name, '\n');
if (!end)
end = &drc_name[nbytes];
*end = '\0';
rc = dlpar_add_slot(drc_name);
if (rc)
return rc;
return nbytes;
}
| null | null | 207,069
|
115299723316486657840703980559738544414
| 23
|
PCI: rpadlpar: Fix potential drc_name corruption in store functions
Both add_slot_store() and remove_slot_store() try to fix up the
drc_name copied from the store buffer by placing a NUL terminator at
nbyte + 1 or in place of a '\n' if present. However, the static buffer
that we copy the drc_name data into is not zeroed and can contain
anything past the n-th byte.
This is problematic if a '\n' byte appears in that buffer after nbytes
and the string copied into the store buffer was not NUL terminated to
start with as the strchr() search for a '\n' byte will mark this
incorrectly as the end of the drc_name string resulting in a drc_name
string that contains garbage data after the n-th byte.
Additionally it will cause us to overwrite that '\n' byte on the stack
with NUL, potentially corrupting data on the stack.
The following debugging shows an example of the drmgr utility writing
"PHB 4543" to the add_slot sysfs attribute, but add_slot_store()
logging a corrupted string value.
drmgr: drmgr: -c phb -a -s PHB 4543 -d 1
add_slot_store: drc_name = PHB 4543°|<82>!, rc = -19
Fix this by using strscpy() instead of memcpy() to ensure the string
is NUL terminated when copied into the static drc_name buffer.
Further, since the string is now NUL terminated the code only needs to
change '\n' to '\0' when present.
Cc: [email protected]
Signed-off-by: Tyrel Datwyler <[email protected]>
[mpe: Reformat change log and add mention of possible stack corruption]
Signed-off-by: Michael Ellerman <[email protected]>
Link: https://lore.kernel.org/r/[email protected]
|
other
|
samba
|
60f922bf1bd8816eacbb32c24793ad1f97a1d9f2
| 1
|
static NTSTATUS create_file_unixpath(connection_struct *conn,
struct smb_request *req,
struct smb_filename *smb_fname,
uint32_t access_mask,
uint32_t share_access,
uint32_t create_disposition,
uint32_t create_options,
uint32_t file_attributes,
uint32_t oplock_request,
uint64_t allocation_size,
uint32_t private_flags,
struct security_descriptor *sd,
struct ea_list *ea_list,
files_struct **result,
int *pinfo)
{
int info = FILE_WAS_OPENED;
files_struct *base_fsp = NULL;
files_struct *fsp = NULL;
NTSTATUS status;
DEBUG(10,("create_file_unixpath: access_mask = 0x%x "
"file_attributes = 0x%x, share_access = 0x%x, "
"create_disposition = 0x%x create_options = 0x%x "
"oplock_request = 0x%x private_flags = 0x%x "
"ea_list = 0x%p, sd = 0x%p, "
"fname = %s\n",
(unsigned int)access_mask,
(unsigned int)file_attributes,
(unsigned int)share_access,
(unsigned int)create_disposition,
(unsigned int)create_options,
(unsigned int)oplock_request,
(unsigned int)private_flags,
ea_list, sd, smb_fname_str_dbg(smb_fname)));
if (create_options & FILE_OPEN_BY_FILE_ID) {
status = NT_STATUS_NOT_SUPPORTED;
goto fail;
}
if (create_options & NTCREATEX_OPTIONS_INVALID_PARAM_MASK) {
status = NT_STATUS_INVALID_PARAMETER;
goto fail;
}
if (req == NULL) {
oplock_request |= INTERNAL_OPEN_ONLY;
}
if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
&& (access_mask & DELETE_ACCESS)
&& !is_ntfs_stream_smb_fname(smb_fname)) {
/*
* We can't open a file with DELETE access if any of the
* streams is open without FILE_SHARE_DELETE
*/
status = open_streams_for_delete(conn, smb_fname->base_name);
if (!NT_STATUS_IS_OK(status)) {
goto fail;
}
}
if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
!security_token_has_privilege(get_current_nttok(conn),
SEC_PRIV_SECURITY)) {
DEBUG(10, ("create_file_unixpath: open on %s "
"failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
smb_fname_str_dbg(smb_fname)));
status = NT_STATUS_PRIVILEGE_NOT_HELD;
goto fail;
}
if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
&& is_ntfs_stream_smb_fname(smb_fname)
&& (!(private_flags & NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE))) {
uint32 base_create_disposition;
struct smb_filename *smb_fname_base = NULL;
if (create_options & FILE_DIRECTORY_FILE) {
status = NT_STATUS_NOT_A_DIRECTORY;
goto fail;
}
switch (create_disposition) {
case FILE_OPEN:
base_create_disposition = FILE_OPEN;
break;
default:
base_create_disposition = FILE_OPEN_IF;
break;
}
/* Create an smb_filename with stream_name == NULL. */
smb_fname_base = synthetic_smb_fname(talloc_tos(),
smb_fname->base_name,
NULL, NULL);
if (smb_fname_base == NULL) {
status = NT_STATUS_NO_MEMORY;
goto fail;
}
if (SMB_VFS_STAT(conn, smb_fname_base) == -1) {
DEBUG(10, ("Unable to stat stream: %s\n",
smb_fname_str_dbg(smb_fname_base)));
}
/* Open the base file. */
status = create_file_unixpath(conn, NULL, smb_fname_base, 0,
FILE_SHARE_READ
| FILE_SHARE_WRITE
| FILE_SHARE_DELETE,
base_create_disposition,
0, 0, 0, 0, 0, NULL, NULL,
&base_fsp, NULL);
TALLOC_FREE(smb_fname_base);
if (!NT_STATUS_IS_OK(status)) {
DEBUG(10, ("create_file_unixpath for base %s failed: "
"%s\n", smb_fname->base_name,
nt_errstr(status)));
goto fail;
}
/* we don't need to low level fd */
fd_close(base_fsp);
}
/*
* If it's a request for a directory open, deal with it separately.
*/
if (create_options & FILE_DIRECTORY_FILE) {
if (create_options & FILE_NON_DIRECTORY_FILE) {
status = NT_STATUS_INVALID_PARAMETER;
goto fail;
}
/* Can't open a temp directory. IFS kit test. */
if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS) &&
(file_attributes & FILE_ATTRIBUTE_TEMPORARY)) {
status = NT_STATUS_INVALID_PARAMETER;
goto fail;
}
/*
* We will get a create directory here if the Win32
* app specified a security descriptor in the
* CreateDirectory() call.
*/
oplock_request = 0;
status = open_directory(
conn, req, smb_fname, access_mask, share_access,
create_disposition, create_options, file_attributes,
&info, &fsp);
} else {
/*
* Ordinary file case.
*/
status = file_new(req, conn, &fsp);
if(!NT_STATUS_IS_OK(status)) {
goto fail;
}
status = fsp_set_smb_fname(fsp, smb_fname);
if (!NT_STATUS_IS_OK(status)) {
goto fail;
}
if (base_fsp) {
/*
* We're opening the stream element of a
* base_fsp we already opened. Set up the
* base_fsp pointer.
*/
fsp->base_fsp = base_fsp;
}
if (allocation_size) {
fsp->initial_allocation_size = smb_roundup(fsp->conn,
allocation_size);
}
status = open_file_ntcreate(conn,
req,
access_mask,
share_access,
create_disposition,
create_options,
file_attributes,
oplock_request,
private_flags,
&info,
fsp);
if(!NT_STATUS_IS_OK(status)) {
file_free(req, fsp);
fsp = NULL;
}
if (NT_STATUS_EQUAL(status, NT_STATUS_FILE_IS_A_DIRECTORY)) {
/* A stream open never opens a directory */
if (base_fsp) {
status = NT_STATUS_FILE_IS_A_DIRECTORY;
goto fail;
}
/*
* Fail the open if it was explicitly a non-directory
* file.
*/
if (create_options & FILE_NON_DIRECTORY_FILE) {
status = NT_STATUS_FILE_IS_A_DIRECTORY;
goto fail;
}
oplock_request = 0;
status = open_directory(
conn, req, smb_fname, access_mask,
share_access, create_disposition,
create_options, file_attributes,
&info, &fsp);
}
}
if (!NT_STATUS_IS_OK(status)) {
goto fail;
}
fsp->base_fsp = base_fsp;
if ((ea_list != NULL) &&
((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN))) {
status = set_ea(conn, fsp, fsp->fsp_name, ea_list);
if (!NT_STATUS_IS_OK(status)) {
goto fail;
}
}
if (!fsp->is_directory && S_ISDIR(fsp->fsp_name->st.st_ex_mode)) {
status = NT_STATUS_ACCESS_DENIED;
goto fail;
}
/* Save the requested allocation size. */
if ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN)) {
if (allocation_size
&& (allocation_size > fsp->fsp_name->st.st_ex_size)) {
fsp->initial_allocation_size = smb_roundup(
fsp->conn, allocation_size);
if (fsp->is_directory) {
/* Can't set allocation size on a directory. */
status = NT_STATUS_ACCESS_DENIED;
goto fail;
}
if (vfs_allocate_file_space(
fsp, fsp->initial_allocation_size) == -1) {
status = NT_STATUS_DISK_FULL;
goto fail;
}
} else {
fsp->initial_allocation_size = smb_roundup(
fsp->conn, (uint64_t)fsp->fsp_name->st.st_ex_size);
}
} else {
fsp->initial_allocation_size = 0;
}
if ((info == FILE_WAS_CREATED) && lp_nt_acl_support(SNUM(conn)) &&
fsp->base_fsp == NULL) {
if (sd != NULL) {
/*
* According to the MS documentation, the only time the security
* descriptor is applied to the opened file is iff we *created* the
* file; an existing file stays the same.
*
* Also, it seems (from observation) that you can open the file with
* any access mask but you can still write the sd. We need to override
* the granted access before we call set_sd
* Patch for bug #2242 from Tom Lackemann <[email protected]>.
*/
uint32_t sec_info_sent;
uint32_t saved_access_mask = fsp->access_mask;
sec_info_sent = get_sec_info(sd);
fsp->access_mask = FILE_GENERIC_ALL;
if (sec_info_sent & (SECINFO_OWNER|
SECINFO_GROUP|
SECINFO_DACL|
SECINFO_SACL)) {
status = set_sd(fsp, sd, sec_info_sent);
}
fsp->access_mask = saved_access_mask;
if (!NT_STATUS_IS_OK(status)) {
goto fail;
}
} else if (lp_inherit_acls(SNUM(conn))) {
/* Inherit from parent. Errors here are not fatal. */
status = inherit_new_acl(fsp);
if (!NT_STATUS_IS_OK(status)) {
DEBUG(10,("inherit_new_acl: failed for %s with %s\n",
fsp_str_dbg(fsp),
nt_errstr(status) ));
}
}
}
DEBUG(10, ("create_file_unixpath: info=%d\n", info));
*result = fsp;
if (pinfo != NULL) {
*pinfo = info;
}
smb_fname->st = fsp->fsp_name->st;
return NT_STATUS_OK;
fail:
DEBUG(10, ("create_file_unixpath: %s\n", nt_errstr(status)));
if (fsp != NULL) {
if (base_fsp && fsp->base_fsp == base_fsp) {
/*
* The close_file below will close
* fsp->base_fsp.
*/
base_fsp = NULL;
}
close_file(req, fsp, ERROR_CLOSE);
fsp = NULL;
}
if (base_fsp != NULL) {
close_file(req, base_fsp, ERROR_CLOSE);
base_fsp = NULL;
}
return status;
}
| null | null | 207,070
|
86756942410942814677576331572585726402
| 351
|
Fix bug #10229 - No access check verification on stream files.
https://bugzilla.samba.org/show_bug.cgi?id=10229
We need to check if the requested access mask
could be used to open the underlying file (if
it existed), as we're passing in zero for the
access mask to the base filename.
Signed-off-by: Jeremy Allison <[email protected]>
Reviewed-by: Stefan Metzmacher <[email protected]>
Reviewed-by: David Disseldorp <[email protected]>
|
other
|
openexr
|
467be80b75642efbbe6bdace558079f68c16acb1
| 1
|
DeepTiledInputFile::initialize ()
{
if (_data->partNumber == -1)
if (_data->header.type() != DEEPTILE)
throw IEX_NAMESPACE::ArgExc ("Expected a deep tiled file but the file is not deep tiled.");
if(_data->header.version()!=1)
{
THROW(IEX_NAMESPACE::ArgExc, "Version " << _data->header.version() << " not supported for deeptiled images in this version of the library");
}
_data->header.sanityCheck (true);
//
// before allocating memory for tile offsets, confirm file is large enough
// to contain tile offset table
// (for multipart files, the chunk offset table has already been read)
//
if (!isMultiPart(_data->version))
{
_data->validateStreamSize();
}
_data->tileDesc = _data->header.tileDescription();
_data->lineOrder = _data->header.lineOrder();
//
// Save the dataWindow information
//
const Box2i &dataWindow = _data->header.dataWindow();
_data->minX = dataWindow.min.x;
_data->maxX = dataWindow.max.x;
_data->minY = dataWindow.min.y;
_data->maxY = dataWindow.max.y;
//
// Precompute level and tile information to speed up utility functions
//
precalculateTileInfo (_data->tileDesc,
_data->minX, _data->maxX,
_data->minY, _data->maxY,
_data->numXTiles, _data->numYTiles,
_data->numXLevels, _data->numYLevels);
//
// Create all the TileBuffers and allocate their internal buffers
//
_data->tileOffsets = TileOffsets (_data->tileDesc.mode,
_data->numXLevels,
_data->numYLevels,
_data->numXTiles,
_data->numYTiles);
for (size_t i = 0; i < _data->tileBuffers.size(); i++)
_data->tileBuffers[i] = new TileBuffer ();
_data->maxSampleCountTableSize = _data->tileDesc.ySize *
_data->tileDesc.xSize *
sizeof(int);
_data->sampleCountTableBuffer.resizeErase(_data->maxSampleCountTableSize);
_data->sampleCountTableComp = newCompressor(_data->header.compression(),
_data->maxSampleCountTableSize,
_data->header);
const ChannelList & c=_data->header.channels();
_data->combinedSampleSize=0;
for(ChannelList::ConstIterator i=c.begin();i!=c.end();i++)
{
switch( i.channel().type )
{
case OPENEXR_IMF_INTERNAL_NAMESPACE::HALF :
_data->combinedSampleSize+=Xdr::size<half>();
break;
case OPENEXR_IMF_INTERNAL_NAMESPACE::FLOAT :
_data->combinedSampleSize+=Xdr::size<float>();
break;
case OPENEXR_IMF_INTERNAL_NAMESPACE::UINT :
_data->combinedSampleSize+=Xdr::size<unsigned int>();
break;
default :
THROW(IEX_NAMESPACE::ArgExc, "Bad type for channel " << i.name() << " initializing deepscanline reader");
}
}
}
| null | null | 207,071
|
53867069728921487090628063652681608429
| 91
|
Fix overflow computing deeptile sample table size (#861)
Signed-off-by: Peter Hillman <[email protected]>
|
other
|
squirrel
|
a6413aa690e0bdfef648c68693349a7b878fe60d
| 1
|
static SQInteger thread_call(HSQUIRRELVM v)
{
SQObjectPtr o = stack_get(v,1);
if(sq_type(o) == OT_THREAD) {
SQInteger nparams = sq_gettop(v);
_thread(o)->Push(_thread(o)->_roottable);
for(SQInteger i = 2; i<(nparams+1); i++)
sq_move(_thread(o),v,i);
if(SQ_SUCCEEDED(sq_call(_thread(o),nparams,SQTrue,SQTrue))) {
sq_move(v,_thread(o),-1);
sq_pop(_thread(o),1);
return 1;
}
v->_lasterror = _thread(o)->_lasterror;
return SQ_ERROR;
}
return sq_throwerror(v,_SC("wrong parameter"));
}
| null | null | 207,150
|
306139211902210519273801023569379950602
| 18
|
fix in thread.call
|
other
|
samba
|
86fe9d48883f87c928bf31ccbd275db420386803
| 1
|
static NTSTATUS ldapsrv_SearchRequest(struct ldapsrv_call *call)
{
struct ldap_SearchRequest *req = &call->request->r.SearchRequest;
struct ldap_Result *done;
struct ldapsrv_reply *done_r;
TALLOC_CTX *local_ctx;
struct ldapsrv_context *callback_ctx = NULL;
struct ldb_context *samdb = talloc_get_type(call->conn->ldb, struct ldb_context);
struct ldb_dn *basedn;
struct ldb_request *lreq;
struct ldb_control *search_control;
struct ldb_search_options_control *search_options;
struct ldb_control *extended_dn_control;
struct ldb_extended_dn_control *extended_dn_decoded = NULL;
struct ldb_control *notification_control = NULL;
enum ldb_scope scope = LDB_SCOPE_DEFAULT;
const char **attrs = NULL;
const char *scope_str, *errstr = NULL;
int result = -1;
int ldb_ret = -1;
unsigned int i;
int extended_type = 1;
DEBUG(10, ("SearchRequest"));
DEBUGADD(10, (" basedn: %s", req->basedn));
DEBUGADD(10, (" filter: %s\n", ldb_filter_from_tree(call, req->tree)));
local_ctx = talloc_new(call);
NT_STATUS_HAVE_NO_MEMORY(local_ctx);
basedn = ldb_dn_new(local_ctx, samdb, req->basedn);
NT_STATUS_HAVE_NO_MEMORY(basedn);
DEBUG(10, ("SearchRequest: basedn: [%s]\n", req->basedn));
DEBUG(10, ("SearchRequest: filter: [%s]\n", ldb_filter_from_tree(call, req->tree)));
switch (req->scope) {
case LDAP_SEARCH_SCOPE_BASE:
scope_str = "BASE";
scope = LDB_SCOPE_BASE;
break;
case LDAP_SEARCH_SCOPE_SINGLE:
scope_str = "ONE";
scope = LDB_SCOPE_ONELEVEL;
break;
case LDAP_SEARCH_SCOPE_SUB:
scope_str = "SUB";
scope = LDB_SCOPE_SUBTREE;
break;
default:
result = LDAP_PROTOCOL_ERROR;
map_ldb_error(local_ctx, LDB_ERR_PROTOCOL_ERROR, NULL,
&errstr);
errstr = talloc_asprintf(local_ctx,
"%s. Invalid scope", errstr);
goto reply;
}
DEBUG(10,("SearchRequest: scope: [%s]\n", scope_str));
if (req->num_attributes >= 1) {
attrs = talloc_array(local_ctx, const char *, req->num_attributes+1);
NT_STATUS_HAVE_NO_MEMORY(attrs);
for (i=0; i < req->num_attributes; i++) {
DEBUG(10,("SearchRequest: attrs: [%s]\n",req->attributes[i]));
attrs[i] = req->attributes[i];
}
attrs[i] = NULL;
}
DEBUG(5,("ldb_request %s dn=%s filter=%s\n",
scope_str, req->basedn, ldb_filter_from_tree(call, req->tree)));
callback_ctx = talloc_zero(local_ctx, struct ldapsrv_context);
NT_STATUS_HAVE_NO_MEMORY(callback_ctx);
callback_ctx->call = call;
callback_ctx->extended_type = extended_type;
callback_ctx->attributesonly = req->attributesonly;
ldb_ret = ldb_build_search_req_ex(&lreq, samdb, local_ctx,
basedn, scope,
req->tree, attrs,
call->request->controls,
callback_ctx,
ldap_server_search_callback,
NULL);
if (ldb_ret != LDB_SUCCESS) {
goto reply;
}
if (call->conn->global_catalog) {
search_control = ldb_request_get_control(lreq, LDB_CONTROL_SEARCH_OPTIONS_OID);
search_options = NULL;
if (search_control) {
search_options = talloc_get_type(search_control->data, struct ldb_search_options_control);
search_options->search_options |= LDB_SEARCH_OPTION_PHANTOM_ROOT;
} else {
search_options = talloc(lreq, struct ldb_search_options_control);
NT_STATUS_HAVE_NO_MEMORY(search_options);
search_options->search_options = LDB_SEARCH_OPTION_PHANTOM_ROOT;
ldb_request_add_control(lreq, LDB_CONTROL_SEARCH_OPTIONS_OID, false, search_options);
}
} else {
ldb_request_add_control(lreq, DSDB_CONTROL_NO_GLOBAL_CATALOG, false, NULL);
}
extended_dn_control = ldb_request_get_control(lreq, LDB_CONTROL_EXTENDED_DN_OID);
if (extended_dn_control) {
if (extended_dn_control->data) {
extended_dn_decoded = talloc_get_type(extended_dn_control->data, struct ldb_extended_dn_control);
extended_type = extended_dn_decoded->type;
} else {
extended_type = 0;
}
callback_ctx->extended_type = extended_type;
}
notification_control = ldb_request_get_control(lreq, LDB_CONTROL_NOTIFICATION_OID);
if (notification_control != NULL) {
const struct ldapsrv_call *pc = NULL;
size_t count = 0;
for (pc = call->conn->pending_calls; pc != NULL; pc = pc->next) {
count += 1;
}
if (count >= call->conn->limits.max_notifications) {
DEBUG(10,("SearchRequest: error MaxNotificationPerConn\n"));
result = map_ldb_error(local_ctx,
LDB_ERR_ADMIN_LIMIT_EXCEEDED,
"MaxNotificationPerConn reached",
&errstr);
goto reply;
}
/*
* For now we need to do periodic retries on our own.
* As the dsdb_notification module will return after each run.
*/
call->notification.busy = true;
}
{
const char *scheme = NULL;
switch (call->conn->referral_scheme) {
case LDAP_REFERRAL_SCHEME_LDAPS:
scheme = "ldaps";
break;
default:
scheme = "ldap";
}
ldb_ret = ldb_set_opaque(
samdb,
LDAP_REFERRAL_SCHEME_OPAQUE,
discard_const_p(char *, scheme));
if (ldb_ret != LDB_SUCCESS) {
goto reply;
}
}
ldb_set_timeout(samdb, lreq, req->timelimit);
if (!call->conn->is_privileged) {
ldb_req_mark_untrusted(lreq);
}
LDB_REQ_SET_LOCATION(lreq);
ldb_ret = ldb_request(samdb, lreq);
if (ldb_ret != LDB_SUCCESS) {
goto reply;
}
ldb_ret = ldb_wait(lreq->handle, LDB_WAIT_ALL);
if (ldb_ret == LDB_SUCCESS) {
if (call->notification.busy) {
/* Move/Add it to the end */
DLIST_DEMOTE(call->conn->pending_calls, call);
call->notification.generation =
call->conn->service->notification.generation;
if (callback_ctx->count != 0) {
call->notification.generation += 1;
ldapsrv_notification_retry_setup(call->conn->service,
true);
}
talloc_free(local_ctx);
return NT_STATUS_OK;
}
}
reply:
DLIST_REMOVE(call->conn->pending_calls, call);
call->notification.busy = false;
done_r = ldapsrv_init_reply(call, LDAP_TAG_SearchResultDone);
NT_STATUS_HAVE_NO_MEMORY(done_r);
done = &done_r->msg->r.SearchResultDone;
done->dn = NULL;
done->referral = NULL;
if (result != -1) {
} else if (ldb_ret == LDB_SUCCESS) {
if (callback_ctx->controls) {
done_r->msg->controls = callback_ctx->controls;
talloc_steal(done_r->msg, callback_ctx->controls);
}
result = LDB_SUCCESS;
} else {
DEBUG(10,("SearchRequest: error\n"));
result = map_ldb_error(local_ctx, ldb_ret, ldb_errstring(samdb),
&errstr);
}
done->resultcode = result;
done->errormessage = (errstr?talloc_strdup(done_r, errstr):NULL);
talloc_free(local_ctx);
return ldapsrv_queue_reply_forced(call, done_r);
}
| null | null | 207,250
|
60235456371507544999726672828529582162
| 228
|
CVE-2021-3670 ldap_server: Set timeout on requests based on MaxQueryDuration
BUG: https://bugzilla.samba.org/show_bug.cgi?id=14694
Signed-off-by: Joseph Sutton <[email protected]>
Reviewed-by: Douglas Bagnall <[email protected]>
|
other
|
vim
|
826bfe4bbd7594188e3d74d2539d9707b1c6a14b
| 1
|
win_redr_status(win_T *wp, int ignore_pum UNUSED)
{
int row;
char_u *p;
int len;
int fillchar;
int attr;
int this_ru_col;
static int busy = FALSE;
// It's possible to get here recursively when 'statusline' (indirectly)
// invokes ":redrawstatus". Simply ignore the call then.
if (busy)
return;
busy = TRUE;
row = statusline_row(wp);
wp->w_redr_status = FALSE;
if (wp->w_status_height == 0)
{
// no status line, can only be last window
redraw_cmdline = TRUE;
}
else if (!redrawing()
// don't update status line when popup menu is visible and may be
// drawn over it, unless it will be redrawn later
|| (!ignore_pum && pum_visible()))
{
// Don't redraw right now, do it later.
wp->w_redr_status = TRUE;
}
#ifdef FEAT_STL_OPT
else if (*p_stl != NUL || *wp->w_p_stl != NUL)
{
// redraw custom status line
redraw_custom_statusline(wp);
}
#endif
else
{
fillchar = fillchar_status(&attr, wp);
get_trans_bufname(wp->w_buffer);
p = NameBuff;
len = (int)STRLEN(p);
if (bt_help(wp->w_buffer)
#ifdef FEAT_QUICKFIX
|| wp->w_p_pvw
#endif
|| bufIsChanged(wp->w_buffer)
|| wp->w_buffer->b_p_ro)
*(p + len++) = ' ';
if (bt_help(wp->w_buffer))
{
STRCPY(p + len, _("[Help]"));
len += (int)STRLEN(p + len);
}
#ifdef FEAT_QUICKFIX
if (wp->w_p_pvw)
{
STRCPY(p + len, _("[Preview]"));
len += (int)STRLEN(p + len);
}
#endif
if (bufIsChanged(wp->w_buffer)
#ifdef FEAT_TERMINAL
&& !bt_terminal(wp->w_buffer)
#endif
)
{
STRCPY(p + len, "[+]");
len += 3;
}
if (wp->w_buffer->b_p_ro)
{
STRCPY(p + len, _("[RO]"));
len += (int)STRLEN(p + len);
}
this_ru_col = ru_col - (Columns - wp->w_width);
if (this_ru_col < (wp->w_width + 1) / 2)
this_ru_col = (wp->w_width + 1) / 2;
if (this_ru_col <= 1)
{
p = (char_u *)"<"; // No room for file name!
len = 1;
}
else if (has_mbyte)
{
int clen = 0, i;
// Count total number of display cells.
clen = mb_string2cells(p, -1);
// Find first character that will fit.
// Going from start to end is much faster for DBCS.
for (i = 0; p[i] != NUL && clen >= this_ru_col - 1;
i += (*mb_ptr2len)(p + i))
clen -= (*mb_ptr2cells)(p + i);
len = clen;
if (i > 0)
{
p = p + i - 1;
*p = '<';
++len;
}
}
else if (len > this_ru_col - 1)
{
p += len - (this_ru_col - 1);
*p = '<';
len = this_ru_col - 1;
}
screen_puts(p, row, wp->w_wincol, attr);
screen_fill(row, row + 1, len + wp->w_wincol,
this_ru_col + wp->w_wincol, fillchar, fillchar, attr);
if (get_keymap_str(wp, (char_u *)"<%s>", NameBuff, MAXPATHL)
&& (int)(this_ru_col - len) > (int)(STRLEN(NameBuff) + 1))
screen_puts(NameBuff, row, (int)(this_ru_col - STRLEN(NameBuff)
- 1 + wp->w_wincol), attr);
#ifdef FEAT_CMDL_INFO
win_redr_ruler(wp, TRUE, ignore_pum);
#endif
}
/*
* May need to draw the character below the vertical separator.
*/
if (wp->w_vsep_width != 0 && wp->w_status_height != 0 && redrawing())
{
if (stl_connected(wp))
fillchar = fillchar_status(&attr, wp);
else
fillchar = fillchar_vsep(&attr);
screen_putchar(fillchar, row, W_ENDCOL(wp), attr);
}
busy = FALSE;
}
| null | null | 207,280
|
86191050608755204136835057171061669117
| 144
|
patch 8.2.3487: illegal memory access if buffer name is very long
Problem: Illegal memory access if buffer name is very long.
Solution: Make sure not to go over the end of the buffer.
|
other
|
autotrace
|
e96bffadc25ff0ba0e10745f8012efcc5f920ea9
| 1
|
at_bitmap input_bmp_reader(gchar * filename, at_input_opts_type * opts, at_msg_func msg_func, gpointer msg_data, gpointer user_data)
{
FILE *fd;
unsigned char buffer[64];
int ColormapSize, rowbytes, Maps;
gboolean Grey = FALSE;
unsigned char ColorMap[256][3];
at_bitmap image = at_bitmap_init(0, 0, 0, 1);
unsigned char *image_storage;
at_exception_type exp = at_exception_new(msg_func, msg_data);
char magick[2];
Bitmap_Channel masks[4];
fd = fopen(filename, "rb");
if (!fd) {
LOG("Can't open \"%s\"\n", filename);
at_exception_fatal(&exp, "bmp: cannot open input file");
goto cleanup;
}
/* It is a File. Now is it a Bitmap? Read the shortest possible header. */
if (!ReadOK(fd, magick, 2) ||
!(!strncmp(magick, "BA", 2) ||
!strncmp(magick, "BM", 2) ||
!strncmp(magick, "IC", 2) ||
!strncmp(magick, "PT", 2) ||
!strncmp(magick, "CI", 2) ||
!strncmp(magick, "CP", 2)))
{
LOG("%s is not a valid BMP file", filename);
at_exception_fatal(&exp, "bmp: invalid input file");
goto cleanup;
}
while (!strncmp(magick, "BA", 2))
{
if (!ReadOK(fd, buffer, 12))
{
LOG("%s is not a valid BMP file", filename);
at_exception_fatal(&exp, "bmp: invalid input file");
goto cleanup;
}
if (!ReadOK(fd, magick, 2))
{
LOG("%s is not a valid BMP file", filename);
at_exception_fatal(&exp, "bmp: invalid input file");
goto cleanup;
}
}
if (!ReadOK(fd, buffer, 12))////
{
LOG("%s is not a valid BMP file", filename);
at_exception_fatal(&exp, "bmp: invalid input file");
goto cleanup;
}
/* bring them to the right byteorder. Not too nice, but it should work */
Bitmap_File_Head.bfSize = ToL(&buffer[0x00]);
Bitmap_File_Head.zzHotX = ToS(&buffer[0x04]);
Bitmap_File_Head.zzHotY = ToS(&buffer[0x06]);
Bitmap_File_Head.bfOffs = ToL(&buffer[0x08]);
if (!ReadOK(fd, buffer, 4))
{
LOG("%s is not a valid BMP file", filename);
at_exception_fatal(&exp, "bmp: invalid input file");
goto cleanup;
}
Bitmap_File_Head.biSize = ToL(&buffer[0x00]);
/* What kind of bitmap is it? */
if (Bitmap_File_Head.biSize == 12) { /* OS/2 1.x ? */
if (!ReadOK(fd, buffer, 8)) {
LOG("Error reading BMP file header\n");
at_exception_fatal(&exp, "Error reading BMP file header");
goto cleanup;
}
Bitmap_Head.biWidth = ToS(&buffer[0x00]); /* 12 */
Bitmap_Head.biHeight = ToS(&buffer[0x02]); /* 14 */
Bitmap_Head.biPlanes = ToS(&buffer[0x04]); /* 16 */
Bitmap_Head.biBitCnt = ToS(&buffer[0x06]); /* 18 */
Bitmap_Head.biCompr = 0;
Bitmap_Head.biSizeIm = 0;
Bitmap_Head.biXPels = Bitmap_Head.biYPels = 0;
Bitmap_Head.biClrUsed = 0;
Bitmap_Head.biClrImp = 0;
Bitmap_Head.masks[0] = 0;
Bitmap_Head.masks[1] = 0;
Bitmap_Head.masks[2] = 0;
Bitmap_Head.masks[3] = 0;
memset(masks, 0, sizeof(masks));
Maps = 3;
} else if (Bitmap_File_Head.biSize == 40) { /* Windows 3.x */
if (!ReadOK(fd, buffer, 36))
{
LOG ("Error reading BMP file header\n");
at_exception_fatal(&exp, "Error reading BMP file header");
goto cleanup;
}
Bitmap_Head.biWidth = ToL(&buffer[0x00]); /* 12 */
Bitmap_Head.biHeight = ToL(&buffer[0x04]); /* 16 */
Bitmap_Head.biPlanes = ToS(&buffer[0x08]); /* 1A */
Bitmap_Head.biBitCnt = ToS(&buffer[0x0A]); /* 1C */
Bitmap_Head.biCompr = ToL(&buffer[0x0C]); /* 1E */
Bitmap_Head.biSizeIm = ToL(&buffer[0x10]); /* 22 */
Bitmap_Head.biXPels = ToL(&buffer[0x14]); /* 26 */
Bitmap_Head.biYPels = ToL(&buffer[0x18]); /* 2A */
Bitmap_Head.biClrUsed = ToL(&buffer[0x1C]); /* 2E */
Bitmap_Head.biClrImp = ToL(&buffer[0x20]); /* 32 */
Bitmap_Head.masks[0] = 0;
Bitmap_Head.masks[1] = 0;
Bitmap_Head.masks[2] = 0;
Bitmap_Head.masks[3] = 0;
Maps = 4;
memset(masks, 0, sizeof(masks));
if (Bitmap_Head.biCompr == BI_BITFIELDS)
{
if (!ReadOK(fd, buffer, 3 * sizeof(unsigned long)))
{
LOG("Error reading BMP file header\n");
at_exception_fatal(&exp, "Error reading BMP file header");
goto cleanup;
}
Bitmap_Head.masks[0] = ToL(&buffer[0x00]);
Bitmap_Head.masks[1] = ToL(&buffer[0x04]);
Bitmap_Head.masks[2] = ToL(&buffer[0x08]);
ReadChannelMasks(&Bitmap_Head.masks[0], masks, 3);
}
else if (Bitmap_Head.biCompr == BI_RGB)
{
setMasksDefault(Bitmap_Head.biBitCnt, masks);
}
else if ((Bitmap_Head.biCompr != BI_RLE4) &&
(Bitmap_Head.biCompr != BI_RLE8))
{
/* BI_ALPHABITFIELDS, etc. */
LOG("Unsupported compression in BMP file\n");
at_exception_fatal(&exp, "Unsupported compression in BMP file");
goto cleanup;
}
}
else if (Bitmap_File_Head.biSize >= 56 &&
Bitmap_File_Head.biSize <= 64)
{
/* enhanced Windows format with bit masks */
if (!ReadOK (fd, buffer, Bitmap_File_Head.biSize - 4))
{
LOG("Error reading BMP file header\n");
at_exception_fatal(&exp, "Error reading BMP file header");
goto cleanup;
}
Bitmap_Head.biWidth = ToL(&buffer[0x00]); /* 12 */
Bitmap_Head.biHeight = ToL(&buffer[0x04]); /* 16 */
Bitmap_Head.biPlanes = ToS(&buffer[0x08]); /* 1A */
Bitmap_Head.biBitCnt = ToS(&buffer[0x0A]); /* 1C */
Bitmap_Head.biCompr = ToL(&buffer[0x0C]); /* 1E */
Bitmap_Head.biSizeIm = ToL(&buffer[0x10]); /* 22 */
Bitmap_Head.biXPels = ToL(&buffer[0x14]); /* 26 */
Bitmap_Head.biYPels = ToL(&buffer[0x18]); /* 2A */
Bitmap_Head.biClrUsed = ToL(&buffer[0x1C]); /* 2E */
Bitmap_Head.biClrImp = ToL(&buffer[0x20]); /* 32 */
Bitmap_Head.masks[0] = ToL(&buffer[0x24]); /* 36 */
Bitmap_Head.masks[1] = ToL(&buffer[0x28]); /* 3A */
Bitmap_Head.masks[2] = ToL(&buffer[0x2C]); /* 3E */
Bitmap_Head.masks[3] = ToL(&buffer[0x30]); /* 42 */
Maps = 4;
ReadChannelMasks(&Bitmap_Head.masks[0], masks, 4);
}
else if (Bitmap_File_Head.biSize == 108 ||
Bitmap_File_Head.biSize == 124)
{
/* BMP Version 4 or 5 */
if (!ReadOK(fd, buffer, Bitmap_File_Head.biSize - 4))
{
LOG("Error reading BMP file header\n");
at_exception_fatal(&exp, "Error reading BMP file header");
goto cleanup;
}
Bitmap_Head.biWidth = ToL(&buffer[0x00]);
Bitmap_Head.biHeight = ToL(&buffer[0x04]);
Bitmap_Head.biPlanes = ToS(&buffer[0x08]);
Bitmap_Head.biBitCnt = ToS(&buffer[0x0A]);
Bitmap_Head.biCompr = ToL(&buffer[0x0C]);
Bitmap_Head.biSizeIm = ToL(&buffer[0x10]);
Bitmap_Head.biXPels = ToL(&buffer[0x14]);
Bitmap_Head.biYPels = ToL(&buffer[0x18]);
Bitmap_Head.biClrUsed = ToL(&buffer[0x1C]);
Bitmap_Head.biClrImp = ToL(&buffer[0x20]);
Bitmap_Head.masks[0] = ToL(&buffer[0x24]);
Bitmap_Head.masks[1] = ToL(&buffer[0x28]);
Bitmap_Head.masks[2] = ToL(&buffer[0x2C]);
Bitmap_Head.masks[3] = ToL(&buffer[0x30]);
Maps = 4;
if (Bitmap_Head.biCompr == BI_BITFIELDS)
{
ReadChannelMasks(&Bitmap_Head.masks[0], masks, 4);
}
else if (Bitmap_Head.biCompr == BI_RGB)
{
setMasksDefault(Bitmap_Head.biBitCnt, masks);
}
} else {
LOG("Error reading BMP file header\n");
at_exception_fatal(&exp, "Error reading BMP file header");
goto cleanup;
}
/* Valid options 1, 4, 8, 16, 24, 32 */
/* 16 is awful, we should probably shoot whoever invented it */
switch (Bitmap_Head.biBitCnt)
{
case 1:
case 2:
case 4:
case 8:
case 16:
case 24:
case 32:
break;
default:
LOG("%s is not a valid BMP file", filename);
at_exception_fatal(&exp, "bmp: invalid input file");
goto cleanup;
}
/* There should be some colors used! */
ColormapSize = (Bitmap_File_Head.bfOffs - Bitmap_File_Head.biSize - 14) / Maps;
if ((Bitmap_Head.biClrUsed == 0) &&
(Bitmap_Head.biBitCnt <= 8))
{
ColormapSize = Bitmap_Head.biClrUsed = 1 << Bitmap_Head.biBitCnt;
}
if (ColormapSize > 256)
ColormapSize = 256;
/* Sanity checks */
if (Bitmap_Head.biHeight == 0 ||
Bitmap_Head.biWidth == 0)
{
LOG("%s is not a valid BMP file", filename);
at_exception_fatal(&exp, "bmp: invalid input file");
goto cleanup;
}
/* biHeight may be negative, but -2147483648 is dangerous because:
-2147483648 == -(-2147483648) */
if (Bitmap_Head.biWidth < 0 ||
Bitmap_Head.biHeight == -2147483648)
{
LOG("%s is not a valid BMP file", filename);
at_exception_fatal(&exp, "bmp: invalid input file");
goto cleanup;
}
if (Bitmap_Head.biPlanes != 1)
{
LOG("%s is not a valid BMP file", filename);
at_exception_fatal(&exp, "bmp: invalid input file");
goto cleanup;
}
if (Bitmap_Head.biClrUsed > 256 &&
Bitmap_Head.biBitCnt <= 8)
{
LOG("%s is not a valid BMP file", filename);
at_exception_fatal(&exp, "bmp: invalid input file");
goto cleanup;
}
/* protect against integer overflows caused by malicious BMPs */
/* use divisions in comparisons to avoid type overflows */
if (((unsigned long)Bitmap_Head.biWidth) > (unsigned int)0x7fffffff / Bitmap_Head.biBitCnt ||
((unsigned long)Bitmap_Head.biWidth) > ((unsigned int)0x7fffffff /abs(Bitmap_Head.biHeight)) / 4)
{
LOG("%s is not a valid BMP file", filename);
at_exception_fatal(&exp, "bmp: invalid input file");
goto cleanup;
}
/* Windows and OS/2 declare filler so that rows are a multiple of
* word length (32 bits == 4 bytes)
*/
unsigned long overflowTest = Bitmap_Head.biWidth * Bitmap_Head.biBitCnt;
if (overflowTest / Bitmap_Head.biWidth != Bitmap_Head.biBitCnt) {
LOG("Error reading BMP file header. Width is too large\n");
at_exception_fatal(&exp, "Error reading BMP file header. Width is too large");
goto cleanup;
}
rowbytes = ((Bitmap_Head.biWidth * Bitmap_Head.biBitCnt - 1) / 32) * 4 + 4;
#ifdef DEBUG
printf("\nSize: %u, Colors: %u, Bits: %u, Width: %u, Height: %u, Comp: %u, Zeile: %u\n", Bitmap_File_Head.bfSize, Bitmap_Head.biClrUsed, Bitmap_Head.biBitCnt, Bitmap_Head.biWidth, Bitmap_Head.biHeight, Bitmap_Head.biCompr, rowbytes);
#endif
if (Bitmap_Head.biBitCnt <= 8)
{
#ifdef DEBUG
printf("Colormap read\n");
#endif
/* Get the Colormap */
if (!ReadColorMap(fd, ColorMap, ColormapSize, Maps, &Grey, &exp))
goto cleanup;
}
fseek(fd, Bitmap_File_Head.bfOffs, SEEK_SET);
/* Get the Image and return the ID or -1 on error */
image_storage = ReadImage(fd,
Bitmap_Head.biWidth, Bitmap_Head.biHeight,
ColorMap,
Bitmap_Head.biClrUsed,
Bitmap_Head.biBitCnt, Bitmap_Head.biCompr, rowbytes,
Grey,
masks,
&exp);
image = at_bitmap_init(image_storage, (unsigned short)Bitmap_Head.biWidth, (unsigned short)Bitmap_Head.biHeight, Grey ? 1 : 3);
cleanup:
fclose(fd);
return (image);
}
| null | null | 207,461
|
311893824732578184343032245071313510065
| 354
|
input-bmp: Increase header buffer in some cases
Signed-off-by: Peter Lemenkov <[email protected]>
|
other
|
rizin
|
aa6917772d2f32e5a7daab25a46c72df0b5ea406
| 1
|
static const ut8 *parse_die(const ut8 *buf, const ut8 *buf_end, RzBinDwarfDebugInfo *info, RzBinDwarfAbbrevDecl *abbrev,
RzBinDwarfCompUnitHdr *hdr, RzBinDwarfDie *die, const ut8 *debug_str, size_t debug_str_len, bool big_endian) {
size_t i;
const char *comp_dir = NULL;
ut64 line_info_offset = UT64_MAX;
for (i = 0; i < abbrev->count - 1; i++) {
memset(&die->attr_values[i], 0, sizeof(die->attr_values[i]));
buf = parse_attr_value(buf, buf_end - buf, &abbrev->defs[i],
&die->attr_values[i], hdr, debug_str, debug_str_len, big_endian);
RzBinDwarfAttrValue *attribute = &die->attr_values[i];
if (attribute->attr_name == DW_AT_comp_dir && (attribute->attr_form == DW_FORM_strp || attribute->attr_form == DW_FORM_string) && attribute->string.content) {
comp_dir = attribute->string.content;
}
if (attribute->attr_name == DW_AT_stmt_list) {
if (attribute->kind == DW_AT_KIND_CONSTANT) {
line_info_offset = attribute->uconstant;
} else if (attribute->kind == DW_AT_KIND_REFERENCE) {
line_info_offset = attribute->reference;
}
}
die->count++;
}
// If this is a compilation unit dir attribute, we want to cache it so the line info parsing
// which will need this info can quickly look it up.
if (comp_dir && line_info_offset != UT64_MAX) {
char *name = strdup(comp_dir);
if (name) {
if (!ht_up_insert(info->line_info_offset_comp_dir, line_info_offset, name)) {
free(name);
}
}
}
return buf;
}
| null | null | 207,520
|
275181739878774751439131693186874981050
| 39
|
Fix oob write for dwarf with abbrev with count 0 (Fix #2083) (#2086)
|
other
|
libtiff
|
f1b94e8a3ba49febdd3361c0214a1d1149251577
| 1
|
cpTags(TIFF* in, TIFF* out)
{
struct cpTag *p;
for (p = tags; p < &tags[NTAGS]; p++)
cpTag(in, out, p->tag, p->count, p->type);
}
| null | null | 207,644
|
89435351062227040282236387912359292339
| 6
|
only read/write TIFFTAG_GROUP3OPTIONS or TIFFTAG_GROUP4OPTIONS if compression is COMPRESSION_CCITTFAX3 or COMPRESSION_CCITTFAX4
|
other
|
EternalTerminal
|
900348bb8bc96e1c7ba4888ac8480f643c43d3c3
| 1
|
TerminalUserInfo UserTerminalRouter::getInfoForId(const string &id) {
auto it = idInfoMap.find(id);
if (it == idInfoMap.end()) {
STFATAL << " Tried to read from an id that no longer exists";
}
return it->second;
}
| null | null | 207,700
|
8175819761864654166650714063570358802
| 7
|
red fixes (#468)
* red fixes
* remove magic number
|
other
|
EternalTerminal
|
900348bb8bc96e1c7ba4888ac8480f643c43d3c3
| 1
|
set<int> PipeSocketHandler::listen(const SocketEndpoint& endpoint) {
lock_guard<std::recursive_mutex> guard(globalMutex);
string pipePath = endpoint.name();
if (pipeServerSockets.find(pipePath) != pipeServerSockets.end()) {
throw runtime_error("Tried to listen twice on the same path");
}
sockaddr_un local;
int fd = socket(AF_UNIX, SOCK_STREAM, 0);
FATAL_FAIL(fd);
initServerSocket(fd);
local.sun_family = AF_UNIX; /* local is declared before socket() ^ */
strcpy(local.sun_path, pipePath.c_str());
unlink(local.sun_path);
FATAL_FAIL(::bind(fd, (struct sockaddr*)&local, sizeof(sockaddr_un)));
::listen(fd, 5);
#ifndef WIN32
FATAL_FAIL(::chmod(local.sun_path, S_IRUSR | S_IWUSR | S_IXUSR));
#endif
pipeServerSockets[pipePath] = set<int>({fd});
return pipeServerSockets[pipePath];
}
| null | null | 207,703
|
213532589714760033098624205385113026093
| 26
|
red fixes (#468)
* red fixes
* remove magic number
|
other
|
vim
|
e98c88c44c308edaea5994b8ad4363e65030968c
| 1
|
display_dollar(colnr_T col)
{
colnr_T save_col;
if (!redrawing())
return;
cursor_off();
save_col = curwin->w_cursor.col;
curwin->w_cursor.col = col;
if (has_mbyte)
{
char_u *p;
// If on the last byte of a multi-byte move to the first byte.
p = ml_get_curline();
curwin->w_cursor.col -= (*mb_head_off)(p, p + col);
}
curs_columns(FALSE); // recompute w_wrow and w_wcol
if (curwin->w_wcol < curwin->w_width)
{
edit_putchar('$', FALSE);
dollar_vcol = curwin->w_virtcol;
}
curwin->w_cursor.col = save_col;
}
| null | null | 207,719
|
265859281386315904319491494691513391643
| 26
|
patch 9.0.0218: reading before the start of the line
Problem: Reading before the start of the line.
Solution: When displaying "$" check the column is not negative.
|
other
|
linux
|
9d2231c5d74e13b2a0546fee6737ee4446017903
| 1
|
static size_t copy_page_to_iter_pipe(struct page *page, size_t offset, size_t bytes,
struct iov_iter *i)
{
struct pipe_inode_info *pipe = i->pipe;
struct pipe_buffer *buf;
unsigned int p_tail = pipe->tail;
unsigned int p_mask = pipe->ring_size - 1;
unsigned int i_head = i->head;
size_t off;
if (unlikely(bytes > i->count))
bytes = i->count;
if (unlikely(!bytes))
return 0;
if (!sanity(i))
return 0;
off = i->iov_offset;
buf = &pipe->bufs[i_head & p_mask];
if (off) {
if (offset == off && buf->page == page) {
/* merge with the last one */
buf->len += bytes;
i->iov_offset += bytes;
goto out;
}
i_head++;
buf = &pipe->bufs[i_head & p_mask];
}
if (pipe_full(i_head, p_tail, pipe->max_usage))
return 0;
buf->ops = &page_cache_pipe_buf_ops;
get_page(page);
buf->page = page;
buf->offset = offset;
buf->len = bytes;
pipe->head = i_head + 1;
i->iov_offset = offset + bytes;
i->head = i_head;
out:
i->count -= bytes;
return bytes;
}
| null | null | 207,753
|
166347789945326473978894278006579209282
| 47
|
lib/iov_iter: initialize "flags" in new pipe_buffer
The functions copy_page_to_iter_pipe() and push_pipe() can both
allocate a new pipe_buffer, but the "flags" member initializer is
missing.
Fixes: 241699cd72a8 ("new iov_iter flavour: pipe-backed")
To: Alexander Viro <[email protected]>
To: [email protected]
To: [email protected]
Cc: [email protected]
Signed-off-by: Max Kellermann <[email protected]>
Signed-off-by: Al Viro <[email protected]>
|
other
|
linux
|
9d2231c5d74e13b2a0546fee6737ee4446017903
| 1
|
static size_t push_pipe(struct iov_iter *i, size_t size,
int *iter_headp, size_t *offp)
{
struct pipe_inode_info *pipe = i->pipe;
unsigned int p_tail = pipe->tail;
unsigned int p_mask = pipe->ring_size - 1;
unsigned int iter_head;
size_t off;
ssize_t left;
if (unlikely(size > i->count))
size = i->count;
if (unlikely(!size))
return 0;
left = size;
data_start(i, &iter_head, &off);
*iter_headp = iter_head;
*offp = off;
if (off) {
left -= PAGE_SIZE - off;
if (left <= 0) {
pipe->bufs[iter_head & p_mask].len += size;
return size;
}
pipe->bufs[iter_head & p_mask].len = PAGE_SIZE;
iter_head++;
}
while (!pipe_full(iter_head, p_tail, pipe->max_usage)) {
struct pipe_buffer *buf = &pipe->bufs[iter_head & p_mask];
struct page *page = alloc_page(GFP_USER);
if (!page)
break;
buf->ops = &default_pipe_buf_ops;
buf->page = page;
buf->offset = 0;
buf->len = min_t(ssize_t, left, PAGE_SIZE);
left -= buf->len;
iter_head++;
pipe->head = iter_head;
if (left == 0)
return size;
}
return size - left;
}
| null | null | 207,754
|
158977810766051483126143018257673420675
| 47
|
lib/iov_iter: initialize "flags" in new pipe_buffer
The functions copy_page_to_iter_pipe() and push_pipe() can both
allocate a new pipe_buffer, but the "flags" member initializer is
missing.
Fixes: 241699cd72a8 ("new iov_iter flavour: pipe-backed")
To: Alexander Viro <[email protected]>
To: [email protected]
To: [email protected]
Cc: [email protected]
Signed-off-by: Max Kellermann <[email protected]>
Signed-off-by: Al Viro <[email protected]>
|
other
|
php-src
|
095cbc48a8f0090f3b0abc6155f2b61943c9eafb
| 1
|
PHP_FUNCTION(openssl_encrypt)
{
zend_bool raw_output = 0;
char *data, *method, *password, *iv = "";
int data_len, method_len, password_len, iv_len = 0, max_iv_len;
const EVP_CIPHER *cipher_type;
EVP_CIPHER_CTX cipher_ctx;
int i, outlen, keylen;
unsigned char *outbuf, *key;
zend_bool free_iv;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sss|bs", &data, &data_len, &method, &method_len, &password, &password_len, &raw_output, &iv, &iv_len) == FAILURE) {
return;
}
cipher_type = EVP_get_cipherbyname(method);
if (!cipher_type) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown cipher algorithm");
RETURN_FALSE;
}
keylen = EVP_CIPHER_key_length(cipher_type);
if (keylen > password_len) {
key = emalloc(keylen);
memset(key, 0, keylen);
memcpy(key, password, password_len);
} else {
key = (unsigned char*)password;
}
max_iv_len = EVP_CIPHER_iv_length(cipher_type);
if (iv_len <= 0 && max_iv_len > 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Using an empty Initialization Vector (iv) is potentially insecure and not recommended");
}
free_iv = php_openssl_validate_iv(&iv, &iv_len, max_iv_len TSRMLS_CC);
outlen = data_len + EVP_CIPHER_block_size(cipher_type);
outbuf = emalloc(outlen + 1);
EVP_EncryptInit(&cipher_ctx, cipher_type, NULL, NULL);
if (password_len > keylen) {
EVP_CIPHER_CTX_set_key_length(&cipher_ctx, password_len);
}
EVP_EncryptInit_ex(&cipher_ctx, NULL, NULL, key, (unsigned char *)iv);
EVP_EncryptUpdate(&cipher_ctx, outbuf, &i, (unsigned char *)data, data_len);
outlen = i;
if (EVP_EncryptFinal(&cipher_ctx, (unsigned char *)outbuf + i, &i)) {
outlen += i;
if (raw_output) {
outbuf[outlen] = '\0';
RETVAL_STRINGL((char *)outbuf, outlen, 0);
} else {
int base64_str_len;
char *base64_str;
base64_str = (char*)php_base64_encode(outbuf, outlen, &base64_str_len);
efree(outbuf);
RETVAL_STRINGL(base64_str, base64_str_len, 0);
}
} else {
efree(outbuf);
RETVAL_FALSE;
}
if (key != (unsigned char*)password) {
efree(key);
}
if (free_iv) {
efree(iv);
}
EVP_CIPHER_CTX_cleanup(&cipher_ctx);
}
| null | null | 207,755
|
69106918490575140688987216670085944855
| 70
|
Fix segfault in older versions of OpenSSL (before 0.9.8i)
|
other
|
nbdkit
|
09a13dafb7bb3a38ab52eb5501cba786365ba7fd
| 1
|
negotiate_handshake_newstyle_options (void)
{
GET_CONN;
struct nbd_new_option new_option;
size_t nr_options;
bool list_seen = false;
uint64_t version;
uint32_t option;
uint32_t optlen;
struct nbd_export_name_option_reply handshake_finish;
const char *optname;
uint64_t exportsize;
struct backend *b;
for (nr_options = MAX_NR_OPTIONS; nr_options > 0; --nr_options) {
CLEANUP_FREE char *data = NULL;
if (conn_recv_full (&new_option, sizeof new_option,
"reading option: conn->recv: %m") == -1)
return -1;
version = be64toh (new_option.version);
if (version != NBD_NEW_VERSION) {
nbdkit_error ("unknown option version %" PRIx64
", expecting %" PRIx64,
version, NBD_NEW_VERSION);
return -1;
}
/* There is a maximum option length we will accept, regardless
* of the option type.
*/
optlen = be32toh (new_option.optlen);
if (optlen > MAX_REQUEST_SIZE) {
nbdkit_error ("client option data too long (%" PRIu32 ")", optlen);
return -1;
}
data = malloc (optlen + 1); /* Allowing a trailing NUL helps some uses */
if (data == NULL) {
nbdkit_error ("malloc: %m");
return -1;
}
option = be32toh (new_option.option);
optname = name_of_nbd_opt (option);
/* If the client lacks fixed newstyle support, it should only send
* NBD_OPT_EXPORT_NAME.
*/
if (!(conn->cflags & NBD_FLAG_FIXED_NEWSTYLE) &&
option != NBD_OPT_EXPORT_NAME) {
if (send_newstyle_option_reply (option, NBD_REP_ERR_INVALID))
return -1;
continue;
}
/* In --tls=require / FORCEDTLS mode the only options allowed
* before TLS negotiation are NBD_OPT_ABORT and NBD_OPT_STARTTLS.
*/
if (tls == 2 && !conn->using_tls &&
!(option == NBD_OPT_ABORT || option == NBD_OPT_STARTTLS)) {
if (send_newstyle_option_reply (option, NBD_REP_ERR_TLS_REQD))
return -1;
continue;
}
switch (option) {
case NBD_OPT_EXPORT_NAME:
if (conn_recv_full (data, optlen,
"read: %s: %m", name_of_nbd_opt (option)) == -1)
return -1;
if (check_export_name (option, data, optlen, optlen) == -1)
return -1;
/* We have to finish the handshake by sending handshake_finish.
* On failure, we have to disconnect.
*/
if (finish_newstyle_options (&exportsize, data, optlen) == -1)
return -1;
memset (&handshake_finish, 0, sizeof handshake_finish);
handshake_finish.exportsize = htobe64 (exportsize);
handshake_finish.eflags = htobe16 (conn->eflags);
if (conn->send (&handshake_finish,
(conn->cflags & NBD_FLAG_NO_ZEROES)
? offsetof (struct nbd_export_name_option_reply, zeroes)
: sizeof handshake_finish, 0) == -1) {
nbdkit_error ("write: %s: %m", optname);
return -1;
}
break;
case NBD_OPT_ABORT:
if (send_newstyle_option_reply (option, NBD_REP_ACK) == -1)
return -1;
debug ("client sent %s to abort the connection",
name_of_nbd_opt (option));
return -1;
case NBD_OPT_LIST:
if (optlen != 0) {
if (send_newstyle_option_reply (option, NBD_REP_ERR_INVALID)
== -1)
return -1;
if (conn_recv_full (data, optlen,
"read: %s: %m", name_of_nbd_opt (option)) == -1)
return -1;
continue;
}
if (list_seen) {
debug ("newstyle negotiation: %s: export list already advertised",
name_of_nbd_opt (option));
if (send_newstyle_option_reply (option, NBD_REP_ERR_INVALID) == -1)
return -1;
continue;
}
else {
/* Send back the exportname list. */
debug ("newstyle negotiation: %s: advertising exports",
name_of_nbd_opt (option));
if (send_newstyle_option_reply_exportnames (option, &nr_options) == -1)
return -1;
list_seen = true;
}
break;
case NBD_OPT_STARTTLS:
if (optlen != 0) {
if (send_newstyle_option_reply (option, NBD_REP_ERR_INVALID)
== -1)
return -1;
if (conn_recv_full (data, optlen,
"read: %s: %m", name_of_nbd_opt (option)) == -1)
return -1;
continue;
}
if (tls == 0) { /* --tls=off (NOTLS mode). */
#ifdef HAVE_GNUTLS
#define NO_TLS_REPLY NBD_REP_ERR_POLICY
#else
#define NO_TLS_REPLY NBD_REP_ERR_UNSUP
#endif
if (send_newstyle_option_reply (option, NO_TLS_REPLY) == -1)
return -1;
}
else /* --tls=on or --tls=require */ {
/* We can't upgrade to TLS twice on the same connection. */
if (conn->using_tls) {
if (send_newstyle_option_reply (option, NBD_REP_ERR_INVALID) == -1)
return -1;
continue;
}
/* We have to send the (unencrypted) reply before starting
* the handshake.
*/
if (send_newstyle_option_reply (option, NBD_REP_ACK) == -1)
return -1;
/* Upgrade the connection to TLS. Also performs access control. */
if (crypto_negotiate_tls (conn->sockin, conn->sockout) == -1)
return -1;
conn->using_tls = true;
debug ("using TLS on this connection");
/* Wipe out any cached default export name. */
for_each_backend (b) {
free (conn->default_exportname[b->i]);
conn->default_exportname[b->i] = NULL;
}
}
break;
case NBD_OPT_INFO:
case NBD_OPT_GO:
if (conn_recv_full (data, optlen, "read: %s: %m", optname) == -1)
return -1;
if (optlen < 6) { /* 32 bit export length + 16 bit nr info */
debug ("newstyle negotiation: %s option length < 6", optname);
if (send_newstyle_option_reply (option, NBD_REP_ERR_INVALID)
== -1)
return -1;
continue;
}
{
uint32_t exportnamelen;
uint16_t nrinfos;
uint16_t info;
size_t i;
/* Validate the name length and number of INFO requests. */
memcpy (&exportnamelen, &data[0], 4);
exportnamelen = be32toh (exportnamelen);
if (exportnamelen > optlen-6 /* NB optlen >= 6, see above */) {
debug ("newstyle negotiation: %s: export name too long", optname);
if (send_newstyle_option_reply (option, NBD_REP_ERR_INVALID)
== -1)
return -1;
continue;
}
memcpy (&nrinfos, &data[exportnamelen+4], 2);
nrinfos = be16toh (nrinfos);
if (optlen != 4 + exportnamelen + 2 + 2*nrinfos) {
debug ("newstyle negotiation: %s: "
"number of information requests incorrect", optname);
if (send_newstyle_option_reply (option, NBD_REP_ERR_INVALID)
== -1)
return -1;
continue;
}
/* As with NBD_OPT_EXPORT_NAME we print the export name and
* save it in the connection. If an earlier
* NBD_OPT_SET_META_CONTEXT used an export name, it must match
* or else we drop the support for that context.
*/
if (check_export_name (option, &data[4], exportnamelen,
optlen - 6) == -1) {
if (send_newstyle_option_reply (option, NBD_REP_ERR_INVALID)
== -1)
return -1;
continue;
}
/* The spec is confusing, but it is required that we send back
* NBD_INFO_EXPORT, even if the client did not request it!
* qemu client in particular does not request this, but will
* fail if we don't send it. Note that if .open fails, but we
* succeed at .close, then we merely return an error to the
* client and let them try another NBD_OPT, rather than
* disconnecting.
*/
if (finish_newstyle_options (&exportsize,
&data[4], exportnamelen) == -1) {
if (conn->top_context) {
if (backend_finalize (conn->top_context) == -1)
return -1;
backend_close (conn->top_context);
conn->top_context = NULL;
}
if (send_newstyle_option_reply (option, NBD_REP_ERR_UNKNOWN) == -1)
return -1;
continue;
}
if (send_newstyle_option_reply_info_export (option,
NBD_REP_INFO,
NBD_INFO_EXPORT,
exportsize) == -1)
return -1;
/* For now we send NBD_INFO_NAME and NBD_INFO_DESCRIPTION if
* requested, and ignore all other info requests (including
* NBD_INFO_EXPORT if it was requested, because we replied
* already above).
*/
for (i = 0; i < nrinfos; ++i) {
memcpy (&info, &data[4 + exportnamelen + 2 + i*2], 2);
info = be16toh (info);
switch (info) {
case NBD_INFO_EXPORT: /* ignore - reply sent above */ break;
case NBD_INFO_NAME:
{
const char *name = &data[4];
size_t namelen = exportnamelen;
if (exportnamelen == 0) {
name = backend_default_export (top, read_only);
if (!name) {
debug ("newstyle negotiation: %s: "
"NBD_INFO_NAME: no name to send", optname);
break;
}
namelen = -1;
}
if (send_newstyle_option_reply_info_str (option,
NBD_REP_INFO,
NBD_INFO_NAME,
name, namelen) == -1)
return -1;
}
break;
case NBD_INFO_DESCRIPTION:
{
const char *desc = backend_export_description (conn->top_context);
if (!desc) {
debug ("newstyle negotiation: %s: "
"NBD_INFO_DESCRIPTION: no description to send",
optname);
break;
}
if (send_newstyle_option_reply_info_str (option,
NBD_REP_INFO,
NBD_INFO_DESCRIPTION,
desc, -1) == -1)
return -1;
}
break;
default:
debug ("newstyle negotiation: %s: "
"ignoring NBD_INFO_* request %u (%s)",
optname, (unsigned) info, name_of_nbd_info (info));
break;
}
}
}
/* Unlike NBD_OPT_EXPORT_NAME, NBD_OPT_GO sends back an ACK
* or ERROR packet. If this was NBD_OPT_LIST, call .close.
*/
if (send_newstyle_option_reply (option, NBD_REP_ACK) == -1)
return -1;
if (option == NBD_OPT_INFO) {
if (backend_finalize (conn->top_context) == -1)
return -1;
backend_close (conn->top_context);
conn->top_context = NULL;
}
break;
case NBD_OPT_STRUCTURED_REPLY:
if (optlen != 0) {
if (send_newstyle_option_reply (option, NBD_REP_ERR_INVALID)
== -1)
return -1;
if (conn_recv_full (data, optlen,
"read: %s: %m", name_of_nbd_opt (option)) == -1)
return -1;
continue;
}
debug ("newstyle negotiation: %s: client requested structured replies",
name_of_nbd_opt (option));
if (no_sr) {
/* Must fail with ERR_UNSUP for qemu 4.2 to remain happy;
* but failing with ERR_POLICY would have been nicer.
*/
if (send_newstyle_option_reply (option, NBD_REP_ERR_UNSUP) == -1)
return -1;
debug ("newstyle negotiation: %s: structured replies are disabled",
name_of_nbd_opt (option));
break;
}
if (send_newstyle_option_reply (option, NBD_REP_ACK) == -1)
return -1;
conn->structured_replies = true;
break;
case NBD_OPT_LIST_META_CONTEXT:
case NBD_OPT_SET_META_CONTEXT:
{
uint32_t opt_index;
uint32_t exportnamelen;
uint32_t nr_queries;
uint32_t querylen;
const char *what;
if (conn_recv_full (data, optlen, "read: %s: %m", optname) == -1)
return -1;
/* Note that we support base:allocation whether or not the plugin
* supports can_extents.
*/
if (!conn->structured_replies) {
if (send_newstyle_option_reply (option, NBD_REP_ERR_INVALID)
== -1)
return -1;
continue;
}
/* Minimum length of the option payload is:
* 32 bit export name length followed by empty export name
* + 32 bit number of queries followed by no queries
* = 8 bytes.
*/
what = "optlen < 8";
if (optlen < 8) {
opt_meta_invalid_option_len:
debug ("newstyle negotiation: %s: invalid option length: %s",
optname, what);
if (send_newstyle_option_reply (option, NBD_REP_ERR_INVALID)
== -1)
return -1;
continue;
}
memcpy (&exportnamelen, &data[0], 4);
exportnamelen = be32toh (exportnamelen);
what = "validating export name";
if (check_export_name (option, &data[4], exportnamelen,
optlen - 8) == -1)
goto opt_meta_invalid_option_len;
/* Remember the export name: the NBD spec says that if the client
* later uses NBD_OPT_GO on a different export, then the context
* returned here is not usable.
*/
if (option == NBD_OPT_SET_META_CONTEXT) {
conn->exportname_from_set_meta_context =
strndup (&data[4], exportnamelen);
if (conn->exportname_from_set_meta_context == NULL) {
nbdkit_error ("malloc: %m");
return -1;
}
}
opt_index = 4 + exportnamelen;
/* Read the number of queries. */
what = "reading number of queries";
if (opt_index+4 > optlen)
goto opt_meta_invalid_option_len;
memcpy (&nr_queries, &data[opt_index], 4);
nr_queries = be32toh (nr_queries);
opt_index += 4;
/* for LIST: nr_queries == 0 means return all meta contexts
* for SET: nr_queries == 0 means reset all contexts
*/
debug ("newstyle negotiation: %s: %s count: %d", optname,
option == NBD_OPT_LIST_META_CONTEXT ? "query" : "set",
nr_queries);
if (option == NBD_OPT_SET_META_CONTEXT)
conn->meta_context_base_allocation = false;
if (nr_queries == 0) {
if (option == NBD_OPT_LIST_META_CONTEXT) {
if (send_newstyle_option_reply_meta_context (option,
NBD_REP_META_CONTEXT,
0, "base:allocation")
== -1)
return -1;
}
if (send_newstyle_option_reply (option, NBD_REP_ACK) == -1)
return -1;
}
else {
/* Read and answer each query. */
while (nr_queries > 0) {
what = "reading query string length";
if (opt_index+4 > optlen)
goto opt_meta_invalid_option_len;
memcpy (&querylen, &data[opt_index], 4);
querylen = be32toh (querylen);
opt_index += 4;
what = "reading query string";
if (check_string (option, &data[opt_index], querylen,
optlen - opt_index, "meta context query") == -1)
goto opt_meta_invalid_option_len;
debug ("newstyle negotiation: %s: %s %.*s",
optname,
option == NBD_OPT_LIST_META_CONTEXT ? "query" : "set",
(int) querylen, &data[opt_index]);
/* For LIST, "base:" returns all supported contexts in the
* base namespace. We only support "base:allocation".
*/
if (option == NBD_OPT_LIST_META_CONTEXT &&
querylen == 5 &&
strncmp (&data[opt_index], "base:", 5) == 0) {
if (send_newstyle_option_reply_meta_context
(option, NBD_REP_META_CONTEXT,
0, "base:allocation") == -1)
return -1;
}
/* "base:allocation" requested by name. */
else if (querylen == 15 &&
strncmp (&data[opt_index], "base:allocation", 15) == 0) {
if (send_newstyle_option_reply_meta_context
(option, NBD_REP_META_CONTEXT,
option == NBD_OPT_SET_META_CONTEXT
? base_allocation_id : 0,
"base:allocation") == -1)
return -1;
if (option == NBD_OPT_SET_META_CONTEXT)
conn->meta_context_base_allocation = true;
}
/* Every other query must be ignored. */
opt_index += querylen;
nr_queries--;
}
if (send_newstyle_option_reply (option, NBD_REP_ACK) == -1)
return -1;
}
debug ("newstyle negotiation: %s: reply complete", optname);
}
break;
default:
/* Unknown option. */
if (send_newstyle_option_reply (option, NBD_REP_ERR_UNSUP) == -1)
return -1;
if (conn_recv_full (data, optlen,
"reading unknown option data: conn->recv: %m") == -1)
return -1;
}
/* Note, since it's not very clear from the protocol doc, that the
* client must send NBD_OPT_EXPORT_NAME or NBD_OPT_GO last, and
* that ends option negotiation.
*/
if (option == NBD_OPT_EXPORT_NAME || option == NBD_OPT_GO)
break;
}
if (nr_options == 0) {
nbdkit_error ("client spent too much time negotiating without selecting "
"an export");
return -1;
}
/* In --tls=require / FORCEDTLS mode, we must have upgraded to TLS
* by the time we finish option negotiation. If not, give up.
*/
if (tls == 2 && !conn->using_tls) {
nbdkit_error ("non-TLS client tried to connect in --tls=require mode");
return -1;
}
return 0;
}
| null | null | 207,762
|
262726525276367986643973964343375138207
| 535
|
server: CVE-2021-3716 reset structured replies on starttls
https://nostarttls.secvuln.info/ pointed out a series of CVEs in
common implementation flaw in various SMTP and IMAP clients and
servers, all with a common thread of improperly caching plaintext
state across the STARTTLS encryption boundary; and recommended that
other protocols with a STARTTLS operation perform a similar audit.
It turns out that nbdkit has the same vulnerability in regards to the
NBD protocol: when nbdkit is run in opportunistic TLS mode, an
attacker is able to inject a plaintext NBD_OPT_STRUCTURED_REPLY before
proxying everything else a client sends to the server; if the server
then acts on that plaintext request (as nbdkit did before this patch),
then the server ends up sending structured replies to at least
NBD_CMD_READ, even though the client was assuming that the transition
to TLS has ruled out a MitM attack.
On the bright side, nbdkit's behavior on a second
NBD_OPT_STRUCTURED_REPLY was to still reply with success, so a client
that always requests structured replies after starting TLS sees no
difference in behavior (that is, qemu 2.12 and later are immune) (had
nbdkit given an error to the second request, that may have caused
confusion to more clients). And there is always the mitigation of
using --tls=require, which lets nbdkit reject the MitM message
pre-encryption. However, nbd-client 3.15 to the present do not
understand structured replies, and I have confirmed that a MitM
attacker can thus cause a denial-of-service attack that does not
trigger until the client does its first encrypted NBD_CMD_READ.
The NBD spec has been recently tightened to declare the nbdkit
behavior to be a security hole:
https://github.com/NetworkBlockDevice/nbd/commit/77e55378096aa
|
other
|
radare2
|
2b77b277d67ce061ee6ef839e7139ebc2103c1e3
| 1
|
static RList *create_cache_bins(RBinFile *bf, RDyldCache *cache) {
RList *bins = r_list_newf ((RListFree)free_bin);
ut16 *depArray = NULL;
cache_imgxtr_t *extras = NULL;
if (!bins) {
return NULL;
}
char *target_libs = NULL;
RList *target_lib_names = NULL;
int *deps = NULL;
target_libs = r_sys_getenv ("R_DYLDCACHE_FILTER");
if (target_libs) {
target_lib_names = r_str_split_list (target_libs, ":", 0);
if (!target_lib_names) {
r_list_free (bins);
return NULL;
}
deps = R_NEWS0 (int, cache->hdr->imagesCount);
if (!deps) {
r_list_free (bins);
r_list_free (target_lib_names);
return NULL;
}
}
ut32 i;
for (i = 0; i < cache->n_hdr; i++) {
cache_hdr_t *hdr = &cache->hdr[i];
ut64 hdr_offset = cache->hdr_offset[i];
ut32 maps_index = cache->maps_index[i];
cache_img_t *img = read_cache_images (cache->buf, hdr, hdr_offset);
if (!img) {
goto next;
}
ut32 j;
if (target_libs) {
HtPU *path_to_idx = NULL;
if (cache->accel) {
depArray = R_NEWS0 (ut16, cache->accel->depListCount);
if (!depArray) {
goto next;
}
if (r_buf_fread_at (cache->buf, cache->accel->depListOffset, (ut8*) depArray, "s", cache->accel->depListCount) != cache->accel->depListCount * 2) {
goto next;
}
extras = read_cache_imgextra (cache->buf, hdr, cache->accel);
if (!extras) {
goto next;
}
} else {
path_to_idx = create_path_to_index (cache->buf, img, hdr);
}
for (j = 0; j < hdr->imagesCount; j++) {
bool printing = !deps[j];
char *lib_name = get_lib_name (cache->buf, &img[j]);
if (!lib_name) {
break;
}
if (strstr (lib_name, "libobjc.A.dylib")) {
deps[j]++;
}
if (!r_list_find (target_lib_names, lib_name, string_contains)) {
R_FREE (lib_name);
continue;
}
if (printing) {
eprintf ("FILTER: %s\n", lib_name);
}
R_FREE (lib_name);
deps[j]++;
if (extras && depArray) {
ut32 k;
for (k = extras[j].dependentsStartArrayIndex; depArray[k] != 0xffff; k++) {
ut16 dep_index = depArray[k] & 0x7fff;
deps[dep_index]++;
char *dep_name = get_lib_name (cache->buf, &img[dep_index]);
if (!dep_name) {
break;
}
if (printing) {
eprintf ("-> %s\n", dep_name);
}
free (dep_name);
}
} else if (path_to_idx) {
carve_deps_at_address (cache, img, path_to_idx, img[j].address, deps, printing);
}
}
ht_pu_free (path_to_idx);
R_FREE (depArray);
R_FREE (extras);
}
for (j = 0; j < hdr->imagesCount; j++) {
if (deps && !deps[j]) {
continue;
}
ut64 pa = va2pa (img[j].address, hdr->mappingCount, &cache->maps[maps_index], cache->buf, 0, NULL, NULL);
if (pa == UT64_MAX) {
continue;
}
ut8 magicbytes[4];
r_buf_read_at (cache->buf, pa, magicbytes, 4);
int magic = r_read_le32 (magicbytes);
switch (magic) {
case MH_MAGIC_64:
{
char file[256];
RDyldBinImage *bin = R_NEW0 (RDyldBinImage);
if (!bin) {
goto next;
}
bin->header_at = pa;
bin->hdr_offset = hdr_offset;
bin->symbols_off = resolve_symbols_off (cache, pa);
bin->va = img[j].address;
if (r_buf_read_at (cache->buf, img[j].pathFileOffset, (ut8*) &file, sizeof (file)) == sizeof (file)) {
file[255] = 0;
char *last_slash = strrchr (file, '/');
if (last_slash && *last_slash) {
if (last_slash > file) {
char *scan = last_slash - 1;
while (scan > file && *scan != '/') {
scan--;
}
if (*scan == '/') {
bin->file = strdup (scan + 1);
} else {
bin->file = strdup (last_slash + 1);
}
} else {
bin->file = strdup (last_slash + 1);
}
} else {
bin->file = strdup (file);
}
}
r_list_append (bins, bin);
break;
}
default:
eprintf ("Unknown sub-bin\n");
break;
}
}
next:
R_FREE (depArray);
R_FREE (extras);
R_FREE (img);
}
if (r_list_empty (bins)) {
r_list_free (bins);
bins = NULL;
}
R_FREE (deps);
R_FREE (target_libs);
r_list_free (target_lib_names);
return bins;
}
| null | null | 207,780
|
180694851627521696664028718644842779676
| 167
|
Fix oobread in dyldcache ##crash
* Reported by @hdthky via huntr.dev
* Reproducers: poc1
* BountyID: 8ae2c61a-2220-47a5-bfe8-fe6d41ab1f82
|
other
|
linux
|
f227e3ec3b5cad859ad15666874405e8c1bbc1d4
| 1
|
void add_interrupt_randomness(int irq, int irq_flags)
{
struct entropy_store *r;
struct fast_pool *fast_pool = this_cpu_ptr(&irq_randomness);
struct pt_regs *regs = get_irq_regs();
unsigned long now = jiffies;
cycles_t cycles = random_get_entropy();
__u32 c_high, j_high;
__u64 ip;
unsigned long seed;
int credit = 0;
if (cycles == 0)
cycles = get_reg(fast_pool, regs);
c_high = (sizeof(cycles) > 4) ? cycles >> 32 : 0;
j_high = (sizeof(now) > 4) ? now >> 32 : 0;
fast_pool->pool[0] ^= cycles ^ j_high ^ irq;
fast_pool->pool[1] ^= now ^ c_high;
ip = regs ? instruction_pointer(regs) : _RET_IP_;
fast_pool->pool[2] ^= ip;
fast_pool->pool[3] ^= (sizeof(ip) > 4) ? ip >> 32 :
get_reg(fast_pool, regs);
fast_mix(fast_pool);
add_interrupt_bench(cycles);
if (unlikely(crng_init == 0)) {
if ((fast_pool->count >= 64) &&
crng_fast_load((char *) fast_pool->pool,
sizeof(fast_pool->pool))) {
fast_pool->count = 0;
fast_pool->last = now;
}
return;
}
if ((fast_pool->count < 64) &&
!time_after(now, fast_pool->last + HZ))
return;
r = &input_pool;
if (!spin_trylock(&r->lock))
return;
fast_pool->last = now;
__mix_pool_bytes(r, &fast_pool->pool, sizeof(fast_pool->pool));
/*
* If we have architectural seed generator, produce a seed and
* add it to the pool. For the sake of paranoia don't let the
* architectural seed generator dominate the input from the
* interrupt noise.
*/
if (arch_get_random_seed_long(&seed)) {
__mix_pool_bytes(r, &seed, sizeof(seed));
credit = 1;
}
spin_unlock(&r->lock);
fast_pool->count = 0;
/* award one bit for the contents of the fast pool */
credit_entropy_bits(r, credit + 1);
}
| null | null | 207,803
|
93078228868817235538615789338167903266
| 64
|
random32: update the net random state on interrupt and activity
This modifies the first 32 bits out of the 128 bits of a random CPU's
net_rand_state on interrupt or CPU activity to complicate remote
observations that could lead to guessing the network RNG's internal
state.
Note that depending on some network devices' interrupt rate moderation
or binding, this re-seeding might happen on every packet or even almost
never.
In addition, with NOHZ some CPUs might not even get timer interrupts,
leaving their local state rarely updated, while they are running
networked processes making use of the random state. For this reason, we
also perform this update in update_process_times() in order to at least
update the state when there is user or system activity, since it's the
only case we care about.
Reported-by: Amit Klein <[email protected]>
Suggested-by: Linus Torvalds <[email protected]>
Cc: Eric Dumazet <[email protected]>
Cc: "Jason A. Donenfeld" <[email protected]>
Cc: Andy Lutomirski <[email protected]>
Cc: Kees Cook <[email protected]>
Cc: Thomas Gleixner <[email protected]>
Cc: Peter Zijlstra <[email protected]>
Cc: <[email protected]>
Signed-off-by: Willy Tarreau <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
|
other
|
linux
|
f227e3ec3b5cad859ad15666874405e8c1bbc1d4
| 1
|
void update_process_times(int user_tick)
{
struct task_struct *p = current;
/* Note: this timer irq context must be accounted for as well. */
account_process_tick(p, user_tick);
run_local_timers();
rcu_sched_clock_irq(user_tick);
#ifdef CONFIG_IRQ_WORK
if (in_irq())
irq_work_tick();
#endif
scheduler_tick();
if (IS_ENABLED(CONFIG_POSIX_TIMERS))
run_posix_cpu_timers();
}
| null | null | 207,804
|
33405367387359628492741828293788263595
| 16
|
random32: update the net random state on interrupt and activity
This modifies the first 32 bits out of the 128 bits of a random CPU's
net_rand_state on interrupt or CPU activity to complicate remote
observations that could lead to guessing the network RNG's internal
state.
Note that depending on some network devices' interrupt rate moderation
or binding, this re-seeding might happen on every packet or even almost
never.
In addition, with NOHZ some CPUs might not even get timer interrupts,
leaving their local state rarely updated, while they are running
networked processes making use of the random state. For this reason, we
also perform this update in update_process_times() in order to at least
update the state when there is user or system activity, since it's the
only case we care about.
Reported-by: Amit Klein <[email protected]>
Suggested-by: Linus Torvalds <[email protected]>
Cc: Eric Dumazet <[email protected]>
Cc: "Jason A. Donenfeld" <[email protected]>
Cc: Andy Lutomirski <[email protected]>
Cc: Kees Cook <[email protected]>
Cc: Thomas Gleixner <[email protected]>
Cc: Peter Zijlstra <[email protected]>
Cc: <[email protected]>
Signed-off-by: Willy Tarreau <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
|
other
|
linux
|
86cdf8e38792545161dbe3350a7eced558ba4d15
| 1
|
inline int nci_request(struct nci_dev *ndev,
void (*req)(struct nci_dev *ndev,
const void *opt),
const void *opt, __u32 timeout)
{
int rc;
if (!test_bit(NCI_UP, &ndev->flags))
return -ENETDOWN;
/* Serialize all requests */
mutex_lock(&ndev->req_lock);
rc = __nci_request(ndev, req, opt, timeout);
mutex_unlock(&ndev->req_lock);
return rc;
}
| null | null | 207,826
|
66021090386999143440826290693907389327
| 17
|
NFC: reorganize the functions in nci_request
There is a possible data race as shown below:
thread-A in nci_request() | thread-B in nci_close_device()
| mutex_lock(&ndev->req_lock);
test_bit(NCI_UP, &ndev->flags); |
... | test_and_clear_bit(NCI_UP, &ndev->flags)
mutex_lock(&ndev->req_lock); |
|
This race will allow __nci_request() to be awaked while the device is
getting removed.
Similar to commit e2cb6b891ad2 ("bluetooth: eliminate the potential race
condition when removing the HCI controller"). this patch alters the
function sequence in nci_request() to prevent the data races between the
nci_close_device().
Signed-off-by: Lin Ma <[email protected]>
Fixes: 6a2968aaf50c ("NFC: basic NCI protocol implementation")
Link: https://lore.kernel.org/r/[email protected]
Signed-off-by: Jakub Kicinski <[email protected]>
|
other
|
pesign
|
12f16710ee44ef64ddb044a3523c3c4c4d90039a
| 1
|
handle_unlock_token(context *ctx, struct pollfd *pollfd, socklen_t size)
{
struct msghdr msg;
struct iovec iov;
ssize_t n;
int rc = cms_context_alloc(&ctx->cms);
if (rc < 0) {
send_response(ctx, ctx->backup_cms, pollfd, rc);
return;
}
steal_from_cms(ctx->backup_cms, ctx->cms);
char *buffer = malloc(size);
if (!buffer) {
oom:
ctx->cms->log(ctx->cms, ctx->priority|LOG_ERR,
"unable to allocate memory: %m");
exit(1);
}
memset(&msg, '\0', sizeof(msg));
iov.iov_base = buffer;
iov.iov_len = size;
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
n = recvmsg(pollfd->fd, &msg, MSG_WAITALL);
pesignd_string *tn = (pesignd_string *)buffer;
if (n < (long long)sizeof(tn->size)) {
malformed:
ctx->cms->log(ctx->cms, ctx->priority|LOG_ERR,
"unlock-token: invalid data");
ctx->cms->log(ctx->cms, ctx->priority|LOG_ERR,
"possible exploit attempt. closing.");
close(pollfd->fd);
return;
}
n -= sizeof(tn->size);
if ((size_t)n < tn->size)
goto malformed;
n -= tn->size;
if (tn->value[tn->size - 1] != '\0')
goto malformed;
pesignd_string *tp = pesignd_string_next(tn);
if ((size_t)n < sizeof(tp->size))
goto malformed;
n -= sizeof(tp->size);
if ((size_t)n < tp->size)
goto malformed;
n -= tp->size;
if (tn->value[tn->size - 1] != '\0')
goto malformed;
if (n != 0)
goto malformed;
ctx->cms->log(ctx->cms, ctx->priority|LOG_NOTICE,
"unlocking token \"%s\"", tn->value);
/* authenticating with nss frees this ... best API ever. */
ctx->cms->tokenname = PORT_ArenaStrdup(ctx->cms->arena,
(char *)tn->value);
if (!ctx->cms->tokenname)
goto oom;
char *pin = (char *)tp->value;
if (!pin)
goto oom;
cms_set_pw_callback(ctx->cms, get_password_passthrough);
cms_set_pw_data(ctx->cms, pin);
rc = unlock_nss_token(ctx->cms);
cms_set_pw_callback(ctx->cms, get_password_fail);
cms_set_pw_data(ctx->cms, NULL);
if (rc == -1)
ctx->cms->log(ctx->cms, ctx->priority|LOG_ERR,
"could not find token \"%s\"", tn->value);
else if (rc == 0) {
ctx->cms->log(ctx->cms, ctx->priority|LOG_NOTICE,
"authentication succeeded for token \"%s\"",
tn->value);
rc = add_token_to_authenticated_list(ctx, tn->value);
if (rc < 0)
ctx->cms->log(ctx->cms, ctx->priority|LOG_ERR,
"couldn't add token to internal list: %m");
}
send_response(ctx, ctx->cms, pollfd, rc);
free(buffer);
hide_stolen_goods_from_cms(ctx->cms, ctx->backup_cms);
cms_context_fini(ctx->cms);
}
| null | null | 207,873
|
336651457369522937879967751310608385506
| 103
|
Rework the wildly undocumented NSS password file goo.
This probably doesn't work yet.
|
other
|
pesign
|
12f16710ee44ef64ddb044a3523c3c4c4d90039a
| 1
|
void cms_set_pw_data(cms_context *cms, void *pwdata)
{
cms->pwdata = pwdata;
}
| null | null | 207,874
|
39431258010802991871202478740642266914
| 4
|
Rework the wildly undocumented NSS password file goo.
This probably doesn't work yet.
|
other
|
pcre2
|
03654e751e7f0700693526b67dfcadda6b42c9d0
| 1
|
static int get_recurse_data_length(compiler_common *common, PCRE2_SPTR cc, PCRE2_SPTR ccend,
BOOL *needs_control_head, BOOL *has_quit, BOOL *has_accept)
{
int length = 1;
int size;
PCRE2_SPTR alternative;
BOOL quit_found = FALSE;
BOOL accept_found = FALSE;
BOOL setsom_found = FALSE;
BOOL setmark_found = FALSE;
BOOL capture_last_found = FALSE;
BOOL control_head_found = FALSE;
#if defined DEBUG_FORCE_CONTROL_HEAD && DEBUG_FORCE_CONTROL_HEAD
SLJIT_ASSERT(common->control_head_ptr != 0);
control_head_found = TRUE;
#endif
/* Calculate the sum of the private machine words. */
while (cc < ccend)
{
size = 0;
switch(*cc)
{
case OP_SET_SOM:
SLJIT_ASSERT(common->has_set_som);
setsom_found = TRUE;
cc += 1;
break;
case OP_RECURSE:
if (common->has_set_som)
setsom_found = TRUE;
if (common->mark_ptr != 0)
setmark_found = TRUE;
if (common->capture_last_ptr != 0)
capture_last_found = TRUE;
cc += 1 + LINK_SIZE;
break;
case OP_KET:
if (PRIVATE_DATA(cc) != 0)
{
length++;
SLJIT_ASSERT(PRIVATE_DATA(cc + 1) != 0);
cc += PRIVATE_DATA(cc + 1);
}
cc += 1 + LINK_SIZE;
break;
case OP_ASSERT:
case OP_ASSERT_NOT:
case OP_ASSERTBACK:
case OP_ASSERTBACK_NOT:
case OP_ASSERT_NA:
case OP_ASSERTBACK_NA:
case OP_ONCE:
case OP_SCRIPT_RUN:
case OP_BRAPOS:
case OP_SBRA:
case OP_SBRAPOS:
case OP_SCOND:
length++;
SLJIT_ASSERT(PRIVATE_DATA(cc) != 0);
cc += 1 + LINK_SIZE;
break;
case OP_CBRA:
case OP_SCBRA:
length += 2;
if (common->capture_last_ptr != 0)
capture_last_found = TRUE;
if (common->optimized_cbracket[GET2(cc, 1 + LINK_SIZE)] == 0)
length++;
cc += 1 + LINK_SIZE + IMM2_SIZE;
break;
case OP_CBRAPOS:
case OP_SCBRAPOS:
length += 2 + 2;
if (common->capture_last_ptr != 0)
capture_last_found = TRUE;
cc += 1 + LINK_SIZE + IMM2_SIZE;
break;
case OP_COND:
/* Might be a hidden SCOND. */
alternative = cc + GET(cc, 1);
if (*alternative == OP_KETRMAX || *alternative == OP_KETRMIN)
length++;
cc += 1 + LINK_SIZE;
break;
CASE_ITERATOR_PRIVATE_DATA_1
if (PRIVATE_DATA(cc) != 0)
length++;
cc += 2;
#ifdef SUPPORT_UNICODE
if (common->utf && HAS_EXTRALEN(cc[-1])) cc += GET_EXTRALEN(cc[-1]);
#endif
break;
CASE_ITERATOR_PRIVATE_DATA_2A
if (PRIVATE_DATA(cc) != 0)
length += 2;
cc += 2;
#ifdef SUPPORT_UNICODE
if (common->utf && HAS_EXTRALEN(cc[-1])) cc += GET_EXTRALEN(cc[-1]);
#endif
break;
CASE_ITERATOR_PRIVATE_DATA_2B
if (PRIVATE_DATA(cc) != 0)
length += 2;
cc += 2 + IMM2_SIZE;
#ifdef SUPPORT_UNICODE
if (common->utf && HAS_EXTRALEN(cc[-1])) cc += GET_EXTRALEN(cc[-1]);
#endif
break;
CASE_ITERATOR_TYPE_PRIVATE_DATA_1
if (PRIVATE_DATA(cc) != 0)
length++;
cc += 1;
break;
CASE_ITERATOR_TYPE_PRIVATE_DATA_2A
if (PRIVATE_DATA(cc) != 0)
length += 2;
cc += 1;
break;
CASE_ITERATOR_TYPE_PRIVATE_DATA_2B
if (PRIVATE_DATA(cc) != 0)
length += 2;
cc += 1 + IMM2_SIZE;
break;
case OP_CLASS:
case OP_NCLASS:
#if defined SUPPORT_UNICODE || PCRE2_CODE_UNIT_WIDTH != 8
case OP_XCLASS:
size = (*cc == OP_XCLASS) ? GET(cc, 1) : 1 + 32 / (int)sizeof(PCRE2_UCHAR);
#else
size = 1 + 32 / (int)sizeof(PCRE2_UCHAR);
#endif
if (PRIVATE_DATA(cc) != 0)
length += get_class_iterator_size(cc + size);
cc += size;
break;
case OP_MARK:
case OP_COMMIT_ARG:
case OP_PRUNE_ARG:
case OP_THEN_ARG:
SLJIT_ASSERT(common->mark_ptr != 0);
if (!setmark_found)
setmark_found = TRUE;
if (common->control_head_ptr != 0)
control_head_found = TRUE;
if (*cc != OP_MARK)
quit_found = TRUE;
cc += 1 + 2 + cc[1];
break;
case OP_PRUNE:
case OP_SKIP:
case OP_COMMIT:
quit_found = TRUE;
cc++;
break;
case OP_SKIP_ARG:
quit_found = TRUE;
cc += 1 + 2 + cc[1];
break;
case OP_THEN:
SLJIT_ASSERT(common->control_head_ptr != 0);
quit_found = TRUE;
if (!control_head_found)
control_head_found = TRUE;
cc++;
break;
case OP_ACCEPT:
case OP_ASSERT_ACCEPT:
accept_found = TRUE;
cc++;
break;
default:
cc = next_opcode(common, cc);
SLJIT_ASSERT(cc != NULL);
break;
}
}
SLJIT_ASSERT(cc == ccend);
if (control_head_found)
length++;
if (capture_last_found)
length++;
if (quit_found)
{
if (setsom_found)
length++;
if (setmark_found)
length++;
}
*needs_control_head = control_head_found;
*has_quit = quit_found;
*has_accept = accept_found;
return length;
}
| null | null | 207,990
|
271890704880282234244724577171237704348
| 217
|
Fixed an issue affecting recursions in JIT
|
other
|
radare2
|
18d1d064bf599a255d55f09fca3104776fc34a67
| 1
|
RList *r_bin_ne_get_entrypoints(r_bin_ne_obj_t *bin) {
RList *entries = r_list_newf (free);
if (!entries) {
return NULL;
}
RList *segments = r_bin_ne_get_segments (bin);
if (!segments) {
r_list_free (entries);
return NULL;
}
if (bin->ne_header->csEntryPoint) {
RBinAddr *entry = R_NEW0 (RBinAddr);
if (!entry) {
r_list_free (entries);
return NULL;
}
entry->bits = 16;
ut32 entry_cs = bin->ne_header->csEntryPoint;
RBinSection *s = r_list_get_n (segments, entry_cs - 1);
entry->paddr = bin->ne_header->ipEntryPoint + (s? s->paddr: 0);
r_list_append (entries, entry);
}
int off = 0;
size_t tableat = bin->header_offset + bin->ne_header->EntryTableOffset;
while (off < bin->ne_header->EntryTableLength) {
if (tableat + off >= r_buf_size (bin->buf)) {
break;
}
ut8 bundle_length = *(ut8 *)(bin->entry_table + off);
if (!bundle_length) {
break;
}
off++;
ut8 bundle_type = *(ut8 *)(bin->entry_table + off);
off++;
int i;
for (i = 0; i < bundle_length; i++) {
if (tableat + off + 4 >= r_buf_size (bin->buf)) {
break;
}
RBinAddr *entry = R_NEW0 (RBinAddr);
if (!entry) {
r_list_free (entries);
return NULL;
}
off++;
if (!bundle_type) { // Skip
off--;
free (entry);
break;
} else if (bundle_type == 0xff) { // moveable
off += 2;
ut8 segnum = *(bin->entry_table + off);
off++;
ut16 segoff = *(ut16 *)(bin->entry_table + off);
if (segnum > 0) {
entry->paddr = (ut64)bin->segment_entries[segnum - 1].offset * bin->alignment + segoff;
}
} else { // Fixed
if (bundle_type < bin->ne_header->SegCount) {
entry->paddr = (ut64)bin->segment_entries[bundle_type - 1].offset
* bin->alignment + *(ut16 *)(bin->entry_table + off);
}
}
off += 2;
r_list_append (entries, entry);
}
}
r_list_free (segments);
bin->entries = entries;
return entries;
}
| null | null | 208,076
|
311431254745849220001801039617784937971
| 73
|
Fix null deref in the ne parser ##crash
* Reported by @hmsec via huntr.dev
* Reproducer: nepoc00
* BountyID: bfeb8fb8-644d-4587-80d4-cb704c404013
|
other
|
linux
|
054aa8d439b9185d4f5eb9a90282d1ce74772969
| 1
|
static struct file *__fget_files(struct files_struct *files, unsigned int fd,
fmode_t mask, unsigned int refs)
{
struct file *file;
rcu_read_lock();
loop:
file = files_lookup_fd_rcu(files, fd);
if (file) {
/* File object ref couldn't be taken.
* dup2() atomicity guarantee is the reason
* we loop to catch the new file (or NULL pointer)
*/
if (file->f_mode & mask)
file = NULL;
else if (!get_file_rcu_many(file, refs))
goto loop;
}
rcu_read_unlock();
return file;
}
| null | null | 208,085
|
236448832030969755251234701523533614254
| 22
|
fget: check that the fd still exists after getting a ref to it
Jann Horn points out that there is another possible race wrt Unix domain
socket garbage collection, somewhat reminiscent of the one fixed in
commit cbcf01128d0a ("af_unix: fix garbage collect vs MSG_PEEK").
See the extended comment about the garbage collection requirements added
to unix_peek_fds() by that commit for details.
The race comes from how we can locklessly look up a file descriptor just
as it is in the process of being closed, and with the right artificial
timing (Jann added a few strategic 'mdelay(500)' calls to do that), the
Unix domain socket garbage collector could see the reference count
decrement of the close() happen before fget() took its reference to the
file and the file was attached onto a new file descriptor.
This is all (intentionally) correct on the 'struct file *' side, with
RCU lookups and lockless reference counting very much part of the
design. Getting that reference count out of order isn't a problem per
se.
But the garbage collector can get confused by seeing this situation of
having seen a file not having any remaining external references and then
seeing it being attached to an fd.
In commit cbcf01128d0a ("af_unix: fix garbage collect vs MSG_PEEK") the
fix was to serialize the file descriptor install with the garbage
collector by taking and releasing the unix_gc_lock.
That's not really an option here, but since this all happens when we are
in the process of looking up a file descriptor, we can instead simply
just re-check that the file hasn't been closed in the meantime, and just
re-do the lookup if we raced with a concurrent close() of the same file
descriptor.
Reported-and-tested-by: Jann Horn <[email protected]>
Acked-by: Miklos Szeredi <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
|
other
|
linux
|
f85daf0e725358be78dfd208dea5fd665d8cb901
| 1
|
static int xfrm_expand_policies(const struct flowi *fl, u16 family,
struct xfrm_policy **pols,
int *num_pols, int *num_xfrms)
{
int i;
if (*num_pols == 0 || !pols[0]) {
*num_pols = 0;
*num_xfrms = 0;
return 0;
}
if (IS_ERR(pols[0]))
return PTR_ERR(pols[0]);
*num_xfrms = pols[0]->xfrm_nr;
#ifdef CONFIG_XFRM_SUB_POLICY
if (pols[0]->action == XFRM_POLICY_ALLOW &&
pols[0]->type != XFRM_POLICY_TYPE_MAIN) {
pols[1] = xfrm_policy_lookup_bytype(xp_net(pols[0]),
XFRM_POLICY_TYPE_MAIN,
fl, family,
XFRM_POLICY_OUT,
pols[0]->if_id);
if (pols[1]) {
if (IS_ERR(pols[1])) {
xfrm_pols_put(pols, *num_pols);
return PTR_ERR(pols[1]);
}
(*num_pols)++;
(*num_xfrms) += pols[1]->xfrm_nr;
}
}
#endif
for (i = 0; i < *num_pols; i++) {
if (pols[i]->action != XFRM_POLICY_ALLOW) {
*num_xfrms = -1;
break;
}
}
return 0;
}
| null | null | 208,107
|
160505295107260782838646323717685740675
| 44
|
xfrm: xfrm_policy: fix a possible double xfrm_pols_put() in xfrm_bundle_lookup()
xfrm_policy_lookup() will call xfrm_pol_hold_rcu() to get a refcount of
pols[0]. This refcount can be dropped in xfrm_expand_policies() when
xfrm_expand_policies() return error. pols[0]'s refcount is balanced in
here. But xfrm_bundle_lookup() will also call xfrm_pols_put() with
num_pols == 1 to drop this refcount when xfrm_expand_policies() return
error.
This patch also fix an illegal address access. pols[0] will save a error
point when xfrm_policy_lookup fails. This lead to xfrm_pols_put to resolve
an illegal address in xfrm_bundle_lookup's error path.
Fix these by setting num_pols = 0 in xfrm_expand_policies()'s error path.
Fixes: 80c802f3073e ("xfrm: cache bundles instead of policies for outgoing flows")
Signed-off-by: Hangyu Hua <[email protected]>
Signed-off-by: Steffen Klassert <[email protected]>
|
other
|
linux
|
d0d62baa7f505bd4c59cd169692ff07ec49dde37
| 1
|
static int xemaclite_of_probe(struct platform_device *ofdev)
{
struct resource *res;
struct net_device *ndev = NULL;
struct net_local *lp = NULL;
struct device *dev = &ofdev->dev;
int rc = 0;
dev_info(dev, "Device Tree Probing\n");
/* Create an ethernet device instance */
ndev = alloc_etherdev(sizeof(struct net_local));
if (!ndev)
return -ENOMEM;
dev_set_drvdata(dev, ndev);
SET_NETDEV_DEV(ndev, &ofdev->dev);
lp = netdev_priv(ndev);
lp->ndev = ndev;
/* Get IRQ for the device */
res = platform_get_resource(ofdev, IORESOURCE_IRQ, 0);
if (!res) {
dev_err(dev, "no IRQ found\n");
rc = -ENXIO;
goto error;
}
ndev->irq = res->start;
res = platform_get_resource(ofdev, IORESOURCE_MEM, 0);
lp->base_addr = devm_ioremap_resource(&ofdev->dev, res);
if (IS_ERR(lp->base_addr)) {
rc = PTR_ERR(lp->base_addr);
goto error;
}
ndev->mem_start = res->start;
ndev->mem_end = res->end;
spin_lock_init(&lp->reset_lock);
lp->next_tx_buf_to_use = 0x0;
lp->next_rx_buf_to_use = 0x0;
lp->tx_ping_pong = get_bool(ofdev, "xlnx,tx-ping-pong");
lp->rx_ping_pong = get_bool(ofdev, "xlnx,rx-ping-pong");
rc = of_get_mac_address(ofdev->dev.of_node, ndev->dev_addr);
if (rc) {
dev_warn(dev, "No MAC address found, using random\n");
eth_hw_addr_random(ndev);
}
/* Clear the Tx CSR's in case this is a restart */
xemaclite_writel(0, lp->base_addr + XEL_TSR_OFFSET);
xemaclite_writel(0, lp->base_addr + XEL_BUFFER_OFFSET + XEL_TSR_OFFSET);
/* Set the MAC address in the EmacLite device */
xemaclite_update_address(lp, ndev->dev_addr);
lp->phy_node = of_parse_phandle(ofdev->dev.of_node, "phy-handle", 0);
xemaclite_mdio_setup(lp, &ofdev->dev);
dev_info(dev, "MAC address is now %pM\n", ndev->dev_addr);
ndev->netdev_ops = &xemaclite_netdev_ops;
ndev->ethtool_ops = &xemaclite_ethtool_ops;
ndev->flags &= ~IFF_MULTICAST;
ndev->watchdog_timeo = TX_TIMEOUT;
/* Finally, register the device */
rc = register_netdev(ndev);
if (rc) {
dev_err(dev,
"Cannot register network device, aborting\n");
goto error;
}
dev_info(dev,
"Xilinx EmacLite at 0x%08lX mapped to 0x%08lX, irq=%d\n",
(unsigned long __force)ndev->mem_start,
(unsigned long __force)lp->base_addr, ndev->irq);
return 0;
error:
free_netdev(ndev);
return rc;
}
| null | null | 208,115
|
206871728932650153351585055932751180331
| 89
|
net: xilinx_emaclite: Do not print real IOMEM pointer
Printing kernel pointers is discouraged because they might leak kernel
memory layout. This fixes smatch warning:
drivers/net/ethernet/xilinx/xilinx_emaclite.c:1191 xemaclite_of_probe() warn:
argument 4 to %08lX specifier is cast from pointer
Signed-off-by: YueHaibing <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
|
other
|
util-linux
|
5ebbc3865d1e53ef42e5f121c41faab23dd59075
| 1
|
int main(int argc, char **argv)
{
int c, rc = MOUNT_EX_SUCCESS, all = 0, show_labels = 0;
struct libmnt_context *cxt;
struct libmnt_table *fstab = NULL;
char *srcbuf = NULL;
char *types = NULL;
unsigned long oper = 0;
enum {
MOUNT_OPT_SHARED = CHAR_MAX + 1,
MOUNT_OPT_SLAVE,
MOUNT_OPT_PRIVATE,
MOUNT_OPT_UNBINDABLE,
MOUNT_OPT_RSHARED,
MOUNT_OPT_RSLAVE,
MOUNT_OPT_RPRIVATE,
MOUNT_OPT_RUNBINDABLE,
MOUNT_OPT_TARGET,
MOUNT_OPT_SOURCE
};
static const struct option longopts[] = {
{ "all", 0, 0, 'a' },
{ "fake", 0, 0, 'f' },
{ "fstab", 1, 0, 'T' },
{ "fork", 0, 0, 'F' },
{ "help", 0, 0, 'h' },
{ "no-mtab", 0, 0, 'n' },
{ "read-only", 0, 0, 'r' },
{ "ro", 0, 0, 'r' },
{ "verbose", 0, 0, 'v' },
{ "version", 0, 0, 'V' },
{ "read-write", 0, 0, 'w' },
{ "rw", 0, 0, 'w' },
{ "options", 1, 0, 'o' },
{ "test-opts", 1, 0, 'O' },
{ "pass-fd", 1, 0, 'p' },
{ "types", 1, 0, 't' },
{ "uuid", 1, 0, 'U' },
{ "label", 1, 0, 'L'},
{ "bind", 0, 0, 'B' },
{ "move", 0, 0, 'M' },
{ "rbind", 0, 0, 'R' },
{ "make-shared", 0, 0, MOUNT_OPT_SHARED },
{ "make-slave", 0, 0, MOUNT_OPT_SLAVE },
{ "make-private", 0, 0, MOUNT_OPT_PRIVATE },
{ "make-unbindable", 0, 0, MOUNT_OPT_UNBINDABLE },
{ "make-rshared", 0, 0, MOUNT_OPT_RSHARED },
{ "make-rslave", 0, 0, MOUNT_OPT_RSLAVE },
{ "make-rprivate", 0, 0, MOUNT_OPT_RPRIVATE },
{ "make-runbindable", 0, 0, MOUNT_OPT_RUNBINDABLE },
{ "no-canonicalize", 0, 0, 'c' },
{ "internal-only", 0, 0, 'i' },
{ "show-labels", 0, 0, 'l' },
{ "target", 1, 0, MOUNT_OPT_TARGET },
{ "source", 1, 0, MOUNT_OPT_SOURCE },
{ NULL, 0, 0, 0 }
};
static const ul_excl_t excl[] = { /* rows and cols in in ASCII order */
{ 'B','M','R', /* bind,move,rbind */
MOUNT_OPT_SHARED, MOUNT_OPT_SLAVE,
MOUNT_OPT_PRIVATE, MOUNT_OPT_UNBINDABLE,
MOUNT_OPT_RSHARED, MOUNT_OPT_RSLAVE,
MOUNT_OPT_RPRIVATE, MOUNT_OPT_RUNBINDABLE },
{ 'L','U', MOUNT_OPT_SOURCE }, /* label,uuid,source */
{ 0 }
};
int excl_st[ARRAY_SIZE(excl)] = UL_EXCL_STATUS_INIT;
sanitize_env();
setlocale(LC_ALL, "");
bindtextdomain(PACKAGE, LOCALEDIR);
textdomain(PACKAGE);
atexit(close_stdout);
mnt_init_debug(0);
cxt = mnt_new_context();
if (!cxt)
err(MOUNT_EX_SYSERR, _("libmount context allocation failed"));
mnt_context_set_tables_errcb(cxt, table_parser_errcb);
while ((c = getopt_long(argc, argv, "aBcfFhilL:Mno:O:p:rRsU:vVwt:T:",
longopts, NULL)) != -1) {
/* only few options are allowed for non-root users */
if (mnt_context_is_restricted(cxt) &&
!strchr("hlLUVvpris", c) &&
c != MOUNT_OPT_TARGET &&
c != MOUNT_OPT_SOURCE)
exit_non_root(option_to_longopt(c, longopts));
err_exclusive_options(c, longopts, excl, excl_st);
switch(c) {
case 'a':
all = 1;
break;
case 'c':
mnt_context_disable_canonicalize(cxt, TRUE);
break;
case 'f':
mnt_context_enable_fake(cxt, TRUE);
break;
case 'F':
mnt_context_enable_fork(cxt, TRUE);
break;
case 'h':
usage(stdout);
break;
case 'i':
mnt_context_disable_helpers(cxt, TRUE);
break;
case 'n':
mnt_context_disable_mtab(cxt, TRUE);
break;
case 'r':
if (mnt_context_append_options(cxt, "ro"))
err(MOUNT_EX_SYSERR, _("failed to append options"));
readwrite = 0;
break;
case 'v':
mnt_context_enable_verbose(cxt, TRUE);
break;
case 'V':
print_version();
break;
case 'w':
if (mnt_context_append_options(cxt, "rw"))
err(MOUNT_EX_SYSERR, _("failed to append options"));
readwrite = 1;
break;
case 'o':
if (mnt_context_append_options(cxt, optarg))
err(MOUNT_EX_SYSERR, _("failed to append options"));
break;
case 'O':
if (mnt_context_set_options_pattern(cxt, optarg))
err(MOUNT_EX_SYSERR, _("failed to set options pattern"));
break;
case 'p':
warnx(_("--pass-fd is no longer supported"));
break;
case 'L':
xasprintf(&srcbuf, "LABEL=\"%s\"", optarg);
mnt_context_disable_swapmatch(cxt, 1);
mnt_context_set_source(cxt, srcbuf);
free(srcbuf);
break;
case 'U':
xasprintf(&srcbuf, "UUID=\"%s\"", optarg);
mnt_context_disable_swapmatch(cxt, 1);
mnt_context_set_source(cxt, srcbuf);
free(srcbuf);
break;
case 'l':
show_labels = 1;
break;
case 't':
types = optarg;
break;
case 'T':
fstab = append_fstab(cxt, fstab, optarg);
break;
case 's':
mnt_context_enable_sloppy(cxt, TRUE);
break;
case 'B':
oper |= MS_BIND;
break;
case 'M':
oper |= MS_MOVE;
break;
case 'R':
oper |= (MS_BIND | MS_REC);
break;
case MOUNT_OPT_SHARED:
oper |= MS_SHARED;
break;
case MOUNT_OPT_SLAVE:
oper |= MS_SLAVE;
break;
case MOUNT_OPT_PRIVATE:
oper |= MS_PRIVATE;
break;
case MOUNT_OPT_UNBINDABLE:
oper |= MS_UNBINDABLE;
break;
case MOUNT_OPT_RSHARED:
oper |= (MS_SHARED | MS_REC);
break;
case MOUNT_OPT_RSLAVE:
oper |= (MS_SLAVE | MS_REC);
break;
case MOUNT_OPT_RPRIVATE:
oper |= (MS_PRIVATE | MS_REC);
break;
case MOUNT_OPT_RUNBINDABLE:
oper |= (MS_UNBINDABLE | MS_REC);
break;
case MOUNT_OPT_TARGET:
mnt_context_disable_swapmatch(cxt, 1);
mnt_context_set_target(cxt, optarg);
break;
case MOUNT_OPT_SOURCE:
mnt_context_disable_swapmatch(cxt, 1);
mnt_context_set_source(cxt, optarg);
break;
default:
usage(stderr);
break;
}
}
argc -= optind;
argv += optind;
if (fstab && !mnt_context_is_nocanonicalize(cxt)) {
/*
* We have external (context independent) fstab instance, let's
* make a connection between the fstab and the canonicalization
* cache.
*/
struct libmnt_cache *cache = mnt_context_get_cache(cxt);
mnt_table_set_cache(fstab, cache);
}
if (!mnt_context_get_source(cxt) &&
!mnt_context_get_target(cxt) &&
!argc &&
!all) {
if (oper)
usage(stderr);
print_all(cxt, types, show_labels);
goto done;
}
if (oper && (types || all || mnt_context_get_source(cxt)))
usage(stderr);
if (types && (all || strchr(types, ',') ||
strncmp(types, "no", 2) == 0))
mnt_context_set_fstype_pattern(cxt, types);
else if (types)
mnt_context_set_fstype(cxt, types);
if (all) {
/*
* A) Mount all
*/
rc = mount_all(cxt);
goto done;
} else if (argc == 0 && (mnt_context_get_source(cxt) ||
mnt_context_get_target(cxt))) {
/*
* B) mount -L|-U|--source|--target
*/
if (mnt_context_is_restricted(cxt) &&
mnt_context_get_source(cxt) &&
mnt_context_get_target(cxt))
exit_non_root(NULL);
} else if (argc == 1) {
/*
* C) mount [-L|-U|--source] <target>
* mount <source|target>
*
* non-root may specify source *or* target, but not both
*/
if (mnt_context_is_restricted(cxt) &&
mnt_context_get_source(cxt))
exit_non_root(NULL);
mnt_context_set_target(cxt, argv[0]);
} else if (argc == 2 && !mnt_context_get_source(cxt)
&& !mnt_context_get_target(cxt)) {
/*
* D) mount <source> <target>
*/
if (mnt_context_is_restricted(cxt))
exit_non_root(NULL);
mnt_context_set_source(cxt, argv[0]);
mnt_context_set_target(cxt, argv[1]);
} else
usage(stderr);
if (oper) {
/* MS_PROPAGATION operations, let's set the mount flags */
mnt_context_set_mflags(cxt, oper);
/* For -make* or --bind is fstab unnecessary */
mnt_context_set_optsmode(cxt, MNT_OMODE_NOTAB);
}
rc = mnt_context_mount(cxt);
rc = mk_exit_code(cxt, rc);
if (rc == MOUNT_EX_SUCCESS && mnt_context_is_verbose(cxt))
success_message(cxt);
done:
mnt_free_context(cxt);
mnt_free_table(fstab);
return rc;
}
| null | null | 208,140
|
28463599175286661619944378926902691836
| 310
|
mount: sanitize paths from non-root users
$ mount /root/.ssh/../../dev/sda2
mount: only root can mount UUID=17bc65ec-4125-4e7c-8a7d-e2795064c736 on /boot
this is too promiscuous. It seems better to ignore on command line
specified paths which are not resolve-able for non-root users.
Fixed version:
$ mount /root/.ssh/../../dev/sda2
mount: /root/.ssh/../../dev/sda2: Permission denied
$ mount /dev/sda2
mount: only root can mount UUID=17bc65ec-4125-4e7c-8a7d-e2795064c736 on /boot
Note that this bug has no relation to mount(2) permissions evaluation
in suid mode. The way how non-root user specifies paths on command
line is completely irrelevant for comparison with fstab entries.
Signed-off-by: Karel Zak <[email protected]>
|
other
|
vim
|
806d037671e133bd28a7864248763f643967973a
| 1
|
bracketed_paste(paste_mode_T mode, int drop, garray_T *gap)
{
int c;
char_u buf[NUMBUFLEN + MB_MAXBYTES];
int idx = 0;
char_u *end = find_termcode((char_u *)"PE");
int ret_char = -1;
int save_allow_keys = allow_keys;
int save_paste = p_paste;
// If the end code is too long we can't detect it, read everything.
if (end != NULL && STRLEN(end) >= NUMBUFLEN)
end = NULL;
++no_mapping;
allow_keys = 0;
if (!p_paste)
// Also have the side effects of setting 'paste' to make it work much
// faster.
set_option_value((char_u *)"paste", TRUE, NULL, 0);
for (;;)
{
// When the end is not defined read everything there is.
if (end == NULL && vpeekc() == NUL)
break;
do
c = vgetc();
while (c == K_IGNORE || c == K_VER_SCROLLBAR || c == K_HOR_SCROLLBAR);
if (c == NUL || got_int || (ex_normal_busy > 0 && c == Ctrl_C))
// When CTRL-C was encountered the typeahead will be flushed and we
// won't get the end sequence. Except when using ":normal".
break;
if (has_mbyte)
idx += (*mb_char2bytes)(c, buf + idx);
else
buf[idx++] = c;
buf[idx] = NUL;
if (end != NULL && STRNCMP(buf, end, idx) == 0)
{
if (end[idx] == NUL)
break; // Found the end of paste code.
continue;
}
if (!drop)
{
switch (mode)
{
case PASTE_CMDLINE:
put_on_cmdline(buf, idx, TRUE);
break;
case PASTE_EX:
if (gap != NULL && ga_grow(gap, idx) == OK)
{
mch_memmove((char *)gap->ga_data + gap->ga_len,
buf, (size_t)idx);
gap->ga_len += idx;
}
break;
case PASTE_INSERT:
if (stop_arrow() == OK)
{
c = buf[0];
if (idx == 1 && (c == CAR || c == K_KENTER || c == NL))
ins_eol(c);
else
{
ins_char_bytes(buf, idx);
AppendToRedobuffLit(buf, idx);
}
}
break;
case PASTE_ONE_CHAR:
if (ret_char == -1)
{
if (has_mbyte)
ret_char = (*mb_ptr2char)(buf);
else
ret_char = buf[0];
}
break;
}
}
idx = 0;
}
--no_mapping;
allow_keys = save_allow_keys;
if (!save_paste)
set_option_value((char_u *)"paste", FALSE, NULL, 0);
return ret_char;
}
| null | null | 208,370
|
254669502955167580665201581449085115752
| 96
|
patch 8.2.4218: illegal memory access with bracketed paste in Ex mode
Problem: Illegal memory access with bracketed paste in Ex mode.
Solution: Reserve space for the trailing NUL.
|
other
|
vim
|
27efc62f5d86afcb2ecb7565587fe8dea4b036fe
| 1
|
check_termcode(
int max_offset,
char_u *buf,
int bufsize,
int *buflen)
{
char_u *tp;
char_u *p;
int slen = 0; // init for GCC
int modslen;
int len;
int retval = 0;
int offset;
char_u key_name[2];
int modifiers;
char_u *modifiers_start = NULL;
int key;
int new_slen; // Length of what will replace the termcode
char_u string[MAX_KEY_CODE_LEN + 1];
int i, j;
int idx = 0;
int cpo_koffset;
cpo_koffset = (vim_strchr(p_cpo, CPO_KOFFSET) != NULL);
/*
* Speed up the checks for terminal codes by gathering all first bytes
* used in termleader[]. Often this is just a single <Esc>.
*/
if (need_gather)
gather_termleader();
/*
* Check at several positions in typebuf.tb_buf[], to catch something like
* "x<Up>" that can be mapped. Stop at max_offset, because characters
* after that cannot be used for mapping, and with @r commands
* typebuf.tb_buf[] can become very long.
* This is used often, KEEP IT FAST!
*/
for (offset = 0; offset < max_offset; ++offset)
{
if (buf == NULL)
{
if (offset >= typebuf.tb_len)
break;
tp = typebuf.tb_buf + typebuf.tb_off + offset;
len = typebuf.tb_len - offset; // length of the input
}
else
{
if (offset >= *buflen)
break;
tp = buf + offset;
len = *buflen - offset;
}
/*
* Don't check characters after K_SPECIAL, those are already
* translated terminal chars (avoid translating ~@^Hx).
*/
if (*tp == K_SPECIAL)
{
offset += 2; // there are always 2 extra characters
continue;
}
/*
* Skip this position if the character does not appear as the first
* character in term_strings. This speeds up a lot, since most
* termcodes start with the same character (ESC or CSI).
*/
i = *tp;
for (p = termleader; *p && *p != i; ++p)
;
if (*p == NUL)
continue;
/*
* Skip this position if p_ek is not set and tp[0] is an ESC and we
* are in Insert mode.
*/
if (*tp == ESC && !p_ek && (State & MODE_INSERT))
continue;
key_name[0] = NUL; // no key name found yet
key_name[1] = NUL; // no key name found yet
modifiers = 0; // no modifiers yet
#ifdef FEAT_GUI
if (gui.in_use)
{
/*
* GUI special key codes are all of the form [CSI xx].
*/
if (*tp == CSI) // Special key from GUI
{
if (len < 3)
return -1; // Shouldn't happen
slen = 3;
key_name[0] = tp[1];
key_name[1] = tp[2];
}
}
else
#endif // FEAT_GUI
{
int mouse_index_found = -1;
for (idx = 0; idx < tc_len; ++idx)
{
/*
* Ignore the entry if we are not at the start of
* typebuf.tb_buf[]
* and there are not enough characters to make a match.
* But only when the 'K' flag is in 'cpoptions'.
*/
slen = termcodes[idx].len;
modifiers_start = NULL;
if (cpo_koffset && offset && len < slen)
continue;
if (STRNCMP(termcodes[idx].code, tp,
(size_t)(slen > len ? len : slen)) == 0)
{
int looks_like_mouse_start = FALSE;
if (len < slen) // got a partial sequence
return -1; // need to get more chars
/*
* When found a keypad key, check if there is another key
* that matches and use that one. This makes <Home> to be
* found instead of <kHome> when they produce the same
* key code.
*/
if (termcodes[idx].name[0] == 'K'
&& VIM_ISDIGIT(termcodes[idx].name[1]))
{
for (j = idx + 1; j < tc_len; ++j)
if (termcodes[j].len == slen &&
STRNCMP(termcodes[idx].code,
termcodes[j].code, slen) == 0)
{
idx = j;
break;
}
}
if (slen == 2 && len > 2
&& termcodes[idx].code[0] == ESC
&& termcodes[idx].code[1] == '[')
{
// The mouse termcode "ESC [" is also the prefix of
// "ESC [ I" (focus gained) and other keys. Check some
// more bytes to find out.
if (!isdigit(tp[2]))
{
// ESC [ without number following: Only use it when
// there is no other match.
looks_like_mouse_start = TRUE;
}
else if (termcodes[idx].name[0] == KS_DEC_MOUSE)
{
char_u *nr = tp + 2;
int count = 0;
// If a digit is following it could be a key with
// modifier, e.g., ESC [ 1;2P. Can be confused
// with DEC_MOUSE, which requires four numbers
// following. If not then it can't be a DEC_MOUSE
// code.
for (;;)
{
++count;
(void)getdigits(&nr);
if (nr >= tp + len)
return -1; // partial sequence
if (*nr != ';')
break;
++nr;
if (nr >= tp + len)
return -1; // partial sequence
}
if (count < 4)
continue; // no match
}
}
if (looks_like_mouse_start)
{
// Only use it when there is no other match.
if (mouse_index_found < 0)
mouse_index_found = idx;
}
else
{
key_name[0] = termcodes[idx].name[0];
key_name[1] = termcodes[idx].name[1];
break;
}
}
/*
* Check for code with modifier, like xterm uses:
* <Esc>[123;*X (modslen == slen - 3)
* <Esc>[@;*X (matches <Esc>[X and <Esc>[1;9X )
* Also <Esc>O*X and <M-O>*X (modslen == slen - 2).
* When there is a modifier the * matches a number.
* When there is no modifier the ;* or * is omitted.
*/
if (termcodes[idx].modlen > 0 && mouse_index_found < 0)
{
int at_code;
modslen = termcodes[idx].modlen;
if (cpo_koffset && offset && len < modslen)
continue;
at_code = termcodes[idx].code[modslen] == '@';
if (STRNCMP(termcodes[idx].code, tp,
(size_t)(modslen > len ? len : modslen)) == 0)
{
int n;
if (len <= modslen) // got a partial sequence
return -1; // need to get more chars
if (tp[modslen] == termcodes[idx].code[slen - 1])
// no modifiers
slen = modslen + 1;
else if (tp[modslen] != ';' && modslen == slen - 3)
// no match for "code;*X" with "code;"
continue;
else if (at_code && tp[modslen] != '1')
// no match for "<Esc>[@" with "<Esc>[1"
continue;
else
{
// Skip over the digits, the final char must
// follow. URXVT can use a negative value, thus
// also accept '-'.
for (j = slen - 2; j < len && (isdigit(tp[j])
|| tp[j] == '-' || tp[j] == ';'); ++j)
;
++j;
if (len < j) // got a partial sequence
return -1; // need to get more chars
if (tp[j - 1] != termcodes[idx].code[slen - 1])
continue; // no match
modifiers_start = tp + slen - 2;
// Match! Convert modifier bits.
n = atoi((char *)modifiers_start);
modifiers |= decode_modifiers(n);
slen = j;
}
key_name[0] = termcodes[idx].name[0];
key_name[1] = termcodes[idx].name[1];
break;
}
}
}
if (idx == tc_len && mouse_index_found >= 0)
{
key_name[0] = termcodes[mouse_index_found].name[0];
key_name[1] = termcodes[mouse_index_found].name[1];
}
}
#ifdef FEAT_TERMRESPONSE
if (key_name[0] == NUL
// Mouse codes of DEC and pterm start with <ESC>[. When
// detecting the start of these mouse codes they might as well be
// another key code or terminal response.
# ifdef FEAT_MOUSE_DEC
|| key_name[0] == KS_DEC_MOUSE
# endif
# ifdef FEAT_MOUSE_PTERM
|| key_name[0] == KS_PTERM_MOUSE
# endif
)
{
char_u *argp = tp[0] == ESC ? tp + 2 : tp + 1;
/*
* Check for responses from the terminal starting with {lead}:
* "<Esc>[" or CSI followed by [0-9>?]
*
* - Xterm version string: {lead}>{x};{vers};{y}c
* Also eat other possible responses to t_RV, rxvt returns
* "{lead}?1;2c".
*
* - Cursor position report: {lead}{row};{col}R
* The final byte must be 'R'. It is used for checking the
* ambiguous-width character state.
*
* - window position reply: {lead}3;{x};{y}t
*
* - key with modifiers when modifyOtherKeys is enabled:
* {lead}27;{modifier};{key}~
* {lead}{key};{modifier}u
*/
if (((tp[0] == ESC && len >= 3 && tp[1] == '[')
|| (tp[0] == CSI && len >= 2))
&& (VIM_ISDIGIT(*argp) || *argp == '>' || *argp == '?'))
{
int resp = handle_csi(tp, len, argp, offset, buf,
bufsize, buflen, key_name, &slen);
if (resp != 0)
{
# ifdef DEBUG_TERMRESPONSE
if (resp == -1)
LOG_TR(("Not enough characters for CSI sequence"));
# endif
return resp;
}
}
// Check for fore/background color response from the terminal,
// starting} with <Esc>] or OSC
else if ((*T_RBG != NUL || *T_RFG != NUL)
&& ((tp[0] == ESC && len >= 2 && tp[1] == ']')
|| tp[0] == OSC))
{
if (handle_osc(tp, argp, len, key_name, &slen) == FAIL)
return -1;
}
// Check for key code response from xterm,
// starting with <Esc>P or DCS
else if ((check_for_codes || rcs_status.tr_progress == STATUS_SENT)
&& ((tp[0] == ESC && len >= 2 && tp[1] == 'P')
|| tp[0] == DCS))
{
if (handle_dcs(tp, argp, len, key_name, &slen) == FAIL)
return -1;
}
}
#endif
if (key_name[0] == NUL)
continue; // No match at this position, try next one
// We only get here when we have a complete termcode match
#ifdef FEAT_GUI
/*
* Only in the GUI: Fetch the pointer coordinates of the scroll event
* so that we know which window to scroll later.
*/
if (gui.in_use
&& key_name[0] == (int)KS_EXTRA
&& (key_name[1] == (int)KE_X1MOUSE
|| key_name[1] == (int)KE_X2MOUSE
|| key_name[1] == (int)KE_MOUSEMOVE_XY
|| key_name[1] == (int)KE_MOUSELEFT
|| key_name[1] == (int)KE_MOUSERIGHT
|| key_name[1] == (int)KE_MOUSEDOWN
|| key_name[1] == (int)KE_MOUSEUP))
{
char_u bytes[6];
int num_bytes = get_bytes_from_buf(tp + slen, bytes, 4);
if (num_bytes == -1) // not enough coordinates
return -1;
mouse_col = 128 * (bytes[0] - ' ' - 1) + bytes[1] - ' ' - 1;
mouse_row = 128 * (bytes[2] - ' ' - 1) + bytes[3] - ' ' - 1;
slen += num_bytes;
// equal to K_MOUSEMOVE
if (key_name[1] == (int)KE_MOUSEMOVE_XY)
key_name[1] = (int)KE_MOUSEMOVE;
}
else
#endif
/*
* If it is a mouse click, get the coordinates.
*/
if (key_name[0] == KS_MOUSE
#ifdef FEAT_MOUSE_GPM
|| key_name[0] == KS_GPM_MOUSE
#endif
#ifdef FEAT_MOUSE_JSB
|| key_name[0] == KS_JSBTERM_MOUSE
#endif
#ifdef FEAT_MOUSE_NET
|| key_name[0] == KS_NETTERM_MOUSE
#endif
#ifdef FEAT_MOUSE_DEC
|| key_name[0] == KS_DEC_MOUSE
#endif
#ifdef FEAT_MOUSE_PTERM
|| key_name[0] == KS_PTERM_MOUSE
#endif
#ifdef FEAT_MOUSE_URXVT
|| key_name[0] == KS_URXVT_MOUSE
#endif
|| key_name[0] == KS_SGR_MOUSE
|| key_name[0] == KS_SGR_MOUSE_RELEASE)
{
if (check_termcode_mouse(tp, &slen, key_name, modifiers_start, idx,
&modifiers) == -1)
return -1;
}
#ifdef FEAT_GUI
/*
* If using the GUI, then we get menu and scrollbar events.
*
* A menu event is encoded as K_SPECIAL, KS_MENU, KE_FILLER followed by
* four bytes which are to be taken as a pointer to the vimmenu_T
* structure.
*
* A tab line event is encoded as K_SPECIAL KS_TABLINE nr, where "nr"
* is one byte with the tab index.
*
* A scrollbar event is K_SPECIAL, KS_VER_SCROLLBAR, KE_FILLER followed
* by one byte representing the scrollbar number, and then four bytes
* representing a long_u which is the new value of the scrollbar.
*
* A horizontal scrollbar event is K_SPECIAL, KS_HOR_SCROLLBAR,
* KE_FILLER followed by four bytes representing a long_u which is the
* new value of the scrollbar.
*/
# ifdef FEAT_MENU
else if (key_name[0] == (int)KS_MENU)
{
long_u val;
int num_bytes = get_long_from_buf(tp + slen, &val);
if (num_bytes == -1)
return -1;
current_menu = (vimmenu_T *)val;
slen += num_bytes;
// The menu may have been deleted right after it was used, check
// for that.
if (check_menu_pointer(root_menu, current_menu) == FAIL)
{
key_name[0] = KS_EXTRA;
key_name[1] = (int)KE_IGNORE;
}
}
# endif
# ifdef FEAT_GUI_TABLINE
else if (key_name[0] == (int)KS_TABLINE)
{
// Selecting tabline tab or using its menu.
char_u bytes[6];
int num_bytes = get_bytes_from_buf(tp + slen, bytes, 1);
if (num_bytes == -1)
return -1;
current_tab = (int)bytes[0];
if (current_tab == 255) // -1 in a byte gives 255
current_tab = -1;
slen += num_bytes;
}
else if (key_name[0] == (int)KS_TABMENU)
{
// Selecting tabline tab or using its menu.
char_u bytes[6];
int num_bytes = get_bytes_from_buf(tp + slen, bytes, 2);
if (num_bytes == -1)
return -1;
current_tab = (int)bytes[0];
current_tabmenu = (int)bytes[1];
slen += num_bytes;
}
# endif
# ifndef USE_ON_FLY_SCROLL
else if (key_name[0] == (int)KS_VER_SCROLLBAR)
{
long_u val;
char_u bytes[6];
int num_bytes;
// Get the last scrollbar event in the queue of the same type
j = 0;
for (i = 0; tp[j] == CSI && tp[j + 1] == KS_VER_SCROLLBAR
&& tp[j + 2] != NUL; ++i)
{
j += 3;
num_bytes = get_bytes_from_buf(tp + j, bytes, 1);
if (num_bytes == -1)
break;
if (i == 0)
current_scrollbar = (int)bytes[0];
else if (current_scrollbar != (int)bytes[0])
break;
j += num_bytes;
num_bytes = get_long_from_buf(tp + j, &val);
if (num_bytes == -1)
break;
scrollbar_value = val;
j += num_bytes;
slen = j;
}
if (i == 0) // not enough characters to make one
return -1;
}
else if (key_name[0] == (int)KS_HOR_SCROLLBAR)
{
long_u val;
int num_bytes;
// Get the last horiz. scrollbar event in the queue
j = 0;
for (i = 0; tp[j] == CSI && tp[j + 1] == KS_HOR_SCROLLBAR
&& tp[j + 2] != NUL; ++i)
{
j += 3;
num_bytes = get_long_from_buf(tp + j, &val);
if (num_bytes == -1)
break;
scrollbar_value = val;
j += num_bytes;
slen = j;
}
if (i == 0) // not enough characters to make one
return -1;
}
# endif // !USE_ON_FLY_SCROLL
#endif // FEAT_GUI
#if (defined(UNIX) || defined(VMS))
/*
* Handle FocusIn/FocusOut event sequences reported by XTerm.
* (CSI I/CSI O)
*/
if (key_name[0] == KS_EXTRA
# ifdef FEAT_GUI
&& !gui.in_use
# endif
)
{
if (key_name[1] == KE_FOCUSGAINED)
{
if (!focus_state)
{
ui_focus_change(TRUE);
did_cursorhold = TRUE;
focus_state = TRUE;
}
key_name[1] = (int)KE_IGNORE;
}
else if (key_name[1] == KE_FOCUSLOST)
{
if (focus_state)
{
ui_focus_change(FALSE);
did_cursorhold = TRUE;
focus_state = FALSE;
}
key_name[1] = (int)KE_IGNORE;
}
}
#endif
/*
* Change <xHome> to <Home>, <xUp> to <Up>, etc.
*/
key = handle_x_keys(TERMCAP2KEY(key_name[0], key_name[1]));
/*
* Add any modifier codes to our string.
*/
new_slen = modifiers2keycode(modifiers, &key, string);
// Finally, add the special key code to our string
key_name[0] = KEY2TERMCAP0(key);
key_name[1] = KEY2TERMCAP1(key);
if (key_name[0] == KS_KEY)
{
// from ":set <M-b>=xx"
if (has_mbyte)
new_slen += (*mb_char2bytes)(key_name[1], string + new_slen);
else
string[new_slen++] = key_name[1];
}
else if (new_slen == 0 && key_name[0] == KS_EXTRA
&& key_name[1] == KE_IGNORE)
{
// Do not put K_IGNORE into the buffer, do return KEYLEN_REMOVED
// to indicate what happened.
retval = KEYLEN_REMOVED;
}
else
{
string[new_slen++] = K_SPECIAL;
string[new_slen++] = key_name[0];
string[new_slen++] = key_name[1];
}
if (put_string_in_typebuf(offset, slen, string, new_slen,
buf, bufsize, buflen) == FAIL)
return -1;
return retval == 0 ? (len + new_slen - slen + offset) : retval;
}
#ifdef FEAT_TERMRESPONSE
LOG_TR(("normal character"));
#endif
return 0; // no match found
}
| null | null | 208,411
|
141177609605865586721920240131748064761
| 604
|
patch 9.0.0018: going over the end of the typahead
Problem: Going over the end of the typahead.
Solution: Put a NUL after the typeahead.
|
other
|
vim
|
c5274dd12224421f2430b30c53b881b9403d649e
| 1
|
ex_diffgetput(exarg_T *eap)
{
linenr_T lnum;
int count;
linenr_T off = 0;
diff_T *dp;
diff_T *dprev;
diff_T *dfree;
int idx_cur;
int idx_other;
int idx_from;
int idx_to;
int i;
int added;
char_u *p;
aco_save_T aco;
buf_T *buf;
int start_skip, end_skip;
int new_count;
int buf_empty;
int found_not_ma = FALSE;
// Find the current buffer in the list of diff buffers.
idx_cur = diff_buf_idx(curbuf);
if (idx_cur == DB_COUNT)
{
emsg(_(e_current_buffer_is_not_in_diff_mode));
return;
}
if (*eap->arg == NUL)
{
// No argument: Find the other buffer in the list of diff buffers.
for (idx_other = 0; idx_other < DB_COUNT; ++idx_other)
if (curtab->tp_diffbuf[idx_other] != curbuf
&& curtab->tp_diffbuf[idx_other] != NULL)
{
if (eap->cmdidx != CMD_diffput
|| curtab->tp_diffbuf[idx_other]->b_p_ma)
break;
found_not_ma = TRUE;
}
if (idx_other == DB_COUNT)
{
if (found_not_ma)
emsg(_(e_no_other_buffer_in_diff_mode_is_modifiable));
else
emsg(_(e_no_other_buffer_in_diff_mode));
return;
}
// Check that there isn't a third buffer in the list
for (i = idx_other + 1; i < DB_COUNT; ++i)
if (curtab->tp_diffbuf[i] != curbuf
&& curtab->tp_diffbuf[i] != NULL
&& (eap->cmdidx != CMD_diffput || curtab->tp_diffbuf[i]->b_p_ma))
{
emsg(_(e_more_than_two_buffers_in_diff_mode_dont_know_which_one_to_use));
return;
}
}
else
{
// Buffer number or pattern given. Ignore trailing white space.
p = eap->arg + STRLEN(eap->arg);
while (p > eap->arg && VIM_ISWHITE(p[-1]))
--p;
for (i = 0; vim_isdigit(eap->arg[i]) && eap->arg + i < p; ++i)
;
if (eap->arg + i == p) // digits only
i = atol((char *)eap->arg);
else
{
i = buflist_findpat(eap->arg, p, FALSE, TRUE, FALSE);
if (i < 0)
return; // error message already given
}
buf = buflist_findnr(i);
if (buf == NULL)
{
semsg(_(e_cant_find_buffer_str), eap->arg);
return;
}
if (buf == curbuf)
return; // nothing to do
idx_other = diff_buf_idx(buf);
if (idx_other == DB_COUNT)
{
semsg(_(e_buffer_str_is_not_in_diff_mode), eap->arg);
return;
}
}
diff_busy = TRUE;
// When no range given include the line above or below the cursor.
if (eap->addr_count == 0)
{
// Make it possible that ":diffget" on the last line gets line below
// the cursor line when there is no difference above the cursor.
if (eap->cmdidx == CMD_diffget
&& eap->line1 == curbuf->b_ml.ml_line_count
&& diff_check(curwin, eap->line1) == 0
&& (eap->line1 == 1 || diff_check(curwin, eap->line1 - 1) == 0))
++eap->line2;
else if (eap->line1 > 0)
--eap->line1;
}
if (eap->cmdidx == CMD_diffget)
{
idx_from = idx_other;
idx_to = idx_cur;
}
else
{
idx_from = idx_cur;
idx_to = idx_other;
// Need to make the other buffer the current buffer to be able to make
// changes in it.
// set curwin/curbuf to buf and save a few things
aucmd_prepbuf(&aco, curtab->tp_diffbuf[idx_other]);
}
// May give the warning for a changed buffer here, which can trigger the
// FileChangedRO autocommand, which may do nasty things and mess
// everything up.
if (!curbuf->b_changed)
{
change_warning(0);
if (diff_buf_idx(curbuf) != idx_to)
{
emsg(_(e_buffer_changed_unexpectedly));
goto theend;
}
}
dprev = NULL;
for (dp = curtab->tp_first_diff; dp != NULL; )
{
if (dp->df_lnum[idx_cur] > eap->line2 + off)
break; // past the range that was specified
dfree = NULL;
lnum = dp->df_lnum[idx_to];
count = dp->df_count[idx_to];
if (dp->df_lnum[idx_cur] + dp->df_count[idx_cur] > eap->line1 + off
&& u_save(lnum - 1, lnum + count) != FAIL)
{
// Inside the specified range and saving for undo worked.
start_skip = 0;
end_skip = 0;
if (eap->addr_count > 0)
{
// A range was specified: check if lines need to be skipped.
start_skip = eap->line1 + off - dp->df_lnum[idx_cur];
if (start_skip > 0)
{
// range starts below start of current diff block
if (start_skip > count)
{
lnum += count;
count = 0;
}
else
{
count -= start_skip;
lnum += start_skip;
}
}
else
start_skip = 0;
end_skip = dp->df_lnum[idx_cur] + dp->df_count[idx_cur] - 1
- (eap->line2 + off);
if (end_skip > 0)
{
// range ends above end of current/from diff block
if (idx_cur == idx_from) // :diffput
{
i = dp->df_count[idx_cur] - start_skip - end_skip;
if (count > i)
count = i;
}
else // :diffget
{
count -= end_skip;
end_skip = dp->df_count[idx_from] - start_skip - count;
if (end_skip < 0)
end_skip = 0;
}
}
else
end_skip = 0;
}
buf_empty = BUFEMPTY();
added = 0;
for (i = 0; i < count; ++i)
{
// remember deleting the last line of the buffer
buf_empty = curbuf->b_ml.ml_line_count == 1;
ml_delete(lnum);
--added;
}
for (i = 0; i < dp->df_count[idx_from] - start_skip - end_skip; ++i)
{
linenr_T nr;
nr = dp->df_lnum[idx_from] + start_skip + i;
if (nr > curtab->tp_diffbuf[idx_from]->b_ml.ml_line_count)
break;
p = vim_strsave(ml_get_buf(curtab->tp_diffbuf[idx_from],
nr, FALSE));
if (p != NULL)
{
ml_append(lnum + i - 1, p, 0, FALSE);
vim_free(p);
++added;
if (buf_empty && curbuf->b_ml.ml_line_count == 2)
{
// Added the first line into an empty buffer, need to
// delete the dummy empty line.
buf_empty = FALSE;
ml_delete((linenr_T)2);
}
}
}
new_count = dp->df_count[idx_to] + added;
dp->df_count[idx_to] = new_count;
if (start_skip == 0 && end_skip == 0)
{
// Check if there are any other buffers and if the diff is
// equal in them.
for (i = 0; i < DB_COUNT; ++i)
if (curtab->tp_diffbuf[i] != NULL && i != idx_from
&& i != idx_to
&& !diff_equal_entry(dp, idx_from, i))
break;
if (i == DB_COUNT)
{
// delete the diff entry, the buffers are now equal here
dfree = dp;
dp = dp->df_next;
if (dprev == NULL)
curtab->tp_first_diff = dp;
else
dprev->df_next = dp;
}
}
// Adjust marks. This will change the following entries!
if (added != 0)
{
mark_adjust(lnum, lnum + count - 1, (long)MAXLNUM, (long)added);
if (curwin->w_cursor.lnum >= lnum)
{
// Adjust the cursor position if it's in/after the changed
// lines.
if (curwin->w_cursor.lnum >= lnum + count)
curwin->w_cursor.lnum += added;
else if (added < 0)
curwin->w_cursor.lnum = lnum;
}
}
changed_lines(lnum, 0, lnum + count, (long)added);
if (dfree != NULL)
{
// Diff is deleted, update folds in other windows.
#ifdef FEAT_FOLDING
diff_fold_update(dfree, idx_to);
#endif
vim_free(dfree);
}
else
// mark_adjust() may have changed the count in a wrong way
dp->df_count[idx_to] = new_count;
// When changing the current buffer, keep track of line numbers
if (idx_cur == idx_to)
off += added;
}
// If before the range or not deleted, go to next diff.
if (dfree == NULL)
{
dprev = dp;
dp = dp->df_next;
}
}
// restore curwin/curbuf and a few other things
if (eap->cmdidx != CMD_diffget)
{
// Syncing undo only works for the current buffer, but we change
// another buffer. Sync undo if the command was typed. This isn't
// 100% right when ":diffput" is used in a function or mapping.
if (KeyTyped)
u_sync(FALSE);
aucmd_restbuf(&aco);
}
theend:
diff_busy = FALSE;
if (diff_need_update)
ex_diffupdate(NULL);
// Check that the cursor is on a valid character and update its
// position. When there were filler lines the topline has become
// invalid.
check_cursor();
changed_line_abv_curs();
if (diff_need_update)
// redraw already done by ex_diffupdate()
diff_need_update = FALSE;
else
{
// Also need to redraw the other buffers.
diff_redraw(FALSE);
apply_autocmds(EVENT_DIFFUPDATED, NULL, NULL, FALSE, curbuf);
}
}
| null | null | 208,421
|
58922319338264688518591068281475702979
| 325
|
patch 9.0.0026: accessing freed memory with diff put
Problem: Accessing freed memory with diff put.
Solution: Bail out when diff pointer is no longer valid.
|
other
|
linux
|
717adfdaf14704fd3ec7fa2c04520c0723247eac
| 1
|
static ssize_t hid_debug_events_read(struct file *file, char __user *buffer,
size_t count, loff_t *ppos)
{
struct hid_debug_list *list = file->private_data;
int ret = 0, len;
DECLARE_WAITQUEUE(wait, current);
mutex_lock(&list->read_mutex);
while (ret == 0) {
if (list->head == list->tail) {
add_wait_queue(&list->hdev->debug_wait, &wait);
set_current_state(TASK_INTERRUPTIBLE);
while (list->head == list->tail) {
if (file->f_flags & O_NONBLOCK) {
ret = -EAGAIN;
break;
}
if (signal_pending(current)) {
ret = -ERESTARTSYS;
break;
}
if (!list->hdev || !list->hdev->debug) {
ret = -EIO;
set_current_state(TASK_RUNNING);
goto out;
}
/* allow O_NONBLOCK from other threads */
mutex_unlock(&list->read_mutex);
schedule();
mutex_lock(&list->read_mutex);
set_current_state(TASK_INTERRUPTIBLE);
}
set_current_state(TASK_RUNNING);
remove_wait_queue(&list->hdev->debug_wait, &wait);
}
if (ret)
goto out;
/* pass the ringbuffer contents to userspace */
copy_rest:
if (list->tail == list->head)
goto out;
if (list->tail > list->head) {
len = list->tail - list->head;
if (copy_to_user(buffer + ret, &list->hid_debug_buf[list->head], len)) {
ret = -EFAULT;
goto out;
}
ret += len;
list->head += len;
} else {
len = HID_DEBUG_BUFSIZE - list->head;
if (copy_to_user(buffer, &list->hid_debug_buf[list->head], len)) {
ret = -EFAULT;
goto out;
}
list->head = 0;
ret += len;
goto copy_rest;
}
}
out:
mutex_unlock(&list->read_mutex);
return ret;
}
| null | null | 208,430
|
155206844330449950846334904452225854896
| 73
|
HID: debug: check length before copy_to_user()
If our length is greater than the size of the buffer, we
overflow the buffer
Cc: [email protected]
Signed-off-by: Daniel Rosenberg <[email protected]>
Reviewed-by: Benjamin Tissoires <[email protected]>
Signed-off-by: Jiri Kosina <[email protected]>
|
other
|
linux
|
ec6af094ea28f0f2dda1a6a33b14cd57e36a9755
| 1
|
static int packet_set_ring(struct sock *sk, union tpacket_req_u *req_u,
int closing, int tx_ring)
{
struct pgv *pg_vec = NULL;
struct packet_sock *po = pkt_sk(sk);
unsigned long *rx_owner_map = NULL;
int was_running, order = 0;
struct packet_ring_buffer *rb;
struct sk_buff_head *rb_queue;
__be16 num;
int err;
/* Added to avoid minimal code churn */
struct tpacket_req *req = &req_u->req;
rb = tx_ring ? &po->tx_ring : &po->rx_ring;
rb_queue = tx_ring ? &sk->sk_write_queue : &sk->sk_receive_queue;
err = -EBUSY;
if (!closing) {
if (atomic_read(&po->mapped))
goto out;
if (packet_read_pending(rb))
goto out;
}
if (req->tp_block_nr) {
unsigned int min_frame_size;
/* Sanity tests and some calculations */
err = -EBUSY;
if (unlikely(rb->pg_vec))
goto out;
switch (po->tp_version) {
case TPACKET_V1:
po->tp_hdrlen = TPACKET_HDRLEN;
break;
case TPACKET_V2:
po->tp_hdrlen = TPACKET2_HDRLEN;
break;
case TPACKET_V3:
po->tp_hdrlen = TPACKET3_HDRLEN;
break;
}
err = -EINVAL;
if (unlikely((int)req->tp_block_size <= 0))
goto out;
if (unlikely(!PAGE_ALIGNED(req->tp_block_size)))
goto out;
min_frame_size = po->tp_hdrlen + po->tp_reserve;
if (po->tp_version >= TPACKET_V3 &&
req->tp_block_size <
BLK_PLUS_PRIV((u64)req_u->req3.tp_sizeof_priv) + min_frame_size)
goto out;
if (unlikely(req->tp_frame_size < min_frame_size))
goto out;
if (unlikely(req->tp_frame_size & (TPACKET_ALIGNMENT - 1)))
goto out;
rb->frames_per_block = req->tp_block_size / req->tp_frame_size;
if (unlikely(rb->frames_per_block == 0))
goto out;
if (unlikely(rb->frames_per_block > UINT_MAX / req->tp_block_nr))
goto out;
if (unlikely((rb->frames_per_block * req->tp_block_nr) !=
req->tp_frame_nr))
goto out;
err = -ENOMEM;
order = get_order(req->tp_block_size);
pg_vec = alloc_pg_vec(req, order);
if (unlikely(!pg_vec))
goto out;
switch (po->tp_version) {
case TPACKET_V3:
/* Block transmit is not supported yet */
if (!tx_ring) {
init_prb_bdqc(po, rb, pg_vec, req_u);
} else {
struct tpacket_req3 *req3 = &req_u->req3;
if (req3->tp_retire_blk_tov ||
req3->tp_sizeof_priv ||
req3->tp_feature_req_word) {
err = -EINVAL;
goto out_free_pg_vec;
}
}
break;
default:
if (!tx_ring) {
rx_owner_map = bitmap_alloc(req->tp_frame_nr,
GFP_KERNEL | __GFP_NOWARN | __GFP_ZERO);
if (!rx_owner_map)
goto out_free_pg_vec;
}
break;
}
}
/* Done */
else {
err = -EINVAL;
if (unlikely(req->tp_frame_nr))
goto out;
}
/* Detach socket from network */
spin_lock(&po->bind_lock);
was_running = po->running;
num = po->num;
if (was_running) {
WRITE_ONCE(po->num, 0);
__unregister_prot_hook(sk, false);
}
spin_unlock(&po->bind_lock);
synchronize_net();
err = -EBUSY;
mutex_lock(&po->pg_vec_lock);
if (closing || atomic_read(&po->mapped) == 0) {
err = 0;
spin_lock_bh(&rb_queue->lock);
swap(rb->pg_vec, pg_vec);
if (po->tp_version <= TPACKET_V2)
swap(rb->rx_owner_map, rx_owner_map);
rb->frame_max = (req->tp_frame_nr - 1);
rb->head = 0;
rb->frame_size = req->tp_frame_size;
spin_unlock_bh(&rb_queue->lock);
swap(rb->pg_vec_order, order);
swap(rb->pg_vec_len, req->tp_block_nr);
rb->pg_vec_pages = req->tp_block_size/PAGE_SIZE;
po->prot_hook.func = (po->rx_ring.pg_vec) ?
tpacket_rcv : packet_rcv;
skb_queue_purge(rb_queue);
if (atomic_read(&po->mapped))
pr_err("packet_mmap: vma is busy: %d\n",
atomic_read(&po->mapped));
}
mutex_unlock(&po->pg_vec_lock);
spin_lock(&po->bind_lock);
if (was_running) {
WRITE_ONCE(po->num, num);
register_prot_hook(sk);
}
spin_unlock(&po->bind_lock);
if (pg_vec && (po->tp_version > TPACKET_V2)) {
/* Because we don't support block-based V3 on tx-ring */
if (!tx_ring)
prb_shutdown_retire_blk_timer(po, rb_queue);
}
out_free_pg_vec:
bitmap_free(rx_owner_map);
if (pg_vec)
free_pg_vec(pg_vec, order, req->tp_block_nr);
out:
return err;
}
| null | null | 208,464
|
200165837155630935603644589325319442945
| 165
|
net/packet: rx_owner_map depends on pg_vec
Packet sockets may switch ring versions. Avoid misinterpreting state
between versions, whose fields share a union. rx_owner_map is only
allocated with a packet ring (pg_vec) and both are swapped together.
If pg_vec is NULL, meaning no packet ring was allocated, then neither
was rx_owner_map. And the field may be old state from a tpacket_v3.
Fixes: 61fad6816fc1 ("net/packet: tpacket_rcv: avoid a producer race condition")
Reported-by: Syzbot <[email protected]>
Signed-off-by: Willem de Bruijn <[email protected]>
Reviewed-by: Eric Dumazet <[email protected]>
Link: https://lore.kernel.org/r/[email protected]
Signed-off-by: Jakub Kicinski <[email protected]>
|
other
|
at-spi2-core
|
c2e87fe00b596dba20c9d57d406ab8faa744b15a
| 1
|
unix_read_all_fd_to_string (int fd,
char *buf,
ssize_t max_bytes)
{
ssize_t bytes_read;
while (max_bytes > 1 && (bytes_read = read (fd, buf, MAX (4096, max_bytes - 1))))
{
if (bytes_read < 0)
return FALSE;
buf += bytes_read;
max_bytes -= bytes_read;
}
*buf = '\0';
return TRUE;
}
| null | null | 208,489
|
150591971212711102629762668927420518838
| 16
|
Fix inverted logic.
Don't write more into a buffer than it can hold.
https://bugzilla.gnome.org/show_bug.cgi?id=791124
|
other
|
tor
|
57e35ad3d91724882c345ac709666a551a977f0f
| 1
|
networkstatus_parse_vote_from_string(const char *s, const char **eos_out,
networkstatus_type_t ns_type)
{
smartlist_t *tokens = smartlist_create();
smartlist_t *rs_tokens = NULL, *footer_tokens = NULL;
networkstatus_voter_info_t *voter = NULL;
networkstatus_t *ns = NULL;
digests_t ns_digests;
const char *cert, *end_of_header, *end_of_footer, *s_dup = s;
directory_token_t *tok;
int ok;
struct in_addr in;
int i, inorder, n_signatures = 0;
memarea_t *area = NULL, *rs_area = NULL;
consensus_flavor_t flav = FLAV_NS;
tor_assert(s);
if (eos_out)
*eos_out = NULL;
if (router_get_networkstatus_v3_hashes(s, &ns_digests)) {
log_warn(LD_DIR, "Unable to compute digest of network-status");
goto err;
}
area = memarea_new();
end_of_header = find_start_of_next_routerstatus(s);
if (tokenize_string(area, s, end_of_header, tokens,
(ns_type == NS_TYPE_CONSENSUS) ?
networkstatus_consensus_token_table :
networkstatus_token_table, 0)) {
log_warn(LD_DIR, "Error tokenizing network-status vote header");
goto err;
}
ns = tor_malloc_zero(sizeof(networkstatus_t));
memcpy(&ns->digests, &ns_digests, sizeof(ns_digests));
tok = find_by_keyword(tokens, K_NETWORK_STATUS_VERSION);
tor_assert(tok);
if (tok->n_args > 1) {
int flavor = networkstatus_parse_flavor_name(tok->args[1]);
if (flavor < 0) {
log_warn(LD_DIR, "Can't parse document with unknown flavor %s",
escaped(tok->args[2]));
goto err;
}
ns->flavor = flav = flavor;
}
if (flav != FLAV_NS && ns_type != NS_TYPE_CONSENSUS) {
log_warn(LD_DIR, "Flavor found on non-consensus networkstatus.");
goto err;
}
if (ns_type != NS_TYPE_CONSENSUS) {
const char *end_of_cert = NULL;
if (!(cert = strstr(s, "\ndir-key-certificate-version")))
goto err;
++cert;
ns->cert = authority_cert_parse_from_string(cert, &end_of_cert);
if (!ns->cert || !end_of_cert || end_of_cert > end_of_header)
goto err;
}
tok = find_by_keyword(tokens, K_VOTE_STATUS);
tor_assert(tok->n_args);
if (!strcmp(tok->args[0], "vote")) {
ns->type = NS_TYPE_VOTE;
} else if (!strcmp(tok->args[0], "consensus")) {
ns->type = NS_TYPE_CONSENSUS;
} else if (!strcmp(tok->args[0], "opinion")) {
ns->type = NS_TYPE_OPINION;
} else {
log_warn(LD_DIR, "Unrecognized vote status %s in network-status",
escaped(tok->args[0]));
goto err;
}
if (ns_type != ns->type) {
log_warn(LD_DIR, "Got the wrong kind of v3 networkstatus.");
goto err;
}
if (ns->type == NS_TYPE_VOTE || ns->type == NS_TYPE_OPINION) {
tok = find_by_keyword(tokens, K_PUBLISHED);
if (parse_iso_time(tok->args[0], &ns->published))
goto err;
ns->supported_methods = smartlist_create();
tok = find_opt_by_keyword(tokens, K_CONSENSUS_METHODS);
if (tok) {
for (i=0; i < tok->n_args; ++i)
smartlist_add(ns->supported_methods, tor_strdup(tok->args[i]));
} else {
smartlist_add(ns->supported_methods, tor_strdup("1"));
}
} else {
tok = find_opt_by_keyword(tokens, K_CONSENSUS_METHOD);
if (tok) {
ns->consensus_method = (int)tor_parse_long(tok->args[0], 10, 1, INT_MAX,
&ok, NULL);
if (!ok)
goto err;
} else {
ns->consensus_method = 1;
}
}
tok = find_by_keyword(tokens, K_VALID_AFTER);
if (parse_iso_time(tok->args[0], &ns->valid_after))
goto err;
tok = find_by_keyword(tokens, K_FRESH_UNTIL);
if (parse_iso_time(tok->args[0], &ns->fresh_until))
goto err;
tok = find_by_keyword(tokens, K_VALID_UNTIL);
if (parse_iso_time(tok->args[0], &ns->valid_until))
goto err;
tok = find_by_keyword(tokens, K_VOTING_DELAY);
tor_assert(tok->n_args >= 2);
ns->vote_seconds =
(int) tor_parse_long(tok->args[0], 10, 0, INT_MAX, &ok, NULL);
if (!ok)
goto err;
ns->dist_seconds =
(int) tor_parse_long(tok->args[1], 10, 0, INT_MAX, &ok, NULL);
if (!ok)
goto err;
if (ns->valid_after + MIN_VOTE_INTERVAL > ns->fresh_until) {
log_warn(LD_DIR, "Vote/consensus freshness interval is too short");
goto err;
}
if (ns->valid_after + MIN_VOTE_INTERVAL*2 > ns->valid_until) {
log_warn(LD_DIR, "Vote/consensus liveness interval is too short");
goto err;
}
if (ns->vote_seconds < MIN_VOTE_SECONDS) {
log_warn(LD_DIR, "Vote seconds is too short");
goto err;
}
if (ns->dist_seconds < MIN_DIST_SECONDS) {
log_warn(LD_DIR, "Dist seconds is too short");
goto err;
}
if ((tok = find_opt_by_keyword(tokens, K_CLIENT_VERSIONS))) {
ns->client_versions = tor_strdup(tok->args[0]);
}
if ((tok = find_opt_by_keyword(tokens, K_SERVER_VERSIONS))) {
ns->server_versions = tor_strdup(tok->args[0]);
}
tok = find_by_keyword(tokens, K_KNOWN_FLAGS);
ns->known_flags = smartlist_create();
inorder = 1;
for (i = 0; i < tok->n_args; ++i) {
smartlist_add(ns->known_flags, tor_strdup(tok->args[i]));
if (i>0 && strcmp(tok->args[i-1], tok->args[i])>= 0) {
log_warn(LD_DIR, "%s >= %s", tok->args[i-1], tok->args[i]);
inorder = 0;
}
}
if (!inorder) {
log_warn(LD_DIR, "known-flags not in order");
goto err;
}
tok = find_opt_by_keyword(tokens, K_PARAMS);
if (tok) {
inorder = 1;
ns->net_params = smartlist_create();
for (i = 0; i < tok->n_args; ++i) {
int ok=0;
char *eq = strchr(tok->args[i], '=');
if (!eq) {
log_warn(LD_DIR, "Bad element '%s' in params", escaped(tok->args[i]));
goto err;
}
tor_parse_long(eq+1, 10, INT32_MIN, INT32_MAX, &ok, NULL);
if (!ok) {
log_warn(LD_DIR, "Bad element '%s' in params", escaped(tok->args[i]));
goto err;
}
if (i > 0 && strcmp(tok->args[i-1], tok->args[i]) >= 0) {
log_warn(LD_DIR, "%s >= %s", tok->args[i-1], tok->args[i]);
inorder = 0;
}
smartlist_add(ns->net_params, tor_strdup(tok->args[i]));
}
if (!inorder) {
log_warn(LD_DIR, "params not in order");
goto err;
}
}
ns->voters = smartlist_create();
SMARTLIST_FOREACH_BEGIN(tokens, directory_token_t *, _tok) {
tok = _tok;
if (tok->tp == K_DIR_SOURCE) {
tor_assert(tok->n_args >= 6);
if (voter)
smartlist_add(ns->voters, voter);
voter = tor_malloc_zero(sizeof(networkstatus_voter_info_t));
voter->sigs = smartlist_create();
if (ns->type != NS_TYPE_CONSENSUS)
memcpy(voter->vote_digest, ns_digests.d[DIGEST_SHA1], DIGEST_LEN);
voter->nickname = tor_strdup(tok->args[0]);
if (strlen(tok->args[1]) != HEX_DIGEST_LEN ||
base16_decode(voter->identity_digest, sizeof(voter->identity_digest),
tok->args[1], HEX_DIGEST_LEN) < 0) {
log_warn(LD_DIR, "Error decoding identity digest %s in "
"network-status vote.", escaped(tok->args[1]));
goto err;
}
if (ns->type != NS_TYPE_CONSENSUS &&
tor_memneq(ns->cert->cache_info.identity_digest,
voter->identity_digest, DIGEST_LEN)) {
log_warn(LD_DIR,"Mismatch between identities in certificate and vote");
goto err;
}
voter->address = tor_strdup(tok->args[2]);
if (!tor_inet_aton(tok->args[3], &in)) {
log_warn(LD_DIR, "Error decoding IP address %s in network-status.",
escaped(tok->args[3]));
goto err;
}
voter->addr = ntohl(in.s_addr);
voter->dir_port = (uint16_t)
tor_parse_long(tok->args[4], 10, 0, 65535, &ok, NULL);
if (!ok)
goto err;
voter->or_port = (uint16_t)
tor_parse_long(tok->args[5], 10, 0, 65535, &ok, NULL);
if (!ok)
goto err;
} else if (tok->tp == K_CONTACT) {
if (!voter || voter->contact) {
log_warn(LD_DIR, "contact element is out of place.");
goto err;
}
voter->contact = tor_strdup(tok->args[0]);
} else if (tok->tp == K_VOTE_DIGEST) {
tor_assert(ns->type == NS_TYPE_CONSENSUS);
tor_assert(tok->n_args >= 1);
if (!voter || ! tor_digest_is_zero(voter->vote_digest)) {
log_warn(LD_DIR, "vote-digest element is out of place.");
goto err;
}
if (strlen(tok->args[0]) != HEX_DIGEST_LEN ||
base16_decode(voter->vote_digest, sizeof(voter->vote_digest),
tok->args[0], HEX_DIGEST_LEN) < 0) {
log_warn(LD_DIR, "Error decoding vote digest %s in "
"network-status consensus.", escaped(tok->args[0]));
goto err;
}
}
} SMARTLIST_FOREACH_END(_tok);
if (voter) {
smartlist_add(ns->voters, voter);
voter = NULL;
}
if (smartlist_len(ns->voters) == 0) {
log_warn(LD_DIR, "Missing dir-source elements in a vote networkstatus.");
goto err;
} else if (ns->type != NS_TYPE_CONSENSUS && smartlist_len(ns->voters) != 1) {
log_warn(LD_DIR, "Too many dir-source elements in a vote networkstatus.");
goto err;
}
if (ns->type != NS_TYPE_CONSENSUS &&
(tok = find_opt_by_keyword(tokens, K_LEGACY_DIR_KEY))) {
int bad = 1;
if (strlen(tok->args[0]) == HEX_DIGEST_LEN) {
networkstatus_voter_info_t *voter = smartlist_get(ns->voters, 0);
if (base16_decode(voter->legacy_id_digest, DIGEST_LEN,
tok->args[0], HEX_DIGEST_LEN)<0)
bad = 1;
else
bad = 0;
}
if (bad) {
log_warn(LD_DIR, "Invalid legacy key digest %s on vote.",
escaped(tok->args[0]));
}
}
/* Parse routerstatus lines. */
rs_tokens = smartlist_create();
rs_area = memarea_new();
s = end_of_header;
ns->routerstatus_list = smartlist_create();
while (!strcmpstart(s, "r ")) {
if (ns->type != NS_TYPE_CONSENSUS) {
vote_routerstatus_t *rs = tor_malloc_zero(sizeof(vote_routerstatus_t));
if (routerstatus_parse_entry_from_string(rs_area, &s, rs_tokens, ns,
rs, 0, 0))
smartlist_add(ns->routerstatus_list, rs);
else {
tor_free(rs->version);
tor_free(rs);
}
} else {
routerstatus_t *rs;
if ((rs = routerstatus_parse_entry_from_string(rs_area, &s, rs_tokens,
NULL, NULL,
ns->consensus_method,
flav)))
smartlist_add(ns->routerstatus_list, rs);
}
}
for (i = 1; i < smartlist_len(ns->routerstatus_list); ++i) {
routerstatus_t *rs1, *rs2;
if (ns->type != NS_TYPE_CONSENSUS) {
vote_routerstatus_t *a = smartlist_get(ns->routerstatus_list, i-1);
vote_routerstatus_t *b = smartlist_get(ns->routerstatus_list, i);
rs1 = &a->status; rs2 = &b->status;
} else {
rs1 = smartlist_get(ns->routerstatus_list, i-1);
rs2 = smartlist_get(ns->routerstatus_list, i);
}
if (fast_memcmp(rs1->identity_digest, rs2->identity_digest, DIGEST_LEN)
>= 0) {
log_warn(LD_DIR, "Vote networkstatus entries not sorted by identity "
"digest");
goto err;
}
}
/* Parse footer; check signature. */
footer_tokens = smartlist_create();
if ((end_of_footer = strstr(s, "\nnetwork-status-version ")))
++end_of_footer;
else
end_of_footer = s + strlen(s);
if (tokenize_string(area,s, end_of_footer, footer_tokens,
networkstatus_vote_footer_token_table, 0)) {
log_warn(LD_DIR, "Error tokenizing network-status vote footer.");
goto err;
}
{
int found_sig = 0;
SMARTLIST_FOREACH_BEGIN(footer_tokens, directory_token_t *, _tok) {
tok = _tok;
if (tok->tp == K_DIRECTORY_SIGNATURE)
found_sig = 1;
else if (found_sig) {
log_warn(LD_DIR, "Extraneous token after first directory-signature");
goto err;
}
} SMARTLIST_FOREACH_END(_tok);
}
if ((tok = find_opt_by_keyword(footer_tokens, K_DIRECTORY_FOOTER))) {
if (tok != smartlist_get(footer_tokens, 0)) {
log_warn(LD_DIR, "Misplaced directory-footer token");
goto err;
}
}
tok = find_opt_by_keyword(footer_tokens, K_BW_WEIGHTS);
if (tok) {
ns->weight_params = smartlist_create();
for (i = 0; i < tok->n_args; ++i) {
int ok=0;
char *eq = strchr(tok->args[i], '=');
if (!eq) {
log_warn(LD_DIR, "Bad element '%s' in weight params",
escaped(tok->args[i]));
goto err;
}
tor_parse_long(eq+1, 10, INT32_MIN, INT32_MAX, &ok, NULL);
if (!ok) {
log_warn(LD_DIR, "Bad element '%s' in params", escaped(tok->args[i]));
goto err;
}
smartlist_add(ns->weight_params, tor_strdup(tok->args[i]));
}
}
SMARTLIST_FOREACH_BEGIN(footer_tokens, directory_token_t *, _tok) {
char declared_identity[DIGEST_LEN];
networkstatus_voter_info_t *v;
document_signature_t *sig;
const char *id_hexdigest = NULL;
const char *sk_hexdigest = NULL;
digest_algorithm_t alg = DIGEST_SHA1;
tok = _tok;
if (tok->tp != K_DIRECTORY_SIGNATURE)
continue;
tor_assert(tok->n_args >= 2);
if (tok->n_args == 2) {
id_hexdigest = tok->args[0];
sk_hexdigest = tok->args[1];
} else {
const char *algname = tok->args[0];
int a;
id_hexdigest = tok->args[1];
sk_hexdigest = tok->args[2];
a = crypto_digest_algorithm_parse_name(algname);
if (a<0) {
log_warn(LD_DIR, "Unknown digest algorithm %s; skipping",
escaped(algname));
continue;
}
alg = a;
}
if (!tok->object_type ||
strcmp(tok->object_type, "SIGNATURE") ||
tok->object_size < 128 || tok->object_size > 512) {
log_warn(LD_DIR, "Bad object type or length on directory-signature");
goto err;
}
if (strlen(id_hexdigest) != HEX_DIGEST_LEN ||
base16_decode(declared_identity, sizeof(declared_identity),
id_hexdigest, HEX_DIGEST_LEN) < 0) {
log_warn(LD_DIR, "Error decoding declared identity %s in "
"network-status vote.", escaped(id_hexdigest));
goto err;
}
if (!(v = networkstatus_get_voter_by_id(ns, declared_identity))) {
log_warn(LD_DIR, "ID on signature on network-status vote does not match "
"any declared directory source.");
goto err;
}
sig = tor_malloc_zero(sizeof(document_signature_t));
memcpy(sig->identity_digest, v->identity_digest, DIGEST_LEN);
sig->alg = alg;
if (strlen(sk_hexdigest) != HEX_DIGEST_LEN ||
base16_decode(sig->signing_key_digest, sizeof(sig->signing_key_digest),
sk_hexdigest, HEX_DIGEST_LEN) < 0) {
log_warn(LD_DIR, "Error decoding declared signing key digest %s in "
"network-status vote.", escaped(sk_hexdigest));
tor_free(sig);
goto err;
}
if (ns->type != NS_TYPE_CONSENSUS) {
if (tor_memneq(declared_identity, ns->cert->cache_info.identity_digest,
DIGEST_LEN)) {
log_warn(LD_DIR, "Digest mismatch between declared and actual on "
"network-status vote.");
tor_free(sig);
goto err;
}
}
if (voter_get_sig_by_algorithm(v, sig->alg)) {
/* We already parsed a vote with this algorithm from this voter. Use the
first one. */
log_fn(LOG_PROTOCOL_WARN, LD_DIR, "We received a networkstatus "
"that contains two votes from the same voter with the same "
"algorithm. Ignoring the second vote.");
tor_free(sig);
continue;
}
if (ns->type != NS_TYPE_CONSENSUS) {
if (check_signature_token(ns_digests.d[DIGEST_SHA1], DIGEST_LEN,
tok, ns->cert->signing_key, 0,
"network-status vote")) {
tor_free(sig);
goto err;
}
sig->good_signature = 1;
} else {
if (tok->object_size >= INT_MAX || tok->object_size >= SIZE_T_CEILING) {
tor_free(sig);
goto err;
}
sig->signature = tor_memdup(tok->object_body, tok->object_size);
sig->signature_len = (int) tok->object_size;
}
smartlist_add(v->sigs, sig);
++n_signatures;
} SMARTLIST_FOREACH_END(_tok);
if (! n_signatures) {
log_warn(LD_DIR, "No signatures on networkstatus vote.");
goto err;
} else if (ns->type == NS_TYPE_VOTE && n_signatures != 1) {
log_warn(LD_DIR, "Received more than one signature on a "
"network-status vote.");
goto err;
}
if (eos_out)
*eos_out = end_of_footer;
goto done;
err:
dump_desc(s_dup, "v3 networkstatus");
networkstatus_vote_free(ns);
ns = NULL;
done:
if (tokens) {
SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
smartlist_free(tokens);
}
if (voter) {
if (voter->sigs) {
SMARTLIST_FOREACH(voter->sigs, document_signature_t *, sig,
document_signature_free(sig));
smartlist_free(voter->sigs);
}
tor_free(voter->nickname);
tor_free(voter->address);
tor_free(voter->contact);
tor_free(voter);
}
if (rs_tokens) {
SMARTLIST_FOREACH(rs_tokens, directory_token_t *, t, token_clear(t));
smartlist_free(rs_tokens);
}
if (footer_tokens) {
SMARTLIST_FOREACH(footer_tokens, directory_token_t *, t, token_clear(t));
smartlist_free(footer_tokens);
}
if (area) {
DUMP_AREA(area, "v3 networkstatus");
memarea_drop_all(area);
}
if (rs_area)
memarea_drop_all(rs_area);
return ns;
}
| null | null | 208,505
|
320303562647980943317783282141447596021
| 536
|
Avoid possible segfault when handling networkstatus vote with bad flavor
Fix for 6530; fix on 0.2.2.6-alpha.
|
other
|
heimdal
|
04171147948d0a3636bc6374181926f0fb2ec83a
| 1
|
tgs_build_reply(astgs_request_t priv,
hdb_entry_ex *krbtgt,
krb5_enctype krbtgt_etype,
const krb5_keyblock *replykey,
int rk_is_subkey,
krb5_ticket *ticket,
const char **e_text,
AuthorizationData **auth_data,
const struct sockaddr *from_addr)
{
krb5_context context = priv->context;
krb5_kdc_configuration *config = priv->config;
KDC_REQ *req = &priv->req;
KDC_REQ_BODY *b = &priv->req.req_body;
const char *from = priv->from;
krb5_error_code ret, ret2;
krb5_principal cp = NULL, sp = NULL, rsp = NULL, tp = NULL, dp = NULL;
krb5_principal krbtgt_out_principal = NULL;
char *spn = NULL, *cpn = NULL, *tpn = NULL, *dpn = NULL, *krbtgt_out_n = NULL;
hdb_entry_ex *server = NULL, *client = NULL, *s4u2self_impersonated_client = NULL;
HDB *clientdb, *s4u2self_impersonated_clientdb;
krb5_realm ref_realm = NULL;
EncTicketPart *tgt = &ticket->ticket;
krb5_principals spp = NULL;
const EncryptionKey *ekey;
krb5_keyblock sessionkey;
krb5_kvno kvno;
krb5_data rspac;
const char *tgt_realm = /* Realm of TGT issuer */
krb5_principal_get_realm(context, krbtgt->entry.principal);
const char *our_realm = /* Realm of this KDC */
krb5_principal_get_comp_string(context, krbtgt->entry.principal, 1);
char **capath = NULL;
size_t num_capath = 0;
hdb_entry_ex *krbtgt_out = NULL;
METHOD_DATA enc_pa_data;
PrincipalName *s;
Realm r;
EncTicketPart adtkt;
char opt_str[128];
int signedpath = 0;
Key *tkey_check;
Key *tkey_sign;
int flags = HDB_F_FOR_TGS_REQ;
memset(&sessionkey, 0, sizeof(sessionkey));
memset(&adtkt, 0, sizeof(adtkt));
krb5_data_zero(&rspac);
memset(&enc_pa_data, 0, sizeof(enc_pa_data));
s = b->sname;
r = b->realm;
/*
* The canonicalize KDC option is passed as a hint to the backend, but
* can typically be ignored. Per RFC 6806, names are not canonicalized
* in response to a TGS request (although we make an exception, see
* force-canonicalize below).
*/
if (b->kdc_options.canonicalize)
flags |= HDB_F_CANON;
if(b->kdc_options.enc_tkt_in_skey){
Ticket *t;
hdb_entry_ex *uu;
krb5_principal p;
Key *uukey;
krb5uint32 second_kvno = 0;
krb5uint32 *kvno_ptr = NULL;
if(b->additional_tickets == NULL ||
b->additional_tickets->len == 0){
ret = KRB5KDC_ERR_BADOPTION; /* ? */
kdc_log(context, config, 4,
"No second ticket present in user-to-user request");
_kdc_audit_addreason((kdc_request_t)priv,
"No second ticket present in user-to-user request");
goto out;
}
t = &b->additional_tickets->val[0];
if(!get_krbtgt_realm(&t->sname)){
kdc_log(context, config, 4,
"Additional ticket is not a ticket-granting ticket");
_kdc_audit_addreason((kdc_request_t)priv,
"Additional ticket is not a ticket-granting ticket");
ret = KRB5KDC_ERR_POLICY;
goto out;
}
_krb5_principalname2krb5_principal(context, &p, t->sname, t->realm);
ret = krb5_unparse_name(context, p, &tpn);
if (ret)
goto out;
if(t->enc_part.kvno){
second_kvno = *t->enc_part.kvno;
kvno_ptr = &second_kvno;
}
ret = _kdc_db_fetch(context, config, p,
HDB_F_GET_KRBTGT, kvno_ptr,
NULL, &uu);
krb5_free_principal(context, p);
if(ret){
if (ret == HDB_ERR_NOENTRY)
ret = KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN;
_kdc_audit_addreason((kdc_request_t)priv,
"User-to-user service principal (TGS) unknown");
goto out;
}
ret = hdb_enctype2key(context, &uu->entry, NULL,
t->enc_part.etype, &uukey);
if(ret){
_kdc_free_ent(context, uu);
ret = KRB5KDC_ERR_ETYPE_NOSUPP; /* XXX */
_kdc_audit_addreason((kdc_request_t)priv,
"User-to-user enctype not supported");
goto out;
}
ret = krb5_decrypt_ticket(context, t, &uukey->key, &adtkt, 0);
_kdc_free_ent(context, uu);
if(ret) {
_kdc_audit_addreason((kdc_request_t)priv,
"User-to-user TGT decrypt failure");
goto out;
}
ret = verify_flags(context, config, &adtkt, tpn);
if (ret) {
_kdc_audit_addreason((kdc_request_t)priv,
"User-to-user TGT expired or invalid");
goto out;
}
s = &adtkt.cname;
r = adtkt.crealm;
}
_krb5_principalname2krb5_principal(context, &sp, *s, r);
ret = krb5_unparse_name(context, sp, &priv->sname);
if (ret)
goto out;
spn = priv->sname;
_krb5_principalname2krb5_principal(context, &cp, tgt->cname, tgt->crealm);
ret = krb5_unparse_name(context, cp, &priv->cname);
if (ret)
goto out;
cpn = priv->cname;
unparse_flags (KDCOptions2int(b->kdc_options),
asn1_KDCOptions_units(),
opt_str, sizeof(opt_str));
if(*opt_str)
kdc_log(context, config, 4,
"TGS-REQ %s from %s for %s [%s]",
cpn, from, spn, opt_str);
else
kdc_log(context, config, 4,
"TGS-REQ %s from %s for %s", cpn, from, spn);
/*
* Fetch server
*/
server_lookup:
ret = _kdc_db_fetch(context, config, sp,
HDB_F_GET_SERVER | HDB_F_DELAY_NEW_KEYS | flags,
NULL, NULL, &server);
priv->server = server;
if (ret == HDB_ERR_NOT_FOUND_HERE) {
kdc_log(context, config, 5, "target %s does not have secrets at this KDC, need to proxy", spn);
_kdc_audit_addreason((kdc_request_t)priv, "Target not found here");
goto out;
} else if (ret == HDB_ERR_WRONG_REALM) {
free(ref_realm);
ref_realm = strdup(server->entry.principal->realm);
if (ref_realm == NULL) {
ret = krb5_enomem(context);
goto out;
}
kdc_log(context, config, 4,
"Returning a referral to realm %s for "
"server %s.",
ref_realm, spn);
krb5_free_principal(context, sp);
sp = NULL;
ret = krb5_make_principal(context, &sp, r, KRB5_TGS_NAME,
ref_realm, NULL);
if (ret)
goto out;
free(priv->sname);
priv->sname = NULL;
ret = krb5_unparse_name(context, sp, &priv->sname);
if (ret)
goto out;
spn = priv->sname;
goto server_lookup;
} else if (ret) {
const char *new_rlm, *msg;
Realm req_rlm;
krb5_realm *realms;
if ((req_rlm = get_krbtgt_realm(&sp->name)) != NULL) {
if (capath == NULL) {
/* With referalls, hierarchical capaths are always enabled */
ret2 = _krb5_find_capath(context, tgt->crealm, our_realm,
req_rlm, TRUE, &capath, &num_capath);
if (ret2) {
ret = ret2;
_kdc_audit_addreason((kdc_request_t)priv,
"No trusted path from client realm to ours");
goto out;
}
}
new_rlm = num_capath > 0 ? capath[--num_capath] : NULL;
if (new_rlm) {
kdc_log(context, config, 5, "krbtgt from %s via %s for "
"realm %s not found, trying %s", tgt->crealm,
our_realm, req_rlm, new_rlm);
free(ref_realm);
ref_realm = strdup(new_rlm);
if (ref_realm == NULL) {
ret = krb5_enomem(context);
goto out;
}
krb5_free_principal(context, sp);
sp = NULL;
krb5_make_principal(context, &sp, r,
KRB5_TGS_NAME, ref_realm, NULL);
free(priv->sname);
priv->sname = NULL;
ret = krb5_unparse_name(context, sp, &priv->sname);
if (ret)
goto out;
spn = priv->sname;
goto server_lookup;
}
} else if (need_referral(context, config, &b->kdc_options, sp, &realms)) {
if (strcmp(realms[0], sp->realm) != 0) {
kdc_log(context, config, 4,
"Returning a referral to realm %s for "
"server %s that was not found",
realms[0], spn);
krb5_free_principal(context, sp);
sp = NULL;
krb5_make_principal(context, &sp, r, KRB5_TGS_NAME,
realms[0], NULL);
free(priv->sname);
priv->sname = NULL;
ret = krb5_unparse_name(context, sp, &priv->sname);
if (ret) {
krb5_free_host_realm(context, realms);
goto out;
}
spn = priv->sname;
free(ref_realm);
ref_realm = strdup(realms[0]);
krb5_free_host_realm(context, realms);
goto server_lookup;
}
krb5_free_host_realm(context, realms);
}
msg = krb5_get_error_message(context, ret);
kdc_log(context, config, 3,
"Server not found in database: %s: %s", spn, msg);
krb5_free_error_message(context, msg);
if (ret == HDB_ERR_NOENTRY)
ret = KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN;
_kdc_audit_addreason((kdc_request_t)priv,
"Service principal unknown");
goto out;
}
/*
* RFC 6806 notes that names MUST NOT be changed in the response to
* a TGS request. Hence we ignore the setting of the canonicalize
* KDC option. However, for legacy interoperability we do allow the
* backend to override this by setting the force-canonicalize HDB
* flag in the server entry.
*/
if (server->entry.flags.force_canonicalize)
rsp = server->entry.principal;
else
rsp = sp;
/*
* Select enctype, return key and kvno.
*/
{
krb5_enctype etype;
if(b->kdc_options.enc_tkt_in_skey) {
size_t i;
ekey = &adtkt.key;
for(i = 0; i < b->etype.len; i++)
if (b->etype.val[i] == adtkt.key.keytype)
break;
if(i == b->etype.len) {
kdc_log(context, config, 4,
"Addition ticket have not matching etypes");
krb5_clear_error_message(context);
ret = KRB5KDC_ERR_ETYPE_NOSUPP;
_kdc_audit_addreason((kdc_request_t)priv,
"No matching enctypes for 2nd ticket");
goto out;
}
etype = b->etype.val[i];
kvno = 0;
} else {
Key *skey;
ret = _kdc_find_etype(priv, krb5_principal_is_krbtgt(context, sp)
? KFE_IS_TGS : 0,
b->etype.val, b->etype.len, &etype, NULL,
NULL);
if(ret) {
kdc_log(context, config, 4,
"Server (%s) has no support for etypes", spn);
_kdc_audit_addreason((kdc_request_t)priv,
"Enctype not supported");
goto out;
}
ret = _kdc_get_preferred_key(context, config, server, spn,
NULL, &skey);
if(ret) {
kdc_log(context, config, 4,
"Server (%s) has no supported etypes", spn);
_kdc_audit_addreason((kdc_request_t)priv,
"Enctype not supported");
goto out;
}
ekey = &skey->key;
kvno = server->entry.kvno;
}
ret = krb5_generate_random_keyblock(context, etype, &sessionkey);
if (ret)
goto out;
}
/*
* Check that service is in the same realm as the krbtgt. If it's
* not the same, it's someone that is using a uni-directional trust
* backward.
*/
/*
* Validate authorization data
*/
ret = hdb_enctype2key(context, &krbtgt->entry, NULL, /* XXX use the right kvno! */
krbtgt_etype, &tkey_check);
if(ret) {
kdc_log(context, config, 4,
"Failed to find key for krbtgt PAC check");
_kdc_audit_addreason((kdc_request_t)priv,
"No key for krbtgt PAC check");
goto out;
}
/*
* Now refetch the primary krbtgt, and get the current kvno (the
* sign check may have been on an old kvno, and the server may
* have been an incoming trust)
*/
ret = krb5_make_principal(context,
&krbtgt_out_principal,
our_realm,
KRB5_TGS_NAME,
our_realm,
NULL);
if (ret) {
kdc_log(context, config, 4,
"Failed to make krbtgt principal name object for "
"authz-data signatures");
goto out;
}
ret = krb5_unparse_name(context, krbtgt_out_principal, &krbtgt_out_n);
if (ret) {
kdc_log(context, config, 4,
"Failed to make krbtgt principal name object for "
"authz-data signatures");
goto out;
}
ret = _kdc_db_fetch(context, config, krbtgt_out_principal,
HDB_F_GET_KRBTGT, NULL, NULL, &krbtgt_out);
if (ret) {
char *ktpn = NULL;
ret = krb5_unparse_name(context, krbtgt->entry.principal, &ktpn);
kdc_log(context, config, 4,
"No such principal %s (needed for authz-data signature keys) "
"while processing TGS-REQ for service %s with krbtg %s",
krbtgt_out_n, spn, (ret == 0) ? ktpn : "<unknown>");
free(ktpn);
ret = KRB5KRB_AP_ERR_NOT_US;
goto out;
}
/*
* The first realm is the realm of the service, the second is
* krbtgt/<this>/@REALM component of the krbtgt DN the request was
* encrypted to. The redirection via the krbtgt_out entry allows
* the DB to possibly correct the case of the realm (Samba4 does
* this) before the strcmp()
*/
if (strcmp(krb5_principal_get_realm(context, server->entry.principal),
krb5_principal_get_realm(context, krbtgt_out->entry.principal)) != 0) {
char *ktpn;
ret = krb5_unparse_name(context, krbtgt_out->entry.principal, &ktpn);
kdc_log(context, config, 4,
"Request with wrong krbtgt: %s",
(ret == 0) ? ktpn : "<unknown>");
if(ret == 0)
free(ktpn);
ret = KRB5KRB_AP_ERR_NOT_US;
_kdc_audit_addreason((kdc_request_t)priv, "Request with wrong TGT");
goto out;
}
ret = _kdc_get_preferred_key(context, config, krbtgt_out, krbtgt_out_n,
NULL, &tkey_sign);
if (ret) {
kdc_log(context, config, 4,
"Failed to find key for krbtgt PAC signature");
_kdc_audit_addreason((kdc_request_t)priv,
"Failed to find key for krbtgt PAC signature");
goto out;
}
ret = hdb_enctype2key(context, &krbtgt_out->entry, NULL,
tkey_sign->key.keytype, &tkey_sign);
if(ret) {
kdc_log(context, config, 4,
"Failed to find key for krbtgt PAC signature");
_kdc_audit_addreason((kdc_request_t)priv,
"Failed to find key for krbtgt PAC signature");
goto out;
}
{
krb5_data verified_cas;
/*
* If the client doesn't exist in the HDB but has a TGT and it's
* obtained with PKINIT then we assume it's a synthetic client -- that
* is, a client whose name was vouched for by a CA using a PKINIT SAN,
* but which doesn't exist in the HDB proper. We'll allow such a
* client to do TGT requests even though normally we'd reject all
* clients that don't exist in the HDB.
*/
ret = krb5_ticket_get_authorization_data_type(context, ticket,
KRB5_AUTHDATA_INITIAL_VERIFIED_CAS,
&verified_cas);
if (ret == 0) {
krb5_data_free(&verified_cas);
flags |= HDB_F_SYNTHETIC_OK;
}
}
ret = _kdc_db_fetch(context, config, cp, HDB_F_GET_CLIENT | flags,
NULL, &clientdb, &client);
flags &= ~HDB_F_SYNTHETIC_OK;
priv->client = client;
if(ret == HDB_ERR_NOT_FOUND_HERE) {
/* This is OK, we are just trying to find out if they have
* been disabled or deleted in the meantime, missing secrets
* is OK */
} else if(ret){
const char *krbtgt_realm, *msg;
/*
* If the client belongs to the same realm as our krbtgt, it
* should exist in the local database.
*
*/
krbtgt_realm = krb5_principal_get_realm(context, krbtgt_out->entry.principal);
if(strcmp(krb5_principal_get_realm(context, cp), krbtgt_realm) == 0) {
if (ret == HDB_ERR_NOENTRY)
ret = KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN;
kdc_log(context, config, 4, "Client no longer in database: %s",
cpn);
_kdc_audit_addreason((kdc_request_t)priv, "Client no longer in HDB");
goto out;
}
msg = krb5_get_error_message(context, ret);
kdc_log(context, config, 4, "Client not found in database: %s", msg);
_kdc_audit_addreason((kdc_request_t)priv, "Client does not exist");
krb5_free_error_message(context, msg);
} else if (ret == 0 &&
(client->entry.flags.invalid || !client->entry.flags.client)) {
_kdc_audit_addreason((kdc_request_t)priv, "Client has invalid bit set");
kdc_log(context, config, 4, "Client has invalid bit set");
ret = KRB5KDC_ERR_POLICY;
goto out;
}
ret = check_PAC(context, config, cp, NULL,
client, server, krbtgt,
&tkey_check->key,
ekey, &tkey_sign->key,
tgt, &rspac, &signedpath);
if (ret) {
const char *msg = krb5_get_error_message(context, ret);
_kdc_audit_addreason((kdc_request_t)priv, "PAC check failed");
kdc_log(context, config, 4,
"Verify PAC failed for %s (%s) from %s with %s",
spn, cpn, from, msg);
krb5_free_error_message(context, msg);
goto out;
}
/* also check the krbtgt for signature */
ret = check_KRB5SignedPath(context,
config,
krbtgt,
cp,
tgt,
&spp,
&signedpath);
if (ret) {
const char *msg = krb5_get_error_message(context, ret);
_kdc_audit_addreason((kdc_request_t)priv, "KRB5SignedPath check failed");
kdc_log(context, config, 4,
"KRB5SignedPath check failed for %s (%s) from %s with %s",
spn, cpn, from, msg);
krb5_free_error_message(context, msg);
goto out;
}
/*
* Process request
*/
/* by default the tgt principal matches the client principal */
tp = cp;
tpn = cpn;
if (client) {
const PA_DATA *sdata;
int i = 0;
sdata = _kdc_find_padata(req, &i, KRB5_PADATA_FOR_USER);
if (sdata) {
struct astgs_request_desc imp_req;
krb5_crypto crypto;
krb5_data datack;
PA_S4U2Self self;
const char *str;
ret = decode_PA_S4U2Self(sdata->padata_value.data,
sdata->padata_value.length,
&self, NULL);
if (ret) {
_kdc_audit_addreason((kdc_request_t)priv,
"Failed to decode PA-S4U2Self");
kdc_log(context, config, 4, "Failed to decode PA-S4U2Self");
goto out;
}
if (!krb5_checksum_is_keyed(context, self.cksum.cksumtype)) {
free_PA_S4U2Self(&self);
_kdc_audit_addreason((kdc_request_t)priv,
"PA-S4U2Self with unkeyed checksum");
kdc_log(context, config, 4, "Reject PA-S4U2Self with unkeyed checksum");
ret = KRB5KRB_AP_ERR_INAPP_CKSUM;
goto out;
}
ret = _krb5_s4u2self_to_checksumdata(context, &self, &datack);
if (ret)
goto out;
ret = krb5_crypto_init(context, &tgt->key, 0, &crypto);
if (ret) {
const char *msg = krb5_get_error_message(context, ret);
free_PA_S4U2Self(&self);
krb5_data_free(&datack);
kdc_log(context, config, 4, "krb5_crypto_init failed: %s", msg);
krb5_free_error_message(context, msg);
goto out;
}
/* Allow HMAC_MD5 checksum with any key type */
if (self.cksum.cksumtype == CKSUMTYPE_HMAC_MD5) {
struct krb5_crypto_iov iov;
unsigned char csdata[16];
Checksum cs;
cs.checksum.length = sizeof(csdata);
cs.checksum.data = &csdata;
iov.data.data = datack.data;
iov.data.length = datack.length;
iov.flags = KRB5_CRYPTO_TYPE_DATA;
ret = _krb5_HMAC_MD5_checksum(context, NULL, &crypto->key,
KRB5_KU_OTHER_CKSUM, &iov, 1,
&cs);
if (ret == 0 &&
krb5_data_ct_cmp(&cs.checksum, &self.cksum.checksum) != 0)
ret = KRB5KRB_AP_ERR_BAD_INTEGRITY;
}
else {
ret = krb5_verify_checksum(context,
crypto,
KRB5_KU_OTHER_CKSUM,
datack.data,
datack.length,
&self.cksum);
}
krb5_data_free(&datack);
krb5_crypto_destroy(context, crypto);
if (ret) {
const char *msg = krb5_get_error_message(context, ret);
free_PA_S4U2Self(&self);
_kdc_audit_addreason((kdc_request_t)priv,
"S4U2Self checksum failed");
kdc_log(context, config, 4,
"krb5_verify_checksum failed for S4U2Self: %s", msg);
krb5_free_error_message(context, msg);
goto out;
}
ret = _krb5_principalname2krb5_principal(context,
&tp,
self.name,
self.realm);
free_PA_S4U2Self(&self);
if (ret)
goto out;
ret = krb5_unparse_name(context, tp, &tpn);
if (ret)
goto out;
/*
* Note no HDB_F_SYNTHETIC_OK -- impersonating non-existent clients
* is probably not desirable!
*/
ret = _kdc_db_fetch(context, config, tp, HDB_F_GET_CLIENT | flags,
NULL, &s4u2self_impersonated_clientdb,
&s4u2self_impersonated_client);
if (ret) {
const char *msg;
/*
* If the client belongs to the same realm as our krbtgt, it
* should exist in the local database.
*
*/
if (ret == HDB_ERR_NOENTRY)
ret = KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN;
msg = krb5_get_error_message(context, ret);
_kdc_audit_addreason((kdc_request_t)priv,
"S4U2Self principal to impersonate not found");
kdc_log(context, config, 2,
"S4U2Self principal to impersonate %s not found in database: %s",
tpn, msg);
krb5_free_error_message(context, msg);
goto out;
}
/* Ignore require_pwchange and pw_end attributes (as Windows does),
* since S4U2Self is not password authentication. */
s4u2self_impersonated_client->entry.flags.require_pwchange = FALSE;
free(s4u2self_impersonated_client->entry.pw_end);
s4u2self_impersonated_client->entry.pw_end = NULL;
imp_req = *priv;
imp_req.client = s4u2self_impersonated_client;
imp_req.client_princ = tp;
ret = kdc_check_flags(&imp_req, FALSE);
if (ret)
goto out; /* kdc_check_flags() calls _kdc_audit_addreason() */
/* If we were about to put a PAC into the ticket, we better fix it to be the right PAC */
if(rspac.data) {
krb5_pac p = NULL;
krb5_data_free(&rspac);
ret = _kdc_pac_generate(context, s4u2self_impersonated_client, &p);
if (ret) {
_kdc_audit_addreason((kdc_request_t)priv,
"KRB5SignedPath missing");
kdc_log(context, config, 4, "PAC generation failed for -- %s",
tpn);
goto out;
}
if (p != NULL) {
ret = _krb5_pac_sign(context, p, ticket->ticket.authtime,
s4u2self_impersonated_client->entry.principal,
ekey, &tkey_sign->key,
&rspac);
krb5_pac_free(context, p);
if (ret) {
kdc_log(context, config, 4, "PAC signing failed for -- %s",
tpn);
goto out;
}
}
}
/*
* Check that service doing the impersonating is
* requesting a ticket to it-self.
*/
ret = check_s4u2self(context, config, clientdb, client, sp);
if (ret) {
kdc_log(context, config, 4, "S4U2Self: %s is not allowed "
"to impersonate to service "
"(tried for user %s to service %s)",
cpn, tpn, spn);
goto out;
}
/*
* If the service isn't trusted for authentication to
* delegation or if the impersonate client is disallowed
* forwardable, remove the forwardable flag.
*/
if (client->entry.flags.trusted_for_delegation &&
s4u2self_impersonated_client->entry.flags.forwardable) {
str = "[forwardable]";
} else {
b->kdc_options.forwardable = 0;
str = "";
}
kdc_log(context, config, 4, "s4u2self %s impersonating %s to "
"service %s %s", cpn, tpn, spn, str);
}
}
/*
* Constrained delegation
*/
if (client != NULL
&& b->additional_tickets != NULL
&& b->additional_tickets->len != 0
&& b->kdc_options.cname_in_addl_tkt
&& b->kdc_options.enc_tkt_in_skey == 0)
{
int ad_signedpath = 0;
Key *clientkey;
Ticket *t;
/*
* Require that the KDC have issued the service's krbtgt (not
* self-issued ticket with kimpersonate(1).
*/
if (!signedpath) {
ret = KRB5KDC_ERR_BADOPTION;
_kdc_audit_addreason((kdc_request_t)priv, "KRB5SignedPath missing");
kdc_log(context, config, 4,
"Constrained delegation done on service ticket %s/%s",
cpn, spn);
goto out;
}
t = &b->additional_tickets->val[0];
ret = hdb_enctype2key(context, &client->entry,
hdb_kvno2keys(context, &client->entry,
t->enc_part.kvno ? * t->enc_part.kvno : 0),
t->enc_part.etype, &clientkey);
if(ret){
ret = KRB5KDC_ERR_ETYPE_NOSUPP; /* XXX */
goto out;
}
ret = krb5_decrypt_ticket(context, t, &clientkey->key, &adtkt, 0);
if (ret) {
_kdc_audit_addreason((kdc_request_t)priv,
"Failed to decrypt constrained delegation ticket");
kdc_log(context, config, 4,
"failed to decrypt ticket for "
"constrained delegation from %s to %s ", cpn, spn);
goto out;
}
ret = _krb5_principalname2krb5_principal(context,
&tp,
adtkt.cname,
adtkt.crealm);
if (ret)
goto out;
ret = krb5_unparse_name(context, tp, &tpn);
if (ret)
goto out;
_kdc_audit_addkv((kdc_request_t)priv, 0, "impersonatee", "%s", tpn);
ret = _krb5_principalname2krb5_principal(context,
&dp,
t->sname,
t->realm);
if (ret)
goto out;
ret = krb5_unparse_name(context, dp, &dpn);
if (ret)
goto out;
/* check that ticket is valid */
if (adtkt.flags.forwardable == 0) {
_kdc_audit_addreason((kdc_request_t)priv,
"Missing forwardable flag on ticket for constrained delegation");
kdc_log(context, config, 4,
"Missing forwardable flag on ticket for "
"constrained delegation from %s (%s) as %s to %s ",
cpn, dpn, tpn, spn);
ret = KRB5KDC_ERR_BADOPTION;
goto out;
}
ret = check_constrained_delegation(context, config, clientdb,
client, server, sp);
if (ret) {
_kdc_audit_addreason((kdc_request_t)priv,
"Constrained delegation not allowed");
kdc_log(context, config, 4,
"constrained delegation from %s (%s) as %s to %s not allowed",
cpn, dpn, tpn, spn);
goto out;
}
ret = verify_flags(context, config, &adtkt, tpn);
if (ret) {
_kdc_audit_addreason((kdc_request_t)priv,
"Constrained delegation ticket expired or invalid");
goto out;
}
krb5_data_free(&rspac);
/*
* generate the PAC for the user.
*
* TODO: pass in t->sname and t->realm and build
* a S4U_DELEGATION_INFO blob to the PAC.
*/
ret = check_PAC(context, config, tp, dp,
client, server, krbtgt,
&clientkey->key,
ekey, &tkey_sign->key,
&adtkt, &rspac, &ad_signedpath);
if (ret) {
const char *msg = krb5_get_error_message(context, ret);
_kdc_audit_addreason((kdc_request_t)priv,
"Constrained delegation ticket PAC check failed");
kdc_log(context, config, 4,
"Verify delegated PAC failed to %s for client"
"%s (%s) as %s from %s with %s",
spn, cpn, dpn, tpn, from, msg);
krb5_free_error_message(context, msg);
goto out;
}
/*
* Check that the KDC issued the user's ticket.
*/
ret = check_KRB5SignedPath(context,
config,
krbtgt,
cp,
&adtkt,
NULL,
&ad_signedpath);
if (ret) {
const char *msg = krb5_get_error_message(context, ret);
kdc_log(context, config, 4,
"KRB5SignedPath check from service %s failed "
"for delegation to %s for client %s (%s)"
"from %s failed with %s",
spn, tpn, dpn, cpn, from, msg);
krb5_free_error_message(context, msg);
_kdc_audit_addreason((kdc_request_t)priv,
"KRB5SignedPath check failed");
goto out;
}
if (!ad_signedpath) {
ret = KRB5KDC_ERR_BADOPTION;
kdc_log(context, config, 4,
"Ticket not signed with PAC nor SignedPath service %s failed "
"for delegation to %s for client %s (%s)"
"from %s",
spn, tpn, dpn, cpn, from);
_kdc_audit_addreason((kdc_request_t)priv,
"Constrained delegation ticket not signed");
goto out;
}
kdc_log(context, config, 4, "constrained delegation for %s "
"from %s (%s) to %s", tpn, cpn, dpn, spn);
}
/*
* Check flags
*/
ret = kdc_check_flags(priv, FALSE);
if(ret)
goto out;
if((b->kdc_options.validate || b->kdc_options.renew) &&
!krb5_principal_compare(context,
krbtgt->entry.principal,
server->entry.principal)){
_kdc_audit_addreason((kdc_request_t)priv, "Inconsistent request");
kdc_log(context, config, 4, "Inconsistent request.");
ret = KRB5KDC_ERR_SERVER_NOMATCH;
goto out;
}
/* check for valid set of addresses */
if (!_kdc_check_addresses(priv, tgt->caddr, from_addr)) {
if (config->check_ticket_addresses) {
ret = KRB5KRB_AP_ERR_BADADDR;
_kdc_audit_addkv((kdc_request_t)priv, 0, "wrongaddr", "yes");
kdc_log(context, config, 4, "Request from wrong address");
_kdc_audit_addreason((kdc_request_t)priv, "Request from wrong address");
goto out;
} else if (config->warn_ticket_addresses) {
_kdc_audit_addkv((kdc_request_t)priv, 0, "wrongaddr", "yes");
}
}
/* check local and per-principal anonymous ticket issuance policy */
if (is_anon_tgs_request_p(b, tgt)) {
ret = _kdc_check_anon_policy(priv);
if (ret)
goto out;
}
/*
* If this is an referral, add server referral data to the
* auth_data reply .
*/
if (ref_realm) {
PA_DATA pa;
krb5_crypto crypto;
kdc_log(context, config, 3,
"Adding server referral to %s", ref_realm);
ret = krb5_crypto_init(context, &sessionkey, 0, &crypto);
if (ret)
goto out;
ret = build_server_referral(context, config, crypto, ref_realm,
NULL, s, &pa.padata_value);
krb5_crypto_destroy(context, crypto);
if (ret) {
_kdc_audit_addreason((kdc_request_t)priv, "Referral build failed");
kdc_log(context, config, 4,
"Failed building server referral");
goto out;
}
pa.padata_type = KRB5_PADATA_SERVER_REFERRAL;
ret = add_METHOD_DATA(&enc_pa_data, &pa);
krb5_data_free(&pa.padata_value);
if (ret) {
kdc_log(context, config, 4,
"Add server referral METHOD-DATA failed");
goto out;
}
}
/*
*
*/
ret = tgs_make_reply(priv,
tp,
tgt,
replykey,
rk_is_subkey,
ekey,
&sessionkey,
kvno,
*auth_data,
server,
rsp,
client,
cp,
tgt_realm,
krbtgt_out,
tkey_sign->key.keytype,
spp,
&rspac,
&enc_pa_data);
out:
if (tpn != cpn)
free(tpn);
free(dpn);
free(krbtgt_out_n);
_krb5_free_capath(context, capath);
krb5_data_free(&rspac);
krb5_free_keyblock_contents(context, &sessionkey);
if(krbtgt_out)
_kdc_free_ent(context, krbtgt_out);
if(server)
_kdc_free_ent(context, server);
if(client)
_kdc_free_ent(context, client);
if(s4u2self_impersonated_client)
_kdc_free_ent(context, s4u2self_impersonated_client);
if (tp && tp != cp)
krb5_free_principal(context, tp);
krb5_free_principal(context, cp);
krb5_free_principal(context, dp);
krb5_free_principal(context, sp);
krb5_free_principal(context, krbtgt_out_principal);
free(ref_realm);
free_METHOD_DATA(&enc_pa_data);
free_EncTicketPart(&adtkt);
return ret;
}
| null | null | 208,506
|
172674879650950329667725116403393224452
| 1,038
|
kdc: validate sname in TGS-REQ
In tgs_build_reply(), validate the server name in the TGS-REQ is present before
dereferencing.
|
other
|
unbound
|
02080f6b180232f43b77f403d0c038e9360a460f
| 1
|
dnsc_load_local_data(struct dnsc_env* dnscenv, struct config_file *cfg)
{
size_t i, j;
// Insert 'local-zone: "2.dnscrypt-cert.example.com" deny'
if(!cfg_str2list_insert(&cfg->local_zones,
strdup(dnscenv->provider_name),
strdup("deny"))) {
log_err("Could not load dnscrypt local-zone: %s deny",
dnscenv->provider_name);
return -1;
}
// Add local data entry of type:
// 2.dnscrypt-cert.example.com 86400 IN TXT "DNSC......"
for(i=0; i<dnscenv->signed_certs_count; i++) {
const char *ttl_class_type = " 86400 IN TXT \"";
int rotated_cert = 0;
uint32_t serial;
uint16_t rrlen;
char* rr;
struct SignedCert *cert = dnscenv->signed_certs + i;
// Check if the certificate is being rotated and should not be published
for(j=0; j<dnscenv->rotated_certs_count; j++){
if(cert == dnscenv->rotated_certs[j]) {
rotated_cert = 1;
break;
}
}
memcpy(&serial, cert->serial, sizeof serial);
serial = htonl(serial);
if(rotated_cert) {
verbose(VERB_OPS,
"DNSCrypt: not adding cert with serial #%"
PRIu32
" to local-data as it is rotated",
serial
);
continue;
}
rrlen = strlen(dnscenv->provider_name) +
strlen(ttl_class_type) +
4 * sizeof(struct SignedCert) + // worst case scenario
1 + // trailing double quote
1;
rr = malloc(rrlen);
if(!rr) {
log_err("Could not allocate memory");
return -2;
}
snprintf(rr, rrlen - 1, "%s 86400 IN TXT \"", dnscenv->provider_name);
for(j=0; j<sizeof(struct SignedCert); j++) {
int c = (int)*((const uint8_t *) cert + j);
if (isprint(c) && c != '"' && c != '\\') {
snprintf(rr + strlen(rr), rrlen - 1 - strlen(rr), "%c", c);
} else {
snprintf(rr + strlen(rr), rrlen - 1 - strlen(rr), "\\%03d", c);
}
}
verbose(VERB_OPS,
"DNSCrypt: adding cert with serial #%"
PRIu32
" to local-data to config: %s",
serial, rr
);
snprintf(rr + strlen(rr), rrlen - 1 - strlen(rr), "\"");
cfg_strlist_insert(&cfg->local_data, strdup(rr));
free(rr);
}
return dnscenv->signed_certs_count;
}
| null | null | 208,522
|
610710673926578047133575486433853683
| 70
|
- Fix Integer Overflows in Size Calculations,
reported by X41 D-Sec.
|
other
|
vim
|
6046aded8da002b08d380db29de2ba0268b6616e
| 1
|
cmdline_insert_reg(int *gotesc UNUSED)
{
int i;
int c;
#ifdef USE_ON_FLY_SCROLL
dont_scroll = TRUE; // disallow scrolling here
#endif
putcmdline('"', TRUE);
++no_mapping;
++allow_keys;
i = c = plain_vgetc(); // CTRL-R <char>
if (i == Ctrl_O)
i = Ctrl_R; // CTRL-R CTRL-O == CTRL-R CTRL-R
if (i == Ctrl_R)
c = plain_vgetc(); // CTRL-R CTRL-R <char>
extra_char = NUL;
--no_mapping;
--allow_keys;
#ifdef FEAT_EVAL
/*
* Insert the result of an expression.
* Need to save the current command line, to be able to enter
* a new one...
*/
new_cmdpos = -1;
if (c == '=')
{
if (ccline.cmdfirstc == '=' // can't do this recursively
|| cmdline_star > 0) // or when typing a password
{
beep_flush();
c = ESC;
}
else
c = get_expr_register();
}
#endif
if (c != ESC) // use ESC to cancel inserting register
{
cmdline_paste(c, i == Ctrl_R, FALSE);
#ifdef FEAT_EVAL
// When there was a serious error abort getting the
// command line.
if (aborting())
{
*gotesc = TRUE; // will free ccline.cmdbuff after
// putting it in history
return GOTO_NORMAL_MODE;
}
#endif
KeyTyped = FALSE; // Don't do p_wc completion.
#ifdef FEAT_EVAL
if (new_cmdpos >= 0)
{
// set_cmdline_pos() was used
if (new_cmdpos > ccline.cmdlen)
ccline.cmdpos = ccline.cmdlen;
else
ccline.cmdpos = new_cmdpos;
}
#endif
}
// remove the double quote
redrawcmd();
// The text has been stuffed, the command line didn't change yet.
return CMDLINE_NOT_CHANGED;
}
| null | null | 208,525
|
225374604065010647908706692694589619090
| 70
|
patch 8.2.5148: invalid memory access when using expression on command line
Problem: Invalid memory access when using an expression on the command line.
Solution: Make sure the position does not go negative.
|
other
|
libxml2
|
b1d34de46a11323fccffa9fadeb33be670d602f5
| 1
|
xmlStringLenDecodeEntities(xmlParserCtxtPtr ctxt, const xmlChar *str, int len,
int what, xmlChar end, xmlChar end2, xmlChar end3) {
xmlChar *buffer = NULL;
size_t buffer_size = 0;
size_t nbchars = 0;
xmlChar *current = NULL;
xmlChar *rep = NULL;
const xmlChar *last;
xmlEntityPtr ent;
int c,l;
if ((ctxt == NULL) || (str == NULL) || (len < 0))
return(NULL);
last = str + len;
if (((ctxt->depth > 40) &&
((ctxt->options & XML_PARSE_HUGE) == 0)) ||
(ctxt->depth > 1024)) {
xmlFatalErr(ctxt, XML_ERR_ENTITY_LOOP, NULL);
return(NULL);
}
/*
* allocate a translation buffer.
*/
buffer_size = XML_PARSER_BIG_BUFFER_SIZE;
buffer = (xmlChar *) xmlMallocAtomic(buffer_size);
if (buffer == NULL) goto mem_error;
/*
* OK loop until we reach one of the ending char or a size limit.
* we are operating on already parsed values.
*/
if (str < last)
c = CUR_SCHAR(str, l);
else
c = 0;
while ((c != 0) && (c != end) && /* non input consuming loop */
(c != end2) && (c != end3)) {
if (c == 0) break;
if ((c == '&') && (str[1] == '#')) {
int val = xmlParseStringCharRef(ctxt, &str);
if (val != 0) {
COPY_BUF(0,buffer,nbchars,val);
}
if (nbchars + XML_PARSER_BUFFER_SIZE > buffer_size) {
growBuffer(buffer, XML_PARSER_BUFFER_SIZE);
}
} else if ((c == '&') && (what & XML_SUBSTITUTE_REF)) {
if (xmlParserDebugEntities)
xmlGenericError(xmlGenericErrorContext,
"String decoding Entity Reference: %.30s\n",
str);
ent = xmlParseStringEntityRef(ctxt, &str);
if ((ctxt->lastError.code == XML_ERR_ENTITY_LOOP) ||
(ctxt->lastError.code == XML_ERR_INTERNAL_ERROR))
goto int_error;
xmlParserEntityCheck(ctxt, 0, ent, 0);
if (ent != NULL)
ctxt->nbentities += ent->checked / 2;
if ((ent != NULL) &&
(ent->etype == XML_INTERNAL_PREDEFINED_ENTITY)) {
if (ent->content != NULL) {
COPY_BUF(0,buffer,nbchars,ent->content[0]);
if (nbchars + XML_PARSER_BUFFER_SIZE > buffer_size) {
growBuffer(buffer, XML_PARSER_BUFFER_SIZE);
}
} else {
xmlFatalErrMsg(ctxt, XML_ERR_INTERNAL_ERROR,
"predefined entity has no content\n");
}
} else if ((ent != NULL) && (ent->content != NULL)) {
ctxt->depth++;
rep = xmlStringDecodeEntities(ctxt, ent->content, what,
0, 0, 0);
ctxt->depth--;
if ((ctxt->lastError.code == XML_ERR_ENTITY_LOOP) ||
(ctxt->lastError.code == XML_ERR_INTERNAL_ERROR))
goto int_error;
if (rep != NULL) {
current = rep;
while (*current != 0) { /* non input consuming loop */
buffer[nbchars++] = *current++;
if (nbchars + XML_PARSER_BUFFER_SIZE > buffer_size) {
if (xmlParserEntityCheck(ctxt, nbchars, ent, 0))
goto int_error;
growBuffer(buffer, XML_PARSER_BUFFER_SIZE);
}
}
xmlFree(rep);
rep = NULL;
}
} else if (ent != NULL) {
int i = xmlStrlen(ent->name);
const xmlChar *cur = ent->name;
buffer[nbchars++] = '&';
if (nbchars + i + XML_PARSER_BUFFER_SIZE > buffer_size) {
growBuffer(buffer, i + XML_PARSER_BUFFER_SIZE);
}
for (;i > 0;i--)
buffer[nbchars++] = *cur++;
buffer[nbchars++] = ';';
}
} else if (c == '%' && (what & XML_SUBSTITUTE_PEREF)) {
if (xmlParserDebugEntities)
xmlGenericError(xmlGenericErrorContext,
"String decoding PE Reference: %.30s\n", str);
ent = xmlParseStringPEReference(ctxt, &str);
if (ctxt->lastError.code == XML_ERR_ENTITY_LOOP)
goto int_error;
xmlParserEntityCheck(ctxt, 0, ent, 0);
if (ent != NULL)
ctxt->nbentities += ent->checked / 2;
if (ent != NULL) {
if (ent->content == NULL) {
xmlLoadEntityContent(ctxt, ent);
}
ctxt->depth++;
rep = xmlStringDecodeEntities(ctxt, ent->content, what,
0, 0, 0);
ctxt->depth--;
if (rep != NULL) {
current = rep;
while (*current != 0) { /* non input consuming loop */
buffer[nbchars++] = *current++;
if (nbchars + XML_PARSER_BUFFER_SIZE > buffer_size) {
if (xmlParserEntityCheck(ctxt, nbchars, ent, 0))
goto int_error;
growBuffer(buffer, XML_PARSER_BUFFER_SIZE);
}
}
xmlFree(rep);
rep = NULL;
}
}
} else {
COPY_BUF(l,buffer,nbchars,c);
str += l;
if (nbchars + XML_PARSER_BUFFER_SIZE > buffer_size) {
growBuffer(buffer, XML_PARSER_BUFFER_SIZE);
}
}
if (str < last)
c = CUR_SCHAR(str, l);
else
c = 0;
}
buffer[nbchars] = 0;
return(buffer);
mem_error:
xmlErrMemory(ctxt, NULL);
int_error:
if (rep != NULL)
xmlFree(rep);
if (buffer != NULL)
xmlFree(buffer);
return(NULL);
}
| null | null | 208,533
|
301710766906450297101615067146831788109
| 164
|
Fix inappropriate fetch of entities content
For https://bugzilla.gnome.org/show_bug.cgi?id=761430
libfuzzer regression testing exposed another case where the parser would
fetch content of an external entity while not in validating mode.
Plug that hole
|
other
|
rizin
|
58926dffbe819fe9ebf5062f7130e026351cae01
| 1
|
static RzList *relocs(RzBinFile *bf) {
rz_return_val_if_fail(bf && bf->o, NULL);
QnxObj *qo = bf->o->bin_obj;
return rz_list_clone(qo->fixups);
}
| null | null | 208,535
|
115023292561390646487128713150698949735
| 5
|
fix #2964 - double-free in bin_qnx.c
|
other
|
php-src
|
cab1c3b3708eead315e033359d07049b23b147a3
| 1
|
PHP_MINIT_FUNCTION(snmp)
{
netsnmp_log_handler *logh;
zend_class_entry ce, cex;
le_snmp_session = zend_register_list_destructors_ex(php_snmp_session_destructor, NULL, PHP_SNMP_SESSION_RES_NAME, module_number);
init_snmp("snmpapp");
#ifdef NETSNMP_DS_LIB_DONT_PERSIST_STATE
/* Prevent update of the snmpapp.conf file */
netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_DONT_PERSIST_STATE, 1);
#endif
/* Disable logging, use exit status'es and related variabled to detect errors */
shutdown_snmp_logging();
logh = netsnmp_register_loghandler(NETSNMP_LOGHANDLER_NONE, LOG_ERR);
if (logh) {
logh->pri_max = LOG_ERR;
}
memcpy(&php_snmp_object_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers));
php_snmp_object_handlers.read_property = php_snmp_read_property;
php_snmp_object_handlers.write_property = php_snmp_write_property;
php_snmp_object_handlers.has_property = php_snmp_has_property;
php_snmp_object_handlers.get_properties = php_snmp_get_properties;
/* Register SNMP Class */
INIT_CLASS_ENTRY(ce, "SNMP", php_snmp_class_methods);
ce.create_object = php_snmp_object_new;
php_snmp_object_handlers.clone_obj = NULL;
php_snmp_ce = zend_register_internal_class(&ce TSRMLS_CC);
/* Register SNMP Class properties */
zend_hash_init(&php_snmp_properties, 0, NULL, NULL, 1);
PHP_SNMP_ADD_PROPERTIES(&php_snmp_properties, php_snmp_property_entries);
REGISTER_LONG_CONSTANT("SNMP_OID_OUTPUT_SUFFIX", NETSNMP_OID_OUTPUT_SUFFIX, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("SNMP_OID_OUTPUT_MODULE", NETSNMP_OID_OUTPUT_MODULE, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("SNMP_OID_OUTPUT_FULL", NETSNMP_OID_OUTPUT_FULL, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("SNMP_OID_OUTPUT_NUMERIC", NETSNMP_OID_OUTPUT_NUMERIC, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("SNMP_OID_OUTPUT_UCD", NETSNMP_OID_OUTPUT_UCD, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("SNMP_OID_OUTPUT_NONE", NETSNMP_OID_OUTPUT_NONE, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("SNMP_VALUE_LIBRARY", SNMP_VALUE_LIBRARY, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("SNMP_VALUE_PLAIN", SNMP_VALUE_PLAIN, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("SNMP_VALUE_OBJECT", SNMP_VALUE_OBJECT, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("SNMP_BIT_STR", ASN_BIT_STR, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("SNMP_OCTET_STR", ASN_OCTET_STR, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("SNMP_OPAQUE", ASN_OPAQUE, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("SNMP_NULL", ASN_NULL, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("SNMP_OBJECT_ID", ASN_OBJECT_ID, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("SNMP_IPADDRESS", ASN_IPADDRESS, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("SNMP_COUNTER", ASN_GAUGE, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("SNMP_UNSIGNED", ASN_UNSIGNED, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("SNMP_TIMETICKS", ASN_TIMETICKS, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("SNMP_UINTEGER", ASN_UINTEGER, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("SNMP_INTEGER", ASN_INTEGER, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("SNMP_COUNTER64", ASN_COUNTER64, CONST_CS | CONST_PERSISTENT);
REGISTER_SNMP_CLASS_CONST_LONG("VERSION_1", SNMP_VERSION_1);
REGISTER_SNMP_CLASS_CONST_LONG("VERSION_2c", SNMP_VERSION_2c);
REGISTER_SNMP_CLASS_CONST_LONG("VERSION_2C", SNMP_VERSION_2c);
REGISTER_SNMP_CLASS_CONST_LONG("VERSION_3", SNMP_VERSION_3);
REGISTER_SNMP_CLASS_CONST_LONG("ERRNO_NOERROR", PHP_SNMP_ERRNO_NOERROR);
REGISTER_SNMP_CLASS_CONST_LONG("ERRNO_ANY", PHP_SNMP_ERRNO_ANY);
REGISTER_SNMP_CLASS_CONST_LONG("ERRNO_GENERIC", PHP_SNMP_ERRNO_GENERIC);
REGISTER_SNMP_CLASS_CONST_LONG("ERRNO_TIMEOUT", PHP_SNMP_ERRNO_TIMEOUT);
REGISTER_SNMP_CLASS_CONST_LONG("ERRNO_ERROR_IN_REPLY", PHP_SNMP_ERRNO_ERROR_IN_REPLY);
REGISTER_SNMP_CLASS_CONST_LONG("ERRNO_OID_NOT_INCREASING", PHP_SNMP_ERRNO_OID_NOT_INCREASING);
REGISTER_SNMP_CLASS_CONST_LONG("ERRNO_OID_PARSING_ERROR", PHP_SNMP_ERRNO_OID_PARSING_ERROR);
REGISTER_SNMP_CLASS_CONST_LONG("ERRNO_MULTIPLE_SET_QUERIES", PHP_SNMP_ERRNO_MULTIPLE_SET_QUERIES);
/* Register SNMPException class */
INIT_CLASS_ENTRY(cex, "SNMPException", NULL);
#ifdef HAVE_SPL
php_snmp_exception_ce = zend_register_internal_class_ex(&cex, spl_ce_RuntimeException, NULL TSRMLS_CC);
#else
php_snmp_exception_ce = zend_register_internal_class_ex(&cex, zend_exception_get_default(TSRMLS_C), NULL TSRMLS_CC);
#endif
return SUCCESS;
}
| null | null | 208,654
|
206527472711439509880743098822926959732
| 85
|
Fixed bug #72479 - same as #72434
|
other
|
flatpak
|
e2c4ded323161f47609d0af97d00019d04a635f1
| 1
|
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;
}
/* TODO: Ideally we should let `flatpak run` inherit the portal's
* environment, in case e.g. a LD_LIBRARY_PATH is needed to be able
* to run `flatpak run`, but tell it to start from a blank environment
* when running the Flatpak app; but this isn't currently possible, so
* for now we preserve existing behaviour. */
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;
}
| null | null | 208,673
|
190053802695498490428664499416244210335
| 639
|
portal: Let --env= and --env-fd= take precedence over extra-args
Previously, if you launched a subsandbox while specifying environment
variable overrides, any environment variable overrides that existed
in the parent Flatpak app would take precedence:
host$ flatpak run --env=FOO=1 --command=bash example.app
[📦 example.app ~]$ env | grep FOO
FOO=1
[📦 example.app ~]$ flatpak-spawn --env=FOO=x sh -c 'env | grep FOO'
FOO=1
This does not seem like least-astonishment, and in particular will
cause problems if the app wants to override LD_LIBRARY_PATH in the
subsandbox. Change the precedence so that the environment variables
set by flatpak-spawn will "win":
host$ flatpak run --env=FOO1=1 --env=FOO2=2 --command=bash example.app
[📦 example.app ~]$ env | grep FOO
FOO1=1
FOO2=2
[📦 example.app ~]$ flatpak-spawn --env=FOO1=x sh -c 'env | grep FOO'
FOO1=x
FOO2=2
This follows up from GHSA-4ppf-fxf6-vxg2 to fix an issue that I noticed
while resolving that vulnerability, but is not required for fixing the
vulnerability.
Signed-off-by: Simon McVittie <[email protected]>
|
other
|
radare2
|
10517e3ff0e609697eb8cde60ec8dc999ee5ea24
| 1
|
R_API void r_core_anal_esil(RCore *core, const char *str, const char *target) {
bool cfg_anal_strings = r_config_get_i (core->config, "anal.strings");
bool emu_lazy = r_config_get_i (core->config, "emu.lazy");
bool gp_fixed = r_config_get_i (core->config, "anal.gpfixed");
RAnalEsil *ESIL = core->anal->esil;
ut64 refptr = 0LL;
const char *pcname;
RAnalOp op = R_EMPTY;
ut8 *buf = NULL;
bool end_address_set = false;
int iend;
int minopsize = 4; // XXX this depends on asm->mininstrsize
bool archIsArm = false;
ut64 addr = core->offset;
ut64 start = addr;
ut64 end = 0LL;
ut64 cur;
if (esil_anal_stop || r_cons_is_breaked ()) {
// faster ^C
return;
}
mycore = core;
if (!strcmp (str, "?")) {
eprintf ("Usage: aae[f] [len] [addr] - analyze refs in function, section or len bytes with esil\n");
eprintf (" aae $SS @ $S - analyze the whole section\n");
eprintf (" aae $SS str.Hello @ $S - find references for str.Hellow\n");
eprintf (" aaef - analyze functions discovered with esil\n");
return;
}
#define CHECKREF(x) ((refptr && (x) == refptr) || !refptr)
if (target) {
const char *expr = r_str_trim_head_ro (target);
if (*expr) {
refptr = ntarget = r_num_math (core->num, expr);
if (!refptr) {
ntarget = refptr = addr;
}
} else {
ntarget = UT64_MAX;
refptr = 0LL;
}
} else {
ntarget = UT64_MAX;
refptr = 0LL;
}
RAnalFunction *fcn = NULL;
if (!strcmp (str, "f")) {
fcn = r_anal_get_fcn_in (core->anal, core->offset, 0);
if (fcn) {
start = r_anal_function_min_addr (fcn);
addr = fcn->addr;
end = r_anal_function_max_addr (fcn);
end_address_set = true;
}
}
if (!end_address_set) {
if (str[0] == ' ') {
end = addr + r_num_math (core->num, str + 1);
} else {
RIOMap *map = r_io_map_get_at (core->io, addr);
if (map) {
end = r_io_map_end (map);
} else {
end = addr + core->blocksize;
}
}
}
iend = end - start;
if (iend < 0) {
return;
}
if (iend > MAX_SCAN_SIZE) {
eprintf ("Warning: Not going to analyze 0x%08"PFMT64x" bytes.\n", (ut64)iend);
return;
}
buf = malloc ((size_t)iend + 2);
if (!buf) {
perror ("malloc");
return;
}
esilbreak_last_read = UT64_MAX;
r_io_read_at (core->io, start, buf, iend + 1);
if (!ESIL) {
r_core_cmd0 (core, "aei");
ESIL = core->anal->esil;
if (!ESIL) {
eprintf ("ESIL not initialized\n");
return;
}
r_core_cmd0 (core, "aeim");
ESIL = core->anal->esil;
}
const char *spname = r_reg_get_name (core->anal->reg, R_REG_NAME_SP);
if (!spname) {
eprintf ("Error: No =SP defined in the reg profile.\n");
return;
}
EsilBreakCtx ctx = {
&op,
fcn,
spname,
r_reg_getv (core->anal->reg, spname)
};
ESIL->cb.hook_reg_write = &esilbreak_reg_write;
//this is necessary for the hook to read the id of analop
ESIL->user = &ctx;
ESIL->cb.hook_mem_read = &esilbreak_mem_read;
ESIL->cb.hook_mem_write = &esilbreak_mem_write;
if (fcn && fcn->reg_save_area) {
r_reg_setv (core->anal->reg, ctx.spname, ctx.initial_sp - fcn->reg_save_area);
}
//eprintf ("Analyzing ESIL refs from 0x%"PFMT64x" - 0x%"PFMT64x"\n", addr, end);
// TODO: backup/restore register state before/after analysis
pcname = r_reg_get_name (core->anal->reg, R_REG_NAME_PC);
if (!pcname || !*pcname) {
eprintf ("Cannot find program counter register in the current profile.\n");
return;
}
esil_anal_stop = false;
r_cons_break_push (cccb, core);
int arch = -1;
if (!strcmp (core->anal->cur->arch, "arm")) {
switch (core->anal->cur->bits) {
case 64: arch = R2_ARCH_ARM64; break;
case 32: arch = R2_ARCH_ARM32; break;
case 16: arch = R2_ARCH_THUMB; break;
}
archIsArm = true;
}
ut64 gp = r_config_get_i (core->config, "anal.gp");
const char *gp_reg = NULL;
if (!strcmp (core->anal->cur->arch, "mips")) {
gp_reg = "gp";
arch = R2_ARCH_MIPS;
}
const char *sn = r_reg_get_name (core->anal->reg, R_REG_NAME_SN);
if (!sn) {
eprintf ("Warning: No SN reg alias for current architecture.\n");
}
r_reg_arena_push (core->anal->reg);
IterCtx ictx = { start, end, fcn, NULL };
size_t i = addr - start;
size_t i_old = 0;
do {
if (esil_anal_stop || r_cons_is_breaked ()) {
break;
}
cur = start + i;
if (!r_io_is_valid_offset (core->io, cur, 0)) {
break;
}
#if 0
// disabled because it causes some tests to fail
{
RPVector *list = r_meta_get_all_in (core->anal, cur, R_META_TYPE_ANY);
void **it;
r_pvector_foreach (list, it) {
RIntervalNode *node = *it;
RAnalMetaItem *meta = node->data;
switch (meta->type) {
case R_META_TYPE_DATA:
case R_META_TYPE_STRING:
case R_META_TYPE_FORMAT:
#if 0
{
int msz = r_meta_get_size (core->anal, meta->type);
i += (msz > 0)? msz: minopsize;
}
r_pvector_free (list);
goto loopback;
#elif 0
{
int msz = r_meta_get_size (core->anal, meta->type);
i += (msz > 0)? msz: minopsize;
i--;
}
#else
i += 4;
goto repeat;
#endif
default:
break;
}
}
r_pvector_free (list);
}
#endif
/* realign address if needed */
r_core_seek_arch_bits (core, cur);
int opalign = core->anal->pcalign;
if (opalign > 0) {
cur -= (cur % opalign);
}
r_anal_op_fini (&op);
r_asm_set_pc (core->rasm, cur);
i_old = i;
#if 1
if (i > iend) {
goto repeat;
}
#endif
if (!r_anal_op (core->anal, &op, cur, buf + i, iend - i, R_ANAL_OP_MASK_ESIL | R_ANAL_OP_MASK_VAL | R_ANAL_OP_MASK_HINT)) {
i += minopsize - 1; // XXX dupe in op.size below
}
if (op.type == R_ANAL_OP_TYPE_ILL || op.type == R_ANAL_OP_TYPE_UNK) {
// i += 2
r_anal_op_fini (&op);
goto repeat;
}
//we need to check again i because buf+i may goes beyond its boundaries
//because of i+= minopsize - 1
if (op.size < 1) {
i += minopsize - 1;
goto repeat;
}
if (emu_lazy) {
if (op.type & R_ANAL_OP_TYPE_REP) {
i += op.size - 1;
goto repeat;
}
switch (op.type & R_ANAL_OP_TYPE_MASK) {
case R_ANAL_OP_TYPE_JMP:
case R_ANAL_OP_TYPE_CJMP:
case R_ANAL_OP_TYPE_CALL:
case R_ANAL_OP_TYPE_RET:
case R_ANAL_OP_TYPE_ILL:
case R_ANAL_OP_TYPE_NOP:
case R_ANAL_OP_TYPE_UJMP:
case R_ANAL_OP_TYPE_IO:
case R_ANAL_OP_TYPE_LEAVE:
case R_ANAL_OP_TYPE_CRYPTO:
case R_ANAL_OP_TYPE_CPL:
case R_ANAL_OP_TYPE_SYNC:
case R_ANAL_OP_TYPE_SWI:
case R_ANAL_OP_TYPE_CMP:
case R_ANAL_OP_TYPE_ACMP:
case R_ANAL_OP_TYPE_NULL:
case R_ANAL_OP_TYPE_CSWI:
case R_ANAL_OP_TYPE_TRAP:
i += op.size - 1;
goto repeat;
// those require write support
case R_ANAL_OP_TYPE_PUSH:
case R_ANAL_OP_TYPE_POP:
i += op.size - 1;
goto repeat;
}
}
if (sn && op.type == R_ANAL_OP_TYPE_SWI) {
r_strf_buffer (64);
r_flag_space_set (core->flags, R_FLAGS_FS_SYSCALLS);
int snv = (arch == R2_ARCH_THUMB)? op.val: (int)r_reg_getv (core->anal->reg, sn);
RSyscallItem *si = r_syscall_get (core->anal->syscall, snv, -1);
if (si) {
// eprintf ("0x%08"PFMT64x" SYSCALL %-4d %s\n", cur, snv, si->name);
r_flag_set_next (core->flags, r_strf ("syscall.%s", si->name), cur, 1);
} else {
//todo were doing less filtering up top because we can't match against 80 on all platforms
// might get too many of this path now..
// eprintf ("0x%08"PFMT64x" SYSCALL %d\n", cur, snv);
r_flag_set_next (core->flags, r_strf ("syscall.%d", snv), cur, 1);
}
r_flag_space_set (core->flags, NULL);
r_syscall_item_free (si);
}
const char *esilstr = R_STRBUF_SAFEGET (&op.esil);
i += op.size - 1;
if (R_STR_ISEMPTY (esilstr)) {
goto repeat;
}
r_anal_esil_set_pc (ESIL, cur);
r_reg_setv (core->anal->reg, pcname, cur + op.size);
if (gp_fixed && gp_reg) {
r_reg_setv (core->anal->reg, gp_reg, gp);
}
(void)r_anal_esil_parse (ESIL, esilstr);
// looks like ^C is handled by esil_parse !!!!
//r_anal_esil_dumpstack (ESIL);
//r_anal_esil_stack_free (ESIL);
switch (op.type) {
case R_ANAL_OP_TYPE_LEA:
// arm64
if (core->anal->cur && arch == R2_ARCH_ARM64) {
if (CHECKREF (ESIL->cur)) {
r_anal_xrefs_set (core->anal, cur, ESIL->cur, R_ANAL_REF_TYPE_STRING);
}
} else if ((target && op.ptr == ntarget) || !target) {
if (CHECKREF (ESIL->cur)) {
if (op.ptr && r_io_is_valid_offset (core->io, op.ptr, !core->anal->opt.noncode)) {
r_anal_xrefs_set (core->anal, cur, op.ptr, R_ANAL_REF_TYPE_STRING);
} else {
r_anal_xrefs_set (core->anal, cur, ESIL->cur, R_ANAL_REF_TYPE_STRING);
}
}
}
if (cfg_anal_strings) {
add_string_ref (core, op.addr, op.ptr);
}
break;
case R_ANAL_OP_TYPE_ADD:
/* TODO: test if this is valid for other archs too */
if (core->anal->cur && archIsArm) {
/* This code is known to work on Thumb, ARM and ARM64 */
ut64 dst = ESIL->cur;
if ((target && dst == ntarget) || !target) {
if (CHECKREF (dst)) {
int type = core_type_by_addr (core, dst); // R_ANAL_REF_TYPE_DATA;
r_anal_xrefs_set (core->anal, cur, dst, type);
}
}
if (cfg_anal_strings) {
add_string_ref (core, op.addr, dst);
}
} else if ((core->anal->bits == 32 && core->anal->cur && arch == R2_ARCH_MIPS)) {
ut64 dst = ESIL->cur;
if (!op.src[0] || !op.src[0]->reg || !op.src[0]->reg->name) {
break;
}
if (!strcmp (op.src[0]->reg->name, "sp")) {
break;
}
if (!strcmp (op.src[0]->reg->name, "zero")) {
break;
}
if ((target && dst == ntarget) || !target) {
if (dst > 0xffff && op.src[1] && (dst & 0xffff) == (op.src[1]->imm & 0xffff) && myvalid (mycore->io, dst)) {
RFlagItem *f;
char *str;
if (CHECKREF (dst) || CHECKREF (cur)) {
r_anal_xrefs_set (core->anal, cur, dst, R_ANAL_REF_TYPE_DATA);
if (cfg_anal_strings) {
add_string_ref (core, op.addr, dst);
}
if ((f = r_core_flag_get_by_spaces (core->flags, dst))) {
r_meta_set_string (core->anal, R_META_TYPE_COMMENT, cur, f->name);
} else if ((str = is_string_at (mycore, dst, NULL))) {
char *str2 = r_str_newf ("esilref: '%s'", str);
// HACK avoid format string inside string used later as format
// string crashes disasm inside agf under some conditions.
// https://github.com/radareorg/radare2/issues/6937
r_str_replace_char (str2, '%', '&');
r_meta_set_string (core->anal, R_META_TYPE_COMMENT, cur, str2);
free (str2);
free (str);
}
}
}
}
}
break;
case R_ANAL_OP_TYPE_LOAD:
{
ut64 dst = esilbreak_last_read;
if (dst != UT64_MAX && CHECKREF (dst)) {
if (myvalid (mycore->io, dst)) {
r_anal_xrefs_set (core->anal, cur, dst, R_ANAL_REF_TYPE_DATA);
if (cfg_anal_strings) {
add_string_ref (core, op.addr, dst);
}
}
}
dst = esilbreak_last_data;
if (dst != UT64_MAX && CHECKREF (dst)) {
if (myvalid (mycore->io, dst)) {
r_anal_xrefs_set (core->anal, cur, dst, R_ANAL_REF_TYPE_DATA);
if (cfg_anal_strings) {
add_string_ref (core, op.addr, dst);
}
}
}
}
break;
case R_ANAL_OP_TYPE_JMP:
{
ut64 dst = op.jump;
if (CHECKREF (dst)) {
if (myvalid (core->io, dst)) {
r_anal_xrefs_set (core->anal, cur, dst, R_ANAL_REF_TYPE_CODE);
}
}
}
break;
case R_ANAL_OP_TYPE_CALL:
{
ut64 dst = op.jump;
if (CHECKREF (dst)) {
if (myvalid (core->io, dst)) {
r_anal_xrefs_set (core->anal, cur, dst, R_ANAL_REF_TYPE_CALL);
}
ESIL->old = cur + op.size;
getpcfromstack (core, ESIL);
}
}
break;
case R_ANAL_OP_TYPE_UJMP:
case R_ANAL_OP_TYPE_UCALL:
case R_ANAL_OP_TYPE_ICALL:
case R_ANAL_OP_TYPE_RCALL:
case R_ANAL_OP_TYPE_IRCALL:
case R_ANAL_OP_TYPE_MJMP:
{
ut64 dst = core->anal->esil->jump_target;
if (dst == 0 || dst == UT64_MAX) {
dst = r_reg_getv (core->anal->reg, pcname);
}
if (CHECKREF (dst)) {
if (myvalid (core->io, dst)) {
RAnalRefType ref =
(op.type & R_ANAL_OP_TYPE_MASK) == R_ANAL_OP_TYPE_UCALL
? R_ANAL_REF_TYPE_CALL
: R_ANAL_REF_TYPE_CODE;
r_anal_xrefs_set (core->anal, cur, dst, ref);
r_core_anal_fcn (core, dst, UT64_MAX, R_ANAL_REF_TYPE_NULL, 1);
// analyze function here
#if 0
if (op.type == R_ANAL_OP_TYPE_UCALL || op.type == R_ANAL_OP_TYPE_RCALL) {
eprintf ("0x%08"PFMT64x" RCALL TO %llx\n", cur, dst);
}
#endif
}
}
}
break;
default:
break;
}
r_anal_esil_stack_free (ESIL);
repeat:
if (!r_anal_get_block_at (core->anal, cur)) {
size_t fcn_i;
for (fcn_i = i_old + 1; fcn_i <= i; fcn_i++) {
if (r_anal_get_function_at (core->anal, start + fcn_i)) {
i = fcn_i - 1;
break;
}
}
}
if (i >= iend) {
break;
}
} while (get_next_i (&ictx, &i));
r_list_free (ictx.bbl);
r_list_free (ictx.path);
r_list_free (ictx.switch_path);
free (buf);
ESIL->cb.hook_mem_read = NULL;
ESIL->cb.hook_mem_write = NULL;
ESIL->cb.hook_reg_write = NULL;
ESIL->user = NULL;
r_anal_op_fini (&op);
r_cons_break_pop ();
// restore register
r_reg_arena_pop (core->anal->reg);
}
| null | null | 208,680
|
336460335272336496527727478453878770582
| 464
|
aaef on arm/thumb switches causes uaf ##crash
* Reported by peacock-doris via huntr.dev
* Reproducer: poc_uaf_r_reg_get
|
other
|
jdk17u
|
860464e46105b98ccf21e98abe2dc6e80155887c
| 1
|
void LinkResolver::resolve_handle_call(CallInfo& result,
const LinkInfo& link_info,
TRAPS) {
// JSR 292: this must be an implicitly generated method MethodHandle.invokeExact(*...) or similar
Klass* resolved_klass = link_info.resolved_klass();
assert(resolved_klass == vmClasses::MethodHandle_klass() ||
resolved_klass == vmClasses::VarHandle_klass(), "");
assert(MethodHandles::is_signature_polymorphic_name(link_info.name()), "");
Handle resolved_appendix;
Method* resolved_method = lookup_polymorphic_method(link_info, &resolved_appendix, CHECK);
result.set_handle(resolved_klass, methodHandle(THREAD, resolved_method), resolved_appendix, CHECK);
}
| null | null | 208,699
|
30695701720337285266835790248006528789
| 12
|
8281866: Enhance MethodHandle invocations
Reviewed-by: mbaesken
Backport-of: d974d9da365f787f67971d88c79371c8b0769f75
|
other
|
libxml2
|
03c6723043775122313f107695066e5744189a08
| 1
|
*/
static int
xmlXPathCompOpEval(xmlXPathParserContextPtr ctxt, xmlXPathStepOpPtr op)
{
int total = 0;
int equal, ret;
xmlXPathCompExprPtr comp;
xmlXPathObjectPtr arg1, arg2;
xmlNodePtr bak;
xmlDocPtr bakd;
int pp;
int cs;
CHECK_ERROR0;
comp = ctxt->comp;
switch (op->op) {
case XPATH_OP_END:
return (0);
case XPATH_OP_AND:
bakd = ctxt->context->doc;
bak = ctxt->context->node;
pp = ctxt->context->proximityPosition;
cs = ctxt->context->contextSize;
total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]);
CHECK_ERROR0;
xmlXPathBooleanFunction(ctxt, 1);
if ((ctxt->value == NULL) || (ctxt->value->boolval == 0))
return (total);
arg2 = valuePop(ctxt);
ctxt->context->doc = bakd;
ctxt->context->node = bak;
ctxt->context->proximityPosition = pp;
ctxt->context->contextSize = cs;
total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]);
if (ctxt->error) {
xmlXPathFreeObject(arg2);
return(0);
}
xmlXPathBooleanFunction(ctxt, 1);
arg1 = valuePop(ctxt);
arg1->boolval &= arg2->boolval;
valuePush(ctxt, arg1);
xmlXPathReleaseObject(ctxt->context, arg2);
return (total);
case XPATH_OP_OR:
bakd = ctxt->context->doc;
bak = ctxt->context->node;
pp = ctxt->context->proximityPosition;
cs = ctxt->context->contextSize;
total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]);
CHECK_ERROR0;
xmlXPathBooleanFunction(ctxt, 1);
if ((ctxt->value == NULL) || (ctxt->value->boolval == 1))
return (total);
arg2 = valuePop(ctxt);
ctxt->context->doc = bakd;
ctxt->context->node = bak;
ctxt->context->proximityPosition = pp;
ctxt->context->contextSize = cs;
total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]);
if (ctxt->error) {
xmlXPathFreeObject(arg2);
return(0);
}
xmlXPathBooleanFunction(ctxt, 1);
arg1 = valuePop(ctxt);
arg1->boolval |= arg2->boolval;
valuePush(ctxt, arg1);
xmlXPathReleaseObject(ctxt->context, arg2);
return (total);
case XPATH_OP_EQUAL:
bakd = ctxt->context->doc;
bak = ctxt->context->node;
pp = ctxt->context->proximityPosition;
cs = ctxt->context->contextSize;
total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]);
CHECK_ERROR0;
ctxt->context->doc = bakd;
ctxt->context->node = bak;
ctxt->context->proximityPosition = pp;
ctxt->context->contextSize = cs;
total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]);
CHECK_ERROR0;
if (op->value)
equal = xmlXPathEqualValues(ctxt);
else
equal = xmlXPathNotEqualValues(ctxt);
valuePush(ctxt, xmlXPathCacheNewBoolean(ctxt->context, equal));
return (total);
case XPATH_OP_CMP:
bakd = ctxt->context->doc;
bak = ctxt->context->node;
pp = ctxt->context->proximityPosition;
cs = ctxt->context->contextSize;
total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]);
CHECK_ERROR0;
ctxt->context->doc = bakd;
ctxt->context->node = bak;
ctxt->context->proximityPosition = pp;
ctxt->context->contextSize = cs;
total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]);
CHECK_ERROR0;
ret = xmlXPathCompareValues(ctxt, op->value, op->value2);
valuePush(ctxt, xmlXPathCacheNewBoolean(ctxt->context, ret));
return (total);
case XPATH_OP_PLUS:
bakd = ctxt->context->doc;
bak = ctxt->context->node;
pp = ctxt->context->proximityPosition;
cs = ctxt->context->contextSize;
total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]);
CHECK_ERROR0;
if (op->ch2 != -1) {
ctxt->context->doc = bakd;
ctxt->context->node = bak;
ctxt->context->proximityPosition = pp;
ctxt->context->contextSize = cs;
total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]);
}
CHECK_ERROR0;
if (op->value == 0)
xmlXPathSubValues(ctxt);
else if (op->value == 1)
xmlXPathAddValues(ctxt);
else if (op->value == 2)
xmlXPathValueFlipSign(ctxt);
else if (op->value == 3) {
CAST_TO_NUMBER;
CHECK_TYPE0(XPATH_NUMBER);
}
return (total);
case XPATH_OP_MULT:
bakd = ctxt->context->doc;
bak = ctxt->context->node;
pp = ctxt->context->proximityPosition;
cs = ctxt->context->contextSize;
total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]);
CHECK_ERROR0;
ctxt->context->doc = bakd;
ctxt->context->node = bak;
ctxt->context->proximityPosition = pp;
ctxt->context->contextSize = cs;
total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]);
CHECK_ERROR0;
if (op->value == 0)
xmlXPathMultValues(ctxt);
else if (op->value == 1)
xmlXPathDivValues(ctxt);
else if (op->value == 2)
xmlXPathModValues(ctxt);
return (total);
case XPATH_OP_UNION:
bakd = ctxt->context->doc;
bak = ctxt->context->node;
pp = ctxt->context->proximityPosition;
cs = ctxt->context->contextSize;
total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]);
CHECK_ERROR0;
ctxt->context->doc = bakd;
ctxt->context->node = bak;
ctxt->context->proximityPosition = pp;
ctxt->context->contextSize = cs;
total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]);
CHECK_ERROR0;
CHECK_TYPE0(XPATH_NODESET);
arg2 = valuePop(ctxt);
CHECK_TYPE0(XPATH_NODESET);
arg1 = valuePop(ctxt);
if ((arg1->nodesetval == NULL) ||
((arg2->nodesetval != NULL) &&
(arg2->nodesetval->nodeNr != 0)))
{
arg1->nodesetval = xmlXPathNodeSetMerge(arg1->nodesetval,
arg2->nodesetval);
}
valuePush(ctxt, arg1);
xmlXPathReleaseObject(ctxt->context, arg2);
return (total);
case XPATH_OP_ROOT:
xmlXPathRoot(ctxt);
return (total);
case XPATH_OP_NODE:
if (op->ch1 != -1)
total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]);
CHECK_ERROR0;
if (op->ch2 != -1)
total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]);
CHECK_ERROR0;
valuePush(ctxt, xmlXPathCacheNewNodeSet(ctxt->context,
ctxt->context->node));
return (total);
case XPATH_OP_RESET:
if (op->ch1 != -1)
total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]);
CHECK_ERROR0;
if (op->ch2 != -1)
total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]);
CHECK_ERROR0;
ctxt->context->node = NULL;
return (total);
case XPATH_OP_COLLECT:{
if (op->ch1 == -1)
return (total);
total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]);
CHECK_ERROR0;
total += xmlXPathNodeCollectAndTest(ctxt, op, NULL, NULL, 0);
return (total);
}
case XPATH_OP_VALUE:
valuePush(ctxt,
xmlXPathCacheObjectCopy(ctxt->context,
(xmlXPathObjectPtr) op->value4));
return (total);
case XPATH_OP_VARIABLE:{
xmlXPathObjectPtr val;
if (op->ch1 != -1)
total +=
xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]);
if (op->value5 == NULL) {
val = xmlXPathVariableLookup(ctxt->context, op->value4);
if (val == NULL) {
ctxt->error = XPATH_UNDEF_VARIABLE_ERROR;
return(0);
}
valuePush(ctxt, val);
} else {
const xmlChar *URI;
URI = xmlXPathNsLookup(ctxt->context, op->value5);
if (URI == NULL) {
xmlGenericError(xmlGenericErrorContext,
"xmlXPathCompOpEval: variable %s bound to undefined prefix %s\n",
(char *) op->value4, (char *)op->value5);
ctxt->error = XPATH_UNDEF_PREFIX_ERROR;
return (total);
}
val = xmlXPathVariableLookupNS(ctxt->context,
op->value4, URI);
if (val == NULL) {
ctxt->error = XPATH_UNDEF_VARIABLE_ERROR;
return(0);
}
valuePush(ctxt, val);
}
return (total);
}
case XPATH_OP_FUNCTION:{
xmlXPathFunction func;
const xmlChar *oldFunc, *oldFuncURI;
int i;
int frame;
frame = xmlXPathSetFrame(ctxt);
if (op->ch1 != -1)
total +=
xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]);
if (ctxt->valueNr < op->value) {
xmlGenericError(xmlGenericErrorContext,
"xmlXPathCompOpEval: parameter error\n");
ctxt->error = XPATH_INVALID_OPERAND;
xmlXPathPopFrame(ctxt, frame);
return (total);
}
for (i = 0; i < op->value; i++) {
if (ctxt->valueTab[(ctxt->valueNr - 1) - i] == NULL) {
xmlGenericError(xmlGenericErrorContext,
"xmlXPathCompOpEval: parameter error\n");
ctxt->error = XPATH_INVALID_OPERAND;
xmlXPathPopFrame(ctxt, frame);
return (total);
}
}
if (op->cache != NULL)
XML_CAST_FPTR(func) = op->cache;
else {
const xmlChar *URI = NULL;
if (op->value5 == NULL)
func =
xmlXPathFunctionLookup(ctxt->context,
op->value4);
else {
URI = xmlXPathNsLookup(ctxt->context, op->value5);
if (URI == NULL) {
xmlGenericError(xmlGenericErrorContext,
"xmlXPathCompOpEval: function %s bound to undefined prefix %s\n",
(char *)op->value4, (char *)op->value5);
xmlXPathPopFrame(ctxt, frame);
ctxt->error = XPATH_UNDEF_PREFIX_ERROR;
return (total);
}
func = xmlXPathFunctionLookupNS(ctxt->context,
op->value4, URI);
}
if (func == NULL) {
xmlGenericError(xmlGenericErrorContext,
"xmlXPathCompOpEval: function %s not found\n",
(char *)op->value4);
XP_ERROR0(XPATH_UNKNOWN_FUNC_ERROR);
}
op->cache = XML_CAST_FPTR(func);
op->cacheURI = (void *) URI;
}
oldFunc = ctxt->context->function;
oldFuncURI = ctxt->context->functionURI;
ctxt->context->function = op->value4;
ctxt->context->functionURI = op->cacheURI;
func(ctxt, op->value);
ctxt->context->function = oldFunc;
ctxt->context->functionURI = oldFuncURI;
xmlXPathPopFrame(ctxt, frame);
return (total);
}
case XPATH_OP_ARG:
bakd = ctxt->context->doc;
bak = ctxt->context->node;
pp = ctxt->context->proximityPosition;
cs = ctxt->context->contextSize;
if (op->ch1 != -1)
total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]);
ctxt->context->contextSize = cs;
ctxt->context->proximityPosition = pp;
ctxt->context->node = bak;
ctxt->context->doc = bakd;
CHECK_ERROR0;
if (op->ch2 != -1) {
total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]);
ctxt->context->doc = bakd;
ctxt->context->node = bak;
CHECK_ERROR0;
}
return (total);
case XPATH_OP_PREDICATE:
case XPATH_OP_FILTER:{
xmlXPathObjectPtr res;
xmlXPathObjectPtr obj, tmp;
xmlNodeSetPtr newset = NULL;
xmlNodeSetPtr oldset;
xmlNodePtr oldnode;
xmlDocPtr oldDoc;
int i;
/*
* Optimization for ()[1] selection i.e. the first elem
*/
if ((op->ch1 != -1) && (op->ch2 != -1) &&
#ifdef XP_OPTIMIZED_FILTER_FIRST
/*
* FILTER TODO: Can we assume that the inner processing
* will result in an ordered list if we have an
* XPATH_OP_FILTER?
* What about an additional field or flag on
* xmlXPathObject like @sorted ? This way we wouln'd need
* to assume anything, so it would be more robust and
* easier to optimize.
*/
((comp->steps[op->ch1].op == XPATH_OP_SORT) || /* 18 */
(comp->steps[op->ch1].op == XPATH_OP_FILTER)) && /* 17 */
#else
(comp->steps[op->ch1].op == XPATH_OP_SORT) &&
#endif
(comp->steps[op->ch2].op == XPATH_OP_VALUE)) { /* 12 */
xmlXPathObjectPtr val;
val = comp->steps[op->ch2].value4;
if ((val != NULL) && (val->type == XPATH_NUMBER) &&
(val->floatval == 1.0)) {
xmlNodePtr first = NULL;
total +=
xmlXPathCompOpEvalFirst(ctxt,
&comp->steps[op->ch1],
&first);
CHECK_ERROR0;
/*
* The nodeset should be in document order,
* Keep only the first value
*/
if ((ctxt->value != NULL) &&
(ctxt->value->type == XPATH_NODESET) &&
(ctxt->value->nodesetval != NULL) &&
(ctxt->value->nodesetval->nodeNr > 1))
ctxt->value->nodesetval->nodeNr = 1;
return (total);
}
}
/*
* Optimization for ()[last()] selection i.e. the last elem
*/
if ((op->ch1 != -1) && (op->ch2 != -1) &&
(comp->steps[op->ch1].op == XPATH_OP_SORT) &&
(comp->steps[op->ch2].op == XPATH_OP_SORT)) {
int f = comp->steps[op->ch2].ch1;
if ((f != -1) &&
(comp->steps[f].op == XPATH_OP_FUNCTION) &&
(comp->steps[f].value5 == NULL) &&
(comp->steps[f].value == 0) &&
(comp->steps[f].value4 != NULL) &&
(xmlStrEqual
(comp->steps[f].value4, BAD_CAST "last"))) {
xmlNodePtr last = NULL;
total +=
xmlXPathCompOpEvalLast(ctxt,
&comp->steps[op->ch1],
&last);
CHECK_ERROR0;
/*
* The nodeset should be in document order,
* Keep only the last value
*/
if ((ctxt->value != NULL) &&
(ctxt->value->type == XPATH_NODESET) &&
(ctxt->value->nodesetval != NULL) &&
(ctxt->value->nodesetval->nodeTab != NULL) &&
(ctxt->value->nodesetval->nodeNr > 1)) {
ctxt->value->nodesetval->nodeTab[0] =
ctxt->value->nodesetval->nodeTab[ctxt->
value->
nodesetval->
nodeNr -
1];
ctxt->value->nodesetval->nodeNr = 1;
}
return (total);
}
}
/*
* Process inner predicates first.
* Example "index[parent::book][1]":
* ...
* PREDICATE <-- we are here "[1]"
* PREDICATE <-- process "[parent::book]" first
* SORT
* COLLECT 'parent' 'name' 'node' book
* NODE
* ELEM Object is a number : 1
*/
if (op->ch1 != -1)
total +=
xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]);
CHECK_ERROR0;
if (op->ch2 == -1)
return (total);
if (ctxt->value == NULL)
return (total);
oldnode = ctxt->context->node;
#ifdef LIBXML_XPTR_ENABLED
/*
* Hum are we filtering the result of an XPointer expression
*/
if (ctxt->value->type == XPATH_LOCATIONSET) {
xmlLocationSetPtr newlocset = NULL;
xmlLocationSetPtr oldlocset;
/*
* Extract the old locset, and then evaluate the result of the
* expression for all the element in the locset. use it to grow
* up a new locset.
*/
CHECK_TYPE0(XPATH_LOCATIONSET);
obj = valuePop(ctxt);
oldlocset = obj->user;
ctxt->context->node = NULL;
if ((oldlocset == NULL) || (oldlocset->locNr == 0)) {
ctxt->context->contextSize = 0;
ctxt->context->proximityPosition = 0;
if (op->ch2 != -1)
total +=
xmlXPathCompOpEval(ctxt,
&comp->steps[op->ch2]);
res = valuePop(ctxt);
if (res != NULL) {
xmlXPathReleaseObject(ctxt->context, res);
}
valuePush(ctxt, obj);
CHECK_ERROR0;
return (total);
}
newlocset = xmlXPtrLocationSetCreate(NULL);
for (i = 0; i < oldlocset->locNr; i++) {
/*
* Run the evaluation with a node list made of a
* single item in the nodelocset.
*/
ctxt->context->node = oldlocset->locTab[i]->user;
ctxt->context->contextSize = oldlocset->locNr;
ctxt->context->proximityPosition = i + 1;
tmp = xmlXPathCacheNewNodeSet(ctxt->context,
ctxt->context->node);
valuePush(ctxt, tmp);
if (op->ch2 != -1)
total +=
xmlXPathCompOpEval(ctxt,
&comp->steps[op->ch2]);
if (ctxt->error != XPATH_EXPRESSION_OK) {
xmlXPathFreeObject(obj);
return(0);
}
/*
* The result of the evaluation need to be tested to
* decided whether the filter succeeded or not
*/
res = valuePop(ctxt);
if (xmlXPathEvaluatePredicateResult(ctxt, res)) {
xmlXPtrLocationSetAdd(newlocset,
xmlXPathObjectCopy
(oldlocset->locTab[i]));
}
/*
* Cleanup
*/
if (res != NULL) {
xmlXPathReleaseObject(ctxt->context, res);
}
if (ctxt->value == tmp) {
res = valuePop(ctxt);
xmlXPathReleaseObject(ctxt->context, res);
}
ctxt->context->node = NULL;
}
/*
* The result is used as the new evaluation locset.
*/
xmlXPathReleaseObject(ctxt->context, obj);
ctxt->context->node = NULL;
ctxt->context->contextSize = -1;
ctxt->context->proximityPosition = -1;
valuePush(ctxt, xmlXPtrWrapLocationSet(newlocset));
ctxt->context->node = oldnode;
return (total);
}
#endif /* LIBXML_XPTR_ENABLED */
/*
* Extract the old set, and then evaluate the result of the
* expression for all the element in the set. use it to grow
* up a new set.
*/
CHECK_TYPE0(XPATH_NODESET);
obj = valuePop(ctxt);
oldset = obj->nodesetval;
oldnode = ctxt->context->node;
oldDoc = ctxt->context->doc;
ctxt->context->node = NULL;
if ((oldset == NULL) || (oldset->nodeNr == 0)) {
ctxt->context->contextSize = 0;
ctxt->context->proximityPosition = 0;
/*
if (op->ch2 != -1)
total +=
xmlXPathCompOpEval(ctxt,
&comp->steps[op->ch2]);
CHECK_ERROR0;
res = valuePop(ctxt);
if (res != NULL)
xmlXPathFreeObject(res);
*/
valuePush(ctxt, obj);
ctxt->context->node = oldnode;
CHECK_ERROR0;
} else {
tmp = NULL;
/*
* Initialize the new set.
* Also set the xpath document in case things like
* key() evaluation are attempted on the predicate
*/
newset = xmlXPathNodeSetCreate(NULL);
/*
* SPEC XPath 1.0:
* "For each node in the node-set to be filtered, the
* PredicateExpr is evaluated with that node as the
* context node, with the number of nodes in the
* node-set as the context size, and with the proximity
* position of the node in the node-set with respect to
* the axis as the context position;"
* @oldset is the node-set" to be filtered.
*
* SPEC XPath 1.0:
* "only predicates change the context position and
* context size (see [2.4 Predicates])."
* Example:
* node-set context pos
* nA 1
* nB 2
* nC 3
* After applying predicate [position() > 1] :
* node-set context pos
* nB 1
* nC 2
*
* removed the first node in the node-set, then
* the context position of the
*/
for (i = 0; i < oldset->nodeNr; i++) {
/*
* Run the evaluation with a node list made of
* a single item in the nodeset.
*/
ctxt->context->node = oldset->nodeTab[i];
if ((oldset->nodeTab[i]->type != XML_NAMESPACE_DECL) &&
(oldset->nodeTab[i]->doc != NULL))
ctxt->context->doc = oldset->nodeTab[i]->doc;
if (tmp == NULL) {
tmp = xmlXPathCacheNewNodeSet(ctxt->context,
ctxt->context->node);
} else {
if (xmlXPathNodeSetAddUnique(tmp->nodesetval,
ctxt->context->node) < 0) {
ctxt->error = XPATH_MEMORY_ERROR;
}
}
valuePush(ctxt, tmp);
ctxt->context->contextSize = oldset->nodeNr;
ctxt->context->proximityPosition = i + 1;
/*
* Evaluate the predicate against the context node.
* Can/should we optimize position() predicates
* here (e.g. "[1]")?
*/
if (op->ch2 != -1)
total +=
xmlXPathCompOpEval(ctxt,
&comp->steps[op->ch2]);
if (ctxt->error != XPATH_EXPRESSION_OK) {
xmlXPathFreeNodeSet(newset);
xmlXPathFreeObject(obj);
return(0);
}
/*
* The result of the evaluation needs to be tested to
* decide whether the filter succeeded or not
*/
/*
* OPTIMIZE TODO: Can we use
* xmlXPathNodeSetAdd*Unique()* instead?
*/
res = valuePop(ctxt);
if (xmlXPathEvaluatePredicateResult(ctxt, res)) {
if (xmlXPathNodeSetAdd(newset, oldset->nodeTab[i])
< 0)
ctxt->error = XPATH_MEMORY_ERROR;
}
/*
* Cleanup
*/
if (res != NULL) {
xmlXPathReleaseObject(ctxt->context, res);
}
if (ctxt->value == tmp) {
valuePop(ctxt);
xmlXPathNodeSetClear(tmp->nodesetval, 1);
/*
* Don't free the temporary nodeset
* in order to avoid massive recreation inside this
* loop.
*/
} else
tmp = NULL;
ctxt->context->node = NULL;
}
if (tmp != NULL)
xmlXPathReleaseObject(ctxt->context, tmp);
/*
* The result is used as the new evaluation set.
*/
xmlXPathReleaseObject(ctxt->context, obj);
ctxt->context->node = NULL;
ctxt->context->contextSize = -1;
ctxt->context->proximityPosition = -1;
/* may want to move this past the '}' later */
ctxt->context->doc = oldDoc;
valuePush(ctxt,
xmlXPathCacheWrapNodeSet(ctxt->context, newset));
}
ctxt->context->node = oldnode;
return (total);
}
case XPATH_OP_SORT:
if (op->ch1 != -1)
total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]);
CHECK_ERROR0;
if ((ctxt->value != NULL) &&
(ctxt->value->type == XPATH_NODESET) &&
(ctxt->value->nodesetval != NULL) &&
(ctxt->value->nodesetval->nodeNr > 1))
{
xmlXPathNodeSetSort(ctxt->value->nodesetval);
}
return (total);
#ifdef LIBXML_XPTR_ENABLED
case XPATH_OP_RANGETO:{
xmlXPathObjectPtr range;
xmlXPathObjectPtr res, obj;
xmlXPathObjectPtr tmp;
xmlLocationSetPtr newlocset = NULL;
xmlLocationSetPtr oldlocset;
xmlNodeSetPtr oldset;
int i, j;
if (op->ch1 != -1)
total +=
xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]);
if (op->ch2 == -1)
return (total);
if (ctxt->value->type == XPATH_LOCATIONSET) {
/*
* Extract the old locset, and then evaluate the result of the
* expression for all the element in the locset. use it to grow
* up a new locset.
*/
CHECK_TYPE0(XPATH_LOCATIONSET);
obj = valuePop(ctxt);
oldlocset = obj->user;
if ((oldlocset == NULL) || (oldlocset->locNr == 0)) {
ctxt->context->node = NULL;
ctxt->context->contextSize = 0;
ctxt->context->proximityPosition = 0;
total += xmlXPathCompOpEval(ctxt,&comp->steps[op->ch2]);
res = valuePop(ctxt);
if (res != NULL) {
xmlXPathReleaseObject(ctxt->context, res);
}
valuePush(ctxt, obj);
CHECK_ERROR0;
return (total);
}
newlocset = xmlXPtrLocationSetCreate(NULL);
for (i = 0; i < oldlocset->locNr; i++) {
/*
* Run the evaluation with a node list made of a
* single item in the nodelocset.
*/
ctxt->context->node = oldlocset->locTab[i]->user;
ctxt->context->contextSize = oldlocset->locNr;
ctxt->context->proximityPosition = i + 1;
tmp = xmlXPathCacheNewNodeSet(ctxt->context,
ctxt->context->node);
valuePush(ctxt, tmp);
if (op->ch2 != -1)
total +=
xmlXPathCompOpEval(ctxt,
&comp->steps[op->ch2]);
if (ctxt->error != XPATH_EXPRESSION_OK) {
xmlXPathFreeObject(obj);
return(0);
}
res = valuePop(ctxt);
if (res->type == XPATH_LOCATIONSET) {
xmlLocationSetPtr rloc =
(xmlLocationSetPtr)res->user;
for (j=0; j<rloc->locNr; j++) {
range = xmlXPtrNewRange(
oldlocset->locTab[i]->user,
oldlocset->locTab[i]->index,
rloc->locTab[j]->user2,
rloc->locTab[j]->index2);
if (range != NULL) {
xmlXPtrLocationSetAdd(newlocset, range);
}
}
} else {
range = xmlXPtrNewRangeNodeObject(
(xmlNodePtr)oldlocset->locTab[i]->user, res);
if (range != NULL) {
xmlXPtrLocationSetAdd(newlocset,range);
}
}
/*
* Cleanup
*/
if (res != NULL) {
xmlXPathReleaseObject(ctxt->context, res);
}
if (ctxt->value == tmp) {
res = valuePop(ctxt);
xmlXPathReleaseObject(ctxt->context, res);
}
ctxt->context->node = NULL;
}
} else { /* Not a location set */
CHECK_TYPE0(XPATH_NODESET);
obj = valuePop(ctxt);
oldset = obj->nodesetval;
ctxt->context->node = NULL;
newlocset = xmlXPtrLocationSetCreate(NULL);
if (oldset != NULL) {
for (i = 0; i < oldset->nodeNr; i++) {
/*
* Run the evaluation with a node list made of a single item
* in the nodeset.
*/
ctxt->context->node = oldset->nodeTab[i];
/*
* OPTIMIZE TODO: Avoid recreation for every iteration.
*/
tmp = xmlXPathCacheNewNodeSet(ctxt->context,
ctxt->context->node);
valuePush(ctxt, tmp);
if (op->ch2 != -1)
total +=
xmlXPathCompOpEval(ctxt,
&comp->steps[op->ch2]);
if (ctxt->error != XPATH_EXPRESSION_OK) {
xmlXPathFreeObject(obj);
return(0);
}
res = valuePop(ctxt);
range =
xmlXPtrNewRangeNodeObject(oldset->nodeTab[i],
res);
if (range != NULL) {
xmlXPtrLocationSetAdd(newlocset, range);
}
/*
* Cleanup
*/
if (res != NULL) {
xmlXPathReleaseObject(ctxt->context, res);
}
if (ctxt->value == tmp) {
res = valuePop(ctxt);
xmlXPathReleaseObject(ctxt->context, res);
}
ctxt->context->node = NULL;
}
}
}
/*
* The result is used as the new evaluation set.
*/
xmlXPathReleaseObject(ctxt->context, obj);
ctxt->context->node = NULL;
ctxt->context->contextSize = -1;
ctxt->context->proximityPosition = -1;
valuePush(ctxt, xmlXPtrWrapLocationSet(newlocset));
return (total);
}
#endif /* LIBXML_XPTR_ENABLED */
}
xmlGenericError(xmlGenericErrorContext,
"XPath: unknown precompiled operation %d\n", op->op);
ctxt->error = XPATH_INVALID_OPERAND;
| null | null | 208,741
|
90052071217259512981949438005234061143
| 878
|
Handling of XPath function arguments in error case
The XPath engine tries to guarantee that every XPath function can pop
'nargs' non-NULL values off the stack. libxslt, for example, relies on
this assumption. But the check isn't thorough enough if there are errors
during the evaluation of arguments. This can lead to segfaults:
https://mail.gnome.org/archives/xslt/2013-December/msg00005.html
This commit makes the handling of function arguments more robust.
* Bail out early when evaluation of XPath function arguments fails.
* Make sure that there are 'nargs' arguments in the current call frame.
|
other
|
gnupg
|
b0b3803e8c2959dd67ca96debc54b5c6464f0d41
| 1
|
cmd_readkey (assuan_context_t ctx, char *line)
{
ctrl_t ctrl = assuan_get_pointer (ctx);
int rc;
unsigned char *cert = NULL;
size_t ncert, n;
ksba_cert_t kc = NULL;
ksba_sexp_t p;
unsigned char *pk;
size_t pklen;
if ((rc = open_card (ctrl, NULL)))
return rc;
line = xstrdup (line); /* Need a copy of the line. */
/* If the application supports the READKEY function we use that.
Otherwise we use the old way by extracting it from the
certificate. */
rc = app_readkey (ctrl->app_ctx, line, &pk, &pklen);
if (!rc)
{ /* Yeah, got that key - send it back. */
rc = assuan_send_data (ctx, pk, pklen);
xfree (pk);
xfree (line);
line = NULL;
goto leave;
}
if (gpg_err_code (rc) != GPG_ERR_UNSUPPORTED_OPERATION)
log_error ("app_readkey failed: %s\n", gpg_strerror (rc));
else
{
rc = app_readcert (ctrl->app_ctx, line, &cert, &ncert);
if (rc)
log_error ("app_readcert failed: %s\n", gpg_strerror (rc));
}
xfree (line);
line = NULL;
if (rc)
goto leave;
rc = ksba_cert_new (&kc);
if (rc)
{
xfree (cert);
goto leave;
}
rc = ksba_cert_init_from_mem (kc, cert, ncert);
if (rc)
{
log_error ("failed to parse the certificate: %s\n", gpg_strerror (rc));
goto leave;
}
p = ksba_cert_get_public_key (kc);
if (!p)
{
rc = gpg_error (GPG_ERR_NO_PUBKEY);
goto leave;
}
n = gcry_sexp_canon_len (p, 0, NULL, NULL);
rc = assuan_send_data (ctx, p, n);
xfree (p);
leave:
ksba_cert_release (kc);
xfree (cert);
TEST_CARD_REMOVAL (ctrl, rc);
return rc;
}
| null | null | 208,760
|
317911316520292420537394099555416973180
| 72
|
scd: Avoid double-free on error condition in scd
* scd/command.c (cmd_readkey): avoid double-free of cert
--
When ksba_cert_new() fails, cert will be double-freed.
Debian-Bug-Id: 773471
Original patch changed by wk to do the free only at leave.
|
other
|
vim
|
1c3dd8ddcba63c1af5112e567215b3cec2de11d0
| 1
|
getcmdline_int(
int firstc,
long count UNUSED, // only used for incremental search
int indent, // indent for inside conditionals
int clear_ccline) // clear ccline first
{
static int depth = 0; // call depth
int c;
int i;
int j;
int gotesc = FALSE; // TRUE when <ESC> just typed
int do_abbr; // when TRUE check for abbr.
char_u *lookfor = NULL; // string to match
int hiscnt; // current history line in use
int histype; // history type to be used
#ifdef FEAT_SEARCH_EXTRA
incsearch_state_T is_state;
#endif
int did_wild_list = FALSE; // did wild_list() recently
int wim_index = 0; // index in wim_flags[]
int res;
int save_msg_scroll = msg_scroll;
int save_State = State; // remember State when called
int some_key_typed = FALSE; // one of the keys was typed
// mouse drag and release events are ignored, unless they are
// preceded with a mouse down event
int ignore_drag_release = TRUE;
#ifdef FEAT_EVAL
int break_ctrl_c = FALSE;
#endif
expand_T xpc;
long *b_im_ptr = NULL;
cmdline_info_T save_ccline;
int did_save_ccline = FALSE;
int cmdline_type;
int wild_type;
// one recursion level deeper
++depth;
if (ccline.cmdbuff != NULL)
{
// Being called recursively. Since ccline is global, we need to save
// the current buffer and restore it when returning.
save_cmdline(&save_ccline);
did_save_ccline = TRUE;
}
if (clear_ccline)
CLEAR_FIELD(ccline);
#ifdef FEAT_EVAL
if (firstc == -1)
{
firstc = NUL;
break_ctrl_c = TRUE;
}
#endif
#ifdef FEAT_RIGHTLEFT
// start without Hebrew mapping for a command line
if (firstc == ':' || firstc == '=' || firstc == '>')
cmd_hkmap = 0;
#endif
#ifdef FEAT_SEARCH_EXTRA
init_incsearch_state(&is_state);
#endif
if (init_ccline(firstc, indent) != OK)
goto theend; // out of memory
if (depth == 50)
{
// Somehow got into a loop recursively calling getcmdline(), bail out.
emsg(_(e_command_too_recursive));
goto theend;
}
ExpandInit(&xpc);
ccline.xpc = &xpc;
#ifdef FEAT_RIGHTLEFT
if (curwin->w_p_rl && *curwin->w_p_rlc == 's'
&& (firstc == '/' || firstc == '?'))
cmdmsg_rl = TRUE;
else
cmdmsg_rl = FALSE;
#endif
redir_off = TRUE; // don't redirect the typed command
if (!cmd_silent)
{
i = msg_scrolled;
msg_scrolled = 0; // avoid wait_return() message
gotocmdline(TRUE);
msg_scrolled += i;
redrawcmdprompt(); // draw prompt or indent
set_cmdspos();
}
xpc.xp_context = EXPAND_NOTHING;
xpc.xp_backslash = XP_BS_NONE;
#ifndef BACKSLASH_IN_FILENAME
xpc.xp_shell = FALSE;
#endif
#if defined(FEAT_EVAL)
if (ccline.input_fn)
{
xpc.xp_context = ccline.xp_context;
xpc.xp_pattern = ccline.cmdbuff;
xpc.xp_arg = ccline.xp_arg;
}
#endif
/*
* Avoid scrolling when called by a recursive do_cmdline(), e.g. when
* doing ":@0" when register 0 doesn't contain a CR.
*/
msg_scroll = FALSE;
State = MODE_CMDLINE;
if (firstc == '/' || firstc == '?' || firstc == '@')
{
// Use ":lmap" mappings for search pattern and input().
if (curbuf->b_p_imsearch == B_IMODE_USE_INSERT)
b_im_ptr = &curbuf->b_p_iminsert;
else
b_im_ptr = &curbuf->b_p_imsearch;
if (*b_im_ptr == B_IMODE_LMAP)
State |= MODE_LANGMAP;
#ifdef HAVE_INPUT_METHOD
im_set_active(*b_im_ptr == B_IMODE_IM);
#endif
}
#ifdef HAVE_INPUT_METHOD
else if (p_imcmdline)
im_set_active(TRUE);
#endif
setmouse();
#ifdef CURSOR_SHAPE
ui_cursor_shape(); // may show different cursor shape
#endif
// When inside an autocommand for writing "exiting" may be set and
// terminal mode set to cooked. Need to set raw mode here then.
settmode(TMODE_RAW);
// Trigger CmdlineEnter autocommands.
cmdline_type = firstc == NUL ? '-' : firstc;
trigger_cmd_autocmd(cmdline_type, EVENT_CMDLINEENTER);
#ifdef FEAT_EVAL
if (!debug_mode)
may_trigger_modechanged();
#endif
init_history();
hiscnt = get_hislen(); // set hiscnt to impossible history value
histype = hist_char2type(firstc);
#ifdef FEAT_DIGRAPHS
do_digraph(-1); // init digraph typeahead
#endif
// If something above caused an error, reset the flags, we do want to type
// and execute commands. Display may be messed up a bit.
if (did_emsg)
redrawcmd();
#ifdef FEAT_STL_OPT
// Redraw the statusline in case it uses the current mode using the mode()
// function.
if (!cmd_silent && msg_scrolled == 0)
{
int found_one = FALSE;
win_T *wp;
FOR_ALL_WINDOWS(wp)
if (*p_stl != NUL || *wp->w_p_stl != NUL)
{
wp->w_redr_status = TRUE;
found_one = TRUE;
}
if (*p_tal != NUL)
{
redraw_tabline = TRUE;
found_one = TRUE;
}
if (found_one)
redraw_statuslines();
}
#endif
did_emsg = FALSE;
got_int = FALSE;
/*
* Collect the command string, handling editing keys.
*/
for (;;)
{
int trigger_cmdlinechanged = TRUE;
int end_wildmenu;
redir_off = TRUE; // Don't redirect the typed command.
// Repeated, because a ":redir" inside
// completion may switch it on.
#ifdef USE_ON_FLY_SCROLL
dont_scroll = FALSE; // allow scrolling here
#endif
quit_more = FALSE; // reset after CTRL-D which had a more-prompt
did_emsg = FALSE; // There can't really be a reason why an error
// that occurs while typing a command should
// cause the command not to be executed.
// Trigger SafeState if nothing is pending.
may_trigger_safestate(xpc.xp_numfiles <= 0);
// Get a character. Ignore K_IGNORE and K_NOP, they should not do
// anything, such as stop completion.
do
{
cursorcmd(); // set the cursor on the right spot
c = safe_vgetc();
} while (c == K_IGNORE || c == K_NOP);
if (c == K_COMMAND || c == K_SCRIPT_COMMAND)
{
int clen = ccline.cmdlen;
if (do_cmdkey_command(c, DOCMD_NOWAIT) == OK)
{
if (clen == ccline.cmdlen)
trigger_cmdlinechanged = FALSE;
goto cmdline_changed;
}
}
if (KeyTyped)
{
some_key_typed = TRUE;
#ifdef FEAT_RIGHTLEFT
if (cmd_hkmap)
c = hkmap(c);
if (cmdmsg_rl && !KeyStuffed)
{
// Invert horizontal movements and operations. Only when
// typed by the user directly, not when the result of a
// mapping.
switch (c)
{
case K_RIGHT: c = K_LEFT; break;
case K_S_RIGHT: c = K_S_LEFT; break;
case K_C_RIGHT: c = K_C_LEFT; break;
case K_LEFT: c = K_RIGHT; break;
case K_S_LEFT: c = K_S_RIGHT; break;
case K_C_LEFT: c = K_C_RIGHT; break;
}
}
#endif
}
/*
* Ignore got_int when CTRL-C was typed here.
* Don't ignore it in :global, we really need to break then, e.g., for
* ":g/pat/normal /pat" (without the <CR>).
* Don't ignore it for the input() function.
*/
if ((c == Ctrl_C
#ifdef UNIX
|| c == intr_char
#endif
)
#if defined(FEAT_EVAL) || defined(FEAT_CRYPT)
&& firstc != '@'
#endif
#ifdef FEAT_EVAL
// do clear got_int in Ex mode to avoid infinite Ctrl-C loop
&& (!break_ctrl_c || exmode_active)
#endif
&& !global_busy)
got_int = FALSE;
// free old command line when finished moving around in the history
// list
if (lookfor != NULL
&& c != K_S_DOWN && c != K_S_UP
&& c != K_DOWN && c != K_UP
&& c != K_PAGEDOWN && c != K_PAGEUP
&& c != K_KPAGEDOWN && c != K_KPAGEUP
&& c != K_LEFT && c != K_RIGHT
&& (xpc.xp_numfiles > 0 || (c != Ctrl_P && c != Ctrl_N)))
VIM_CLEAR(lookfor);
/*
* When there are matching completions to select <S-Tab> works like
* CTRL-P (unless 'wc' is <S-Tab>).
*/
if (c != p_wc && c == K_S_TAB && xpc.xp_numfiles > 0)
c = Ctrl_P;
if (p_wmnu)
c = wildmenu_translate_key(&ccline, c, &xpc, did_wild_list);
if (cmdline_pum_active())
{
// Ctrl-Y: Accept the current selection and close the popup menu.
// Ctrl-E: cancel the cmdline popup menu and return the original
// text.
if (c == Ctrl_E || c == Ctrl_Y)
{
wild_type = (c == Ctrl_E) ? WILD_CANCEL : WILD_APPLY;
if (nextwild(&xpc, wild_type, WILD_NO_BEEP,
firstc != '@') == FAIL)
break;
c = Ctrl_E;
}
}
// The wildmenu is cleared if the pressed key is not used for
// navigating the wild menu (i.e. the key is not 'wildchar' or
// 'wildcharm' or Ctrl-N or Ctrl-P or Ctrl-A or Ctrl-L).
// If the popup menu is displayed, then PageDown and PageUp keys are
// also used to navigate the menu.
end_wildmenu = (!(c == p_wc && KeyTyped) && c != p_wcm
&& c != Ctrl_N && c != Ctrl_P && c != Ctrl_A && c != Ctrl_L);
end_wildmenu = end_wildmenu && (!cmdline_pum_active() ||
(c != K_PAGEDOWN && c != K_PAGEUP
&& c != K_KPAGEDOWN && c != K_KPAGEUP));
// free expanded names when finished walking through matches
if (end_wildmenu)
{
if (cmdline_pum_active())
cmdline_pum_remove();
if (xpc.xp_numfiles != -1)
(void)ExpandOne(&xpc, NULL, NULL, 0, WILD_FREE);
did_wild_list = FALSE;
if (!p_wmnu || (c != K_UP && c != K_DOWN))
xpc.xp_context = EXPAND_NOTHING;
wim_index = 0;
wildmenu_cleanup(&ccline);
}
if (p_wmnu)
c = wildmenu_process_key(&ccline, c, &xpc);
// CTRL-\ CTRL-N goes to Normal mode, CTRL-\ CTRL-G goes to Insert
// mode when 'insertmode' is set, CTRL-\ e prompts for an expression.
if (c == Ctrl_BSL)
{
res = cmdline_handle_backslash_key(c, &gotesc);
if (res == CMDLINE_CHANGED)
goto cmdline_changed;
else if (res == CMDLINE_NOT_CHANGED)
goto cmdline_not_changed;
else if (res == GOTO_NORMAL_MODE)
goto returncmd; // back to cmd mode
c = Ctrl_BSL; // backslash key not processed by
// cmdline_handle_backslash_key()
}
#ifdef FEAT_CMDWIN
if (c == cedit_key || c == K_CMDWIN)
{
// TODO: why is ex_normal_busy checked here?
if ((c == K_CMDWIN || ex_normal_busy == 0) && got_int == FALSE)
{
/*
* Open a window to edit the command line (and history).
*/
c = open_cmdwin();
some_key_typed = TRUE;
}
}
# ifdef FEAT_DIGRAPHS
else
# endif
#endif
#ifdef FEAT_DIGRAPHS
c = do_digraph(c);
#endif
if (c == '\n' || c == '\r' || c == K_KENTER || (c == ESC
&& (!KeyTyped || vim_strchr(p_cpo, CPO_ESC) != NULL)))
{
// In Ex mode a backslash escapes a newline.
if (exmode_active
&& c != ESC
&& ccline.cmdpos == ccline.cmdlen
&& ccline.cmdpos > 0
&& ccline.cmdbuff[ccline.cmdpos - 1] == '\\')
{
if (c == K_KENTER)
c = '\n';
}
else
{
gotesc = FALSE; // Might have typed ESC previously, don't
// truncate the cmdline now.
if (ccheck_abbr(c + ABBR_OFF))
goto cmdline_changed;
if (!cmd_silent)
{
windgoto(msg_row, 0);
out_flush();
}
break;
}
}
// Completion for 'wildchar' or 'wildcharm' key.
if ((c == p_wc && !gotesc && KeyTyped) || c == p_wcm)
{
res = cmdline_wildchar_complete(c, firstc != '@', &did_wild_list,
&wim_index, &xpc, &gotesc);
if (res == CMDLINE_CHANGED)
goto cmdline_changed;
}
gotesc = FALSE;
// <S-Tab> goes to last match, in a clumsy way
if (c == K_S_TAB && KeyTyped)
{
if (nextwild(&xpc, WILD_EXPAND_KEEP, 0, firstc != '@') == OK)
{
if (xpc.xp_numfiles > 1
&& ((!did_wild_list && (wim_flags[wim_index] & WIM_LIST))
|| p_wmnu))
{
// Trigger the popup menu when wildoptions=pum
showmatches(&xpc, p_wmnu
&& ((wim_flags[wim_index] & WIM_LIST) == 0));
}
if (nextwild(&xpc, WILD_PREV, 0, firstc != '@') == OK
&& nextwild(&xpc, WILD_PREV, 0, firstc != '@') == OK)
goto cmdline_changed;
}
}
if (c == NUL || c == K_ZERO) // NUL is stored as NL
c = NL;
do_abbr = TRUE; // default: check for abbreviation
/*
* Big switch for a typed command line character.
*/
switch (c)
{
case K_BS:
case Ctrl_H:
case K_DEL:
case K_KDEL:
case Ctrl_W:
res = cmdline_erase_chars(c, indent
#ifdef FEAT_SEARCH_EXTRA
, &is_state
#endif
);
if (res == CMDLINE_NOT_CHANGED)
goto cmdline_not_changed;
else if (res == GOTO_NORMAL_MODE)
goto returncmd; // back to cmd mode
goto cmdline_changed;
case K_INS:
case K_KINS:
ccline.overstrike = !ccline.overstrike;
#ifdef CURSOR_SHAPE
ui_cursor_shape(); // may show different cursor shape
#endif
goto cmdline_not_changed;
case Ctrl_HAT:
cmdline_toggle_langmap(b_im_ptr);
goto cmdline_not_changed;
// case '@': only in very old vi
case Ctrl_U:
// delete all characters left of the cursor
j = ccline.cmdpos;
ccline.cmdlen -= j;
i = ccline.cmdpos = 0;
while (i < ccline.cmdlen)
ccline.cmdbuff[i++] = ccline.cmdbuff[j++];
// Truncate at the end, required for multi-byte chars.
ccline.cmdbuff[ccline.cmdlen] = NUL;
#ifdef FEAT_SEARCH_EXTRA
if (ccline.cmdlen == 0)
is_state.search_start = is_state.save_cursor;
#endif
redrawcmd();
goto cmdline_changed;
#ifdef FEAT_CLIPBOARD
case Ctrl_Y:
// Copy the modeless selection, if there is one.
if (clip_star.state != SELECT_CLEARED)
{
if (clip_star.state == SELECT_DONE)
clip_copy_modeless_selection(TRUE);
goto cmdline_not_changed;
}
break;
#endif
case ESC: // get here if p_wc != ESC or when ESC typed twice
case Ctrl_C:
// In exmode it doesn't make sense to return. Except when
// ":normal" runs out of characters.
if (exmode_active
&& (ex_normal_busy == 0 || typebuf.tb_len > 0))
goto cmdline_not_changed;
gotesc = TRUE; // will free ccline.cmdbuff after
// putting it in history
goto returncmd; // back to cmd mode
case Ctrl_R: // insert register
res = cmdline_insert_reg(&gotesc);
if (res == CMDLINE_NOT_CHANGED)
goto cmdline_not_changed;
else if (res == GOTO_NORMAL_MODE)
goto returncmd;
goto cmdline_changed;
case Ctrl_D:
if (showmatches(&xpc, FALSE) == EXPAND_NOTHING)
break; // Use ^D as normal char instead
redrawcmd();
continue; // don't do incremental search now
case K_RIGHT:
case K_S_RIGHT:
case K_C_RIGHT:
do
{
if (ccline.cmdpos >= ccline.cmdlen)
break;
i = cmdline_charsize(ccline.cmdpos);
if (KeyTyped && ccline.cmdspos + i >= Columns * Rows)
break;
ccline.cmdspos += i;
if (has_mbyte)
ccline.cmdpos += (*mb_ptr2len)(ccline.cmdbuff
+ ccline.cmdpos);
else
++ccline.cmdpos;
}
while ((c == K_S_RIGHT || c == K_C_RIGHT
|| (mod_mask & (MOD_MASK_SHIFT|MOD_MASK_CTRL)))
&& ccline.cmdbuff[ccline.cmdpos] != ' ');
if (has_mbyte)
set_cmdspos_cursor();
goto cmdline_not_changed;
case K_LEFT:
case K_S_LEFT:
case K_C_LEFT:
if (ccline.cmdpos == 0)
goto cmdline_not_changed;
do
{
--ccline.cmdpos;
if (has_mbyte) // move to first byte of char
ccline.cmdpos -= (*mb_head_off)(ccline.cmdbuff,
ccline.cmdbuff + ccline.cmdpos);
ccline.cmdspos -= cmdline_charsize(ccline.cmdpos);
}
while (ccline.cmdpos > 0
&& (c == K_S_LEFT || c == K_C_LEFT
|| (mod_mask & (MOD_MASK_SHIFT|MOD_MASK_CTRL)))
&& ccline.cmdbuff[ccline.cmdpos - 1] != ' ');
if (has_mbyte)
set_cmdspos_cursor();
goto cmdline_not_changed;
case K_IGNORE:
// Ignore mouse event or open_cmdwin() result.
goto cmdline_not_changed;
#ifdef FEAT_GUI_MSWIN
// On MS-Windows ignore <M-F4>, we get it when closing the window
// was cancelled.
case K_F4:
if (mod_mask == MOD_MASK_ALT)
{
redrawcmd(); // somehow the cmdline is cleared
goto cmdline_not_changed;
}
break;
#endif
case K_MIDDLEDRAG:
case K_MIDDLERELEASE:
goto cmdline_not_changed; // Ignore mouse
case K_MIDDLEMOUSE:
# ifdef FEAT_GUI
// When GUI is active, also paste when 'mouse' is empty
if (!gui.in_use)
# endif
if (!mouse_has(MOUSE_COMMAND))
goto cmdline_not_changed; // Ignore mouse
# ifdef FEAT_CLIPBOARD
if (clip_star.available)
cmdline_paste('*', TRUE, TRUE);
else
# endif
cmdline_paste(0, TRUE, TRUE);
redrawcmd();
goto cmdline_changed;
# ifdef FEAT_DND
case K_DROP:
cmdline_paste('~', TRUE, FALSE);
redrawcmd();
goto cmdline_changed;
# endif
case K_LEFTDRAG:
case K_LEFTRELEASE:
case K_RIGHTDRAG:
case K_RIGHTRELEASE:
// Ignore drag and release events when the button-down wasn't
// seen before.
if (ignore_drag_release)
goto cmdline_not_changed;
// FALLTHROUGH
case K_LEFTMOUSE:
case K_RIGHTMOUSE:
cmdline_left_right_mouse(c, &ignore_drag_release);
goto cmdline_not_changed;
// Mouse scroll wheel: ignored here
case K_MOUSEDOWN:
case K_MOUSEUP:
case K_MOUSELEFT:
case K_MOUSERIGHT:
// Alternate buttons ignored here
case K_X1MOUSE:
case K_X1DRAG:
case K_X1RELEASE:
case K_X2MOUSE:
case K_X2DRAG:
case K_X2RELEASE:
case K_MOUSEMOVE:
goto cmdline_not_changed;
#ifdef FEAT_GUI
case K_LEFTMOUSE_NM: // mousefocus click, ignored
case K_LEFTRELEASE_NM:
goto cmdline_not_changed;
case K_VER_SCROLLBAR:
if (msg_scrolled == 0)
{
gui_do_scroll();
redrawcmd();
}
goto cmdline_not_changed;
case K_HOR_SCROLLBAR:
if (msg_scrolled == 0)
{
gui_do_horiz_scroll(scrollbar_value, FALSE);
redrawcmd();
}
goto cmdline_not_changed;
#endif
#ifdef FEAT_GUI_TABLINE
case K_TABLINE:
case K_TABMENU:
// Don't want to change any tabs here. Make sure the same tab
// is still selected.
if (gui_use_tabline())
gui_mch_set_curtab(tabpage_index(curtab));
goto cmdline_not_changed;
#endif
case K_SELECT: // end of Select mode mapping - ignore
goto cmdline_not_changed;
case Ctrl_B: // begin of command line
case K_HOME:
case K_KHOME:
case K_S_HOME:
case K_C_HOME:
ccline.cmdpos = 0;
set_cmdspos();
goto cmdline_not_changed;
case Ctrl_E: // end of command line
case K_END:
case K_KEND:
case K_S_END:
case K_C_END:
ccline.cmdpos = ccline.cmdlen;
set_cmdspos_cursor();
goto cmdline_not_changed;
case Ctrl_A: // all matches
if (cmdline_pum_active())
// As Ctrl-A completes all the matches, close the popup
// menu (if present)
cmdline_pum_cleanup(&ccline);
if (nextwild(&xpc, WILD_ALL, 0, firstc != '@') == FAIL)
break;
xpc.xp_context = EXPAND_NOTHING;
did_wild_list = FALSE;
goto cmdline_changed;
case Ctrl_L:
#ifdef FEAT_SEARCH_EXTRA
if (may_add_char_to_search(firstc, &c, &is_state) == OK)
goto cmdline_not_changed;
#endif
// completion: longest common part
if (nextwild(&xpc, WILD_LONGEST, 0, firstc != '@') == FAIL)
break;
goto cmdline_changed;
case Ctrl_N: // next match
case Ctrl_P: // previous match
if (xpc.xp_numfiles > 0)
{
wild_type = (c == Ctrl_P) ? WILD_PREV : WILD_NEXT;
if (nextwild(&xpc, wild_type, 0, firstc != '@') == FAIL)
break;
goto cmdline_not_changed;
}
// FALLTHROUGH
case K_UP:
case K_DOWN:
case K_S_UP:
case K_S_DOWN:
case K_PAGEUP:
case K_KPAGEUP:
case K_PAGEDOWN:
case K_KPAGEDOWN:
if (cmdline_pum_active()
&& (c == K_PAGEUP || c == K_PAGEDOWN ||
c == K_KPAGEUP || c == K_KPAGEDOWN))
{
// If the popup menu is displayed, then PageUp and PageDown
// are used to scroll the menu.
wild_type = WILD_PAGEUP;
if (c == K_PAGEDOWN || c == K_KPAGEDOWN)
wild_type = WILD_PAGEDOWN;
if (nextwild(&xpc, wild_type, 0, firstc != '@') == FAIL)
break;
goto cmdline_not_changed;
}
else
{
res = cmdline_browse_history(c, firstc, &lookfor, histype,
&hiscnt, &xpc);
if (res == CMDLINE_CHANGED)
goto cmdline_changed;
else if (res == GOTO_NORMAL_MODE)
goto returncmd;
}
goto cmdline_not_changed;
#ifdef FEAT_SEARCH_EXTRA
case Ctrl_G: // next match
case Ctrl_T: // previous match
if (may_adjust_incsearch_highlighting(
firstc, count, &is_state, c) == FAIL)
goto cmdline_not_changed;
break;
#endif
case Ctrl_V:
case Ctrl_Q:
{
ignore_drag_release = TRUE;
putcmdline('^', TRUE);
// Get next (two) character(s). Do not change any
// modifyOtherKeys ESC sequence to a normal key for
// CTRL-SHIFT-V.
c = get_literal(mod_mask & MOD_MASK_SHIFT);
do_abbr = FALSE; // don't do abbreviation now
extra_char = NUL;
// may need to remove ^ when composing char was typed
if (enc_utf8 && utf_iscomposing(c) && !cmd_silent)
{
draw_cmdline(ccline.cmdpos,
ccline.cmdlen - ccline.cmdpos);
msg_putchar(' ');
cursorcmd();
}
}
break;
#ifdef FEAT_DIGRAPHS
case Ctrl_K:
ignore_drag_release = TRUE;
putcmdline('?', TRUE);
# ifdef USE_ON_FLY_SCROLL
dont_scroll = TRUE; // disallow scrolling here
# endif
c = get_digraph(TRUE);
extra_char = NUL;
if (c != NUL)
break;
redrawcmd();
goto cmdline_not_changed;
#endif // FEAT_DIGRAPHS
#ifdef FEAT_RIGHTLEFT
case Ctrl__: // CTRL-_: switch language mode
if (!p_ari)
break;
cmd_hkmap = !cmd_hkmap;
goto cmdline_not_changed;
#endif
case K_PS:
bracketed_paste(PASTE_CMDLINE, FALSE, NULL);
goto cmdline_changed;
default:
#ifdef UNIX
if (c == intr_char)
{
gotesc = TRUE; // will free ccline.cmdbuff after
// putting it in history
goto returncmd; // back to Normal mode
}
#endif
/*
* Normal character with no special meaning. Just set mod_mask
* to 0x0 so that typing Shift-Space in the GUI doesn't enter
* the string <S-Space>. This should only happen after ^V.
*/
if (!IS_SPECIAL(c))
mod_mask = 0x0;
break;
}
/*
* End of switch on command line character.
* We come here if we have a normal character.
*/
if (do_abbr && (IS_SPECIAL(c) || !vim_iswordc(c))
&& (ccheck_abbr(
// Add ABBR_OFF for characters above 0x100, this is
// what check_abbr() expects.
(has_mbyte && c >= 0x100) ? (c + ABBR_OFF) : c)
|| c == Ctrl_RSB))
goto cmdline_changed;
/*
* put the character in the command line
*/
if (IS_SPECIAL(c) || mod_mask != 0)
put_on_cmdline(get_special_key_name(c, mod_mask), -1, TRUE);
else
{
if (has_mbyte)
{
j = (*mb_char2bytes)(c, IObuff);
IObuff[j] = NUL; // exclude composing chars
put_on_cmdline(IObuff, j, TRUE);
}
else
{
IObuff[0] = c;
put_on_cmdline(IObuff, 1, TRUE);
}
}
goto cmdline_changed;
/*
* This part implements incremental searches for "/" and "?"
* Jump to cmdline_not_changed when a character has been read but the command
* line did not change. Then we only search and redraw if something changed in
* the past.
* Jump to cmdline_changed when the command line did change.
* (Sorry for the goto's, I know it is ugly).
*/
cmdline_not_changed:
#ifdef FEAT_SEARCH_EXTRA
if (!is_state.incsearch_postponed)
continue;
#endif
cmdline_changed:
#ifdef FEAT_SEARCH_EXTRA
// If the window changed incremental search state is not valid.
if (is_state.winid != curwin->w_id)
init_incsearch_state(&is_state);
#endif
if (trigger_cmdlinechanged)
// Trigger CmdlineChanged autocommands.
trigger_cmd_autocmd(cmdline_type, EVENT_CMDLINECHANGED);
#ifdef FEAT_SEARCH_EXTRA
if (xpc.xp_context == EXPAND_NOTHING && (KeyTyped || vpeekc() == NUL))
may_do_incsearch_highlighting(firstc, count, &is_state);
#endif
#ifdef FEAT_RIGHTLEFT
if (cmdmsg_rl
# ifdef FEAT_ARABIC
|| (p_arshape && !p_tbidi
&& cmdline_has_arabic(0, ccline.cmdlen))
# endif
)
// Always redraw the whole command line to fix shaping and
// right-left typing. Not efficient, but it works.
// Do it only when there are no characters left to read
// to avoid useless intermediate redraws.
if (vpeekc() == NUL)
redrawcmd();
#endif
}
returncmd:
#ifdef FEAT_RIGHTLEFT
cmdmsg_rl = FALSE;
#endif
ExpandCleanup(&xpc);
ccline.xpc = NULL;
#ifdef FEAT_SEARCH_EXTRA
finish_incsearch_highlighting(gotesc, &is_state, FALSE);
#endif
if (ccline.cmdbuff != NULL)
{
/*
* Put line in history buffer (":" and "=" only when it was typed).
*/
if (ccline.cmdlen && firstc != NUL
&& (some_key_typed || histype == HIST_SEARCH))
{
add_to_history(histype, ccline.cmdbuff, TRUE,
histype == HIST_SEARCH ? firstc : NUL);
if (firstc == ':')
{
vim_free(new_last_cmdline);
new_last_cmdline = vim_strsave(ccline.cmdbuff);
}
}
if (gotesc)
abandon_cmdline();
}
/*
* If the screen was shifted up, redraw the whole screen (later).
* If the line is too long, clear it, so ruler and shown command do
* not get printed in the middle of it.
*/
msg_check();
msg_scroll = save_msg_scroll;
redir_off = FALSE;
// When the command line was typed, no need for a wait-return prompt.
if (some_key_typed)
need_wait_return = FALSE;
// Trigger CmdlineLeave autocommands.
trigger_cmd_autocmd(cmdline_type, EVENT_CMDLINELEAVE);
State = save_State;
#ifdef FEAT_EVAL
if (!debug_mode)
may_trigger_modechanged();
#endif
#ifdef HAVE_INPUT_METHOD
if (b_im_ptr != NULL && *b_im_ptr != B_IMODE_LMAP)
im_save_status(b_im_ptr);
im_set_active(FALSE);
#endif
setmouse();
#ifdef CURSOR_SHAPE
ui_cursor_shape(); // may show different cursor shape
#endif
sb_text_end_cmdline();
theend:
{
char_u *p = ccline.cmdbuff;
--depth;
if (did_save_ccline)
restore_cmdline(&save_ccline);
else
ccline.cmdbuff = NULL;
return p;
}
}
| null | null | 208,912
|
4331970736416170867022307973835499272
| 1,011
|
patch 9.0.0490: using freed memory with cmdwin and BufEnter autocmd
Problem: Using freed memory with cmdwin and BufEnter autocmd.
Solution: Make sure pointer to b_p_iminsert is still valid.
|
other
|
jasper
|
c54113d6fa49f8f26d1572e972b806276c5b05d5
| 1
|
jas_image_t *jp2_decode(jas_stream_t *in, char *optstr)
{
jp2_box_t *box;
int found;
jas_image_t *image;
jp2_dec_t *dec;
bool samedtype;
int dtype;
unsigned int i;
jp2_cmap_t *cmapd;
jp2_pclr_t *pclrd;
jp2_cdef_t *cdefd;
unsigned int channo;
int newcmptno;
int_fast32_t *lutents;
#if 0
jp2_cdefchan_t *cdefent;
int cmptno;
#endif
jp2_cmapent_t *cmapent;
jas_icchdr_t icchdr;
jas_iccprof_t *iccprof;
dec = 0;
box = 0;
image = 0;
if (!(dec = jp2_dec_create())) {
goto error;
}
/* Get the first box. This should be a JP box. */
if (!(box = jp2_box_get(in))) {
jas_eprintf("error: cannot get box\n");
goto error;
}
if (box->type != JP2_BOX_JP) {
jas_eprintf("error: expecting signature box\n");
goto error;
}
if (box->data.jp.magic != JP2_JP_MAGIC) {
jas_eprintf("incorrect magic number\n");
goto error;
}
jp2_box_destroy(box);
box = 0;
/* Get the second box. This should be a FTYP box. */
if (!(box = jp2_box_get(in))) {
goto error;
}
if (box->type != JP2_BOX_FTYP) {
jas_eprintf("expecting file type box\n");
goto error;
}
jp2_box_destroy(box);
box = 0;
/* Get more boxes... */
found = 0;
while ((box = jp2_box_get(in))) {
if (jas_getdbglevel() >= 1) {
jas_eprintf("box type %s\n", box->info->name);
}
switch (box->type) {
case JP2_BOX_JP2C:
found = 1;
break;
case JP2_BOX_IHDR:
if (!dec->ihdr) {
dec->ihdr = box;
box = 0;
}
break;
case JP2_BOX_BPCC:
if (!dec->bpcc) {
dec->bpcc = box;
box = 0;
}
break;
case JP2_BOX_CDEF:
if (!dec->cdef) {
dec->cdef = box;
box = 0;
}
break;
case JP2_BOX_PCLR:
if (!dec->pclr) {
dec->pclr = box;
box = 0;
}
break;
case JP2_BOX_CMAP:
if (!dec->cmap) {
dec->cmap = box;
box = 0;
}
break;
case JP2_BOX_COLR:
if (!dec->colr) {
dec->colr = box;
box = 0;
}
break;
}
if (box) {
jp2_box_destroy(box);
box = 0;
}
if (found) {
break;
}
}
if (!found) {
jas_eprintf("error: no code stream found\n");
goto error;
}
if (!(dec->image = jpc_decode(in, optstr))) {
jas_eprintf("error: cannot decode code stream\n");
goto error;
}
/* An IHDR box must be present. */
if (!dec->ihdr) {
jas_eprintf("error: missing IHDR box\n");
goto error;
}
/* Does the number of components indicated in the IHDR box match
the value specified in the code stream? */
if (dec->ihdr->data.ihdr.numcmpts != JAS_CAST(uint, jas_image_numcmpts(dec->image))) {
jas_eprintf("warning: number of components mismatch\n");
}
/* At least one component must be present. */
if (!jas_image_numcmpts(dec->image)) {
jas_eprintf("error: no components\n");
goto error;
}
/* Determine if all components have the same data type. */
samedtype = true;
dtype = jas_image_cmptdtype(dec->image, 0);
for (i = 1; i < JAS_CAST(uint, jas_image_numcmpts(dec->image)); ++i) {
if (jas_image_cmptdtype(dec->image, i) != dtype) {
samedtype = false;
break;
}
}
/* Is the component data type indicated in the IHDR box consistent
with the data in the code stream? */
if ((samedtype && dec->ihdr->data.ihdr.bpc != JP2_DTYPETOBPC(dtype)) ||
(!samedtype && dec->ihdr->data.ihdr.bpc != JP2_IHDR_BPCNULL)) {
jas_eprintf("warning: component data type mismatch\n");
}
/* Is the compression type supported? */
if (dec->ihdr->data.ihdr.comptype != JP2_IHDR_COMPTYPE) {
jas_eprintf("error: unsupported compression type\n");
goto error;
}
if (dec->bpcc) {
/* Is the number of components indicated in the BPCC box
consistent with the code stream data? */
if (dec->bpcc->data.bpcc.numcmpts != JAS_CAST(uint, jas_image_numcmpts(
dec->image))) {
jas_eprintf("warning: number of components mismatch\n");
}
/* Is the component data type information indicated in the BPCC
box consistent with the code stream data? */
if (!samedtype) {
for (i = 0; i < JAS_CAST(uint, jas_image_numcmpts(dec->image)); ++i) {
if (jas_image_cmptdtype(dec->image, i) != JP2_BPCTODTYPE(dec->bpcc->data.bpcc.bpcs[i])) {
jas_eprintf("warning: component data type mismatch\n");
}
}
} else {
jas_eprintf("warning: superfluous BPCC box\n");
}
}
/* A COLR box must be present. */
if (!dec->colr) {
jas_eprintf("error: no COLR box\n");
goto error;
}
switch (dec->colr->data.colr.method) {
case JP2_COLR_ENUM:
jas_image_setclrspc(dec->image, jp2_getcs(&dec->colr->data.colr));
break;
case JP2_COLR_ICC:
iccprof = jas_iccprof_createfrombuf(dec->colr->data.colr.iccp,
dec->colr->data.colr.iccplen);
assert(iccprof);
jas_iccprof_gethdr(iccprof, &icchdr);
jas_eprintf("ICC Profile CS %08x\n", icchdr.colorspc);
jas_image_setclrspc(dec->image, fromiccpcs(icchdr.colorspc));
dec->image->cmprof_ = jas_cmprof_createfromiccprof(iccprof);
assert(dec->image->cmprof_);
jas_iccprof_destroy(iccprof);
break;
}
/* If a CMAP box is present, a PCLR box must also be present. */
if (dec->cmap && !dec->pclr) {
jas_eprintf("warning: missing PCLR box or superfluous CMAP box\n");
jp2_box_destroy(dec->cmap);
dec->cmap = 0;
}
/* If a CMAP box is not present, a PCLR box must not be present. */
if (!dec->cmap && dec->pclr) {
jas_eprintf("warning: missing CMAP box or superfluous PCLR box\n");
jp2_box_destroy(dec->pclr);
dec->pclr = 0;
}
/* Determine the number of channels (which is essentially the number
of components after any palette mappings have been applied). */
dec->numchans = dec->cmap ? dec->cmap->data.cmap.numchans : JAS_CAST(uint, jas_image_numcmpts(dec->image));
/* Perform a basic sanity check on the CMAP box if present. */
if (dec->cmap) {
for (i = 0; i < dec->numchans; ++i) {
/* Is the component number reasonable? */
if (dec->cmap->data.cmap.ents[i].cmptno >= JAS_CAST(uint, jas_image_numcmpts(dec->image))) {
jas_eprintf("error: invalid component number in CMAP box\n");
goto error;
}
/* Is the LUT index reasonable? */
if (dec->cmap->data.cmap.ents[i].pcol >= dec->pclr->data.pclr.numchans) {
jas_eprintf("error: invalid CMAP LUT index\n");
goto error;
}
}
}
/* Allocate space for the channel-number to component-number LUT. */
if (!(dec->chantocmptlut = jas_malloc(dec->numchans * sizeof(uint_fast16_t)))) {
jas_eprintf("error: no memory\n");
goto error;
}
if (!dec->cmap) {
for (i = 0; i < dec->numchans; ++i) {
dec->chantocmptlut[i] = i;
}
} else {
cmapd = &dec->cmap->data.cmap;
pclrd = &dec->pclr->data.pclr;
cdefd = &dec->cdef->data.cdef;
for (channo = 0; channo < cmapd->numchans; ++channo) {
cmapent = &cmapd->ents[channo];
if (cmapent->map == JP2_CMAP_DIRECT) {
dec->chantocmptlut[channo] = channo;
} else if (cmapent->map == JP2_CMAP_PALETTE) {
lutents = jas_malloc(pclrd->numlutents * sizeof(int_fast32_t));
for (i = 0; i < pclrd->numlutents; ++i) {
lutents[i] = pclrd->lutdata[cmapent->pcol + i * pclrd->numchans];
}
newcmptno = jas_image_numcmpts(dec->image);
jas_image_depalettize(dec->image, cmapent->cmptno, pclrd->numlutents, lutents, JP2_BPCTODTYPE(pclrd->bpc[cmapent->pcol]), newcmptno);
dec->chantocmptlut[channo] = newcmptno;
jas_free(lutents);
#if 0
if (dec->cdef) {
cdefent = jp2_cdef_lookup(cdefd, channo);
if (!cdefent) {
abort();
}
jas_image_setcmpttype(dec->image, newcmptno, jp2_getct(jas_image_clrspc(dec->image), cdefent->type, cdefent->assoc));
} else {
jas_image_setcmpttype(dec->image, newcmptno, jp2_getct(jas_image_clrspc(dec->image), 0, channo + 1));
}
#endif
}
}
}
/* Mark all components as being of unknown type. */
for (i = 0; i < JAS_CAST(uint, jas_image_numcmpts(dec->image)); ++i) {
jas_image_setcmpttype(dec->image, i, JAS_IMAGE_CT_UNKNOWN);
}
/* Determine the type of each component. */
if (dec->cdef) {
for (i = 0; i < dec->numchans; ++i) {
jas_image_setcmpttype(dec->image,
dec->chantocmptlut[dec->cdef->data.cdef.ents[i].channo],
jp2_getct(jas_image_clrspc(dec->image),
dec->cdef->data.cdef.ents[i].type, dec->cdef->data.cdef.ents[i].assoc));
}
} else {
for (i = 0; i < dec->numchans; ++i) {
jas_image_setcmpttype(dec->image, dec->chantocmptlut[i],
jp2_getct(jas_image_clrspc(dec->image), 0, i + 1));
}
}
/* Delete any components that are not of interest. */
for (i = jas_image_numcmpts(dec->image); i > 0; --i) {
if (jas_image_cmpttype(dec->image, i - 1) == JAS_IMAGE_CT_UNKNOWN) {
jas_image_delcmpt(dec->image, i - 1);
}
}
/* Ensure that some components survived. */
if (!jas_image_numcmpts(dec->image)) {
jas_eprintf("error: no components\n");
goto error;
}
#if 0
jas_eprintf("no of components is %d\n", jas_image_numcmpts(dec->image));
#endif
/* Prevent the image from being destroyed later. */
image = dec->image;
dec->image = 0;
jp2_dec_destroy(dec);
return image;
error:
if (box) {
jp2_box_destroy(box);
}
if (dec) {
jp2_dec_destroy(dec);
}
return 0;
}
| null | null | 208,983
|
202294942807550333016367317921252998953
| 338
|
CVE-2014-8138
|
other
|
MilkyTracker
|
7afd55c42ad80d01a339197a2d8b5461d214edaf
| 1
|
PlayerGeneric::~PlayerGeneric()
{
if (mixer)
delete mixer;
if (player)
{
if (mixer->isActive() && !mixer->isDeviceRemoved(player))
mixer->removeDevice(player);
delete player;
}
delete[] audioDriverName;
delete listener;
}
| null | null | 208,987
|
92094026136705352235035243298769766413
| 16
|
Fix use-after-free in PlayerGeneric destructor
|
other
|
libvirt
|
4c4d0e2da07b5a035b26a0ff13ec27070f7c7b1a
| 1
|
virNodeDeviceGetMdevTypesCaps(const char *sysfspath,
virMediatedDeviceTypePtr **mdev_types,
size_t *nmdev_types)
{
virMediatedDeviceTypePtr *types = NULL;
size_t ntypes = 0;
size_t i;
/* this could be a refresh, so clear out the old data */
for (i = 0; i < *nmdev_types; i++)
virMediatedDeviceTypeFree(*mdev_types[i]);
VIR_FREE(*mdev_types);
*nmdev_types = 0;
if (virMediatedDeviceGetMdevTypes(sysfspath, &types, &ntypes) < 0)
return -1;
*mdev_types = g_steal_pointer(&types);
*nmdev_types = ntypes;
return 0;
}
| null | null | 209,026
|
28606370464435655007062922198657708535
| 22
|
conf: Fix segfault when parsing mdev types
Commit f1b0890 introduced a potential crash due to incorrect operator
precedence when accessing an element from a pointer to an array.
Backtrace below:
#0 virNodeDeviceGetMdevTypesCaps (sysfspath=0x7fff801661e0 "/sys/devices/pci0000:00/0000:00:02.0", mdev_types=0x7fff801c9b40, nmdev_types=0x7fff801c9b48) at ../src/conf/node_device_conf.c:2676
#1 0x00007ffff7caf53d in virNodeDeviceGetPCIDynamicCaps (sysfsPath=0x7fff801661e0 "/sys/devices/pci0000:00/0000:00:02.0", pci_dev=0x7fff801c9ac8) at ../src/conf/node_device_conf.c:2705
#2 0x00007ffff7cae38f in virNodeDeviceUpdateCaps (def=0x7fff80168a10) at ../src/conf/node_device_conf.c:2342
#3 0x00007ffff7cb11c0 in virNodeDeviceObjMatch (obj=0x7fff84002e50, flags=0) at ../src/conf/virnodedeviceobj.c:850
#4 0x00007ffff7cb153d in virNodeDeviceObjListExportCallback (payload=0x7fff84002e50, name=0x7fff801cbc20 "pci_0000_00_02_0", opaque=0x7fffe2ffc6a0) at ../src/conf/virnodedeviceobj.c:909
#5 0x00007ffff7b69146 in virHashForEach (table=0x7fff9814b700 = {...}, iter=0x7ffff7cb149e <virNodeDeviceObjListExportCallback>, opaque=0x7fffe2ffc6a0) at ../src/util/virhash.c:394
#6 0x00007ffff7cb1694 in virNodeDeviceObjListExport (conn=0x7fff98013170, devs=0x7fff98154430, devices=0x7fffe2ffc798, filter=0x7ffff7cf47a1 <virConnectListAllNodeDevicesCheckACL>, flags=0)
at ../src/conf/virnodedeviceobj.c:943
#7 0x00007fffe00694b2 in nodeConnectListAllNodeDevices (conn=0x7fff98013170, devices=0x7fffe2ffc798, flags=0) at ../src/node_device/node_device_driver.c:228
#8 0x00007ffff7e703aa in virConnectListAllNodeDevices (conn=0x7fff98013170, devices=0x7fffe2ffc798, flags=0) at ../src/libvirt-nodedev.c:130
#9 0x000055555557f796 in remoteDispatchConnectListAllNodeDevices (server=0x555555627080, client=0x5555556bf050, msg=0x5555556c0000, rerr=0x7fffe2ffc8a0, args=0x7fffd4008470, ret=0x7fffd40084e0)
at src/remote/remote_daemon_dispatch_stubs.h:1613
#10 0x000055555557f6f9 in remoteDispatchConnectListAllNodeDevicesHelper (server=0x555555627080, client=0x5555556bf050, msg=0x5555556c0000, rerr=0x7fffe2ffc8a0, args=0x7fffd4008470, ret=0x7fffd40084e0)
at src/remote/remote_daemon_dispatch_stubs.h:1591
#11 0x00007ffff7ce9542 in virNetServerProgramDispatchCall (prog=0x555555690c10, server=0x555555627080, client=0x5555556bf050, msg=0x5555556c0000) at ../src/rpc/virnetserverprogram.c:428
#12 0x00007ffff7ce90bd in virNetServerProgramDispatch (prog=0x555555690c10, server=0x555555627080, client=0x5555556bf050, msg=0x5555556c0000) at ../src/rpc/virnetserverprogram.c:302
#13 0x00007ffff7cf042b in virNetServerProcessMsg (srv=0x555555627080, client=0x5555556bf050, prog=0x555555690c10, msg=0x5555556c0000) at ../src/rpc/virnetserver.c:137
#14 0x00007ffff7cf04eb in virNetServerHandleJob (jobOpaque=0x5555556b66b0, opaque=0x555555627080) at ../src/rpc/virnetserver.c:154
#15 0x00007ffff7bd912f in virThreadPoolWorker (opaque=0x55555562bc70) at ../src/util/virthreadpool.c:163
#16 0x00007ffff7bd8645 in virThreadHelper (data=0x55555562bc90) at ../src/util/virthread.c:233
#17 0x00007ffff6d90432 in start_thread () at /lib64/libpthread.so.0
#18 0x00007ffff75c5913 in clone () at /lib64/libc.so.6
Signed-off-by: Jonathon Jongsma <[email protected]>
Reviewed-by: Ján Tomko <[email protected]>
Signed-off-by: Ján Tomko <[email protected]>
|
other
|
libxml2
|
f1063fdbe7fa66332bbb76874101c2a7b51b519f
| 1
|
xmlParseStartTag2(xmlParserCtxtPtr ctxt, const xmlChar **pref,
const xmlChar **URI, int *tlen) {
const xmlChar *localname;
const xmlChar *prefix;
const xmlChar *attname;
const xmlChar *aprefix;
const xmlChar *nsname;
xmlChar *attvalue;
const xmlChar **atts = ctxt->atts;
int maxatts = ctxt->maxatts;
int nratts, nbatts, nbdef;
int i, j, nbNs, attval, oldline, oldcol;
const xmlChar *base;
unsigned long cur;
int nsNr = ctxt->nsNr;
if (RAW != '<') return(NULL);
NEXT1;
/*
* NOTE: it is crucial with the SAX2 API to never call SHRINK beyond that
* point since the attribute values may be stored as pointers to
* the buffer and calling SHRINK would destroy them !
* The Shrinking is only possible once the full set of attribute
* callbacks have been done.
*/
reparse:
SHRINK;
base = ctxt->input->base;
cur = ctxt->input->cur - ctxt->input->base;
oldline = ctxt->input->line;
oldcol = ctxt->input->col;
nbatts = 0;
nratts = 0;
nbdef = 0;
nbNs = 0;
attval = 0;
/* Forget any namespaces added during an earlier parse of this element. */
ctxt->nsNr = nsNr;
localname = xmlParseQName(ctxt, &prefix);
if (localname == NULL) {
xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
"StartTag: invalid element name\n");
return(NULL);
}
*tlen = ctxt->input->cur - ctxt->input->base - cur;
/*
* Now parse the attributes, it ends up with the ending
*
* (S Attribute)* S?
*/
SKIP_BLANKS;
GROW;
if (ctxt->input->base != base) goto base_changed;
while (((RAW != '>') &&
((RAW != '/') || (NXT(1) != '>')) &&
(IS_BYTE_CHAR(RAW))) && (ctxt->instate != XML_PARSER_EOF)) {
const xmlChar *q = CUR_PTR;
unsigned int cons = ctxt->input->consumed;
int len = -1, alloc = 0;
attname = xmlParseAttribute2(ctxt, prefix, localname,
&aprefix, &attvalue, &len, &alloc);
if (ctxt->input->base != base) {
if ((attvalue != NULL) && (alloc != 0))
xmlFree(attvalue);
attvalue = NULL;
goto base_changed;
}
if ((attname != NULL) && (attvalue != NULL)) {
if (len < 0) len = xmlStrlen(attvalue);
if ((attname == ctxt->str_xmlns) && (aprefix == NULL)) {
const xmlChar *URL = xmlDictLookup(ctxt->dict, attvalue, len);
xmlURIPtr uri;
if (URL == NULL) {
xmlErrMemory(ctxt, "dictionary allocation failure");
if ((attvalue != NULL) && (alloc != 0))
xmlFree(attvalue);
return(NULL);
}
if (*URL != 0) {
uri = xmlParseURI((const char *) URL);
if (uri == NULL) {
xmlNsErr(ctxt, XML_WAR_NS_URI,
"xmlns: '%s' is not a valid URI\n",
URL, NULL, NULL);
} else {
if (uri->scheme == NULL) {
xmlNsWarn(ctxt, XML_WAR_NS_URI_RELATIVE,
"xmlns: URI %s is not absolute\n",
URL, NULL, NULL);
}
xmlFreeURI(uri);
}
if (URL == ctxt->str_xml_ns) {
if (attname != ctxt->str_xml) {
xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE,
"xml namespace URI cannot be the default namespace\n",
NULL, NULL, NULL);
}
goto skip_default_ns;
}
if ((len == 29) &&
(xmlStrEqual(URL,
BAD_CAST "http://www.w3.org/2000/xmlns/"))) {
xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE,
"reuse of the xmlns namespace name is forbidden\n",
NULL, NULL, NULL);
goto skip_default_ns;
}
}
/*
* check that it's not a defined namespace
*/
for (j = 1;j <= nbNs;j++)
if (ctxt->nsTab[ctxt->nsNr - 2 * j] == NULL)
break;
if (j <= nbNs)
xmlErrAttributeDup(ctxt, NULL, attname);
else
if (nsPush(ctxt, NULL, URL) > 0) nbNs++;
skip_default_ns:
if (alloc != 0) xmlFree(attvalue);
if ((RAW == '>') || (((RAW == '/') && (NXT(1) == '>'))))
break;
if (!IS_BLANK_CH(RAW)) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"attributes construct error\n");
break;
}
SKIP_BLANKS;
continue;
}
if (aprefix == ctxt->str_xmlns) {
const xmlChar *URL = xmlDictLookup(ctxt->dict, attvalue, len);
xmlURIPtr uri;
if (attname == ctxt->str_xml) {
if (URL != ctxt->str_xml_ns) {
xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE,
"xml namespace prefix mapped to wrong URI\n",
NULL, NULL, NULL);
}
/*
* Do not keep a namespace definition node
*/
goto skip_ns;
}
if (URL == ctxt->str_xml_ns) {
if (attname != ctxt->str_xml) {
xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE,
"xml namespace URI mapped to wrong prefix\n",
NULL, NULL, NULL);
}
goto skip_ns;
}
if (attname == ctxt->str_xmlns) {
xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE,
"redefinition of the xmlns prefix is forbidden\n",
NULL, NULL, NULL);
goto skip_ns;
}
if ((len == 29) &&
(xmlStrEqual(URL,
BAD_CAST "http://www.w3.org/2000/xmlns/"))) {
xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE,
"reuse of the xmlns namespace name is forbidden\n",
NULL, NULL, NULL);
goto skip_ns;
}
if ((URL == NULL) || (URL[0] == 0)) {
xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE,
"xmlns:%s: Empty XML namespace is not allowed\n",
attname, NULL, NULL);
goto skip_ns;
} else {
uri = xmlParseURI((const char *) URL);
if (uri == NULL) {
xmlNsErr(ctxt, XML_WAR_NS_URI,
"xmlns:%s: '%s' is not a valid URI\n",
attname, URL, NULL);
} else {
if ((ctxt->pedantic) && (uri->scheme == NULL)) {
xmlNsWarn(ctxt, XML_WAR_NS_URI_RELATIVE,
"xmlns:%s: URI %s is not absolute\n",
attname, URL, NULL);
}
xmlFreeURI(uri);
}
}
/*
* check that it's not a defined namespace
*/
for (j = 1;j <= nbNs;j++)
if (ctxt->nsTab[ctxt->nsNr - 2 * j] == attname)
break;
if (j <= nbNs)
xmlErrAttributeDup(ctxt, aprefix, attname);
else
if (nsPush(ctxt, attname, URL) > 0) nbNs++;
skip_ns:
if (alloc != 0) xmlFree(attvalue);
if ((RAW == '>') || (((RAW == '/') && (NXT(1) == '>'))))
break;
if (!IS_BLANK_CH(RAW)) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"attributes construct error\n");
break;
}
SKIP_BLANKS;
if (ctxt->input->base != base) goto base_changed;
continue;
}
/*
* Add the pair to atts
*/
if ((atts == NULL) || (nbatts + 5 > maxatts)) {
if (xmlCtxtGrowAttrs(ctxt, nbatts + 5) < 0) {
if (attvalue[len] == 0)
xmlFree(attvalue);
goto failed;
}
maxatts = ctxt->maxatts;
atts = ctxt->atts;
}
ctxt->attallocs[nratts++] = alloc;
atts[nbatts++] = attname;
atts[nbatts++] = aprefix;
atts[nbatts++] = NULL; /* the URI will be fetched later */
atts[nbatts++] = attvalue;
attvalue += len;
atts[nbatts++] = attvalue;
/*
* tag if some deallocation is needed
*/
if (alloc != 0) attval = 1;
} else {
if ((attvalue != NULL) && (attvalue[len] == 0))
xmlFree(attvalue);
}
failed:
GROW
if (ctxt->instate == XML_PARSER_EOF)
break;
if (ctxt->input->base != base) goto base_changed;
if ((RAW == '>') || (((RAW == '/') && (NXT(1) == '>'))))
break;
if (!IS_BLANK_CH(RAW)) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"attributes construct error\n");
break;
}
SKIP_BLANKS;
if ((cons == ctxt->input->consumed) && (q == CUR_PTR) &&
(attname == NULL) && (attvalue == NULL)) {
xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR,
"xmlParseStartTag: problem parsing attributes\n");
break;
}
GROW;
if (ctxt->input->base != base) goto base_changed;
}
/*
* The attributes defaulting
*/
if (ctxt->attsDefault != NULL) {
xmlDefAttrsPtr defaults;
defaults = xmlHashLookup2(ctxt->attsDefault, localname, prefix);
if (defaults != NULL) {
for (i = 0;i < defaults->nbAttrs;i++) {
attname = defaults->values[5 * i];
aprefix = defaults->values[5 * i + 1];
/*
* special work for namespaces defaulted defs
*/
if ((attname == ctxt->str_xmlns) && (aprefix == NULL)) {
/*
* check that it's not a defined namespace
*/
for (j = 1;j <= nbNs;j++)
if (ctxt->nsTab[ctxt->nsNr - 2 * j] == NULL)
break;
if (j <= nbNs) continue;
nsname = xmlGetNamespace(ctxt, NULL);
if (nsname != defaults->values[5 * i + 2]) {
if (nsPush(ctxt, NULL,
defaults->values[5 * i + 2]) > 0)
nbNs++;
}
} else if (aprefix == ctxt->str_xmlns) {
/*
* check that it's not a defined namespace
*/
for (j = 1;j <= nbNs;j++)
if (ctxt->nsTab[ctxt->nsNr - 2 * j] == attname)
break;
if (j <= nbNs) continue;
nsname = xmlGetNamespace(ctxt, attname);
if (nsname != defaults->values[2]) {
if (nsPush(ctxt, attname,
defaults->values[5 * i + 2]) > 0)
nbNs++;
}
} else {
/*
* check that it's not a defined attribute
*/
for (j = 0;j < nbatts;j+=5) {
if ((attname == atts[j]) && (aprefix == atts[j+1]))
break;
}
if (j < nbatts) continue;
if ((atts == NULL) || (nbatts + 5 > maxatts)) {
if (xmlCtxtGrowAttrs(ctxt, nbatts + 5) < 0) {
return(NULL);
}
maxatts = ctxt->maxatts;
atts = ctxt->atts;
}
atts[nbatts++] = attname;
atts[nbatts++] = aprefix;
if (aprefix == NULL)
atts[nbatts++] = NULL;
else
atts[nbatts++] = xmlGetNamespace(ctxt, aprefix);
atts[nbatts++] = defaults->values[5 * i + 2];
atts[nbatts++] = defaults->values[5 * i + 3];
if ((ctxt->standalone == 1) &&
(defaults->values[5 * i + 4] != NULL)) {
xmlValidityError(ctxt, XML_DTD_STANDALONE_DEFAULTED,
"standalone: attribute %s on %s defaulted from external subset\n",
attname, localname);
}
nbdef++;
}
}
}
}
/*
* The attributes checkings
*/
for (i = 0; i < nbatts;i += 5) {
/*
* The default namespace does not apply to attribute names.
*/
if (atts[i + 1] != NULL) {
nsname = xmlGetNamespace(ctxt, atts[i + 1]);
if (nsname == NULL) {
xmlNsErr(ctxt, XML_NS_ERR_UNDEFINED_NAMESPACE,
"Namespace prefix %s for %s on %s is not defined\n",
atts[i + 1], atts[i], localname);
}
atts[i + 2] = nsname;
} else
nsname = NULL;
/*
* [ WFC: Unique Att Spec ]
* No attribute name may appear more than once in the same
* start-tag or empty-element tag.
* As extended by the Namespace in XML REC.
*/
for (j = 0; j < i;j += 5) {
if (atts[i] == atts[j]) {
if (atts[i+1] == atts[j+1]) {
xmlErrAttributeDup(ctxt, atts[i+1], atts[i]);
break;
}
if ((nsname != NULL) && (atts[j + 2] == nsname)) {
xmlNsErr(ctxt, XML_NS_ERR_ATTRIBUTE_REDEFINED,
"Namespaced Attribute %s in '%s' redefined\n",
atts[i], nsname, NULL);
break;
}
}
}
}
nsname = xmlGetNamespace(ctxt, prefix);
if ((prefix != NULL) && (nsname == NULL)) {
xmlNsErr(ctxt, XML_NS_ERR_UNDEFINED_NAMESPACE,
"Namespace prefix %s on %s is not defined\n",
prefix, localname, NULL);
}
*pref = prefix;
*URI = nsname;
/*
* SAX: Start of Element !
*/
if ((ctxt->sax != NULL) && (ctxt->sax->startElementNs != NULL) &&
(!ctxt->disableSAX)) {
if (nbNs > 0)
ctxt->sax->startElementNs(ctxt->userData, localname, prefix,
nsname, nbNs, &ctxt->nsTab[ctxt->nsNr - 2 * nbNs],
nbatts / 5, nbdef, atts);
else
ctxt->sax->startElementNs(ctxt->userData, localname, prefix,
nsname, 0, NULL, nbatts / 5, nbdef, atts);
}
/*
* Free up attribute allocated strings if needed
*/
if (attval != 0) {
for (i = 3,j = 0; j < nratts;i += 5,j++)
if ((ctxt->attallocs[j] != 0) && (atts[i] != NULL))
xmlFree((xmlChar *) atts[i]);
}
return(localname);
base_changed:
/*
* the attribute strings are valid iif the base didn't changed
*/
if (attval != 0) {
for (i = 3,j = 0; j < nratts;i += 5,j++)
if ((ctxt->attallocs[j] != 0) && (atts[i] != NULL))
xmlFree((xmlChar *) atts[i]);
}
ctxt->input->cur = ctxt->input->base + cur;
ctxt->input->line = oldline;
ctxt->input->col = oldcol;
if (ctxt->wellFormed == 1) {
goto reparse;
}
return(NULL);
}
| null | null | 209,049
|
250291329740874587936948809023195704384
| 443
|
CVE-2015-7500 Fix memory access error due to incorrect entities boundaries
For https://bugzilla.gnome.org/show_bug.cgi?id=756525
handle properly the case where we popped out of the current entity
while processing a start tag
Reported by Kostya Serebryany @ Google
This slightly modifies the output of 754946 in regression tests
|
other
|
vim
|
80525751c5ce9ed82c41d83faf9ef38667bf61b1
| 1
|
do_mouse(
oparg_T *oap, // operator argument, can be NULL
int c, // K_LEFTMOUSE, etc
int dir, // Direction to 'put' if necessary
long count,
int fixindent) // PUT_FIXINDENT if fixing indent necessary
{
static int do_always = FALSE; // ignore 'mouse' setting next time
static int got_click = FALSE; // got a click some time back
int which_button; // MOUSE_LEFT, _MIDDLE or _RIGHT
int is_click = FALSE; // If FALSE it's a drag or release event
int is_drag = FALSE; // If TRUE it's a drag event
int jump_flags = 0; // flags for jump_to_mouse()
pos_T start_visual;
int moved; // Has cursor moved?
int in_status_line; // mouse in status line
static int in_tab_line = FALSE; // mouse clicked in tab line
int in_sep_line; // mouse in vertical separator line
int c1, c2;
#if defined(FEAT_FOLDING)
pos_T save_cursor;
#endif
win_T *old_curwin = curwin;
static pos_T orig_cursor;
colnr_T leftcol, rightcol;
pos_T end_visual;
int diff;
int old_active = VIsual_active;
int old_mode = VIsual_mode;
int regname;
#if defined(FEAT_FOLDING)
save_cursor = curwin->w_cursor;
#endif
// When GUI is active, always recognize mouse events, otherwise:
// - Ignore mouse event in normal mode if 'mouse' doesn't include 'n'.
// - Ignore mouse event in visual mode if 'mouse' doesn't include 'v'.
// - For command line and insert mode 'mouse' is checked before calling
// do_mouse().
if (do_always)
do_always = FALSE;
else
#ifdef FEAT_GUI
if (!gui.in_use)
#endif
{
if (VIsual_active)
{
if (!mouse_has(MOUSE_VISUAL))
return FALSE;
}
else if (State == MODE_NORMAL && !mouse_has(MOUSE_NORMAL))
return FALSE;
}
for (;;)
{
which_button = get_mouse_button(KEY2TERMCAP1(c), &is_click, &is_drag);
if (is_drag)
{
// If the next character is the same mouse event then use that
// one. Speeds up dragging the status line.
// Note: Since characters added to the stuff buffer in the code
// below need to come before the next character, do not do this
// when the current character was stuffed.
if (!KeyStuffed && vpeekc() != NUL)
{
int nc;
int save_mouse_row = mouse_row;
int save_mouse_col = mouse_col;
// Need to get the character, peeking doesn't get the actual
// one.
nc = safe_vgetc();
if (c == nc)
continue;
vungetc(nc);
mouse_row = save_mouse_row;
mouse_col = save_mouse_col;
}
}
break;
}
if (c == K_MOUSEMOVE)
{
// Mouse moved without a button pressed.
#ifdef FEAT_BEVAL_TERM
ui_may_remove_balloon();
if (p_bevalterm)
{
profile_setlimit(p_bdlay, &bevalexpr_due);
bevalexpr_due_set = TRUE;
}
#endif
#ifdef FEAT_PROP_POPUP
popup_handle_mouse_moved();
#endif
return FALSE;
}
#ifdef FEAT_MOUSESHAPE
// May have stopped dragging the status or separator line. The pointer is
// most likely still on the status or separator line.
if (!is_drag && drag_status_line)
{
drag_status_line = FALSE;
update_mouseshape(SHAPE_IDX_STATUS);
}
if (!is_drag && drag_sep_line)
{
drag_sep_line = FALSE;
update_mouseshape(SHAPE_IDX_VSEP);
}
#endif
// Ignore drag and release events if we didn't get a click.
if (is_click)
got_click = TRUE;
else
{
if (!got_click) // didn't get click, ignore
return FALSE;
if (!is_drag) // release, reset got_click
{
got_click = FALSE;
if (in_tab_line)
{
in_tab_line = FALSE;
return FALSE;
}
}
}
// CTRL right mouse button does CTRL-T
if (is_click && (mod_mask & MOD_MASK_CTRL) && which_button == MOUSE_RIGHT)
{
if (State & MODE_INSERT)
stuffcharReadbuff(Ctrl_O);
if (count > 1)
stuffnumReadbuff(count);
stuffcharReadbuff(Ctrl_T);
got_click = FALSE; // ignore drag&release now
return FALSE;
}
// CTRL only works with left mouse button
if ((mod_mask & MOD_MASK_CTRL) && which_button != MOUSE_LEFT)
return FALSE;
// When a modifier is down, ignore drag and release events, as well as
// multiple clicks and the middle mouse button.
// Accept shift-leftmouse drags when 'mousemodel' is "popup.*".
if ((mod_mask & (MOD_MASK_SHIFT | MOD_MASK_CTRL | MOD_MASK_ALT
| MOD_MASK_META))
&& (!is_click
|| (mod_mask & MOD_MASK_MULTI_CLICK)
|| which_button == MOUSE_MIDDLE)
&& !((mod_mask & (MOD_MASK_SHIFT|MOD_MASK_ALT))
&& mouse_model_popup()
&& which_button == MOUSE_LEFT)
&& !((mod_mask & MOD_MASK_ALT)
&& !mouse_model_popup()
&& which_button == MOUSE_RIGHT)
)
return FALSE;
// If the button press was used as the movement command for an operator
// (eg "d<MOUSE>"), or it is the middle button that is held down, ignore
// drag/release events.
if (!is_click && which_button == MOUSE_MIDDLE)
return FALSE;
if (oap != NULL)
regname = oap->regname;
else
regname = 0;
// Middle mouse button does a 'put' of the selected text
if (which_button == MOUSE_MIDDLE)
{
if (State == MODE_NORMAL)
{
// If an operator was pending, we don't know what the user wanted
// to do. Go back to normal mode: Clear the operator and beep().
if (oap != NULL && oap->op_type != OP_NOP)
{
clearopbeep(oap);
return FALSE;
}
// If visual was active, yank the highlighted text and put it
// before the mouse pointer position.
// In Select mode replace the highlighted text with the clipboard.
if (VIsual_active)
{
if (VIsual_select)
{
stuffcharReadbuff(Ctrl_G);
stuffReadbuff((char_u *)"\"+p");
}
else
{
stuffcharReadbuff('y');
stuffcharReadbuff(K_MIDDLEMOUSE);
}
do_always = TRUE; // ignore 'mouse' setting next time
return FALSE;
}
// The rest is below jump_to_mouse()
}
else if ((State & MODE_INSERT) == 0)
return FALSE;
// Middle click in insert mode doesn't move the mouse, just insert the
// contents of a register. '.' register is special, can't insert that
// with do_put().
// Also paste at the cursor if the current mode isn't in 'mouse' (only
// happens for the GUI).
if ((State & MODE_INSERT) || !mouse_has(MOUSE_NORMAL))
{
if (regname == '.')
insert_reg(regname, TRUE);
else
{
#ifdef FEAT_CLIPBOARD
if (clip_star.available && regname == 0)
regname = '*';
#endif
if ((State & REPLACE_FLAG) && !yank_register_mline(regname))
insert_reg(regname, TRUE);
else
{
do_put(regname, NULL, BACKWARD, 1L,
fixindent | PUT_CURSEND);
// Repeat it with CTRL-R CTRL-O r or CTRL-R CTRL-P r
AppendCharToRedobuff(Ctrl_R);
AppendCharToRedobuff(fixindent ? Ctrl_P : Ctrl_O);
AppendCharToRedobuff(regname == 0 ? '"' : regname);
}
}
return FALSE;
}
}
// When dragging or button-up stay in the same window.
if (!is_click)
jump_flags |= MOUSE_FOCUS | MOUSE_DID_MOVE;
start_visual.lnum = 0;
// Check for clicking in the tab page line.
if (mouse_row == 0 && firstwin->w_winrow > 0)
{
if (is_drag)
{
if (in_tab_line)
{
c1 = TabPageIdxs[mouse_col];
tabpage_move(c1 <= 0 ? 9999 : c1 < tabpage_index(curtab)
? c1 - 1 : c1);
}
return FALSE;
}
// click in a tab selects that tab page
if (is_click
# ifdef FEAT_CMDWIN
&& cmdwin_type == 0
# endif
&& mouse_col < Columns)
{
in_tab_line = TRUE;
c1 = TabPageIdxs[mouse_col];
if (c1 >= 0)
{
if ((mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_2CLICK)
{
// double click opens new page
end_visual_mode_keep_button();
tabpage_new();
tabpage_move(c1 == 0 ? 9999 : c1 - 1);
}
else
{
// Go to specified tab page, or next one if not clicking
// on a label.
goto_tabpage(c1);
// It's like clicking on the status line of a window.
if (curwin != old_curwin)
end_visual_mode_keep_button();
}
}
else
{
tabpage_T *tp;
// Close the current or specified tab page.
if (c1 == -999)
tp = curtab;
else
tp = find_tabpage(-c1);
if (tp == curtab)
{
if (first_tabpage->tp_next != NULL)
tabpage_close(FALSE);
}
else if (tp != NULL)
tabpage_close_other(tp, FALSE);
}
}
return TRUE;
}
else if (is_drag && in_tab_line)
{
c1 = TabPageIdxs[mouse_col];
tabpage_move(c1 <= 0 ? 9999 : c1 - 1);
return FALSE;
}
// When 'mousemodel' is "popup" or "popup_setpos", translate mouse events:
// right button up -> pop-up menu
// shift-left button -> right button
// alt-left button -> alt-right button
if (mouse_model_popup())
{
if (which_button == MOUSE_RIGHT
&& !(mod_mask & (MOD_MASK_SHIFT | MOD_MASK_CTRL)))
{
#ifdef USE_POPUP_SETPOS
# ifdef FEAT_GUI
if (gui.in_use)
{
# if defined(FEAT_GUI_MOTIF) || defined(FEAT_GUI_GTK) \
|| defined(FEAT_GUI_PHOTON)
if (!is_click)
// Ignore right button release events, only shows the popup
// menu on the button down event.
return FALSE;
# endif
# if defined(FEAT_GUI_MSWIN) || defined(FEAT_GUI_HAIKU)
if (is_click || is_drag)
// Ignore right button down and drag mouse events. Windows
// only shows the popup menu on the button up event.
return FALSE;
# endif
}
# endif
# if defined(FEAT_GUI) && defined(FEAT_TERM_POPUP_MENU)
else
# endif
# if defined(FEAT_TERM_POPUP_MENU)
if (!is_click)
// Ignore right button release events, only shows the popup
// menu on the button down event.
return FALSE;
#endif
jump_flags = 0;
if (STRCMP(p_mousem, "popup_setpos") == 0)
{
// First set the cursor position before showing the popup
// menu.
if (VIsual_active)
{
pos_T m_pos;
// set MOUSE_MAY_STOP_VIS if we are outside the
// selection or the current window (might have false
// negative here)
if (mouse_row < curwin->w_winrow
|| mouse_row
> (curwin->w_winrow + curwin->w_height))
jump_flags = MOUSE_MAY_STOP_VIS;
else if (get_fpos_of_mouse(&m_pos) != IN_BUFFER)
jump_flags = MOUSE_MAY_STOP_VIS;
else
{
if ((LT_POS(curwin->w_cursor, VIsual)
&& (LT_POS(m_pos, curwin->w_cursor)
|| LT_POS(VIsual, m_pos)))
|| (LT_POS(VIsual, curwin->w_cursor)
&& (LT_POS(m_pos, VIsual)
|| LT_POS(curwin->w_cursor, m_pos))))
{
jump_flags = MOUSE_MAY_STOP_VIS;
}
else if (VIsual_mode == Ctrl_V)
{
getvcols(curwin, &curwin->w_cursor, &VIsual,
&leftcol, &rightcol);
getvcol(curwin, &m_pos, NULL, &m_pos.col, NULL);
if (m_pos.col < leftcol || m_pos.col > rightcol)
jump_flags = MOUSE_MAY_STOP_VIS;
}
}
}
else
jump_flags = MOUSE_MAY_STOP_VIS;
}
if (jump_flags)
{
jump_flags = jump_to_mouse(jump_flags, NULL, which_button);
update_curbuf(VIsual_active ? UPD_INVERTED : UPD_VALID);
setcursor();
out_flush(); // Update before showing popup menu
}
# ifdef FEAT_MENU
show_popupmenu();
got_click = FALSE; // ignore release events
# endif
return (jump_flags & CURSOR_MOVED) != 0;
#else
return FALSE;
#endif
}
if (which_button == MOUSE_LEFT
&& (mod_mask & (MOD_MASK_SHIFT|MOD_MASK_ALT)))
{
which_button = MOUSE_RIGHT;
mod_mask &= ~MOD_MASK_SHIFT;
}
}
if ((State & (MODE_NORMAL | MODE_INSERT))
&& !(mod_mask & (MOD_MASK_SHIFT | MOD_MASK_CTRL)))
{
if (which_button == MOUSE_LEFT)
{
if (is_click)
{
// stop Visual mode for a left click in a window, but not when
// on a status line
if (VIsual_active)
jump_flags |= MOUSE_MAY_STOP_VIS;
}
else if (mouse_has(MOUSE_VISUAL))
jump_flags |= MOUSE_MAY_VIS;
}
else if (which_button == MOUSE_RIGHT)
{
if (is_click && VIsual_active)
{
// Remember the start and end of visual before moving the
// cursor.
if (LT_POS(curwin->w_cursor, VIsual))
{
start_visual = curwin->w_cursor;
end_visual = VIsual;
}
else
{
start_visual = VIsual;
end_visual = curwin->w_cursor;
}
}
jump_flags |= MOUSE_FOCUS;
if (mouse_has(MOUSE_VISUAL))
jump_flags |= MOUSE_MAY_VIS;
}
}
// If an operator is pending, ignore all drags and releases until the
// next mouse click.
if (!is_drag && oap != NULL && oap->op_type != OP_NOP)
{
got_click = FALSE;
oap->motion_type = MCHAR;
}
// When releasing the button let jump_to_mouse() know.
if (!is_click && !is_drag)
jump_flags |= MOUSE_RELEASED;
// JUMP!
jump_flags = jump_to_mouse(jump_flags,
oap == NULL ? NULL : &(oap->inclusive), which_button);
#ifdef FEAT_MENU
// A click in the window toolbar has no side effects.
if (jump_flags & MOUSE_WINBAR)
return FALSE;
#endif
moved = (jump_flags & CURSOR_MOVED);
in_status_line = (jump_flags & IN_STATUS_LINE);
in_sep_line = (jump_flags & IN_SEP_LINE);
#ifdef FEAT_NETBEANS_INTG
if (isNetbeansBuffer(curbuf)
&& !(jump_flags & (IN_STATUS_LINE | IN_SEP_LINE)))
{
int key = KEY2TERMCAP1(c);
if (key == (int)KE_LEFTRELEASE || key == (int)KE_MIDDLERELEASE
|| key == (int)KE_RIGHTRELEASE)
netbeans_button_release(which_button);
}
#endif
// When jumping to another window, clear a pending operator. That's a bit
// friendlier than beeping and not jumping to that window.
if (curwin != old_curwin && oap != NULL && oap->op_type != OP_NOP)
clearop(oap);
#ifdef FEAT_FOLDING
if (mod_mask == 0
&& !is_drag
&& (jump_flags & (MOUSE_FOLD_CLOSE | MOUSE_FOLD_OPEN))
&& which_button == MOUSE_LEFT)
{
// open or close a fold at this line
if (jump_flags & MOUSE_FOLD_OPEN)
openFold(curwin->w_cursor.lnum, 1L);
else
closeFold(curwin->w_cursor.lnum, 1L);
// don't move the cursor if still in the same window
if (curwin == old_curwin)
curwin->w_cursor = save_cursor;
}
#endif
#if defined(FEAT_CLIPBOARD) && defined(FEAT_CMDWIN)
if ((jump_flags & IN_OTHER_WIN) && !VIsual_active && clip_star.available)
{
clip_modeless(which_button, is_click, is_drag);
return FALSE;
}
#endif
// Set global flag that we are extending the Visual area with mouse
// dragging; temporarily minimize 'scrolloff'.
if (VIsual_active && is_drag && get_scrolloff_value())
{
// In the very first line, allow scrolling one line
if (mouse_row == 0)
mouse_dragging = 2;
else
mouse_dragging = 1;
}
// When dragging the mouse above the window, scroll down.
if (is_drag && mouse_row < 0 && !in_status_line)
{
scroll_redraw(FALSE, 1L);
mouse_row = 0;
}
if (start_visual.lnum) // right click in visual mode
{
// When ALT is pressed make Visual mode blockwise.
if (mod_mask & MOD_MASK_ALT)
VIsual_mode = Ctrl_V;
// In Visual-block mode, divide the area in four, pick up the corner
// that is in the quarter that the cursor is in.
if (VIsual_mode == Ctrl_V)
{
getvcols(curwin, &start_visual, &end_visual, &leftcol, &rightcol);
if (curwin->w_curswant > (leftcol + rightcol) / 2)
end_visual.col = leftcol;
else
end_visual.col = rightcol;
if (curwin->w_cursor.lnum >=
(start_visual.lnum + end_visual.lnum) / 2)
end_visual.lnum = start_visual.lnum;
// move VIsual to the right column
start_visual = curwin->w_cursor; // save the cursor pos
curwin->w_cursor = end_visual;
coladvance(end_visual.col);
VIsual = curwin->w_cursor;
curwin->w_cursor = start_visual; // restore the cursor
}
else
{
// If the click is before the start of visual, change the start.
// If the click is after the end of visual, change the end. If
// the click is inside the visual, change the closest side.
if (LT_POS(curwin->w_cursor, start_visual))
VIsual = end_visual;
else if (LT_POS(end_visual, curwin->w_cursor))
VIsual = start_visual;
else
{
// In the same line, compare column number
if (end_visual.lnum == start_visual.lnum)
{
if (curwin->w_cursor.col - start_visual.col >
end_visual.col - curwin->w_cursor.col)
VIsual = start_visual;
else
VIsual = end_visual;
}
// In different lines, compare line number
else
{
diff = (curwin->w_cursor.lnum - start_visual.lnum) -
(end_visual.lnum - curwin->w_cursor.lnum);
if (diff > 0) // closest to end
VIsual = start_visual;
else if (diff < 0) // closest to start
VIsual = end_visual;
else // in the middle line
{
if (curwin->w_cursor.col <
(start_visual.col + end_visual.col) / 2)
VIsual = end_visual;
else
VIsual = start_visual;
}
}
}
}
}
// If Visual mode started in insert mode, execute "CTRL-O"
else if ((State & MODE_INSERT) && VIsual_active)
stuffcharReadbuff(Ctrl_O);
// Middle mouse click: Put text before cursor.
if (which_button == MOUSE_MIDDLE)
{
#ifdef FEAT_CLIPBOARD
if (clip_star.available && regname == 0)
regname = '*';
#endif
if (yank_register_mline(regname))
{
if (mouse_past_bottom)
dir = FORWARD;
}
else if (mouse_past_eol)
dir = FORWARD;
if (fixindent)
{
c1 = (dir == BACKWARD) ? '[' : ']';
c2 = 'p';
}
else
{
c1 = (dir == FORWARD) ? 'p' : 'P';
c2 = NUL;
}
prep_redo(regname, count, NUL, c1, NUL, c2, NUL);
// Remember where the paste started, so in edit() Insstart can be set
// to this position
if (restart_edit != 0)
where_paste_started = curwin->w_cursor;
do_put(regname, NULL, dir, count, fixindent | PUT_CURSEND);
}
#if defined(FEAT_QUICKFIX)
// Ctrl-Mouse click or double click in a quickfix window jumps to the
// error under the mouse pointer.
else if (((mod_mask & MOD_MASK_CTRL)
|| (mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_2CLICK)
&& bt_quickfix(curbuf))
{
if (curwin->w_llist_ref == NULL) // quickfix window
do_cmdline_cmd((char_u *)".cc");
else // location list window
do_cmdline_cmd((char_u *)".ll");
got_click = FALSE; // ignore drag&release now
}
#endif
// Ctrl-Mouse click (or double click in a help window) jumps to the tag
// under the mouse pointer.
else if ((mod_mask & MOD_MASK_CTRL) || (curbuf->b_help
&& (mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_2CLICK))
{
if (State & MODE_INSERT)
stuffcharReadbuff(Ctrl_O);
stuffcharReadbuff(Ctrl_RSB);
got_click = FALSE; // ignore drag&release now
}
// Shift-Mouse click searches for the next occurrence of the word under
// the mouse pointer
else if ((mod_mask & MOD_MASK_SHIFT))
{
if ((State & MODE_INSERT) || (VIsual_active && VIsual_select))
stuffcharReadbuff(Ctrl_O);
if (which_button == MOUSE_LEFT)
stuffcharReadbuff('*');
else // MOUSE_RIGHT
stuffcharReadbuff('#');
}
// Handle double clicks, unless on status line
else if (in_status_line)
{
#ifdef FEAT_MOUSESHAPE
if ((is_drag || is_click) && !drag_status_line)
{
drag_status_line = TRUE;
update_mouseshape(-1);
}
#endif
}
else if (in_sep_line)
{
#ifdef FEAT_MOUSESHAPE
if ((is_drag || is_click) && !drag_sep_line)
{
drag_sep_line = TRUE;
update_mouseshape(-1);
}
#endif
}
else if ((mod_mask & MOD_MASK_MULTI_CLICK)
&& (State & (MODE_NORMAL | MODE_INSERT))
&& mouse_has(MOUSE_VISUAL))
{
if (is_click || !VIsual_active)
{
if (VIsual_active)
orig_cursor = VIsual;
else
{
check_visual_highlight();
VIsual = curwin->w_cursor;
orig_cursor = VIsual;
VIsual_active = TRUE;
VIsual_reselect = TRUE;
// start Select mode if 'selectmode' contains "mouse"
may_start_select('o');
setmouse();
}
if ((mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_2CLICK)
{
// Double click with ALT pressed makes it blockwise.
if (mod_mask & MOD_MASK_ALT)
VIsual_mode = Ctrl_V;
else
VIsual_mode = 'v';
}
else if ((mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_3CLICK)
VIsual_mode = 'V';
else if ((mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_4CLICK)
VIsual_mode = Ctrl_V;
#ifdef FEAT_CLIPBOARD
// Make sure the clipboard gets updated. Needed because start and
// end may still be the same, and the selection needs to be owned
clip_star.vmode = NUL;
#endif
}
// A double click selects a word or a block.
if ((mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_2CLICK)
{
pos_T *pos = NULL;
int gc;
if (is_click)
{
// If the character under the cursor (skipping white space) is
// not a word character, try finding a match and select a (),
// {}, [], #if/#endif, etc. block.
end_visual = curwin->w_cursor;
while (gc = gchar_pos(&end_visual), VIM_ISWHITE(gc))
inc(&end_visual);
if (oap != NULL)
oap->motion_type = MCHAR;
if (oap != NULL
&& VIsual_mode == 'v'
&& !vim_iswordc(gchar_pos(&end_visual))
&& EQUAL_POS(curwin->w_cursor, VIsual)
&& (pos = findmatch(oap, NUL)) != NULL)
{
curwin->w_cursor = *pos;
if (oap->motion_type == MLINE)
VIsual_mode = 'V';
else if (*p_sel == 'e')
{
if (LT_POS(curwin->w_cursor, VIsual))
++VIsual.col;
else
++curwin->w_cursor.col;
}
}
}
if (pos == NULL && (is_click || is_drag))
{
// When not found a match or when dragging: extend to include
// a word.
if (LT_POS(curwin->w_cursor, orig_cursor))
{
find_start_of_word(&curwin->w_cursor);
find_end_of_word(&VIsual);
}
else
{
find_start_of_word(&VIsual);
if (*p_sel == 'e' && *ml_get_cursor() != NUL)
curwin->w_cursor.col +=
(*mb_ptr2len)(ml_get_cursor());
find_end_of_word(&curwin->w_cursor);
}
}
curwin->w_set_curswant = TRUE;
}
if (is_click)
redraw_curbuf_later(UPD_INVERTED); // update the inversion
}
else if (VIsual_active && !old_active)
{
if (mod_mask & MOD_MASK_ALT)
VIsual_mode = Ctrl_V;
else
VIsual_mode = 'v';
}
// If Visual mode changed show it later.
if ((!VIsual_active && old_active && mode_displayed)
|| (VIsual_active && p_smd && msg_silent == 0
&& (!old_active || VIsual_mode != old_mode)))
redraw_cmdline = TRUE;
return moved;
}
| null | null | 209,102
|
159266025064479013943001437579885155483
| 829
|
patch 9.0.0259: crash with mouse click when not initialized
Problem: Crash with mouse click when not initialized.
Solution: Check TabPageIdxs[] is not NULL.
|
other
|
linux
|
5352a761308397a0e6250fdc629bb3f615b94747
| 1
|
static int ax25_release(struct socket *sock)
{
struct sock *sk = sock->sk;
ax25_cb *ax25;
ax25_dev *ax25_dev;
if (sk == NULL)
return 0;
sock_hold(sk);
lock_sock(sk);
sock_orphan(sk);
ax25 = sk_to_ax25(sk);
ax25_dev = ax25->ax25_dev;
if (ax25_dev) {
dev_put_track(ax25_dev->dev, &ax25_dev->dev_tracker);
ax25_dev_put(ax25_dev);
}
if (sk->sk_type == SOCK_SEQPACKET) {
switch (ax25->state) {
case AX25_STATE_0:
release_sock(sk);
ax25_disconnect(ax25, 0);
lock_sock(sk);
ax25_destroy_socket(ax25);
break;
case AX25_STATE_1:
case AX25_STATE_2:
ax25_send_control(ax25, AX25_DISC, AX25_POLLON, AX25_COMMAND);
release_sock(sk);
ax25_disconnect(ax25, 0);
lock_sock(sk);
if (!sock_flag(ax25->sk, SOCK_DESTROY))
ax25_destroy_socket(ax25);
break;
case AX25_STATE_3:
case AX25_STATE_4:
ax25_clear_queues(ax25);
ax25->n2count = 0;
switch (ax25->ax25_dev->values[AX25_VALUES_PROTOCOL]) {
case AX25_PROTO_STD_SIMPLEX:
case AX25_PROTO_STD_DUPLEX:
ax25_send_control(ax25,
AX25_DISC,
AX25_POLLON,
AX25_COMMAND);
ax25_stop_t2timer(ax25);
ax25_stop_t3timer(ax25);
ax25_stop_idletimer(ax25);
break;
#ifdef CONFIG_AX25_DAMA_SLAVE
case AX25_PROTO_DAMA_SLAVE:
ax25_stop_t3timer(ax25);
ax25_stop_idletimer(ax25);
break;
#endif
}
ax25_calculate_t1(ax25);
ax25_start_t1timer(ax25);
ax25->state = AX25_STATE_2;
sk->sk_state = TCP_CLOSE;
sk->sk_shutdown |= SEND_SHUTDOWN;
sk->sk_state_change(sk);
sock_set_flag(sk, SOCK_DESTROY);
break;
default:
break;
}
} else {
sk->sk_state = TCP_CLOSE;
sk->sk_shutdown |= SEND_SHUTDOWN;
sk->sk_state_change(sk);
ax25_destroy_socket(ax25);
}
sock->sk = NULL;
release_sock(sk);
sock_put(sk);
return 0;
}
| null | null | 209,106
|
64131604211410647910287923265003264859
| 86
|
ax25: fix UAF bug in ax25_send_control()
There are UAF bugs in ax25_send_control(), when we call ax25_release()
to deallocate ax25_dev. The possible race condition is shown below:
(Thread 1) | (Thread 2)
ax25_dev_device_up() //(1) |
| ax25_kill_by_device()
ax25_bind() //(2) |
ax25_connect() | ...
ax25->state = AX25_STATE_1 |
... | ax25_dev_device_down() //(3)
(Thread 3)
ax25_release() |
ax25_dev_put() //(4) FREE |
case AX25_STATE_1: |
ax25_send_control() |
alloc_skb() //USE |
The refcount of ax25_dev increases in position (1) and (2), and
decreases in position (3) and (4). The ax25_dev will be freed
before dereference sites in ax25_send_control().
The following is part of the report:
[ 102.297448] BUG: KASAN: use-after-free in ax25_send_control+0x33/0x210
[ 102.297448] Read of size 8 at addr ffff888009e6e408 by task ax25_close/602
[ 102.297448] Call Trace:
[ 102.303751] ax25_send_control+0x33/0x210
[ 102.303751] ax25_release+0x356/0x450
[ 102.305431] __sock_release+0x6d/0x120
[ 102.305431] sock_close+0xf/0x20
[ 102.305431] __fput+0x11f/0x420
[ 102.305431] task_work_run+0x86/0xd0
[ 102.307130] get_signal+0x1075/0x1220
[ 102.308253] arch_do_signal_or_restart+0x1df/0xc00
[ 102.308253] exit_to_user_mode_prepare+0x150/0x1e0
[ 102.308253] syscall_exit_to_user_mode+0x19/0x50
[ 102.308253] do_syscall_64+0x48/0x90
[ 102.308253] entry_SYSCALL_64_after_hwframe+0x44/0xae
[ 102.308253] RIP: 0033:0x405ae7
This patch defers the free operation of ax25_dev and net_device after
all corresponding dereference sites in ax25_release() to avoid UAF.
Fixes: 9fd75b66b8f6 ("ax25: Fix refcount leaks caused by ax25_cb_del()")
Signed-off-by: Duoming Zhou <[email protected]>
Signed-off-by: Paolo Abeni <[email protected]>
|
other
|
quagga
|
099ed6744881e71957f2bfeebc4c0727714d2394
| 1
|
ospf_packet_add_top (struct ospf_interface *oi, struct ospf_packet *op)
{
if (!oi->obuf)
{
zlog_err("ospf_packet_add(interface %s in state %d [%s], packet type %s, "
"destination %s) called with NULL obuf, ignoring "
"(please report this bug)!\n",
IF_NAME(oi), oi->state, LOOKUP (ospf_ism_state_msg, oi->state),
ospf_packet_type_str[stream_getc_from(op->s, 1)],
inet_ntoa (op->dst));
return;
}
/* Add packet to head of queue. */
ospf_fifo_push_head (oi->obuf, op);
/* Debug of packet fifo*/
/* ospf_fifo_debug (oi->obuf); */
}
| null | null | 209,771
|
147568580972588828700710848557085359496
| 19
|
ospfd: fix ospf_packet_add_top() to use LOOKUP()
|
other
|
mujs
|
f5b3c703e18725e380b83427004632e744f85a6f
| 1
|
void jsP_dumpsyntax(js_State *J, js_Ast *prog, int dominify)
{
minify = dominify;
if (prog->type == AST_LIST)
pstmlist(-1, prog);
else {
pstm(0, prog);
nl();
}
if (minify > 1)
putchar('\n');
}
| null | null | 209,801
|
179855345628520056045814922229839668834
| 12
|
Issue #161: Cope with empty programs in mujs-pp.
|
other
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.