id
stringlengths
25
30
content
stringlengths
14
942k
max_stars_repo_path
stringlengths
49
55
crossvul-cpp_data_bad_2415_1
/* * namei.c * * PURPOSE * Inode name handling routines for the OSTA-UDF(tm) filesystem. * * COPYRIGHT * This file is distributed under the terms of the GNU General Public * License (GPL). Copies of the GPL can be obtained from: * ftp://prep.ai.mit.edu/pub/gnu/GPL * Each contributing author retains all rights to their own work. * * (C) 1998-2004 Ben Fennema * (C) 1999-2000 Stelias Computing Inc * * HISTORY * * 12/12/98 blf Created. Split out the lookup code from dir.c * 04/19/99 blf link, mknod, symlink support */ #include "udfdecl.h" #include "udf_i.h" #include "udf_sb.h" #include <linux/string.h> #include <linux/errno.h> #include <linux/mm.h> #include <linux/slab.h> #include <linux/buffer_head.h> #include <linux/sched.h> #include <linux/crc-itu-t.h> #include <linux/exportfs.h> static inline int udf_match(int len1, const unsigned char *name1, int len2, const unsigned char *name2) { if (len1 != len2) return 0; return !memcmp(name1, name2, len1); } int udf_write_fi(struct inode *inode, struct fileIdentDesc *cfi, struct fileIdentDesc *sfi, struct udf_fileident_bh *fibh, uint8_t *impuse, uint8_t *fileident) { uint16_t crclen = fibh->eoffset - fibh->soffset - sizeof(struct tag); uint16_t crc; int offset; uint16_t liu = le16_to_cpu(cfi->lengthOfImpUse); uint8_t lfi = cfi->lengthFileIdent; int padlen = fibh->eoffset - fibh->soffset - liu - lfi - sizeof(struct fileIdentDesc); int adinicb = 0; if (UDF_I(inode)->i_alloc_type == ICBTAG_FLAG_AD_IN_ICB) adinicb = 1; offset = fibh->soffset + sizeof(struct fileIdentDesc); if (impuse) { if (adinicb || (offset + liu < 0)) { memcpy((uint8_t *)sfi->impUse, impuse, liu); } else if (offset >= 0) { memcpy(fibh->ebh->b_data + offset, impuse, liu); } else { memcpy((uint8_t *)sfi->impUse, impuse, -offset); memcpy(fibh->ebh->b_data, impuse - offset, liu + offset); } } offset += liu; if (fileident) { if (adinicb || (offset + lfi < 0)) { memcpy((uint8_t *)sfi->fileIdent + liu, fileident, lfi); } else if (offset >= 0) { memcpy(fibh->ebh->b_data + offset, fileident, lfi); } else { memcpy((uint8_t *)sfi->fileIdent + liu, fileident, -offset); memcpy(fibh->ebh->b_data, fileident - offset, lfi + offset); } } offset += lfi; if (adinicb || (offset + padlen < 0)) { memset((uint8_t *)sfi->padding + liu + lfi, 0x00, padlen); } else if (offset >= 0) { memset(fibh->ebh->b_data + offset, 0x00, padlen); } else { memset((uint8_t *)sfi->padding + liu + lfi, 0x00, -offset); memset(fibh->ebh->b_data, 0x00, padlen + offset); } crc = crc_itu_t(0, (uint8_t *)cfi + sizeof(struct tag), sizeof(struct fileIdentDesc) - sizeof(struct tag)); if (fibh->sbh == fibh->ebh) { crc = crc_itu_t(crc, (uint8_t *)sfi->impUse, crclen + sizeof(struct tag) - sizeof(struct fileIdentDesc)); } else if (sizeof(struct fileIdentDesc) >= -fibh->soffset) { crc = crc_itu_t(crc, fibh->ebh->b_data + sizeof(struct fileIdentDesc) + fibh->soffset, crclen + sizeof(struct tag) - sizeof(struct fileIdentDesc)); } else { crc = crc_itu_t(crc, (uint8_t *)sfi->impUse, -fibh->soffset - sizeof(struct fileIdentDesc)); crc = crc_itu_t(crc, fibh->ebh->b_data, fibh->eoffset); } cfi->descTag.descCRC = cpu_to_le16(crc); cfi->descTag.descCRCLength = cpu_to_le16(crclen); cfi->descTag.tagChecksum = udf_tag_checksum(&cfi->descTag); if (adinicb || (sizeof(struct fileIdentDesc) <= -fibh->soffset)) { memcpy((uint8_t *)sfi, (uint8_t *)cfi, sizeof(struct fileIdentDesc)); } else { memcpy((uint8_t *)sfi, (uint8_t *)cfi, -fibh->soffset); memcpy(fibh->ebh->b_data, (uint8_t *)cfi - fibh->soffset, sizeof(struct fileIdentDesc) + fibh->soffset); } if (adinicb) { mark_inode_dirty(inode); } else { if (fibh->sbh != fibh->ebh) mark_buffer_dirty_inode(fibh->ebh, inode); mark_buffer_dirty_inode(fibh->sbh, inode); } return 0; } static struct fileIdentDesc *udf_find_entry(struct inode *dir, const struct qstr *child, struct udf_fileident_bh *fibh, struct fileIdentDesc *cfi) { struct fileIdentDesc *fi = NULL; loff_t f_pos; int block, flen; unsigned char *fname = NULL; unsigned char *nameptr; uint8_t lfi; uint16_t liu; loff_t size; struct kernel_lb_addr eloc; uint32_t elen; sector_t offset; struct extent_position epos = {}; struct udf_inode_info *dinfo = UDF_I(dir); int isdotdot = child->len == 2 && child->name[0] == '.' && child->name[1] == '.'; size = udf_ext0_offset(dir) + dir->i_size; f_pos = udf_ext0_offset(dir); fibh->sbh = fibh->ebh = NULL; fibh->soffset = fibh->eoffset = f_pos & (dir->i_sb->s_blocksize - 1); if (dinfo->i_alloc_type != ICBTAG_FLAG_AD_IN_ICB) { if (inode_bmap(dir, f_pos >> dir->i_sb->s_blocksize_bits, &epos, &eloc, &elen, &offset) != (EXT_RECORDED_ALLOCATED >> 30)) goto out_err; block = udf_get_lb_pblock(dir->i_sb, &eloc, offset); if ((++offset << dir->i_sb->s_blocksize_bits) < elen) { if (dinfo->i_alloc_type == ICBTAG_FLAG_AD_SHORT) epos.offset -= sizeof(struct short_ad); else if (dinfo->i_alloc_type == ICBTAG_FLAG_AD_LONG) epos.offset -= sizeof(struct long_ad); } else offset = 0; fibh->sbh = fibh->ebh = udf_tread(dir->i_sb, block); if (!fibh->sbh) goto out_err; } fname = kmalloc(UDF_NAME_LEN, GFP_NOFS); if (!fname) goto out_err; while (f_pos < size) { fi = udf_fileident_read(dir, &f_pos, fibh, cfi, &epos, &eloc, &elen, &offset); if (!fi) goto out_err; liu = le16_to_cpu(cfi->lengthOfImpUse); lfi = cfi->lengthFileIdent; if (fibh->sbh == fibh->ebh) { nameptr = fi->fileIdent + liu; } else { int poffset; /* Unpaded ending offset */ poffset = fibh->soffset + sizeof(struct fileIdentDesc) + liu + lfi; if (poffset >= lfi) nameptr = (uint8_t *)(fibh->ebh->b_data + poffset - lfi); else { nameptr = fname; memcpy(nameptr, fi->fileIdent + liu, lfi - poffset); memcpy(nameptr + lfi - poffset, fibh->ebh->b_data, poffset); } } if ((cfi->fileCharacteristics & FID_FILE_CHAR_DELETED) != 0) { if (!UDF_QUERY_FLAG(dir->i_sb, UDF_FLAG_UNDELETE)) continue; } if ((cfi->fileCharacteristics & FID_FILE_CHAR_HIDDEN) != 0) { if (!UDF_QUERY_FLAG(dir->i_sb, UDF_FLAG_UNHIDE)) continue; } if ((cfi->fileCharacteristics & FID_FILE_CHAR_PARENT) && isdotdot) goto out_ok; if (!lfi) continue; flen = udf_get_filename(dir->i_sb, nameptr, fname, lfi); if (flen && udf_match(flen, fname, child->len, child->name)) goto out_ok; } out_err: fi = NULL; if (fibh->sbh != fibh->ebh) brelse(fibh->ebh); brelse(fibh->sbh); out_ok: brelse(epos.bh); kfree(fname); return fi; } static struct dentry *udf_lookup(struct inode *dir, struct dentry *dentry, unsigned int flags) { struct inode *inode = NULL; struct fileIdentDesc cfi; struct udf_fileident_bh fibh; if (dentry->d_name.len > UDF_NAME_LEN - 2) return ERR_PTR(-ENAMETOOLONG); #ifdef UDF_RECOVERY /* temporary shorthand for specifying files by inode number */ if (!strncmp(dentry->d_name.name, ".B=", 3)) { struct kernel_lb_addr lb = { .logicalBlockNum = 0, .partitionReferenceNum = simple_strtoul(dentry->d_name.name + 3, NULL, 0), }; inode = udf_iget(dir->i_sb, lb); if (IS_ERR(inode)) return inode; } else #endif /* UDF_RECOVERY */ if (udf_find_entry(dir, &dentry->d_name, &fibh, &cfi)) { struct kernel_lb_addr loc; if (fibh.sbh != fibh.ebh) brelse(fibh.ebh); brelse(fibh.sbh); loc = lelb_to_cpu(cfi.icb.extLocation); inode = udf_iget(dir->i_sb, &loc); if (IS_ERR(inode)) return ERR_CAST(inode); } return d_splice_alias(inode, dentry); } static struct fileIdentDesc *udf_add_entry(struct inode *dir, struct dentry *dentry, struct udf_fileident_bh *fibh, struct fileIdentDesc *cfi, int *err) { struct super_block *sb = dir->i_sb; struct fileIdentDesc *fi = NULL; unsigned char *name = NULL; int namelen; loff_t f_pos; loff_t size = udf_ext0_offset(dir) + dir->i_size; int nfidlen; uint8_t lfi; uint16_t liu; int block; struct kernel_lb_addr eloc; uint32_t elen = 0; sector_t offset; struct extent_position epos = {}; struct udf_inode_info *dinfo; fibh->sbh = fibh->ebh = NULL; name = kmalloc(UDF_NAME_LEN, GFP_NOFS); if (!name) { *err = -ENOMEM; goto out_err; } if (dentry) { if (!dentry->d_name.len) { *err = -EINVAL; goto out_err; } namelen = udf_put_filename(sb, dentry->d_name.name, name, dentry->d_name.len); if (!namelen) { *err = -ENAMETOOLONG; goto out_err; } } else { namelen = 0; } nfidlen = (sizeof(struct fileIdentDesc) + namelen + 3) & ~3; f_pos = udf_ext0_offset(dir); fibh->soffset = fibh->eoffset = f_pos & (dir->i_sb->s_blocksize - 1); dinfo = UDF_I(dir); if (dinfo->i_alloc_type != ICBTAG_FLAG_AD_IN_ICB) { if (inode_bmap(dir, f_pos >> dir->i_sb->s_blocksize_bits, &epos, &eloc, &elen, &offset) != (EXT_RECORDED_ALLOCATED >> 30)) { block = udf_get_lb_pblock(dir->i_sb, &dinfo->i_location, 0); fibh->soffset = fibh->eoffset = sb->s_blocksize; goto add; } block = udf_get_lb_pblock(dir->i_sb, &eloc, offset); if ((++offset << dir->i_sb->s_blocksize_bits) < elen) { if (dinfo->i_alloc_type == ICBTAG_FLAG_AD_SHORT) epos.offset -= sizeof(struct short_ad); else if (dinfo->i_alloc_type == ICBTAG_FLAG_AD_LONG) epos.offset -= sizeof(struct long_ad); } else offset = 0; fibh->sbh = fibh->ebh = udf_tread(dir->i_sb, block); if (!fibh->sbh) { *err = -EIO; goto out_err; } block = dinfo->i_location.logicalBlockNum; } while (f_pos < size) { fi = udf_fileident_read(dir, &f_pos, fibh, cfi, &epos, &eloc, &elen, &offset); if (!fi) { *err = -EIO; goto out_err; } liu = le16_to_cpu(cfi->lengthOfImpUse); lfi = cfi->lengthFileIdent; if ((cfi->fileCharacteristics & FID_FILE_CHAR_DELETED) != 0) { if (((sizeof(struct fileIdentDesc) + liu + lfi + 3) & ~3) == nfidlen) { cfi->descTag.tagSerialNum = cpu_to_le16(1); cfi->fileVersionNum = cpu_to_le16(1); cfi->fileCharacteristics = 0; cfi->lengthFileIdent = namelen; cfi->lengthOfImpUse = cpu_to_le16(0); if (!udf_write_fi(dir, cfi, fi, fibh, NULL, name)) goto out_ok; else { *err = -EIO; goto out_err; } } } } add: f_pos += nfidlen; if (dinfo->i_alloc_type == ICBTAG_FLAG_AD_IN_ICB && sb->s_blocksize - fibh->eoffset < nfidlen) { brelse(epos.bh); epos.bh = NULL; fibh->soffset -= udf_ext0_offset(dir); fibh->eoffset -= udf_ext0_offset(dir); f_pos -= udf_ext0_offset(dir); if (fibh->sbh != fibh->ebh) brelse(fibh->ebh); brelse(fibh->sbh); fibh->sbh = fibh->ebh = udf_expand_dir_adinicb(dir, &block, err); if (!fibh->sbh) goto out_err; epos.block = dinfo->i_location; epos.offset = udf_file_entry_alloc_offset(dir); /* Load extent udf_expand_dir_adinicb() has created */ udf_current_aext(dir, &epos, &eloc, &elen, 1); } /* Entry fits into current block? */ if (sb->s_blocksize - fibh->eoffset >= nfidlen) { fibh->soffset = fibh->eoffset; fibh->eoffset += nfidlen; if (fibh->sbh != fibh->ebh) { brelse(fibh->sbh); fibh->sbh = fibh->ebh; } if (dinfo->i_alloc_type == ICBTAG_FLAG_AD_IN_ICB) { block = dinfo->i_location.logicalBlockNum; fi = (struct fileIdentDesc *) (dinfo->i_ext.i_data + fibh->soffset - udf_ext0_offset(dir) + dinfo->i_lenEAttr); } else { block = eloc.logicalBlockNum + ((elen - 1) >> dir->i_sb->s_blocksize_bits); fi = (struct fileIdentDesc *) (fibh->sbh->b_data + fibh->soffset); } } else { /* Round up last extent in the file */ elen = (elen + sb->s_blocksize - 1) & ~(sb->s_blocksize - 1); if (dinfo->i_alloc_type == ICBTAG_FLAG_AD_SHORT) epos.offset -= sizeof(struct short_ad); else if (dinfo->i_alloc_type == ICBTAG_FLAG_AD_LONG) epos.offset -= sizeof(struct long_ad); udf_write_aext(dir, &epos, &eloc, elen, 1); dinfo->i_lenExtents = (dinfo->i_lenExtents + sb->s_blocksize - 1) & ~(sb->s_blocksize - 1); fibh->soffset = fibh->eoffset - sb->s_blocksize; fibh->eoffset += nfidlen - sb->s_blocksize; if (fibh->sbh != fibh->ebh) { brelse(fibh->sbh); fibh->sbh = fibh->ebh; } block = eloc.logicalBlockNum + ((elen - 1) >> dir->i_sb->s_blocksize_bits); fibh->ebh = udf_bread(dir, f_pos >> dir->i_sb->s_blocksize_bits, 1, err); if (!fibh->ebh) goto out_err; /* Extents could have been merged, invalidate our position */ brelse(epos.bh); epos.bh = NULL; epos.block = dinfo->i_location; epos.offset = udf_file_entry_alloc_offset(dir); if (!fibh->soffset) { /* Find the freshly allocated block */ while (udf_next_aext(dir, &epos, &eloc, &elen, 1) == (EXT_RECORDED_ALLOCATED >> 30)) ; block = eloc.logicalBlockNum + ((elen - 1) >> dir->i_sb->s_blocksize_bits); brelse(fibh->sbh); fibh->sbh = fibh->ebh; fi = (struct fileIdentDesc *)(fibh->sbh->b_data); } else { fi = (struct fileIdentDesc *) (fibh->sbh->b_data + sb->s_blocksize + fibh->soffset); } } memset(cfi, 0, sizeof(struct fileIdentDesc)); if (UDF_SB(sb)->s_udfrev >= 0x0200) udf_new_tag((char *)cfi, TAG_IDENT_FID, 3, 1, block, sizeof(struct tag)); else udf_new_tag((char *)cfi, TAG_IDENT_FID, 2, 1, block, sizeof(struct tag)); cfi->fileVersionNum = cpu_to_le16(1); cfi->lengthFileIdent = namelen; cfi->lengthOfImpUse = cpu_to_le16(0); if (!udf_write_fi(dir, cfi, fi, fibh, NULL, name)) { dir->i_size += nfidlen; if (dinfo->i_alloc_type == ICBTAG_FLAG_AD_IN_ICB) dinfo->i_lenAlloc += nfidlen; else { /* Find the last extent and truncate it to proper size */ while (udf_next_aext(dir, &epos, &eloc, &elen, 1) == (EXT_RECORDED_ALLOCATED >> 30)) ; elen -= dinfo->i_lenExtents - dir->i_size; if (dinfo->i_alloc_type == ICBTAG_FLAG_AD_SHORT) epos.offset -= sizeof(struct short_ad); else if (dinfo->i_alloc_type == ICBTAG_FLAG_AD_LONG) epos.offset -= sizeof(struct long_ad); udf_write_aext(dir, &epos, &eloc, elen, 1); dinfo->i_lenExtents = dir->i_size; } mark_inode_dirty(dir); goto out_ok; } else { *err = -EIO; goto out_err; } out_err: fi = NULL; if (fibh->sbh != fibh->ebh) brelse(fibh->ebh); brelse(fibh->sbh); out_ok: brelse(epos.bh); kfree(name); return fi; } static int udf_delete_entry(struct inode *inode, struct fileIdentDesc *fi, struct udf_fileident_bh *fibh, struct fileIdentDesc *cfi) { cfi->fileCharacteristics |= FID_FILE_CHAR_DELETED; if (UDF_QUERY_FLAG(inode->i_sb, UDF_FLAG_STRICT)) memset(&(cfi->icb), 0x00, sizeof(struct long_ad)); return udf_write_fi(inode, cfi, fi, fibh, NULL, NULL); } static int udf_add_nondir(struct dentry *dentry, struct inode *inode) { struct udf_inode_info *iinfo = UDF_I(inode); struct inode *dir = dentry->d_parent->d_inode; struct udf_fileident_bh fibh; struct fileIdentDesc cfi, *fi; int err; fi = udf_add_entry(dir, dentry, &fibh, &cfi, &err); if (unlikely(!fi)) { inode_dec_link_count(inode); unlock_new_inode(inode); iput(inode); return err; } cfi.icb.extLength = cpu_to_le32(inode->i_sb->s_blocksize); cfi.icb.extLocation = cpu_to_lelb(iinfo->i_location); *(__le32 *)((struct allocDescImpUse *)cfi.icb.impUse)->impUse = cpu_to_le32(iinfo->i_unique & 0x00000000FFFFFFFFUL); udf_write_fi(dir, &cfi, fi, &fibh, NULL, NULL); if (UDF_I(dir)->i_alloc_type == ICBTAG_FLAG_AD_IN_ICB) mark_inode_dirty(dir); if (fibh.sbh != fibh.ebh) brelse(fibh.ebh); brelse(fibh.sbh); unlock_new_inode(inode); d_instantiate(dentry, inode); return 0; } static int udf_create(struct inode *dir, struct dentry *dentry, umode_t mode, bool excl) { struct inode *inode = udf_new_inode(dir, mode); if (IS_ERR(inode)) return PTR_ERR(inode); if (UDF_I(inode)->i_alloc_type == ICBTAG_FLAG_AD_IN_ICB) inode->i_data.a_ops = &udf_adinicb_aops; else inode->i_data.a_ops = &udf_aops; inode->i_op = &udf_file_inode_operations; inode->i_fop = &udf_file_operations; mark_inode_dirty(inode); return udf_add_nondir(dentry, inode); } static int udf_tmpfile(struct inode *dir, struct dentry *dentry, umode_t mode) { struct inode *inode = udf_new_inode(dir, mode); if (IS_ERR(inode)) return PTR_ERR(inode); if (UDF_I(inode)->i_alloc_type == ICBTAG_FLAG_AD_IN_ICB) inode->i_data.a_ops = &udf_adinicb_aops; else inode->i_data.a_ops = &udf_aops; inode->i_op = &udf_file_inode_operations; inode->i_fop = &udf_file_operations; mark_inode_dirty(inode); d_tmpfile(dentry, inode); unlock_new_inode(inode); return 0; } static int udf_mknod(struct inode *dir, struct dentry *dentry, umode_t mode, dev_t rdev) { struct inode *inode; if (!old_valid_dev(rdev)) return -EINVAL; inode = udf_new_inode(dir, mode); if (IS_ERR(inode)) return PTR_ERR(inode); init_special_inode(inode, mode, rdev); return udf_add_nondir(dentry, inode); } static int udf_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode) { struct inode *inode; struct udf_fileident_bh fibh; struct fileIdentDesc cfi, *fi; int err; struct udf_inode_info *dinfo = UDF_I(dir); struct udf_inode_info *iinfo; inode = udf_new_inode(dir, S_IFDIR | mode); if (IS_ERR(inode)) return PTR_ERR(inode); iinfo = UDF_I(inode); inode->i_op = &udf_dir_inode_operations; inode->i_fop = &udf_dir_operations; fi = udf_add_entry(inode, NULL, &fibh, &cfi, &err); if (!fi) { inode_dec_link_count(inode); unlock_new_inode(inode); iput(inode); goto out; } set_nlink(inode, 2); cfi.icb.extLength = cpu_to_le32(inode->i_sb->s_blocksize); cfi.icb.extLocation = cpu_to_lelb(dinfo->i_location); *(__le32 *)((struct allocDescImpUse *)cfi.icb.impUse)->impUse = cpu_to_le32(dinfo->i_unique & 0x00000000FFFFFFFFUL); cfi.fileCharacteristics = FID_FILE_CHAR_DIRECTORY | FID_FILE_CHAR_PARENT; udf_write_fi(inode, &cfi, fi, &fibh, NULL, NULL); brelse(fibh.sbh); mark_inode_dirty(inode); fi = udf_add_entry(dir, dentry, &fibh, &cfi, &err); if (!fi) { clear_nlink(inode); mark_inode_dirty(inode); unlock_new_inode(inode); iput(inode); goto out; } cfi.icb.extLength = cpu_to_le32(inode->i_sb->s_blocksize); cfi.icb.extLocation = cpu_to_lelb(iinfo->i_location); *(__le32 *)((struct allocDescImpUse *)cfi.icb.impUse)->impUse = cpu_to_le32(iinfo->i_unique & 0x00000000FFFFFFFFUL); cfi.fileCharacteristics |= FID_FILE_CHAR_DIRECTORY; udf_write_fi(dir, &cfi, fi, &fibh, NULL, NULL); inc_nlink(dir); mark_inode_dirty(dir); unlock_new_inode(inode); d_instantiate(dentry, inode); if (fibh.sbh != fibh.ebh) brelse(fibh.ebh); brelse(fibh.sbh); err = 0; out: return err; } static int empty_dir(struct inode *dir) { struct fileIdentDesc *fi, cfi; struct udf_fileident_bh fibh; loff_t f_pos; loff_t size = udf_ext0_offset(dir) + dir->i_size; int block; struct kernel_lb_addr eloc; uint32_t elen; sector_t offset; struct extent_position epos = {}; struct udf_inode_info *dinfo = UDF_I(dir); f_pos = udf_ext0_offset(dir); fibh.soffset = fibh.eoffset = f_pos & (dir->i_sb->s_blocksize - 1); if (dinfo->i_alloc_type == ICBTAG_FLAG_AD_IN_ICB) fibh.sbh = fibh.ebh = NULL; else if (inode_bmap(dir, f_pos >> dir->i_sb->s_blocksize_bits, &epos, &eloc, &elen, &offset) == (EXT_RECORDED_ALLOCATED >> 30)) { block = udf_get_lb_pblock(dir->i_sb, &eloc, offset); if ((++offset << dir->i_sb->s_blocksize_bits) < elen) { if (dinfo->i_alloc_type == ICBTAG_FLAG_AD_SHORT) epos.offset -= sizeof(struct short_ad); else if (dinfo->i_alloc_type == ICBTAG_FLAG_AD_LONG) epos.offset -= sizeof(struct long_ad); } else offset = 0; fibh.sbh = fibh.ebh = udf_tread(dir->i_sb, block); if (!fibh.sbh) { brelse(epos.bh); return 0; } } else { brelse(epos.bh); return 0; } while (f_pos < size) { fi = udf_fileident_read(dir, &f_pos, &fibh, &cfi, &epos, &eloc, &elen, &offset); if (!fi) { if (fibh.sbh != fibh.ebh) brelse(fibh.ebh); brelse(fibh.sbh); brelse(epos.bh); return 0; } if (cfi.lengthFileIdent && (cfi.fileCharacteristics & FID_FILE_CHAR_DELETED) == 0) { if (fibh.sbh != fibh.ebh) brelse(fibh.ebh); brelse(fibh.sbh); brelse(epos.bh); return 0; } } if (fibh.sbh != fibh.ebh) brelse(fibh.ebh); brelse(fibh.sbh); brelse(epos.bh); return 1; } static int udf_rmdir(struct inode *dir, struct dentry *dentry) { int retval; struct inode *inode = dentry->d_inode; struct udf_fileident_bh fibh; struct fileIdentDesc *fi, cfi; struct kernel_lb_addr tloc; retval = -ENOENT; fi = udf_find_entry(dir, &dentry->d_name, &fibh, &cfi); if (!fi) goto out; retval = -EIO; tloc = lelb_to_cpu(cfi.icb.extLocation); if (udf_get_lb_pblock(dir->i_sb, &tloc, 0) != inode->i_ino) goto end_rmdir; retval = -ENOTEMPTY; if (!empty_dir(inode)) goto end_rmdir; retval = udf_delete_entry(dir, fi, &fibh, &cfi); if (retval) goto end_rmdir; if (inode->i_nlink != 2) udf_warn(inode->i_sb, "empty directory has nlink != 2 (%d)\n", inode->i_nlink); clear_nlink(inode); inode->i_size = 0; inode_dec_link_count(dir); inode->i_ctime = dir->i_ctime = dir->i_mtime = current_fs_time(dir->i_sb); mark_inode_dirty(dir); end_rmdir: if (fibh.sbh != fibh.ebh) brelse(fibh.ebh); brelse(fibh.sbh); out: return retval; } static int udf_unlink(struct inode *dir, struct dentry *dentry) { int retval; struct inode *inode = dentry->d_inode; struct udf_fileident_bh fibh; struct fileIdentDesc *fi; struct fileIdentDesc cfi; struct kernel_lb_addr tloc; retval = -ENOENT; fi = udf_find_entry(dir, &dentry->d_name, &fibh, &cfi); if (!fi) goto out; retval = -EIO; tloc = lelb_to_cpu(cfi.icb.extLocation); if (udf_get_lb_pblock(dir->i_sb, &tloc, 0) != inode->i_ino) goto end_unlink; if (!inode->i_nlink) { udf_debug("Deleting nonexistent file (%lu), %d\n", inode->i_ino, inode->i_nlink); set_nlink(inode, 1); } retval = udf_delete_entry(dir, fi, &fibh, &cfi); if (retval) goto end_unlink; dir->i_ctime = dir->i_mtime = current_fs_time(dir->i_sb); mark_inode_dirty(dir); inode_dec_link_count(inode); inode->i_ctime = dir->i_ctime; retval = 0; end_unlink: if (fibh.sbh != fibh.ebh) brelse(fibh.ebh); brelse(fibh.sbh); out: return retval; } static int udf_symlink(struct inode *dir, struct dentry *dentry, const char *symname) { struct inode *inode = udf_new_inode(dir, S_IFLNK | S_IRWXUGO); struct pathComponent *pc; const char *compstart; struct extent_position epos = {}; int eoffset, elen = 0; uint8_t *ea; int err; int block; unsigned char *name = NULL; int namelen; struct udf_inode_info *iinfo; struct super_block *sb = dir->i_sb; if (IS_ERR(inode)) return PTR_ERR(inode); iinfo = UDF_I(inode); down_write(&iinfo->i_data_sem); name = kmalloc(UDF_NAME_LEN, GFP_NOFS); if (!name) { err = -ENOMEM; goto out_no_entry; } inode->i_data.a_ops = &udf_symlink_aops; inode->i_op = &udf_symlink_inode_operations; if (iinfo->i_alloc_type != ICBTAG_FLAG_AD_IN_ICB) { struct kernel_lb_addr eloc; uint32_t bsize; block = udf_new_block(sb, inode, iinfo->i_location.partitionReferenceNum, iinfo->i_location.logicalBlockNum, &err); if (!block) goto out_no_entry; epos.block = iinfo->i_location; epos.offset = udf_file_entry_alloc_offset(inode); epos.bh = NULL; eloc.logicalBlockNum = block; eloc.partitionReferenceNum = iinfo->i_location.partitionReferenceNum; bsize = sb->s_blocksize; iinfo->i_lenExtents = bsize; udf_add_aext(inode, &epos, &eloc, bsize, 0); brelse(epos.bh); block = udf_get_pblock(sb, block, iinfo->i_location.partitionReferenceNum, 0); epos.bh = udf_tgetblk(sb, block); lock_buffer(epos.bh); memset(epos.bh->b_data, 0x00, bsize); set_buffer_uptodate(epos.bh); unlock_buffer(epos.bh); mark_buffer_dirty_inode(epos.bh, inode); ea = epos.bh->b_data + udf_ext0_offset(inode); } else ea = iinfo->i_ext.i_data + iinfo->i_lenEAttr; eoffset = sb->s_blocksize - udf_ext0_offset(inode); pc = (struct pathComponent *)ea; if (*symname == '/') { do { symname++; } while (*symname == '/'); pc->componentType = 1; pc->lengthComponentIdent = 0; pc->componentFileVersionNum = 0; elen += sizeof(struct pathComponent); } err = -ENAMETOOLONG; while (*symname) { if (elen + sizeof(struct pathComponent) > eoffset) goto out_no_entry; pc = (struct pathComponent *)(ea + elen); compstart = symname; do { symname++; } while (*symname && *symname != '/'); pc->componentType = 5; pc->lengthComponentIdent = 0; pc->componentFileVersionNum = 0; if (compstart[0] == '.') { if ((symname - compstart) == 1) pc->componentType = 4; else if ((symname - compstart) == 2 && compstart[1] == '.') pc->componentType = 3; } if (pc->componentType == 5) { namelen = udf_put_filename(sb, compstart, name, symname - compstart); if (!namelen) goto out_no_entry; if (elen + sizeof(struct pathComponent) + namelen > eoffset) goto out_no_entry; else pc->lengthComponentIdent = namelen; memcpy(pc->componentIdent, name, namelen); } elen += sizeof(struct pathComponent) + pc->lengthComponentIdent; if (*symname) { do { symname++; } while (*symname == '/'); } } brelse(epos.bh); inode->i_size = elen; if (iinfo->i_alloc_type == ICBTAG_FLAG_AD_IN_ICB) iinfo->i_lenAlloc = inode->i_size; else udf_truncate_tail_extent(inode); mark_inode_dirty(inode); up_write(&iinfo->i_data_sem); err = udf_add_nondir(dentry, inode); out: kfree(name); return err; out_no_entry: up_write(&iinfo->i_data_sem); inode_dec_link_count(inode); unlock_new_inode(inode); iput(inode); goto out; } static int udf_link(struct dentry *old_dentry, struct inode *dir, struct dentry *dentry) { struct inode *inode = old_dentry->d_inode; struct udf_fileident_bh fibh; struct fileIdentDesc cfi, *fi; int err; fi = udf_add_entry(dir, dentry, &fibh, &cfi, &err); if (!fi) { return err; } cfi.icb.extLength = cpu_to_le32(inode->i_sb->s_blocksize); cfi.icb.extLocation = cpu_to_lelb(UDF_I(inode)->i_location); if (UDF_SB(inode->i_sb)->s_lvid_bh) { *(__le32 *)((struct allocDescImpUse *)cfi.icb.impUse)->impUse = cpu_to_le32(lvid_get_unique_id(inode->i_sb)); } udf_write_fi(dir, &cfi, fi, &fibh, NULL, NULL); if (UDF_I(dir)->i_alloc_type == ICBTAG_FLAG_AD_IN_ICB) mark_inode_dirty(dir); if (fibh.sbh != fibh.ebh) brelse(fibh.ebh); brelse(fibh.sbh); inc_nlink(inode); inode->i_ctime = current_fs_time(inode->i_sb); mark_inode_dirty(inode); ihold(inode); d_instantiate(dentry, inode); return 0; } /* Anybody can rename anything with this: the permission checks are left to the * higher-level routines. */ static int udf_rename(struct inode *old_dir, struct dentry *old_dentry, struct inode *new_dir, struct dentry *new_dentry) { struct inode *old_inode = old_dentry->d_inode; struct inode *new_inode = new_dentry->d_inode; struct udf_fileident_bh ofibh, nfibh; struct fileIdentDesc *ofi = NULL, *nfi = NULL, *dir_fi = NULL; struct fileIdentDesc ocfi, ncfi; struct buffer_head *dir_bh = NULL; int retval = -ENOENT; struct kernel_lb_addr tloc; struct udf_inode_info *old_iinfo = UDF_I(old_inode); ofi = udf_find_entry(old_dir, &old_dentry->d_name, &ofibh, &ocfi); if (ofi) { if (ofibh.sbh != ofibh.ebh) brelse(ofibh.ebh); brelse(ofibh.sbh); } tloc = lelb_to_cpu(ocfi.icb.extLocation); if (!ofi || udf_get_lb_pblock(old_dir->i_sb, &tloc, 0) != old_inode->i_ino) goto end_rename; nfi = udf_find_entry(new_dir, &new_dentry->d_name, &nfibh, &ncfi); if (nfi) { if (!new_inode) { if (nfibh.sbh != nfibh.ebh) brelse(nfibh.ebh); brelse(nfibh.sbh); nfi = NULL; } } if (S_ISDIR(old_inode->i_mode)) { int offset = udf_ext0_offset(old_inode); if (new_inode) { retval = -ENOTEMPTY; if (!empty_dir(new_inode)) goto end_rename; } retval = -EIO; if (old_iinfo->i_alloc_type == ICBTAG_FLAG_AD_IN_ICB) { dir_fi = udf_get_fileident( old_iinfo->i_ext.i_data - (old_iinfo->i_efe ? sizeof(struct extendedFileEntry) : sizeof(struct fileEntry)), old_inode->i_sb->s_blocksize, &offset); } else { dir_bh = udf_bread(old_inode, 0, 0, &retval); if (!dir_bh) goto end_rename; dir_fi = udf_get_fileident(dir_bh->b_data, old_inode->i_sb->s_blocksize, &offset); } if (!dir_fi) goto end_rename; tloc = lelb_to_cpu(dir_fi->icb.extLocation); if (udf_get_lb_pblock(old_inode->i_sb, &tloc, 0) != old_dir->i_ino) goto end_rename; } if (!nfi) { nfi = udf_add_entry(new_dir, new_dentry, &nfibh, &ncfi, &retval); if (!nfi) goto end_rename; } /* * Like most other Unix systems, set the ctime for inodes on a * rename. */ old_inode->i_ctime = current_fs_time(old_inode->i_sb); mark_inode_dirty(old_inode); /* * ok, that's it */ ncfi.fileVersionNum = ocfi.fileVersionNum; ncfi.fileCharacteristics = ocfi.fileCharacteristics; memcpy(&(ncfi.icb), &(ocfi.icb), sizeof(struct long_ad)); udf_write_fi(new_dir, &ncfi, nfi, &nfibh, NULL, NULL); /* The old fid may have moved - find it again */ ofi = udf_find_entry(old_dir, &old_dentry->d_name, &ofibh, &ocfi); udf_delete_entry(old_dir, ofi, &ofibh, &ocfi); if (new_inode) { new_inode->i_ctime = current_fs_time(new_inode->i_sb); inode_dec_link_count(new_inode); } old_dir->i_ctime = old_dir->i_mtime = current_fs_time(old_dir->i_sb); mark_inode_dirty(old_dir); if (dir_fi) { dir_fi->icb.extLocation = cpu_to_lelb(UDF_I(new_dir)->i_location); udf_update_tag((char *)dir_fi, (sizeof(struct fileIdentDesc) + le16_to_cpu(dir_fi->lengthOfImpUse) + 3) & ~3); if (old_iinfo->i_alloc_type == ICBTAG_FLAG_AD_IN_ICB) mark_inode_dirty(old_inode); else mark_buffer_dirty_inode(dir_bh, old_inode); inode_dec_link_count(old_dir); if (new_inode) inode_dec_link_count(new_inode); else { inc_nlink(new_dir); mark_inode_dirty(new_dir); } } if (ofi) { if (ofibh.sbh != ofibh.ebh) brelse(ofibh.ebh); brelse(ofibh.sbh); } retval = 0; end_rename: brelse(dir_bh); if (nfi) { if (nfibh.sbh != nfibh.ebh) brelse(nfibh.ebh); brelse(nfibh.sbh); } return retval; } static struct dentry *udf_get_parent(struct dentry *child) { struct kernel_lb_addr tloc; struct inode *inode = NULL; struct qstr dotdot = QSTR_INIT("..", 2); struct fileIdentDesc cfi; struct udf_fileident_bh fibh; if (!udf_find_entry(child->d_inode, &dotdot, &fibh, &cfi)) return ERR_PTR(-EACCES); if (fibh.sbh != fibh.ebh) brelse(fibh.ebh); brelse(fibh.sbh); tloc = lelb_to_cpu(cfi.icb.extLocation); inode = udf_iget(child->d_inode->i_sb, &tloc); if (IS_ERR(inode)) return ERR_CAST(inode); return d_obtain_alias(inode); } static struct dentry *udf_nfs_get_inode(struct super_block *sb, u32 block, u16 partref, __u32 generation) { struct inode *inode; struct kernel_lb_addr loc; if (block == 0) return ERR_PTR(-ESTALE); loc.logicalBlockNum = block; loc.partitionReferenceNum = partref; inode = udf_iget(sb, &loc); if (IS_ERR(inode)) return ERR_CAST(inode); if (generation && inode->i_generation != generation) { iput(inode); return ERR_PTR(-ESTALE); } return d_obtain_alias(inode); } static struct dentry *udf_fh_to_dentry(struct super_block *sb, struct fid *fid, int fh_len, int fh_type) { if ((fh_len != 3 && fh_len != 5) || (fh_type != FILEID_UDF_WITH_PARENT && fh_type != FILEID_UDF_WITHOUT_PARENT)) return NULL; return udf_nfs_get_inode(sb, fid->udf.block, fid->udf.partref, fid->udf.generation); } static struct dentry *udf_fh_to_parent(struct super_block *sb, struct fid *fid, int fh_len, int fh_type) { if (fh_len != 5 || fh_type != FILEID_UDF_WITH_PARENT) return NULL; return udf_nfs_get_inode(sb, fid->udf.parent_block, fid->udf.parent_partref, fid->udf.parent_generation); } static int udf_encode_fh(struct inode *inode, __u32 *fh, int *lenp, struct inode *parent) { int len = *lenp; struct kernel_lb_addr location = UDF_I(inode)->i_location; struct fid *fid = (struct fid *)fh; int type = FILEID_UDF_WITHOUT_PARENT; if (parent && (len < 5)) { *lenp = 5; return FILEID_INVALID; } else if (len < 3) { *lenp = 3; return FILEID_INVALID; } *lenp = 3; fid->udf.block = location.logicalBlockNum; fid->udf.partref = location.partitionReferenceNum; fid->udf.parent_partref = 0; fid->udf.generation = inode->i_generation; if (parent) { location = UDF_I(parent)->i_location; fid->udf.parent_block = location.logicalBlockNum; fid->udf.parent_partref = location.partitionReferenceNum; fid->udf.parent_generation = inode->i_generation; *lenp = 5; type = FILEID_UDF_WITH_PARENT; } return type; } const struct export_operations udf_export_ops = { .encode_fh = udf_encode_fh, .fh_to_dentry = udf_fh_to_dentry, .fh_to_parent = udf_fh_to_parent, .get_parent = udf_get_parent, }; const struct inode_operations udf_dir_inode_operations = { .lookup = udf_lookup, .create = udf_create, .link = udf_link, .unlink = udf_unlink, .symlink = udf_symlink, .mkdir = udf_mkdir, .rmdir = udf_rmdir, .mknod = udf_mknod, .rename = udf_rename, .tmpfile = udf_tmpfile, }; const struct inode_operations udf_symlink_inode_operations = { .readlink = generic_readlink, .follow_link = page_follow_link_light, .put_link = page_put_link, };
./CrossVul/dataset_final_sorted/CWE-17/c/bad_2415_1
crossvul-cpp_data_bad_1482_1
/* * INET An implementation of the TCP/IP protocol suite for the LINUX * operating system. INET is implemented using the BSD Socket * interface as the means of communication with the user level. * * The IP forwarding functionality. * * Authors: see ip.c * * Fixes: * Many : Split from ip.c , see ip_input.c for * history. * Dave Gregorich : NULL ip_rt_put fix for multicast * routing. * Jos Vos : Add call_out_firewall before sending, * use output device for accounting. * Jos Vos : Call forward firewall after routing * (always use output device). * Mike McLagan : Routing by source */ #include <linux/types.h> #include <linux/mm.h> #include <linux/skbuff.h> #include <linux/ip.h> #include <linux/icmp.h> #include <linux/netdevice.h> #include <linux/slab.h> #include <net/sock.h> #include <net/ip.h> #include <net/tcp.h> #include <net/udp.h> #include <net/icmp.h> #include <linux/tcp.h> #include <linux/udp.h> #include <linux/netfilter_ipv4.h> #include <net/checksum.h> #include <linux/route.h> #include <net/route.h> #include <net/xfrm.h> static bool ip_may_fragment(const struct sk_buff *skb) { return unlikely((ip_hdr(skb)->frag_off & htons(IP_DF)) == 0) || skb->ignore_df; } static bool ip_exceeds_mtu(const struct sk_buff *skb, unsigned int mtu) { if (skb->len <= mtu) return false; if (skb_is_gso(skb) && skb_gso_network_seglen(skb) <= mtu) return false; return true; } static int ip_forward_finish(struct sk_buff *skb) { struct ip_options *opt = &(IPCB(skb)->opt); IP_INC_STATS_BH(dev_net(skb_dst(skb)->dev), IPSTATS_MIB_OUTFORWDATAGRAMS); IP_ADD_STATS_BH(dev_net(skb_dst(skb)->dev), IPSTATS_MIB_OUTOCTETS, skb->len); if (unlikely(opt->optlen)) ip_forward_options(skb); return dst_output(skb); } int ip_forward(struct sk_buff *skb) { u32 mtu; struct iphdr *iph; /* Our header */ struct rtable *rt; /* Route we use */ struct ip_options *opt = &(IPCB(skb)->opt); /* that should never happen */ if (skb->pkt_type != PACKET_HOST) goto drop; if (skb_warn_if_lro(skb)) goto drop; if (!xfrm4_policy_check(NULL, XFRM_POLICY_FWD, skb)) goto drop; if (IPCB(skb)->opt.router_alert && ip_call_ra_chain(skb)) return NET_RX_SUCCESS; skb_forward_csum(skb); /* * According to the RFC, we must first decrease the TTL field. If * that reaches zero, we must reply an ICMP control message telling * that the packet's lifetime expired. */ if (ip_hdr(skb)->ttl <= 1) goto too_many_hops; if (!xfrm4_route_forward(skb)) goto drop; rt = skb_rtable(skb); if (opt->is_strictroute && rt->rt_uses_gateway) goto sr_failed; IPCB(skb)->flags |= IPSKB_FORWARDED; mtu = ip_dst_mtu_maybe_forward(&rt->dst, true); if (!ip_may_fragment(skb) && ip_exceeds_mtu(skb, mtu)) { IP_INC_STATS(dev_net(rt->dst.dev), IPSTATS_MIB_FRAGFAILS); icmp_send(skb, ICMP_DEST_UNREACH, ICMP_FRAG_NEEDED, htonl(mtu)); goto drop; } /* We are about to mangle packet. Copy it! */ if (skb_cow(skb, LL_RESERVED_SPACE(rt->dst.dev)+rt->dst.header_len)) goto drop; iph = ip_hdr(skb); /* Decrease ttl after skb cow done */ ip_decrease_ttl(iph); /* * We now generate an ICMP HOST REDIRECT giving the route * we calculated. */ if (rt->rt_flags&RTCF_DOREDIRECT && !opt->srr && !skb_sec_path(skb)) ip_rt_send_redirect(skb); skb->priority = rt_tos2priority(iph->tos); return NF_HOOK(NFPROTO_IPV4, NF_INET_FORWARD, skb, skb->dev, rt->dst.dev, ip_forward_finish); sr_failed: /* * Strict routing permits no gatewaying */ icmp_send(skb, ICMP_DEST_UNREACH, ICMP_SR_FAILED, 0); goto drop; too_many_hops: /* Tell the sender its packet died... */ IP_INC_STATS_BH(dev_net(skb_dst(skb)->dev), IPSTATS_MIB_INHDRERRORS); icmp_send(skb, ICMP_TIME_EXCEEDED, ICMP_EXC_TTL, 0); drop: kfree_skb(skb); return NET_RX_DROP; }
./CrossVul/dataset_final_sorted/CWE-17/c/bad_1482_1
crossvul-cpp_data_bad_2348_5
/* * Copyright (C) 1991, 1992 Linus Torvalds * Copyright (C) 2000, 2001, 2002 Andi Kleen, SuSE Labs * * Pentium III FXSR, SSE support * Gareth Hughes <gareth@valinux.com>, May 2000 */ /* * Handle hardware traps and faults. */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/context_tracking.h> #include <linux/interrupt.h> #include <linux/kallsyms.h> #include <linux/spinlock.h> #include <linux/kprobes.h> #include <linux/uaccess.h> #include <linux/kdebug.h> #include <linux/kgdb.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/ptrace.h> #include <linux/uprobes.h> #include <linux/string.h> #include <linux/delay.h> #include <linux/errno.h> #include <linux/kexec.h> #include <linux/sched.h> #include <linux/timer.h> #include <linux/init.h> #include <linux/bug.h> #include <linux/nmi.h> #include <linux/mm.h> #include <linux/smp.h> #include <linux/io.h> #ifdef CONFIG_EISA #include <linux/ioport.h> #include <linux/eisa.h> #endif #if defined(CONFIG_EDAC) #include <linux/edac.h> #endif #include <asm/kmemcheck.h> #include <asm/stacktrace.h> #include <asm/processor.h> #include <asm/debugreg.h> #include <linux/atomic.h> #include <asm/ftrace.h> #include <asm/traps.h> #include <asm/desc.h> #include <asm/i387.h> #include <asm/fpu-internal.h> #include <asm/mce.h> #include <asm/fixmap.h> #include <asm/mach_traps.h> #include <asm/alternative.h> #ifdef CONFIG_X86_64 #include <asm/x86_init.h> #include <asm/pgalloc.h> #include <asm/proto.h> /* No need to be aligned, but done to keep all IDTs defined the same way. */ gate_desc debug_idt_table[NR_VECTORS] __page_aligned_bss; #else #include <asm/processor-flags.h> #include <asm/setup.h> asmlinkage int system_call(void); #endif /* Must be page-aligned because the real IDT is used in a fixmap. */ gate_desc idt_table[NR_VECTORS] __page_aligned_bss; DECLARE_BITMAP(used_vectors, NR_VECTORS); EXPORT_SYMBOL_GPL(used_vectors); static inline void conditional_sti(struct pt_regs *regs) { if (regs->flags & X86_EFLAGS_IF) local_irq_enable(); } static inline void preempt_conditional_sti(struct pt_regs *regs) { preempt_count_inc(); if (regs->flags & X86_EFLAGS_IF) local_irq_enable(); } static inline void conditional_cli(struct pt_regs *regs) { if (regs->flags & X86_EFLAGS_IF) local_irq_disable(); } static inline void preempt_conditional_cli(struct pt_regs *regs) { if (regs->flags & X86_EFLAGS_IF) local_irq_disable(); preempt_count_dec(); } static nokprobe_inline int do_trap_no_signal(struct task_struct *tsk, int trapnr, char *str, struct pt_regs *regs, long error_code) { #ifdef CONFIG_X86_32 if (regs->flags & X86_VM_MASK) { /* * Traps 0, 1, 3, 4, and 5 should be forwarded to vm86. * On nmi (interrupt 2), do_trap should not be called. */ if (trapnr < X86_TRAP_UD) { if (!handle_vm86_trap((struct kernel_vm86_regs *) regs, error_code, trapnr)) return 0; } return -1; } #endif if (!user_mode(regs)) { if (!fixup_exception(regs)) { tsk->thread.error_code = error_code; tsk->thread.trap_nr = trapnr; die(str, regs, error_code); } return 0; } return -1; } static siginfo_t *fill_trap_info(struct pt_regs *regs, int signr, int trapnr, siginfo_t *info) { unsigned long siaddr; int sicode; switch (trapnr) { default: return SEND_SIG_PRIV; case X86_TRAP_DE: sicode = FPE_INTDIV; siaddr = uprobe_get_trap_addr(regs); break; case X86_TRAP_UD: sicode = ILL_ILLOPN; siaddr = uprobe_get_trap_addr(regs); break; case X86_TRAP_AC: sicode = BUS_ADRALN; siaddr = 0; break; } info->si_signo = signr; info->si_errno = 0; info->si_code = sicode; info->si_addr = (void __user *)siaddr; return info; } static void do_trap(int trapnr, int signr, char *str, struct pt_regs *regs, long error_code, siginfo_t *info) { struct task_struct *tsk = current; if (!do_trap_no_signal(tsk, trapnr, str, regs, error_code)) return; /* * We want error_code and trap_nr set for userspace faults and * kernelspace faults which result in die(), but not * kernelspace faults which are fixed up. die() gives the * process no chance to handle the signal and notice the * kernel fault information, so that won't result in polluting * the information about previously queued, but not yet * delivered, faults. See also do_general_protection below. */ tsk->thread.error_code = error_code; tsk->thread.trap_nr = trapnr; #ifdef CONFIG_X86_64 if (show_unhandled_signals && unhandled_signal(tsk, signr) && printk_ratelimit()) { pr_info("%s[%d] trap %s ip:%lx sp:%lx error:%lx", tsk->comm, tsk->pid, str, regs->ip, regs->sp, error_code); print_vma_addr(" in ", regs->ip); pr_cont("\n"); } #endif force_sig_info(signr, info ?: SEND_SIG_PRIV, tsk); } NOKPROBE_SYMBOL(do_trap); static void do_error_trap(struct pt_regs *regs, long error_code, char *str, unsigned long trapnr, int signr) { enum ctx_state prev_state = exception_enter(); siginfo_t info; if (notify_die(DIE_TRAP, str, regs, error_code, trapnr, signr) != NOTIFY_STOP) { conditional_sti(regs); do_trap(trapnr, signr, str, regs, error_code, fill_trap_info(regs, signr, trapnr, &info)); } exception_exit(prev_state); } #define DO_ERROR(trapnr, signr, str, name) \ dotraplinkage void do_##name(struct pt_regs *regs, long error_code) \ { \ do_error_trap(regs, error_code, str, trapnr, signr); \ } DO_ERROR(X86_TRAP_DE, SIGFPE, "divide error", divide_error) DO_ERROR(X86_TRAP_OF, SIGSEGV, "overflow", overflow) DO_ERROR(X86_TRAP_BR, SIGSEGV, "bounds", bounds) DO_ERROR(X86_TRAP_UD, SIGILL, "invalid opcode", invalid_op) DO_ERROR(X86_TRAP_OLD_MF, SIGFPE, "coprocessor segment overrun",coprocessor_segment_overrun) DO_ERROR(X86_TRAP_TS, SIGSEGV, "invalid TSS", invalid_TSS) DO_ERROR(X86_TRAP_NP, SIGBUS, "segment not present", segment_not_present) #ifdef CONFIG_X86_32 DO_ERROR(X86_TRAP_SS, SIGBUS, "stack segment", stack_segment) #endif DO_ERROR(X86_TRAP_AC, SIGBUS, "alignment check", alignment_check) #ifdef CONFIG_X86_64 /* Runs on IST stack */ dotraplinkage void do_stack_segment(struct pt_regs *regs, long error_code) { enum ctx_state prev_state; prev_state = exception_enter(); if (notify_die(DIE_TRAP, "stack segment", regs, error_code, X86_TRAP_SS, SIGBUS) != NOTIFY_STOP) { preempt_conditional_sti(regs); do_trap(X86_TRAP_SS, SIGBUS, "stack segment", regs, error_code, NULL); preempt_conditional_cli(regs); } exception_exit(prev_state); } dotraplinkage void do_double_fault(struct pt_regs *regs, long error_code) { static const char str[] = "double fault"; struct task_struct *tsk = current; #ifdef CONFIG_X86_ESPFIX64 extern unsigned char native_irq_return_iret[]; /* * If IRET takes a non-IST fault on the espfix64 stack, then we * end up promoting it to a doublefault. In that case, modify * the stack to make it look like we just entered the #GP * handler from user space, similar to bad_iret. */ if (((long)regs->sp >> PGDIR_SHIFT) == ESPFIX_PGD_ENTRY && regs->cs == __KERNEL_CS && regs->ip == (unsigned long)native_irq_return_iret) { struct pt_regs *normal_regs = task_pt_regs(current); /* Fake a #GP(0) from userspace. */ memmove(&normal_regs->ip, (void *)regs->sp, 5*8); normal_regs->orig_ax = 0; /* Missing (lost) #GP error code */ regs->ip = (unsigned long)general_protection; regs->sp = (unsigned long)&normal_regs->orig_ax; return; } #endif exception_enter(); /* Return not checked because double check cannot be ignored */ notify_die(DIE_TRAP, str, regs, error_code, X86_TRAP_DF, SIGSEGV); tsk->thread.error_code = error_code; tsk->thread.trap_nr = X86_TRAP_DF; #ifdef CONFIG_DOUBLEFAULT df_debug(regs, error_code); #endif /* * This is always a kernel trap and never fixable (and thus must * never return). */ for (;;) die(str, regs, error_code); } #endif dotraplinkage void do_general_protection(struct pt_regs *regs, long error_code) { struct task_struct *tsk; enum ctx_state prev_state; prev_state = exception_enter(); conditional_sti(regs); #ifdef CONFIG_X86_32 if (regs->flags & X86_VM_MASK) { local_irq_enable(); handle_vm86_fault((struct kernel_vm86_regs *) regs, error_code); goto exit; } #endif tsk = current; if (!user_mode(regs)) { if (fixup_exception(regs)) goto exit; tsk->thread.error_code = error_code; tsk->thread.trap_nr = X86_TRAP_GP; if (notify_die(DIE_GPF, "general protection fault", regs, error_code, X86_TRAP_GP, SIGSEGV) != NOTIFY_STOP) die("general protection fault", regs, error_code); goto exit; } tsk->thread.error_code = error_code; tsk->thread.trap_nr = X86_TRAP_GP; if (show_unhandled_signals && unhandled_signal(tsk, SIGSEGV) && printk_ratelimit()) { pr_info("%s[%d] general protection ip:%lx sp:%lx error:%lx", tsk->comm, task_pid_nr(tsk), regs->ip, regs->sp, error_code); print_vma_addr(" in ", regs->ip); pr_cont("\n"); } force_sig_info(SIGSEGV, SEND_SIG_PRIV, tsk); exit: exception_exit(prev_state); } NOKPROBE_SYMBOL(do_general_protection); /* May run on IST stack. */ dotraplinkage void notrace do_int3(struct pt_regs *regs, long error_code) { enum ctx_state prev_state; #ifdef CONFIG_DYNAMIC_FTRACE /* * ftrace must be first, everything else may cause a recursive crash. * See note by declaration of modifying_ftrace_code in ftrace.c */ if (unlikely(atomic_read(&modifying_ftrace_code)) && ftrace_int3_handler(regs)) return; #endif if (poke_int3_handler(regs)) return; prev_state = exception_enter(); #ifdef CONFIG_KGDB_LOW_LEVEL_TRAP if (kgdb_ll_trap(DIE_INT3, "int3", regs, error_code, X86_TRAP_BP, SIGTRAP) == NOTIFY_STOP) goto exit; #endif /* CONFIG_KGDB_LOW_LEVEL_TRAP */ #ifdef CONFIG_KPROBES if (kprobe_int3_handler(regs)) goto exit; #endif if (notify_die(DIE_INT3, "int3", regs, error_code, X86_TRAP_BP, SIGTRAP) == NOTIFY_STOP) goto exit; /* * Let others (NMI) know that the debug stack is in use * as we may switch to the interrupt stack. */ debug_stack_usage_inc(); preempt_conditional_sti(regs); do_trap(X86_TRAP_BP, SIGTRAP, "int3", regs, error_code, NULL); preempt_conditional_cli(regs); debug_stack_usage_dec(); exit: exception_exit(prev_state); } NOKPROBE_SYMBOL(do_int3); #ifdef CONFIG_X86_64 /* * Help handler running on IST stack to switch back to user stack * for scheduling or signal handling. The actual stack switch is done in * entry.S */ asmlinkage __visible struct pt_regs *sync_regs(struct pt_regs *eregs) { struct pt_regs *regs = eregs; /* Did already sync */ if (eregs == (struct pt_regs *)eregs->sp) ; /* Exception from user space */ else if (user_mode(eregs)) regs = task_pt_regs(current); /* * Exception from kernel and interrupts are enabled. Move to * kernel process stack. */ else if (eregs->flags & X86_EFLAGS_IF) regs = (struct pt_regs *)(eregs->sp -= sizeof(struct pt_regs)); if (eregs != regs) *regs = *eregs; return regs; } NOKPROBE_SYMBOL(sync_regs); #endif /* * Our handling of the processor debug registers is non-trivial. * We do not clear them on entry and exit from the kernel. Therefore * it is possible to get a watchpoint trap here from inside the kernel. * However, the code in ./ptrace.c has ensured that the user can * only set watchpoints on userspace addresses. Therefore the in-kernel * watchpoint trap can only occur in code which is reading/writing * from user space. Such code must not hold kernel locks (since it * can equally take a page fault), therefore it is safe to call * force_sig_info even though that claims and releases locks. * * Code in ./signal.c ensures that the debug control register * is restored before we deliver any signal, and therefore that * user code runs with the correct debug control register even though * we clear it here. * * Being careful here means that we don't have to be as careful in a * lot of more complicated places (task switching can be a bit lazy * about restoring all the debug state, and ptrace doesn't have to * find every occurrence of the TF bit that could be saved away even * by user code) * * May run on IST stack. */ dotraplinkage void do_debug(struct pt_regs *regs, long error_code) { struct task_struct *tsk = current; enum ctx_state prev_state; int user_icebp = 0; unsigned long dr6; int si_code; prev_state = exception_enter(); get_debugreg(dr6, 6); /* Filter out all the reserved bits which are preset to 1 */ dr6 &= ~DR6_RESERVED; /* * If dr6 has no reason to give us about the origin of this trap, * then it's very likely the result of an icebp/int01 trap. * User wants a sigtrap for that. */ if (!dr6 && user_mode(regs)) user_icebp = 1; /* Catch kmemcheck conditions first of all! */ if ((dr6 & DR_STEP) && kmemcheck_trap(regs)) goto exit; /* DR6 may or may not be cleared by the CPU */ set_debugreg(0, 6); /* * The processor cleared BTF, so don't mark that we need it set. */ clear_tsk_thread_flag(tsk, TIF_BLOCKSTEP); /* Store the virtualized DR6 value */ tsk->thread.debugreg6 = dr6; #ifdef CONFIG_KPROBES if (kprobe_debug_handler(regs)) goto exit; #endif if (notify_die(DIE_DEBUG, "debug", regs, (long)&dr6, error_code, SIGTRAP) == NOTIFY_STOP) goto exit; /* * Let others (NMI) know that the debug stack is in use * as we may switch to the interrupt stack. */ debug_stack_usage_inc(); /* It's safe to allow irq's after DR6 has been saved */ preempt_conditional_sti(regs); if (regs->flags & X86_VM_MASK) { handle_vm86_trap((struct kernel_vm86_regs *) regs, error_code, X86_TRAP_DB); preempt_conditional_cli(regs); debug_stack_usage_dec(); goto exit; } /* * Single-stepping through system calls: ignore any exceptions in * kernel space, but re-enable TF when returning to user mode. * * We already checked v86 mode above, so we can check for kernel mode * by just checking the CPL of CS. */ if ((dr6 & DR_STEP) && !user_mode(regs)) { tsk->thread.debugreg6 &= ~DR_STEP; set_tsk_thread_flag(tsk, TIF_SINGLESTEP); regs->flags &= ~X86_EFLAGS_TF; } si_code = get_si_code(tsk->thread.debugreg6); if (tsk->thread.debugreg6 & (DR_STEP | DR_TRAP_BITS) || user_icebp) send_sigtrap(tsk, regs, error_code, si_code); preempt_conditional_cli(regs); debug_stack_usage_dec(); exit: exception_exit(prev_state); } NOKPROBE_SYMBOL(do_debug); /* * Note that we play around with the 'TS' bit in an attempt to get * the correct behaviour even in the presence of the asynchronous * IRQ13 behaviour */ static void math_error(struct pt_regs *regs, int error_code, int trapnr) { struct task_struct *task = current; siginfo_t info; unsigned short err; char *str = (trapnr == X86_TRAP_MF) ? "fpu exception" : "simd exception"; if (notify_die(DIE_TRAP, str, regs, error_code, trapnr, SIGFPE) == NOTIFY_STOP) return; conditional_sti(regs); if (!user_mode_vm(regs)) { if (!fixup_exception(regs)) { task->thread.error_code = error_code; task->thread.trap_nr = trapnr; die(str, regs, error_code); } return; } /* * Save the info for the exception handler and clear the error. */ save_init_fpu(task); task->thread.trap_nr = trapnr; task->thread.error_code = error_code; info.si_signo = SIGFPE; info.si_errno = 0; info.si_addr = (void __user *)uprobe_get_trap_addr(regs); if (trapnr == X86_TRAP_MF) { unsigned short cwd, swd; /* * (~cwd & swd) will mask out exceptions that are not set to unmasked * status. 0x3f is the exception bits in these regs, 0x200 is the * C1 reg you need in case of a stack fault, 0x040 is the stack * fault bit. We should only be taking one exception at a time, * so if this combination doesn't produce any single exception, * then we have a bad program that isn't synchronizing its FPU usage * and it will suffer the consequences since we won't be able to * fully reproduce the context of the exception */ cwd = get_fpu_cwd(task); swd = get_fpu_swd(task); err = swd & ~cwd; } else { /* * The SIMD FPU exceptions are handled a little differently, as there * is only a single status/control register. Thus, to determine which * unmasked exception was caught we must mask the exception mask bits * at 0x1f80, and then use these to mask the exception bits at 0x3f. */ unsigned short mxcsr = get_fpu_mxcsr(task); err = ~(mxcsr >> 7) & mxcsr; } if (err & 0x001) { /* Invalid op */ /* * swd & 0x240 == 0x040: Stack Underflow * swd & 0x240 == 0x240: Stack Overflow * User must clear the SF bit (0x40) if set */ info.si_code = FPE_FLTINV; } else if (err & 0x004) { /* Divide by Zero */ info.si_code = FPE_FLTDIV; } else if (err & 0x008) { /* Overflow */ info.si_code = FPE_FLTOVF; } else if (err & 0x012) { /* Denormal, Underflow */ info.si_code = FPE_FLTUND; } else if (err & 0x020) { /* Precision */ info.si_code = FPE_FLTRES; } else { /* * If we're using IRQ 13, or supposedly even some trap * X86_TRAP_MF implementations, it's possible * we get a spurious trap, which is not an error. */ return; } force_sig_info(SIGFPE, &info, task); } dotraplinkage void do_coprocessor_error(struct pt_regs *regs, long error_code) { enum ctx_state prev_state; prev_state = exception_enter(); math_error(regs, error_code, X86_TRAP_MF); exception_exit(prev_state); } dotraplinkage void do_simd_coprocessor_error(struct pt_regs *regs, long error_code) { enum ctx_state prev_state; prev_state = exception_enter(); math_error(regs, error_code, X86_TRAP_XF); exception_exit(prev_state); } dotraplinkage void do_spurious_interrupt_bug(struct pt_regs *regs, long error_code) { conditional_sti(regs); #if 0 /* No need to warn about this any longer. */ pr_info("Ignoring P6 Local APIC Spurious Interrupt Bug...\n"); #endif } asmlinkage __visible void __attribute__((weak)) smp_thermal_interrupt(void) { } asmlinkage __visible void __attribute__((weak)) smp_threshold_interrupt(void) { } /* * 'math_state_restore()' saves the current math information in the * old math state array, and gets the new ones from the current task * * Careful.. There are problems with IBM-designed IRQ13 behaviour. * Don't touch unless you *really* know how it works. * * Must be called with kernel preemption disabled (eg with local * local interrupts as in the case of do_device_not_available). */ void math_state_restore(void) { struct task_struct *tsk = current; if (!tsk_used_math(tsk)) { local_irq_enable(); /* * does a slab alloc which can sleep */ if (init_fpu(tsk)) { /* * ran out of memory! */ do_group_exit(SIGKILL); return; } local_irq_disable(); } __thread_fpu_begin(tsk); /* * Paranoid restore. send a SIGSEGV if we fail to restore the state. */ if (unlikely(restore_fpu_checking(tsk))) { drop_init_fpu(tsk); force_sig_info(SIGSEGV, SEND_SIG_PRIV, tsk); return; } tsk->thread.fpu_counter++; } EXPORT_SYMBOL_GPL(math_state_restore); dotraplinkage void do_device_not_available(struct pt_regs *regs, long error_code) { enum ctx_state prev_state; prev_state = exception_enter(); BUG_ON(use_eager_fpu()); #ifdef CONFIG_MATH_EMULATION if (read_cr0() & X86_CR0_EM) { struct math_emu_info info = { }; conditional_sti(regs); info.regs = regs; math_emulate(&info); exception_exit(prev_state); return; } #endif math_state_restore(); /* interrupts still off */ #ifdef CONFIG_X86_32 conditional_sti(regs); #endif exception_exit(prev_state); } NOKPROBE_SYMBOL(do_device_not_available); #ifdef CONFIG_X86_32 dotraplinkage void do_iret_error(struct pt_regs *regs, long error_code) { siginfo_t info; enum ctx_state prev_state; prev_state = exception_enter(); local_irq_enable(); info.si_signo = SIGILL; info.si_errno = 0; info.si_code = ILL_BADSTK; info.si_addr = NULL; if (notify_die(DIE_TRAP, "iret exception", regs, error_code, X86_TRAP_IRET, SIGILL) != NOTIFY_STOP) { do_trap(X86_TRAP_IRET, SIGILL, "iret exception", regs, error_code, &info); } exception_exit(prev_state); } #endif /* Set of traps needed for early debugging. */ void __init early_trap_init(void) { set_intr_gate_ist(X86_TRAP_DB, &debug, DEBUG_STACK); /* int3 can be called from all */ set_system_intr_gate_ist(X86_TRAP_BP, &int3, DEBUG_STACK); #ifdef CONFIG_X86_32 set_intr_gate(X86_TRAP_PF, page_fault); #endif load_idt(&idt_descr); } void __init early_trap_pf_init(void) { #ifdef CONFIG_X86_64 set_intr_gate(X86_TRAP_PF, page_fault); #endif } void __init trap_init(void) { int i; #ifdef CONFIG_EISA void __iomem *p = early_ioremap(0x0FFFD9, 4); if (readl(p) == 'E' + ('I'<<8) + ('S'<<16) + ('A'<<24)) EISA_bus = 1; early_iounmap(p, 4); #endif set_intr_gate(X86_TRAP_DE, divide_error); set_intr_gate_ist(X86_TRAP_NMI, &nmi, NMI_STACK); /* int4 can be called from all */ set_system_intr_gate(X86_TRAP_OF, &overflow); set_intr_gate(X86_TRAP_BR, bounds); set_intr_gate(X86_TRAP_UD, invalid_op); set_intr_gate(X86_TRAP_NM, device_not_available); #ifdef CONFIG_X86_32 set_task_gate(X86_TRAP_DF, GDT_ENTRY_DOUBLEFAULT_TSS); #else set_intr_gate_ist(X86_TRAP_DF, &double_fault, DOUBLEFAULT_STACK); #endif set_intr_gate(X86_TRAP_OLD_MF, coprocessor_segment_overrun); set_intr_gate(X86_TRAP_TS, invalid_TSS); set_intr_gate(X86_TRAP_NP, segment_not_present); set_intr_gate_ist(X86_TRAP_SS, &stack_segment, STACKFAULT_STACK); set_intr_gate(X86_TRAP_GP, general_protection); set_intr_gate(X86_TRAP_SPURIOUS, spurious_interrupt_bug); set_intr_gate(X86_TRAP_MF, coprocessor_error); set_intr_gate(X86_TRAP_AC, alignment_check); #ifdef CONFIG_X86_MCE set_intr_gate_ist(X86_TRAP_MC, &machine_check, MCE_STACK); #endif set_intr_gate(X86_TRAP_XF, simd_coprocessor_error); /* Reserve all the builtin and the syscall vector: */ for (i = 0; i < FIRST_EXTERNAL_VECTOR; i++) set_bit(i, used_vectors); #ifdef CONFIG_IA32_EMULATION set_system_intr_gate(IA32_SYSCALL_VECTOR, ia32_syscall); set_bit(IA32_SYSCALL_VECTOR, used_vectors); #endif #ifdef CONFIG_X86_32 set_system_trap_gate(SYSCALL_VECTOR, &system_call); set_bit(SYSCALL_VECTOR, used_vectors); #endif /* * Set the IDT descriptor to a fixed read-only location, so that the * "sidt" instruction will not leak the location of the kernel, and * to defend the IDT against arbitrary memory write vulnerabilities. * It will be reloaded in cpu_init() */ __set_fixmap(FIX_RO_IDT, __pa_symbol(idt_table), PAGE_KERNEL_RO); idt_descr.address = fix_to_virt(FIX_RO_IDT); /* * Should be a barrier for any external CPU state: */ cpu_init(); x86_init.irqs.trap_init(); #ifdef CONFIG_X86_64 memcpy(&debug_idt_table, &idt_table, IDT_ENTRIES * 16); set_nmi_gate(X86_TRAP_DB, &debug); set_nmi_gate(X86_TRAP_BP, &int3); #endif }
./CrossVul/dataset_final_sorted/CWE-17/c/bad_2348_5
crossvul-cpp_data_bad_2306_0
/* * linux/fs/file_table.c * * Copyright (C) 1991, 1992 Linus Torvalds * Copyright (C) 1997 David S. Miller (davem@caip.rutgers.edu) */ #include <linux/string.h> #include <linux/slab.h> #include <linux/file.h> #include <linux/fdtable.h> #include <linux/init.h> #include <linux/module.h> #include <linux/fs.h> #include <linux/security.h> #include <linux/eventpoll.h> #include <linux/rcupdate.h> #include <linux/mount.h> #include <linux/capability.h> #include <linux/cdev.h> #include <linux/fsnotify.h> #include <linux/sysctl.h> #include <linux/lglock.h> #include <linux/percpu_counter.h> #include <linux/percpu.h> #include <linux/hardirq.h> #include <linux/task_work.h> #include <linux/ima.h> #include <linux/atomic.h> #include "internal.h" /* sysctl tunables... */ struct files_stat_struct files_stat = { .max_files = NR_FILE }; DEFINE_STATIC_LGLOCK(files_lglock); /* SLAB cache for file structures */ static struct kmem_cache *filp_cachep __read_mostly; static struct percpu_counter nr_files __cacheline_aligned_in_smp; static void file_free_rcu(struct rcu_head *head) { struct file *f = container_of(head, struct file, f_u.fu_rcuhead); put_cred(f->f_cred); kmem_cache_free(filp_cachep, f); } static inline void file_free(struct file *f) { percpu_counter_dec(&nr_files); file_check_state(f); call_rcu(&f->f_u.fu_rcuhead, file_free_rcu); } /* * Return the total number of open files in the system */ static long get_nr_files(void) { return percpu_counter_read_positive(&nr_files); } /* * Return the maximum number of open files in the system */ unsigned long get_max_files(void) { return files_stat.max_files; } EXPORT_SYMBOL_GPL(get_max_files); /* * Handle nr_files sysctl */ #if defined(CONFIG_SYSCTL) && defined(CONFIG_PROC_FS) int proc_nr_files(ctl_table *table, int write, void __user *buffer, size_t *lenp, loff_t *ppos) { files_stat.nr_files = get_nr_files(); return proc_doulongvec_minmax(table, write, buffer, lenp, ppos); } #else int proc_nr_files(ctl_table *table, int write, void __user *buffer, size_t *lenp, loff_t *ppos) { return -ENOSYS; } #endif /* Find an unused file structure and return a pointer to it. * Returns an error pointer if some error happend e.g. we over file * structures limit, run out of memory or operation is not permitted. * * Be very careful using this. You are responsible for * getting write access to any mount that you might assign * to this filp, if it is opened for write. If this is not * done, you will imbalance int the mount's writer count * and a warning at __fput() time. */ struct file *get_empty_filp(void) { const struct cred *cred = current_cred(); static long old_max; struct file *f; int error; /* * Privileged users can go above max_files */ if (get_nr_files() >= files_stat.max_files && !capable(CAP_SYS_ADMIN)) { /* * percpu_counters are inaccurate. Do an expensive check before * we go and fail. */ if (percpu_counter_sum_positive(&nr_files) >= files_stat.max_files) goto over; } f = kmem_cache_zalloc(filp_cachep, GFP_KERNEL); if (unlikely(!f)) return ERR_PTR(-ENOMEM); percpu_counter_inc(&nr_files); f->f_cred = get_cred(cred); error = security_file_alloc(f); if (unlikely(error)) { file_free(f); return ERR_PTR(error); } INIT_LIST_HEAD(&f->f_u.fu_list); atomic_long_set(&f->f_count, 1); rwlock_init(&f->f_owner.lock); spin_lock_init(&f->f_lock); eventpoll_init_file(f); /* f->f_version: 0 */ return f; over: /* Ran out of filps - report that */ if (get_nr_files() > old_max) { pr_info("VFS: file-max limit %lu reached\n", get_max_files()); old_max = get_nr_files(); } return ERR_PTR(-ENFILE); } /** * alloc_file - allocate and initialize a 'struct file' * @mnt: the vfsmount on which the file will reside * @dentry: the dentry representing the new file * @mode: the mode with which the new file will be opened * @fop: the 'struct file_operations' for the new file * * Use this instead of get_empty_filp() to get a new * 'struct file'. Do so because of the same initialization * pitfalls reasons listed for init_file(). This is a * preferred interface to using init_file(). * * If all the callers of init_file() are eliminated, its * code should be moved into this function. */ struct file *alloc_file(struct path *path, fmode_t mode, const struct file_operations *fop) { struct file *file; file = get_empty_filp(); if (IS_ERR(file)) return file; file->f_path = *path; file->f_inode = path->dentry->d_inode; file->f_mapping = path->dentry->d_inode->i_mapping; file->f_mode = mode; file->f_op = fop; /* * These mounts don't really matter in practice * for r/o bind mounts. They aren't userspace- * visible. We do this for consistency, and so * that we can do debugging checks at __fput() */ if ((mode & FMODE_WRITE) && !special_file(path->dentry->d_inode->i_mode)) { file_take_write(file); WARN_ON(mnt_clone_write(path->mnt)); } if ((mode & (FMODE_READ | FMODE_WRITE)) == FMODE_READ) i_readcount_inc(path->dentry->d_inode); return file; } EXPORT_SYMBOL(alloc_file); /** * drop_file_write_access - give up ability to write to a file * @file: the file to which we will stop writing * * This is a central place which will give up the ability * to write to @file, along with access to write through * its vfsmount. */ static void drop_file_write_access(struct file *file) { struct vfsmount *mnt = file->f_path.mnt; struct dentry *dentry = file->f_path.dentry; struct inode *inode = dentry->d_inode; put_write_access(inode); if (special_file(inode->i_mode)) return; if (file_check_writeable(file) != 0) return; __mnt_drop_write(mnt); file_release_write(file); } /* the real guts of fput() - releasing the last reference to file */ static void __fput(struct file *file) { struct dentry *dentry = file->f_path.dentry; struct vfsmount *mnt = file->f_path.mnt; struct inode *inode = file->f_inode; might_sleep(); fsnotify_close(file); /* * The function eventpoll_release() should be the first called * in the file cleanup chain. */ eventpoll_release(file); locks_remove_flock(file); if (unlikely(file->f_flags & FASYNC)) { if (file->f_op->fasync) file->f_op->fasync(-1, file, 0); } ima_file_free(file); if (file->f_op->release) file->f_op->release(inode, file); security_file_free(file); if (unlikely(S_ISCHR(inode->i_mode) && inode->i_cdev != NULL && !(file->f_mode & FMODE_PATH))) { cdev_put(inode->i_cdev); } fops_put(file->f_op); put_pid(file->f_owner.pid); if ((file->f_mode & (FMODE_READ | FMODE_WRITE)) == FMODE_READ) i_readcount_dec(inode); if (file->f_mode & FMODE_WRITE) drop_file_write_access(file); file->f_path.dentry = NULL; file->f_path.mnt = NULL; file->f_inode = NULL; file_free(file); dput(dentry); mntput(mnt); } static LLIST_HEAD(delayed_fput_list); static void delayed_fput(struct work_struct *unused) { struct llist_node *node = llist_del_all(&delayed_fput_list); struct llist_node *next; for (; node; node = next) { next = llist_next(node); __fput(llist_entry(node, struct file, f_u.fu_llist)); } } static void ____fput(struct callback_head *work) { __fput(container_of(work, struct file, f_u.fu_rcuhead)); } /* * If kernel thread really needs to have the final fput() it has done * to complete, call this. The only user right now is the boot - we * *do* need to make sure our writes to binaries on initramfs has * not left us with opened struct file waiting for __fput() - execve() * won't work without that. Please, don't add more callers without * very good reasons; in particular, never call that with locks * held and never call that from a thread that might need to do * some work on any kind of umount. */ void flush_delayed_fput(void) { delayed_fput(NULL); } static DECLARE_WORK(delayed_fput_work, delayed_fput); void fput(struct file *file) { if (atomic_long_dec_and_test(&file->f_count)) { struct task_struct *task = current; file_sb_list_del(file); if (likely(!in_interrupt() && !(task->flags & PF_KTHREAD))) { init_task_work(&file->f_u.fu_rcuhead, ____fput); if (!task_work_add(task, &file->f_u.fu_rcuhead, true)) return; /* * After this task has run exit_task_work(), * task_work_add() will fail. Fall through to delayed * fput to avoid leaking *file. */ } if (llist_add(&file->f_u.fu_llist, &delayed_fput_list)) schedule_work(&delayed_fput_work); } } /* * synchronous analog of fput(); for kernel threads that might be needed * in some umount() (and thus can't use flush_delayed_fput() without * risking deadlocks), need to wait for completion of __fput() and know * for this specific struct file it won't involve anything that would * need them. Use only if you really need it - at the very least, * don't blindly convert fput() by kernel thread to that. */ void __fput_sync(struct file *file) { if (atomic_long_dec_and_test(&file->f_count)) { struct task_struct *task = current; file_sb_list_del(file); BUG_ON(!(task->flags & PF_KTHREAD)); __fput(file); } } EXPORT_SYMBOL(fput); void put_filp(struct file *file) { if (atomic_long_dec_and_test(&file->f_count)) { security_file_free(file); file_sb_list_del(file); file_free(file); } } static inline int file_list_cpu(struct file *file) { #ifdef CONFIG_SMP return file->f_sb_list_cpu; #else return smp_processor_id(); #endif } /* helper for file_sb_list_add to reduce ifdefs */ static inline void __file_sb_list_add(struct file *file, struct super_block *sb) { struct list_head *list; #ifdef CONFIG_SMP int cpu; cpu = smp_processor_id(); file->f_sb_list_cpu = cpu; list = per_cpu_ptr(sb->s_files, cpu); #else list = &sb->s_files; #endif list_add(&file->f_u.fu_list, list); } /** * file_sb_list_add - add a file to the sb's file list * @file: file to add * @sb: sb to add it to * * Use this function to associate a file with the superblock of the inode it * refers to. */ void file_sb_list_add(struct file *file, struct super_block *sb) { if (likely(!(file->f_mode & FMODE_WRITE))) return; if (!S_ISREG(file_inode(file)->i_mode)) return; lg_local_lock(&files_lglock); __file_sb_list_add(file, sb); lg_local_unlock(&files_lglock); } /** * file_sb_list_del - remove a file from the sb's file list * @file: file to remove * @sb: sb to remove it from * * Use this function to remove a file from its superblock. */ void file_sb_list_del(struct file *file) { if (!list_empty(&file->f_u.fu_list)) { lg_local_lock_cpu(&files_lglock, file_list_cpu(file)); list_del_init(&file->f_u.fu_list); lg_local_unlock_cpu(&files_lglock, file_list_cpu(file)); } } #ifdef CONFIG_SMP /* * These macros iterate all files on all CPUs for a given superblock. * files_lglock must be held globally. */ #define do_file_list_for_each_entry(__sb, __file) \ { \ int i; \ for_each_possible_cpu(i) { \ struct list_head *list; \ list = per_cpu_ptr((__sb)->s_files, i); \ list_for_each_entry((__file), list, f_u.fu_list) #define while_file_list_for_each_entry \ } \ } #else #define do_file_list_for_each_entry(__sb, __file) \ { \ struct list_head *list; \ list = &(sb)->s_files; \ list_for_each_entry((__file), list, f_u.fu_list) #define while_file_list_for_each_entry \ } #endif /** * mark_files_ro - mark all files read-only * @sb: superblock in question * * All files are marked read-only. We don't care about pending * delete files so this should be used in 'force' mode only. */ void mark_files_ro(struct super_block *sb) { struct file *f; lg_global_lock(&files_lglock); do_file_list_for_each_entry(sb, f) { if (!file_count(f)) continue; if (!(f->f_mode & FMODE_WRITE)) continue; spin_lock(&f->f_lock); f->f_mode &= ~FMODE_WRITE; spin_unlock(&f->f_lock); if (file_check_writeable(f) != 0) continue; __mnt_drop_write(f->f_path.mnt); file_release_write(f); } while_file_list_for_each_entry; lg_global_unlock(&files_lglock); } void __init files_init(unsigned long mempages) { unsigned long n; filp_cachep = kmem_cache_create("filp", sizeof(struct file), 0, SLAB_HWCACHE_ALIGN | SLAB_PANIC, NULL); /* * One file with associated inode and dcache is very roughly 1K. * Per default don't use more than 10% of our memory for files. */ n = (mempages * (PAGE_SIZE / 1024)) / 10; files_stat.max_files = max_t(unsigned long, n, NR_FILE); files_defer_init(); lg_lock_init(&files_lglock, "files_lglock"); percpu_counter_init(&nr_files, 0); }
./CrossVul/dataset_final_sorted/CWE-17/c/bad_2306_0
crossvul-cpp_data_good_1482_2
/* * INET An implementation of the TCP/IP protocol suite for the LINUX * operating system. INET is implemented using the BSD Socket * interface as the means of communication with the user level. * * ROUTE - implementation of the IP router. * * Authors: Ross Biro * Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG> * Alan Cox, <gw4pts@gw4pts.ampr.org> * Linus Torvalds, <Linus.Torvalds@helsinki.fi> * Alexey Kuznetsov, <kuznet@ms2.inr.ac.ru> * * Fixes: * Alan Cox : Verify area fixes. * Alan Cox : cli() protects routing changes * Rui Oliveira : ICMP routing table updates * (rco@di.uminho.pt) Routing table insertion and update * Linus Torvalds : Rewrote bits to be sensible * Alan Cox : Added BSD route gw semantics * Alan Cox : Super /proc >4K * Alan Cox : MTU in route table * Alan Cox : MSS actually. Also added the window * clamper. * Sam Lantinga : Fixed route matching in rt_del() * Alan Cox : Routing cache support. * Alan Cox : Removed compatibility cruft. * Alan Cox : RTF_REJECT support. * Alan Cox : TCP irtt support. * Jonathan Naylor : Added Metric support. * Miquel van Smoorenburg : BSD API fixes. * Miquel van Smoorenburg : Metrics. * Alan Cox : Use __u32 properly * Alan Cox : Aligned routing errors more closely with BSD * our system is still very different. * Alan Cox : Faster /proc handling * Alexey Kuznetsov : Massive rework to support tree based routing, * routing caches and better behaviour. * * Olaf Erb : irtt wasn't being copied right. * Bjorn Ekwall : Kerneld route support. * Alan Cox : Multicast fixed (I hope) * Pavel Krauz : Limited broadcast fixed * Mike McLagan : Routing by source * Alexey Kuznetsov : End of old history. Split to fib.c and * route.c and rewritten from scratch. * Andi Kleen : Load-limit warning messages. * Vitaly E. Lavrov : Transparent proxy revived after year coma. * Vitaly E. Lavrov : Race condition in ip_route_input_slow. * Tobias Ringstrom : Uninitialized res.type in ip_route_output_slow. * Vladimir V. Ivanov : IP rule info (flowid) is really useful. * Marc Boucher : routing by fwmark * Robert Olsson : Added rt_cache statistics * Arnaldo C. Melo : Convert proc stuff to seq_file * Eric Dumazet : hashed spinlocks and rt_check_expire() fixes. * Ilia Sotnikov : Ignore TOS on PMTUD and Redirect * Ilia Sotnikov : Removed TOS from hash calculations * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #define pr_fmt(fmt) "IPv4: " fmt #include <linux/module.h> #include <asm/uaccess.h> #include <linux/bitops.h> #include <linux/types.h> #include <linux/kernel.h> #include <linux/mm.h> #include <linux/string.h> #include <linux/socket.h> #include <linux/sockios.h> #include <linux/errno.h> #include <linux/in.h> #include <linux/inet.h> #include <linux/netdevice.h> #include <linux/proc_fs.h> #include <linux/init.h> #include <linux/skbuff.h> #include <linux/inetdevice.h> #include <linux/igmp.h> #include <linux/pkt_sched.h> #include <linux/mroute.h> #include <linux/netfilter_ipv4.h> #include <linux/random.h> #include <linux/rcupdate.h> #include <linux/times.h> #include <linux/slab.h> #include <linux/jhash.h> #include <net/dst.h> #include <net/net_namespace.h> #include <net/protocol.h> #include <net/ip.h> #include <net/route.h> #include <net/inetpeer.h> #include <net/sock.h> #include <net/ip_fib.h> #include <net/arp.h> #include <net/tcp.h> #include <net/icmp.h> #include <net/xfrm.h> #include <net/netevent.h> #include <net/rtnetlink.h> #ifdef CONFIG_SYSCTL #include <linux/sysctl.h> #include <linux/kmemleak.h> #endif #include <net/secure_seq.h> #define RT_FL_TOS(oldflp4) \ ((oldflp4)->flowi4_tos & (IPTOS_RT_MASK | RTO_ONLINK)) #define RT_GC_TIMEOUT (300*HZ) static int ip_rt_max_size; static int ip_rt_redirect_number __read_mostly = 9; static int ip_rt_redirect_load __read_mostly = HZ / 50; static int ip_rt_redirect_silence __read_mostly = ((HZ / 50) << (9 + 1)); static int ip_rt_error_cost __read_mostly = HZ; static int ip_rt_error_burst __read_mostly = 5 * HZ; static int ip_rt_mtu_expires __read_mostly = 10 * 60 * HZ; static int ip_rt_min_pmtu __read_mostly = 512 + 20 + 20; static int ip_rt_min_advmss __read_mostly = 256; /* * Interface to generic destination cache. */ static struct dst_entry *ipv4_dst_check(struct dst_entry *dst, u32 cookie); static unsigned int ipv4_default_advmss(const struct dst_entry *dst); static unsigned int ipv4_mtu(const struct dst_entry *dst); static struct dst_entry *ipv4_negative_advice(struct dst_entry *dst); static void ipv4_link_failure(struct sk_buff *skb); static void ip_rt_update_pmtu(struct dst_entry *dst, struct sock *sk, struct sk_buff *skb, u32 mtu); static void ip_do_redirect(struct dst_entry *dst, struct sock *sk, struct sk_buff *skb); static void ipv4_dst_destroy(struct dst_entry *dst); static u32 *ipv4_cow_metrics(struct dst_entry *dst, unsigned long old) { WARN_ON(1); return NULL; } static struct neighbour *ipv4_neigh_lookup(const struct dst_entry *dst, struct sk_buff *skb, const void *daddr); static struct dst_ops ipv4_dst_ops = { .family = AF_INET, .protocol = cpu_to_be16(ETH_P_IP), .check = ipv4_dst_check, .default_advmss = ipv4_default_advmss, .mtu = ipv4_mtu, .cow_metrics = ipv4_cow_metrics, .destroy = ipv4_dst_destroy, .negative_advice = ipv4_negative_advice, .link_failure = ipv4_link_failure, .update_pmtu = ip_rt_update_pmtu, .redirect = ip_do_redirect, .local_out = __ip_local_out, .neigh_lookup = ipv4_neigh_lookup, }; #define ECN_OR_COST(class) TC_PRIO_##class const __u8 ip_tos2prio[16] = { TC_PRIO_BESTEFFORT, ECN_OR_COST(BESTEFFORT), TC_PRIO_BESTEFFORT, ECN_OR_COST(BESTEFFORT), TC_PRIO_BULK, ECN_OR_COST(BULK), TC_PRIO_BULK, ECN_OR_COST(BULK), TC_PRIO_INTERACTIVE, ECN_OR_COST(INTERACTIVE), TC_PRIO_INTERACTIVE, ECN_OR_COST(INTERACTIVE), TC_PRIO_INTERACTIVE_BULK, ECN_OR_COST(INTERACTIVE_BULK), TC_PRIO_INTERACTIVE_BULK, ECN_OR_COST(INTERACTIVE_BULK) }; EXPORT_SYMBOL(ip_tos2prio); static DEFINE_PER_CPU(struct rt_cache_stat, rt_cache_stat); #define RT_CACHE_STAT_INC(field) raw_cpu_inc(rt_cache_stat.field) #ifdef CONFIG_PROC_FS static void *rt_cache_seq_start(struct seq_file *seq, loff_t *pos) { if (*pos) return NULL; return SEQ_START_TOKEN; } static void *rt_cache_seq_next(struct seq_file *seq, void *v, loff_t *pos) { ++*pos; return NULL; } static void rt_cache_seq_stop(struct seq_file *seq, void *v) { } static int rt_cache_seq_show(struct seq_file *seq, void *v) { if (v == SEQ_START_TOKEN) seq_printf(seq, "%-127s\n", "Iface\tDestination\tGateway \tFlags\t\tRefCnt\tUse\t" "Metric\tSource\t\tMTU\tWindow\tIRTT\tTOS\tHHRef\t" "HHUptod\tSpecDst"); return 0; } static const struct seq_operations rt_cache_seq_ops = { .start = rt_cache_seq_start, .next = rt_cache_seq_next, .stop = rt_cache_seq_stop, .show = rt_cache_seq_show, }; static int rt_cache_seq_open(struct inode *inode, struct file *file) { return seq_open(file, &rt_cache_seq_ops); } static const struct file_operations rt_cache_seq_fops = { .owner = THIS_MODULE, .open = rt_cache_seq_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release, }; static void *rt_cpu_seq_start(struct seq_file *seq, loff_t *pos) { int cpu; if (*pos == 0) return SEQ_START_TOKEN; for (cpu = *pos-1; cpu < nr_cpu_ids; ++cpu) { if (!cpu_possible(cpu)) continue; *pos = cpu+1; return &per_cpu(rt_cache_stat, cpu); } return NULL; } static void *rt_cpu_seq_next(struct seq_file *seq, void *v, loff_t *pos) { int cpu; for (cpu = *pos; cpu < nr_cpu_ids; ++cpu) { if (!cpu_possible(cpu)) continue; *pos = cpu+1; return &per_cpu(rt_cache_stat, cpu); } return NULL; } static void rt_cpu_seq_stop(struct seq_file *seq, void *v) { } static int rt_cpu_seq_show(struct seq_file *seq, void *v) { struct rt_cache_stat *st = v; if (v == SEQ_START_TOKEN) { seq_printf(seq, "entries in_hit in_slow_tot in_slow_mc in_no_route in_brd in_martian_dst in_martian_src out_hit out_slow_tot out_slow_mc gc_total gc_ignored gc_goal_miss gc_dst_overflow in_hlist_search out_hlist_search\n"); return 0; } seq_printf(seq,"%08x %08x %08x %08x %08x %08x %08x %08x " " %08x %08x %08x %08x %08x %08x %08x %08x %08x \n", dst_entries_get_slow(&ipv4_dst_ops), 0, /* st->in_hit */ st->in_slow_tot, st->in_slow_mc, st->in_no_route, st->in_brd, st->in_martian_dst, st->in_martian_src, 0, /* st->out_hit */ st->out_slow_tot, st->out_slow_mc, 0, /* st->gc_total */ 0, /* st->gc_ignored */ 0, /* st->gc_goal_miss */ 0, /* st->gc_dst_overflow */ 0, /* st->in_hlist_search */ 0 /* st->out_hlist_search */ ); return 0; } static const struct seq_operations rt_cpu_seq_ops = { .start = rt_cpu_seq_start, .next = rt_cpu_seq_next, .stop = rt_cpu_seq_stop, .show = rt_cpu_seq_show, }; static int rt_cpu_seq_open(struct inode *inode, struct file *file) { return seq_open(file, &rt_cpu_seq_ops); } static const struct file_operations rt_cpu_seq_fops = { .owner = THIS_MODULE, .open = rt_cpu_seq_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release, }; #ifdef CONFIG_IP_ROUTE_CLASSID static int rt_acct_proc_show(struct seq_file *m, void *v) { struct ip_rt_acct *dst, *src; unsigned int i, j; dst = kcalloc(256, sizeof(struct ip_rt_acct), GFP_KERNEL); if (!dst) return -ENOMEM; for_each_possible_cpu(i) { src = (struct ip_rt_acct *)per_cpu_ptr(ip_rt_acct, i); for (j = 0; j < 256; j++) { dst[j].o_bytes += src[j].o_bytes; dst[j].o_packets += src[j].o_packets; dst[j].i_bytes += src[j].i_bytes; dst[j].i_packets += src[j].i_packets; } } seq_write(m, dst, 256 * sizeof(struct ip_rt_acct)); kfree(dst); return 0; } static int rt_acct_proc_open(struct inode *inode, struct file *file) { return single_open(file, rt_acct_proc_show, NULL); } static const struct file_operations rt_acct_proc_fops = { .owner = THIS_MODULE, .open = rt_acct_proc_open, .read = seq_read, .llseek = seq_lseek, .release = single_release, }; #endif static int __net_init ip_rt_do_proc_init(struct net *net) { struct proc_dir_entry *pde; pde = proc_create("rt_cache", S_IRUGO, net->proc_net, &rt_cache_seq_fops); if (!pde) goto err1; pde = proc_create("rt_cache", S_IRUGO, net->proc_net_stat, &rt_cpu_seq_fops); if (!pde) goto err2; #ifdef CONFIG_IP_ROUTE_CLASSID pde = proc_create("rt_acct", 0, net->proc_net, &rt_acct_proc_fops); if (!pde) goto err3; #endif return 0; #ifdef CONFIG_IP_ROUTE_CLASSID err3: remove_proc_entry("rt_cache", net->proc_net_stat); #endif err2: remove_proc_entry("rt_cache", net->proc_net); err1: return -ENOMEM; } static void __net_exit ip_rt_do_proc_exit(struct net *net) { remove_proc_entry("rt_cache", net->proc_net_stat); remove_proc_entry("rt_cache", net->proc_net); #ifdef CONFIG_IP_ROUTE_CLASSID remove_proc_entry("rt_acct", net->proc_net); #endif } static struct pernet_operations ip_rt_proc_ops __net_initdata = { .init = ip_rt_do_proc_init, .exit = ip_rt_do_proc_exit, }; static int __init ip_rt_proc_init(void) { return register_pernet_subsys(&ip_rt_proc_ops); } #else static inline int ip_rt_proc_init(void) { return 0; } #endif /* CONFIG_PROC_FS */ static inline bool rt_is_expired(const struct rtable *rth) { return rth->rt_genid != rt_genid_ipv4(dev_net(rth->dst.dev)); } void rt_cache_flush(struct net *net) { rt_genid_bump_ipv4(net); } static struct neighbour *ipv4_neigh_lookup(const struct dst_entry *dst, struct sk_buff *skb, const void *daddr) { struct net_device *dev = dst->dev; const __be32 *pkey = daddr; const struct rtable *rt; struct neighbour *n; rt = (const struct rtable *) dst; if (rt->rt_gateway) pkey = (const __be32 *) &rt->rt_gateway; else if (skb) pkey = &ip_hdr(skb)->daddr; n = __ipv4_neigh_lookup(dev, *(__force u32 *)pkey); if (n) return n; return neigh_create(&arp_tbl, pkey, dev); } #define IP_IDENTS_SZ 2048u struct ip_ident_bucket { atomic_t id; u32 stamp32; }; static struct ip_ident_bucket *ip_idents __read_mostly; /* In order to protect privacy, we add a perturbation to identifiers * if one generator is seldom used. This makes hard for an attacker * to infer how many packets were sent between two points in time. */ u32 ip_idents_reserve(u32 hash, int segs) { struct ip_ident_bucket *bucket = ip_idents + hash % IP_IDENTS_SZ; u32 old = ACCESS_ONCE(bucket->stamp32); u32 now = (u32)jiffies; u32 delta = 0; if (old != now && cmpxchg(&bucket->stamp32, old, now) == old) delta = prandom_u32_max(now - old); return atomic_add_return(segs + delta, &bucket->id) - segs; } EXPORT_SYMBOL(ip_idents_reserve); void __ip_select_ident(struct iphdr *iph, int segs) { static u32 ip_idents_hashrnd __read_mostly; u32 hash, id; net_get_random_once(&ip_idents_hashrnd, sizeof(ip_idents_hashrnd)); hash = jhash_3words((__force u32)iph->daddr, (__force u32)iph->saddr, iph->protocol, ip_idents_hashrnd); id = ip_idents_reserve(hash, segs); iph->id = htons(id); } EXPORT_SYMBOL(__ip_select_ident); static void __build_flow_key(struct flowi4 *fl4, const struct sock *sk, const struct iphdr *iph, int oif, u8 tos, u8 prot, u32 mark, int flow_flags) { if (sk) { const struct inet_sock *inet = inet_sk(sk); oif = sk->sk_bound_dev_if; mark = sk->sk_mark; tos = RT_CONN_FLAGS(sk); prot = inet->hdrincl ? IPPROTO_RAW : sk->sk_protocol; } flowi4_init_output(fl4, oif, mark, tos, RT_SCOPE_UNIVERSE, prot, flow_flags, iph->daddr, iph->saddr, 0, 0); } static void build_skb_flow_key(struct flowi4 *fl4, const struct sk_buff *skb, const struct sock *sk) { const struct iphdr *iph = ip_hdr(skb); int oif = skb->dev->ifindex; u8 tos = RT_TOS(iph->tos); u8 prot = iph->protocol; u32 mark = skb->mark; __build_flow_key(fl4, sk, iph, oif, tos, prot, mark, 0); } static void build_sk_flow_key(struct flowi4 *fl4, const struct sock *sk) { const struct inet_sock *inet = inet_sk(sk); const struct ip_options_rcu *inet_opt; __be32 daddr = inet->inet_daddr; rcu_read_lock(); inet_opt = rcu_dereference(inet->inet_opt); if (inet_opt && inet_opt->opt.srr) daddr = inet_opt->opt.faddr; flowi4_init_output(fl4, sk->sk_bound_dev_if, sk->sk_mark, RT_CONN_FLAGS(sk), RT_SCOPE_UNIVERSE, inet->hdrincl ? IPPROTO_RAW : sk->sk_protocol, inet_sk_flowi_flags(sk), daddr, inet->inet_saddr, 0, 0); rcu_read_unlock(); } static void ip_rt_build_flow_key(struct flowi4 *fl4, const struct sock *sk, const struct sk_buff *skb) { if (skb) build_skb_flow_key(fl4, skb, sk); else build_sk_flow_key(fl4, sk); } static inline void rt_free(struct rtable *rt) { call_rcu(&rt->dst.rcu_head, dst_rcu_free); } static DEFINE_SPINLOCK(fnhe_lock); static void fnhe_flush_routes(struct fib_nh_exception *fnhe) { struct rtable *rt; rt = rcu_dereference(fnhe->fnhe_rth_input); if (rt) { RCU_INIT_POINTER(fnhe->fnhe_rth_input, NULL); rt_free(rt); } rt = rcu_dereference(fnhe->fnhe_rth_output); if (rt) { RCU_INIT_POINTER(fnhe->fnhe_rth_output, NULL); rt_free(rt); } } static struct fib_nh_exception *fnhe_oldest(struct fnhe_hash_bucket *hash) { struct fib_nh_exception *fnhe, *oldest; oldest = rcu_dereference(hash->chain); for (fnhe = rcu_dereference(oldest->fnhe_next); fnhe; fnhe = rcu_dereference(fnhe->fnhe_next)) { if (time_before(fnhe->fnhe_stamp, oldest->fnhe_stamp)) oldest = fnhe; } fnhe_flush_routes(oldest); return oldest; } static inline u32 fnhe_hashfun(__be32 daddr) { static u32 fnhe_hashrnd __read_mostly; u32 hval; net_get_random_once(&fnhe_hashrnd, sizeof(fnhe_hashrnd)); hval = jhash_1word((__force u32) daddr, fnhe_hashrnd); return hash_32(hval, FNHE_HASH_SHIFT); } static void fill_route_from_fnhe(struct rtable *rt, struct fib_nh_exception *fnhe) { rt->rt_pmtu = fnhe->fnhe_pmtu; rt->dst.expires = fnhe->fnhe_expires; if (fnhe->fnhe_gw) { rt->rt_flags |= RTCF_REDIRECTED; rt->rt_gateway = fnhe->fnhe_gw; rt->rt_uses_gateway = 1; } } static void update_or_create_fnhe(struct fib_nh *nh, __be32 daddr, __be32 gw, u32 pmtu, unsigned long expires) { struct fnhe_hash_bucket *hash; struct fib_nh_exception *fnhe; struct rtable *rt; unsigned int i; int depth; u32 hval = fnhe_hashfun(daddr); spin_lock_bh(&fnhe_lock); hash = rcu_dereference(nh->nh_exceptions); if (!hash) { hash = kzalloc(FNHE_HASH_SIZE * sizeof(*hash), GFP_ATOMIC); if (!hash) goto out_unlock; rcu_assign_pointer(nh->nh_exceptions, hash); } hash += hval; depth = 0; for (fnhe = rcu_dereference(hash->chain); fnhe; fnhe = rcu_dereference(fnhe->fnhe_next)) { if (fnhe->fnhe_daddr == daddr) break; depth++; } if (fnhe) { if (gw) fnhe->fnhe_gw = gw; if (pmtu) { fnhe->fnhe_pmtu = pmtu; fnhe->fnhe_expires = max(1UL, expires); } /* Update all cached dsts too */ rt = rcu_dereference(fnhe->fnhe_rth_input); if (rt) fill_route_from_fnhe(rt, fnhe); rt = rcu_dereference(fnhe->fnhe_rth_output); if (rt) fill_route_from_fnhe(rt, fnhe); } else { if (depth > FNHE_RECLAIM_DEPTH) fnhe = fnhe_oldest(hash); else { fnhe = kzalloc(sizeof(*fnhe), GFP_ATOMIC); if (!fnhe) goto out_unlock; fnhe->fnhe_next = hash->chain; rcu_assign_pointer(hash->chain, fnhe); } fnhe->fnhe_genid = fnhe_genid(dev_net(nh->nh_dev)); fnhe->fnhe_daddr = daddr; fnhe->fnhe_gw = gw; fnhe->fnhe_pmtu = pmtu; fnhe->fnhe_expires = expires; /* Exception created; mark the cached routes for the nexthop * stale, so anyone caching it rechecks if this exception * applies to them. */ rt = rcu_dereference(nh->nh_rth_input); if (rt) rt->dst.obsolete = DST_OBSOLETE_KILL; for_each_possible_cpu(i) { struct rtable __rcu **prt; prt = per_cpu_ptr(nh->nh_pcpu_rth_output, i); rt = rcu_dereference(*prt); if (rt) rt->dst.obsolete = DST_OBSOLETE_KILL; } } fnhe->fnhe_stamp = jiffies; out_unlock: spin_unlock_bh(&fnhe_lock); } static void __ip_do_redirect(struct rtable *rt, struct sk_buff *skb, struct flowi4 *fl4, bool kill_route) { __be32 new_gw = icmp_hdr(skb)->un.gateway; __be32 old_gw = ip_hdr(skb)->saddr; struct net_device *dev = skb->dev; struct in_device *in_dev; struct fib_result res; struct neighbour *n; struct net *net; switch (icmp_hdr(skb)->code & 7) { case ICMP_REDIR_NET: case ICMP_REDIR_NETTOS: case ICMP_REDIR_HOST: case ICMP_REDIR_HOSTTOS: break; default: return; } if (rt->rt_gateway != old_gw) return; in_dev = __in_dev_get_rcu(dev); if (!in_dev) return; net = dev_net(dev); if (new_gw == old_gw || !IN_DEV_RX_REDIRECTS(in_dev) || ipv4_is_multicast(new_gw) || ipv4_is_lbcast(new_gw) || ipv4_is_zeronet(new_gw)) goto reject_redirect; if (!IN_DEV_SHARED_MEDIA(in_dev)) { if (!inet_addr_onlink(in_dev, new_gw, old_gw)) goto reject_redirect; if (IN_DEV_SEC_REDIRECTS(in_dev) && ip_fib_check_default(new_gw, dev)) goto reject_redirect; } else { if (inet_addr_type(net, new_gw) != RTN_UNICAST) goto reject_redirect; } n = ipv4_neigh_lookup(&rt->dst, NULL, &new_gw); if (!IS_ERR(n)) { if (!(n->nud_state & NUD_VALID)) { neigh_event_send(n, NULL); } else { if (fib_lookup(net, fl4, &res) == 0) { struct fib_nh *nh = &FIB_RES_NH(res); update_or_create_fnhe(nh, fl4->daddr, new_gw, 0, 0); } if (kill_route) rt->dst.obsolete = DST_OBSOLETE_KILL; call_netevent_notifiers(NETEVENT_NEIGH_UPDATE, n); } neigh_release(n); } return; reject_redirect: #ifdef CONFIG_IP_ROUTE_VERBOSE if (IN_DEV_LOG_MARTIANS(in_dev)) { const struct iphdr *iph = (const struct iphdr *) skb->data; __be32 daddr = iph->daddr; __be32 saddr = iph->saddr; net_info_ratelimited("Redirect from %pI4 on %s about %pI4 ignored\n" " Advised path = %pI4 -> %pI4\n", &old_gw, dev->name, &new_gw, &saddr, &daddr); } #endif ; } static void ip_do_redirect(struct dst_entry *dst, struct sock *sk, struct sk_buff *skb) { struct rtable *rt; struct flowi4 fl4; const struct iphdr *iph = (const struct iphdr *) skb->data; int oif = skb->dev->ifindex; u8 tos = RT_TOS(iph->tos); u8 prot = iph->protocol; u32 mark = skb->mark; rt = (struct rtable *) dst; __build_flow_key(&fl4, sk, iph, oif, tos, prot, mark, 0); __ip_do_redirect(rt, skb, &fl4, true); } static struct dst_entry *ipv4_negative_advice(struct dst_entry *dst) { struct rtable *rt = (struct rtable *)dst; struct dst_entry *ret = dst; if (rt) { if (dst->obsolete > 0) { ip_rt_put(rt); ret = NULL; } else if ((rt->rt_flags & RTCF_REDIRECTED) || rt->dst.expires) { ip_rt_put(rt); ret = NULL; } } return ret; } /* * Algorithm: * 1. The first ip_rt_redirect_number redirects are sent * with exponential backoff, then we stop sending them at all, * assuming that the host ignores our redirects. * 2. If we did not see packets requiring redirects * during ip_rt_redirect_silence, we assume that the host * forgot redirected route and start to send redirects again. * * This algorithm is much cheaper and more intelligent than dumb load limiting * in icmp.c. * * NOTE. Do not forget to inhibit load limiting for redirects (redundant) * and "frag. need" (breaks PMTU discovery) in icmp.c. */ void ip_rt_send_redirect(struct sk_buff *skb) { struct rtable *rt = skb_rtable(skb); struct in_device *in_dev; struct inet_peer *peer; struct net *net; int log_martians; rcu_read_lock(); in_dev = __in_dev_get_rcu(rt->dst.dev); if (!in_dev || !IN_DEV_TX_REDIRECTS(in_dev)) { rcu_read_unlock(); return; } log_martians = IN_DEV_LOG_MARTIANS(in_dev); rcu_read_unlock(); net = dev_net(rt->dst.dev); peer = inet_getpeer_v4(net->ipv4.peers, ip_hdr(skb)->saddr, 1); if (!peer) { icmp_send(skb, ICMP_REDIRECT, ICMP_REDIR_HOST, rt_nexthop(rt, ip_hdr(skb)->daddr)); return; } /* No redirected packets during ip_rt_redirect_silence; * reset the algorithm. */ if (time_after(jiffies, peer->rate_last + ip_rt_redirect_silence)) peer->rate_tokens = 0; /* Too many ignored redirects; do not send anything * set dst.rate_last to the last seen redirected packet. */ if (peer->rate_tokens >= ip_rt_redirect_number) { peer->rate_last = jiffies; goto out_put_peer; } /* Check for load limit; set rate_last to the latest sent * redirect. */ if (peer->rate_tokens == 0 || time_after(jiffies, (peer->rate_last + (ip_rt_redirect_load << peer->rate_tokens)))) { __be32 gw = rt_nexthop(rt, ip_hdr(skb)->daddr); icmp_send(skb, ICMP_REDIRECT, ICMP_REDIR_HOST, gw); peer->rate_last = jiffies; ++peer->rate_tokens; #ifdef CONFIG_IP_ROUTE_VERBOSE if (log_martians && peer->rate_tokens == ip_rt_redirect_number) net_warn_ratelimited("host %pI4/if%d ignores redirects for %pI4 to %pI4\n", &ip_hdr(skb)->saddr, inet_iif(skb), &ip_hdr(skb)->daddr, &gw); #endif } out_put_peer: inet_putpeer(peer); } static int ip_error(struct sk_buff *skb) { struct in_device *in_dev = __in_dev_get_rcu(skb->dev); struct rtable *rt = skb_rtable(skb); struct inet_peer *peer; unsigned long now; struct net *net; bool send; int code; net = dev_net(rt->dst.dev); if (!IN_DEV_FORWARD(in_dev)) { switch (rt->dst.error) { case EHOSTUNREACH: IP_INC_STATS_BH(net, IPSTATS_MIB_INADDRERRORS); break; case ENETUNREACH: IP_INC_STATS_BH(net, IPSTATS_MIB_INNOROUTES); break; } goto out; } switch (rt->dst.error) { case EINVAL: default: goto out; case EHOSTUNREACH: code = ICMP_HOST_UNREACH; break; case ENETUNREACH: code = ICMP_NET_UNREACH; IP_INC_STATS_BH(net, IPSTATS_MIB_INNOROUTES); break; case EACCES: code = ICMP_PKT_FILTERED; break; } peer = inet_getpeer_v4(net->ipv4.peers, ip_hdr(skb)->saddr, 1); send = true; if (peer) { now = jiffies; peer->rate_tokens += now - peer->rate_last; if (peer->rate_tokens > ip_rt_error_burst) peer->rate_tokens = ip_rt_error_burst; peer->rate_last = now; if (peer->rate_tokens >= ip_rt_error_cost) peer->rate_tokens -= ip_rt_error_cost; else send = false; inet_putpeer(peer); } if (send) icmp_send(skb, ICMP_DEST_UNREACH, code, 0); out: kfree_skb(skb); return 0; } static void __ip_rt_update_pmtu(struct rtable *rt, struct flowi4 *fl4, u32 mtu) { struct dst_entry *dst = &rt->dst; struct fib_result res; if (dst_metric_locked(dst, RTAX_MTU)) return; if (dst->dev->mtu < mtu) return; if (mtu < ip_rt_min_pmtu) mtu = ip_rt_min_pmtu; if (rt->rt_pmtu == mtu && time_before(jiffies, dst->expires - ip_rt_mtu_expires / 2)) return; rcu_read_lock(); if (fib_lookup(dev_net(dst->dev), fl4, &res) == 0) { struct fib_nh *nh = &FIB_RES_NH(res); update_or_create_fnhe(nh, fl4->daddr, 0, mtu, jiffies + ip_rt_mtu_expires); } rcu_read_unlock(); } static void ip_rt_update_pmtu(struct dst_entry *dst, struct sock *sk, struct sk_buff *skb, u32 mtu) { struct rtable *rt = (struct rtable *) dst; struct flowi4 fl4; ip_rt_build_flow_key(&fl4, sk, skb); __ip_rt_update_pmtu(rt, &fl4, mtu); } void ipv4_update_pmtu(struct sk_buff *skb, struct net *net, u32 mtu, int oif, u32 mark, u8 protocol, int flow_flags) { const struct iphdr *iph = (const struct iphdr *) skb->data; struct flowi4 fl4; struct rtable *rt; if (!mark) mark = IP4_REPLY_MARK(net, skb->mark); __build_flow_key(&fl4, NULL, iph, oif, RT_TOS(iph->tos), protocol, mark, flow_flags); rt = __ip_route_output_key(net, &fl4); if (!IS_ERR(rt)) { __ip_rt_update_pmtu(rt, &fl4, mtu); ip_rt_put(rt); } } EXPORT_SYMBOL_GPL(ipv4_update_pmtu); static void __ipv4_sk_update_pmtu(struct sk_buff *skb, struct sock *sk, u32 mtu) { const struct iphdr *iph = (const struct iphdr *) skb->data; struct flowi4 fl4; struct rtable *rt; __build_flow_key(&fl4, sk, iph, 0, 0, 0, 0, 0); if (!fl4.flowi4_mark) fl4.flowi4_mark = IP4_REPLY_MARK(sock_net(sk), skb->mark); rt = __ip_route_output_key(sock_net(sk), &fl4); if (!IS_ERR(rt)) { __ip_rt_update_pmtu(rt, &fl4, mtu); ip_rt_put(rt); } } void ipv4_sk_update_pmtu(struct sk_buff *skb, struct sock *sk, u32 mtu) { const struct iphdr *iph = (const struct iphdr *) skb->data; struct flowi4 fl4; struct rtable *rt; struct dst_entry *odst = NULL; bool new = false; bh_lock_sock(sk); if (!ip_sk_accept_pmtu(sk)) goto out; odst = sk_dst_get(sk); if (sock_owned_by_user(sk) || !odst) { __ipv4_sk_update_pmtu(skb, sk, mtu); goto out; } __build_flow_key(&fl4, sk, iph, 0, 0, 0, 0, 0); rt = (struct rtable *)odst; if (odst->obsolete && odst->ops->check(odst, 0) == NULL) { rt = ip_route_output_flow(sock_net(sk), &fl4, sk); if (IS_ERR(rt)) goto out; new = true; } __ip_rt_update_pmtu((struct rtable *) rt->dst.path, &fl4, mtu); if (!dst_check(&rt->dst, 0)) { if (new) dst_release(&rt->dst); rt = ip_route_output_flow(sock_net(sk), &fl4, sk); if (IS_ERR(rt)) goto out; new = true; } if (new) sk_dst_set(sk, &rt->dst); out: bh_unlock_sock(sk); dst_release(odst); } EXPORT_SYMBOL_GPL(ipv4_sk_update_pmtu); void ipv4_redirect(struct sk_buff *skb, struct net *net, int oif, u32 mark, u8 protocol, int flow_flags) { const struct iphdr *iph = (const struct iphdr *) skb->data; struct flowi4 fl4; struct rtable *rt; __build_flow_key(&fl4, NULL, iph, oif, RT_TOS(iph->tos), protocol, mark, flow_flags); rt = __ip_route_output_key(net, &fl4); if (!IS_ERR(rt)) { __ip_do_redirect(rt, skb, &fl4, false); ip_rt_put(rt); } } EXPORT_SYMBOL_GPL(ipv4_redirect); void ipv4_sk_redirect(struct sk_buff *skb, struct sock *sk) { const struct iphdr *iph = (const struct iphdr *) skb->data; struct flowi4 fl4; struct rtable *rt; __build_flow_key(&fl4, sk, iph, 0, 0, 0, 0, 0); rt = __ip_route_output_key(sock_net(sk), &fl4); if (!IS_ERR(rt)) { __ip_do_redirect(rt, skb, &fl4, false); ip_rt_put(rt); } } EXPORT_SYMBOL_GPL(ipv4_sk_redirect); static struct dst_entry *ipv4_dst_check(struct dst_entry *dst, u32 cookie) { struct rtable *rt = (struct rtable *) dst; /* All IPV4 dsts are created with ->obsolete set to the value * DST_OBSOLETE_FORCE_CHK which forces validation calls down * into this function always. * * When a PMTU/redirect information update invalidates a route, * this is indicated by setting obsolete to DST_OBSOLETE_KILL or * DST_OBSOLETE_DEAD by dst_free(). */ if (dst->obsolete != DST_OBSOLETE_FORCE_CHK || rt_is_expired(rt)) return NULL; return dst; } static void ipv4_link_failure(struct sk_buff *skb) { struct rtable *rt; icmp_send(skb, ICMP_DEST_UNREACH, ICMP_HOST_UNREACH, 0); rt = skb_rtable(skb); if (rt) dst_set_expires(&rt->dst, 0); } static int ip_rt_bug(struct sock *sk, struct sk_buff *skb) { pr_debug("%s: %pI4 -> %pI4, %s\n", __func__, &ip_hdr(skb)->saddr, &ip_hdr(skb)->daddr, skb->dev ? skb->dev->name : "?"); kfree_skb(skb); WARN_ON(1); return 0; } /* We do not cache source address of outgoing interface, because it is used only by IP RR, TS and SRR options, so that it out of fast path. BTW remember: "addr" is allowed to be not aligned in IP options! */ void ip_rt_get_source(u8 *addr, struct sk_buff *skb, struct rtable *rt) { __be32 src; if (rt_is_output_route(rt)) src = ip_hdr(skb)->saddr; else { struct fib_result res; struct flowi4 fl4; struct iphdr *iph; iph = ip_hdr(skb); memset(&fl4, 0, sizeof(fl4)); fl4.daddr = iph->daddr; fl4.saddr = iph->saddr; fl4.flowi4_tos = RT_TOS(iph->tos); fl4.flowi4_oif = rt->dst.dev->ifindex; fl4.flowi4_iif = skb->dev->ifindex; fl4.flowi4_mark = skb->mark; rcu_read_lock(); if (fib_lookup(dev_net(rt->dst.dev), &fl4, &res) == 0) src = FIB_RES_PREFSRC(dev_net(rt->dst.dev), res); else src = inet_select_addr(rt->dst.dev, rt_nexthop(rt, iph->daddr), RT_SCOPE_UNIVERSE); rcu_read_unlock(); } memcpy(addr, &src, 4); } #ifdef CONFIG_IP_ROUTE_CLASSID static void set_class_tag(struct rtable *rt, u32 tag) { if (!(rt->dst.tclassid & 0xFFFF)) rt->dst.tclassid |= tag & 0xFFFF; if (!(rt->dst.tclassid & 0xFFFF0000)) rt->dst.tclassid |= tag & 0xFFFF0000; } #endif static unsigned int ipv4_default_advmss(const struct dst_entry *dst) { unsigned int advmss = dst_metric_raw(dst, RTAX_ADVMSS); if (advmss == 0) { advmss = max_t(unsigned int, dst->dev->mtu - 40, ip_rt_min_advmss); if (advmss > 65535 - 40) advmss = 65535 - 40; } return advmss; } static unsigned int ipv4_mtu(const struct dst_entry *dst) { const struct rtable *rt = (const struct rtable *) dst; unsigned int mtu = rt->rt_pmtu; if (!mtu || time_after_eq(jiffies, rt->dst.expires)) mtu = dst_metric_raw(dst, RTAX_MTU); if (mtu) return mtu; mtu = dst->dev->mtu; if (unlikely(dst_metric_locked(dst, RTAX_MTU))) { if (rt->rt_uses_gateway && mtu > 576) mtu = 576; } return min_t(unsigned int, mtu, IP_MAX_MTU); } static struct fib_nh_exception *find_exception(struct fib_nh *nh, __be32 daddr) { struct fnhe_hash_bucket *hash = rcu_dereference(nh->nh_exceptions); struct fib_nh_exception *fnhe; u32 hval; if (!hash) return NULL; hval = fnhe_hashfun(daddr); for (fnhe = rcu_dereference(hash[hval].chain); fnhe; fnhe = rcu_dereference(fnhe->fnhe_next)) { if (fnhe->fnhe_daddr == daddr) return fnhe; } return NULL; } static bool rt_bind_exception(struct rtable *rt, struct fib_nh_exception *fnhe, __be32 daddr) { bool ret = false; spin_lock_bh(&fnhe_lock); if (daddr == fnhe->fnhe_daddr) { struct rtable __rcu **porig; struct rtable *orig; int genid = fnhe_genid(dev_net(rt->dst.dev)); if (rt_is_input_route(rt)) porig = &fnhe->fnhe_rth_input; else porig = &fnhe->fnhe_rth_output; orig = rcu_dereference(*porig); if (fnhe->fnhe_genid != genid) { fnhe->fnhe_genid = genid; fnhe->fnhe_gw = 0; fnhe->fnhe_pmtu = 0; fnhe->fnhe_expires = 0; fnhe_flush_routes(fnhe); orig = NULL; } fill_route_from_fnhe(rt, fnhe); if (!rt->rt_gateway) rt->rt_gateway = daddr; if (!(rt->dst.flags & DST_NOCACHE)) { rcu_assign_pointer(*porig, rt); if (orig) rt_free(orig); ret = true; } fnhe->fnhe_stamp = jiffies; } spin_unlock_bh(&fnhe_lock); return ret; } static bool rt_cache_route(struct fib_nh *nh, struct rtable *rt) { struct rtable *orig, *prev, **p; bool ret = true; if (rt_is_input_route(rt)) { p = (struct rtable **)&nh->nh_rth_input; } else { p = (struct rtable **)raw_cpu_ptr(nh->nh_pcpu_rth_output); } orig = *p; prev = cmpxchg(p, orig, rt); if (prev == orig) { if (orig) rt_free(orig); } else ret = false; return ret; } static DEFINE_SPINLOCK(rt_uncached_lock); static LIST_HEAD(rt_uncached_list); static void rt_add_uncached_list(struct rtable *rt) { spin_lock_bh(&rt_uncached_lock); list_add_tail(&rt->rt_uncached, &rt_uncached_list); spin_unlock_bh(&rt_uncached_lock); } static void ipv4_dst_destroy(struct dst_entry *dst) { struct rtable *rt = (struct rtable *) dst; if (!list_empty(&rt->rt_uncached)) { spin_lock_bh(&rt_uncached_lock); list_del(&rt->rt_uncached); spin_unlock_bh(&rt_uncached_lock); } } void rt_flush_dev(struct net_device *dev) { if (!list_empty(&rt_uncached_list)) { struct net *net = dev_net(dev); struct rtable *rt; spin_lock_bh(&rt_uncached_lock); list_for_each_entry(rt, &rt_uncached_list, rt_uncached) { if (rt->dst.dev != dev) continue; rt->dst.dev = net->loopback_dev; dev_hold(rt->dst.dev); dev_put(dev); } spin_unlock_bh(&rt_uncached_lock); } } static bool rt_cache_valid(const struct rtable *rt) { return rt && rt->dst.obsolete == DST_OBSOLETE_FORCE_CHK && !rt_is_expired(rt); } static void rt_set_nexthop(struct rtable *rt, __be32 daddr, const struct fib_result *res, struct fib_nh_exception *fnhe, struct fib_info *fi, u16 type, u32 itag) { bool cached = false; if (fi) { struct fib_nh *nh = &FIB_RES_NH(*res); if (nh->nh_gw && nh->nh_scope == RT_SCOPE_LINK) { rt->rt_gateway = nh->nh_gw; rt->rt_uses_gateway = 1; } dst_init_metrics(&rt->dst, fi->fib_metrics, true); #ifdef CONFIG_IP_ROUTE_CLASSID rt->dst.tclassid = nh->nh_tclassid; #endif if (unlikely(fnhe)) cached = rt_bind_exception(rt, fnhe, daddr); else if (!(rt->dst.flags & DST_NOCACHE)) cached = rt_cache_route(nh, rt); if (unlikely(!cached)) { /* Routes we intend to cache in nexthop exception or * FIB nexthop have the DST_NOCACHE bit clear. * However, if we are unsuccessful at storing this * route into the cache we really need to set it. */ rt->dst.flags |= DST_NOCACHE; if (!rt->rt_gateway) rt->rt_gateway = daddr; rt_add_uncached_list(rt); } } else rt_add_uncached_list(rt); #ifdef CONFIG_IP_ROUTE_CLASSID #ifdef CONFIG_IP_MULTIPLE_TABLES set_class_tag(rt, res->tclassid); #endif set_class_tag(rt, itag); #endif } static struct rtable *rt_dst_alloc(struct net_device *dev, bool nopolicy, bool noxfrm, bool will_cache) { return dst_alloc(&ipv4_dst_ops, dev, 1, DST_OBSOLETE_FORCE_CHK, (will_cache ? 0 : (DST_HOST | DST_NOCACHE)) | (nopolicy ? DST_NOPOLICY : 0) | (noxfrm ? DST_NOXFRM : 0)); } /* called in rcu_read_lock() section */ static int ip_route_input_mc(struct sk_buff *skb, __be32 daddr, __be32 saddr, u8 tos, struct net_device *dev, int our) { struct rtable *rth; struct in_device *in_dev = __in_dev_get_rcu(dev); u32 itag = 0; int err; /* Primary sanity checks. */ if (in_dev == NULL) return -EINVAL; if (ipv4_is_multicast(saddr) || ipv4_is_lbcast(saddr) || skb->protocol != htons(ETH_P_IP)) goto e_inval; if (likely(!IN_DEV_ROUTE_LOCALNET(in_dev))) if (ipv4_is_loopback(saddr)) goto e_inval; if (ipv4_is_zeronet(saddr)) { if (!ipv4_is_local_multicast(daddr)) goto e_inval; } else { err = fib_validate_source(skb, saddr, 0, tos, 0, dev, in_dev, &itag); if (err < 0) goto e_err; } rth = rt_dst_alloc(dev_net(dev)->loopback_dev, IN_DEV_CONF_GET(in_dev, NOPOLICY), false, false); if (!rth) goto e_nobufs; #ifdef CONFIG_IP_ROUTE_CLASSID rth->dst.tclassid = itag; #endif rth->dst.output = ip_rt_bug; rth->rt_genid = rt_genid_ipv4(dev_net(dev)); rth->rt_flags = RTCF_MULTICAST; rth->rt_type = RTN_MULTICAST; rth->rt_is_input= 1; rth->rt_iif = 0; rth->rt_pmtu = 0; rth->rt_gateway = 0; rth->rt_uses_gateway = 0; INIT_LIST_HEAD(&rth->rt_uncached); if (our) { rth->dst.input= ip_local_deliver; rth->rt_flags |= RTCF_LOCAL; } #ifdef CONFIG_IP_MROUTE if (!ipv4_is_local_multicast(daddr) && IN_DEV_MFORWARD(in_dev)) rth->dst.input = ip_mr_input; #endif RT_CACHE_STAT_INC(in_slow_mc); skb_dst_set(skb, &rth->dst); return 0; e_nobufs: return -ENOBUFS; e_inval: return -EINVAL; e_err: return err; } static void ip_handle_martian_source(struct net_device *dev, struct in_device *in_dev, struct sk_buff *skb, __be32 daddr, __be32 saddr) { RT_CACHE_STAT_INC(in_martian_src); #ifdef CONFIG_IP_ROUTE_VERBOSE if (IN_DEV_LOG_MARTIANS(in_dev) && net_ratelimit()) { /* * RFC1812 recommendation, if source is martian, * the only hint is MAC header. */ pr_warn("martian source %pI4 from %pI4, on dev %s\n", &daddr, &saddr, dev->name); if (dev->hard_header_len && skb_mac_header_was_set(skb)) { print_hex_dump(KERN_WARNING, "ll header: ", DUMP_PREFIX_OFFSET, 16, 1, skb_mac_header(skb), dev->hard_header_len, true); } } #endif } /* called in rcu_read_lock() section */ static int __mkroute_input(struct sk_buff *skb, const struct fib_result *res, struct in_device *in_dev, __be32 daddr, __be32 saddr, u32 tos) { struct fib_nh_exception *fnhe; struct rtable *rth; int err; struct in_device *out_dev; unsigned int flags = 0; bool do_cache; u32 itag = 0; /* get a working reference to the output device */ out_dev = __in_dev_get_rcu(FIB_RES_DEV(*res)); if (out_dev == NULL) { net_crit_ratelimited("Bug in ip_route_input_slow(). Please report.\n"); return -EINVAL; } err = fib_validate_source(skb, saddr, daddr, tos, FIB_RES_OIF(*res), in_dev->dev, in_dev, &itag); if (err < 0) { ip_handle_martian_source(in_dev->dev, in_dev, skb, daddr, saddr); goto cleanup; } do_cache = res->fi && !itag; if (out_dev == in_dev && err && IN_DEV_TX_REDIRECTS(out_dev) && skb->protocol == htons(ETH_P_IP) && (IN_DEV_SHARED_MEDIA(out_dev) || inet_addr_onlink(out_dev, saddr, FIB_RES_GW(*res)))) IPCB(skb)->flags |= IPSKB_DOREDIRECT; if (skb->protocol != htons(ETH_P_IP)) { /* Not IP (i.e. ARP). Do not create route, if it is * invalid for proxy arp. DNAT routes are always valid. * * Proxy arp feature have been extended to allow, ARP * replies back to the same interface, to support * Private VLAN switch technologies. See arp.c. */ if (out_dev == in_dev && IN_DEV_PROXY_ARP_PVLAN(in_dev) == 0) { err = -EINVAL; goto cleanup; } } fnhe = find_exception(&FIB_RES_NH(*res), daddr); if (do_cache) { if (fnhe != NULL) rth = rcu_dereference(fnhe->fnhe_rth_input); else rth = rcu_dereference(FIB_RES_NH(*res).nh_rth_input); if (rt_cache_valid(rth)) { skb_dst_set_noref(skb, &rth->dst); goto out; } } rth = rt_dst_alloc(out_dev->dev, IN_DEV_CONF_GET(in_dev, NOPOLICY), IN_DEV_CONF_GET(out_dev, NOXFRM), do_cache); if (!rth) { err = -ENOBUFS; goto cleanup; } rth->rt_genid = rt_genid_ipv4(dev_net(rth->dst.dev)); rth->rt_flags = flags; rth->rt_type = res->type; rth->rt_is_input = 1; rth->rt_iif = 0; rth->rt_pmtu = 0; rth->rt_gateway = 0; rth->rt_uses_gateway = 0; INIT_LIST_HEAD(&rth->rt_uncached); RT_CACHE_STAT_INC(in_slow_tot); rth->dst.input = ip_forward; rth->dst.output = ip_output; rt_set_nexthop(rth, daddr, res, fnhe, res->fi, res->type, itag); skb_dst_set(skb, &rth->dst); out: err = 0; cleanup: return err; } static int ip_mkroute_input(struct sk_buff *skb, struct fib_result *res, const struct flowi4 *fl4, struct in_device *in_dev, __be32 daddr, __be32 saddr, u32 tos) { #ifdef CONFIG_IP_ROUTE_MULTIPATH if (res->fi && res->fi->fib_nhs > 1) fib_select_multipath(res); #endif /* create a routing cache entry */ return __mkroute_input(skb, res, in_dev, daddr, saddr, tos); } /* * NOTE. We drop all the packets that has local source * addresses, because every properly looped back packet * must have correct destination already attached by output routine. * * Such approach solves two big problems: * 1. Not simplex devices are handled properly. * 2. IP spoofing attempts are filtered with 100% of guarantee. * called with rcu_read_lock() */ static int ip_route_input_slow(struct sk_buff *skb, __be32 daddr, __be32 saddr, u8 tos, struct net_device *dev) { struct fib_result res; struct in_device *in_dev = __in_dev_get_rcu(dev); struct flowi4 fl4; unsigned int flags = 0; u32 itag = 0; struct rtable *rth; int err = -EINVAL; struct net *net = dev_net(dev); bool do_cache; /* IP on this device is disabled. */ if (!in_dev) goto out; /* Check for the most weird martians, which can be not detected by fib_lookup. */ if (ipv4_is_multicast(saddr) || ipv4_is_lbcast(saddr)) goto martian_source; res.fi = NULL; if (ipv4_is_lbcast(daddr) || (saddr == 0 && daddr == 0)) goto brd_input; /* Accept zero addresses only to limited broadcast; * I even do not know to fix it or not. Waiting for complains :-) */ if (ipv4_is_zeronet(saddr)) goto martian_source; if (ipv4_is_zeronet(daddr)) goto martian_destination; /* Following code try to avoid calling IN_DEV_NET_ROUTE_LOCALNET(), * and call it once if daddr or/and saddr are loopback addresses */ if (ipv4_is_loopback(daddr)) { if (!IN_DEV_NET_ROUTE_LOCALNET(in_dev, net)) goto martian_destination; } else if (ipv4_is_loopback(saddr)) { if (!IN_DEV_NET_ROUTE_LOCALNET(in_dev, net)) goto martian_source; } /* * Now we are ready to route packet. */ fl4.flowi4_oif = 0; fl4.flowi4_iif = dev->ifindex; fl4.flowi4_mark = skb->mark; fl4.flowi4_tos = tos; fl4.flowi4_scope = RT_SCOPE_UNIVERSE; fl4.daddr = daddr; fl4.saddr = saddr; err = fib_lookup(net, &fl4, &res); if (err != 0) { if (!IN_DEV_FORWARD(in_dev)) err = -EHOSTUNREACH; goto no_route; } if (res.type == RTN_BROADCAST) goto brd_input; if (res.type == RTN_LOCAL) { err = fib_validate_source(skb, saddr, daddr, tos, 0, dev, in_dev, &itag); if (err < 0) goto martian_source_keep_err; goto local_input; } if (!IN_DEV_FORWARD(in_dev)) { err = -EHOSTUNREACH; goto no_route; } if (res.type != RTN_UNICAST) goto martian_destination; err = ip_mkroute_input(skb, &res, &fl4, in_dev, daddr, saddr, tos); out: return err; brd_input: if (skb->protocol != htons(ETH_P_IP)) goto e_inval; if (!ipv4_is_zeronet(saddr)) { err = fib_validate_source(skb, saddr, 0, tos, 0, dev, in_dev, &itag); if (err < 0) goto martian_source_keep_err; } flags |= RTCF_BROADCAST; res.type = RTN_BROADCAST; RT_CACHE_STAT_INC(in_brd); local_input: do_cache = false; if (res.fi) { if (!itag) { rth = rcu_dereference(FIB_RES_NH(res).nh_rth_input); if (rt_cache_valid(rth)) { skb_dst_set_noref(skb, &rth->dst); err = 0; goto out; } do_cache = true; } } rth = rt_dst_alloc(net->loopback_dev, IN_DEV_CONF_GET(in_dev, NOPOLICY), false, do_cache); if (!rth) goto e_nobufs; rth->dst.input= ip_local_deliver; rth->dst.output= ip_rt_bug; #ifdef CONFIG_IP_ROUTE_CLASSID rth->dst.tclassid = itag; #endif rth->rt_genid = rt_genid_ipv4(net); rth->rt_flags = flags|RTCF_LOCAL; rth->rt_type = res.type; rth->rt_is_input = 1; rth->rt_iif = 0; rth->rt_pmtu = 0; rth->rt_gateway = 0; rth->rt_uses_gateway = 0; INIT_LIST_HEAD(&rth->rt_uncached); RT_CACHE_STAT_INC(in_slow_tot); if (res.type == RTN_UNREACHABLE) { rth->dst.input= ip_error; rth->dst.error= -err; rth->rt_flags &= ~RTCF_LOCAL; } if (do_cache) { if (unlikely(!rt_cache_route(&FIB_RES_NH(res), rth))) { rth->dst.flags |= DST_NOCACHE; rt_add_uncached_list(rth); } } skb_dst_set(skb, &rth->dst); err = 0; goto out; no_route: RT_CACHE_STAT_INC(in_no_route); res.type = RTN_UNREACHABLE; res.fi = NULL; goto local_input; /* * Do not cache martian addresses: they should be logged (RFC1812) */ martian_destination: RT_CACHE_STAT_INC(in_martian_dst); #ifdef CONFIG_IP_ROUTE_VERBOSE if (IN_DEV_LOG_MARTIANS(in_dev)) net_warn_ratelimited("martian destination %pI4 from %pI4, dev %s\n", &daddr, &saddr, dev->name); #endif e_inval: err = -EINVAL; goto out; e_nobufs: err = -ENOBUFS; goto out; martian_source: err = -EINVAL; martian_source_keep_err: ip_handle_martian_source(dev, in_dev, skb, daddr, saddr); goto out; } int ip_route_input_noref(struct sk_buff *skb, __be32 daddr, __be32 saddr, u8 tos, struct net_device *dev) { int res; rcu_read_lock(); /* Multicast recognition logic is moved from route cache to here. The problem was that too many Ethernet cards have broken/missing hardware multicast filters :-( As result the host on multicasting network acquires a lot of useless route cache entries, sort of SDR messages from all the world. Now we try to get rid of them. Really, provided software IP multicast filter is organized reasonably (at least, hashed), it does not result in a slowdown comparing with route cache reject entries. Note, that multicast routers are not affected, because route cache entry is created eventually. */ if (ipv4_is_multicast(daddr)) { struct in_device *in_dev = __in_dev_get_rcu(dev); if (in_dev) { int our = ip_check_mc_rcu(in_dev, daddr, saddr, ip_hdr(skb)->protocol); if (our #ifdef CONFIG_IP_MROUTE || (!ipv4_is_local_multicast(daddr) && IN_DEV_MFORWARD(in_dev)) #endif ) { int res = ip_route_input_mc(skb, daddr, saddr, tos, dev, our); rcu_read_unlock(); return res; } } rcu_read_unlock(); return -EINVAL; } res = ip_route_input_slow(skb, daddr, saddr, tos, dev); rcu_read_unlock(); return res; } EXPORT_SYMBOL(ip_route_input_noref); /* called with rcu_read_lock() */ static struct rtable *__mkroute_output(const struct fib_result *res, const struct flowi4 *fl4, int orig_oif, struct net_device *dev_out, unsigned int flags) { struct fib_info *fi = res->fi; struct fib_nh_exception *fnhe; struct in_device *in_dev; u16 type = res->type; struct rtable *rth; bool do_cache; in_dev = __in_dev_get_rcu(dev_out); if (!in_dev) return ERR_PTR(-EINVAL); if (likely(!IN_DEV_ROUTE_LOCALNET(in_dev))) if (ipv4_is_loopback(fl4->saddr) && !(dev_out->flags & IFF_LOOPBACK)) return ERR_PTR(-EINVAL); if (ipv4_is_lbcast(fl4->daddr)) type = RTN_BROADCAST; else if (ipv4_is_multicast(fl4->daddr)) type = RTN_MULTICAST; else if (ipv4_is_zeronet(fl4->daddr)) return ERR_PTR(-EINVAL); if (dev_out->flags & IFF_LOOPBACK) flags |= RTCF_LOCAL; do_cache = true; if (type == RTN_BROADCAST) { flags |= RTCF_BROADCAST | RTCF_LOCAL; fi = NULL; } else if (type == RTN_MULTICAST) { flags |= RTCF_MULTICAST | RTCF_LOCAL; if (!ip_check_mc_rcu(in_dev, fl4->daddr, fl4->saddr, fl4->flowi4_proto)) flags &= ~RTCF_LOCAL; else do_cache = false; /* If multicast route do not exist use * default one, but do not gateway in this case. * Yes, it is hack. */ if (fi && res->prefixlen < 4) fi = NULL; } fnhe = NULL; do_cache &= fi != NULL; if (do_cache) { struct rtable __rcu **prth; struct fib_nh *nh = &FIB_RES_NH(*res); fnhe = find_exception(nh, fl4->daddr); if (fnhe) prth = &fnhe->fnhe_rth_output; else { if (unlikely(fl4->flowi4_flags & FLOWI_FLAG_KNOWN_NH && !(nh->nh_gw && nh->nh_scope == RT_SCOPE_LINK))) { do_cache = false; goto add; } prth = raw_cpu_ptr(nh->nh_pcpu_rth_output); } rth = rcu_dereference(*prth); if (rt_cache_valid(rth)) { dst_hold(&rth->dst); return rth; } } add: rth = rt_dst_alloc(dev_out, IN_DEV_CONF_GET(in_dev, NOPOLICY), IN_DEV_CONF_GET(in_dev, NOXFRM), do_cache); if (!rth) return ERR_PTR(-ENOBUFS); rth->dst.output = ip_output; rth->rt_genid = rt_genid_ipv4(dev_net(dev_out)); rth->rt_flags = flags; rth->rt_type = type; rth->rt_is_input = 0; rth->rt_iif = orig_oif ? : 0; rth->rt_pmtu = 0; rth->rt_gateway = 0; rth->rt_uses_gateway = 0; INIT_LIST_HEAD(&rth->rt_uncached); RT_CACHE_STAT_INC(out_slow_tot); if (flags & RTCF_LOCAL) rth->dst.input = ip_local_deliver; if (flags & (RTCF_BROADCAST | RTCF_MULTICAST)) { if (flags & RTCF_LOCAL && !(dev_out->flags & IFF_LOOPBACK)) { rth->dst.output = ip_mc_output; RT_CACHE_STAT_INC(out_slow_mc); } #ifdef CONFIG_IP_MROUTE if (type == RTN_MULTICAST) { if (IN_DEV_MFORWARD(in_dev) && !ipv4_is_local_multicast(fl4->daddr)) { rth->dst.input = ip_mr_input; rth->dst.output = ip_mc_output; } } #endif } rt_set_nexthop(rth, fl4->daddr, res, fnhe, fi, type, 0); return rth; } /* * Major route resolver routine. */ struct rtable *__ip_route_output_key(struct net *net, struct flowi4 *fl4) { struct net_device *dev_out = NULL; __u8 tos = RT_FL_TOS(fl4); unsigned int flags = 0; struct fib_result res; struct rtable *rth; int orig_oif; res.tclassid = 0; res.fi = NULL; res.table = NULL; orig_oif = fl4->flowi4_oif; fl4->flowi4_iif = LOOPBACK_IFINDEX; fl4->flowi4_tos = tos & IPTOS_RT_MASK; fl4->flowi4_scope = ((tos & RTO_ONLINK) ? RT_SCOPE_LINK : RT_SCOPE_UNIVERSE); rcu_read_lock(); if (fl4->saddr) { rth = ERR_PTR(-EINVAL); if (ipv4_is_multicast(fl4->saddr) || ipv4_is_lbcast(fl4->saddr) || ipv4_is_zeronet(fl4->saddr)) goto out; /* I removed check for oif == dev_out->oif here. It was wrong for two reasons: 1. ip_dev_find(net, saddr) can return wrong iface, if saddr is assigned to multiple interfaces. 2. Moreover, we are allowed to send packets with saddr of another iface. --ANK */ if (fl4->flowi4_oif == 0 && (ipv4_is_multicast(fl4->daddr) || ipv4_is_lbcast(fl4->daddr))) { /* It is equivalent to inet_addr_type(saddr) == RTN_LOCAL */ dev_out = __ip_dev_find(net, fl4->saddr, false); if (dev_out == NULL) goto out; /* Special hack: user can direct multicasts and limited broadcast via necessary interface without fiddling with IP_MULTICAST_IF or IP_PKTINFO. This hack is not just for fun, it allows vic,vat and friends to work. They bind socket to loopback, set ttl to zero and expect that it will work. From the viewpoint of routing cache they are broken, because we are not allowed to build multicast path with loopback source addr (look, routing cache cannot know, that ttl is zero, so that packet will not leave this host and route is valid). Luckily, this hack is good workaround. */ fl4->flowi4_oif = dev_out->ifindex; goto make_route; } if (!(fl4->flowi4_flags & FLOWI_FLAG_ANYSRC)) { /* It is equivalent to inet_addr_type(saddr) == RTN_LOCAL */ if (!__ip_dev_find(net, fl4->saddr, false)) goto out; } } if (fl4->flowi4_oif) { dev_out = dev_get_by_index_rcu(net, fl4->flowi4_oif); rth = ERR_PTR(-ENODEV); if (dev_out == NULL) goto out; /* RACE: Check return value of inet_select_addr instead. */ if (!(dev_out->flags & IFF_UP) || !__in_dev_get_rcu(dev_out)) { rth = ERR_PTR(-ENETUNREACH); goto out; } if (ipv4_is_local_multicast(fl4->daddr) || ipv4_is_lbcast(fl4->daddr)) { if (!fl4->saddr) fl4->saddr = inet_select_addr(dev_out, 0, RT_SCOPE_LINK); goto make_route; } if (!fl4->saddr) { if (ipv4_is_multicast(fl4->daddr)) fl4->saddr = inet_select_addr(dev_out, 0, fl4->flowi4_scope); else if (!fl4->daddr) fl4->saddr = inet_select_addr(dev_out, 0, RT_SCOPE_HOST); } } if (!fl4->daddr) { fl4->daddr = fl4->saddr; if (!fl4->daddr) fl4->daddr = fl4->saddr = htonl(INADDR_LOOPBACK); dev_out = net->loopback_dev; fl4->flowi4_oif = LOOPBACK_IFINDEX; res.type = RTN_LOCAL; flags |= RTCF_LOCAL; goto make_route; } if (fib_lookup(net, fl4, &res)) { res.fi = NULL; res.table = NULL; if (fl4->flowi4_oif) { /* Apparently, routing tables are wrong. Assume, that the destination is on link. WHY? DW. Because we are allowed to send to iface even if it has NO routes and NO assigned addresses. When oif is specified, routing tables are looked up with only one purpose: to catch if destination is gatewayed, rather than direct. Moreover, if MSG_DONTROUTE is set, we send packet, ignoring both routing tables and ifaddr state. --ANK We could make it even if oif is unknown, likely IPv6, but we do not. */ if (fl4->saddr == 0) fl4->saddr = inet_select_addr(dev_out, 0, RT_SCOPE_LINK); res.type = RTN_UNICAST; goto make_route; } rth = ERR_PTR(-ENETUNREACH); goto out; } if (res.type == RTN_LOCAL) { if (!fl4->saddr) { if (res.fi->fib_prefsrc) fl4->saddr = res.fi->fib_prefsrc; else fl4->saddr = fl4->daddr; } dev_out = net->loopback_dev; fl4->flowi4_oif = dev_out->ifindex; flags |= RTCF_LOCAL; goto make_route; } #ifdef CONFIG_IP_ROUTE_MULTIPATH if (res.fi->fib_nhs > 1 && fl4->flowi4_oif == 0) fib_select_multipath(&res); else #endif if (!res.prefixlen && res.table->tb_num_default > 1 && res.type == RTN_UNICAST && !fl4->flowi4_oif) fib_select_default(&res); if (!fl4->saddr) fl4->saddr = FIB_RES_PREFSRC(net, res); dev_out = FIB_RES_DEV(res); fl4->flowi4_oif = dev_out->ifindex; make_route: rth = __mkroute_output(&res, fl4, orig_oif, dev_out, flags); out: rcu_read_unlock(); return rth; } EXPORT_SYMBOL_GPL(__ip_route_output_key); static struct dst_entry *ipv4_blackhole_dst_check(struct dst_entry *dst, u32 cookie) { return NULL; } static unsigned int ipv4_blackhole_mtu(const struct dst_entry *dst) { unsigned int mtu = dst_metric_raw(dst, RTAX_MTU); return mtu ? : dst->dev->mtu; } static void ipv4_rt_blackhole_update_pmtu(struct dst_entry *dst, struct sock *sk, struct sk_buff *skb, u32 mtu) { } static void ipv4_rt_blackhole_redirect(struct dst_entry *dst, struct sock *sk, struct sk_buff *skb) { } static u32 *ipv4_rt_blackhole_cow_metrics(struct dst_entry *dst, unsigned long old) { return NULL; } static struct dst_ops ipv4_dst_blackhole_ops = { .family = AF_INET, .protocol = cpu_to_be16(ETH_P_IP), .check = ipv4_blackhole_dst_check, .mtu = ipv4_blackhole_mtu, .default_advmss = ipv4_default_advmss, .update_pmtu = ipv4_rt_blackhole_update_pmtu, .redirect = ipv4_rt_blackhole_redirect, .cow_metrics = ipv4_rt_blackhole_cow_metrics, .neigh_lookup = ipv4_neigh_lookup, }; struct dst_entry *ipv4_blackhole_route(struct net *net, struct dst_entry *dst_orig) { struct rtable *ort = (struct rtable *) dst_orig; struct rtable *rt; rt = dst_alloc(&ipv4_dst_blackhole_ops, NULL, 1, DST_OBSOLETE_NONE, 0); if (rt) { struct dst_entry *new = &rt->dst; new->__use = 1; new->input = dst_discard; new->output = dst_discard_sk; new->dev = ort->dst.dev; if (new->dev) dev_hold(new->dev); rt->rt_is_input = ort->rt_is_input; rt->rt_iif = ort->rt_iif; rt->rt_pmtu = ort->rt_pmtu; rt->rt_genid = rt_genid_ipv4(net); rt->rt_flags = ort->rt_flags; rt->rt_type = ort->rt_type; rt->rt_gateway = ort->rt_gateway; rt->rt_uses_gateway = ort->rt_uses_gateway; INIT_LIST_HEAD(&rt->rt_uncached); dst_free(new); } dst_release(dst_orig); return rt ? &rt->dst : ERR_PTR(-ENOMEM); } struct rtable *ip_route_output_flow(struct net *net, struct flowi4 *flp4, struct sock *sk) { struct rtable *rt = __ip_route_output_key(net, flp4); if (IS_ERR(rt)) return rt; if (flp4->flowi4_proto) rt = (struct rtable *)xfrm_lookup_route(net, &rt->dst, flowi4_to_flowi(flp4), sk, 0); return rt; } EXPORT_SYMBOL_GPL(ip_route_output_flow); static int rt_fill_info(struct net *net, __be32 dst, __be32 src, struct flowi4 *fl4, struct sk_buff *skb, u32 portid, u32 seq, int event, int nowait, unsigned int flags) { struct rtable *rt = skb_rtable(skb); struct rtmsg *r; struct nlmsghdr *nlh; unsigned long expires = 0; u32 error; u32 metrics[RTAX_MAX]; nlh = nlmsg_put(skb, portid, seq, event, sizeof(*r), flags); if (nlh == NULL) return -EMSGSIZE; r = nlmsg_data(nlh); r->rtm_family = AF_INET; r->rtm_dst_len = 32; r->rtm_src_len = 0; r->rtm_tos = fl4->flowi4_tos; r->rtm_table = RT_TABLE_MAIN; if (nla_put_u32(skb, RTA_TABLE, RT_TABLE_MAIN)) goto nla_put_failure; r->rtm_type = rt->rt_type; r->rtm_scope = RT_SCOPE_UNIVERSE; r->rtm_protocol = RTPROT_UNSPEC; r->rtm_flags = (rt->rt_flags & ~0xFFFF) | RTM_F_CLONED; if (rt->rt_flags & RTCF_NOTIFY) r->rtm_flags |= RTM_F_NOTIFY; if (IPCB(skb)->flags & IPSKB_DOREDIRECT) r->rtm_flags |= RTCF_DOREDIRECT; if (nla_put_be32(skb, RTA_DST, dst)) goto nla_put_failure; if (src) { r->rtm_src_len = 32; if (nla_put_be32(skb, RTA_SRC, src)) goto nla_put_failure; } if (rt->dst.dev && nla_put_u32(skb, RTA_OIF, rt->dst.dev->ifindex)) goto nla_put_failure; #ifdef CONFIG_IP_ROUTE_CLASSID if (rt->dst.tclassid && nla_put_u32(skb, RTA_FLOW, rt->dst.tclassid)) goto nla_put_failure; #endif if (!rt_is_input_route(rt) && fl4->saddr != src) { if (nla_put_be32(skb, RTA_PREFSRC, fl4->saddr)) goto nla_put_failure; } if (rt->rt_uses_gateway && nla_put_be32(skb, RTA_GATEWAY, rt->rt_gateway)) goto nla_put_failure; expires = rt->dst.expires; if (expires) { unsigned long now = jiffies; if (time_before(now, expires)) expires -= now; else expires = 0; } memcpy(metrics, dst_metrics_ptr(&rt->dst), sizeof(metrics)); if (rt->rt_pmtu && expires) metrics[RTAX_MTU - 1] = rt->rt_pmtu; if (rtnetlink_put_metrics(skb, metrics) < 0) goto nla_put_failure; if (fl4->flowi4_mark && nla_put_u32(skb, RTA_MARK, fl4->flowi4_mark)) goto nla_put_failure; error = rt->dst.error; if (rt_is_input_route(rt)) { #ifdef CONFIG_IP_MROUTE if (ipv4_is_multicast(dst) && !ipv4_is_local_multicast(dst) && IPV4_DEVCONF_ALL(net, MC_FORWARDING)) { int err = ipmr_get_route(net, skb, fl4->saddr, fl4->daddr, r, nowait); if (err <= 0) { if (!nowait) { if (err == 0) return 0; goto nla_put_failure; } else { if (err == -EMSGSIZE) goto nla_put_failure; error = err; } } } else #endif if (nla_put_u32(skb, RTA_IIF, skb->dev->ifindex)) goto nla_put_failure; } if (rtnl_put_cacheinfo(skb, &rt->dst, 0, expires, error) < 0) goto nla_put_failure; return nlmsg_end(skb, nlh); nla_put_failure: nlmsg_cancel(skb, nlh); return -EMSGSIZE; } static int inet_rtm_getroute(struct sk_buff *in_skb, struct nlmsghdr *nlh) { struct net *net = sock_net(in_skb->sk); struct rtmsg *rtm; struct nlattr *tb[RTA_MAX+1]; struct rtable *rt = NULL; struct flowi4 fl4; __be32 dst = 0; __be32 src = 0; u32 iif; int err; int mark; struct sk_buff *skb; err = nlmsg_parse(nlh, sizeof(*rtm), tb, RTA_MAX, rtm_ipv4_policy); if (err < 0) goto errout; rtm = nlmsg_data(nlh); skb = alloc_skb(NLMSG_GOODSIZE, GFP_KERNEL); if (skb == NULL) { err = -ENOBUFS; goto errout; } /* Reserve room for dummy headers, this skb can pass through good chunk of routing engine. */ skb_reset_mac_header(skb); skb_reset_network_header(skb); /* Bugfix: need to give ip_route_input enough of an IP header to not gag. */ ip_hdr(skb)->protocol = IPPROTO_ICMP; skb_reserve(skb, MAX_HEADER + sizeof(struct iphdr)); src = tb[RTA_SRC] ? nla_get_be32(tb[RTA_SRC]) : 0; dst = tb[RTA_DST] ? nla_get_be32(tb[RTA_DST]) : 0; iif = tb[RTA_IIF] ? nla_get_u32(tb[RTA_IIF]) : 0; mark = tb[RTA_MARK] ? nla_get_u32(tb[RTA_MARK]) : 0; memset(&fl4, 0, sizeof(fl4)); fl4.daddr = dst; fl4.saddr = src; fl4.flowi4_tos = rtm->rtm_tos; fl4.flowi4_oif = tb[RTA_OIF] ? nla_get_u32(tb[RTA_OIF]) : 0; fl4.flowi4_mark = mark; if (iif) { struct net_device *dev; dev = __dev_get_by_index(net, iif); if (dev == NULL) { err = -ENODEV; goto errout_free; } skb->protocol = htons(ETH_P_IP); skb->dev = dev; skb->mark = mark; local_bh_disable(); err = ip_route_input(skb, dst, src, rtm->rtm_tos, dev); local_bh_enable(); rt = skb_rtable(skb); if (err == 0 && rt->dst.error) err = -rt->dst.error; } else { rt = ip_route_output_key(net, &fl4); err = 0; if (IS_ERR(rt)) err = PTR_ERR(rt); } if (err) goto errout_free; skb_dst_set(skb, &rt->dst); if (rtm->rtm_flags & RTM_F_NOTIFY) rt->rt_flags |= RTCF_NOTIFY; err = rt_fill_info(net, dst, src, &fl4, skb, NETLINK_CB(in_skb).portid, nlh->nlmsg_seq, RTM_NEWROUTE, 0, 0); if (err <= 0) goto errout_free; err = rtnl_unicast(skb, net, NETLINK_CB(in_skb).portid); errout: return err; errout_free: kfree_skb(skb); goto errout; } void ip_rt_multicast_event(struct in_device *in_dev) { rt_cache_flush(dev_net(in_dev->dev)); } #ifdef CONFIG_SYSCTL static int ip_rt_gc_timeout __read_mostly = RT_GC_TIMEOUT; static int ip_rt_gc_interval __read_mostly = 60 * HZ; static int ip_rt_gc_min_interval __read_mostly = HZ / 2; static int ip_rt_gc_elasticity __read_mostly = 8; static int ipv4_sysctl_rtcache_flush(struct ctl_table *__ctl, int write, void __user *buffer, size_t *lenp, loff_t *ppos) { struct net *net = (struct net *)__ctl->extra1; if (write) { rt_cache_flush(net); fnhe_genid_bump(net); return 0; } return -EINVAL; } static struct ctl_table ipv4_route_table[] = { { .procname = "gc_thresh", .data = &ipv4_dst_ops.gc_thresh, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "max_size", .data = &ip_rt_max_size, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { /* Deprecated. Use gc_min_interval_ms */ .procname = "gc_min_interval", .data = &ip_rt_gc_min_interval, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec_jiffies, }, { .procname = "gc_min_interval_ms", .data = &ip_rt_gc_min_interval, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec_ms_jiffies, }, { .procname = "gc_timeout", .data = &ip_rt_gc_timeout, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec_jiffies, }, { .procname = "gc_interval", .data = &ip_rt_gc_interval, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec_jiffies, }, { .procname = "redirect_load", .data = &ip_rt_redirect_load, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "redirect_number", .data = &ip_rt_redirect_number, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "redirect_silence", .data = &ip_rt_redirect_silence, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "error_cost", .data = &ip_rt_error_cost, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "error_burst", .data = &ip_rt_error_burst, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "gc_elasticity", .data = &ip_rt_gc_elasticity, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "mtu_expires", .data = &ip_rt_mtu_expires, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec_jiffies, }, { .procname = "min_pmtu", .data = &ip_rt_min_pmtu, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "min_adv_mss", .data = &ip_rt_min_advmss, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { } }; static struct ctl_table ipv4_route_flush_table[] = { { .procname = "flush", .maxlen = sizeof(int), .mode = 0200, .proc_handler = ipv4_sysctl_rtcache_flush, }, { }, }; static __net_init int sysctl_route_net_init(struct net *net) { struct ctl_table *tbl; tbl = ipv4_route_flush_table; if (!net_eq(net, &init_net)) { tbl = kmemdup(tbl, sizeof(ipv4_route_flush_table), GFP_KERNEL); if (tbl == NULL) goto err_dup; /* Don't export sysctls to unprivileged users */ if (net->user_ns != &init_user_ns) tbl[0].procname = NULL; } tbl[0].extra1 = net; net->ipv4.route_hdr = register_net_sysctl(net, "net/ipv4/route", tbl); if (net->ipv4.route_hdr == NULL) goto err_reg; return 0; err_reg: if (tbl != ipv4_route_flush_table) kfree(tbl); err_dup: return -ENOMEM; } static __net_exit void sysctl_route_net_exit(struct net *net) { struct ctl_table *tbl; tbl = net->ipv4.route_hdr->ctl_table_arg; unregister_net_sysctl_table(net->ipv4.route_hdr); BUG_ON(tbl == ipv4_route_flush_table); kfree(tbl); } static __net_initdata struct pernet_operations sysctl_route_ops = { .init = sysctl_route_net_init, .exit = sysctl_route_net_exit, }; #endif static __net_init int rt_genid_init(struct net *net) { atomic_set(&net->ipv4.rt_genid, 0); atomic_set(&net->fnhe_genid, 0); get_random_bytes(&net->ipv4.dev_addr_genid, sizeof(net->ipv4.dev_addr_genid)); return 0; } static __net_initdata struct pernet_operations rt_genid_ops = { .init = rt_genid_init, }; static int __net_init ipv4_inetpeer_init(struct net *net) { struct inet_peer_base *bp = kmalloc(sizeof(*bp), GFP_KERNEL); if (!bp) return -ENOMEM; inet_peer_base_init(bp); net->ipv4.peers = bp; return 0; } static void __net_exit ipv4_inetpeer_exit(struct net *net) { struct inet_peer_base *bp = net->ipv4.peers; net->ipv4.peers = NULL; inetpeer_invalidate_tree(bp); kfree(bp); } static __net_initdata struct pernet_operations ipv4_inetpeer_ops = { .init = ipv4_inetpeer_init, .exit = ipv4_inetpeer_exit, }; #ifdef CONFIG_IP_ROUTE_CLASSID struct ip_rt_acct __percpu *ip_rt_acct __read_mostly; #endif /* CONFIG_IP_ROUTE_CLASSID */ int __init ip_rt_init(void) { int rc = 0; ip_idents = kmalloc(IP_IDENTS_SZ * sizeof(*ip_idents), GFP_KERNEL); if (!ip_idents) panic("IP: failed to allocate ip_idents\n"); prandom_bytes(ip_idents, IP_IDENTS_SZ * sizeof(*ip_idents)); #ifdef CONFIG_IP_ROUTE_CLASSID ip_rt_acct = __alloc_percpu(256 * sizeof(struct ip_rt_acct), __alignof__(struct ip_rt_acct)); if (!ip_rt_acct) panic("IP: failed to allocate ip_rt_acct\n"); #endif ipv4_dst_ops.kmem_cachep = kmem_cache_create("ip_dst_cache", sizeof(struct rtable), 0, SLAB_HWCACHE_ALIGN|SLAB_PANIC, NULL); ipv4_dst_blackhole_ops.kmem_cachep = ipv4_dst_ops.kmem_cachep; if (dst_entries_init(&ipv4_dst_ops) < 0) panic("IP: failed to allocate ipv4_dst_ops counter\n"); if (dst_entries_init(&ipv4_dst_blackhole_ops) < 0) panic("IP: failed to allocate ipv4_dst_blackhole_ops counter\n"); ipv4_dst_ops.gc_thresh = ~0; ip_rt_max_size = INT_MAX; devinet_init(); ip_fib_init(); if (ip_rt_proc_init()) pr_err("Unable to create route proc files\n"); #ifdef CONFIG_XFRM xfrm_init(); xfrm4_init(); #endif rtnl_register(PF_INET, RTM_GETROUTE, inet_rtm_getroute, NULL, NULL); #ifdef CONFIG_SYSCTL register_pernet_subsys(&sysctl_route_ops); #endif register_pernet_subsys(&rt_genid_ops); register_pernet_subsys(&ipv4_inetpeer_ops); return rc; } #ifdef CONFIG_SYSCTL /* * We really need to sanitize the damn ipv4 init order, then all * this nonsense will go away. */ void __init ip_static_sysctl_init(void) { register_net_sysctl(&init_net, "net/ipv4/route", ipv4_route_table); } #endif
./CrossVul/dataset_final_sorted/CWE-17/c/good_1482_2
crossvul-cpp_data_bad_2348_3
/* * Copyright (C) 1991, 1992 Linus Torvalds * Copyright (C) 2000, 2001, 2002 Andi Kleen, SuSE Labs */ #include <linux/kallsyms.h> #include <linux/kprobes.h> #include <linux/uaccess.h> #include <linux/hardirq.h> #include <linux/kdebug.h> #include <linux/module.h> #include <linux/ptrace.h> #include <linux/kexec.h> #include <linux/sysfs.h> #include <linux/bug.h> #include <linux/nmi.h> #include <asm/stacktrace.h> #define N_EXCEPTION_STACKS_END \ (N_EXCEPTION_STACKS + DEBUG_STKSZ/EXCEPTION_STKSZ - 2) static char x86_stack_ids[][8] = { [ DEBUG_STACK-1 ] = "#DB", [ NMI_STACK-1 ] = "NMI", [ DOUBLEFAULT_STACK-1 ] = "#DF", [ STACKFAULT_STACK-1 ] = "#SS", [ MCE_STACK-1 ] = "#MC", #if DEBUG_STKSZ > EXCEPTION_STKSZ [ N_EXCEPTION_STACKS ... N_EXCEPTION_STACKS_END ] = "#DB[?]" #endif }; static unsigned long *in_exception_stack(unsigned cpu, unsigned long stack, unsigned *usedp, char **idp) { unsigned k; /* * Iterate over all exception stacks, and figure out whether * 'stack' is in one of them: */ for (k = 0; k < N_EXCEPTION_STACKS; k++) { unsigned long end = per_cpu(orig_ist, cpu).ist[k]; /* * Is 'stack' above this exception frame's end? * If yes then skip to the next frame. */ if (stack >= end) continue; /* * Is 'stack' above this exception frame's start address? * If yes then we found the right frame. */ if (stack >= end - EXCEPTION_STKSZ) { /* * Make sure we only iterate through an exception * stack once. If it comes up for the second time * then there's something wrong going on - just * break out and return NULL: */ if (*usedp & (1U << k)) break; *usedp |= 1U << k; *idp = x86_stack_ids[k]; return (unsigned long *)end; } /* * If this is a debug stack, and if it has a larger size than * the usual exception stacks, then 'stack' might still * be within the lower portion of the debug stack: */ #if DEBUG_STKSZ > EXCEPTION_STKSZ if (k == DEBUG_STACK - 1 && stack >= end - DEBUG_STKSZ) { unsigned j = N_EXCEPTION_STACKS - 1; /* * Black magic. A large debug stack is composed of * multiple exception stack entries, which we * iterate through now. Dont look: */ do { ++j; end -= EXCEPTION_STKSZ; x86_stack_ids[j][4] = '1' + (j - N_EXCEPTION_STACKS); } while (stack < end - EXCEPTION_STKSZ); if (*usedp & (1U << j)) break; *usedp |= 1U << j; *idp = x86_stack_ids[j]; return (unsigned long *)end; } #endif } return NULL; } static inline int in_irq_stack(unsigned long *stack, unsigned long *irq_stack, unsigned long *irq_stack_end) { return (stack >= irq_stack && stack < irq_stack_end); } static const unsigned long irq_stack_size = (IRQ_STACK_SIZE - 64) / sizeof(unsigned long); enum stack_type { STACK_IS_UNKNOWN, STACK_IS_NORMAL, STACK_IS_EXCEPTION, STACK_IS_IRQ, }; static enum stack_type analyze_stack(int cpu, struct task_struct *task, unsigned long *stack, unsigned long **stack_end, unsigned long *irq_stack, unsigned *used, char **id) { unsigned long addr; addr = ((unsigned long)stack & (~(THREAD_SIZE - 1))); if ((unsigned long)task_stack_page(task) == addr) return STACK_IS_NORMAL; *stack_end = in_exception_stack(cpu, (unsigned long)stack, used, id); if (*stack_end) return STACK_IS_EXCEPTION; if (!irq_stack) return STACK_IS_NORMAL; *stack_end = irq_stack; irq_stack = irq_stack - irq_stack_size; if (in_irq_stack(stack, irq_stack, *stack_end)) return STACK_IS_IRQ; return STACK_IS_UNKNOWN; } /* * x86-64 can have up to three kernel stacks: * process stack * interrupt stack * severe exception (double fault, nmi, stack fault, debug, mce) hardware stack */ void dump_trace(struct task_struct *task, struct pt_regs *regs, unsigned long *stack, unsigned long bp, const struct stacktrace_ops *ops, void *data) { const unsigned cpu = get_cpu(); struct thread_info *tinfo; unsigned long *irq_stack = (unsigned long *)per_cpu(irq_stack_ptr, cpu); unsigned long dummy; unsigned used = 0; int graph = 0; int done = 0; if (!task) task = current; if (!stack) { if (regs) stack = (unsigned long *)regs->sp; else if (task != current) stack = (unsigned long *)task->thread.sp; else stack = &dummy; } if (!bp) bp = stack_frame(task, regs); /* * Print function call entries in all stacks, starting at the * current stack address. If the stacks consist of nested * exceptions */ tinfo = task_thread_info(task); while (!done) { unsigned long *stack_end; enum stack_type stype; char *id; stype = analyze_stack(cpu, task, stack, &stack_end, irq_stack, &used, &id); /* Default finish unless specified to continue */ done = 1; switch (stype) { /* Break out early if we are on the thread stack */ case STACK_IS_NORMAL: break; case STACK_IS_EXCEPTION: if (ops->stack(data, id) < 0) break; bp = ops->walk_stack(tinfo, stack, bp, ops, data, stack_end, &graph); ops->stack(data, "<EOE>"); /* * We link to the next stack via the * second-to-last pointer (index -2 to end) in the * exception stack: */ stack = (unsigned long *) stack_end[-2]; done = 0; break; case STACK_IS_IRQ: if (ops->stack(data, "IRQ") < 0) break; bp = ops->walk_stack(tinfo, stack, bp, ops, data, stack_end, &graph); /* * We link to the next stack (which would be * the process stack normally) the last * pointer (index -1 to end) in the IRQ stack: */ stack = (unsigned long *) (stack_end[-1]); irq_stack = NULL; ops->stack(data, "EOI"); done = 0; break; case STACK_IS_UNKNOWN: ops->stack(data, "UNK"); break; } } /* * This handles the process stack: */ bp = ops->walk_stack(tinfo, stack, bp, ops, data, NULL, &graph); put_cpu(); } EXPORT_SYMBOL(dump_trace); void show_stack_log_lvl(struct task_struct *task, struct pt_regs *regs, unsigned long *sp, unsigned long bp, char *log_lvl) { unsigned long *irq_stack_end; unsigned long *irq_stack; unsigned long *stack; int cpu; int i; preempt_disable(); cpu = smp_processor_id(); irq_stack_end = (unsigned long *)(per_cpu(irq_stack_ptr, cpu)); irq_stack = (unsigned long *)(per_cpu(irq_stack_ptr, cpu) - IRQ_STACK_SIZE); /* * Debugging aid: "show_stack(NULL, NULL);" prints the * back trace for this cpu: */ if (sp == NULL) { if (task) sp = (unsigned long *)task->thread.sp; else sp = (unsigned long *)&sp; } stack = sp; for (i = 0; i < kstack_depth_to_print; i++) { if (stack >= irq_stack && stack <= irq_stack_end) { if (stack == irq_stack_end) { stack = (unsigned long *) (irq_stack_end[-1]); pr_cont(" <EOI> "); } } else { if (((long) stack & (THREAD_SIZE-1)) == 0) break; } if (i && ((i % STACKSLOTS_PER_LINE) == 0)) pr_cont("\n"); pr_cont(" %016lx", *stack++); touch_nmi_watchdog(); } preempt_enable(); pr_cont("\n"); show_trace_log_lvl(task, regs, sp, bp, log_lvl); } void show_regs(struct pt_regs *regs) { int i; unsigned long sp; sp = regs->sp; show_regs_print_info(KERN_DEFAULT); __show_regs(regs, 1); /* * When in-kernel, we also print out the stack and code at the * time of the fault.. */ if (!user_mode(regs)) { unsigned int code_prologue = code_bytes * 43 / 64; unsigned int code_len = code_bytes; unsigned char c; u8 *ip; printk(KERN_DEFAULT "Stack:\n"); show_stack_log_lvl(NULL, regs, (unsigned long *)sp, 0, KERN_DEFAULT); printk(KERN_DEFAULT "Code: "); ip = (u8 *)regs->ip - code_prologue; if (ip < (u8 *)PAGE_OFFSET || probe_kernel_address(ip, c)) { /* try starting at IP */ ip = (u8 *)regs->ip; code_len = code_len - code_prologue + 1; } for (i = 0; i < code_len; i++, ip++) { if (ip < (u8 *)PAGE_OFFSET || probe_kernel_address(ip, c)) { pr_cont(" Bad RIP value."); break; } if (ip == (u8 *)regs->ip) pr_cont("<%02x> ", c); else pr_cont("%02x ", c); } } pr_cont("\n"); } int is_valid_bugaddr(unsigned long ip) { unsigned short ud2; if (__copy_from_user(&ud2, (const void __user *) ip, sizeof(ud2))) return 0; return ud2 == 0x0b0f; }
./CrossVul/dataset_final_sorted/CWE-17/c/bad_2348_3
crossvul-cpp_data_bad_2306_3
/* * linux/fs/super.c * * Copyright (C) 1991, 1992 Linus Torvalds * * super.c contains code to handle: - mount structures * - super-block tables * - filesystem drivers list * - mount system call * - umount system call * - ustat system call * * GK 2/5/95 - Changed to support mounting the root fs via NFS * * Added kerneld support: Jacques Gelinas and Bjorn Ekwall * Added change_root: Werner Almesberger & Hans Lermen, Feb '96 * Added options to /proc/mounts: * Torbjörn Lindh (torbjorn.lindh@gopta.se), April 14, 1996. * Added devfs support: Richard Gooch <rgooch@atnf.csiro.au>, 13-JAN-1998 * Heavily rewritten for 'one fs - one tree' dcache architecture. AV, Mar 2000 */ #include <linux/export.h> #include <linux/slab.h> #include <linux/acct.h> #include <linux/blkdev.h> #include <linux/mount.h> #include <linux/security.h> #include <linux/writeback.h> /* for the emergency remount stuff */ #include <linux/idr.h> #include <linux/mutex.h> #include <linux/backing-dev.h> #include <linux/rculist_bl.h> #include <linux/cleancache.h> #include <linux/fsnotify.h> #include <linux/lockdep.h> #include "internal.h" LIST_HEAD(super_blocks); DEFINE_SPINLOCK(sb_lock); static char *sb_writers_name[SB_FREEZE_LEVELS] = { "sb_writers", "sb_pagefaults", "sb_internal", }; /* * One thing we have to be careful of with a per-sb shrinker is that we don't * drop the last active reference to the superblock from within the shrinker. * If that happens we could trigger unregistering the shrinker from within the * shrinker path and that leads to deadlock on the shrinker_rwsem. Hence we * take a passive reference to the superblock to avoid this from occurring. */ static unsigned long super_cache_scan(struct shrinker *shrink, struct shrink_control *sc) { struct super_block *sb; long fs_objects = 0; long total_objects; long freed = 0; long dentries; long inodes; sb = container_of(shrink, struct super_block, s_shrink); /* * Deadlock avoidance. We may hold various FS locks, and we don't want * to recurse into the FS that called us in clear_inode() and friends.. */ if (!(sc->gfp_mask & __GFP_FS)) return SHRINK_STOP; if (!grab_super_passive(sb)) return SHRINK_STOP; if (sb->s_op->nr_cached_objects) fs_objects = sb->s_op->nr_cached_objects(sb, sc->nid); inodes = list_lru_count_node(&sb->s_inode_lru, sc->nid); dentries = list_lru_count_node(&sb->s_dentry_lru, sc->nid); total_objects = dentries + inodes + fs_objects + 1; /* proportion the scan between the caches */ dentries = mult_frac(sc->nr_to_scan, dentries, total_objects); inodes = mult_frac(sc->nr_to_scan, inodes, total_objects); /* * prune the dcache first as the icache is pinned by it, then * prune the icache, followed by the filesystem specific caches */ freed = prune_dcache_sb(sb, dentries, sc->nid); freed += prune_icache_sb(sb, inodes, sc->nid); if (fs_objects) { fs_objects = mult_frac(sc->nr_to_scan, fs_objects, total_objects); freed += sb->s_op->free_cached_objects(sb, fs_objects, sc->nid); } drop_super(sb); return freed; } static unsigned long super_cache_count(struct shrinker *shrink, struct shrink_control *sc) { struct super_block *sb; long total_objects = 0; sb = container_of(shrink, struct super_block, s_shrink); if (!grab_super_passive(sb)) return 0; if (sb->s_op && sb->s_op->nr_cached_objects) total_objects = sb->s_op->nr_cached_objects(sb, sc->nid); total_objects += list_lru_count_node(&sb->s_dentry_lru, sc->nid); total_objects += list_lru_count_node(&sb->s_inode_lru, sc->nid); total_objects = vfs_pressure_ratio(total_objects); drop_super(sb); return total_objects; } /** * destroy_super - frees a superblock * @s: superblock to free * * Frees a superblock. */ static void destroy_super(struct super_block *s) { int i; list_lru_destroy(&s->s_dentry_lru); list_lru_destroy(&s->s_inode_lru); #ifdef CONFIG_SMP free_percpu(s->s_files); #endif for (i = 0; i < SB_FREEZE_LEVELS; i++) percpu_counter_destroy(&s->s_writers.counter[i]); security_sb_free(s); WARN_ON(!list_empty(&s->s_mounts)); kfree(s->s_subtype); kfree(s->s_options); kfree_rcu(s, rcu); } /** * alloc_super - create new superblock * @type: filesystem type superblock should belong to * @flags: the mount flags * * Allocates and initializes a new &struct super_block. alloc_super() * returns a pointer new superblock or %NULL if allocation had failed. */ static struct super_block *alloc_super(struct file_system_type *type, int flags) { struct super_block *s = kzalloc(sizeof(struct super_block), GFP_USER); static const struct super_operations default_op; int i; if (!s) return NULL; if (security_sb_alloc(s)) goto fail; #ifdef CONFIG_SMP s->s_files = alloc_percpu(struct list_head); if (!s->s_files) goto fail; for_each_possible_cpu(i) INIT_LIST_HEAD(per_cpu_ptr(s->s_files, i)); #else INIT_LIST_HEAD(&s->s_files); #endif for (i = 0; i < SB_FREEZE_LEVELS; i++) { if (percpu_counter_init(&s->s_writers.counter[i], 0) < 0) goto fail; lockdep_init_map(&s->s_writers.lock_map[i], sb_writers_name[i], &type->s_writers_key[i], 0); } init_waitqueue_head(&s->s_writers.wait); init_waitqueue_head(&s->s_writers.wait_unfrozen); s->s_flags = flags; s->s_bdi = &default_backing_dev_info; INIT_HLIST_NODE(&s->s_instances); INIT_HLIST_BL_HEAD(&s->s_anon); INIT_LIST_HEAD(&s->s_inodes); if (list_lru_init(&s->s_dentry_lru)) goto fail; if (list_lru_init(&s->s_inode_lru)) goto fail; INIT_LIST_HEAD(&s->s_mounts); init_rwsem(&s->s_umount); lockdep_set_class(&s->s_umount, &type->s_umount_key); /* * sget() can have s_umount recursion. * * When it cannot find a suitable sb, it allocates a new * one (this one), and tries again to find a suitable old * one. * * In case that succeeds, it will acquire the s_umount * lock of the old one. Since these are clearly distrinct * locks, and this object isn't exposed yet, there's no * risk of deadlocks. * * Annotate this by putting this lock in a different * subclass. */ down_write_nested(&s->s_umount, SINGLE_DEPTH_NESTING); s->s_count = 1; atomic_set(&s->s_active, 1); mutex_init(&s->s_vfs_rename_mutex); lockdep_set_class(&s->s_vfs_rename_mutex, &type->s_vfs_rename_key); mutex_init(&s->s_dquot.dqio_mutex); mutex_init(&s->s_dquot.dqonoff_mutex); init_rwsem(&s->s_dquot.dqptr_sem); s->s_maxbytes = MAX_NON_LFS; s->s_op = &default_op; s->s_time_gran = 1000000000; s->cleancache_poolid = -1; s->s_shrink.seeks = DEFAULT_SEEKS; s->s_shrink.scan_objects = super_cache_scan; s->s_shrink.count_objects = super_cache_count; s->s_shrink.batch = 1024; s->s_shrink.flags = SHRINKER_NUMA_AWARE; return s; fail: destroy_super(s); return NULL; } /* Superblock refcounting */ /* * Drop a superblock's refcount. The caller must hold sb_lock. */ static void __put_super(struct super_block *sb) { if (!--sb->s_count) { list_del_init(&sb->s_list); destroy_super(sb); } } /** * put_super - drop a temporary reference to superblock * @sb: superblock in question * * Drops a temporary reference, frees superblock if there's no * references left. */ static void put_super(struct super_block *sb) { spin_lock(&sb_lock); __put_super(sb); spin_unlock(&sb_lock); } /** * deactivate_locked_super - drop an active reference to superblock * @s: superblock to deactivate * * Drops an active reference to superblock, converting it into a temprory * one if there is no other active references left. In that case we * tell fs driver to shut it down and drop the temporary reference we * had just acquired. * * Caller holds exclusive lock on superblock; that lock is released. */ void deactivate_locked_super(struct super_block *s) { struct file_system_type *fs = s->s_type; if (atomic_dec_and_test(&s->s_active)) { cleancache_invalidate_fs(s); fs->kill_sb(s); /* caches are now gone, we can safely kill the shrinker now */ unregister_shrinker(&s->s_shrink); put_filesystem(fs); put_super(s); } else { up_write(&s->s_umount); } } EXPORT_SYMBOL(deactivate_locked_super); /** * deactivate_super - drop an active reference to superblock * @s: superblock to deactivate * * Variant of deactivate_locked_super(), except that superblock is *not* * locked by caller. If we are going to drop the final active reference, * lock will be acquired prior to that. */ void deactivate_super(struct super_block *s) { if (!atomic_add_unless(&s->s_active, -1, 1)) { down_write(&s->s_umount); deactivate_locked_super(s); } } EXPORT_SYMBOL(deactivate_super); /** * grab_super - acquire an active reference * @s: reference we are trying to make active * * Tries to acquire an active reference. grab_super() is used when we * had just found a superblock in super_blocks or fs_type->fs_supers * and want to turn it into a full-blown active reference. grab_super() * is called with sb_lock held and drops it. Returns 1 in case of * success, 0 if we had failed (superblock contents was already dead or * dying when grab_super() had been called). Note that this is only * called for superblocks not in rundown mode (== ones still on ->fs_supers * of their type), so increment of ->s_count is OK here. */ static int grab_super(struct super_block *s) __releases(sb_lock) { s->s_count++; spin_unlock(&sb_lock); down_write(&s->s_umount); if ((s->s_flags & MS_BORN) && atomic_inc_not_zero(&s->s_active)) { put_super(s); return 1; } up_write(&s->s_umount); put_super(s); return 0; } /* * grab_super_passive - acquire a passive reference * @sb: reference we are trying to grab * * Tries to acquire a passive reference. This is used in places where we * cannot take an active reference but we need to ensure that the * superblock does not go away while we are working on it. It returns * false if a reference was not gained, and returns true with the s_umount * lock held in read mode if a reference is gained. On successful return, * the caller must drop the s_umount lock and the passive reference when * done. */ bool grab_super_passive(struct super_block *sb) { spin_lock(&sb_lock); if (hlist_unhashed(&sb->s_instances)) { spin_unlock(&sb_lock); return false; } sb->s_count++; spin_unlock(&sb_lock); if (down_read_trylock(&sb->s_umount)) { if (sb->s_root && (sb->s_flags & MS_BORN)) return true; up_read(&sb->s_umount); } put_super(sb); return false; } /** * generic_shutdown_super - common helper for ->kill_sb() * @sb: superblock to kill * * generic_shutdown_super() does all fs-independent work on superblock * shutdown. Typical ->kill_sb() should pick all fs-specific objects * that need destruction out of superblock, call generic_shutdown_super() * and release aforementioned objects. Note: dentries and inodes _are_ * taken care of and do not need specific handling. * * Upon calling this function, the filesystem may no longer alter or * rearrange the set of dentries belonging to this super_block, nor may it * change the attachments of dentries to inodes. */ void generic_shutdown_super(struct super_block *sb) { const struct super_operations *sop = sb->s_op; if (sb->s_root) { shrink_dcache_for_umount(sb); sync_filesystem(sb); sb->s_flags &= ~MS_ACTIVE; fsnotify_unmount_inodes(&sb->s_inodes); evict_inodes(sb); if (sb->s_dio_done_wq) { destroy_workqueue(sb->s_dio_done_wq); sb->s_dio_done_wq = NULL; } if (sop->put_super) sop->put_super(sb); if (!list_empty(&sb->s_inodes)) { printk("VFS: Busy inodes after unmount of %s. " "Self-destruct in 5 seconds. Have a nice day...\n", sb->s_id); } } spin_lock(&sb_lock); /* should be initialized for __put_super_and_need_restart() */ hlist_del_init(&sb->s_instances); spin_unlock(&sb_lock); up_write(&sb->s_umount); } EXPORT_SYMBOL(generic_shutdown_super); /** * sget - find or create a superblock * @type: filesystem type superblock should belong to * @test: comparison callback * @set: setup callback * @flags: mount flags * @data: argument to each of them */ struct super_block *sget(struct file_system_type *type, int (*test)(struct super_block *,void *), int (*set)(struct super_block *,void *), int flags, void *data) { struct super_block *s = NULL; struct super_block *old; int err; retry: spin_lock(&sb_lock); if (test) { hlist_for_each_entry(old, &type->fs_supers, s_instances) { if (!test(old, data)) continue; if (!grab_super(old)) goto retry; if (s) { up_write(&s->s_umount); destroy_super(s); s = NULL; } return old; } } if (!s) { spin_unlock(&sb_lock); s = alloc_super(type, flags); if (!s) return ERR_PTR(-ENOMEM); goto retry; } err = set(s, data); if (err) { spin_unlock(&sb_lock); up_write(&s->s_umount); destroy_super(s); return ERR_PTR(err); } s->s_type = type; strlcpy(s->s_id, type->name, sizeof(s->s_id)); list_add_tail(&s->s_list, &super_blocks); hlist_add_head(&s->s_instances, &type->fs_supers); spin_unlock(&sb_lock); get_filesystem(type); register_shrinker(&s->s_shrink); return s; } EXPORT_SYMBOL(sget); void drop_super(struct super_block *sb) { up_read(&sb->s_umount); put_super(sb); } EXPORT_SYMBOL(drop_super); /** * iterate_supers - call function for all active superblocks * @f: function to call * @arg: argument to pass to it * * Scans the superblock list and calls given function, passing it * locked superblock and given argument. */ void iterate_supers(void (*f)(struct super_block *, void *), void *arg) { struct super_block *sb, *p = NULL; spin_lock(&sb_lock); list_for_each_entry(sb, &super_blocks, s_list) { if (hlist_unhashed(&sb->s_instances)) continue; sb->s_count++; spin_unlock(&sb_lock); down_read(&sb->s_umount); if (sb->s_root && (sb->s_flags & MS_BORN)) f(sb, arg); up_read(&sb->s_umount); spin_lock(&sb_lock); if (p) __put_super(p); p = sb; } if (p) __put_super(p); spin_unlock(&sb_lock); } /** * iterate_supers_type - call function for superblocks of given type * @type: fs type * @f: function to call * @arg: argument to pass to it * * Scans the superblock list and calls given function, passing it * locked superblock and given argument. */ void iterate_supers_type(struct file_system_type *type, void (*f)(struct super_block *, void *), void *arg) { struct super_block *sb, *p = NULL; spin_lock(&sb_lock); hlist_for_each_entry(sb, &type->fs_supers, s_instances) { sb->s_count++; spin_unlock(&sb_lock); down_read(&sb->s_umount); if (sb->s_root && (sb->s_flags & MS_BORN)) f(sb, arg); up_read(&sb->s_umount); spin_lock(&sb_lock); if (p) __put_super(p); p = sb; } if (p) __put_super(p); spin_unlock(&sb_lock); } EXPORT_SYMBOL(iterate_supers_type); /** * get_super - get the superblock of a device * @bdev: device to get the superblock for * * Scans the superblock list and finds the superblock of the file system * mounted on the device given. %NULL is returned if no match is found. */ struct super_block *get_super(struct block_device *bdev) { struct super_block *sb; if (!bdev) return NULL; spin_lock(&sb_lock); rescan: list_for_each_entry(sb, &super_blocks, s_list) { if (hlist_unhashed(&sb->s_instances)) continue; if (sb->s_bdev == bdev) { sb->s_count++; spin_unlock(&sb_lock); down_read(&sb->s_umount); /* still alive? */ if (sb->s_root && (sb->s_flags & MS_BORN)) return sb; up_read(&sb->s_umount); /* nope, got unmounted */ spin_lock(&sb_lock); __put_super(sb); goto rescan; } } spin_unlock(&sb_lock); return NULL; } EXPORT_SYMBOL(get_super); /** * get_super_thawed - get thawed superblock of a device * @bdev: device to get the superblock for * * Scans the superblock list and finds the superblock of the file system * mounted on the device. The superblock is returned once it is thawed * (or immediately if it was not frozen). %NULL is returned if no match * is found. */ struct super_block *get_super_thawed(struct block_device *bdev) { while (1) { struct super_block *s = get_super(bdev); if (!s || s->s_writers.frozen == SB_UNFROZEN) return s; up_read(&s->s_umount); wait_event(s->s_writers.wait_unfrozen, s->s_writers.frozen == SB_UNFROZEN); put_super(s); } } EXPORT_SYMBOL(get_super_thawed); /** * get_active_super - get an active reference to the superblock of a device * @bdev: device to get the superblock for * * Scans the superblock list and finds the superblock of the file system * mounted on the device given. Returns the superblock with an active * reference or %NULL if none was found. */ struct super_block *get_active_super(struct block_device *bdev) { struct super_block *sb; if (!bdev) return NULL; restart: spin_lock(&sb_lock); list_for_each_entry(sb, &super_blocks, s_list) { if (hlist_unhashed(&sb->s_instances)) continue; if (sb->s_bdev == bdev) { if (!grab_super(sb)) goto restart; up_write(&sb->s_umount); return sb; } } spin_unlock(&sb_lock); return NULL; } struct super_block *user_get_super(dev_t dev) { struct super_block *sb; spin_lock(&sb_lock); rescan: list_for_each_entry(sb, &super_blocks, s_list) { if (hlist_unhashed(&sb->s_instances)) continue; if (sb->s_dev == dev) { sb->s_count++; spin_unlock(&sb_lock); down_read(&sb->s_umount); /* still alive? */ if (sb->s_root && (sb->s_flags & MS_BORN)) return sb; up_read(&sb->s_umount); /* nope, got unmounted */ spin_lock(&sb_lock); __put_super(sb); goto rescan; } } spin_unlock(&sb_lock); return NULL; } /** * do_remount_sb - asks filesystem to change mount options. * @sb: superblock in question * @flags: numeric part of options * @data: the rest of options * @force: whether or not to force the change * * Alters the mount options of a mounted file system. */ int do_remount_sb(struct super_block *sb, int flags, void *data, int force) { int retval; int remount_ro; if (sb->s_writers.frozen != SB_UNFROZEN) return -EBUSY; #ifdef CONFIG_BLOCK if (!(flags & MS_RDONLY) && bdev_read_only(sb->s_bdev)) return -EACCES; #endif if (flags & MS_RDONLY) acct_auto_close(sb); shrink_dcache_sb(sb); sync_filesystem(sb); remount_ro = (flags & MS_RDONLY) && !(sb->s_flags & MS_RDONLY); /* If we are remounting RDONLY and current sb is read/write, make sure there are no rw files opened */ if (remount_ro) { if (force) { mark_files_ro(sb); } else { retval = sb_prepare_remount_readonly(sb); if (retval) return retval; } } if (sb->s_op->remount_fs) { retval = sb->s_op->remount_fs(sb, &flags, data); if (retval) { if (!force) goto cancel_readonly; /* If forced remount, go ahead despite any errors */ WARN(1, "forced remount of a %s fs returned %i\n", sb->s_type->name, retval); } } sb->s_flags = (sb->s_flags & ~MS_RMT_MASK) | (flags & MS_RMT_MASK); /* Needs to be ordered wrt mnt_is_readonly() */ smp_wmb(); sb->s_readonly_remount = 0; /* * Some filesystems modify their metadata via some other path than the * bdev buffer cache (eg. use a private mapping, or directories in * pagecache, etc). Also file data modifications go via their own * mappings. So If we try to mount readonly then copy the filesystem * from bdev, we could get stale data, so invalidate it to give a best * effort at coherency. */ if (remount_ro && sb->s_bdev) invalidate_bdev(sb->s_bdev); return 0; cancel_readonly: sb->s_readonly_remount = 0; return retval; } static void do_emergency_remount(struct work_struct *work) { struct super_block *sb, *p = NULL; spin_lock(&sb_lock); list_for_each_entry(sb, &super_blocks, s_list) { if (hlist_unhashed(&sb->s_instances)) continue; sb->s_count++; spin_unlock(&sb_lock); down_write(&sb->s_umount); if (sb->s_root && sb->s_bdev && (sb->s_flags & MS_BORN) && !(sb->s_flags & MS_RDONLY)) { /* * What lock protects sb->s_flags?? */ do_remount_sb(sb, MS_RDONLY, NULL, 1); } up_write(&sb->s_umount); spin_lock(&sb_lock); if (p) __put_super(p); p = sb; } if (p) __put_super(p); spin_unlock(&sb_lock); kfree(work); printk("Emergency Remount complete\n"); } void emergency_remount(void) { struct work_struct *work; work = kmalloc(sizeof(*work), GFP_ATOMIC); if (work) { INIT_WORK(work, do_emergency_remount); schedule_work(work); } } /* * Unnamed block devices are dummy devices used by virtual * filesystems which don't use real block-devices. -- jrs */ static DEFINE_IDA(unnamed_dev_ida); static DEFINE_SPINLOCK(unnamed_dev_lock);/* protects the above */ static int unnamed_dev_start = 0; /* don't bother trying below it */ int get_anon_bdev(dev_t *p) { int dev; int error; retry: if (ida_pre_get(&unnamed_dev_ida, GFP_ATOMIC) == 0) return -ENOMEM; spin_lock(&unnamed_dev_lock); error = ida_get_new_above(&unnamed_dev_ida, unnamed_dev_start, &dev); if (!error) unnamed_dev_start = dev + 1; spin_unlock(&unnamed_dev_lock); if (error == -EAGAIN) /* We raced and lost with another CPU. */ goto retry; else if (error) return -EAGAIN; if (dev == (1 << MINORBITS)) { spin_lock(&unnamed_dev_lock); ida_remove(&unnamed_dev_ida, dev); if (unnamed_dev_start > dev) unnamed_dev_start = dev; spin_unlock(&unnamed_dev_lock); return -EMFILE; } *p = MKDEV(0, dev & MINORMASK); return 0; } EXPORT_SYMBOL(get_anon_bdev); void free_anon_bdev(dev_t dev) { int slot = MINOR(dev); spin_lock(&unnamed_dev_lock); ida_remove(&unnamed_dev_ida, slot); if (slot < unnamed_dev_start) unnamed_dev_start = slot; spin_unlock(&unnamed_dev_lock); } EXPORT_SYMBOL(free_anon_bdev); int set_anon_super(struct super_block *s, void *data) { int error = get_anon_bdev(&s->s_dev); if (!error) s->s_bdi = &noop_backing_dev_info; return error; } EXPORT_SYMBOL(set_anon_super); void kill_anon_super(struct super_block *sb) { dev_t dev = sb->s_dev; generic_shutdown_super(sb); free_anon_bdev(dev); } EXPORT_SYMBOL(kill_anon_super); void kill_litter_super(struct super_block *sb) { if (sb->s_root) d_genocide(sb->s_root); kill_anon_super(sb); } EXPORT_SYMBOL(kill_litter_super); static int ns_test_super(struct super_block *sb, void *data) { return sb->s_fs_info == data; } static int ns_set_super(struct super_block *sb, void *data) { sb->s_fs_info = data; return set_anon_super(sb, NULL); } struct dentry *mount_ns(struct file_system_type *fs_type, int flags, void *data, int (*fill_super)(struct super_block *, void *, int)) { struct super_block *sb; sb = sget(fs_type, ns_test_super, ns_set_super, flags, data); if (IS_ERR(sb)) return ERR_CAST(sb); if (!sb->s_root) { int err; err = fill_super(sb, data, flags & MS_SILENT ? 1 : 0); if (err) { deactivate_locked_super(sb); return ERR_PTR(err); } sb->s_flags |= MS_ACTIVE; } return dget(sb->s_root); } EXPORT_SYMBOL(mount_ns); #ifdef CONFIG_BLOCK static int set_bdev_super(struct super_block *s, void *data) { s->s_bdev = data; s->s_dev = s->s_bdev->bd_dev; /* * We set the bdi here to the queue backing, file systems can * overwrite this in ->fill_super() */ s->s_bdi = &bdev_get_queue(s->s_bdev)->backing_dev_info; return 0; } static int test_bdev_super(struct super_block *s, void *data) { return (void *)s->s_bdev == data; } struct dentry *mount_bdev(struct file_system_type *fs_type, int flags, const char *dev_name, void *data, int (*fill_super)(struct super_block *, void *, int)) { struct block_device *bdev; struct super_block *s; fmode_t mode = FMODE_READ | FMODE_EXCL; int error = 0; if (!(flags & MS_RDONLY)) mode |= FMODE_WRITE; bdev = blkdev_get_by_path(dev_name, mode, fs_type); if (IS_ERR(bdev)) return ERR_CAST(bdev); /* * once the super is inserted into the list by sget, s_umount * will protect the lockfs code from trying to start a snapshot * while we are mounting */ mutex_lock(&bdev->bd_fsfreeze_mutex); if (bdev->bd_fsfreeze_count > 0) { mutex_unlock(&bdev->bd_fsfreeze_mutex); error = -EBUSY; goto error_bdev; } s = sget(fs_type, test_bdev_super, set_bdev_super, flags | MS_NOSEC, bdev); mutex_unlock(&bdev->bd_fsfreeze_mutex); if (IS_ERR(s)) goto error_s; if (s->s_root) { if ((flags ^ s->s_flags) & MS_RDONLY) { deactivate_locked_super(s); error = -EBUSY; goto error_bdev; } /* * s_umount nests inside bd_mutex during * __invalidate_device(). blkdev_put() acquires * bd_mutex and can't be called under s_umount. Drop * s_umount temporarily. This is safe as we're * holding an active reference. */ up_write(&s->s_umount); blkdev_put(bdev, mode); down_write(&s->s_umount); } else { char b[BDEVNAME_SIZE]; s->s_mode = mode; strlcpy(s->s_id, bdevname(bdev, b), sizeof(s->s_id)); sb_set_blocksize(s, block_size(bdev)); error = fill_super(s, data, flags & MS_SILENT ? 1 : 0); if (error) { deactivate_locked_super(s); goto error; } s->s_flags |= MS_ACTIVE; bdev->bd_super = s; } return dget(s->s_root); error_s: error = PTR_ERR(s); error_bdev: blkdev_put(bdev, mode); error: return ERR_PTR(error); } EXPORT_SYMBOL(mount_bdev); void kill_block_super(struct super_block *sb) { struct block_device *bdev = sb->s_bdev; fmode_t mode = sb->s_mode; bdev->bd_super = NULL; generic_shutdown_super(sb); sync_blockdev(bdev); WARN_ON_ONCE(!(mode & FMODE_EXCL)); blkdev_put(bdev, mode | FMODE_EXCL); } EXPORT_SYMBOL(kill_block_super); #endif struct dentry *mount_nodev(struct file_system_type *fs_type, int flags, void *data, int (*fill_super)(struct super_block *, void *, int)) { int error; struct super_block *s = sget(fs_type, NULL, set_anon_super, flags, NULL); if (IS_ERR(s)) return ERR_CAST(s); error = fill_super(s, data, flags & MS_SILENT ? 1 : 0); if (error) { deactivate_locked_super(s); return ERR_PTR(error); } s->s_flags |= MS_ACTIVE; return dget(s->s_root); } EXPORT_SYMBOL(mount_nodev); static int compare_single(struct super_block *s, void *p) { return 1; } struct dentry *mount_single(struct file_system_type *fs_type, int flags, void *data, int (*fill_super)(struct super_block *, void *, int)) { struct super_block *s; int error; s = sget(fs_type, compare_single, set_anon_super, flags, NULL); if (IS_ERR(s)) return ERR_CAST(s); if (!s->s_root) { error = fill_super(s, data, flags & MS_SILENT ? 1 : 0); if (error) { deactivate_locked_super(s); return ERR_PTR(error); } s->s_flags |= MS_ACTIVE; } else { do_remount_sb(s, flags, data, 0); } return dget(s->s_root); } EXPORT_SYMBOL(mount_single); struct dentry * mount_fs(struct file_system_type *type, int flags, const char *name, void *data) { struct dentry *root; struct super_block *sb; char *secdata = NULL; int error = -ENOMEM; if (data && !(type->fs_flags & FS_BINARY_MOUNTDATA)) { secdata = alloc_secdata(); if (!secdata) goto out; error = security_sb_copy_data(data, secdata); if (error) goto out_free_secdata; } root = type->mount(type, flags, name, data); if (IS_ERR(root)) { error = PTR_ERR(root); goto out_free_secdata; } sb = root->d_sb; BUG_ON(!sb); WARN_ON(!sb->s_bdi); WARN_ON(sb->s_bdi == &default_backing_dev_info); sb->s_flags |= MS_BORN; error = security_sb_kern_mount(sb, flags, secdata); if (error) goto out_sb; /* * filesystems should never set s_maxbytes larger than MAX_LFS_FILESIZE * but s_maxbytes was an unsigned long long for many releases. Throw * this warning for a little while to try and catch filesystems that * violate this rule. */ WARN((sb->s_maxbytes < 0), "%s set sb->s_maxbytes to " "negative value (%lld)\n", type->name, sb->s_maxbytes); up_write(&sb->s_umount); free_secdata(secdata); return root; out_sb: dput(root); deactivate_locked_super(sb); out_free_secdata: free_secdata(secdata); out: return ERR_PTR(error); } /* * This is an internal function, please use sb_end_{write,pagefault,intwrite} * instead. */ void __sb_end_write(struct super_block *sb, int level) { percpu_counter_dec(&sb->s_writers.counter[level-1]); /* * Make sure s_writers are updated before we wake up waiters in * freeze_super(). */ smp_mb(); if (waitqueue_active(&sb->s_writers.wait)) wake_up(&sb->s_writers.wait); rwsem_release(&sb->s_writers.lock_map[level-1], 1, _RET_IP_); } EXPORT_SYMBOL(__sb_end_write); #ifdef CONFIG_LOCKDEP /* * We want lockdep to tell us about possible deadlocks with freezing but * it's it bit tricky to properly instrument it. Getting a freeze protection * works as getting a read lock but there are subtle problems. XFS for example * gets freeze protection on internal level twice in some cases, which is OK * only because we already hold a freeze protection also on higher level. Due * to these cases we have to tell lockdep we are doing trylock when we * already hold a freeze protection for a higher freeze level. */ static void acquire_freeze_lock(struct super_block *sb, int level, bool trylock, unsigned long ip) { int i; if (!trylock) { for (i = 0; i < level - 1; i++) if (lock_is_held(&sb->s_writers.lock_map[i])) { trylock = true; break; } } rwsem_acquire_read(&sb->s_writers.lock_map[level-1], 0, trylock, ip); } #endif /* * This is an internal function, please use sb_start_{write,pagefault,intwrite} * instead. */ int __sb_start_write(struct super_block *sb, int level, bool wait) { retry: if (unlikely(sb->s_writers.frozen >= level)) { if (!wait) return 0; wait_event(sb->s_writers.wait_unfrozen, sb->s_writers.frozen < level); } #ifdef CONFIG_LOCKDEP acquire_freeze_lock(sb, level, !wait, _RET_IP_); #endif percpu_counter_inc(&sb->s_writers.counter[level-1]); /* * Make sure counter is updated before we check for frozen. * freeze_super() first sets frozen and then checks the counter. */ smp_mb(); if (unlikely(sb->s_writers.frozen >= level)) { __sb_end_write(sb, level); goto retry; } return 1; } EXPORT_SYMBOL(__sb_start_write); /** * sb_wait_write - wait until all writers to given file system finish * @sb: the super for which we wait * @level: type of writers we wait for (normal vs page fault) * * This function waits until there are no writers of given type to given file * system. Caller of this function should make sure there can be no new writers * of type @level before calling this function. Otherwise this function can * livelock. */ static void sb_wait_write(struct super_block *sb, int level) { s64 writers; /* * We just cycle-through lockdep here so that it does not complain * about returning with lock to userspace */ rwsem_acquire(&sb->s_writers.lock_map[level-1], 0, 0, _THIS_IP_); rwsem_release(&sb->s_writers.lock_map[level-1], 1, _THIS_IP_); do { DEFINE_WAIT(wait); /* * We use a barrier in prepare_to_wait() to separate setting * of frozen and checking of the counter */ prepare_to_wait(&sb->s_writers.wait, &wait, TASK_UNINTERRUPTIBLE); writers = percpu_counter_sum(&sb->s_writers.counter[level-1]); if (writers) schedule(); finish_wait(&sb->s_writers.wait, &wait); } while (writers); } /** * freeze_super - lock the filesystem and force it into a consistent state * @sb: the super to lock * * Syncs the super to make sure the filesystem is consistent and calls the fs's * freeze_fs. Subsequent calls to this without first thawing the fs will return * -EBUSY. * * During this function, sb->s_writers.frozen goes through these values: * * SB_UNFROZEN: File system is normal, all writes progress as usual. * * SB_FREEZE_WRITE: The file system is in the process of being frozen. New * writes should be blocked, though page faults are still allowed. We wait for * all writes to complete and then proceed to the next stage. * * SB_FREEZE_PAGEFAULT: Freezing continues. Now also page faults are blocked * but internal fs threads can still modify the filesystem (although they * should not dirty new pages or inodes), writeback can run etc. After waiting * for all running page faults we sync the filesystem which will clean all * dirty pages and inodes (no new dirty pages or inodes can be created when * sync is running). * * SB_FREEZE_FS: The file system is frozen. Now all internal sources of fs * modification are blocked (e.g. XFS preallocation truncation on inode * reclaim). This is usually implemented by blocking new transactions for * filesystems that have them and need this additional guard. After all * internal writers are finished we call ->freeze_fs() to finish filesystem * freezing. Then we transition to SB_FREEZE_COMPLETE state. This state is * mostly auxiliary for filesystems to verify they do not modify frozen fs. * * sb->s_writers.frozen is protected by sb->s_umount. */ int freeze_super(struct super_block *sb) { int ret; atomic_inc(&sb->s_active); down_write(&sb->s_umount); if (sb->s_writers.frozen != SB_UNFROZEN) { deactivate_locked_super(sb); return -EBUSY; } if (!(sb->s_flags & MS_BORN)) { up_write(&sb->s_umount); return 0; /* sic - it's "nothing to do" */ } if (sb->s_flags & MS_RDONLY) { /* Nothing to do really... */ sb->s_writers.frozen = SB_FREEZE_COMPLETE; up_write(&sb->s_umount); return 0; } /* From now on, no new normal writers can start */ sb->s_writers.frozen = SB_FREEZE_WRITE; smp_wmb(); /* Release s_umount to preserve sb_start_write -> s_umount ordering */ up_write(&sb->s_umount); sb_wait_write(sb, SB_FREEZE_WRITE); /* Now we go and block page faults... */ down_write(&sb->s_umount); sb->s_writers.frozen = SB_FREEZE_PAGEFAULT; smp_wmb(); sb_wait_write(sb, SB_FREEZE_PAGEFAULT); /* All writers are done so after syncing there won't be dirty data */ sync_filesystem(sb); /* Now wait for internal filesystem counter */ sb->s_writers.frozen = SB_FREEZE_FS; smp_wmb(); sb_wait_write(sb, SB_FREEZE_FS); if (sb->s_op->freeze_fs) { ret = sb->s_op->freeze_fs(sb); if (ret) { printk(KERN_ERR "VFS:Filesystem freeze failed\n"); sb->s_writers.frozen = SB_UNFROZEN; smp_wmb(); wake_up(&sb->s_writers.wait_unfrozen); deactivate_locked_super(sb); return ret; } } /* * This is just for debugging purposes so that fs can warn if it * sees write activity when frozen is set to SB_FREEZE_COMPLETE. */ sb->s_writers.frozen = SB_FREEZE_COMPLETE; up_write(&sb->s_umount); return 0; } EXPORT_SYMBOL(freeze_super); /** * thaw_super -- unlock filesystem * @sb: the super to thaw * * Unlocks the filesystem and marks it writeable again after freeze_super(). */ int thaw_super(struct super_block *sb) { int error; down_write(&sb->s_umount); if (sb->s_writers.frozen == SB_UNFROZEN) { up_write(&sb->s_umount); return -EINVAL; } if (sb->s_flags & MS_RDONLY) goto out; if (sb->s_op->unfreeze_fs) { error = sb->s_op->unfreeze_fs(sb); if (error) { printk(KERN_ERR "VFS:Filesystem thaw failed\n"); up_write(&sb->s_umount); return error; } } out: sb->s_writers.frozen = SB_UNFROZEN; smp_wmb(); wake_up(&sb->s_writers.wait_unfrozen); deactivate_locked_super(sb); return 0; } EXPORT_SYMBOL(thaw_super);
./CrossVul/dataset_final_sorted/CWE-17/c/bad_2306_3
crossvul-cpp_data_bad_1510_0
/* * sysctl_net_llc.c: sysctl interface to LLC net subsystem. * * Arnaldo Carvalho de Melo <acme@conectiva.com.br> */ #include <linux/mm.h> #include <linux/init.h> #include <linux/sysctl.h> #include <net/net_namespace.h> #include <net/llc.h> #ifndef CONFIG_SYSCTL #error This file should not be compiled without CONFIG_SYSCTL defined #endif static struct ctl_table llc2_timeout_table[] = { { .procname = "ack", .data = &sysctl_llc2_ack_timeout, .maxlen = sizeof(long), .mode = 0644, .proc_handler = proc_dointvec_jiffies, }, { .procname = "busy", .data = &sysctl_llc2_busy_timeout, .maxlen = sizeof(long), .mode = 0644, .proc_handler = proc_dointvec_jiffies, }, { .procname = "p", .data = &sysctl_llc2_p_timeout, .maxlen = sizeof(long), .mode = 0644, .proc_handler = proc_dointvec_jiffies, }, { .procname = "rej", .data = &sysctl_llc2_rej_timeout, .maxlen = sizeof(long), .mode = 0644, .proc_handler = proc_dointvec_jiffies, }, { }, }; static struct ctl_table llc_station_table[] = { { }, }; static struct ctl_table_header *llc2_timeout_header; static struct ctl_table_header *llc_station_header; int __init llc_sysctl_init(void) { llc2_timeout_header = register_net_sysctl(&init_net, "net/llc/llc2/timeout", llc2_timeout_table); llc_station_header = register_net_sysctl(&init_net, "net/llc/station", llc_station_table); if (!llc2_timeout_header || !llc_station_header) { llc_sysctl_exit(); return -ENOMEM; } return 0; } void llc_sysctl_exit(void) { if (llc2_timeout_header) { unregister_net_sysctl_table(llc2_timeout_header); llc2_timeout_header = NULL; } if (llc_station_header) { unregister_net_sysctl_table(llc_station_header); llc_station_header = NULL; } }
./CrossVul/dataset_final_sorted/CWE-17/c/bad_1510_0
crossvul-cpp_data_good_1498_0
/* * linux/fs/pipe.c * * Copyright (C) 1991, 1992, 1999 Linus Torvalds */ #include <linux/mm.h> #include <linux/file.h> #include <linux/poll.h> #include <linux/slab.h> #include <linux/module.h> #include <linux/init.h> #include <linux/fs.h> #include <linux/log2.h> #include <linux/mount.h> #include <linux/magic.h> #include <linux/pipe_fs_i.h> #include <linux/uio.h> #include <linux/highmem.h> #include <linux/pagemap.h> #include <linux/audit.h> #include <linux/syscalls.h> #include <linux/fcntl.h> #include <linux/aio.h> #include <asm/uaccess.h> #include <asm/ioctls.h> #include "internal.h" /* * The max size that a non-root user is allowed to grow the pipe. Can * be set by root in /proc/sys/fs/pipe-max-size */ unsigned int pipe_max_size = 1048576; /* * Minimum pipe size, as required by POSIX */ unsigned int pipe_min_size = PAGE_SIZE; /* * We use a start+len construction, which provides full use of the * allocated memory. * -- Florian Coosmann (FGC) * * Reads with count = 0 should always return 0. * -- Julian Bradfield 1999-06-07. * * FIFOs and Pipes now generate SIGIO for both readers and writers. * -- Jeremy Elson <jelson@circlemud.org> 2001-08-16 * * pipe_read & write cleanup * -- Manfred Spraul <manfred@colorfullife.com> 2002-05-09 */ static void pipe_lock_nested(struct pipe_inode_info *pipe, int subclass) { if (pipe->files) mutex_lock_nested(&pipe->mutex, subclass); } void pipe_lock(struct pipe_inode_info *pipe) { /* * pipe_lock() nests non-pipe inode locks (for writing to a file) */ pipe_lock_nested(pipe, I_MUTEX_PARENT); } EXPORT_SYMBOL(pipe_lock); void pipe_unlock(struct pipe_inode_info *pipe) { if (pipe->files) mutex_unlock(&pipe->mutex); } EXPORT_SYMBOL(pipe_unlock); static inline void __pipe_lock(struct pipe_inode_info *pipe) { mutex_lock_nested(&pipe->mutex, I_MUTEX_PARENT); } static inline void __pipe_unlock(struct pipe_inode_info *pipe) { mutex_unlock(&pipe->mutex); } void pipe_double_lock(struct pipe_inode_info *pipe1, struct pipe_inode_info *pipe2) { BUG_ON(pipe1 == pipe2); if (pipe1 < pipe2) { pipe_lock_nested(pipe1, I_MUTEX_PARENT); pipe_lock_nested(pipe2, I_MUTEX_CHILD); } else { pipe_lock_nested(pipe2, I_MUTEX_PARENT); pipe_lock_nested(pipe1, I_MUTEX_CHILD); } } /* Drop the inode semaphore and wait for a pipe event, atomically */ void pipe_wait(struct pipe_inode_info *pipe) { DEFINE_WAIT(wait); /* * Pipes are system-local resources, so sleeping on them * is considered a noninteractive wait: */ prepare_to_wait(&pipe->wait, &wait, TASK_INTERRUPTIBLE); pipe_unlock(pipe); schedule(); finish_wait(&pipe->wait, &wait); pipe_lock(pipe); } static int pipe_iov_copy_from_user(void *to, struct iovec *iov, unsigned long len, int atomic) { unsigned long copy; while (len > 0) { while (!iov->iov_len) iov++; copy = min_t(unsigned long, len, iov->iov_len); if (atomic) { if (__copy_from_user_inatomic(to, iov->iov_base, copy)) return -EFAULT; } else { if (copy_from_user(to, iov->iov_base, copy)) return -EFAULT; } to += copy; len -= copy; iov->iov_base += copy; iov->iov_len -= copy; } return 0; } /* * Pre-fault in the user memory, so we can use atomic copies. */ static void iov_fault_in_pages_read(struct iovec *iov, unsigned long len) { while (!iov->iov_len) iov++; while (len > 0) { unsigned long this_len; this_len = min_t(unsigned long, len, iov->iov_len); fault_in_pages_readable(iov->iov_base, this_len); len -= this_len; iov++; } } static void anon_pipe_buf_release(struct pipe_inode_info *pipe, struct pipe_buffer *buf) { struct page *page = buf->page; /* * If nobody else uses this page, and we don't already have a * temporary page, let's keep track of it as a one-deep * allocation cache. (Otherwise just release our reference to it) */ if (page_count(page) == 1 && !pipe->tmp_page) pipe->tmp_page = page; else page_cache_release(page); } /** * generic_pipe_buf_steal - attempt to take ownership of a &pipe_buffer * @pipe: the pipe that the buffer belongs to * @buf: the buffer to attempt to steal * * Description: * This function attempts to steal the &struct page attached to * @buf. If successful, this function returns 0 and returns with * the page locked. The caller may then reuse the page for whatever * he wishes; the typical use is insertion into a different file * page cache. */ int generic_pipe_buf_steal(struct pipe_inode_info *pipe, struct pipe_buffer *buf) { struct page *page = buf->page; /* * A reference of one is golden, that means that the owner of this * page is the only one holding a reference to it. lock the page * and return OK. */ if (page_count(page) == 1) { lock_page(page); return 0; } return 1; } EXPORT_SYMBOL(generic_pipe_buf_steal); /** * generic_pipe_buf_get - get a reference to a &struct pipe_buffer * @pipe: the pipe that the buffer belongs to * @buf: the buffer to get a reference to * * Description: * This function grabs an extra reference to @buf. It's used in * in the tee() system call, when we duplicate the buffers in one * pipe into another. */ void generic_pipe_buf_get(struct pipe_inode_info *pipe, struct pipe_buffer *buf) { page_cache_get(buf->page); } EXPORT_SYMBOL(generic_pipe_buf_get); /** * generic_pipe_buf_confirm - verify contents of the pipe buffer * @info: the pipe that the buffer belongs to * @buf: the buffer to confirm * * Description: * This function does nothing, because the generic pipe code uses * pages that are always good when inserted into the pipe. */ int generic_pipe_buf_confirm(struct pipe_inode_info *info, struct pipe_buffer *buf) { return 0; } EXPORT_SYMBOL(generic_pipe_buf_confirm); /** * generic_pipe_buf_release - put a reference to a &struct pipe_buffer * @pipe: the pipe that the buffer belongs to * @buf: the buffer to put a reference to * * Description: * This function releases a reference to @buf. */ void generic_pipe_buf_release(struct pipe_inode_info *pipe, struct pipe_buffer *buf) { page_cache_release(buf->page); } EXPORT_SYMBOL(generic_pipe_buf_release); static const struct pipe_buf_operations anon_pipe_buf_ops = { .can_merge = 1, .confirm = generic_pipe_buf_confirm, .release = anon_pipe_buf_release, .steal = generic_pipe_buf_steal, .get = generic_pipe_buf_get, }; static const struct pipe_buf_operations packet_pipe_buf_ops = { .can_merge = 0, .confirm = generic_pipe_buf_confirm, .release = anon_pipe_buf_release, .steal = generic_pipe_buf_steal, .get = generic_pipe_buf_get, }; static ssize_t pipe_read(struct kiocb *iocb, const struct iovec *_iov, unsigned long nr_segs, loff_t pos) { struct file *filp = iocb->ki_filp; struct pipe_inode_info *pipe = filp->private_data; int do_wakeup; ssize_t ret; struct iovec *iov = (struct iovec *)_iov; size_t total_len; struct iov_iter iter; total_len = iov_length(iov, nr_segs); /* Null read succeeds. */ if (unlikely(total_len == 0)) return 0; iov_iter_init(&iter, iov, nr_segs, total_len, 0); do_wakeup = 0; ret = 0; __pipe_lock(pipe); for (;;) { int bufs = pipe->nrbufs; if (bufs) { int curbuf = pipe->curbuf; struct pipe_buffer *buf = pipe->bufs + curbuf; const struct pipe_buf_operations *ops = buf->ops; size_t chars = buf->len; size_t written; int error; if (chars > total_len) chars = total_len; error = ops->confirm(pipe, buf); if (error) { if (!ret) ret = error; break; } written = copy_page_to_iter(buf->page, buf->offset, chars, &iter); if (unlikely(written < chars)) { if (!ret) ret = -EFAULT; break; } ret += chars; buf->offset += chars; buf->len -= chars; /* Was it a packet buffer? Clean up and exit */ if (buf->flags & PIPE_BUF_FLAG_PACKET) { total_len = chars; buf->len = 0; } if (!buf->len) { buf->ops = NULL; ops->release(pipe, buf); curbuf = (curbuf + 1) & (pipe->buffers - 1); pipe->curbuf = curbuf; pipe->nrbufs = --bufs; do_wakeup = 1; } total_len -= chars; if (!total_len) break; /* common path: read succeeded */ } if (bufs) /* More to do? */ continue; if (!pipe->writers) break; if (!pipe->waiting_writers) { /* syscall merging: Usually we must not sleep * if O_NONBLOCK is set, or if we got some data. * But if a writer sleeps in kernel space, then * we can wait for that data without violating POSIX. */ if (ret) break; if (filp->f_flags & O_NONBLOCK) { ret = -EAGAIN; break; } } if (signal_pending(current)) { if (!ret) ret = -ERESTARTSYS; break; } if (do_wakeup) { wake_up_interruptible_sync_poll(&pipe->wait, POLLOUT | POLLWRNORM); kill_fasync(&pipe->fasync_writers, SIGIO, POLL_OUT); } pipe_wait(pipe); } __pipe_unlock(pipe); /* Signal writers asynchronously that there is more room. */ if (do_wakeup) { wake_up_interruptible_sync_poll(&pipe->wait, POLLOUT | POLLWRNORM); kill_fasync(&pipe->fasync_writers, SIGIO, POLL_OUT); } if (ret > 0) file_accessed(filp); return ret; } static inline int is_packetized(struct file *file) { return (file->f_flags & O_DIRECT) != 0; } static ssize_t pipe_write(struct kiocb *iocb, const struct iovec *_iov, unsigned long nr_segs, loff_t ppos) { struct file *filp = iocb->ki_filp; struct pipe_inode_info *pipe = filp->private_data; ssize_t ret; int do_wakeup; struct iovec *iov = (struct iovec *)_iov; size_t total_len; ssize_t chars; total_len = iov_length(iov, nr_segs); /* Null write succeeds. */ if (unlikely(total_len == 0)) return 0; do_wakeup = 0; ret = 0; __pipe_lock(pipe); if (!pipe->readers) { send_sig(SIGPIPE, current, 0); ret = -EPIPE; goto out; } /* We try to merge small writes */ chars = total_len & (PAGE_SIZE-1); /* size of the last buffer */ if (pipe->nrbufs && chars != 0) { int lastbuf = (pipe->curbuf + pipe->nrbufs - 1) & (pipe->buffers - 1); struct pipe_buffer *buf = pipe->bufs + lastbuf; const struct pipe_buf_operations *ops = buf->ops; int offset = buf->offset + buf->len; if (ops->can_merge && offset + chars <= PAGE_SIZE) { int error, atomic = 1; void *addr; error = ops->confirm(pipe, buf); if (error) goto out; iov_fault_in_pages_read(iov, chars); redo1: if (atomic) addr = kmap_atomic(buf->page); else addr = kmap(buf->page); error = pipe_iov_copy_from_user(offset + addr, iov, chars, atomic); if (atomic) kunmap_atomic(addr); else kunmap(buf->page); ret = error; do_wakeup = 1; if (error) { if (atomic) { atomic = 0; goto redo1; } goto out; } buf->len += chars; total_len -= chars; ret = chars; if (!total_len) goto out; } } for (;;) { int bufs; if (!pipe->readers) { send_sig(SIGPIPE, current, 0); if (!ret) ret = -EPIPE; break; } bufs = pipe->nrbufs; if (bufs < pipe->buffers) { int newbuf = (pipe->curbuf + bufs) & (pipe->buffers-1); struct pipe_buffer *buf = pipe->bufs + newbuf; struct page *page = pipe->tmp_page; char *src; int error, atomic = 1; if (!page) { page = alloc_page(GFP_HIGHUSER); if (unlikely(!page)) { ret = ret ? : -ENOMEM; break; } pipe->tmp_page = page; } /* Always wake up, even if the copy fails. Otherwise * we lock up (O_NONBLOCK-)readers that sleep due to * syscall merging. * FIXME! Is this really true? */ do_wakeup = 1; chars = PAGE_SIZE; if (chars > total_len) chars = total_len; iov_fault_in_pages_read(iov, chars); redo2: if (atomic) src = kmap_atomic(page); else src = kmap(page); error = pipe_iov_copy_from_user(src, iov, chars, atomic); if (atomic) kunmap_atomic(src); else kunmap(page); if (unlikely(error)) { if (atomic) { atomic = 0; goto redo2; } if (!ret) ret = error; break; } ret += chars; /* Insert it into the buffer array */ buf->page = page; buf->ops = &anon_pipe_buf_ops; buf->offset = 0; buf->len = chars; buf->flags = 0; if (is_packetized(filp)) { buf->ops = &packet_pipe_buf_ops; buf->flags = PIPE_BUF_FLAG_PACKET; } pipe->nrbufs = ++bufs; pipe->tmp_page = NULL; total_len -= chars; if (!total_len) break; } if (bufs < pipe->buffers) continue; if (filp->f_flags & O_NONBLOCK) { if (!ret) ret = -EAGAIN; break; } if (signal_pending(current)) { if (!ret) ret = -ERESTARTSYS; break; } if (do_wakeup) { wake_up_interruptible_sync_poll(&pipe->wait, POLLIN | POLLRDNORM); kill_fasync(&pipe->fasync_readers, SIGIO, POLL_IN); do_wakeup = 0; } pipe->waiting_writers++; pipe_wait(pipe); pipe->waiting_writers--; } out: __pipe_unlock(pipe); if (do_wakeup) { wake_up_interruptible_sync_poll(&pipe->wait, POLLIN | POLLRDNORM); kill_fasync(&pipe->fasync_readers, SIGIO, POLL_IN); } if (ret > 0 && sb_start_write_trylock(file_inode(filp)->i_sb)) { int err = file_update_time(filp); if (err) ret = err; sb_end_write(file_inode(filp)->i_sb); } return ret; } static long pipe_ioctl(struct file *filp, unsigned int cmd, unsigned long arg) { struct pipe_inode_info *pipe = filp->private_data; int count, buf, nrbufs; switch (cmd) { case FIONREAD: __pipe_lock(pipe); count = 0; buf = pipe->curbuf; nrbufs = pipe->nrbufs; while (--nrbufs >= 0) { count += pipe->bufs[buf].len; buf = (buf+1) & (pipe->buffers - 1); } __pipe_unlock(pipe); return put_user(count, (int __user *)arg); default: return -ENOIOCTLCMD; } } /* No kernel lock held - fine */ static unsigned int pipe_poll(struct file *filp, poll_table *wait) { unsigned int mask; struct pipe_inode_info *pipe = filp->private_data; int nrbufs; poll_wait(filp, &pipe->wait, wait); /* Reading only -- no need for acquiring the semaphore. */ nrbufs = pipe->nrbufs; mask = 0; if (filp->f_mode & FMODE_READ) { mask = (nrbufs > 0) ? POLLIN | POLLRDNORM : 0; if (!pipe->writers && filp->f_version != pipe->w_counter) mask |= POLLHUP; } if (filp->f_mode & FMODE_WRITE) { mask |= (nrbufs < pipe->buffers) ? POLLOUT | POLLWRNORM : 0; /* * Most Unices do not set POLLERR for FIFOs but on Linux they * behave exactly like pipes for poll(). */ if (!pipe->readers) mask |= POLLERR; } return mask; } static void put_pipe_info(struct inode *inode, struct pipe_inode_info *pipe) { int kill = 0; spin_lock(&inode->i_lock); if (!--pipe->files) { inode->i_pipe = NULL; kill = 1; } spin_unlock(&inode->i_lock); if (kill) free_pipe_info(pipe); } static int pipe_release(struct inode *inode, struct file *file) { struct pipe_inode_info *pipe = file->private_data; __pipe_lock(pipe); if (file->f_mode & FMODE_READ) pipe->readers--; if (file->f_mode & FMODE_WRITE) pipe->writers--; if (pipe->readers || pipe->writers) { wake_up_interruptible_sync_poll(&pipe->wait, POLLIN | POLLOUT | POLLRDNORM | POLLWRNORM | POLLERR | POLLHUP); kill_fasync(&pipe->fasync_readers, SIGIO, POLL_IN); kill_fasync(&pipe->fasync_writers, SIGIO, POLL_OUT); } __pipe_unlock(pipe); put_pipe_info(inode, pipe); return 0; } static int pipe_fasync(int fd, struct file *filp, int on) { struct pipe_inode_info *pipe = filp->private_data; int retval = 0; __pipe_lock(pipe); if (filp->f_mode & FMODE_READ) retval = fasync_helper(fd, filp, on, &pipe->fasync_readers); if ((filp->f_mode & FMODE_WRITE) && retval >= 0) { retval = fasync_helper(fd, filp, on, &pipe->fasync_writers); if (retval < 0 && (filp->f_mode & FMODE_READ)) /* this can happen only if on == T */ fasync_helper(-1, filp, 0, &pipe->fasync_readers); } __pipe_unlock(pipe); return retval; } struct pipe_inode_info *alloc_pipe_info(void) { struct pipe_inode_info *pipe; pipe = kzalloc(sizeof(struct pipe_inode_info), GFP_KERNEL); if (pipe) { pipe->bufs = kzalloc(sizeof(struct pipe_buffer) * PIPE_DEF_BUFFERS, GFP_KERNEL); if (pipe->bufs) { init_waitqueue_head(&pipe->wait); pipe->r_counter = pipe->w_counter = 1; pipe->buffers = PIPE_DEF_BUFFERS; mutex_init(&pipe->mutex); return pipe; } kfree(pipe); } return NULL; } void free_pipe_info(struct pipe_inode_info *pipe) { int i; for (i = 0; i < pipe->buffers; i++) { struct pipe_buffer *buf = pipe->bufs + i; if (buf->ops) buf->ops->release(pipe, buf); } if (pipe->tmp_page) __free_page(pipe->tmp_page); kfree(pipe->bufs); kfree(pipe); } static struct vfsmount *pipe_mnt __read_mostly; /* * pipefs_dname() is called from d_path(). */ static char *pipefs_dname(struct dentry *dentry, char *buffer, int buflen) { return dynamic_dname(dentry, buffer, buflen, "pipe:[%lu]", dentry->d_inode->i_ino); } static const struct dentry_operations pipefs_dentry_operations = { .d_dname = pipefs_dname, }; static struct inode * get_pipe_inode(void) { struct inode *inode = new_inode_pseudo(pipe_mnt->mnt_sb); struct pipe_inode_info *pipe; if (!inode) goto fail_inode; inode->i_ino = get_next_ino(); pipe = alloc_pipe_info(); if (!pipe) goto fail_iput; inode->i_pipe = pipe; pipe->files = 2; pipe->readers = pipe->writers = 1; inode->i_fop = &pipefifo_fops; /* * Mark the inode dirty from the very beginning, * that way it will never be moved to the dirty * list because "mark_inode_dirty()" will think * that it already _is_ on the dirty list. */ inode->i_state = I_DIRTY; inode->i_mode = S_IFIFO | S_IRUSR | S_IWUSR; inode->i_uid = current_fsuid(); inode->i_gid = current_fsgid(); inode->i_atime = inode->i_mtime = inode->i_ctime = CURRENT_TIME; return inode; fail_iput: iput(inode); fail_inode: return NULL; } int create_pipe_files(struct file **res, int flags) { int err; struct inode *inode = get_pipe_inode(); struct file *f; struct path path; static struct qstr name = { .name = "" }; if (!inode) return -ENFILE; err = -ENOMEM; path.dentry = d_alloc_pseudo(pipe_mnt->mnt_sb, &name); if (!path.dentry) goto err_inode; path.mnt = mntget(pipe_mnt); d_instantiate(path.dentry, inode); err = -ENFILE; f = alloc_file(&path, FMODE_WRITE, &pipefifo_fops); if (IS_ERR(f)) goto err_dentry; f->f_flags = O_WRONLY | (flags & (O_NONBLOCK | O_DIRECT)); f->private_data = inode->i_pipe; res[0] = alloc_file(&path, FMODE_READ, &pipefifo_fops); if (IS_ERR(res[0])) goto err_file; path_get(&path); res[0]->private_data = inode->i_pipe; res[0]->f_flags = O_RDONLY | (flags & O_NONBLOCK); res[1] = f; return 0; err_file: put_filp(f); err_dentry: free_pipe_info(inode->i_pipe); path_put(&path); return err; err_inode: free_pipe_info(inode->i_pipe); iput(inode); return err; } static int __do_pipe_flags(int *fd, struct file **files, int flags) { int error; int fdw, fdr; if (flags & ~(O_CLOEXEC | O_NONBLOCK | O_DIRECT)) return -EINVAL; error = create_pipe_files(files, flags); if (error) return error; error = get_unused_fd_flags(flags); if (error < 0) goto err_read_pipe; fdr = error; error = get_unused_fd_flags(flags); if (error < 0) goto err_fdr; fdw = error; audit_fd_pair(fdr, fdw); fd[0] = fdr; fd[1] = fdw; return 0; err_fdr: put_unused_fd(fdr); err_read_pipe: fput(files[0]); fput(files[1]); return error; } int do_pipe_flags(int *fd, int flags) { struct file *files[2]; int error = __do_pipe_flags(fd, files, flags); if (!error) { fd_install(fd[0], files[0]); fd_install(fd[1], files[1]); } return error; } /* * sys_pipe() is the normal C calling standard for creating * a pipe. It's not the way Unix traditionally does this, though. */ SYSCALL_DEFINE2(pipe2, int __user *, fildes, int, flags) { struct file *files[2]; int fd[2]; int error; error = __do_pipe_flags(fd, files, flags); if (!error) { if (unlikely(copy_to_user(fildes, fd, sizeof(fd)))) { fput(files[0]); fput(files[1]); put_unused_fd(fd[0]); put_unused_fd(fd[1]); error = -EFAULT; } else { fd_install(fd[0], files[0]); fd_install(fd[1], files[1]); } } return error; } SYSCALL_DEFINE1(pipe, int __user *, fildes) { return sys_pipe2(fildes, 0); } static int wait_for_partner(struct pipe_inode_info *pipe, unsigned int *cnt) { int cur = *cnt; while (cur == *cnt) { pipe_wait(pipe); if (signal_pending(current)) break; } return cur == *cnt ? -ERESTARTSYS : 0; } static void wake_up_partner(struct pipe_inode_info *pipe) { wake_up_interruptible(&pipe->wait); } static int fifo_open(struct inode *inode, struct file *filp) { struct pipe_inode_info *pipe; bool is_pipe = inode->i_sb->s_magic == PIPEFS_MAGIC; int ret; filp->f_version = 0; spin_lock(&inode->i_lock); if (inode->i_pipe) { pipe = inode->i_pipe; pipe->files++; spin_unlock(&inode->i_lock); } else { spin_unlock(&inode->i_lock); pipe = alloc_pipe_info(); if (!pipe) return -ENOMEM; pipe->files = 1; spin_lock(&inode->i_lock); if (unlikely(inode->i_pipe)) { inode->i_pipe->files++; spin_unlock(&inode->i_lock); free_pipe_info(pipe); pipe = inode->i_pipe; } else { inode->i_pipe = pipe; spin_unlock(&inode->i_lock); } } filp->private_data = pipe; /* OK, we have a pipe and it's pinned down */ __pipe_lock(pipe); /* We can only do regular read/write on fifos */ filp->f_mode &= (FMODE_READ | FMODE_WRITE); switch (filp->f_mode) { case FMODE_READ: /* * O_RDONLY * POSIX.1 says that O_NONBLOCK means return with the FIFO * opened, even when there is no process writing the FIFO. */ pipe->r_counter++; if (pipe->readers++ == 0) wake_up_partner(pipe); if (!is_pipe && !pipe->writers) { if ((filp->f_flags & O_NONBLOCK)) { /* suppress POLLHUP until we have * seen a writer */ filp->f_version = pipe->w_counter; } else { if (wait_for_partner(pipe, &pipe->w_counter)) goto err_rd; } } break; case FMODE_WRITE: /* * O_WRONLY * POSIX.1 says that O_NONBLOCK means return -1 with * errno=ENXIO when there is no process reading the FIFO. */ ret = -ENXIO; if (!is_pipe && (filp->f_flags & O_NONBLOCK) && !pipe->readers) goto err; pipe->w_counter++; if (!pipe->writers++) wake_up_partner(pipe); if (!is_pipe && !pipe->readers) { if (wait_for_partner(pipe, &pipe->r_counter)) goto err_wr; } break; case FMODE_READ | FMODE_WRITE: /* * O_RDWR * POSIX.1 leaves this case "undefined" when O_NONBLOCK is set. * This implementation will NEVER block on a O_RDWR open, since * the process can at least talk to itself. */ pipe->readers++; pipe->writers++; pipe->r_counter++; pipe->w_counter++; if (pipe->readers == 1 || pipe->writers == 1) wake_up_partner(pipe); break; default: ret = -EINVAL; goto err; } /* Ok! */ __pipe_unlock(pipe); return 0; err_rd: if (!--pipe->readers) wake_up_interruptible(&pipe->wait); ret = -ERESTARTSYS; goto err; err_wr: if (!--pipe->writers) wake_up_interruptible(&pipe->wait); ret = -ERESTARTSYS; goto err; err: __pipe_unlock(pipe); put_pipe_info(inode, pipe); return ret; } const struct file_operations pipefifo_fops = { .open = fifo_open, .llseek = no_llseek, .read = do_sync_read, .aio_read = pipe_read, .write = do_sync_write, .aio_write = pipe_write, .poll = pipe_poll, .unlocked_ioctl = pipe_ioctl, .release = pipe_release, .fasync = pipe_fasync, }; /* * Allocate a new array of pipe buffers and copy the info over. Returns the * pipe size if successful, or return -ERROR on error. */ static long pipe_set_size(struct pipe_inode_info *pipe, unsigned long nr_pages) { struct pipe_buffer *bufs; /* * We can shrink the pipe, if arg >= pipe->nrbufs. Since we don't * expect a lot of shrink+grow operations, just free and allocate * again like we would do for growing. If the pipe currently * contains more buffers than arg, then return busy. */ if (nr_pages < pipe->nrbufs) return -EBUSY; bufs = kcalloc(nr_pages, sizeof(*bufs), GFP_KERNEL | __GFP_NOWARN); if (unlikely(!bufs)) return -ENOMEM; /* * The pipe array wraps around, so just start the new one at zero * and adjust the indexes. */ if (pipe->nrbufs) { unsigned int tail; unsigned int head; tail = pipe->curbuf + pipe->nrbufs; if (tail < pipe->buffers) tail = 0; else tail &= (pipe->buffers - 1); head = pipe->nrbufs - tail; if (head) memcpy(bufs, pipe->bufs + pipe->curbuf, head * sizeof(struct pipe_buffer)); if (tail) memcpy(bufs + head, pipe->bufs, tail * sizeof(struct pipe_buffer)); } pipe->curbuf = 0; kfree(pipe->bufs); pipe->bufs = bufs; pipe->buffers = nr_pages; return nr_pages * PAGE_SIZE; } /* * Currently we rely on the pipe array holding a power-of-2 number * of pages. */ static inline unsigned int round_pipe_size(unsigned int size) { unsigned long nr_pages; nr_pages = (size + PAGE_SIZE - 1) >> PAGE_SHIFT; return roundup_pow_of_two(nr_pages) << PAGE_SHIFT; } /* * This should work even if CONFIG_PROC_FS isn't set, as proc_dointvec_minmax * will return an error. */ int pipe_proc_fn(struct ctl_table *table, int write, void __user *buf, size_t *lenp, loff_t *ppos) { int ret; ret = proc_dointvec_minmax(table, write, buf, lenp, ppos); if (ret < 0 || !write) return ret; pipe_max_size = round_pipe_size(pipe_max_size); return ret; } /* * After the inode slimming patch, i_pipe/i_bdev/i_cdev share the same * location, so checking ->i_pipe is not enough to verify that this is a * pipe. */ struct pipe_inode_info *get_pipe_info(struct file *file) { return file->f_op == &pipefifo_fops ? file->private_data : NULL; } long pipe_fcntl(struct file *file, unsigned int cmd, unsigned long arg) { struct pipe_inode_info *pipe; long ret; pipe = get_pipe_info(file); if (!pipe) return -EBADF; __pipe_lock(pipe); switch (cmd) { case F_SETPIPE_SZ: { unsigned int size, nr_pages; size = round_pipe_size(arg); nr_pages = size >> PAGE_SHIFT; ret = -EINVAL; if (!nr_pages) goto out; if (!capable(CAP_SYS_RESOURCE) && size > pipe_max_size) { ret = -EPERM; goto out; } ret = pipe_set_size(pipe, nr_pages); break; } case F_GETPIPE_SZ: ret = pipe->buffers * PAGE_SIZE; break; default: ret = -EINVAL; break; } out: __pipe_unlock(pipe); return ret; } static const struct super_operations pipefs_ops = { .destroy_inode = free_inode_nonrcu, .statfs = simple_statfs, }; /* * pipefs should _never_ be mounted by userland - too much of security hassle, * no real gain from having the whole whorehouse mounted. So we don't need * any operations on the root directory. However, we need a non-trivial * d_name - pipe: will go nicely and kill the special-casing in procfs. */ static struct dentry *pipefs_mount(struct file_system_type *fs_type, int flags, const char *dev_name, void *data) { return mount_pseudo(fs_type, "pipe:", &pipefs_ops, &pipefs_dentry_operations, PIPEFS_MAGIC); } static struct file_system_type pipe_fs_type = { .name = "pipefs", .mount = pipefs_mount, .kill_sb = kill_anon_super, }; static int __init init_pipe_fs(void) { int err = register_filesystem(&pipe_fs_type); if (!err) { pipe_mnt = kern_mount(&pipe_fs_type); if (IS_ERR(pipe_mnt)) { err = PTR_ERR(pipe_mnt); unregister_filesystem(&pipe_fs_type); } } return err; } fs_initcall(init_pipe_fs);
./CrossVul/dataset_final_sorted/CWE-17/c/good_1498_0
crossvul-cpp_data_good_1643_0
/* bpf_jit_comp.c : BPF JIT compiler * * Copyright (C) 2011-2013 Eric Dumazet (eric.dumazet@gmail.com) * Internal BPF Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; version 2 * of the License. */ #include <linux/netdevice.h> #include <linux/filter.h> #include <linux/if_vlan.h> #include <asm/cacheflush.h> int bpf_jit_enable __read_mostly; /* * assembly code in arch/x86/net/bpf_jit.S */ extern u8 sk_load_word[], sk_load_half[], sk_load_byte[]; extern u8 sk_load_word_positive_offset[], sk_load_half_positive_offset[]; extern u8 sk_load_byte_positive_offset[]; extern u8 sk_load_word_negative_offset[], sk_load_half_negative_offset[]; extern u8 sk_load_byte_negative_offset[]; static u8 *emit_code(u8 *ptr, u32 bytes, unsigned int len) { if (len == 1) *ptr = bytes; else if (len == 2) *(u16 *)ptr = bytes; else { *(u32 *)ptr = bytes; barrier(); } return ptr + len; } #define EMIT(bytes, len) do { prog = emit_code(prog, bytes, len); } while (0) #define EMIT1(b1) EMIT(b1, 1) #define EMIT2(b1, b2) EMIT((b1) + ((b2) << 8), 2) #define EMIT3(b1, b2, b3) EMIT((b1) + ((b2) << 8) + ((b3) << 16), 3) #define EMIT4(b1, b2, b3, b4) EMIT((b1) + ((b2) << 8) + ((b3) << 16) + ((b4) << 24), 4) #define EMIT1_off32(b1, off) \ do {EMIT1(b1); EMIT(off, 4); } while (0) #define EMIT2_off32(b1, b2, off) \ do {EMIT2(b1, b2); EMIT(off, 4); } while (0) #define EMIT3_off32(b1, b2, b3, off) \ do {EMIT3(b1, b2, b3); EMIT(off, 4); } while (0) #define EMIT4_off32(b1, b2, b3, b4, off) \ do {EMIT4(b1, b2, b3, b4); EMIT(off, 4); } while (0) static bool is_imm8(int value) { return value <= 127 && value >= -128; } static bool is_simm32(s64 value) { return value == (s64) (s32) value; } /* mov dst, src */ #define EMIT_mov(DST, SRC) \ do {if (DST != SRC) \ EMIT3(add_2mod(0x48, DST, SRC), 0x89, add_2reg(0xC0, DST, SRC)); \ } while (0) static int bpf_size_to_x86_bytes(int bpf_size) { if (bpf_size == BPF_W) return 4; else if (bpf_size == BPF_H) return 2; else if (bpf_size == BPF_B) return 1; else if (bpf_size == BPF_DW) return 4; /* imm32 */ else return 0; } /* list of x86 cond jumps opcodes (. + s8) * Add 0x10 (and an extra 0x0f) to generate far jumps (. + s32) */ #define X86_JB 0x72 #define X86_JAE 0x73 #define X86_JE 0x74 #define X86_JNE 0x75 #define X86_JBE 0x76 #define X86_JA 0x77 #define X86_JGE 0x7D #define X86_JG 0x7F static void bpf_flush_icache(void *start, void *end) { mm_segment_t old_fs = get_fs(); set_fs(KERNEL_DS); smp_wmb(); flush_icache_range((unsigned long)start, (unsigned long)end); set_fs(old_fs); } #define CHOOSE_LOAD_FUNC(K, func) \ ((int)K < 0 ? ((int)K >= SKF_LL_OFF ? func##_negative_offset : func) : func##_positive_offset) /* pick a register outside of BPF range for JIT internal work */ #define AUX_REG (MAX_BPF_REG + 1) /* the following table maps BPF registers to x64 registers. * x64 register r12 is unused, since if used as base address register * in load/store instructions, it always needs an extra byte of encoding */ static const int reg2hex[] = { [BPF_REG_0] = 0, /* rax */ [BPF_REG_1] = 7, /* rdi */ [BPF_REG_2] = 6, /* rsi */ [BPF_REG_3] = 2, /* rdx */ [BPF_REG_4] = 1, /* rcx */ [BPF_REG_5] = 0, /* r8 */ [BPF_REG_6] = 3, /* rbx callee saved */ [BPF_REG_7] = 5, /* r13 callee saved */ [BPF_REG_8] = 6, /* r14 callee saved */ [BPF_REG_9] = 7, /* r15 callee saved */ [BPF_REG_FP] = 5, /* rbp readonly */ [AUX_REG] = 3, /* r11 temp register */ }; /* is_ereg() == true if BPF register 'reg' maps to x64 r8..r15 * which need extra byte of encoding. * rax,rcx,...,rbp have simpler encoding */ static bool is_ereg(u32 reg) { return (1 << reg) & (BIT(BPF_REG_5) | BIT(AUX_REG) | BIT(BPF_REG_7) | BIT(BPF_REG_8) | BIT(BPF_REG_9)); } /* add modifiers if 'reg' maps to x64 registers r8..r15 */ static u8 add_1mod(u8 byte, u32 reg) { if (is_ereg(reg)) byte |= 1; return byte; } static u8 add_2mod(u8 byte, u32 r1, u32 r2) { if (is_ereg(r1)) byte |= 1; if (is_ereg(r2)) byte |= 4; return byte; } /* encode 'dst_reg' register into x64 opcode 'byte' */ static u8 add_1reg(u8 byte, u32 dst_reg) { return byte + reg2hex[dst_reg]; } /* encode 'dst_reg' and 'src_reg' registers into x64 opcode 'byte' */ static u8 add_2reg(u8 byte, u32 dst_reg, u32 src_reg) { return byte + reg2hex[dst_reg] + (reg2hex[src_reg] << 3); } static void jit_fill_hole(void *area, unsigned int size) { /* fill whole space with int3 instructions */ memset(area, 0xcc, size); } struct jit_context { int cleanup_addr; /* epilogue code offset */ bool seen_ld_abs; }; /* maximum number of bytes emitted while JITing one eBPF insn */ #define BPF_MAX_INSN_SIZE 128 #define BPF_INSN_SAFETY 64 static int do_jit(struct bpf_prog *bpf_prog, int *addrs, u8 *image, int oldproglen, struct jit_context *ctx) { struct bpf_insn *insn = bpf_prog->insnsi; int insn_cnt = bpf_prog->len; bool seen_ld_abs = ctx->seen_ld_abs | (oldproglen == 0); bool seen_exit = false; u8 temp[BPF_MAX_INSN_SIZE + BPF_INSN_SAFETY]; int i; int proglen = 0; u8 *prog = temp; int stacksize = MAX_BPF_STACK + 32 /* space for rbx, r13, r14, r15 */ + 8 /* space for skb_copy_bits() buffer */; EMIT1(0x55); /* push rbp */ EMIT3(0x48, 0x89, 0xE5); /* mov rbp,rsp */ /* sub rsp, stacksize */ EMIT3_off32(0x48, 0x81, 0xEC, stacksize); /* all classic BPF filters use R6(rbx) save it */ /* mov qword ptr [rbp-X],rbx */ EMIT3_off32(0x48, 0x89, 0x9D, -stacksize); /* bpf_convert_filter() maps classic BPF register X to R7 and uses R8 * as temporary, so all tcpdump filters need to spill/fill R7(r13) and * R8(r14). R9(r15) spill could be made conditional, but there is only * one 'bpf_error' return path out of helper functions inside bpf_jit.S * The overhead of extra spill is negligible for any filter other * than synthetic ones. Therefore not worth adding complexity. */ /* mov qword ptr [rbp-X],r13 */ EMIT3_off32(0x4C, 0x89, 0xAD, -stacksize + 8); /* mov qword ptr [rbp-X],r14 */ EMIT3_off32(0x4C, 0x89, 0xB5, -stacksize + 16); /* mov qword ptr [rbp-X],r15 */ EMIT3_off32(0x4C, 0x89, 0xBD, -stacksize + 24); /* clear A and X registers */ EMIT2(0x31, 0xc0); /* xor eax, eax */ EMIT3(0x4D, 0x31, 0xED); /* xor r13, r13 */ if (seen_ld_abs) { /* r9d : skb->len - skb->data_len (headlen) * r10 : skb->data */ if (is_imm8(offsetof(struct sk_buff, len))) /* mov %r9d, off8(%rdi) */ EMIT4(0x44, 0x8b, 0x4f, offsetof(struct sk_buff, len)); else /* mov %r9d, off32(%rdi) */ EMIT3_off32(0x44, 0x8b, 0x8f, offsetof(struct sk_buff, len)); if (is_imm8(offsetof(struct sk_buff, data_len))) /* sub %r9d, off8(%rdi) */ EMIT4(0x44, 0x2b, 0x4f, offsetof(struct sk_buff, data_len)); else EMIT3_off32(0x44, 0x2b, 0x8f, offsetof(struct sk_buff, data_len)); if (is_imm8(offsetof(struct sk_buff, data))) /* mov %r10, off8(%rdi) */ EMIT4(0x4c, 0x8b, 0x57, offsetof(struct sk_buff, data)); else /* mov %r10, off32(%rdi) */ EMIT3_off32(0x4c, 0x8b, 0x97, offsetof(struct sk_buff, data)); } for (i = 0; i < insn_cnt; i++, insn++) { const s32 imm32 = insn->imm; u32 dst_reg = insn->dst_reg; u32 src_reg = insn->src_reg; u8 b1 = 0, b2 = 0, b3 = 0; s64 jmp_offset; u8 jmp_cond; int ilen; u8 *func; switch (insn->code) { /* ALU */ case BPF_ALU | BPF_ADD | BPF_X: case BPF_ALU | BPF_SUB | BPF_X: case BPF_ALU | BPF_AND | BPF_X: case BPF_ALU | BPF_OR | BPF_X: case BPF_ALU | BPF_XOR | BPF_X: case BPF_ALU64 | BPF_ADD | BPF_X: case BPF_ALU64 | BPF_SUB | BPF_X: case BPF_ALU64 | BPF_AND | BPF_X: case BPF_ALU64 | BPF_OR | BPF_X: case BPF_ALU64 | BPF_XOR | BPF_X: switch (BPF_OP(insn->code)) { case BPF_ADD: b2 = 0x01; break; case BPF_SUB: b2 = 0x29; break; case BPF_AND: b2 = 0x21; break; case BPF_OR: b2 = 0x09; break; case BPF_XOR: b2 = 0x31; break; } if (BPF_CLASS(insn->code) == BPF_ALU64) EMIT1(add_2mod(0x48, dst_reg, src_reg)); else if (is_ereg(dst_reg) || is_ereg(src_reg)) EMIT1(add_2mod(0x40, dst_reg, src_reg)); EMIT2(b2, add_2reg(0xC0, dst_reg, src_reg)); break; /* mov dst, src */ case BPF_ALU64 | BPF_MOV | BPF_X: EMIT_mov(dst_reg, src_reg); break; /* mov32 dst, src */ case BPF_ALU | BPF_MOV | BPF_X: if (is_ereg(dst_reg) || is_ereg(src_reg)) EMIT1(add_2mod(0x40, dst_reg, src_reg)); EMIT2(0x89, add_2reg(0xC0, dst_reg, src_reg)); break; /* neg dst */ case BPF_ALU | BPF_NEG: case BPF_ALU64 | BPF_NEG: if (BPF_CLASS(insn->code) == BPF_ALU64) EMIT1(add_1mod(0x48, dst_reg)); else if (is_ereg(dst_reg)) EMIT1(add_1mod(0x40, dst_reg)); EMIT2(0xF7, add_1reg(0xD8, dst_reg)); break; case BPF_ALU | BPF_ADD | BPF_K: case BPF_ALU | BPF_SUB | BPF_K: case BPF_ALU | BPF_AND | BPF_K: case BPF_ALU | BPF_OR | BPF_K: case BPF_ALU | BPF_XOR | BPF_K: case BPF_ALU64 | BPF_ADD | BPF_K: case BPF_ALU64 | BPF_SUB | BPF_K: case BPF_ALU64 | BPF_AND | BPF_K: case BPF_ALU64 | BPF_OR | BPF_K: case BPF_ALU64 | BPF_XOR | BPF_K: if (BPF_CLASS(insn->code) == BPF_ALU64) EMIT1(add_1mod(0x48, dst_reg)); else if (is_ereg(dst_reg)) EMIT1(add_1mod(0x40, dst_reg)); switch (BPF_OP(insn->code)) { case BPF_ADD: b3 = 0xC0; break; case BPF_SUB: b3 = 0xE8; break; case BPF_AND: b3 = 0xE0; break; case BPF_OR: b3 = 0xC8; break; case BPF_XOR: b3 = 0xF0; break; } if (is_imm8(imm32)) EMIT3(0x83, add_1reg(b3, dst_reg), imm32); else EMIT2_off32(0x81, add_1reg(b3, dst_reg), imm32); break; case BPF_ALU64 | BPF_MOV | BPF_K: /* optimization: if imm32 is positive, * use 'mov eax, imm32' (which zero-extends imm32) * to save 2 bytes */ if (imm32 < 0) { /* 'mov rax, imm32' sign extends imm32 */ b1 = add_1mod(0x48, dst_reg); b2 = 0xC7; b3 = 0xC0; EMIT3_off32(b1, b2, add_1reg(b3, dst_reg), imm32); break; } case BPF_ALU | BPF_MOV | BPF_K: /* mov %eax, imm32 */ if (is_ereg(dst_reg)) EMIT1(add_1mod(0x40, dst_reg)); EMIT1_off32(add_1reg(0xB8, dst_reg), imm32); break; case BPF_LD | BPF_IMM | BPF_DW: if (insn[1].code != 0 || insn[1].src_reg != 0 || insn[1].dst_reg != 0 || insn[1].off != 0) { /* verifier must catch invalid insns */ pr_err("invalid BPF_LD_IMM64 insn\n"); return -EINVAL; } /* movabsq %rax, imm64 */ EMIT2(add_1mod(0x48, dst_reg), add_1reg(0xB8, dst_reg)); EMIT(insn[0].imm, 4); EMIT(insn[1].imm, 4); insn++; i++; break; /* dst %= src, dst /= src, dst %= imm32, dst /= imm32 */ case BPF_ALU | BPF_MOD | BPF_X: case BPF_ALU | BPF_DIV | BPF_X: case BPF_ALU | BPF_MOD | BPF_K: case BPF_ALU | BPF_DIV | BPF_K: case BPF_ALU64 | BPF_MOD | BPF_X: case BPF_ALU64 | BPF_DIV | BPF_X: case BPF_ALU64 | BPF_MOD | BPF_K: case BPF_ALU64 | BPF_DIV | BPF_K: EMIT1(0x50); /* push rax */ EMIT1(0x52); /* push rdx */ if (BPF_SRC(insn->code) == BPF_X) /* mov r11, src_reg */ EMIT_mov(AUX_REG, src_reg); else /* mov r11, imm32 */ EMIT3_off32(0x49, 0xC7, 0xC3, imm32); /* mov rax, dst_reg */ EMIT_mov(BPF_REG_0, dst_reg); /* xor edx, edx * equivalent to 'xor rdx, rdx', but one byte less */ EMIT2(0x31, 0xd2); if (BPF_SRC(insn->code) == BPF_X) { /* if (src_reg == 0) return 0 */ /* cmp r11, 0 */ EMIT4(0x49, 0x83, 0xFB, 0x00); /* jne .+9 (skip over pop, pop, xor and jmp) */ EMIT2(X86_JNE, 1 + 1 + 2 + 5); EMIT1(0x5A); /* pop rdx */ EMIT1(0x58); /* pop rax */ EMIT2(0x31, 0xc0); /* xor eax, eax */ /* jmp cleanup_addr * addrs[i] - 11, because there are 11 bytes * after this insn: div, mov, pop, pop, mov */ jmp_offset = ctx->cleanup_addr - (addrs[i] - 11); EMIT1_off32(0xE9, jmp_offset); } if (BPF_CLASS(insn->code) == BPF_ALU64) /* div r11 */ EMIT3(0x49, 0xF7, 0xF3); else /* div r11d */ EMIT3(0x41, 0xF7, 0xF3); if (BPF_OP(insn->code) == BPF_MOD) /* mov r11, rdx */ EMIT3(0x49, 0x89, 0xD3); else /* mov r11, rax */ EMIT3(0x49, 0x89, 0xC3); EMIT1(0x5A); /* pop rdx */ EMIT1(0x58); /* pop rax */ /* mov dst_reg, r11 */ EMIT_mov(dst_reg, AUX_REG); break; case BPF_ALU | BPF_MUL | BPF_K: case BPF_ALU | BPF_MUL | BPF_X: case BPF_ALU64 | BPF_MUL | BPF_K: case BPF_ALU64 | BPF_MUL | BPF_X: EMIT1(0x50); /* push rax */ EMIT1(0x52); /* push rdx */ /* mov r11, dst_reg */ EMIT_mov(AUX_REG, dst_reg); if (BPF_SRC(insn->code) == BPF_X) /* mov rax, src_reg */ EMIT_mov(BPF_REG_0, src_reg); else /* mov rax, imm32 */ EMIT3_off32(0x48, 0xC7, 0xC0, imm32); if (BPF_CLASS(insn->code) == BPF_ALU64) EMIT1(add_1mod(0x48, AUX_REG)); else if (is_ereg(AUX_REG)) EMIT1(add_1mod(0x40, AUX_REG)); /* mul(q) r11 */ EMIT2(0xF7, add_1reg(0xE0, AUX_REG)); /* mov r11, rax */ EMIT_mov(AUX_REG, BPF_REG_0); EMIT1(0x5A); /* pop rdx */ EMIT1(0x58); /* pop rax */ /* mov dst_reg, r11 */ EMIT_mov(dst_reg, AUX_REG); break; /* shifts */ case BPF_ALU | BPF_LSH | BPF_K: case BPF_ALU | BPF_RSH | BPF_K: case BPF_ALU | BPF_ARSH | BPF_K: case BPF_ALU64 | BPF_LSH | BPF_K: case BPF_ALU64 | BPF_RSH | BPF_K: case BPF_ALU64 | BPF_ARSH | BPF_K: if (BPF_CLASS(insn->code) == BPF_ALU64) EMIT1(add_1mod(0x48, dst_reg)); else if (is_ereg(dst_reg)) EMIT1(add_1mod(0x40, dst_reg)); switch (BPF_OP(insn->code)) { case BPF_LSH: b3 = 0xE0; break; case BPF_RSH: b3 = 0xE8; break; case BPF_ARSH: b3 = 0xF8; break; } EMIT3(0xC1, add_1reg(b3, dst_reg), imm32); break; case BPF_ALU | BPF_LSH | BPF_X: case BPF_ALU | BPF_RSH | BPF_X: case BPF_ALU | BPF_ARSH | BPF_X: case BPF_ALU64 | BPF_LSH | BPF_X: case BPF_ALU64 | BPF_RSH | BPF_X: case BPF_ALU64 | BPF_ARSH | BPF_X: /* check for bad case when dst_reg == rcx */ if (dst_reg == BPF_REG_4) { /* mov r11, dst_reg */ EMIT_mov(AUX_REG, dst_reg); dst_reg = AUX_REG; } if (src_reg != BPF_REG_4) { /* common case */ EMIT1(0x51); /* push rcx */ /* mov rcx, src_reg */ EMIT_mov(BPF_REG_4, src_reg); } /* shl %rax, %cl | shr %rax, %cl | sar %rax, %cl */ if (BPF_CLASS(insn->code) == BPF_ALU64) EMIT1(add_1mod(0x48, dst_reg)); else if (is_ereg(dst_reg)) EMIT1(add_1mod(0x40, dst_reg)); switch (BPF_OP(insn->code)) { case BPF_LSH: b3 = 0xE0; break; case BPF_RSH: b3 = 0xE8; break; case BPF_ARSH: b3 = 0xF8; break; } EMIT2(0xD3, add_1reg(b3, dst_reg)); if (src_reg != BPF_REG_4) EMIT1(0x59); /* pop rcx */ if (insn->dst_reg == BPF_REG_4) /* mov dst_reg, r11 */ EMIT_mov(insn->dst_reg, AUX_REG); break; case BPF_ALU | BPF_END | BPF_FROM_BE: switch (imm32) { case 16: /* emit 'ror %ax, 8' to swap lower 2 bytes */ EMIT1(0x66); if (is_ereg(dst_reg)) EMIT1(0x41); EMIT3(0xC1, add_1reg(0xC8, dst_reg), 8); /* emit 'movzwl eax, ax' */ if (is_ereg(dst_reg)) EMIT3(0x45, 0x0F, 0xB7); else EMIT2(0x0F, 0xB7); EMIT1(add_2reg(0xC0, dst_reg, dst_reg)); break; case 32: /* emit 'bswap eax' to swap lower 4 bytes */ if (is_ereg(dst_reg)) EMIT2(0x41, 0x0F); else EMIT1(0x0F); EMIT1(add_1reg(0xC8, dst_reg)); break; case 64: /* emit 'bswap rax' to swap 8 bytes */ EMIT3(add_1mod(0x48, dst_reg), 0x0F, add_1reg(0xC8, dst_reg)); break; } break; case BPF_ALU | BPF_END | BPF_FROM_LE: switch (imm32) { case 16: /* emit 'movzwl eax, ax' to zero extend 16-bit * into 64 bit */ if (is_ereg(dst_reg)) EMIT3(0x45, 0x0F, 0xB7); else EMIT2(0x0F, 0xB7); EMIT1(add_2reg(0xC0, dst_reg, dst_reg)); break; case 32: /* emit 'mov eax, eax' to clear upper 32-bits */ if (is_ereg(dst_reg)) EMIT1(0x45); EMIT2(0x89, add_2reg(0xC0, dst_reg, dst_reg)); break; case 64: /* nop */ break; } break; /* ST: *(u8*)(dst_reg + off) = imm */ case BPF_ST | BPF_MEM | BPF_B: if (is_ereg(dst_reg)) EMIT2(0x41, 0xC6); else EMIT1(0xC6); goto st; case BPF_ST | BPF_MEM | BPF_H: if (is_ereg(dst_reg)) EMIT3(0x66, 0x41, 0xC7); else EMIT2(0x66, 0xC7); goto st; case BPF_ST | BPF_MEM | BPF_W: if (is_ereg(dst_reg)) EMIT2(0x41, 0xC7); else EMIT1(0xC7); goto st; case BPF_ST | BPF_MEM | BPF_DW: EMIT2(add_1mod(0x48, dst_reg), 0xC7); st: if (is_imm8(insn->off)) EMIT2(add_1reg(0x40, dst_reg), insn->off); else EMIT1_off32(add_1reg(0x80, dst_reg), insn->off); EMIT(imm32, bpf_size_to_x86_bytes(BPF_SIZE(insn->code))); break; /* STX: *(u8*)(dst_reg + off) = src_reg */ case BPF_STX | BPF_MEM | BPF_B: /* emit 'mov byte ptr [rax + off], al' */ if (is_ereg(dst_reg) || is_ereg(src_reg) || /* have to add extra byte for x86 SIL, DIL regs */ src_reg == BPF_REG_1 || src_reg == BPF_REG_2) EMIT2(add_2mod(0x40, dst_reg, src_reg), 0x88); else EMIT1(0x88); goto stx; case BPF_STX | BPF_MEM | BPF_H: if (is_ereg(dst_reg) || is_ereg(src_reg)) EMIT3(0x66, add_2mod(0x40, dst_reg, src_reg), 0x89); else EMIT2(0x66, 0x89); goto stx; case BPF_STX | BPF_MEM | BPF_W: if (is_ereg(dst_reg) || is_ereg(src_reg)) EMIT2(add_2mod(0x40, dst_reg, src_reg), 0x89); else EMIT1(0x89); goto stx; case BPF_STX | BPF_MEM | BPF_DW: EMIT2(add_2mod(0x48, dst_reg, src_reg), 0x89); stx: if (is_imm8(insn->off)) EMIT2(add_2reg(0x40, dst_reg, src_reg), insn->off); else EMIT1_off32(add_2reg(0x80, dst_reg, src_reg), insn->off); break; /* LDX: dst_reg = *(u8*)(src_reg + off) */ case BPF_LDX | BPF_MEM | BPF_B: /* emit 'movzx rax, byte ptr [rax + off]' */ EMIT3(add_2mod(0x48, src_reg, dst_reg), 0x0F, 0xB6); goto ldx; case BPF_LDX | BPF_MEM | BPF_H: /* emit 'movzx rax, word ptr [rax + off]' */ EMIT3(add_2mod(0x48, src_reg, dst_reg), 0x0F, 0xB7); goto ldx; case BPF_LDX | BPF_MEM | BPF_W: /* emit 'mov eax, dword ptr [rax+0x14]' */ if (is_ereg(dst_reg) || is_ereg(src_reg)) EMIT2(add_2mod(0x40, src_reg, dst_reg), 0x8B); else EMIT1(0x8B); goto ldx; case BPF_LDX | BPF_MEM | BPF_DW: /* emit 'mov rax, qword ptr [rax+0x14]' */ EMIT2(add_2mod(0x48, src_reg, dst_reg), 0x8B); ldx: /* if insn->off == 0 we can save one extra byte, but * special case of x86 r13 which always needs an offset * is not worth the hassle */ if (is_imm8(insn->off)) EMIT2(add_2reg(0x40, src_reg, dst_reg), insn->off); else EMIT1_off32(add_2reg(0x80, src_reg, dst_reg), insn->off); break; /* STX XADD: lock *(u32*)(dst_reg + off) += src_reg */ case BPF_STX | BPF_XADD | BPF_W: /* emit 'lock add dword ptr [rax + off], eax' */ if (is_ereg(dst_reg) || is_ereg(src_reg)) EMIT3(0xF0, add_2mod(0x40, dst_reg, src_reg), 0x01); else EMIT2(0xF0, 0x01); goto xadd; case BPF_STX | BPF_XADD | BPF_DW: EMIT3(0xF0, add_2mod(0x48, dst_reg, src_reg), 0x01); xadd: if (is_imm8(insn->off)) EMIT2(add_2reg(0x40, dst_reg, src_reg), insn->off); else EMIT1_off32(add_2reg(0x80, dst_reg, src_reg), insn->off); break; /* call */ case BPF_JMP | BPF_CALL: func = (u8 *) __bpf_call_base + imm32; jmp_offset = func - (image + addrs[i]); if (seen_ld_abs) { EMIT2(0x41, 0x52); /* push %r10 */ EMIT2(0x41, 0x51); /* push %r9 */ /* need to adjust jmp offset, since * pop %r9, pop %r10 take 4 bytes after call insn */ jmp_offset += 4; } if (!imm32 || !is_simm32(jmp_offset)) { pr_err("unsupported bpf func %d addr %p image %p\n", imm32, func, image); return -EINVAL; } EMIT1_off32(0xE8, jmp_offset); if (seen_ld_abs) { EMIT2(0x41, 0x59); /* pop %r9 */ EMIT2(0x41, 0x5A); /* pop %r10 */ } break; /* cond jump */ case BPF_JMP | BPF_JEQ | BPF_X: case BPF_JMP | BPF_JNE | BPF_X: case BPF_JMP | BPF_JGT | BPF_X: case BPF_JMP | BPF_JGE | BPF_X: case BPF_JMP | BPF_JSGT | BPF_X: case BPF_JMP | BPF_JSGE | BPF_X: /* cmp dst_reg, src_reg */ EMIT3(add_2mod(0x48, dst_reg, src_reg), 0x39, add_2reg(0xC0, dst_reg, src_reg)); goto emit_cond_jmp; case BPF_JMP | BPF_JSET | BPF_X: /* test dst_reg, src_reg */ EMIT3(add_2mod(0x48, dst_reg, src_reg), 0x85, add_2reg(0xC0, dst_reg, src_reg)); goto emit_cond_jmp; case BPF_JMP | BPF_JSET | BPF_K: /* test dst_reg, imm32 */ EMIT1(add_1mod(0x48, dst_reg)); EMIT2_off32(0xF7, add_1reg(0xC0, dst_reg), imm32); goto emit_cond_jmp; case BPF_JMP | BPF_JEQ | BPF_K: case BPF_JMP | BPF_JNE | BPF_K: case BPF_JMP | BPF_JGT | BPF_K: case BPF_JMP | BPF_JGE | BPF_K: case BPF_JMP | BPF_JSGT | BPF_K: case BPF_JMP | BPF_JSGE | BPF_K: /* cmp dst_reg, imm8/32 */ EMIT1(add_1mod(0x48, dst_reg)); if (is_imm8(imm32)) EMIT3(0x83, add_1reg(0xF8, dst_reg), imm32); else EMIT2_off32(0x81, add_1reg(0xF8, dst_reg), imm32); emit_cond_jmp: /* convert BPF opcode to x86 */ switch (BPF_OP(insn->code)) { case BPF_JEQ: jmp_cond = X86_JE; break; case BPF_JSET: case BPF_JNE: jmp_cond = X86_JNE; break; case BPF_JGT: /* GT is unsigned '>', JA in x86 */ jmp_cond = X86_JA; break; case BPF_JGE: /* GE is unsigned '>=', JAE in x86 */ jmp_cond = X86_JAE; break; case BPF_JSGT: /* signed '>', GT in x86 */ jmp_cond = X86_JG; break; case BPF_JSGE: /* signed '>=', GE in x86 */ jmp_cond = X86_JGE; break; default: /* to silence gcc warning */ return -EFAULT; } jmp_offset = addrs[i + insn->off] - addrs[i]; if (is_imm8(jmp_offset)) { EMIT2(jmp_cond, jmp_offset); } else if (is_simm32(jmp_offset)) { EMIT2_off32(0x0F, jmp_cond + 0x10, jmp_offset); } else { pr_err("cond_jmp gen bug %llx\n", jmp_offset); return -EFAULT; } break; case BPF_JMP | BPF_JA: jmp_offset = addrs[i + insn->off] - addrs[i]; if (!jmp_offset) /* optimize out nop jumps */ break; emit_jmp: if (is_imm8(jmp_offset)) { EMIT2(0xEB, jmp_offset); } else if (is_simm32(jmp_offset)) { EMIT1_off32(0xE9, jmp_offset); } else { pr_err("jmp gen bug %llx\n", jmp_offset); return -EFAULT; } break; case BPF_LD | BPF_IND | BPF_W: func = sk_load_word; goto common_load; case BPF_LD | BPF_ABS | BPF_W: func = CHOOSE_LOAD_FUNC(imm32, sk_load_word); common_load: ctx->seen_ld_abs = seen_ld_abs = true; jmp_offset = func - (image + addrs[i]); if (!func || !is_simm32(jmp_offset)) { pr_err("unsupported bpf func %d addr %p image %p\n", imm32, func, image); return -EINVAL; } if (BPF_MODE(insn->code) == BPF_ABS) { /* mov %esi, imm32 */ EMIT1_off32(0xBE, imm32); } else { /* mov %rsi, src_reg */ EMIT_mov(BPF_REG_2, src_reg); if (imm32) { if (is_imm8(imm32)) /* add %esi, imm8 */ EMIT3(0x83, 0xC6, imm32); else /* add %esi, imm32 */ EMIT2_off32(0x81, 0xC6, imm32); } } /* skb pointer is in R6 (%rbx), it will be copied into * %rdi if skb_copy_bits() call is necessary. * sk_load_* helpers also use %r10 and %r9d. * See bpf_jit.S */ EMIT1_off32(0xE8, jmp_offset); /* call */ break; case BPF_LD | BPF_IND | BPF_H: func = sk_load_half; goto common_load; case BPF_LD | BPF_ABS | BPF_H: func = CHOOSE_LOAD_FUNC(imm32, sk_load_half); goto common_load; case BPF_LD | BPF_IND | BPF_B: func = sk_load_byte; goto common_load; case BPF_LD | BPF_ABS | BPF_B: func = CHOOSE_LOAD_FUNC(imm32, sk_load_byte); goto common_load; case BPF_JMP | BPF_EXIT: if (seen_exit) { jmp_offset = ctx->cleanup_addr - addrs[i]; goto emit_jmp; } seen_exit = true; /* update cleanup_addr */ ctx->cleanup_addr = proglen; /* mov rbx, qword ptr [rbp-X] */ EMIT3_off32(0x48, 0x8B, 0x9D, -stacksize); /* mov r13, qword ptr [rbp-X] */ EMIT3_off32(0x4C, 0x8B, 0xAD, -stacksize + 8); /* mov r14, qword ptr [rbp-X] */ EMIT3_off32(0x4C, 0x8B, 0xB5, -stacksize + 16); /* mov r15, qword ptr [rbp-X] */ EMIT3_off32(0x4C, 0x8B, 0xBD, -stacksize + 24); EMIT1(0xC9); /* leave */ EMIT1(0xC3); /* ret */ break; default: /* By design x64 JIT should support all BPF instructions * This error will be seen if new instruction was added * to interpreter, but not to JIT * or if there is junk in bpf_prog */ pr_err("bpf_jit: unknown opcode %02x\n", insn->code); return -EINVAL; } ilen = prog - temp; if (ilen > BPF_MAX_INSN_SIZE) { pr_err("bpf_jit_compile fatal insn size error\n"); return -EFAULT; } if (image) { if (unlikely(proglen + ilen > oldproglen)) { pr_err("bpf_jit_compile fatal error\n"); return -EFAULT; } memcpy(image + proglen, temp, ilen); } proglen += ilen; addrs[i] = proglen; prog = temp; } return proglen; } void bpf_jit_compile(struct bpf_prog *prog) { } void bpf_int_jit_compile(struct bpf_prog *prog) { struct bpf_binary_header *header = NULL; int proglen, oldproglen = 0; struct jit_context ctx = {}; u8 *image = NULL; int *addrs; int pass; int i; if (!bpf_jit_enable) return; if (!prog || !prog->len) return; addrs = kmalloc(prog->len * sizeof(*addrs), GFP_KERNEL); if (!addrs) return; /* Before first pass, make a rough estimation of addrs[] * each bpf instruction is translated to less than 64 bytes */ for (proglen = 0, i = 0; i < prog->len; i++) { proglen += 64; addrs[i] = proglen; } ctx.cleanup_addr = proglen; /* JITed image shrinks with every pass and the loop iterates * until the image stops shrinking. Very large bpf programs * may converge on the last pass. In such case do one more * pass to emit the final image */ for (pass = 0; pass < 10 || image; pass++) { proglen = do_jit(prog, addrs, image, oldproglen, &ctx); if (proglen <= 0) { image = NULL; if (header) bpf_jit_binary_free(header); goto out; } if (image) { if (proglen != oldproglen) { pr_err("bpf_jit: proglen=%d != oldproglen=%d\n", proglen, oldproglen); goto out; } break; } if (proglen == oldproglen) { header = bpf_jit_binary_alloc(proglen, &image, 1, jit_fill_hole); if (!header) goto out; } oldproglen = proglen; } if (bpf_jit_enable > 1) bpf_jit_dump(prog->len, proglen, 0, image); if (image) { bpf_flush_icache(header, image + proglen); set_memory_ro((unsigned long)header, header->pages); prog->bpf_func = (void *)image; prog->jited = true; } out: kfree(addrs); } void bpf_jit_free(struct bpf_prog *fp) { unsigned long addr = (unsigned long)fp->bpf_func & PAGE_MASK; struct bpf_binary_header *header = (void *)addr; if (!fp->jited) goto free_filter; set_memory_rw(addr, header->pages); bpf_jit_binary_free(header); free_filter: bpf_prog_unlock_free(fp); }
./CrossVul/dataset_final_sorted/CWE-17/c/good_1643_0
crossvul-cpp_data_bad_1470_0
/* * lxc: linux Container library * * (C) Copyright IBM Corp. 2007, 2008 * * Authors: * Daniel Lezcano <daniel.lezcano at free.fr> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #define _GNU_SOURCE #include <unistd.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <signal.h> #include <errno.h> #include <fcntl.h> #include <grp.h> #include <sys/param.h> #include <sys/prctl.h> #include <sys/mount.h> #include <sys/socket.h> #include <sys/syscall.h> #include <sys/wait.h> #include <linux/unistd.h> #include <pwd.h> #if !HAVE_DECL_PR_CAPBSET_DROP #define PR_CAPBSET_DROP 24 #endif #include "namespace.h" #include "log.h" #include "attach.h" #include "caps.h" #include "config.h" #include "utils.h" #include "commands.h" #include "cgroup.h" #include "lxclock.h" #include "conf.h" #include "lxcseccomp.h" #include <lxc/lxccontainer.h> #include "lsm/lsm.h" #include "confile.h" #if HAVE_SYS_PERSONALITY_H #include <sys/personality.h> #endif #ifndef SOCK_CLOEXEC # define SOCK_CLOEXEC 02000000 #endif #ifndef MS_REC #define MS_REC 16384 #endif #ifndef MS_SLAVE #define MS_SLAVE (1<<19) #endif lxc_log_define(lxc_attach, lxc); static struct lxc_proc_context_info *lxc_proc_get_context_info(pid_t pid) { struct lxc_proc_context_info *info = calloc(1, sizeof(*info)); FILE *proc_file; char proc_fn[MAXPATHLEN]; char *line = NULL; size_t line_bufsz = 0; int ret, found; if (!info) { SYSERROR("Could not allocate memory."); return NULL; } /* read capabilities */ snprintf(proc_fn, MAXPATHLEN, "/proc/%d/status", pid); proc_file = fopen(proc_fn, "r"); if (!proc_file) { SYSERROR("Could not open %s", proc_fn); goto out_error; } found = 0; while (getline(&line, &line_bufsz, proc_file) != -1) { ret = sscanf(line, "CapBnd: %llx", &info->capability_mask); if (ret != EOF && ret > 0) { found = 1; break; } } free(line); fclose(proc_file); if (!found) { SYSERROR("Could not read capability bounding set from %s", proc_fn); errno = ENOENT; goto out_error; } info->lsm_label = lsm_process_label_get(pid); return info; out_error: free(info); return NULL; } static void lxc_proc_put_context_info(struct lxc_proc_context_info *ctx) { free(ctx->lsm_label); if (ctx->container) lxc_container_put(ctx->container); free(ctx); } static int lxc_attach_to_ns(pid_t pid, int which) { char path[MAXPATHLEN]; /* according to <http://article.gmane.org/gmane.linux.kernel.containers.lxc.devel/1429>, * the file for user namepsaces in /proc/$pid/ns will be called * 'user' once the kernel supports it */ static char *ns[] = { "user", "mnt", "pid", "uts", "ipc", "net" }; static int flags[] = { CLONE_NEWUSER, CLONE_NEWNS, CLONE_NEWPID, CLONE_NEWUTS, CLONE_NEWIPC, CLONE_NEWNET }; static const int size = sizeof(ns) / sizeof(char *); int fd[size]; int i, j, saved_errno; snprintf(path, MAXPATHLEN, "/proc/%d/ns", pid); if (access(path, X_OK)) { ERROR("Does this kernel version support 'attach' ?"); return -1; } for (i = 0; i < size; i++) { /* ignore if we are not supposed to attach to that * namespace */ if (which != -1 && !(which & flags[i])) { fd[i] = -1; continue; } snprintf(path, MAXPATHLEN, "/proc/%d/ns/%s", pid, ns[i]); fd[i] = open(path, O_RDONLY | O_CLOEXEC); if (fd[i] < 0) { saved_errno = errno; /* close all already opened file descriptors before * we return an error, so we don't leak them */ for (j = 0; j < i; j++) close(fd[j]); errno = saved_errno; SYSERROR("failed to open '%s'", path); return -1; } } for (i = 0; i < size; i++) { if (fd[i] >= 0 && setns(fd[i], 0) != 0) { saved_errno = errno; for (j = i; j < size; j++) close(fd[j]); errno = saved_errno; SYSERROR("failed to set namespace '%s'", ns[i]); return -1; } close(fd[i]); } return 0; } static int lxc_attach_remount_sys_proc(void) { int ret; ret = unshare(CLONE_NEWNS); if (ret < 0) { SYSERROR("failed to unshare mount namespace"); return -1; } if (detect_shared_rootfs()) { if (mount(NULL, "/", NULL, MS_SLAVE|MS_REC, NULL)) { SYSERROR("Failed to make / rslave"); ERROR("Continuing..."); } } /* assume /proc is always mounted, so remount it */ ret = umount2("/proc", MNT_DETACH); if (ret < 0) { SYSERROR("failed to unmount /proc"); return -1; } ret = mount("none", "/proc", "proc", 0, NULL); if (ret < 0) { SYSERROR("failed to remount /proc"); return -1; } /* try to umount /sys - if it's not a mount point, * we'll get EINVAL, then we ignore it because it * may not have been mounted in the first place */ ret = umount2("/sys", MNT_DETACH); if (ret < 0 && errno != EINVAL) { SYSERROR("failed to unmount /sys"); return -1; } else if (ret == 0) { /* remount it */ ret = mount("none", "/sys", "sysfs", 0, NULL); if (ret < 0) { SYSERROR("failed to remount /sys"); return -1; } } return 0; } static int lxc_attach_drop_privs(struct lxc_proc_context_info *ctx) { int last_cap = lxc_caps_last_cap(); int cap; for (cap = 0; cap <= last_cap; cap++) { if (ctx->capability_mask & (1LL << cap)) continue; if (prctl(PR_CAPBSET_DROP, cap, 0, 0, 0)) { SYSERROR("failed to remove capability id %d", cap); return -1; } } return 0; } static int lxc_attach_set_environment(enum lxc_attach_env_policy_t policy, char** extra_env, char** extra_keep) { if (policy == LXC_ATTACH_CLEAR_ENV) { char **extra_keep_store = NULL; int path_kept = 0; if (extra_keep) { size_t count, i; for (count = 0; extra_keep[count]; count++); extra_keep_store = calloc(count, sizeof(char *)); if (!extra_keep_store) { SYSERROR("failed to allocate memory for storing current " "environment variable values that will be kept"); return -1; } for (i = 0; i < count; i++) { char *v = getenv(extra_keep[i]); if (v) { extra_keep_store[i] = strdup(v); if (!extra_keep_store[i]) { SYSERROR("failed to allocate memory for storing current " "environment variable values that will be kept"); while (i > 0) free(extra_keep_store[--i]); free(extra_keep_store); return -1; } if (strcmp(extra_keep[i], "PATH") == 0) path_kept = 1; } /* calloc sets entire array to zero, so we don't * need an else */ } } if (clearenv()) { char **p; SYSERROR("failed to clear environment"); if (extra_keep_store) { for (p = extra_keep_store; *p; p++) free(*p); free(extra_keep_store); } return -1; } if (extra_keep_store) { size_t i; for (i = 0; extra_keep[i]; i++) { if (extra_keep_store[i]) { if (setenv(extra_keep[i], extra_keep_store[i], 1) < 0) SYSERROR("Unable to set environment variable"); } free(extra_keep_store[i]); } free(extra_keep_store); } /* always set a default path; shells and execlp tend * to be fine without it, but there is a disturbing * number of C programs out there that just assume * that getenv("PATH") is never NULL and then die a * painful segfault death. */ if (!path_kept) setenv("PATH", "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", 1); } if (putenv("container=lxc")) { SYSERROR("failed to set environment variable"); return -1; } /* set extra environment variables */ if (extra_env) { for (; *extra_env; extra_env++) { /* duplicate the string, just to be on * the safe side, because putenv does not * do it for us */ char *p = strdup(*extra_env); /* we just assume the user knows what they * are doing, so we don't do any checks */ if (!p) { SYSERROR("failed to allocate memory for additional environment " "variables"); return -1; } putenv(p); } } return 0; } static char *lxc_attach_getpwshell(uid_t uid) { /* local variables */ pid_t pid; int pipes[2]; int ret; int fd; char *result = NULL; /* we need to fork off a process that runs the * getent program, and we need to capture its * output, so we use a pipe for that purpose */ ret = pipe(pipes); if (ret < 0) return NULL; pid = fork(); if (pid < 0) { close(pipes[0]); close(pipes[1]); return NULL; } if (pid) { /* parent process */ FILE *pipe_f; char *line = NULL; size_t line_bufsz = 0; int found = 0; int status; close(pipes[1]); pipe_f = fdopen(pipes[0], "r"); while (getline(&line, &line_bufsz, pipe_f) != -1) { char *token; char *saveptr = NULL; long value; char *endptr = NULL; int i; /* if we already found something, just continue * to read until the pipe doesn't deliver any more * data, but don't modify the existing data * structure */ if (found) continue; /* trim line on the right hand side */ for (i = strlen(line); i > 0 && (line[i - 1] == '\n' || line[i - 1] == '\r'); --i) line[i - 1] = '\0'; /* split into tokens: first user name */ token = strtok_r(line, ":", &saveptr); if (!token) continue; /* next: dummy password field */ token = strtok_r(NULL, ":", &saveptr); if (!token) continue; /* next: user id */ token = strtok_r(NULL, ":", &saveptr); value = token ? strtol(token, &endptr, 10) : 0; if (!token || !endptr || *endptr || value == LONG_MIN || value == LONG_MAX) continue; /* dummy sanity check: user id matches */ if ((uid_t) value != uid) continue; /* skip fields: gid, gecos, dir, go to next field 'shell' */ for (i = 0; i < 4; i++) { token = strtok_r(NULL, ":", &saveptr); if (!token) break; } if (!token) continue; free(result); result = strdup(token); /* sanity check that there are no fields after that */ token = strtok_r(NULL, ":", &saveptr); if (token) continue; found = 1; } free(line); fclose(pipe_f); again: if (waitpid(pid, &status, 0) < 0) { if (errno == EINTR) goto again; return NULL; } /* some sanity checks: if anything even hinted at going * wrong: we can't be sure we have a valid result, so * we assume we don't */ if (!WIFEXITED(status)) return NULL; if (WEXITSTATUS(status) != 0) return NULL; if (!found) return NULL; return result; } else { /* child process */ char uid_buf[32]; char *arguments[] = { "getent", "passwd", uid_buf, NULL }; close(pipes[0]); /* we want to capture stdout */ dup2(pipes[1], 1); close(pipes[1]); /* get rid of stdin/stderr, so we try to associate it * with /dev/null */ fd = open("/dev/null", O_RDWR); if (fd < 0) { close(0); close(2); } else { dup2(fd, 0); dup2(fd, 2); close(fd); } /* finish argument list */ ret = snprintf(uid_buf, sizeof(uid_buf), "%ld", (long) uid); if (ret <= 0) exit(-1); /* try to run getent program */ (void) execvp("getent", arguments); exit(-1); } } static void lxc_attach_get_init_uidgid(uid_t* init_uid, gid_t* init_gid) { FILE *proc_file; char proc_fn[MAXPATHLEN]; char *line = NULL; size_t line_bufsz = 0; int ret; long value = -1; uid_t uid = (uid_t)-1; gid_t gid = (gid_t)-1; /* read capabilities */ snprintf(proc_fn, MAXPATHLEN, "/proc/%d/status", 1); proc_file = fopen(proc_fn, "r"); if (!proc_file) return; while (getline(&line, &line_bufsz, proc_file) != -1) { /* format is: real, effective, saved set user, fs * we only care about real uid */ ret = sscanf(line, "Uid: %ld", &value); if (ret != EOF && ret > 0) { uid = (uid_t) value; } else { ret = sscanf(line, "Gid: %ld", &value); if (ret != EOF && ret > 0) gid = (gid_t) value; } if (uid != (uid_t)-1 && gid != (gid_t)-1) break; } fclose(proc_file); free(line); /* only override arguments if we found something */ if (uid != (uid_t)-1) *init_uid = uid; if (gid != (gid_t)-1) *init_gid = gid; /* TODO: we should also parse supplementary groups and use * setgroups() to set them */ } struct attach_clone_payload { int ipc_socket; lxc_attach_options_t* options; struct lxc_proc_context_info* init_ctx; lxc_attach_exec_t exec_function; void* exec_payload; }; static int attach_child_main(void* data); /* help the optimizer along if it doesn't know that exit always exits */ #define rexit(c) do { int __c = (c); _exit(__c); return __c; } while(0) /* define default options if no options are supplied by the user */ static lxc_attach_options_t attach_static_default_options = LXC_ATTACH_OPTIONS_DEFAULT; static bool fetch_seccomp(const char *name, const char *lxcpath, struct lxc_proc_context_info *i, lxc_attach_options_t *options) { struct lxc_container *c; if (!(options->namespaces & CLONE_NEWNS) || !(options->attach_flags & LXC_ATTACH_LSM)) return true; c = lxc_container_new(name, lxcpath); if (!c) return false; i->container = c; if (!c->lxc_conf) return false; if (lxc_read_seccomp_config(c->lxc_conf) < 0) { ERROR("Error reading seccomp policy"); return false; } return true; } static signed long get_personality(const char *name, const char *lxcpath) { char *p = lxc_cmd_get_config_item(name, "lxc.arch", lxcpath); signed long ret; if (!p) return -1; ret = lxc_config_parse_arch(p); free(p); return ret; } int lxc_attach(const char* name, const char* lxcpath, lxc_attach_exec_t exec_function, void* exec_payload, lxc_attach_options_t* options, pid_t* attached_process) { int ret, status; pid_t init_pid, pid, attached_pid, expected; struct lxc_proc_context_info *init_ctx; char* cwd; char* new_cwd; int ipc_sockets[2]; signed long personality; if (!options) options = &attach_static_default_options; init_pid = lxc_cmd_get_init_pid(name, lxcpath); if (init_pid < 0) { ERROR("failed to get the init pid"); return -1; } init_ctx = lxc_proc_get_context_info(init_pid); if (!init_ctx) { ERROR("failed to get context of the init process, pid = %ld", (long)init_pid); return -1; } personality = get_personality(name, lxcpath); if (init_ctx->personality < 0) { ERROR("Failed to get personality of the container"); lxc_proc_put_context_info(init_ctx); return -1; } init_ctx->personality = personality; if (!fetch_seccomp(name, lxcpath, init_ctx, options)) WARN("Failed to get seccomp policy"); cwd = getcwd(NULL, 0); /* determine which namespaces the container was created with * by asking lxc-start, if necessary */ if (options->namespaces == -1) { options->namespaces = lxc_cmd_get_clone_flags(name, lxcpath); /* call failed */ if (options->namespaces == -1) { ERROR("failed to automatically determine the " "namespaces which the container unshared"); free(cwd); lxc_proc_put_context_info(init_ctx); return -1; } } /* create a socket pair for IPC communication; set SOCK_CLOEXEC in order * to make sure we don't irritate other threads that want to fork+exec away * * IMPORTANT: if the initial process is multithreaded and another call * just fork()s away without exec'ing directly after, the socket fd will * exist in the forked process from the other thread and any close() in * our own child process will not really cause the socket to close properly, * potentiall causing the parent to hang. * * For this reason, while IPC is still active, we have to use shutdown() * if the child exits prematurely in order to signal that the socket * is closed and cannot assume that the child exiting will automatically * do that. * * IPC mechanism: (X is receiver) * initial process intermediate attached * X <--- send pid of * attached proc, * then exit * send 0 ------------------------------------> X * [do initialization] * X <------------------------------------ send 1 * [add to cgroup, ...] * send 2 ------------------------------------> X * close socket close socket * run program */ ret = socketpair(PF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0, ipc_sockets); if (ret < 0) { SYSERROR("could not set up required IPC mechanism for attaching"); free(cwd); lxc_proc_put_context_info(init_ctx); return -1; } /* create intermediate subprocess, three reasons: * 1. runs all pthread_atfork handlers and the * child will no longer be threaded * (we can't properly setns() in a threaded process) * 2. we can't setns() in the child itself, since * we want to make sure we are properly attached to * the pidns * 3. also, the initial thread has to put the attached * process into the cgroup, which we can only do if * we didn't already setns() (otherwise, user * namespaces will hate us) */ pid = fork(); if (pid < 0) { SYSERROR("failed to create first subprocess"); free(cwd); lxc_proc_put_context_info(init_ctx); return -1; } if (pid) { pid_t to_cleanup_pid = pid; /* initial thread, we close the socket that is for the * subprocesses */ close(ipc_sockets[1]); free(cwd); /* attach to cgroup, if requested */ if (options->attach_flags & LXC_ATTACH_MOVE_TO_CGROUP) { if (!cgroup_attach(name, lxcpath, pid)) goto cleanup_error; } /* Let the child process know to go ahead */ status = 0; ret = lxc_write_nointr(ipc_sockets[0], &status, sizeof(status)); if (ret <= 0) { ERROR("error using IPC to notify attached process for initialization (0)"); goto cleanup_error; } /* get pid from intermediate process */ ret = lxc_read_nointr_expect(ipc_sockets[0], &attached_pid, sizeof(attached_pid), NULL); if (ret <= 0) { if (ret != 0) ERROR("error using IPC to receive pid of attached process"); goto cleanup_error; } /* ignore SIGKILL (CTRL-C) and SIGQUIT (CTRL-\) - issue #313 */ if (options->stdin_fd == 0) { signal(SIGINT, SIG_IGN); signal(SIGQUIT, SIG_IGN); } /* reap intermediate process */ ret = wait_for_pid(pid); if (ret < 0) goto cleanup_error; /* we will always have to reap the grandchild now */ to_cleanup_pid = attached_pid; /* tell attached process it may start initializing */ status = 0; ret = lxc_write_nointr(ipc_sockets[0], &status, sizeof(status)); if (ret <= 0) { ERROR("error using IPC to notify attached process for initialization (0)"); goto cleanup_error; } /* wait for the attached process to finish initializing */ expected = 1; ret = lxc_read_nointr_expect(ipc_sockets[0], &status, sizeof(status), &expected); if (ret <= 0) { if (ret != 0) ERROR("error using IPC to receive notification from attached process (1)"); goto cleanup_error; } /* tell attached process we're done */ status = 2; ret = lxc_write_nointr(ipc_sockets[0], &status, sizeof(status)); if (ret <= 0) { ERROR("error using IPC to notify attached process for initialization (2)"); goto cleanup_error; } /* now shut down communication with child, we're done */ shutdown(ipc_sockets[0], SHUT_RDWR); close(ipc_sockets[0]); lxc_proc_put_context_info(init_ctx); /* we're done, the child process should now execute whatever * it is that the user requested. The parent can now track it * with waitpid() or similar. */ *attached_process = attached_pid; return 0; cleanup_error: /* first shut down the socket, then wait for the pid, * otherwise the pid we're waiting for may never exit */ shutdown(ipc_sockets[0], SHUT_RDWR); close(ipc_sockets[0]); if (to_cleanup_pid) (void) wait_for_pid(to_cleanup_pid); lxc_proc_put_context_info(init_ctx); return -1; } /* first subprocess begins here, we close the socket that is for the * initial thread */ close(ipc_sockets[0]); /* Wait for the parent to have setup cgroups */ expected = 0; status = -1; ret = lxc_read_nointr_expect(ipc_sockets[1], &status, sizeof(status), &expected); if (ret <= 0) { ERROR("error communicating with child process"); shutdown(ipc_sockets[1], SHUT_RDWR); rexit(-1); } /* attach now, create another subprocess later, since pid namespaces * only really affect the children of the current process */ ret = lxc_attach_to_ns(init_pid, options->namespaces); if (ret < 0) { ERROR("failed to enter the namespace"); shutdown(ipc_sockets[1], SHUT_RDWR); rexit(-1); } /* attach succeeded, try to cwd */ if (options->initial_cwd) new_cwd = options->initial_cwd; else new_cwd = cwd; ret = chdir(new_cwd); if (ret < 0) WARN("could not change directory to '%s'", new_cwd); free(cwd); /* now create the real child process */ { struct attach_clone_payload payload = { .ipc_socket = ipc_sockets[1], .options = options, .init_ctx = init_ctx, .exec_function = exec_function, .exec_payload = exec_payload }; /* We use clone_parent here to make this subprocess a direct child of * the initial process. Then this intermediate process can exit and * the parent can directly track the attached process. */ pid = lxc_clone(attach_child_main, &payload, CLONE_PARENT); } /* shouldn't happen, clone() should always return positive pid */ if (pid <= 0) { SYSERROR("failed to create subprocess"); shutdown(ipc_sockets[1], SHUT_RDWR); rexit(-1); } /* tell grandparent the pid of the pid of the newly created child */ ret = lxc_write_nointr(ipc_sockets[1], &pid, sizeof(pid)); if (ret != sizeof(pid)) { /* if this really happens here, this is very unfortunate, since the * parent will not know the pid of the attached process and will * not be able to wait for it (and we won't either due to CLONE_PARENT) * so the parent won't be able to reap it and the attached process * will remain a zombie */ ERROR("error using IPC to notify main process of pid of the attached process"); shutdown(ipc_sockets[1], SHUT_RDWR); rexit(-1); } /* the rest is in the hands of the initial and the attached process */ rexit(0); } static int attach_child_main(void* data) { struct attach_clone_payload* payload = (struct attach_clone_payload*)data; int ipc_socket = payload->ipc_socket; lxc_attach_options_t* options = payload->options; struct lxc_proc_context_info* init_ctx = payload->init_ctx; #if HAVE_SYS_PERSONALITY_H long new_personality; #endif int ret; int status; int expected; long flags; int fd; uid_t new_uid; gid_t new_gid; /* wait for the initial thread to signal us that it's ready * for us to start initializing */ expected = 0; status = -1; ret = lxc_read_nointr_expect(ipc_socket, &status, sizeof(status), &expected); if (ret <= 0) { ERROR("error using IPC to receive notification from initial process (0)"); shutdown(ipc_socket, SHUT_RDWR); rexit(-1); } /* A description of the purpose of this functionality is * provided in the lxc-attach(1) manual page. We have to * remount here and not in the parent process, otherwise * /proc may not properly reflect the new pid namespace. */ if (!(options->namespaces & CLONE_NEWNS) && (options->attach_flags & LXC_ATTACH_REMOUNT_PROC_SYS)) { ret = lxc_attach_remount_sys_proc(); if (ret < 0) { shutdown(ipc_socket, SHUT_RDWR); rexit(-1); } } /* now perform additional attachments*/ #if HAVE_SYS_PERSONALITY_H if (options->personality < 0) new_personality = init_ctx->personality; else new_personality = options->personality; if (options->attach_flags & LXC_ATTACH_SET_PERSONALITY) { ret = personality(new_personality); if (ret < 0) { SYSERROR("could not ensure correct architecture"); shutdown(ipc_socket, SHUT_RDWR); rexit(-1); } } #endif if (options->attach_flags & LXC_ATTACH_DROP_CAPABILITIES) { ret = lxc_attach_drop_privs(init_ctx); if (ret < 0) { ERROR("could not drop privileges"); shutdown(ipc_socket, SHUT_RDWR); rexit(-1); } } /* always set the environment (specify (LXC_ATTACH_KEEP_ENV, NULL, NULL) if you want this to be a no-op) */ ret = lxc_attach_set_environment(options->env_policy, options->extra_env_vars, options->extra_keep_env); if (ret < 0) { ERROR("could not set initial environment for attached process"); shutdown(ipc_socket, SHUT_RDWR); rexit(-1); } /* set user / group id */ new_uid = 0; new_gid = 0; /* ignore errors, we will fall back to root in that case * (/proc was not mounted etc.) */ if (options->namespaces & CLONE_NEWUSER) lxc_attach_get_init_uidgid(&new_uid, &new_gid); if (options->uid != (uid_t)-1) new_uid = options->uid; if (options->gid != (gid_t)-1) new_gid = options->gid; /* setup the control tty */ if (options->stdin_fd && isatty(options->stdin_fd)) { if (setsid() < 0) { SYSERROR("unable to setsid"); shutdown(ipc_socket, SHUT_RDWR); rexit(-1); } if (ioctl(options->stdin_fd, TIOCSCTTY, (char *)NULL) < 0) { SYSERROR("unable to TIOCSTTY"); shutdown(ipc_socket, SHUT_RDWR); rexit(-1); } } /* try to set the uid/gid combination */ if ((new_gid != 0 || options->namespaces & CLONE_NEWUSER)) { if (setgid(new_gid) || setgroups(0, NULL)) { SYSERROR("switching to container gid"); shutdown(ipc_socket, SHUT_RDWR); rexit(-1); } } if ((new_uid != 0 || options->namespaces & CLONE_NEWUSER) && setuid(new_uid)) { SYSERROR("switching to container uid"); shutdown(ipc_socket, SHUT_RDWR); rexit(-1); } /* tell initial process it may now put us into the cgroups */ status = 1; ret = lxc_write_nointr(ipc_socket, &status, sizeof(status)); if (ret != sizeof(status)) { ERROR("error using IPC to notify initial process for initialization (1)"); shutdown(ipc_socket, SHUT_RDWR); rexit(-1); } /* wait for the initial thread to signal us that it has done * everything for us when it comes to cgroups etc. */ expected = 2; status = -1; ret = lxc_read_nointr_expect(ipc_socket, &status, sizeof(status), &expected); if (ret <= 0) { ERROR("error using IPC to receive final notification from initial process (2)"); shutdown(ipc_socket, SHUT_RDWR); rexit(-1); } shutdown(ipc_socket, SHUT_RDWR); close(ipc_socket); /* set new apparmor profile/selinux context */ if ((options->namespaces & CLONE_NEWNS) && (options->attach_flags & LXC_ATTACH_LSM)) { int on_exec; int proc_mounted; on_exec = options->attach_flags & LXC_ATTACH_LSM_EXEC ? 1 : 0; proc_mounted = mount_proc_if_needed("/"); if (proc_mounted == -1) { ERROR("Error mounting a sane /proc"); rexit(-1); } ret = lsm_process_label_set(init_ctx->lsm_label, init_ctx->container->lxc_conf, 0, on_exec); if (proc_mounted) umount("/proc"); if (ret < 0) { rexit(-1); } } if (init_ctx->container && init_ctx->container->lxc_conf && lxc_seccomp_load(init_ctx->container->lxc_conf) != 0) { ERROR("Loading seccomp policy"); rexit(-1); } lxc_proc_put_context_info(init_ctx); /* The following is done after the communication socket is * shut down. That way, all errors that might (though * unlikely) occur up until this point will have their messages * printed to the original stderr (if logging is so configured) * and not the fd the user supplied, if any. */ /* fd handling for stdin, stdout and stderr; * ignore errors here, user may want to make sure * the fds are closed, for example */ if (options->stdin_fd >= 0 && options->stdin_fd != 0) dup2(options->stdin_fd, 0); if (options->stdout_fd >= 0 && options->stdout_fd != 1) dup2(options->stdout_fd, 1); if (options->stderr_fd >= 0 && options->stderr_fd != 2) dup2(options->stderr_fd, 2); /* close the old fds */ if (options->stdin_fd > 2) close(options->stdin_fd); if (options->stdout_fd > 2) close(options->stdout_fd); if (options->stderr_fd > 2) close(options->stderr_fd); /* try to remove CLOEXEC flag from stdin/stdout/stderr, * but also here, ignore errors */ for (fd = 0; fd <= 2; fd++) { flags = fcntl(fd, F_GETFL); if (flags < 0) continue; if (flags & FD_CLOEXEC) { if (fcntl(fd, F_SETFL, flags & ~FD_CLOEXEC) < 0) { SYSERROR("Unable to clear CLOEXEC from fd"); } } } /* we're done, so we can now do whatever the user intended us to do */ rexit(payload->exec_function(payload->exec_payload)); } int lxc_attach_run_command(void* payload) { lxc_attach_command_t* cmd = (lxc_attach_command_t*)payload; execvp(cmd->program, cmd->argv); SYSERROR("failed to exec '%s'", cmd->program); return -1; } int lxc_attach_run_shell(void* payload) { uid_t uid; struct passwd *passwd; char *user_shell; /* ignore payload parameter */ (void)payload; uid = getuid(); passwd = getpwuid(uid); /* this probably happens because of incompatible nss * implementations in host and container (remember, this * code is still using the host's glibc but our mount * namespace is in the container) * we may try to get the information by spawning a * [getent passwd uid] process and parsing the result */ if (!passwd) user_shell = lxc_attach_getpwshell(uid); else user_shell = passwd->pw_shell; if (user_shell) execlp(user_shell, user_shell, NULL); /* executed if either no passwd entry or execvp fails, * we will fall back on /bin/sh as a default shell */ execlp("/bin/sh", "/bin/sh", NULL); SYSERROR("failed to exec shell"); return -1; }
./CrossVul/dataset_final_sorted/CWE-17/c/bad_1470_0
crossvul-cpp_data_good_2306_3
/* * linux/fs/super.c * * Copyright (C) 1991, 1992 Linus Torvalds * * super.c contains code to handle: - mount structures * - super-block tables * - filesystem drivers list * - mount system call * - umount system call * - ustat system call * * GK 2/5/95 - Changed to support mounting the root fs via NFS * * Added kerneld support: Jacques Gelinas and Bjorn Ekwall * Added change_root: Werner Almesberger & Hans Lermen, Feb '96 * Added options to /proc/mounts: * Torbjörn Lindh (torbjorn.lindh@gopta.se), April 14, 1996. * Added devfs support: Richard Gooch <rgooch@atnf.csiro.au>, 13-JAN-1998 * Heavily rewritten for 'one fs - one tree' dcache architecture. AV, Mar 2000 */ #include <linux/export.h> #include <linux/slab.h> #include <linux/acct.h> #include <linux/blkdev.h> #include <linux/mount.h> #include <linux/security.h> #include <linux/writeback.h> /* for the emergency remount stuff */ #include <linux/idr.h> #include <linux/mutex.h> #include <linux/backing-dev.h> #include <linux/rculist_bl.h> #include <linux/cleancache.h> #include <linux/fsnotify.h> #include <linux/lockdep.h> #include "internal.h" LIST_HEAD(super_blocks); DEFINE_SPINLOCK(sb_lock); static char *sb_writers_name[SB_FREEZE_LEVELS] = { "sb_writers", "sb_pagefaults", "sb_internal", }; /* * One thing we have to be careful of with a per-sb shrinker is that we don't * drop the last active reference to the superblock from within the shrinker. * If that happens we could trigger unregistering the shrinker from within the * shrinker path and that leads to deadlock on the shrinker_rwsem. Hence we * take a passive reference to the superblock to avoid this from occurring. */ static unsigned long super_cache_scan(struct shrinker *shrink, struct shrink_control *sc) { struct super_block *sb; long fs_objects = 0; long total_objects; long freed = 0; long dentries; long inodes; sb = container_of(shrink, struct super_block, s_shrink); /* * Deadlock avoidance. We may hold various FS locks, and we don't want * to recurse into the FS that called us in clear_inode() and friends.. */ if (!(sc->gfp_mask & __GFP_FS)) return SHRINK_STOP; if (!grab_super_passive(sb)) return SHRINK_STOP; if (sb->s_op->nr_cached_objects) fs_objects = sb->s_op->nr_cached_objects(sb, sc->nid); inodes = list_lru_count_node(&sb->s_inode_lru, sc->nid); dentries = list_lru_count_node(&sb->s_dentry_lru, sc->nid); total_objects = dentries + inodes + fs_objects + 1; /* proportion the scan between the caches */ dentries = mult_frac(sc->nr_to_scan, dentries, total_objects); inodes = mult_frac(sc->nr_to_scan, inodes, total_objects); /* * prune the dcache first as the icache is pinned by it, then * prune the icache, followed by the filesystem specific caches */ freed = prune_dcache_sb(sb, dentries, sc->nid); freed += prune_icache_sb(sb, inodes, sc->nid); if (fs_objects) { fs_objects = mult_frac(sc->nr_to_scan, fs_objects, total_objects); freed += sb->s_op->free_cached_objects(sb, fs_objects, sc->nid); } drop_super(sb); return freed; } static unsigned long super_cache_count(struct shrinker *shrink, struct shrink_control *sc) { struct super_block *sb; long total_objects = 0; sb = container_of(shrink, struct super_block, s_shrink); if (!grab_super_passive(sb)) return 0; if (sb->s_op && sb->s_op->nr_cached_objects) total_objects = sb->s_op->nr_cached_objects(sb, sc->nid); total_objects += list_lru_count_node(&sb->s_dentry_lru, sc->nid); total_objects += list_lru_count_node(&sb->s_inode_lru, sc->nid); total_objects = vfs_pressure_ratio(total_objects); drop_super(sb); return total_objects; } /** * destroy_super - frees a superblock * @s: superblock to free * * Frees a superblock. */ static void destroy_super(struct super_block *s) { int i; list_lru_destroy(&s->s_dentry_lru); list_lru_destroy(&s->s_inode_lru); for (i = 0; i < SB_FREEZE_LEVELS; i++) percpu_counter_destroy(&s->s_writers.counter[i]); security_sb_free(s); WARN_ON(!list_empty(&s->s_mounts)); kfree(s->s_subtype); kfree(s->s_options); kfree_rcu(s, rcu); } /** * alloc_super - create new superblock * @type: filesystem type superblock should belong to * @flags: the mount flags * * Allocates and initializes a new &struct super_block. alloc_super() * returns a pointer new superblock or %NULL if allocation had failed. */ static struct super_block *alloc_super(struct file_system_type *type, int flags) { struct super_block *s = kzalloc(sizeof(struct super_block), GFP_USER); static const struct super_operations default_op; int i; if (!s) return NULL; if (security_sb_alloc(s)) goto fail; for (i = 0; i < SB_FREEZE_LEVELS; i++) { if (percpu_counter_init(&s->s_writers.counter[i], 0) < 0) goto fail; lockdep_init_map(&s->s_writers.lock_map[i], sb_writers_name[i], &type->s_writers_key[i], 0); } init_waitqueue_head(&s->s_writers.wait); init_waitqueue_head(&s->s_writers.wait_unfrozen); s->s_flags = flags; s->s_bdi = &default_backing_dev_info; INIT_HLIST_NODE(&s->s_instances); INIT_HLIST_BL_HEAD(&s->s_anon); INIT_LIST_HEAD(&s->s_inodes); if (list_lru_init(&s->s_dentry_lru)) goto fail; if (list_lru_init(&s->s_inode_lru)) goto fail; INIT_LIST_HEAD(&s->s_mounts); init_rwsem(&s->s_umount); lockdep_set_class(&s->s_umount, &type->s_umount_key); /* * sget() can have s_umount recursion. * * When it cannot find a suitable sb, it allocates a new * one (this one), and tries again to find a suitable old * one. * * In case that succeeds, it will acquire the s_umount * lock of the old one. Since these are clearly distrinct * locks, and this object isn't exposed yet, there's no * risk of deadlocks. * * Annotate this by putting this lock in a different * subclass. */ down_write_nested(&s->s_umount, SINGLE_DEPTH_NESTING); s->s_count = 1; atomic_set(&s->s_active, 1); mutex_init(&s->s_vfs_rename_mutex); lockdep_set_class(&s->s_vfs_rename_mutex, &type->s_vfs_rename_key); mutex_init(&s->s_dquot.dqio_mutex); mutex_init(&s->s_dquot.dqonoff_mutex); init_rwsem(&s->s_dquot.dqptr_sem); s->s_maxbytes = MAX_NON_LFS; s->s_op = &default_op; s->s_time_gran = 1000000000; s->cleancache_poolid = -1; s->s_shrink.seeks = DEFAULT_SEEKS; s->s_shrink.scan_objects = super_cache_scan; s->s_shrink.count_objects = super_cache_count; s->s_shrink.batch = 1024; s->s_shrink.flags = SHRINKER_NUMA_AWARE; return s; fail: destroy_super(s); return NULL; } /* Superblock refcounting */ /* * Drop a superblock's refcount. The caller must hold sb_lock. */ static void __put_super(struct super_block *sb) { if (!--sb->s_count) { list_del_init(&sb->s_list); destroy_super(sb); } } /** * put_super - drop a temporary reference to superblock * @sb: superblock in question * * Drops a temporary reference, frees superblock if there's no * references left. */ static void put_super(struct super_block *sb) { spin_lock(&sb_lock); __put_super(sb); spin_unlock(&sb_lock); } /** * deactivate_locked_super - drop an active reference to superblock * @s: superblock to deactivate * * Drops an active reference to superblock, converting it into a temprory * one if there is no other active references left. In that case we * tell fs driver to shut it down and drop the temporary reference we * had just acquired. * * Caller holds exclusive lock on superblock; that lock is released. */ void deactivate_locked_super(struct super_block *s) { struct file_system_type *fs = s->s_type; if (atomic_dec_and_test(&s->s_active)) { cleancache_invalidate_fs(s); fs->kill_sb(s); /* caches are now gone, we can safely kill the shrinker now */ unregister_shrinker(&s->s_shrink); put_filesystem(fs); put_super(s); } else { up_write(&s->s_umount); } } EXPORT_SYMBOL(deactivate_locked_super); /** * deactivate_super - drop an active reference to superblock * @s: superblock to deactivate * * Variant of deactivate_locked_super(), except that superblock is *not* * locked by caller. If we are going to drop the final active reference, * lock will be acquired prior to that. */ void deactivate_super(struct super_block *s) { if (!atomic_add_unless(&s->s_active, -1, 1)) { down_write(&s->s_umount); deactivate_locked_super(s); } } EXPORT_SYMBOL(deactivate_super); /** * grab_super - acquire an active reference * @s: reference we are trying to make active * * Tries to acquire an active reference. grab_super() is used when we * had just found a superblock in super_blocks or fs_type->fs_supers * and want to turn it into a full-blown active reference. grab_super() * is called with sb_lock held and drops it. Returns 1 in case of * success, 0 if we had failed (superblock contents was already dead or * dying when grab_super() had been called). Note that this is only * called for superblocks not in rundown mode (== ones still on ->fs_supers * of their type), so increment of ->s_count is OK here. */ static int grab_super(struct super_block *s) __releases(sb_lock) { s->s_count++; spin_unlock(&sb_lock); down_write(&s->s_umount); if ((s->s_flags & MS_BORN) && atomic_inc_not_zero(&s->s_active)) { put_super(s); return 1; } up_write(&s->s_umount); put_super(s); return 0; } /* * grab_super_passive - acquire a passive reference * @sb: reference we are trying to grab * * Tries to acquire a passive reference. This is used in places where we * cannot take an active reference but we need to ensure that the * superblock does not go away while we are working on it. It returns * false if a reference was not gained, and returns true with the s_umount * lock held in read mode if a reference is gained. On successful return, * the caller must drop the s_umount lock and the passive reference when * done. */ bool grab_super_passive(struct super_block *sb) { spin_lock(&sb_lock); if (hlist_unhashed(&sb->s_instances)) { spin_unlock(&sb_lock); return false; } sb->s_count++; spin_unlock(&sb_lock); if (down_read_trylock(&sb->s_umount)) { if (sb->s_root && (sb->s_flags & MS_BORN)) return true; up_read(&sb->s_umount); } put_super(sb); return false; } /** * generic_shutdown_super - common helper for ->kill_sb() * @sb: superblock to kill * * generic_shutdown_super() does all fs-independent work on superblock * shutdown. Typical ->kill_sb() should pick all fs-specific objects * that need destruction out of superblock, call generic_shutdown_super() * and release aforementioned objects. Note: dentries and inodes _are_ * taken care of and do not need specific handling. * * Upon calling this function, the filesystem may no longer alter or * rearrange the set of dentries belonging to this super_block, nor may it * change the attachments of dentries to inodes. */ void generic_shutdown_super(struct super_block *sb) { const struct super_operations *sop = sb->s_op; if (sb->s_root) { shrink_dcache_for_umount(sb); sync_filesystem(sb); sb->s_flags &= ~MS_ACTIVE; fsnotify_unmount_inodes(&sb->s_inodes); evict_inodes(sb); if (sb->s_dio_done_wq) { destroy_workqueue(sb->s_dio_done_wq); sb->s_dio_done_wq = NULL; } if (sop->put_super) sop->put_super(sb); if (!list_empty(&sb->s_inodes)) { printk("VFS: Busy inodes after unmount of %s. " "Self-destruct in 5 seconds. Have a nice day...\n", sb->s_id); } } spin_lock(&sb_lock); /* should be initialized for __put_super_and_need_restart() */ hlist_del_init(&sb->s_instances); spin_unlock(&sb_lock); up_write(&sb->s_umount); } EXPORT_SYMBOL(generic_shutdown_super); /** * sget - find or create a superblock * @type: filesystem type superblock should belong to * @test: comparison callback * @set: setup callback * @flags: mount flags * @data: argument to each of them */ struct super_block *sget(struct file_system_type *type, int (*test)(struct super_block *,void *), int (*set)(struct super_block *,void *), int flags, void *data) { struct super_block *s = NULL; struct super_block *old; int err; retry: spin_lock(&sb_lock); if (test) { hlist_for_each_entry(old, &type->fs_supers, s_instances) { if (!test(old, data)) continue; if (!grab_super(old)) goto retry; if (s) { up_write(&s->s_umount); destroy_super(s); s = NULL; } return old; } } if (!s) { spin_unlock(&sb_lock); s = alloc_super(type, flags); if (!s) return ERR_PTR(-ENOMEM); goto retry; } err = set(s, data); if (err) { spin_unlock(&sb_lock); up_write(&s->s_umount); destroy_super(s); return ERR_PTR(err); } s->s_type = type; strlcpy(s->s_id, type->name, sizeof(s->s_id)); list_add_tail(&s->s_list, &super_blocks); hlist_add_head(&s->s_instances, &type->fs_supers); spin_unlock(&sb_lock); get_filesystem(type); register_shrinker(&s->s_shrink); return s; } EXPORT_SYMBOL(sget); void drop_super(struct super_block *sb) { up_read(&sb->s_umount); put_super(sb); } EXPORT_SYMBOL(drop_super); /** * iterate_supers - call function for all active superblocks * @f: function to call * @arg: argument to pass to it * * Scans the superblock list and calls given function, passing it * locked superblock and given argument. */ void iterate_supers(void (*f)(struct super_block *, void *), void *arg) { struct super_block *sb, *p = NULL; spin_lock(&sb_lock); list_for_each_entry(sb, &super_blocks, s_list) { if (hlist_unhashed(&sb->s_instances)) continue; sb->s_count++; spin_unlock(&sb_lock); down_read(&sb->s_umount); if (sb->s_root && (sb->s_flags & MS_BORN)) f(sb, arg); up_read(&sb->s_umount); spin_lock(&sb_lock); if (p) __put_super(p); p = sb; } if (p) __put_super(p); spin_unlock(&sb_lock); } /** * iterate_supers_type - call function for superblocks of given type * @type: fs type * @f: function to call * @arg: argument to pass to it * * Scans the superblock list and calls given function, passing it * locked superblock and given argument. */ void iterate_supers_type(struct file_system_type *type, void (*f)(struct super_block *, void *), void *arg) { struct super_block *sb, *p = NULL; spin_lock(&sb_lock); hlist_for_each_entry(sb, &type->fs_supers, s_instances) { sb->s_count++; spin_unlock(&sb_lock); down_read(&sb->s_umount); if (sb->s_root && (sb->s_flags & MS_BORN)) f(sb, arg); up_read(&sb->s_umount); spin_lock(&sb_lock); if (p) __put_super(p); p = sb; } if (p) __put_super(p); spin_unlock(&sb_lock); } EXPORT_SYMBOL(iterate_supers_type); /** * get_super - get the superblock of a device * @bdev: device to get the superblock for * * Scans the superblock list and finds the superblock of the file system * mounted on the device given. %NULL is returned if no match is found. */ struct super_block *get_super(struct block_device *bdev) { struct super_block *sb; if (!bdev) return NULL; spin_lock(&sb_lock); rescan: list_for_each_entry(sb, &super_blocks, s_list) { if (hlist_unhashed(&sb->s_instances)) continue; if (sb->s_bdev == bdev) { sb->s_count++; spin_unlock(&sb_lock); down_read(&sb->s_umount); /* still alive? */ if (sb->s_root && (sb->s_flags & MS_BORN)) return sb; up_read(&sb->s_umount); /* nope, got unmounted */ spin_lock(&sb_lock); __put_super(sb); goto rescan; } } spin_unlock(&sb_lock); return NULL; } EXPORT_SYMBOL(get_super); /** * get_super_thawed - get thawed superblock of a device * @bdev: device to get the superblock for * * Scans the superblock list and finds the superblock of the file system * mounted on the device. The superblock is returned once it is thawed * (or immediately if it was not frozen). %NULL is returned if no match * is found. */ struct super_block *get_super_thawed(struct block_device *bdev) { while (1) { struct super_block *s = get_super(bdev); if (!s || s->s_writers.frozen == SB_UNFROZEN) return s; up_read(&s->s_umount); wait_event(s->s_writers.wait_unfrozen, s->s_writers.frozen == SB_UNFROZEN); put_super(s); } } EXPORT_SYMBOL(get_super_thawed); /** * get_active_super - get an active reference to the superblock of a device * @bdev: device to get the superblock for * * Scans the superblock list and finds the superblock of the file system * mounted on the device given. Returns the superblock with an active * reference or %NULL if none was found. */ struct super_block *get_active_super(struct block_device *bdev) { struct super_block *sb; if (!bdev) return NULL; restart: spin_lock(&sb_lock); list_for_each_entry(sb, &super_blocks, s_list) { if (hlist_unhashed(&sb->s_instances)) continue; if (sb->s_bdev == bdev) { if (!grab_super(sb)) goto restart; up_write(&sb->s_umount); return sb; } } spin_unlock(&sb_lock); return NULL; } struct super_block *user_get_super(dev_t dev) { struct super_block *sb; spin_lock(&sb_lock); rescan: list_for_each_entry(sb, &super_blocks, s_list) { if (hlist_unhashed(&sb->s_instances)) continue; if (sb->s_dev == dev) { sb->s_count++; spin_unlock(&sb_lock); down_read(&sb->s_umount); /* still alive? */ if (sb->s_root && (sb->s_flags & MS_BORN)) return sb; up_read(&sb->s_umount); /* nope, got unmounted */ spin_lock(&sb_lock); __put_super(sb); goto rescan; } } spin_unlock(&sb_lock); return NULL; } /** * do_remount_sb - asks filesystem to change mount options. * @sb: superblock in question * @flags: numeric part of options * @data: the rest of options * @force: whether or not to force the change * * Alters the mount options of a mounted file system. */ int do_remount_sb(struct super_block *sb, int flags, void *data, int force) { int retval; int remount_ro; if (sb->s_writers.frozen != SB_UNFROZEN) return -EBUSY; #ifdef CONFIG_BLOCK if (!(flags & MS_RDONLY) && bdev_read_only(sb->s_bdev)) return -EACCES; #endif if (flags & MS_RDONLY) acct_auto_close(sb); shrink_dcache_sb(sb); sync_filesystem(sb); remount_ro = (flags & MS_RDONLY) && !(sb->s_flags & MS_RDONLY); /* If we are remounting RDONLY and current sb is read/write, make sure there are no rw files opened */ if (remount_ro) { if (force) { sb->s_readonly_remount = 1; smp_wmb(); } else { retval = sb_prepare_remount_readonly(sb); if (retval) return retval; } } if (sb->s_op->remount_fs) { retval = sb->s_op->remount_fs(sb, &flags, data); if (retval) { if (!force) goto cancel_readonly; /* If forced remount, go ahead despite any errors */ WARN(1, "forced remount of a %s fs returned %i\n", sb->s_type->name, retval); } } sb->s_flags = (sb->s_flags & ~MS_RMT_MASK) | (flags & MS_RMT_MASK); /* Needs to be ordered wrt mnt_is_readonly() */ smp_wmb(); sb->s_readonly_remount = 0; /* * Some filesystems modify their metadata via some other path than the * bdev buffer cache (eg. use a private mapping, or directories in * pagecache, etc). Also file data modifications go via their own * mappings. So If we try to mount readonly then copy the filesystem * from bdev, we could get stale data, so invalidate it to give a best * effort at coherency. */ if (remount_ro && sb->s_bdev) invalidate_bdev(sb->s_bdev); return 0; cancel_readonly: sb->s_readonly_remount = 0; return retval; } static void do_emergency_remount(struct work_struct *work) { struct super_block *sb, *p = NULL; spin_lock(&sb_lock); list_for_each_entry(sb, &super_blocks, s_list) { if (hlist_unhashed(&sb->s_instances)) continue; sb->s_count++; spin_unlock(&sb_lock); down_write(&sb->s_umount); if (sb->s_root && sb->s_bdev && (sb->s_flags & MS_BORN) && !(sb->s_flags & MS_RDONLY)) { /* * What lock protects sb->s_flags?? */ do_remount_sb(sb, MS_RDONLY, NULL, 1); } up_write(&sb->s_umount); spin_lock(&sb_lock); if (p) __put_super(p); p = sb; } if (p) __put_super(p); spin_unlock(&sb_lock); kfree(work); printk("Emergency Remount complete\n"); } void emergency_remount(void) { struct work_struct *work; work = kmalloc(sizeof(*work), GFP_ATOMIC); if (work) { INIT_WORK(work, do_emergency_remount); schedule_work(work); } } /* * Unnamed block devices are dummy devices used by virtual * filesystems which don't use real block-devices. -- jrs */ static DEFINE_IDA(unnamed_dev_ida); static DEFINE_SPINLOCK(unnamed_dev_lock);/* protects the above */ static int unnamed_dev_start = 0; /* don't bother trying below it */ int get_anon_bdev(dev_t *p) { int dev; int error; retry: if (ida_pre_get(&unnamed_dev_ida, GFP_ATOMIC) == 0) return -ENOMEM; spin_lock(&unnamed_dev_lock); error = ida_get_new_above(&unnamed_dev_ida, unnamed_dev_start, &dev); if (!error) unnamed_dev_start = dev + 1; spin_unlock(&unnamed_dev_lock); if (error == -EAGAIN) /* We raced and lost with another CPU. */ goto retry; else if (error) return -EAGAIN; if (dev == (1 << MINORBITS)) { spin_lock(&unnamed_dev_lock); ida_remove(&unnamed_dev_ida, dev); if (unnamed_dev_start > dev) unnamed_dev_start = dev; spin_unlock(&unnamed_dev_lock); return -EMFILE; } *p = MKDEV(0, dev & MINORMASK); return 0; } EXPORT_SYMBOL(get_anon_bdev); void free_anon_bdev(dev_t dev) { int slot = MINOR(dev); spin_lock(&unnamed_dev_lock); ida_remove(&unnamed_dev_ida, slot); if (slot < unnamed_dev_start) unnamed_dev_start = slot; spin_unlock(&unnamed_dev_lock); } EXPORT_SYMBOL(free_anon_bdev); int set_anon_super(struct super_block *s, void *data) { int error = get_anon_bdev(&s->s_dev); if (!error) s->s_bdi = &noop_backing_dev_info; return error; } EXPORT_SYMBOL(set_anon_super); void kill_anon_super(struct super_block *sb) { dev_t dev = sb->s_dev; generic_shutdown_super(sb); free_anon_bdev(dev); } EXPORT_SYMBOL(kill_anon_super); void kill_litter_super(struct super_block *sb) { if (sb->s_root) d_genocide(sb->s_root); kill_anon_super(sb); } EXPORT_SYMBOL(kill_litter_super); static int ns_test_super(struct super_block *sb, void *data) { return sb->s_fs_info == data; } static int ns_set_super(struct super_block *sb, void *data) { sb->s_fs_info = data; return set_anon_super(sb, NULL); } struct dentry *mount_ns(struct file_system_type *fs_type, int flags, void *data, int (*fill_super)(struct super_block *, void *, int)) { struct super_block *sb; sb = sget(fs_type, ns_test_super, ns_set_super, flags, data); if (IS_ERR(sb)) return ERR_CAST(sb); if (!sb->s_root) { int err; err = fill_super(sb, data, flags & MS_SILENT ? 1 : 0); if (err) { deactivate_locked_super(sb); return ERR_PTR(err); } sb->s_flags |= MS_ACTIVE; } return dget(sb->s_root); } EXPORT_SYMBOL(mount_ns); #ifdef CONFIG_BLOCK static int set_bdev_super(struct super_block *s, void *data) { s->s_bdev = data; s->s_dev = s->s_bdev->bd_dev; /* * We set the bdi here to the queue backing, file systems can * overwrite this in ->fill_super() */ s->s_bdi = &bdev_get_queue(s->s_bdev)->backing_dev_info; return 0; } static int test_bdev_super(struct super_block *s, void *data) { return (void *)s->s_bdev == data; } struct dentry *mount_bdev(struct file_system_type *fs_type, int flags, const char *dev_name, void *data, int (*fill_super)(struct super_block *, void *, int)) { struct block_device *bdev; struct super_block *s; fmode_t mode = FMODE_READ | FMODE_EXCL; int error = 0; if (!(flags & MS_RDONLY)) mode |= FMODE_WRITE; bdev = blkdev_get_by_path(dev_name, mode, fs_type); if (IS_ERR(bdev)) return ERR_CAST(bdev); /* * once the super is inserted into the list by sget, s_umount * will protect the lockfs code from trying to start a snapshot * while we are mounting */ mutex_lock(&bdev->bd_fsfreeze_mutex); if (bdev->bd_fsfreeze_count > 0) { mutex_unlock(&bdev->bd_fsfreeze_mutex); error = -EBUSY; goto error_bdev; } s = sget(fs_type, test_bdev_super, set_bdev_super, flags | MS_NOSEC, bdev); mutex_unlock(&bdev->bd_fsfreeze_mutex); if (IS_ERR(s)) goto error_s; if (s->s_root) { if ((flags ^ s->s_flags) & MS_RDONLY) { deactivate_locked_super(s); error = -EBUSY; goto error_bdev; } /* * s_umount nests inside bd_mutex during * __invalidate_device(). blkdev_put() acquires * bd_mutex and can't be called under s_umount. Drop * s_umount temporarily. This is safe as we're * holding an active reference. */ up_write(&s->s_umount); blkdev_put(bdev, mode); down_write(&s->s_umount); } else { char b[BDEVNAME_SIZE]; s->s_mode = mode; strlcpy(s->s_id, bdevname(bdev, b), sizeof(s->s_id)); sb_set_blocksize(s, block_size(bdev)); error = fill_super(s, data, flags & MS_SILENT ? 1 : 0); if (error) { deactivate_locked_super(s); goto error; } s->s_flags |= MS_ACTIVE; bdev->bd_super = s; } return dget(s->s_root); error_s: error = PTR_ERR(s); error_bdev: blkdev_put(bdev, mode); error: return ERR_PTR(error); } EXPORT_SYMBOL(mount_bdev); void kill_block_super(struct super_block *sb) { struct block_device *bdev = sb->s_bdev; fmode_t mode = sb->s_mode; bdev->bd_super = NULL; generic_shutdown_super(sb); sync_blockdev(bdev); WARN_ON_ONCE(!(mode & FMODE_EXCL)); blkdev_put(bdev, mode | FMODE_EXCL); } EXPORT_SYMBOL(kill_block_super); #endif struct dentry *mount_nodev(struct file_system_type *fs_type, int flags, void *data, int (*fill_super)(struct super_block *, void *, int)) { int error; struct super_block *s = sget(fs_type, NULL, set_anon_super, flags, NULL); if (IS_ERR(s)) return ERR_CAST(s); error = fill_super(s, data, flags & MS_SILENT ? 1 : 0); if (error) { deactivate_locked_super(s); return ERR_PTR(error); } s->s_flags |= MS_ACTIVE; return dget(s->s_root); } EXPORT_SYMBOL(mount_nodev); static int compare_single(struct super_block *s, void *p) { return 1; } struct dentry *mount_single(struct file_system_type *fs_type, int flags, void *data, int (*fill_super)(struct super_block *, void *, int)) { struct super_block *s; int error; s = sget(fs_type, compare_single, set_anon_super, flags, NULL); if (IS_ERR(s)) return ERR_CAST(s); if (!s->s_root) { error = fill_super(s, data, flags & MS_SILENT ? 1 : 0); if (error) { deactivate_locked_super(s); return ERR_PTR(error); } s->s_flags |= MS_ACTIVE; } else { do_remount_sb(s, flags, data, 0); } return dget(s->s_root); } EXPORT_SYMBOL(mount_single); struct dentry * mount_fs(struct file_system_type *type, int flags, const char *name, void *data) { struct dentry *root; struct super_block *sb; char *secdata = NULL; int error = -ENOMEM; if (data && !(type->fs_flags & FS_BINARY_MOUNTDATA)) { secdata = alloc_secdata(); if (!secdata) goto out; error = security_sb_copy_data(data, secdata); if (error) goto out_free_secdata; } root = type->mount(type, flags, name, data); if (IS_ERR(root)) { error = PTR_ERR(root); goto out_free_secdata; } sb = root->d_sb; BUG_ON(!sb); WARN_ON(!sb->s_bdi); WARN_ON(sb->s_bdi == &default_backing_dev_info); sb->s_flags |= MS_BORN; error = security_sb_kern_mount(sb, flags, secdata); if (error) goto out_sb; /* * filesystems should never set s_maxbytes larger than MAX_LFS_FILESIZE * but s_maxbytes was an unsigned long long for many releases. Throw * this warning for a little while to try and catch filesystems that * violate this rule. */ WARN((sb->s_maxbytes < 0), "%s set sb->s_maxbytes to " "negative value (%lld)\n", type->name, sb->s_maxbytes); up_write(&sb->s_umount); free_secdata(secdata); return root; out_sb: dput(root); deactivate_locked_super(sb); out_free_secdata: free_secdata(secdata); out: return ERR_PTR(error); } /* * This is an internal function, please use sb_end_{write,pagefault,intwrite} * instead. */ void __sb_end_write(struct super_block *sb, int level) { percpu_counter_dec(&sb->s_writers.counter[level-1]); /* * Make sure s_writers are updated before we wake up waiters in * freeze_super(). */ smp_mb(); if (waitqueue_active(&sb->s_writers.wait)) wake_up(&sb->s_writers.wait); rwsem_release(&sb->s_writers.lock_map[level-1], 1, _RET_IP_); } EXPORT_SYMBOL(__sb_end_write); #ifdef CONFIG_LOCKDEP /* * We want lockdep to tell us about possible deadlocks with freezing but * it's it bit tricky to properly instrument it. Getting a freeze protection * works as getting a read lock but there are subtle problems. XFS for example * gets freeze protection on internal level twice in some cases, which is OK * only because we already hold a freeze protection also on higher level. Due * to these cases we have to tell lockdep we are doing trylock when we * already hold a freeze protection for a higher freeze level. */ static void acquire_freeze_lock(struct super_block *sb, int level, bool trylock, unsigned long ip) { int i; if (!trylock) { for (i = 0; i < level - 1; i++) if (lock_is_held(&sb->s_writers.lock_map[i])) { trylock = true; break; } } rwsem_acquire_read(&sb->s_writers.lock_map[level-1], 0, trylock, ip); } #endif /* * This is an internal function, please use sb_start_{write,pagefault,intwrite} * instead. */ int __sb_start_write(struct super_block *sb, int level, bool wait) { retry: if (unlikely(sb->s_writers.frozen >= level)) { if (!wait) return 0; wait_event(sb->s_writers.wait_unfrozen, sb->s_writers.frozen < level); } #ifdef CONFIG_LOCKDEP acquire_freeze_lock(sb, level, !wait, _RET_IP_); #endif percpu_counter_inc(&sb->s_writers.counter[level-1]); /* * Make sure counter is updated before we check for frozen. * freeze_super() first sets frozen and then checks the counter. */ smp_mb(); if (unlikely(sb->s_writers.frozen >= level)) { __sb_end_write(sb, level); goto retry; } return 1; } EXPORT_SYMBOL(__sb_start_write); /** * sb_wait_write - wait until all writers to given file system finish * @sb: the super for which we wait * @level: type of writers we wait for (normal vs page fault) * * This function waits until there are no writers of given type to given file * system. Caller of this function should make sure there can be no new writers * of type @level before calling this function. Otherwise this function can * livelock. */ static void sb_wait_write(struct super_block *sb, int level) { s64 writers; /* * We just cycle-through lockdep here so that it does not complain * about returning with lock to userspace */ rwsem_acquire(&sb->s_writers.lock_map[level-1], 0, 0, _THIS_IP_); rwsem_release(&sb->s_writers.lock_map[level-1], 1, _THIS_IP_); do { DEFINE_WAIT(wait); /* * We use a barrier in prepare_to_wait() to separate setting * of frozen and checking of the counter */ prepare_to_wait(&sb->s_writers.wait, &wait, TASK_UNINTERRUPTIBLE); writers = percpu_counter_sum(&sb->s_writers.counter[level-1]); if (writers) schedule(); finish_wait(&sb->s_writers.wait, &wait); } while (writers); } /** * freeze_super - lock the filesystem and force it into a consistent state * @sb: the super to lock * * Syncs the super to make sure the filesystem is consistent and calls the fs's * freeze_fs. Subsequent calls to this without first thawing the fs will return * -EBUSY. * * During this function, sb->s_writers.frozen goes through these values: * * SB_UNFROZEN: File system is normal, all writes progress as usual. * * SB_FREEZE_WRITE: The file system is in the process of being frozen. New * writes should be blocked, though page faults are still allowed. We wait for * all writes to complete and then proceed to the next stage. * * SB_FREEZE_PAGEFAULT: Freezing continues. Now also page faults are blocked * but internal fs threads can still modify the filesystem (although they * should not dirty new pages or inodes), writeback can run etc. After waiting * for all running page faults we sync the filesystem which will clean all * dirty pages and inodes (no new dirty pages or inodes can be created when * sync is running). * * SB_FREEZE_FS: The file system is frozen. Now all internal sources of fs * modification are blocked (e.g. XFS preallocation truncation on inode * reclaim). This is usually implemented by blocking new transactions for * filesystems that have them and need this additional guard. After all * internal writers are finished we call ->freeze_fs() to finish filesystem * freezing. Then we transition to SB_FREEZE_COMPLETE state. This state is * mostly auxiliary for filesystems to verify they do not modify frozen fs. * * sb->s_writers.frozen is protected by sb->s_umount. */ int freeze_super(struct super_block *sb) { int ret; atomic_inc(&sb->s_active); down_write(&sb->s_umount); if (sb->s_writers.frozen != SB_UNFROZEN) { deactivate_locked_super(sb); return -EBUSY; } if (!(sb->s_flags & MS_BORN)) { up_write(&sb->s_umount); return 0; /* sic - it's "nothing to do" */ } if (sb->s_flags & MS_RDONLY) { /* Nothing to do really... */ sb->s_writers.frozen = SB_FREEZE_COMPLETE; up_write(&sb->s_umount); return 0; } /* From now on, no new normal writers can start */ sb->s_writers.frozen = SB_FREEZE_WRITE; smp_wmb(); /* Release s_umount to preserve sb_start_write -> s_umount ordering */ up_write(&sb->s_umount); sb_wait_write(sb, SB_FREEZE_WRITE); /* Now we go and block page faults... */ down_write(&sb->s_umount); sb->s_writers.frozen = SB_FREEZE_PAGEFAULT; smp_wmb(); sb_wait_write(sb, SB_FREEZE_PAGEFAULT); /* All writers are done so after syncing there won't be dirty data */ sync_filesystem(sb); /* Now wait for internal filesystem counter */ sb->s_writers.frozen = SB_FREEZE_FS; smp_wmb(); sb_wait_write(sb, SB_FREEZE_FS); if (sb->s_op->freeze_fs) { ret = sb->s_op->freeze_fs(sb); if (ret) { printk(KERN_ERR "VFS:Filesystem freeze failed\n"); sb->s_writers.frozen = SB_UNFROZEN; smp_wmb(); wake_up(&sb->s_writers.wait_unfrozen); deactivate_locked_super(sb); return ret; } } /* * This is just for debugging purposes so that fs can warn if it * sees write activity when frozen is set to SB_FREEZE_COMPLETE. */ sb->s_writers.frozen = SB_FREEZE_COMPLETE; up_write(&sb->s_umount); return 0; } EXPORT_SYMBOL(freeze_super); /** * thaw_super -- unlock filesystem * @sb: the super to thaw * * Unlocks the filesystem and marks it writeable again after freeze_super(). */ int thaw_super(struct super_block *sb) { int error; down_write(&sb->s_umount); if (sb->s_writers.frozen == SB_UNFROZEN) { up_write(&sb->s_umount); return -EINVAL; } if (sb->s_flags & MS_RDONLY) goto out; if (sb->s_op->unfreeze_fs) { error = sb->s_op->unfreeze_fs(sb); if (error) { printk(KERN_ERR "VFS:Filesystem thaw failed\n"); up_write(&sb->s_umount); return error; } } out: sb->s_writers.frozen = SB_UNFROZEN; smp_wmb(); wake_up(&sb->s_writers.wait_unfrozen); deactivate_locked_super(sb); return 0; } EXPORT_SYMBOL(thaw_super);
./CrossVul/dataset_final_sorted/CWE-17/c/good_2306_3
crossvul-cpp_data_good_1511_0
/* * Copyright (c) 2006 Oracle. All rights reserved. * * This software is available to you under a choice of one of two * licenses. You may choose to be licensed under the terms of the GNU * General Public License (GPL) Version 2, available from the file * COPYING in the main directory of this source tree, or the * OpenIB.org BSD license below: * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * - Redistributions of source code must retain the above * copyright notice, this list of conditions and the following * disclaimer. * * - Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ #include <linux/kernel.h> #include <linux/sysctl.h> #include <linux/proc_fs.h> #include "rds.h" static struct ctl_table_header *rds_sysctl_reg_table; static unsigned long rds_sysctl_reconnect_min = 1; static unsigned long rds_sysctl_reconnect_max = ~0UL; unsigned long rds_sysctl_reconnect_min_jiffies; unsigned long rds_sysctl_reconnect_max_jiffies = HZ; unsigned int rds_sysctl_max_unacked_packets = 8; unsigned int rds_sysctl_max_unacked_bytes = (16 << 20); unsigned int rds_sysctl_ping_enable = 1; static struct ctl_table rds_sysctl_rds_table[] = { { .procname = "reconnect_min_delay_ms", .data = &rds_sysctl_reconnect_min_jiffies, .maxlen = sizeof(unsigned long), .mode = 0644, .proc_handler = proc_doulongvec_ms_jiffies_minmax, .extra1 = &rds_sysctl_reconnect_min, .extra2 = &rds_sysctl_reconnect_max_jiffies, }, { .procname = "reconnect_max_delay_ms", .data = &rds_sysctl_reconnect_max_jiffies, .maxlen = sizeof(unsigned long), .mode = 0644, .proc_handler = proc_doulongvec_ms_jiffies_minmax, .extra1 = &rds_sysctl_reconnect_min_jiffies, .extra2 = &rds_sysctl_reconnect_max, }, { .procname = "max_unacked_packets", .data = &rds_sysctl_max_unacked_packets, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "max_unacked_bytes", .data = &rds_sysctl_max_unacked_bytes, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "ping_enable", .data = &rds_sysctl_ping_enable, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { } }; void rds_sysctl_exit(void) { unregister_net_sysctl_table(rds_sysctl_reg_table); } int rds_sysctl_init(void) { rds_sysctl_reconnect_min = msecs_to_jiffies(1); rds_sysctl_reconnect_min_jiffies = rds_sysctl_reconnect_min; rds_sysctl_reg_table = register_net_sysctl(&init_net,"net/rds", rds_sysctl_rds_table); if (!rds_sysctl_reg_table) return -ENOMEM; return 0; }
./CrossVul/dataset_final_sorted/CWE-17/c/good_1511_0
crossvul-cpp_data_good_1482_1
/* * INET An implementation of the TCP/IP protocol suite for the LINUX * operating system. INET is implemented using the BSD Socket * interface as the means of communication with the user level. * * The IP forwarding functionality. * * Authors: see ip.c * * Fixes: * Many : Split from ip.c , see ip_input.c for * history. * Dave Gregorich : NULL ip_rt_put fix for multicast * routing. * Jos Vos : Add call_out_firewall before sending, * use output device for accounting. * Jos Vos : Call forward firewall after routing * (always use output device). * Mike McLagan : Routing by source */ #include <linux/types.h> #include <linux/mm.h> #include <linux/skbuff.h> #include <linux/ip.h> #include <linux/icmp.h> #include <linux/netdevice.h> #include <linux/slab.h> #include <net/sock.h> #include <net/ip.h> #include <net/tcp.h> #include <net/udp.h> #include <net/icmp.h> #include <linux/tcp.h> #include <linux/udp.h> #include <linux/netfilter_ipv4.h> #include <net/checksum.h> #include <linux/route.h> #include <net/route.h> #include <net/xfrm.h> static bool ip_may_fragment(const struct sk_buff *skb) { return unlikely((ip_hdr(skb)->frag_off & htons(IP_DF)) == 0) || skb->ignore_df; } static bool ip_exceeds_mtu(const struct sk_buff *skb, unsigned int mtu) { if (skb->len <= mtu) return false; if (skb_is_gso(skb) && skb_gso_network_seglen(skb) <= mtu) return false; return true; } static int ip_forward_finish(struct sk_buff *skb) { struct ip_options *opt = &(IPCB(skb)->opt); IP_INC_STATS_BH(dev_net(skb_dst(skb)->dev), IPSTATS_MIB_OUTFORWDATAGRAMS); IP_ADD_STATS_BH(dev_net(skb_dst(skb)->dev), IPSTATS_MIB_OUTOCTETS, skb->len); if (unlikely(opt->optlen)) ip_forward_options(skb); return dst_output(skb); } int ip_forward(struct sk_buff *skb) { u32 mtu; struct iphdr *iph; /* Our header */ struct rtable *rt; /* Route we use */ struct ip_options *opt = &(IPCB(skb)->opt); /* that should never happen */ if (skb->pkt_type != PACKET_HOST) goto drop; if (skb_warn_if_lro(skb)) goto drop; if (!xfrm4_policy_check(NULL, XFRM_POLICY_FWD, skb)) goto drop; if (IPCB(skb)->opt.router_alert && ip_call_ra_chain(skb)) return NET_RX_SUCCESS; skb_forward_csum(skb); /* * According to the RFC, we must first decrease the TTL field. If * that reaches zero, we must reply an ICMP control message telling * that the packet's lifetime expired. */ if (ip_hdr(skb)->ttl <= 1) goto too_many_hops; if (!xfrm4_route_forward(skb)) goto drop; rt = skb_rtable(skb); if (opt->is_strictroute && rt->rt_uses_gateway) goto sr_failed; IPCB(skb)->flags |= IPSKB_FORWARDED; mtu = ip_dst_mtu_maybe_forward(&rt->dst, true); if (!ip_may_fragment(skb) && ip_exceeds_mtu(skb, mtu)) { IP_INC_STATS(dev_net(rt->dst.dev), IPSTATS_MIB_FRAGFAILS); icmp_send(skb, ICMP_DEST_UNREACH, ICMP_FRAG_NEEDED, htonl(mtu)); goto drop; } /* We are about to mangle packet. Copy it! */ if (skb_cow(skb, LL_RESERVED_SPACE(rt->dst.dev)+rt->dst.header_len)) goto drop; iph = ip_hdr(skb); /* Decrease ttl after skb cow done */ ip_decrease_ttl(iph); /* * We now generate an ICMP HOST REDIRECT giving the route * we calculated. */ if (IPCB(skb)->flags & IPSKB_DOREDIRECT && !opt->srr && !skb_sec_path(skb)) ip_rt_send_redirect(skb); skb->priority = rt_tos2priority(iph->tos); return NF_HOOK(NFPROTO_IPV4, NF_INET_FORWARD, skb, skb->dev, rt->dst.dev, ip_forward_finish); sr_failed: /* * Strict routing permits no gatewaying */ icmp_send(skb, ICMP_DEST_UNREACH, ICMP_SR_FAILED, 0); goto drop; too_many_hops: /* Tell the sender its packet died... */ IP_INC_STATS_BH(dev_net(skb_dst(skb)->dev), IPSTATS_MIB_INHDRERRORS); icmp_send(skb, ICMP_TIME_EXCEEDED, ICMP_EXC_TTL, 0); drop: kfree_skb(skb); return NET_RX_DROP; }
./CrossVul/dataset_final_sorted/CWE-17/c/good_1482_1
crossvul-cpp_data_bad_1643_0
/* bpf_jit_comp.c : BPF JIT compiler * * Copyright (C) 2011-2013 Eric Dumazet (eric.dumazet@gmail.com) * Internal BPF Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; version 2 * of the License. */ #include <linux/netdevice.h> #include <linux/filter.h> #include <linux/if_vlan.h> #include <asm/cacheflush.h> int bpf_jit_enable __read_mostly; /* * assembly code in arch/x86/net/bpf_jit.S */ extern u8 sk_load_word[], sk_load_half[], sk_load_byte[]; extern u8 sk_load_word_positive_offset[], sk_load_half_positive_offset[]; extern u8 sk_load_byte_positive_offset[]; extern u8 sk_load_word_negative_offset[], sk_load_half_negative_offset[]; extern u8 sk_load_byte_negative_offset[]; static u8 *emit_code(u8 *ptr, u32 bytes, unsigned int len) { if (len == 1) *ptr = bytes; else if (len == 2) *(u16 *)ptr = bytes; else { *(u32 *)ptr = bytes; barrier(); } return ptr + len; } #define EMIT(bytes, len) do { prog = emit_code(prog, bytes, len); } while (0) #define EMIT1(b1) EMIT(b1, 1) #define EMIT2(b1, b2) EMIT((b1) + ((b2) << 8), 2) #define EMIT3(b1, b2, b3) EMIT((b1) + ((b2) << 8) + ((b3) << 16), 3) #define EMIT4(b1, b2, b3, b4) EMIT((b1) + ((b2) << 8) + ((b3) << 16) + ((b4) << 24), 4) #define EMIT1_off32(b1, off) \ do {EMIT1(b1); EMIT(off, 4); } while (0) #define EMIT2_off32(b1, b2, off) \ do {EMIT2(b1, b2); EMIT(off, 4); } while (0) #define EMIT3_off32(b1, b2, b3, off) \ do {EMIT3(b1, b2, b3); EMIT(off, 4); } while (0) #define EMIT4_off32(b1, b2, b3, b4, off) \ do {EMIT4(b1, b2, b3, b4); EMIT(off, 4); } while (0) static bool is_imm8(int value) { return value <= 127 && value >= -128; } static bool is_simm32(s64 value) { return value == (s64) (s32) value; } /* mov dst, src */ #define EMIT_mov(DST, SRC) \ do {if (DST != SRC) \ EMIT3(add_2mod(0x48, DST, SRC), 0x89, add_2reg(0xC0, DST, SRC)); \ } while (0) static int bpf_size_to_x86_bytes(int bpf_size) { if (bpf_size == BPF_W) return 4; else if (bpf_size == BPF_H) return 2; else if (bpf_size == BPF_B) return 1; else if (bpf_size == BPF_DW) return 4; /* imm32 */ else return 0; } /* list of x86 cond jumps opcodes (. + s8) * Add 0x10 (and an extra 0x0f) to generate far jumps (. + s32) */ #define X86_JB 0x72 #define X86_JAE 0x73 #define X86_JE 0x74 #define X86_JNE 0x75 #define X86_JBE 0x76 #define X86_JA 0x77 #define X86_JGE 0x7D #define X86_JG 0x7F static void bpf_flush_icache(void *start, void *end) { mm_segment_t old_fs = get_fs(); set_fs(KERNEL_DS); smp_wmb(); flush_icache_range((unsigned long)start, (unsigned long)end); set_fs(old_fs); } #define CHOOSE_LOAD_FUNC(K, func) \ ((int)K < 0 ? ((int)K >= SKF_LL_OFF ? func##_negative_offset : func) : func##_positive_offset) /* pick a register outside of BPF range for JIT internal work */ #define AUX_REG (MAX_BPF_REG + 1) /* the following table maps BPF registers to x64 registers. * x64 register r12 is unused, since if used as base address register * in load/store instructions, it always needs an extra byte of encoding */ static const int reg2hex[] = { [BPF_REG_0] = 0, /* rax */ [BPF_REG_1] = 7, /* rdi */ [BPF_REG_2] = 6, /* rsi */ [BPF_REG_3] = 2, /* rdx */ [BPF_REG_4] = 1, /* rcx */ [BPF_REG_5] = 0, /* r8 */ [BPF_REG_6] = 3, /* rbx callee saved */ [BPF_REG_7] = 5, /* r13 callee saved */ [BPF_REG_8] = 6, /* r14 callee saved */ [BPF_REG_9] = 7, /* r15 callee saved */ [BPF_REG_FP] = 5, /* rbp readonly */ [AUX_REG] = 3, /* r11 temp register */ }; /* is_ereg() == true if BPF register 'reg' maps to x64 r8..r15 * which need extra byte of encoding. * rax,rcx,...,rbp have simpler encoding */ static bool is_ereg(u32 reg) { return (1 << reg) & (BIT(BPF_REG_5) | BIT(AUX_REG) | BIT(BPF_REG_7) | BIT(BPF_REG_8) | BIT(BPF_REG_9)); } /* add modifiers if 'reg' maps to x64 registers r8..r15 */ static u8 add_1mod(u8 byte, u32 reg) { if (is_ereg(reg)) byte |= 1; return byte; } static u8 add_2mod(u8 byte, u32 r1, u32 r2) { if (is_ereg(r1)) byte |= 1; if (is_ereg(r2)) byte |= 4; return byte; } /* encode 'dst_reg' register into x64 opcode 'byte' */ static u8 add_1reg(u8 byte, u32 dst_reg) { return byte + reg2hex[dst_reg]; } /* encode 'dst_reg' and 'src_reg' registers into x64 opcode 'byte' */ static u8 add_2reg(u8 byte, u32 dst_reg, u32 src_reg) { return byte + reg2hex[dst_reg] + (reg2hex[src_reg] << 3); } static void jit_fill_hole(void *area, unsigned int size) { /* fill whole space with int3 instructions */ memset(area, 0xcc, size); } struct jit_context { int cleanup_addr; /* epilogue code offset */ bool seen_ld_abs; }; /* maximum number of bytes emitted while JITing one eBPF insn */ #define BPF_MAX_INSN_SIZE 128 #define BPF_INSN_SAFETY 64 static int do_jit(struct bpf_prog *bpf_prog, int *addrs, u8 *image, int oldproglen, struct jit_context *ctx) { struct bpf_insn *insn = bpf_prog->insnsi; int insn_cnt = bpf_prog->len; bool seen_ld_abs = ctx->seen_ld_abs | (oldproglen == 0); bool seen_exit = false; u8 temp[BPF_MAX_INSN_SIZE + BPF_INSN_SAFETY]; int i; int proglen = 0; u8 *prog = temp; int stacksize = MAX_BPF_STACK + 32 /* space for rbx, r13, r14, r15 */ + 8 /* space for skb_copy_bits() buffer */; EMIT1(0x55); /* push rbp */ EMIT3(0x48, 0x89, 0xE5); /* mov rbp,rsp */ /* sub rsp, stacksize */ EMIT3_off32(0x48, 0x81, 0xEC, stacksize); /* all classic BPF filters use R6(rbx) save it */ /* mov qword ptr [rbp-X],rbx */ EMIT3_off32(0x48, 0x89, 0x9D, -stacksize); /* bpf_convert_filter() maps classic BPF register X to R7 and uses R8 * as temporary, so all tcpdump filters need to spill/fill R7(r13) and * R8(r14). R9(r15) spill could be made conditional, but there is only * one 'bpf_error' return path out of helper functions inside bpf_jit.S * The overhead of extra spill is negligible for any filter other * than synthetic ones. Therefore not worth adding complexity. */ /* mov qword ptr [rbp-X],r13 */ EMIT3_off32(0x4C, 0x89, 0xAD, -stacksize + 8); /* mov qword ptr [rbp-X],r14 */ EMIT3_off32(0x4C, 0x89, 0xB5, -stacksize + 16); /* mov qword ptr [rbp-X],r15 */ EMIT3_off32(0x4C, 0x89, 0xBD, -stacksize + 24); /* clear A and X registers */ EMIT2(0x31, 0xc0); /* xor eax, eax */ EMIT3(0x4D, 0x31, 0xED); /* xor r13, r13 */ if (seen_ld_abs) { /* r9d : skb->len - skb->data_len (headlen) * r10 : skb->data */ if (is_imm8(offsetof(struct sk_buff, len))) /* mov %r9d, off8(%rdi) */ EMIT4(0x44, 0x8b, 0x4f, offsetof(struct sk_buff, len)); else /* mov %r9d, off32(%rdi) */ EMIT3_off32(0x44, 0x8b, 0x8f, offsetof(struct sk_buff, len)); if (is_imm8(offsetof(struct sk_buff, data_len))) /* sub %r9d, off8(%rdi) */ EMIT4(0x44, 0x2b, 0x4f, offsetof(struct sk_buff, data_len)); else EMIT3_off32(0x44, 0x2b, 0x8f, offsetof(struct sk_buff, data_len)); if (is_imm8(offsetof(struct sk_buff, data))) /* mov %r10, off8(%rdi) */ EMIT4(0x4c, 0x8b, 0x57, offsetof(struct sk_buff, data)); else /* mov %r10, off32(%rdi) */ EMIT3_off32(0x4c, 0x8b, 0x97, offsetof(struct sk_buff, data)); } for (i = 0; i < insn_cnt; i++, insn++) { const s32 imm32 = insn->imm; u32 dst_reg = insn->dst_reg; u32 src_reg = insn->src_reg; u8 b1 = 0, b2 = 0, b3 = 0; s64 jmp_offset; u8 jmp_cond; int ilen; u8 *func; switch (insn->code) { /* ALU */ case BPF_ALU | BPF_ADD | BPF_X: case BPF_ALU | BPF_SUB | BPF_X: case BPF_ALU | BPF_AND | BPF_X: case BPF_ALU | BPF_OR | BPF_X: case BPF_ALU | BPF_XOR | BPF_X: case BPF_ALU64 | BPF_ADD | BPF_X: case BPF_ALU64 | BPF_SUB | BPF_X: case BPF_ALU64 | BPF_AND | BPF_X: case BPF_ALU64 | BPF_OR | BPF_X: case BPF_ALU64 | BPF_XOR | BPF_X: switch (BPF_OP(insn->code)) { case BPF_ADD: b2 = 0x01; break; case BPF_SUB: b2 = 0x29; break; case BPF_AND: b2 = 0x21; break; case BPF_OR: b2 = 0x09; break; case BPF_XOR: b2 = 0x31; break; } if (BPF_CLASS(insn->code) == BPF_ALU64) EMIT1(add_2mod(0x48, dst_reg, src_reg)); else if (is_ereg(dst_reg) || is_ereg(src_reg)) EMIT1(add_2mod(0x40, dst_reg, src_reg)); EMIT2(b2, add_2reg(0xC0, dst_reg, src_reg)); break; /* mov dst, src */ case BPF_ALU64 | BPF_MOV | BPF_X: EMIT_mov(dst_reg, src_reg); break; /* mov32 dst, src */ case BPF_ALU | BPF_MOV | BPF_X: if (is_ereg(dst_reg) || is_ereg(src_reg)) EMIT1(add_2mod(0x40, dst_reg, src_reg)); EMIT2(0x89, add_2reg(0xC0, dst_reg, src_reg)); break; /* neg dst */ case BPF_ALU | BPF_NEG: case BPF_ALU64 | BPF_NEG: if (BPF_CLASS(insn->code) == BPF_ALU64) EMIT1(add_1mod(0x48, dst_reg)); else if (is_ereg(dst_reg)) EMIT1(add_1mod(0x40, dst_reg)); EMIT2(0xF7, add_1reg(0xD8, dst_reg)); break; case BPF_ALU | BPF_ADD | BPF_K: case BPF_ALU | BPF_SUB | BPF_K: case BPF_ALU | BPF_AND | BPF_K: case BPF_ALU | BPF_OR | BPF_K: case BPF_ALU | BPF_XOR | BPF_K: case BPF_ALU64 | BPF_ADD | BPF_K: case BPF_ALU64 | BPF_SUB | BPF_K: case BPF_ALU64 | BPF_AND | BPF_K: case BPF_ALU64 | BPF_OR | BPF_K: case BPF_ALU64 | BPF_XOR | BPF_K: if (BPF_CLASS(insn->code) == BPF_ALU64) EMIT1(add_1mod(0x48, dst_reg)); else if (is_ereg(dst_reg)) EMIT1(add_1mod(0x40, dst_reg)); switch (BPF_OP(insn->code)) { case BPF_ADD: b3 = 0xC0; break; case BPF_SUB: b3 = 0xE8; break; case BPF_AND: b3 = 0xE0; break; case BPF_OR: b3 = 0xC8; break; case BPF_XOR: b3 = 0xF0; break; } if (is_imm8(imm32)) EMIT3(0x83, add_1reg(b3, dst_reg), imm32); else EMIT2_off32(0x81, add_1reg(b3, dst_reg), imm32); break; case BPF_ALU64 | BPF_MOV | BPF_K: /* optimization: if imm32 is positive, * use 'mov eax, imm32' (which zero-extends imm32) * to save 2 bytes */ if (imm32 < 0) { /* 'mov rax, imm32' sign extends imm32 */ b1 = add_1mod(0x48, dst_reg); b2 = 0xC7; b3 = 0xC0; EMIT3_off32(b1, b2, add_1reg(b3, dst_reg), imm32); break; } case BPF_ALU | BPF_MOV | BPF_K: /* mov %eax, imm32 */ if (is_ereg(dst_reg)) EMIT1(add_1mod(0x40, dst_reg)); EMIT1_off32(add_1reg(0xB8, dst_reg), imm32); break; case BPF_LD | BPF_IMM | BPF_DW: if (insn[1].code != 0 || insn[1].src_reg != 0 || insn[1].dst_reg != 0 || insn[1].off != 0) { /* verifier must catch invalid insns */ pr_err("invalid BPF_LD_IMM64 insn\n"); return -EINVAL; } /* movabsq %rax, imm64 */ EMIT2(add_1mod(0x48, dst_reg), add_1reg(0xB8, dst_reg)); EMIT(insn[0].imm, 4); EMIT(insn[1].imm, 4); insn++; i++; break; /* dst %= src, dst /= src, dst %= imm32, dst /= imm32 */ case BPF_ALU | BPF_MOD | BPF_X: case BPF_ALU | BPF_DIV | BPF_X: case BPF_ALU | BPF_MOD | BPF_K: case BPF_ALU | BPF_DIV | BPF_K: case BPF_ALU64 | BPF_MOD | BPF_X: case BPF_ALU64 | BPF_DIV | BPF_X: case BPF_ALU64 | BPF_MOD | BPF_K: case BPF_ALU64 | BPF_DIV | BPF_K: EMIT1(0x50); /* push rax */ EMIT1(0x52); /* push rdx */ if (BPF_SRC(insn->code) == BPF_X) /* mov r11, src_reg */ EMIT_mov(AUX_REG, src_reg); else /* mov r11, imm32 */ EMIT3_off32(0x49, 0xC7, 0xC3, imm32); /* mov rax, dst_reg */ EMIT_mov(BPF_REG_0, dst_reg); /* xor edx, edx * equivalent to 'xor rdx, rdx', but one byte less */ EMIT2(0x31, 0xd2); if (BPF_SRC(insn->code) == BPF_X) { /* if (src_reg == 0) return 0 */ /* cmp r11, 0 */ EMIT4(0x49, 0x83, 0xFB, 0x00); /* jne .+9 (skip over pop, pop, xor and jmp) */ EMIT2(X86_JNE, 1 + 1 + 2 + 5); EMIT1(0x5A); /* pop rdx */ EMIT1(0x58); /* pop rax */ EMIT2(0x31, 0xc0); /* xor eax, eax */ /* jmp cleanup_addr * addrs[i] - 11, because there are 11 bytes * after this insn: div, mov, pop, pop, mov */ jmp_offset = ctx->cleanup_addr - (addrs[i] - 11); EMIT1_off32(0xE9, jmp_offset); } if (BPF_CLASS(insn->code) == BPF_ALU64) /* div r11 */ EMIT3(0x49, 0xF7, 0xF3); else /* div r11d */ EMIT3(0x41, 0xF7, 0xF3); if (BPF_OP(insn->code) == BPF_MOD) /* mov r11, rdx */ EMIT3(0x49, 0x89, 0xD3); else /* mov r11, rax */ EMIT3(0x49, 0x89, 0xC3); EMIT1(0x5A); /* pop rdx */ EMIT1(0x58); /* pop rax */ /* mov dst_reg, r11 */ EMIT_mov(dst_reg, AUX_REG); break; case BPF_ALU | BPF_MUL | BPF_K: case BPF_ALU | BPF_MUL | BPF_X: case BPF_ALU64 | BPF_MUL | BPF_K: case BPF_ALU64 | BPF_MUL | BPF_X: EMIT1(0x50); /* push rax */ EMIT1(0x52); /* push rdx */ /* mov r11, dst_reg */ EMIT_mov(AUX_REG, dst_reg); if (BPF_SRC(insn->code) == BPF_X) /* mov rax, src_reg */ EMIT_mov(BPF_REG_0, src_reg); else /* mov rax, imm32 */ EMIT3_off32(0x48, 0xC7, 0xC0, imm32); if (BPF_CLASS(insn->code) == BPF_ALU64) EMIT1(add_1mod(0x48, AUX_REG)); else if (is_ereg(AUX_REG)) EMIT1(add_1mod(0x40, AUX_REG)); /* mul(q) r11 */ EMIT2(0xF7, add_1reg(0xE0, AUX_REG)); /* mov r11, rax */ EMIT_mov(AUX_REG, BPF_REG_0); EMIT1(0x5A); /* pop rdx */ EMIT1(0x58); /* pop rax */ /* mov dst_reg, r11 */ EMIT_mov(dst_reg, AUX_REG); break; /* shifts */ case BPF_ALU | BPF_LSH | BPF_K: case BPF_ALU | BPF_RSH | BPF_K: case BPF_ALU | BPF_ARSH | BPF_K: case BPF_ALU64 | BPF_LSH | BPF_K: case BPF_ALU64 | BPF_RSH | BPF_K: case BPF_ALU64 | BPF_ARSH | BPF_K: if (BPF_CLASS(insn->code) == BPF_ALU64) EMIT1(add_1mod(0x48, dst_reg)); else if (is_ereg(dst_reg)) EMIT1(add_1mod(0x40, dst_reg)); switch (BPF_OP(insn->code)) { case BPF_LSH: b3 = 0xE0; break; case BPF_RSH: b3 = 0xE8; break; case BPF_ARSH: b3 = 0xF8; break; } EMIT3(0xC1, add_1reg(b3, dst_reg), imm32); break; case BPF_ALU | BPF_LSH | BPF_X: case BPF_ALU | BPF_RSH | BPF_X: case BPF_ALU | BPF_ARSH | BPF_X: case BPF_ALU64 | BPF_LSH | BPF_X: case BPF_ALU64 | BPF_RSH | BPF_X: case BPF_ALU64 | BPF_ARSH | BPF_X: /* check for bad case when dst_reg == rcx */ if (dst_reg == BPF_REG_4) { /* mov r11, dst_reg */ EMIT_mov(AUX_REG, dst_reg); dst_reg = AUX_REG; } if (src_reg != BPF_REG_4) { /* common case */ EMIT1(0x51); /* push rcx */ /* mov rcx, src_reg */ EMIT_mov(BPF_REG_4, src_reg); } /* shl %rax, %cl | shr %rax, %cl | sar %rax, %cl */ if (BPF_CLASS(insn->code) == BPF_ALU64) EMIT1(add_1mod(0x48, dst_reg)); else if (is_ereg(dst_reg)) EMIT1(add_1mod(0x40, dst_reg)); switch (BPF_OP(insn->code)) { case BPF_LSH: b3 = 0xE0; break; case BPF_RSH: b3 = 0xE8; break; case BPF_ARSH: b3 = 0xF8; break; } EMIT2(0xD3, add_1reg(b3, dst_reg)); if (src_reg != BPF_REG_4) EMIT1(0x59); /* pop rcx */ if (insn->dst_reg == BPF_REG_4) /* mov dst_reg, r11 */ EMIT_mov(insn->dst_reg, AUX_REG); break; case BPF_ALU | BPF_END | BPF_FROM_BE: switch (imm32) { case 16: /* emit 'ror %ax, 8' to swap lower 2 bytes */ EMIT1(0x66); if (is_ereg(dst_reg)) EMIT1(0x41); EMIT3(0xC1, add_1reg(0xC8, dst_reg), 8); /* emit 'movzwl eax, ax' */ if (is_ereg(dst_reg)) EMIT3(0x45, 0x0F, 0xB7); else EMIT2(0x0F, 0xB7); EMIT1(add_2reg(0xC0, dst_reg, dst_reg)); break; case 32: /* emit 'bswap eax' to swap lower 4 bytes */ if (is_ereg(dst_reg)) EMIT2(0x41, 0x0F); else EMIT1(0x0F); EMIT1(add_1reg(0xC8, dst_reg)); break; case 64: /* emit 'bswap rax' to swap 8 bytes */ EMIT3(add_1mod(0x48, dst_reg), 0x0F, add_1reg(0xC8, dst_reg)); break; } break; case BPF_ALU | BPF_END | BPF_FROM_LE: switch (imm32) { case 16: /* emit 'movzwl eax, ax' to zero extend 16-bit * into 64 bit */ if (is_ereg(dst_reg)) EMIT3(0x45, 0x0F, 0xB7); else EMIT2(0x0F, 0xB7); EMIT1(add_2reg(0xC0, dst_reg, dst_reg)); break; case 32: /* emit 'mov eax, eax' to clear upper 32-bits */ if (is_ereg(dst_reg)) EMIT1(0x45); EMIT2(0x89, add_2reg(0xC0, dst_reg, dst_reg)); break; case 64: /* nop */ break; } break; /* ST: *(u8*)(dst_reg + off) = imm */ case BPF_ST | BPF_MEM | BPF_B: if (is_ereg(dst_reg)) EMIT2(0x41, 0xC6); else EMIT1(0xC6); goto st; case BPF_ST | BPF_MEM | BPF_H: if (is_ereg(dst_reg)) EMIT3(0x66, 0x41, 0xC7); else EMIT2(0x66, 0xC7); goto st; case BPF_ST | BPF_MEM | BPF_W: if (is_ereg(dst_reg)) EMIT2(0x41, 0xC7); else EMIT1(0xC7); goto st; case BPF_ST | BPF_MEM | BPF_DW: EMIT2(add_1mod(0x48, dst_reg), 0xC7); st: if (is_imm8(insn->off)) EMIT2(add_1reg(0x40, dst_reg), insn->off); else EMIT1_off32(add_1reg(0x80, dst_reg), insn->off); EMIT(imm32, bpf_size_to_x86_bytes(BPF_SIZE(insn->code))); break; /* STX: *(u8*)(dst_reg + off) = src_reg */ case BPF_STX | BPF_MEM | BPF_B: /* emit 'mov byte ptr [rax + off], al' */ if (is_ereg(dst_reg) || is_ereg(src_reg) || /* have to add extra byte for x86 SIL, DIL regs */ src_reg == BPF_REG_1 || src_reg == BPF_REG_2) EMIT2(add_2mod(0x40, dst_reg, src_reg), 0x88); else EMIT1(0x88); goto stx; case BPF_STX | BPF_MEM | BPF_H: if (is_ereg(dst_reg) || is_ereg(src_reg)) EMIT3(0x66, add_2mod(0x40, dst_reg, src_reg), 0x89); else EMIT2(0x66, 0x89); goto stx; case BPF_STX | BPF_MEM | BPF_W: if (is_ereg(dst_reg) || is_ereg(src_reg)) EMIT2(add_2mod(0x40, dst_reg, src_reg), 0x89); else EMIT1(0x89); goto stx; case BPF_STX | BPF_MEM | BPF_DW: EMIT2(add_2mod(0x48, dst_reg, src_reg), 0x89); stx: if (is_imm8(insn->off)) EMIT2(add_2reg(0x40, dst_reg, src_reg), insn->off); else EMIT1_off32(add_2reg(0x80, dst_reg, src_reg), insn->off); break; /* LDX: dst_reg = *(u8*)(src_reg + off) */ case BPF_LDX | BPF_MEM | BPF_B: /* emit 'movzx rax, byte ptr [rax + off]' */ EMIT3(add_2mod(0x48, src_reg, dst_reg), 0x0F, 0xB6); goto ldx; case BPF_LDX | BPF_MEM | BPF_H: /* emit 'movzx rax, word ptr [rax + off]' */ EMIT3(add_2mod(0x48, src_reg, dst_reg), 0x0F, 0xB7); goto ldx; case BPF_LDX | BPF_MEM | BPF_W: /* emit 'mov eax, dword ptr [rax+0x14]' */ if (is_ereg(dst_reg) || is_ereg(src_reg)) EMIT2(add_2mod(0x40, src_reg, dst_reg), 0x8B); else EMIT1(0x8B); goto ldx; case BPF_LDX | BPF_MEM | BPF_DW: /* emit 'mov rax, qword ptr [rax+0x14]' */ EMIT2(add_2mod(0x48, src_reg, dst_reg), 0x8B); ldx: /* if insn->off == 0 we can save one extra byte, but * special case of x86 r13 which always needs an offset * is not worth the hassle */ if (is_imm8(insn->off)) EMIT2(add_2reg(0x40, src_reg, dst_reg), insn->off); else EMIT1_off32(add_2reg(0x80, src_reg, dst_reg), insn->off); break; /* STX XADD: lock *(u32*)(dst_reg + off) += src_reg */ case BPF_STX | BPF_XADD | BPF_W: /* emit 'lock add dword ptr [rax + off], eax' */ if (is_ereg(dst_reg) || is_ereg(src_reg)) EMIT3(0xF0, add_2mod(0x40, dst_reg, src_reg), 0x01); else EMIT2(0xF0, 0x01); goto xadd; case BPF_STX | BPF_XADD | BPF_DW: EMIT3(0xF0, add_2mod(0x48, dst_reg, src_reg), 0x01); xadd: if (is_imm8(insn->off)) EMIT2(add_2reg(0x40, dst_reg, src_reg), insn->off); else EMIT1_off32(add_2reg(0x80, dst_reg, src_reg), insn->off); break; /* call */ case BPF_JMP | BPF_CALL: func = (u8 *) __bpf_call_base + imm32; jmp_offset = func - (image + addrs[i]); if (seen_ld_abs) { EMIT2(0x41, 0x52); /* push %r10 */ EMIT2(0x41, 0x51); /* push %r9 */ /* need to adjust jmp offset, since * pop %r9, pop %r10 take 4 bytes after call insn */ jmp_offset += 4; } if (!imm32 || !is_simm32(jmp_offset)) { pr_err("unsupported bpf func %d addr %p image %p\n", imm32, func, image); return -EINVAL; } EMIT1_off32(0xE8, jmp_offset); if (seen_ld_abs) { EMIT2(0x41, 0x59); /* pop %r9 */ EMIT2(0x41, 0x5A); /* pop %r10 */ } break; /* cond jump */ case BPF_JMP | BPF_JEQ | BPF_X: case BPF_JMP | BPF_JNE | BPF_X: case BPF_JMP | BPF_JGT | BPF_X: case BPF_JMP | BPF_JGE | BPF_X: case BPF_JMP | BPF_JSGT | BPF_X: case BPF_JMP | BPF_JSGE | BPF_X: /* cmp dst_reg, src_reg */ EMIT3(add_2mod(0x48, dst_reg, src_reg), 0x39, add_2reg(0xC0, dst_reg, src_reg)); goto emit_cond_jmp; case BPF_JMP | BPF_JSET | BPF_X: /* test dst_reg, src_reg */ EMIT3(add_2mod(0x48, dst_reg, src_reg), 0x85, add_2reg(0xC0, dst_reg, src_reg)); goto emit_cond_jmp; case BPF_JMP | BPF_JSET | BPF_K: /* test dst_reg, imm32 */ EMIT1(add_1mod(0x48, dst_reg)); EMIT2_off32(0xF7, add_1reg(0xC0, dst_reg), imm32); goto emit_cond_jmp; case BPF_JMP | BPF_JEQ | BPF_K: case BPF_JMP | BPF_JNE | BPF_K: case BPF_JMP | BPF_JGT | BPF_K: case BPF_JMP | BPF_JGE | BPF_K: case BPF_JMP | BPF_JSGT | BPF_K: case BPF_JMP | BPF_JSGE | BPF_K: /* cmp dst_reg, imm8/32 */ EMIT1(add_1mod(0x48, dst_reg)); if (is_imm8(imm32)) EMIT3(0x83, add_1reg(0xF8, dst_reg), imm32); else EMIT2_off32(0x81, add_1reg(0xF8, dst_reg), imm32); emit_cond_jmp: /* convert BPF opcode to x86 */ switch (BPF_OP(insn->code)) { case BPF_JEQ: jmp_cond = X86_JE; break; case BPF_JSET: case BPF_JNE: jmp_cond = X86_JNE; break; case BPF_JGT: /* GT is unsigned '>', JA in x86 */ jmp_cond = X86_JA; break; case BPF_JGE: /* GE is unsigned '>=', JAE in x86 */ jmp_cond = X86_JAE; break; case BPF_JSGT: /* signed '>', GT in x86 */ jmp_cond = X86_JG; break; case BPF_JSGE: /* signed '>=', GE in x86 */ jmp_cond = X86_JGE; break; default: /* to silence gcc warning */ return -EFAULT; } jmp_offset = addrs[i + insn->off] - addrs[i]; if (is_imm8(jmp_offset)) { EMIT2(jmp_cond, jmp_offset); } else if (is_simm32(jmp_offset)) { EMIT2_off32(0x0F, jmp_cond + 0x10, jmp_offset); } else { pr_err("cond_jmp gen bug %llx\n", jmp_offset); return -EFAULT; } break; case BPF_JMP | BPF_JA: jmp_offset = addrs[i + insn->off] - addrs[i]; if (!jmp_offset) /* optimize out nop jumps */ break; emit_jmp: if (is_imm8(jmp_offset)) { EMIT2(0xEB, jmp_offset); } else if (is_simm32(jmp_offset)) { EMIT1_off32(0xE9, jmp_offset); } else { pr_err("jmp gen bug %llx\n", jmp_offset); return -EFAULT; } break; case BPF_LD | BPF_IND | BPF_W: func = sk_load_word; goto common_load; case BPF_LD | BPF_ABS | BPF_W: func = CHOOSE_LOAD_FUNC(imm32, sk_load_word); common_load: ctx->seen_ld_abs = seen_ld_abs = true; jmp_offset = func - (image + addrs[i]); if (!func || !is_simm32(jmp_offset)) { pr_err("unsupported bpf func %d addr %p image %p\n", imm32, func, image); return -EINVAL; } if (BPF_MODE(insn->code) == BPF_ABS) { /* mov %esi, imm32 */ EMIT1_off32(0xBE, imm32); } else { /* mov %rsi, src_reg */ EMIT_mov(BPF_REG_2, src_reg); if (imm32) { if (is_imm8(imm32)) /* add %esi, imm8 */ EMIT3(0x83, 0xC6, imm32); else /* add %esi, imm32 */ EMIT2_off32(0x81, 0xC6, imm32); } } /* skb pointer is in R6 (%rbx), it will be copied into * %rdi if skb_copy_bits() call is necessary. * sk_load_* helpers also use %r10 and %r9d. * See bpf_jit.S */ EMIT1_off32(0xE8, jmp_offset); /* call */ break; case BPF_LD | BPF_IND | BPF_H: func = sk_load_half; goto common_load; case BPF_LD | BPF_ABS | BPF_H: func = CHOOSE_LOAD_FUNC(imm32, sk_load_half); goto common_load; case BPF_LD | BPF_IND | BPF_B: func = sk_load_byte; goto common_load; case BPF_LD | BPF_ABS | BPF_B: func = CHOOSE_LOAD_FUNC(imm32, sk_load_byte); goto common_load; case BPF_JMP | BPF_EXIT: if (seen_exit) { jmp_offset = ctx->cleanup_addr - addrs[i]; goto emit_jmp; } seen_exit = true; /* update cleanup_addr */ ctx->cleanup_addr = proglen; /* mov rbx, qword ptr [rbp-X] */ EMIT3_off32(0x48, 0x8B, 0x9D, -stacksize); /* mov r13, qword ptr [rbp-X] */ EMIT3_off32(0x4C, 0x8B, 0xAD, -stacksize + 8); /* mov r14, qword ptr [rbp-X] */ EMIT3_off32(0x4C, 0x8B, 0xB5, -stacksize + 16); /* mov r15, qword ptr [rbp-X] */ EMIT3_off32(0x4C, 0x8B, 0xBD, -stacksize + 24); EMIT1(0xC9); /* leave */ EMIT1(0xC3); /* ret */ break; default: /* By design x64 JIT should support all BPF instructions * This error will be seen if new instruction was added * to interpreter, but not to JIT * or if there is junk in bpf_prog */ pr_err("bpf_jit: unknown opcode %02x\n", insn->code); return -EINVAL; } ilen = prog - temp; if (ilen > BPF_MAX_INSN_SIZE) { pr_err("bpf_jit_compile fatal insn size error\n"); return -EFAULT; } if (image) { if (unlikely(proglen + ilen > oldproglen)) { pr_err("bpf_jit_compile fatal error\n"); return -EFAULT; } memcpy(image + proglen, temp, ilen); } proglen += ilen; addrs[i] = proglen; prog = temp; } return proglen; } void bpf_jit_compile(struct bpf_prog *prog) { } void bpf_int_jit_compile(struct bpf_prog *prog) { struct bpf_binary_header *header = NULL; int proglen, oldproglen = 0; struct jit_context ctx = {}; u8 *image = NULL; int *addrs; int pass; int i; if (!bpf_jit_enable) return; if (!prog || !prog->len) return; addrs = kmalloc(prog->len * sizeof(*addrs), GFP_KERNEL); if (!addrs) return; /* Before first pass, make a rough estimation of addrs[] * each bpf instruction is translated to less than 64 bytes */ for (proglen = 0, i = 0; i < prog->len; i++) { proglen += 64; addrs[i] = proglen; } ctx.cleanup_addr = proglen; for (pass = 0; pass < 10; pass++) { proglen = do_jit(prog, addrs, image, oldproglen, &ctx); if (proglen <= 0) { image = NULL; if (header) bpf_jit_binary_free(header); goto out; } if (image) { if (proglen != oldproglen) { pr_err("bpf_jit: proglen=%d != oldproglen=%d\n", proglen, oldproglen); goto out; } break; } if (proglen == oldproglen) { header = bpf_jit_binary_alloc(proglen, &image, 1, jit_fill_hole); if (!header) goto out; } oldproglen = proglen; } if (bpf_jit_enable > 1) bpf_jit_dump(prog->len, proglen, 0, image); if (image) { bpf_flush_icache(header, image + proglen); set_memory_ro((unsigned long)header, header->pages); prog->bpf_func = (void *)image; prog->jited = true; } out: kfree(addrs); } void bpf_jit_free(struct bpf_prog *fp) { unsigned long addr = (unsigned long)fp->bpf_func & PAGE_MASK; struct bpf_binary_header *header = (void *)addr; if (!fp->jited) goto free_filter; set_memory_rw(addr, header->pages); bpf_jit_binary_free(header); free_filter: bpf_prog_unlock_free(fp); }
./CrossVul/dataset_final_sorted/CWE-17/c/bad_1643_0
crossvul-cpp_data_bad_1629_0
/* ** $Id: ldo.c,v 2.38.1.4 2012/01/18 02:27:10 roberto Exp $ ** Stack and Call structure of Lua ** See Copyright Notice in lua.h */ #include <setjmp.h> #include <stdlib.h> #include <string.h> #define ldo_c #define LUA_CORE #include "lua.h" #include "ldebug.h" #include "ldo.h" #include "lfunc.h" #include "lgc.h" #include "lmem.h" #include "lobject.h" #include "lopcodes.h" #include "lparser.h" #include "lstate.h" #include "lstring.h" #include "ltable.h" #include "ltm.h" #include "lundump.h" #include "lvm.h" #include "lzio.h" /* ** {====================================================== ** Error-recovery functions ** ======================================================= */ /* chain list of long jump buffers */ struct lua_longjmp { struct lua_longjmp *previous; luai_jmpbuf b; volatile int status; /* error code */ }; void luaD_seterrorobj (lua_State *L, int errcode, StkId oldtop) { switch (errcode) { case LUA_ERRMEM: { setsvalue2s(L, oldtop, luaS_newliteral(L, MEMERRMSG)); break; } case LUA_ERRERR: { setsvalue2s(L, oldtop, luaS_newliteral(L, "error in error handling")); break; } case LUA_ERRSYNTAX: case LUA_ERRRUN: { setobjs2s(L, oldtop, L->top - 1); /* error message on current top */ break; } } L->top = oldtop + 1; } static void restore_stack_limit (lua_State *L) { lua_assert(L->stack_last - L->stack == L->stacksize - EXTRA_STACK - 1); if (L->size_ci > LUAI_MAXCALLS) { /* there was an overflow? */ int inuse = cast_int(L->ci - L->base_ci); if (inuse + 1 < LUAI_MAXCALLS) /* can `undo' overflow? */ luaD_reallocCI(L, LUAI_MAXCALLS); } } static void resetstack (lua_State *L, int status) { L->ci = L->base_ci; L->base = L->ci->base; luaF_close(L, L->base); /* close eventual pending closures */ luaD_seterrorobj(L, status, L->base); L->nCcalls = L->baseCcalls; L->allowhook = 1; restore_stack_limit(L); L->errfunc = 0; L->errorJmp = NULL; } void luaD_throw (lua_State *L, int errcode) { if (L->errorJmp) { L->errorJmp->status = errcode; LUAI_THROW(L, L->errorJmp); } else { L->status = cast_byte(errcode); if (G(L)->panic) { resetstack(L, errcode); lua_unlock(L); G(L)->panic(L); } exit(EXIT_FAILURE); } } int luaD_rawrunprotected (lua_State *L, Pfunc f, void *ud) { struct lua_longjmp lj; lj.status = 0; lj.previous = L->errorJmp; /* chain new error handler */ L->errorJmp = &lj; LUAI_TRY(L, &lj, (*f)(L, ud); ); L->errorJmp = lj.previous; /* restore old error handler */ return lj.status; } /* }====================================================== */ static void correctstack (lua_State *L, TValue *oldstack) { CallInfo *ci; GCObject *up; L->top = (L->top - oldstack) + L->stack; for (up = L->openupval; up != NULL; up = up->gch.next) gco2uv(up)->v = (gco2uv(up)->v - oldstack) + L->stack; for (ci = L->base_ci; ci <= L->ci; ci++) { ci->top = (ci->top - oldstack) + L->stack; ci->base = (ci->base - oldstack) + L->stack; ci->func = (ci->func - oldstack) + L->stack; } L->base = (L->base - oldstack) + L->stack; } void luaD_reallocstack (lua_State *L, int newsize) { TValue *oldstack = L->stack; int realsize = newsize + 1 + EXTRA_STACK; lua_assert(L->stack_last - L->stack == L->stacksize - EXTRA_STACK - 1); luaM_reallocvector(L, L->stack, L->stacksize, realsize, TValue); L->stacksize = realsize; L->stack_last = L->stack+newsize; correctstack(L, oldstack); } void luaD_reallocCI (lua_State *L, int newsize) { CallInfo *oldci = L->base_ci; luaM_reallocvector(L, L->base_ci, L->size_ci, newsize, CallInfo); L->size_ci = newsize; L->ci = (L->ci - oldci) + L->base_ci; L->end_ci = L->base_ci + L->size_ci - 1; } void luaD_growstack (lua_State *L, int n) { if (n <= L->stacksize) /* double size is enough? */ luaD_reallocstack(L, 2*L->stacksize); else luaD_reallocstack(L, L->stacksize + n); } static CallInfo *growCI (lua_State *L) { if (L->size_ci > LUAI_MAXCALLS) /* overflow while handling overflow? */ luaD_throw(L, LUA_ERRERR); else { luaD_reallocCI(L, 2*L->size_ci); if (L->size_ci > LUAI_MAXCALLS) luaG_runerror(L, "stack overflow"); } return ++L->ci; } void luaD_callhook (lua_State *L, int event, int line) { lua_Hook hook = L->hook; if (hook && L->allowhook) { ptrdiff_t top = savestack(L, L->top); ptrdiff_t ci_top = savestack(L, L->ci->top); lua_Debug ar; ar.event = event; ar.currentline = line; if (event == LUA_HOOKTAILRET) ar.i_ci = 0; /* tail call; no debug information about it */ else ar.i_ci = cast_int(L->ci - L->base_ci); luaD_checkstack(L, LUA_MINSTACK); /* ensure minimum stack size */ L->ci->top = L->top + LUA_MINSTACK; lua_assert(L->ci->top <= L->stack_last); L->allowhook = 0; /* cannot call hooks inside a hook */ lua_unlock(L); (*hook)(L, &ar); lua_lock(L); lua_assert(!L->allowhook); L->allowhook = 1; L->ci->top = restorestack(L, ci_top); L->top = restorestack(L, top); } } static StkId adjust_varargs (lua_State *L, Proto *p, int actual) { int i; int nfixargs = p->numparams; Table *htab = NULL; StkId base, fixed; for (; actual < nfixargs; ++actual) setnilvalue(L->top++); #if defined(LUA_COMPAT_VARARG) if (p->is_vararg & VARARG_NEEDSARG) { /* compat. with old-style vararg? */ int nvar = actual - nfixargs; /* number of extra arguments */ lua_assert(p->is_vararg & VARARG_HASARG); luaC_checkGC(L); luaD_checkstack(L, p->maxstacksize); htab = luaH_new(L, nvar, 1); /* create `arg' table */ for (i=0; i<nvar; i++) /* put extra arguments into `arg' table */ setobj2n(L, luaH_setnum(L, htab, i+1), L->top - nvar + i); /* store counter in field `n' */ setnvalue(luaH_setstr(L, htab, luaS_newliteral(L, "n")), cast_num(nvar)); } #endif /* move fixed parameters to final position */ fixed = L->top - actual; /* first fixed argument */ base = L->top; /* final position of first argument */ for (i=0; i<nfixargs; i++) { setobjs2s(L, L->top++, fixed+i); setnilvalue(fixed+i); } /* add `arg' parameter */ if (htab) { sethvalue(L, L->top++, htab); lua_assert(iswhite(obj2gco(htab))); } return base; } static StkId tryfuncTM (lua_State *L, StkId func) { const TValue *tm = luaT_gettmbyobj(L, func, TM_CALL); StkId p; ptrdiff_t funcr = savestack(L, func); if (!ttisfunction(tm)) luaG_typeerror(L, func, "call"); /* Open a hole inside the stack at `func' */ for (p = L->top; p > func; p--) setobjs2s(L, p, p-1); incr_top(L); func = restorestack(L, funcr); /* previous call may change stack */ setobj2s(L, func, tm); /* tag method is the new function to be called */ return func; } #define inc_ci(L) \ ((L->ci == L->end_ci) ? growCI(L) : \ (condhardstacktests(luaD_reallocCI(L, L->size_ci)), ++L->ci)) int luaD_precall (lua_State *L, StkId func, int nresults) { LClosure *cl; ptrdiff_t funcr; if (!ttisfunction(func)) /* `func' is not a function? */ func = tryfuncTM(L, func); /* check the `function' tag method */ funcr = savestack(L, func); cl = &clvalue(func)->l; L->ci->savedpc = L->savedpc; if (!cl->isC) { /* Lua function? prepare its call */ CallInfo *ci; StkId st, base; Proto *p = cl->p; luaD_checkstack(L, p->maxstacksize); func = restorestack(L, funcr); if (!p->is_vararg) { /* no varargs? */ base = func + 1; if (L->top > base + p->numparams) L->top = base + p->numparams; } else { /* vararg function */ int nargs = cast_int(L->top - func) - 1; base = adjust_varargs(L, p, nargs); func = restorestack(L, funcr); /* previous call may change the stack */ } ci = inc_ci(L); /* now `enter' new function */ ci->func = func; L->base = ci->base = base; ci->top = L->base + p->maxstacksize; lua_assert(ci->top <= L->stack_last); L->savedpc = p->code; /* starting point */ ci->tailcalls = 0; ci->nresults = nresults; for (st = L->top; st < ci->top; st++) setnilvalue(st); L->top = ci->top; if (L->hookmask & LUA_MASKCALL) { L->savedpc++; /* hooks assume 'pc' is already incremented */ luaD_callhook(L, LUA_HOOKCALL, -1); L->savedpc--; /* correct 'pc' */ } return PCRLUA; } else { /* if is a C function, call it */ CallInfo *ci; int n; luaD_checkstack(L, LUA_MINSTACK); /* ensure minimum stack size */ ci = inc_ci(L); /* now `enter' new function */ ci->func = restorestack(L, funcr); L->base = ci->base = ci->func + 1; ci->top = L->top + LUA_MINSTACK; lua_assert(ci->top <= L->stack_last); ci->nresults = nresults; if (L->hookmask & LUA_MASKCALL) luaD_callhook(L, LUA_HOOKCALL, -1); lua_unlock(L); n = (*curr_func(L)->c.f)(L); /* do the actual call */ lua_lock(L); if (n < 0) /* yielding? */ return PCRYIELD; else { luaD_poscall(L, L->top - n); return PCRC; } } } static StkId callrethooks (lua_State *L, StkId firstResult) { ptrdiff_t fr = savestack(L, firstResult); /* next call may change stack */ luaD_callhook(L, LUA_HOOKRET, -1); if (f_isLua(L->ci)) { /* Lua function? */ while ((L->hookmask & LUA_MASKRET) && L->ci->tailcalls--) /* tail calls */ luaD_callhook(L, LUA_HOOKTAILRET, -1); } return restorestack(L, fr); } int luaD_poscall (lua_State *L, StkId firstResult) { StkId res; int wanted, i; CallInfo *ci; if (L->hookmask & LUA_MASKRET) firstResult = callrethooks(L, firstResult); ci = L->ci--; res = ci->func; /* res == final position of 1st result */ wanted = ci->nresults; L->base = (ci - 1)->base; /* restore base */ L->savedpc = (ci - 1)->savedpc; /* restore savedpc */ /* move results to correct place */ for (i = wanted; i != 0 && firstResult < L->top; i--) setobjs2s(L, res++, firstResult++); while (i-- > 0) setnilvalue(res++); L->top = res; return (wanted - LUA_MULTRET); /* 0 iff wanted == LUA_MULTRET */ } /* ** Call a function (C or Lua). The function to be called is at *func. ** The arguments are on the stack, right after the function. ** When returns, all the results are on the stack, starting at the original ** function position. */ void luaD_call (lua_State *L, StkId func, int nResults) { if (++L->nCcalls >= LUAI_MAXCCALLS) { if (L->nCcalls == LUAI_MAXCCALLS) luaG_runerror(L, "C stack overflow"); else if (L->nCcalls >= (LUAI_MAXCCALLS + (LUAI_MAXCCALLS>>3))) luaD_throw(L, LUA_ERRERR); /* error while handing stack error */ } if (luaD_precall(L, func, nResults) == PCRLUA) /* is a Lua function? */ luaV_execute(L, 1); /* call it */ L->nCcalls--; luaC_checkGC(L); } static void resume (lua_State *L, void *ud) { StkId firstArg = cast(StkId, ud); CallInfo *ci = L->ci; if (L->status == 0) { /* start coroutine? */ lua_assert(ci == L->base_ci && firstArg > L->base); if (luaD_precall(L, firstArg - 1, LUA_MULTRET) != PCRLUA) return; } else { /* resuming from previous yield */ lua_assert(L->status == LUA_YIELD); L->status = 0; if (!f_isLua(ci)) { /* `common' yield? */ /* finish interrupted execution of `OP_CALL' */ lua_assert(GET_OPCODE(*((ci-1)->savedpc - 1)) == OP_CALL || GET_OPCODE(*((ci-1)->savedpc - 1)) == OP_TAILCALL); if (luaD_poscall(L, firstArg)) /* complete it... */ L->top = L->ci->top; /* and correct top if not multiple results */ } else /* yielded inside a hook: just continue its execution */ L->base = L->ci->base; } luaV_execute(L, cast_int(L->ci - L->base_ci)); } static int resume_error (lua_State *L, const char *msg) { L->top = L->ci->base; setsvalue2s(L, L->top, luaS_new(L, msg)); incr_top(L); lua_unlock(L); return LUA_ERRRUN; } LUA_API int lua_resume (lua_State *L, int nargs) { int status; lua_lock(L); if (L->status != LUA_YIELD && (L->status != 0 || L->ci != L->base_ci)) return resume_error(L, "cannot resume non-suspended coroutine"); if (L->nCcalls >= LUAI_MAXCCALLS) return resume_error(L, "C stack overflow"); luai_userstateresume(L, nargs); lua_assert(L->errfunc == 0); L->baseCcalls = ++L->nCcalls; status = luaD_rawrunprotected(L, resume, L->top - nargs); if (status != 0) { /* error? */ L->status = cast_byte(status); /* mark thread as `dead' */ luaD_seterrorobj(L, status, L->top); L->ci->top = L->top; } else { lua_assert(L->nCcalls == L->baseCcalls); status = L->status; } --L->nCcalls; lua_unlock(L); return status; } LUA_API int lua_yield (lua_State *L, int nresults) { luai_userstateyield(L, nresults); lua_lock(L); if (L->nCcalls > L->baseCcalls) luaG_runerror(L, "attempt to yield across metamethod/C-call boundary"); L->base = L->top - nresults; /* protect stack slots below */ L->status = LUA_YIELD; lua_unlock(L); return -1; } int luaD_pcall (lua_State *L, Pfunc func, void *u, ptrdiff_t old_top, ptrdiff_t ef) { int status; unsigned short oldnCcalls = L->nCcalls; ptrdiff_t old_ci = saveci(L, L->ci); lu_byte old_allowhooks = L->allowhook; ptrdiff_t old_errfunc = L->errfunc; L->errfunc = ef; status = luaD_rawrunprotected(L, func, u); if (status != 0) { /* an error occurred? */ StkId oldtop = restorestack(L, old_top); luaF_close(L, oldtop); /* close eventual pending closures */ luaD_seterrorobj(L, status, oldtop); L->nCcalls = oldnCcalls; L->ci = restoreci(L, old_ci); L->base = L->ci->base; L->savedpc = L->ci->savedpc; L->allowhook = old_allowhooks; restore_stack_limit(L); } L->errfunc = old_errfunc; return status; } /* ** Execute a protected parser. */ struct SParser { /* data to `f_parser' */ ZIO *z; Mbuffer buff; /* buffer to be used by the scanner */ const char *name; }; static void f_parser (lua_State *L, void *ud) { int i; Proto *tf; Closure *cl; struct SParser *p = cast(struct SParser *, ud); int c = luaZ_lookahead(p->z); luaC_checkGC(L); tf = ((c == LUA_SIGNATURE[0]) ? luaU_undump : luaY_parser)(L, p->z, &p->buff, p->name); cl = luaF_newLclosure(L, tf->nups, hvalue(gt(L))); cl->l.p = tf; for (i = 0; i < tf->nups; i++) /* initialize eventual upvalues */ cl->l.upvals[i] = luaF_newupval(L); setclvalue(L, L->top, cl); incr_top(L); } int luaD_protectedparser (lua_State *L, ZIO *z, const char *name) { struct SParser p; int status; p.z = z; p.name = name; luaZ_initbuffer(L, &p.buff); status = luaD_pcall(L, f_parser, &p, savestack(L, L->top), L->errfunc); luaZ_freebuffer(L, &p.buff); return status; }
./CrossVul/dataset_final_sorted/CWE-17/c/bad_1629_0
crossvul-cpp_data_good_2348_3
/* * Copyright (C) 1991, 1992 Linus Torvalds * Copyright (C) 2000, 2001, 2002 Andi Kleen, SuSE Labs */ #include <linux/kallsyms.h> #include <linux/kprobes.h> #include <linux/uaccess.h> #include <linux/hardirq.h> #include <linux/kdebug.h> #include <linux/module.h> #include <linux/ptrace.h> #include <linux/kexec.h> #include <linux/sysfs.h> #include <linux/bug.h> #include <linux/nmi.h> #include <asm/stacktrace.h> #define N_EXCEPTION_STACKS_END \ (N_EXCEPTION_STACKS + DEBUG_STKSZ/EXCEPTION_STKSZ - 2) static char x86_stack_ids[][8] = { [ DEBUG_STACK-1 ] = "#DB", [ NMI_STACK-1 ] = "NMI", [ DOUBLEFAULT_STACK-1 ] = "#DF", [ MCE_STACK-1 ] = "#MC", #if DEBUG_STKSZ > EXCEPTION_STKSZ [ N_EXCEPTION_STACKS ... N_EXCEPTION_STACKS_END ] = "#DB[?]" #endif }; static unsigned long *in_exception_stack(unsigned cpu, unsigned long stack, unsigned *usedp, char **idp) { unsigned k; /* * Iterate over all exception stacks, and figure out whether * 'stack' is in one of them: */ for (k = 0; k < N_EXCEPTION_STACKS; k++) { unsigned long end = per_cpu(orig_ist, cpu).ist[k]; /* * Is 'stack' above this exception frame's end? * If yes then skip to the next frame. */ if (stack >= end) continue; /* * Is 'stack' above this exception frame's start address? * If yes then we found the right frame. */ if (stack >= end - EXCEPTION_STKSZ) { /* * Make sure we only iterate through an exception * stack once. If it comes up for the second time * then there's something wrong going on - just * break out and return NULL: */ if (*usedp & (1U << k)) break; *usedp |= 1U << k; *idp = x86_stack_ids[k]; return (unsigned long *)end; } /* * If this is a debug stack, and if it has a larger size than * the usual exception stacks, then 'stack' might still * be within the lower portion of the debug stack: */ #if DEBUG_STKSZ > EXCEPTION_STKSZ if (k == DEBUG_STACK - 1 && stack >= end - DEBUG_STKSZ) { unsigned j = N_EXCEPTION_STACKS - 1; /* * Black magic. A large debug stack is composed of * multiple exception stack entries, which we * iterate through now. Dont look: */ do { ++j; end -= EXCEPTION_STKSZ; x86_stack_ids[j][4] = '1' + (j - N_EXCEPTION_STACKS); } while (stack < end - EXCEPTION_STKSZ); if (*usedp & (1U << j)) break; *usedp |= 1U << j; *idp = x86_stack_ids[j]; return (unsigned long *)end; } #endif } return NULL; } static inline int in_irq_stack(unsigned long *stack, unsigned long *irq_stack, unsigned long *irq_stack_end) { return (stack >= irq_stack && stack < irq_stack_end); } static const unsigned long irq_stack_size = (IRQ_STACK_SIZE - 64) / sizeof(unsigned long); enum stack_type { STACK_IS_UNKNOWN, STACK_IS_NORMAL, STACK_IS_EXCEPTION, STACK_IS_IRQ, }; static enum stack_type analyze_stack(int cpu, struct task_struct *task, unsigned long *stack, unsigned long **stack_end, unsigned long *irq_stack, unsigned *used, char **id) { unsigned long addr; addr = ((unsigned long)stack & (~(THREAD_SIZE - 1))); if ((unsigned long)task_stack_page(task) == addr) return STACK_IS_NORMAL; *stack_end = in_exception_stack(cpu, (unsigned long)stack, used, id); if (*stack_end) return STACK_IS_EXCEPTION; if (!irq_stack) return STACK_IS_NORMAL; *stack_end = irq_stack; irq_stack = irq_stack - irq_stack_size; if (in_irq_stack(stack, irq_stack, *stack_end)) return STACK_IS_IRQ; return STACK_IS_UNKNOWN; } /* * x86-64 can have up to three kernel stacks: * process stack * interrupt stack * severe exception (double fault, nmi, stack fault, debug, mce) hardware stack */ void dump_trace(struct task_struct *task, struct pt_regs *regs, unsigned long *stack, unsigned long bp, const struct stacktrace_ops *ops, void *data) { const unsigned cpu = get_cpu(); struct thread_info *tinfo; unsigned long *irq_stack = (unsigned long *)per_cpu(irq_stack_ptr, cpu); unsigned long dummy; unsigned used = 0; int graph = 0; int done = 0; if (!task) task = current; if (!stack) { if (regs) stack = (unsigned long *)regs->sp; else if (task != current) stack = (unsigned long *)task->thread.sp; else stack = &dummy; } if (!bp) bp = stack_frame(task, regs); /* * Print function call entries in all stacks, starting at the * current stack address. If the stacks consist of nested * exceptions */ tinfo = task_thread_info(task); while (!done) { unsigned long *stack_end; enum stack_type stype; char *id; stype = analyze_stack(cpu, task, stack, &stack_end, irq_stack, &used, &id); /* Default finish unless specified to continue */ done = 1; switch (stype) { /* Break out early if we are on the thread stack */ case STACK_IS_NORMAL: break; case STACK_IS_EXCEPTION: if (ops->stack(data, id) < 0) break; bp = ops->walk_stack(tinfo, stack, bp, ops, data, stack_end, &graph); ops->stack(data, "<EOE>"); /* * We link to the next stack via the * second-to-last pointer (index -2 to end) in the * exception stack: */ stack = (unsigned long *) stack_end[-2]; done = 0; break; case STACK_IS_IRQ: if (ops->stack(data, "IRQ") < 0) break; bp = ops->walk_stack(tinfo, stack, bp, ops, data, stack_end, &graph); /* * We link to the next stack (which would be * the process stack normally) the last * pointer (index -1 to end) in the IRQ stack: */ stack = (unsigned long *) (stack_end[-1]); irq_stack = NULL; ops->stack(data, "EOI"); done = 0; break; case STACK_IS_UNKNOWN: ops->stack(data, "UNK"); break; } } /* * This handles the process stack: */ bp = ops->walk_stack(tinfo, stack, bp, ops, data, NULL, &graph); put_cpu(); } EXPORT_SYMBOL(dump_trace); void show_stack_log_lvl(struct task_struct *task, struct pt_regs *regs, unsigned long *sp, unsigned long bp, char *log_lvl) { unsigned long *irq_stack_end; unsigned long *irq_stack; unsigned long *stack; int cpu; int i; preempt_disable(); cpu = smp_processor_id(); irq_stack_end = (unsigned long *)(per_cpu(irq_stack_ptr, cpu)); irq_stack = (unsigned long *)(per_cpu(irq_stack_ptr, cpu) - IRQ_STACK_SIZE); /* * Debugging aid: "show_stack(NULL, NULL);" prints the * back trace for this cpu: */ if (sp == NULL) { if (task) sp = (unsigned long *)task->thread.sp; else sp = (unsigned long *)&sp; } stack = sp; for (i = 0; i < kstack_depth_to_print; i++) { if (stack >= irq_stack && stack <= irq_stack_end) { if (stack == irq_stack_end) { stack = (unsigned long *) (irq_stack_end[-1]); pr_cont(" <EOI> "); } } else { if (((long) stack & (THREAD_SIZE-1)) == 0) break; } if (i && ((i % STACKSLOTS_PER_LINE) == 0)) pr_cont("\n"); pr_cont(" %016lx", *stack++); touch_nmi_watchdog(); } preempt_enable(); pr_cont("\n"); show_trace_log_lvl(task, regs, sp, bp, log_lvl); } void show_regs(struct pt_regs *regs) { int i; unsigned long sp; sp = regs->sp; show_regs_print_info(KERN_DEFAULT); __show_regs(regs, 1); /* * When in-kernel, we also print out the stack and code at the * time of the fault.. */ if (!user_mode(regs)) { unsigned int code_prologue = code_bytes * 43 / 64; unsigned int code_len = code_bytes; unsigned char c; u8 *ip; printk(KERN_DEFAULT "Stack:\n"); show_stack_log_lvl(NULL, regs, (unsigned long *)sp, 0, KERN_DEFAULT); printk(KERN_DEFAULT "Code: "); ip = (u8 *)regs->ip - code_prologue; if (ip < (u8 *)PAGE_OFFSET || probe_kernel_address(ip, c)) { /* try starting at IP */ ip = (u8 *)regs->ip; code_len = code_len - code_prologue + 1; } for (i = 0; i < code_len; i++, ip++) { if (ip < (u8 *)PAGE_OFFSET || probe_kernel_address(ip, c)) { pr_cont(" Bad RIP value."); break; } if (ip == (u8 *)regs->ip) pr_cont("<%02x> ", c); else pr_cont("%02x ", c); } } pr_cont("\n"); } int is_valid_bugaddr(unsigned long ip) { unsigned short ud2; if (__copy_from_user(&ud2, (const void __user *) ip, sizeof(ud2))) return 0; return ud2 == 0x0b0f; }
./CrossVul/dataset_final_sorted/CWE-17/c/good_2348_3
crossvul-cpp_data_good_2306_2
/* * linux/fs/open.c * * Copyright (C) 1991, 1992 Linus Torvalds */ #include <linux/string.h> #include <linux/mm.h> #include <linux/file.h> #include <linux/fdtable.h> #include <linux/fsnotify.h> #include <linux/module.h> #include <linux/tty.h> #include <linux/namei.h> #include <linux/backing-dev.h> #include <linux/capability.h> #include <linux/securebits.h> #include <linux/security.h> #include <linux/mount.h> #include <linux/fcntl.h> #include <linux/slab.h> #include <asm/uaccess.h> #include <linux/fs.h> #include <linux/personality.h> #include <linux/pagemap.h> #include <linux/syscalls.h> #include <linux/rcupdate.h> #include <linux/audit.h> #include <linux/falloc.h> #include <linux/fs_struct.h> #include <linux/ima.h> #include <linux/dnotify.h> #include <linux/compat.h> #include "internal.h" int do_truncate(struct dentry *dentry, loff_t length, unsigned int time_attrs, struct file *filp) { int ret; struct iattr newattrs; /* Not pretty: "inode->i_size" shouldn't really be signed. But it is. */ if (length < 0) return -EINVAL; newattrs.ia_size = length; newattrs.ia_valid = ATTR_SIZE | time_attrs; if (filp) { newattrs.ia_file = filp; newattrs.ia_valid |= ATTR_FILE; } /* Remove suid/sgid on truncate too */ ret = should_remove_suid(dentry); if (ret) newattrs.ia_valid |= ret | ATTR_FORCE; mutex_lock(&dentry->d_inode->i_mutex); ret = notify_change(dentry, &newattrs); mutex_unlock(&dentry->d_inode->i_mutex); return ret; } long vfs_truncate(struct path *path, loff_t length) { struct inode *inode; long error; inode = path->dentry->d_inode; /* For directories it's -EISDIR, for other non-regulars - -EINVAL */ if (S_ISDIR(inode->i_mode)) return -EISDIR; if (!S_ISREG(inode->i_mode)) return -EINVAL; error = mnt_want_write(path->mnt); if (error) goto out; error = inode_permission(inode, MAY_WRITE); if (error) goto mnt_drop_write_and_out; error = -EPERM; if (IS_APPEND(inode)) goto mnt_drop_write_and_out; error = get_write_access(inode); if (error) goto mnt_drop_write_and_out; /* * Make sure that there are no leases. get_write_access() protects * against the truncate racing with a lease-granting setlease(). */ error = break_lease(inode, O_WRONLY); if (error) goto put_write_and_out; error = locks_verify_truncate(inode, NULL, length); if (!error) error = security_path_truncate(path); if (!error) error = do_truncate(path->dentry, length, 0, NULL); put_write_and_out: put_write_access(inode); mnt_drop_write_and_out: mnt_drop_write(path->mnt); out: return error; } EXPORT_SYMBOL_GPL(vfs_truncate); static long do_sys_truncate(const char __user *pathname, loff_t length) { unsigned int lookup_flags = LOOKUP_FOLLOW; struct path path; int error; if (length < 0) /* sorry, but loff_t says... */ return -EINVAL; retry: error = user_path_at(AT_FDCWD, pathname, lookup_flags, &path); if (!error) { error = vfs_truncate(&path, length); path_put(&path); } if (retry_estale(error, lookup_flags)) { lookup_flags |= LOOKUP_REVAL; goto retry; } return error; } SYSCALL_DEFINE2(truncate, const char __user *, path, long, length) { return do_sys_truncate(path, length); } #ifdef CONFIG_COMPAT COMPAT_SYSCALL_DEFINE2(truncate, const char __user *, path, compat_off_t, length) { return do_sys_truncate(path, length); } #endif static long do_sys_ftruncate(unsigned int fd, loff_t length, int small) { struct inode *inode; struct dentry *dentry; struct fd f; int error; error = -EINVAL; if (length < 0) goto out; error = -EBADF; f = fdget(fd); if (!f.file) goto out; /* explicitly opened as large or we are on 64-bit box */ if (f.file->f_flags & O_LARGEFILE) small = 0; dentry = f.file->f_path.dentry; inode = dentry->d_inode; error = -EINVAL; if (!S_ISREG(inode->i_mode) || !(f.file->f_mode & FMODE_WRITE)) goto out_putf; error = -EINVAL; /* Cannot ftruncate over 2^31 bytes without large file support */ if (small && length > MAX_NON_LFS) goto out_putf; error = -EPERM; if (IS_APPEND(inode)) goto out_putf; sb_start_write(inode->i_sb); error = locks_verify_truncate(inode, f.file, length); if (!error) error = security_path_truncate(&f.file->f_path); if (!error) error = do_truncate(dentry, length, ATTR_MTIME|ATTR_CTIME, f.file); sb_end_write(inode->i_sb); out_putf: fdput(f); out: return error; } SYSCALL_DEFINE2(ftruncate, unsigned int, fd, unsigned long, length) { return do_sys_ftruncate(fd, length, 1); } #ifdef CONFIG_COMPAT COMPAT_SYSCALL_DEFINE2(ftruncate, unsigned int, fd, compat_ulong_t, length) { return do_sys_ftruncate(fd, length, 1); } #endif /* LFS versions of truncate are only needed on 32 bit machines */ #if BITS_PER_LONG == 32 SYSCALL_DEFINE2(truncate64, const char __user *, path, loff_t, length) { return do_sys_truncate(path, length); } SYSCALL_DEFINE2(ftruncate64, unsigned int, fd, loff_t, length) { return do_sys_ftruncate(fd, length, 0); } #endif /* BITS_PER_LONG == 32 */ int do_fallocate(struct file *file, int mode, loff_t offset, loff_t len) { struct inode *inode = file_inode(file); long ret; if (offset < 0 || len <= 0) return -EINVAL; /* Return error if mode is not supported */ if (mode & ~(FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE)) return -EOPNOTSUPP; /* Punch hole must have keep size set */ if ((mode & FALLOC_FL_PUNCH_HOLE) && !(mode & FALLOC_FL_KEEP_SIZE)) return -EOPNOTSUPP; if (!(file->f_mode & FMODE_WRITE)) return -EBADF; /* It's not possible punch hole on append only file */ if (mode & FALLOC_FL_PUNCH_HOLE && IS_APPEND(inode)) return -EPERM; if (IS_IMMUTABLE(inode)) return -EPERM; /* * Revalidate the write permissions, in case security policy has * changed since the files were opened. */ ret = security_file_permission(file, MAY_WRITE); if (ret) return ret; if (S_ISFIFO(inode->i_mode)) return -ESPIPE; /* * Let individual file system decide if it supports preallocation * for directories or not. */ if (!S_ISREG(inode->i_mode) && !S_ISDIR(inode->i_mode)) return -ENODEV; /* Check for wrap through zero too */ if (((offset + len) > inode->i_sb->s_maxbytes) || ((offset + len) < 0)) return -EFBIG; if (!file->f_op->fallocate) return -EOPNOTSUPP; sb_start_write(inode->i_sb); ret = file->f_op->fallocate(file, mode, offset, len); sb_end_write(inode->i_sb); return ret; } SYSCALL_DEFINE4(fallocate, int, fd, int, mode, loff_t, offset, loff_t, len) { struct fd f = fdget(fd); int error = -EBADF; if (f.file) { error = do_fallocate(f.file, mode, offset, len); fdput(f); } return error; } /* * access() needs to use the real uid/gid, not the effective uid/gid. * We do this by temporarily clearing all FS-related capabilities and * switching the fsuid/fsgid around to the real ones. */ SYSCALL_DEFINE3(faccessat, int, dfd, const char __user *, filename, int, mode) { const struct cred *old_cred; struct cred *override_cred; struct path path; struct inode *inode; int res; unsigned int lookup_flags = LOOKUP_FOLLOW; if (mode & ~S_IRWXO) /* where's F_OK, X_OK, W_OK, R_OK? */ return -EINVAL; override_cred = prepare_creds(); if (!override_cred) return -ENOMEM; override_cred->fsuid = override_cred->uid; override_cred->fsgid = override_cred->gid; if (!issecure(SECURE_NO_SETUID_FIXUP)) { /* Clear the capabilities if we switch to a non-root user */ kuid_t root_uid = make_kuid(override_cred->user_ns, 0); if (!uid_eq(override_cred->uid, root_uid)) cap_clear(override_cred->cap_effective); else override_cred->cap_effective = override_cred->cap_permitted; } old_cred = override_creds(override_cred); retry: res = user_path_at(dfd, filename, lookup_flags, &path); if (res) goto out; inode = path.dentry->d_inode; if ((mode & MAY_EXEC) && S_ISREG(inode->i_mode)) { /* * MAY_EXEC on regular files is denied if the fs is mounted * with the "noexec" flag. */ res = -EACCES; if (path.mnt->mnt_flags & MNT_NOEXEC) goto out_path_release; } res = inode_permission(inode, mode | MAY_ACCESS); /* SuS v2 requires we report a read only fs too */ if (res || !(mode & S_IWOTH) || special_file(inode->i_mode)) goto out_path_release; /* * This is a rare case where using __mnt_is_readonly() * is OK without a mnt_want/drop_write() pair. Since * no actual write to the fs is performed here, we do * not need to telegraph to that to anyone. * * By doing this, we accept that this access is * inherently racy and know that the fs may change * state before we even see this result. */ if (__mnt_is_readonly(path.mnt)) res = -EROFS; out_path_release: path_put(&path); if (retry_estale(res, lookup_flags)) { lookup_flags |= LOOKUP_REVAL; goto retry; } out: revert_creds(old_cred); put_cred(override_cred); return res; } SYSCALL_DEFINE2(access, const char __user *, filename, int, mode) { return sys_faccessat(AT_FDCWD, filename, mode); } SYSCALL_DEFINE1(chdir, const char __user *, filename) { struct path path; int error; unsigned int lookup_flags = LOOKUP_FOLLOW | LOOKUP_DIRECTORY; retry: error = user_path_at(AT_FDCWD, filename, lookup_flags, &path); if (error) goto out; error = inode_permission(path.dentry->d_inode, MAY_EXEC | MAY_CHDIR); if (error) goto dput_and_out; set_fs_pwd(current->fs, &path); dput_and_out: path_put(&path); if (retry_estale(error, lookup_flags)) { lookup_flags |= LOOKUP_REVAL; goto retry; } out: return error; } SYSCALL_DEFINE1(fchdir, unsigned int, fd) { struct fd f = fdget_raw(fd); struct inode *inode; int error = -EBADF; error = -EBADF; if (!f.file) goto out; inode = file_inode(f.file); error = -ENOTDIR; if (!S_ISDIR(inode->i_mode)) goto out_putf; error = inode_permission(inode, MAY_EXEC | MAY_CHDIR); if (!error) set_fs_pwd(current->fs, &f.file->f_path); out_putf: fdput(f); out: return error; } SYSCALL_DEFINE1(chroot, const char __user *, filename) { struct path path; int error; unsigned int lookup_flags = LOOKUP_FOLLOW | LOOKUP_DIRECTORY; retry: error = user_path_at(AT_FDCWD, filename, lookup_flags, &path); if (error) goto out; error = inode_permission(path.dentry->d_inode, MAY_EXEC | MAY_CHDIR); if (error) goto dput_and_out; error = -EPERM; if (!ns_capable(current_user_ns(), CAP_SYS_CHROOT)) goto dput_and_out; error = security_path_chroot(&path); if (error) goto dput_and_out; set_fs_root(current->fs, &path); error = 0; dput_and_out: path_put(&path); if (retry_estale(error, lookup_flags)) { lookup_flags |= LOOKUP_REVAL; goto retry; } out: return error; } static int chmod_common(struct path *path, umode_t mode) { struct inode *inode = path->dentry->d_inode; struct iattr newattrs; int error; error = mnt_want_write(path->mnt); if (error) return error; mutex_lock(&inode->i_mutex); error = security_path_chmod(path, mode); if (error) goto out_unlock; newattrs.ia_mode = (mode & S_IALLUGO) | (inode->i_mode & ~S_IALLUGO); newattrs.ia_valid = ATTR_MODE | ATTR_CTIME; error = notify_change(path->dentry, &newattrs); out_unlock: mutex_unlock(&inode->i_mutex); mnt_drop_write(path->mnt); return error; } SYSCALL_DEFINE2(fchmod, unsigned int, fd, umode_t, mode) { struct fd f = fdget(fd); int err = -EBADF; if (f.file) { audit_inode(NULL, f.file->f_path.dentry, 0); err = chmod_common(&f.file->f_path, mode); fdput(f); } return err; } SYSCALL_DEFINE3(fchmodat, int, dfd, const char __user *, filename, umode_t, mode) { struct path path; int error; unsigned int lookup_flags = LOOKUP_FOLLOW; retry: error = user_path_at(dfd, filename, lookup_flags, &path); if (!error) { error = chmod_common(&path, mode); path_put(&path); if (retry_estale(error, lookup_flags)) { lookup_flags |= LOOKUP_REVAL; goto retry; } } return error; } SYSCALL_DEFINE2(chmod, const char __user *, filename, umode_t, mode) { return sys_fchmodat(AT_FDCWD, filename, mode); } static int chown_common(struct path *path, uid_t user, gid_t group) { struct inode *inode = path->dentry->d_inode; int error; struct iattr newattrs; kuid_t uid; kgid_t gid; uid = make_kuid(current_user_ns(), user); gid = make_kgid(current_user_ns(), group); newattrs.ia_valid = ATTR_CTIME; if (user != (uid_t) -1) { if (!uid_valid(uid)) return -EINVAL; newattrs.ia_valid |= ATTR_UID; newattrs.ia_uid = uid; } if (group != (gid_t) -1) { if (!gid_valid(gid)) return -EINVAL; newattrs.ia_valid |= ATTR_GID; newattrs.ia_gid = gid; } if (!S_ISDIR(inode->i_mode)) newattrs.ia_valid |= ATTR_KILL_SUID | ATTR_KILL_SGID | ATTR_KILL_PRIV; mutex_lock(&inode->i_mutex); error = security_path_chown(path, uid, gid); if (!error) error = notify_change(path->dentry, &newattrs); mutex_unlock(&inode->i_mutex); return error; } SYSCALL_DEFINE5(fchownat, int, dfd, const char __user *, filename, uid_t, user, gid_t, group, int, flag) { struct path path; int error = -EINVAL; int lookup_flags; if ((flag & ~(AT_SYMLINK_NOFOLLOW | AT_EMPTY_PATH)) != 0) goto out; lookup_flags = (flag & AT_SYMLINK_NOFOLLOW) ? 0 : LOOKUP_FOLLOW; if (flag & AT_EMPTY_PATH) lookup_flags |= LOOKUP_EMPTY; retry: error = user_path_at(dfd, filename, lookup_flags, &path); if (error) goto out; error = mnt_want_write(path.mnt); if (error) goto out_release; error = chown_common(&path, user, group); mnt_drop_write(path.mnt); out_release: path_put(&path); if (retry_estale(error, lookup_flags)) { lookup_flags |= LOOKUP_REVAL; goto retry; } out: return error; } SYSCALL_DEFINE3(chown, const char __user *, filename, uid_t, user, gid_t, group) { return sys_fchownat(AT_FDCWD, filename, user, group, 0); } SYSCALL_DEFINE3(lchown, const char __user *, filename, uid_t, user, gid_t, group) { return sys_fchownat(AT_FDCWD, filename, user, group, AT_SYMLINK_NOFOLLOW); } SYSCALL_DEFINE3(fchown, unsigned int, fd, uid_t, user, gid_t, group) { struct fd f = fdget(fd); int error = -EBADF; if (!f.file) goto out; error = mnt_want_write_file(f.file); if (error) goto out_fput; audit_inode(NULL, f.file->f_path.dentry, 0); error = chown_common(&f.file->f_path, user, group); mnt_drop_write_file(f.file); out_fput: fdput(f); out: return error; } /* * You have to be very careful that these write * counts get cleaned up in error cases and * upon __fput(). This should probably never * be called outside of __dentry_open(). */ static inline int __get_file_write_access(struct inode *inode, struct vfsmount *mnt) { int error; error = get_write_access(inode); if (error) return error; /* * Do not take mount writer counts on * special files since no writes to * the mount itself will occur. */ if (!special_file(inode->i_mode)) { /* * Balanced in __fput() */ error = __mnt_want_write(mnt); if (error) put_write_access(inode); } return error; } int open_check_o_direct(struct file *f) { /* NB: we're sure to have correct a_ops only after f_op->open */ if (f->f_flags & O_DIRECT) { if (!f->f_mapping->a_ops || ((!f->f_mapping->a_ops->direct_IO) && (!f->f_mapping->a_ops->get_xip_mem))) { return -EINVAL; } } return 0; } static int do_dentry_open(struct file *f, int (*open)(struct inode *, struct file *), const struct cred *cred) { static const struct file_operations empty_fops = {}; struct inode *inode; int error; f->f_mode = OPEN_FMODE(f->f_flags) | FMODE_LSEEK | FMODE_PREAD | FMODE_PWRITE; if (unlikely(f->f_flags & O_PATH)) f->f_mode = FMODE_PATH; path_get(&f->f_path); inode = f->f_inode = f->f_path.dentry->d_inode; if (f->f_mode & FMODE_WRITE) { error = __get_file_write_access(inode, f->f_path.mnt); if (error) goto cleanup_file; if (!special_file(inode->i_mode)) file_take_write(f); } f->f_mapping = inode->i_mapping; if (unlikely(f->f_mode & FMODE_PATH)) { f->f_op = &empty_fops; return 0; } f->f_op = fops_get(inode->i_fop); if (unlikely(WARN_ON(!f->f_op))) { error = -ENODEV; goto cleanup_all; } error = security_file_open(f, cred); if (error) goto cleanup_all; error = break_lease(inode, f->f_flags); if (error) goto cleanup_all; if (!open) open = f->f_op->open; if (open) { error = open(inode, f); if (error) goto cleanup_all; } if ((f->f_mode & (FMODE_READ | FMODE_WRITE)) == FMODE_READ) i_readcount_inc(inode); f->f_flags &= ~(O_CREAT | O_EXCL | O_NOCTTY | O_TRUNC); file_ra_state_init(&f->f_ra, f->f_mapping->host->i_mapping); return 0; cleanup_all: fops_put(f->f_op); if (f->f_mode & FMODE_WRITE) { put_write_access(inode); if (!special_file(inode->i_mode)) { /* * We don't consider this a real * mnt_want/drop_write() pair * because it all happenend right * here, so just reset the state. */ file_reset_write(f); __mnt_drop_write(f->f_path.mnt); } } cleanup_file: path_put(&f->f_path); f->f_path.mnt = NULL; f->f_path.dentry = NULL; f->f_inode = NULL; return error; } /** * finish_open - finish opening a file * @file: file pointer * @dentry: pointer to dentry * @open: open callback * @opened: state of open * * This can be used to finish opening a file passed to i_op->atomic_open(). * * If the open callback is set to NULL, then the standard f_op->open() * filesystem callback is substituted. * * NB: the dentry reference is _not_ consumed. If, for example, the dentry is * the return value of d_splice_alias(), then the caller needs to perform dput() * on it after finish_open(). * * On successful return @file is a fully instantiated open file. After this, if * an error occurs in ->atomic_open(), it needs to clean up with fput(). * * Returns zero on success or -errno if the open failed. */ int finish_open(struct file *file, struct dentry *dentry, int (*open)(struct inode *, struct file *), int *opened) { int error; BUG_ON(*opened & FILE_OPENED); /* once it's opened, it's opened */ file->f_path.dentry = dentry; error = do_dentry_open(file, open, current_cred()); if (!error) *opened |= FILE_OPENED; return error; } EXPORT_SYMBOL(finish_open); /** * finish_no_open - finish ->atomic_open() without opening the file * * @file: file pointer * @dentry: dentry or NULL (as returned from ->lookup()) * * This can be used to set the result of a successful lookup in ->atomic_open(). * * NB: unlike finish_open() this function does consume the dentry reference and * the caller need not dput() it. * * Returns "1" which must be the return value of ->atomic_open() after having * called this function. */ int finish_no_open(struct file *file, struct dentry *dentry) { file->f_path.dentry = dentry; return 1; } EXPORT_SYMBOL(finish_no_open); struct file *dentry_open(const struct path *path, int flags, const struct cred *cred) { int error; struct file *f; validate_creds(cred); /* We must always pass in a valid mount pointer. */ BUG_ON(!path->mnt); f = get_empty_filp(); if (!IS_ERR(f)) { f->f_flags = flags; f->f_path = *path; error = do_dentry_open(f, NULL, cred); if (!error) { /* from now on we need fput() to dispose of f */ error = open_check_o_direct(f); if (error) { fput(f); f = ERR_PTR(error); } } else { put_filp(f); f = ERR_PTR(error); } } return f; } EXPORT_SYMBOL(dentry_open); static inline int build_open_flags(int flags, umode_t mode, struct open_flags *op) { int lookup_flags = 0; int acc_mode; if (flags & (O_CREAT | __O_TMPFILE)) op->mode = (mode & S_IALLUGO) | S_IFREG; else op->mode = 0; /* Must never be set by userspace */ flags &= ~FMODE_NONOTIFY & ~O_CLOEXEC; /* * O_SYNC is implemented as __O_SYNC|O_DSYNC. As many places only * check for O_DSYNC if the need any syncing at all we enforce it's * always set instead of having to deal with possibly weird behaviour * for malicious applications setting only __O_SYNC. */ if (flags & __O_SYNC) flags |= O_DSYNC; if (flags & __O_TMPFILE) { if ((flags & O_TMPFILE_MASK) != O_TMPFILE) return -EINVAL; acc_mode = MAY_OPEN | ACC_MODE(flags); if (!(acc_mode & MAY_WRITE)) return -EINVAL; } else if (flags & O_PATH) { /* * If we have O_PATH in the open flag. Then we * cannot have anything other than the below set of flags */ flags &= O_DIRECTORY | O_NOFOLLOW | O_PATH; acc_mode = 0; } else { acc_mode = MAY_OPEN | ACC_MODE(flags); } op->open_flag = flags; /* O_TRUNC implies we need access checks for write permissions */ if (flags & O_TRUNC) acc_mode |= MAY_WRITE; /* Allow the LSM permission hook to distinguish append access from general write access. */ if (flags & O_APPEND) acc_mode |= MAY_APPEND; op->acc_mode = acc_mode; op->intent = flags & O_PATH ? 0 : LOOKUP_OPEN; if (flags & O_CREAT) { op->intent |= LOOKUP_CREATE; if (flags & O_EXCL) op->intent |= LOOKUP_EXCL; } if (flags & O_DIRECTORY) lookup_flags |= LOOKUP_DIRECTORY; if (!(flags & O_NOFOLLOW)) lookup_flags |= LOOKUP_FOLLOW; op->lookup_flags = lookup_flags; return 0; } /** * file_open_name - open file and return file pointer * * @name: struct filename containing path to open * @flags: open flags as per the open(2) second argument * @mode: mode for the new file if O_CREAT is set, else ignored * * This is the helper to open a file from kernelspace if you really * have to. But in generally you should not do this, so please move * along, nothing to see here.. */ struct file *file_open_name(struct filename *name, int flags, umode_t mode) { struct open_flags op; int err = build_open_flags(flags, mode, &op); return err ? ERR_PTR(err) : do_filp_open(AT_FDCWD, name, &op); } /** * filp_open - open file and return file pointer * * @filename: path to open * @flags: open flags as per the open(2) second argument * @mode: mode for the new file if O_CREAT is set, else ignored * * This is the helper to open a file from kernelspace if you really * have to. But in generally you should not do this, so please move * along, nothing to see here.. */ struct file *filp_open(const char *filename, int flags, umode_t mode) { struct filename name = {.name = filename}; return file_open_name(&name, flags, mode); } EXPORT_SYMBOL(filp_open); struct file *file_open_root(struct dentry *dentry, struct vfsmount *mnt, const char *filename, int flags) { struct open_flags op; int err = build_open_flags(flags, 0, &op); if (err) return ERR_PTR(err); if (flags & O_CREAT) return ERR_PTR(-EINVAL); if (!filename && (flags & O_DIRECTORY)) if (!dentry->d_inode->i_op->lookup) return ERR_PTR(-ENOTDIR); return do_file_open_root(dentry, mnt, filename, &op); } EXPORT_SYMBOL(file_open_root); long do_sys_open(int dfd, const char __user *filename, int flags, umode_t mode) { struct open_flags op; int fd = build_open_flags(flags, mode, &op); struct filename *tmp; if (fd) return fd; tmp = getname(filename); if (IS_ERR(tmp)) return PTR_ERR(tmp); fd = get_unused_fd_flags(flags); if (fd >= 0) { struct file *f = do_filp_open(dfd, tmp, &op); if (IS_ERR(f)) { put_unused_fd(fd); fd = PTR_ERR(f); } else { fsnotify_open(f); fd_install(fd, f); } } putname(tmp); return fd; } SYSCALL_DEFINE3(open, const char __user *, filename, int, flags, umode_t, mode) { if (force_o_largefile()) flags |= O_LARGEFILE; return do_sys_open(AT_FDCWD, filename, flags, mode); } SYSCALL_DEFINE4(openat, int, dfd, const char __user *, filename, int, flags, umode_t, mode) { if (force_o_largefile()) flags |= O_LARGEFILE; return do_sys_open(dfd, filename, flags, mode); } #ifndef __alpha__ /* * For backward compatibility? Maybe this should be moved * into arch/i386 instead? */ SYSCALL_DEFINE2(creat, const char __user *, pathname, umode_t, mode) { return sys_open(pathname, O_CREAT | O_WRONLY | O_TRUNC, mode); } #endif /* * "id" is the POSIX thread ID. We use the * files pointer for this.. */ int filp_close(struct file *filp, fl_owner_t id) { int retval = 0; if (!file_count(filp)) { printk(KERN_ERR "VFS: Close: file count is 0\n"); return 0; } if (filp->f_op->flush) retval = filp->f_op->flush(filp, id); if (likely(!(filp->f_mode & FMODE_PATH))) { dnotify_flush(filp, id); locks_remove_posix(filp, id); } fput(filp); return retval; } EXPORT_SYMBOL(filp_close); /* * Careful here! We test whether the file pointer is NULL before * releasing the fd. This ensures that one clone task can't release * an fd while another clone is opening it. */ SYSCALL_DEFINE1(close, unsigned int, fd) { int retval = __close_fd(current->files, fd); /* can't restart close syscall because file table entry was cleared */ if (unlikely(retval == -ERESTARTSYS || retval == -ERESTARTNOINTR || retval == -ERESTARTNOHAND || retval == -ERESTART_RESTARTBLOCK)) retval = -EINTR; return retval; } EXPORT_SYMBOL(sys_close); /* * This routine simulates a hangup on the tty, to arrange that users * are given clean terminals at login time. */ SYSCALL_DEFINE0(vhangup) { if (capable(CAP_SYS_TTY_CONFIG)) { tty_vhangup_self(); return 0; } return -EPERM; } /* * Called when an inode is about to be open. * We use this to disallow opening large files on 32bit systems if * the caller didn't specify O_LARGEFILE. On 64bit systems we force * on this flag in sys_open. */ int generic_file_open(struct inode * inode, struct file * filp) { if (!(filp->f_flags & O_LARGEFILE) && i_size_read(inode) > MAX_NON_LFS) return -EOVERFLOW; return 0; } EXPORT_SYMBOL(generic_file_open); /* * This is used by subsystems that don't want seekable * file descriptors. The function is not supposed to ever fail, the only * reason it returns an 'int' and not 'void' is so that it can be plugged * directly into file_operations structure. */ int nonseekable_open(struct inode *inode, struct file *filp) { filp->f_mode &= ~(FMODE_LSEEK | FMODE_PREAD | FMODE_PWRITE); return 0; } EXPORT_SYMBOL(nonseekable_open);
./CrossVul/dataset_final_sorted/CWE-17/c/good_2306_2
crossvul-cpp_data_bad_1546_0
/* * Neighbour Discovery for IPv6 * Linux INET6 implementation * * Authors: * Pedro Roque <roque@di.fc.ul.pt> * Mike Shaver <shaver@ingenia.com> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ /* * Changes: * * Alexey I. Froloff : RFC6106 (DNSSL) support * Pierre Ynard : export userland ND options * through netlink (RDNSS support) * Lars Fenneberg : fixed MTU setting on receipt * of an RA. * Janos Farkas : kmalloc failure checks * Alexey Kuznetsov : state machine reworked * and moved to net/core. * Pekka Savola : RFC2461 validation * YOSHIFUJI Hideaki @USAGI : Verify ND options properly */ #define pr_fmt(fmt) "ICMPv6: " fmt #include <linux/module.h> #include <linux/errno.h> #include <linux/types.h> #include <linux/socket.h> #include <linux/sockios.h> #include <linux/sched.h> #include <linux/net.h> #include <linux/in6.h> #include <linux/route.h> #include <linux/init.h> #include <linux/rcupdate.h> #include <linux/slab.h> #ifdef CONFIG_SYSCTL #include <linux/sysctl.h> #endif #include <linux/if_addr.h> #include <linux/if_arp.h> #include <linux/ipv6.h> #include <linux/icmpv6.h> #include <linux/jhash.h> #include <net/sock.h> #include <net/snmp.h> #include <net/ipv6.h> #include <net/protocol.h> #include <net/ndisc.h> #include <net/ip6_route.h> #include <net/addrconf.h> #include <net/icmp.h> #include <net/netlink.h> #include <linux/rtnetlink.h> #include <net/flow.h> #include <net/ip6_checksum.h> #include <net/inet_common.h> #include <linux/proc_fs.h> #include <linux/netfilter.h> #include <linux/netfilter_ipv6.h> /* Set to 3 to get tracing... */ #define ND_DEBUG 1 #define ND_PRINTK(val, level, fmt, ...) \ do { \ if (val <= ND_DEBUG) \ net_##level##_ratelimited(fmt, ##__VA_ARGS__); \ } while (0) static u32 ndisc_hash(const void *pkey, const struct net_device *dev, __u32 *hash_rnd); static int ndisc_constructor(struct neighbour *neigh); static void ndisc_solicit(struct neighbour *neigh, struct sk_buff *skb); static void ndisc_error_report(struct neighbour *neigh, struct sk_buff *skb); static int pndisc_constructor(struct pneigh_entry *n); static void pndisc_destructor(struct pneigh_entry *n); static void pndisc_redo(struct sk_buff *skb); static const struct neigh_ops ndisc_generic_ops = { .family = AF_INET6, .solicit = ndisc_solicit, .error_report = ndisc_error_report, .output = neigh_resolve_output, .connected_output = neigh_connected_output, }; static const struct neigh_ops ndisc_hh_ops = { .family = AF_INET6, .solicit = ndisc_solicit, .error_report = ndisc_error_report, .output = neigh_resolve_output, .connected_output = neigh_resolve_output, }; static const struct neigh_ops ndisc_direct_ops = { .family = AF_INET6, .output = neigh_direct_output, .connected_output = neigh_direct_output, }; struct neigh_table nd_tbl = { .family = AF_INET6, .key_len = sizeof(struct in6_addr), .hash = ndisc_hash, .constructor = ndisc_constructor, .pconstructor = pndisc_constructor, .pdestructor = pndisc_destructor, .proxy_redo = pndisc_redo, .id = "ndisc_cache", .parms = { .tbl = &nd_tbl, .reachable_time = ND_REACHABLE_TIME, .data = { [NEIGH_VAR_MCAST_PROBES] = 3, [NEIGH_VAR_UCAST_PROBES] = 3, [NEIGH_VAR_RETRANS_TIME] = ND_RETRANS_TIMER, [NEIGH_VAR_BASE_REACHABLE_TIME] = ND_REACHABLE_TIME, [NEIGH_VAR_DELAY_PROBE_TIME] = 5 * HZ, [NEIGH_VAR_GC_STALETIME] = 60 * HZ, [NEIGH_VAR_QUEUE_LEN_BYTES] = 64 * 1024, [NEIGH_VAR_PROXY_QLEN] = 64, [NEIGH_VAR_ANYCAST_DELAY] = 1 * HZ, [NEIGH_VAR_PROXY_DELAY] = (8 * HZ) / 10, }, }, .gc_interval = 30 * HZ, .gc_thresh1 = 128, .gc_thresh2 = 512, .gc_thresh3 = 1024, }; static void ndisc_fill_addr_option(struct sk_buff *skb, int type, void *data) { int pad = ndisc_addr_option_pad(skb->dev->type); int data_len = skb->dev->addr_len; int space = ndisc_opt_addr_space(skb->dev); u8 *opt = skb_put(skb, space); opt[0] = type; opt[1] = space>>3; memset(opt + 2, 0, pad); opt += pad; space -= pad; memcpy(opt+2, data, data_len); data_len += 2; opt += data_len; space -= data_len; if (space > 0) memset(opt, 0, space); } static struct nd_opt_hdr *ndisc_next_option(struct nd_opt_hdr *cur, struct nd_opt_hdr *end) { int type; if (!cur || !end || cur >= end) return NULL; type = cur->nd_opt_type; do { cur = ((void *)cur) + (cur->nd_opt_len << 3); } while (cur < end && cur->nd_opt_type != type); return cur <= end && cur->nd_opt_type == type ? cur : NULL; } static inline int ndisc_is_useropt(struct nd_opt_hdr *opt) { return opt->nd_opt_type == ND_OPT_RDNSS || opt->nd_opt_type == ND_OPT_DNSSL; } static struct nd_opt_hdr *ndisc_next_useropt(struct nd_opt_hdr *cur, struct nd_opt_hdr *end) { if (!cur || !end || cur >= end) return NULL; do { cur = ((void *)cur) + (cur->nd_opt_len << 3); } while (cur < end && !ndisc_is_useropt(cur)); return cur <= end && ndisc_is_useropt(cur) ? cur : NULL; } struct ndisc_options *ndisc_parse_options(u8 *opt, int opt_len, struct ndisc_options *ndopts) { struct nd_opt_hdr *nd_opt = (struct nd_opt_hdr *)opt; if (!nd_opt || opt_len < 0 || !ndopts) return NULL; memset(ndopts, 0, sizeof(*ndopts)); while (opt_len) { int l; if (opt_len < sizeof(struct nd_opt_hdr)) return NULL; l = nd_opt->nd_opt_len << 3; if (opt_len < l || l == 0) return NULL; switch (nd_opt->nd_opt_type) { case ND_OPT_SOURCE_LL_ADDR: case ND_OPT_TARGET_LL_ADDR: case ND_OPT_MTU: case ND_OPT_REDIRECT_HDR: if (ndopts->nd_opt_array[nd_opt->nd_opt_type]) { ND_PRINTK(2, warn, "%s: duplicated ND6 option found: type=%d\n", __func__, nd_opt->nd_opt_type); } else { ndopts->nd_opt_array[nd_opt->nd_opt_type] = nd_opt; } break; case ND_OPT_PREFIX_INFO: ndopts->nd_opts_pi_end = nd_opt; if (!ndopts->nd_opt_array[nd_opt->nd_opt_type]) ndopts->nd_opt_array[nd_opt->nd_opt_type] = nd_opt; break; #ifdef CONFIG_IPV6_ROUTE_INFO case ND_OPT_ROUTE_INFO: ndopts->nd_opts_ri_end = nd_opt; if (!ndopts->nd_opts_ri) ndopts->nd_opts_ri = nd_opt; break; #endif default: if (ndisc_is_useropt(nd_opt)) { ndopts->nd_useropts_end = nd_opt; if (!ndopts->nd_useropts) ndopts->nd_useropts = nd_opt; } else { /* * Unknown options must be silently ignored, * to accommodate future extension to the * protocol. */ ND_PRINTK(2, notice, "%s: ignored unsupported option; type=%d, len=%d\n", __func__, nd_opt->nd_opt_type, nd_opt->nd_opt_len); } } opt_len -= l; nd_opt = ((void *)nd_opt) + l; } return ndopts; } int ndisc_mc_map(const struct in6_addr *addr, char *buf, struct net_device *dev, int dir) { switch (dev->type) { case ARPHRD_ETHER: case ARPHRD_IEEE802: /* Not sure. Check it later. --ANK */ case ARPHRD_FDDI: ipv6_eth_mc_map(addr, buf); return 0; case ARPHRD_ARCNET: ipv6_arcnet_mc_map(addr, buf); return 0; case ARPHRD_INFINIBAND: ipv6_ib_mc_map(addr, dev->broadcast, buf); return 0; case ARPHRD_IPGRE: return ipv6_ipgre_mc_map(addr, dev->broadcast, buf); default: if (dir) { memcpy(buf, dev->broadcast, dev->addr_len); return 0; } } return -EINVAL; } EXPORT_SYMBOL(ndisc_mc_map); static u32 ndisc_hash(const void *pkey, const struct net_device *dev, __u32 *hash_rnd) { return ndisc_hashfn(pkey, dev, hash_rnd); } static int ndisc_constructor(struct neighbour *neigh) { struct in6_addr *addr = (struct in6_addr *)&neigh->primary_key; struct net_device *dev = neigh->dev; struct inet6_dev *in6_dev; struct neigh_parms *parms; bool is_multicast = ipv6_addr_is_multicast(addr); in6_dev = in6_dev_get(dev); if (in6_dev == NULL) { return -EINVAL; } parms = in6_dev->nd_parms; __neigh_parms_put(neigh->parms); neigh->parms = neigh_parms_clone(parms); neigh->type = is_multicast ? RTN_MULTICAST : RTN_UNICAST; if (!dev->header_ops) { neigh->nud_state = NUD_NOARP; neigh->ops = &ndisc_direct_ops; neigh->output = neigh_direct_output; } else { if (is_multicast) { neigh->nud_state = NUD_NOARP; ndisc_mc_map(addr, neigh->ha, dev, 1); } else if (dev->flags&(IFF_NOARP|IFF_LOOPBACK)) { neigh->nud_state = NUD_NOARP; memcpy(neigh->ha, dev->dev_addr, dev->addr_len); if (dev->flags&IFF_LOOPBACK) neigh->type = RTN_LOCAL; } else if (dev->flags&IFF_POINTOPOINT) { neigh->nud_state = NUD_NOARP; memcpy(neigh->ha, dev->broadcast, dev->addr_len); } if (dev->header_ops->cache) neigh->ops = &ndisc_hh_ops; else neigh->ops = &ndisc_generic_ops; if (neigh->nud_state&NUD_VALID) neigh->output = neigh->ops->connected_output; else neigh->output = neigh->ops->output; } in6_dev_put(in6_dev); return 0; } static int pndisc_constructor(struct pneigh_entry *n) { struct in6_addr *addr = (struct in6_addr *)&n->key; struct in6_addr maddr; struct net_device *dev = n->dev; if (dev == NULL || __in6_dev_get(dev) == NULL) return -EINVAL; addrconf_addr_solict_mult(addr, &maddr); ipv6_dev_mc_inc(dev, &maddr); return 0; } static void pndisc_destructor(struct pneigh_entry *n) { struct in6_addr *addr = (struct in6_addr *)&n->key; struct in6_addr maddr; struct net_device *dev = n->dev; if (dev == NULL || __in6_dev_get(dev) == NULL) return; addrconf_addr_solict_mult(addr, &maddr); ipv6_dev_mc_dec(dev, &maddr); } static struct sk_buff *ndisc_alloc_skb(struct net_device *dev, int len) { int hlen = LL_RESERVED_SPACE(dev); int tlen = dev->needed_tailroom; struct sock *sk = dev_net(dev)->ipv6.ndisc_sk; struct sk_buff *skb; skb = alloc_skb(hlen + sizeof(struct ipv6hdr) + len + tlen, GFP_ATOMIC); if (!skb) { ND_PRINTK(0, err, "ndisc: %s failed to allocate an skb\n", __func__); return NULL; } skb->protocol = htons(ETH_P_IPV6); skb->dev = dev; skb_reserve(skb, hlen + sizeof(struct ipv6hdr)); skb_reset_transport_header(skb); /* Manually assign socket ownership as we avoid calling * sock_alloc_send_pskb() to bypass wmem buffer limits */ skb_set_owner_w(skb, sk); return skb; } static void ip6_nd_hdr(struct sk_buff *skb, const struct in6_addr *saddr, const struct in6_addr *daddr, int hop_limit, int len) { struct ipv6hdr *hdr; skb_push(skb, sizeof(*hdr)); skb_reset_network_header(skb); hdr = ipv6_hdr(skb); ip6_flow_hdr(hdr, 0, 0); hdr->payload_len = htons(len); hdr->nexthdr = IPPROTO_ICMPV6; hdr->hop_limit = hop_limit; hdr->saddr = *saddr; hdr->daddr = *daddr; } static void ndisc_send_skb(struct sk_buff *skb, const struct in6_addr *daddr, const struct in6_addr *saddr) { struct dst_entry *dst = skb_dst(skb); struct net *net = dev_net(skb->dev); struct sock *sk = net->ipv6.ndisc_sk; struct inet6_dev *idev; int err; struct icmp6hdr *icmp6h = icmp6_hdr(skb); u8 type; type = icmp6h->icmp6_type; if (!dst) { struct flowi6 fl6; icmpv6_flow_init(sk, &fl6, type, saddr, daddr, skb->dev->ifindex); dst = icmp6_dst_alloc(skb->dev, &fl6); if (IS_ERR(dst)) { kfree_skb(skb); return; } skb_dst_set(skb, dst); } icmp6h->icmp6_cksum = csum_ipv6_magic(saddr, daddr, skb->len, IPPROTO_ICMPV6, csum_partial(icmp6h, skb->len, 0)); ip6_nd_hdr(skb, saddr, daddr, inet6_sk(sk)->hop_limit, skb->len); rcu_read_lock(); idev = __in6_dev_get(dst->dev); IP6_UPD_PO_STATS(net, idev, IPSTATS_MIB_OUT, skb->len); err = NF_HOOK(NFPROTO_IPV6, NF_INET_LOCAL_OUT, skb, NULL, dst->dev, dst_output); if (!err) { ICMP6MSGOUT_INC_STATS(net, idev, type); ICMP6_INC_STATS(net, idev, ICMP6_MIB_OUTMSGS); } rcu_read_unlock(); } void ndisc_send_na(struct net_device *dev, struct neighbour *neigh, const struct in6_addr *daddr, const struct in6_addr *solicited_addr, bool router, bool solicited, bool override, bool inc_opt) { struct sk_buff *skb; struct in6_addr tmpaddr; struct inet6_ifaddr *ifp; const struct in6_addr *src_addr; struct nd_msg *msg; int optlen = 0; /* for anycast or proxy, solicited_addr != src_addr */ ifp = ipv6_get_ifaddr(dev_net(dev), solicited_addr, dev, 1); if (ifp) { src_addr = solicited_addr; if (ifp->flags & IFA_F_OPTIMISTIC) override = false; inc_opt |= ifp->idev->cnf.force_tllao; in6_ifa_put(ifp); } else { if (ipv6_dev_get_saddr(dev_net(dev), dev, daddr, inet6_sk(dev_net(dev)->ipv6.ndisc_sk)->srcprefs, &tmpaddr)) return; src_addr = &tmpaddr; } if (!dev->addr_len) inc_opt = 0; if (inc_opt) optlen += ndisc_opt_addr_space(dev); skb = ndisc_alloc_skb(dev, sizeof(*msg) + optlen); if (!skb) return; msg = (struct nd_msg *)skb_put(skb, sizeof(*msg)); *msg = (struct nd_msg) { .icmph = { .icmp6_type = NDISC_NEIGHBOUR_ADVERTISEMENT, .icmp6_router = router, .icmp6_solicited = solicited, .icmp6_override = override, }, .target = *solicited_addr, }; if (inc_opt) ndisc_fill_addr_option(skb, ND_OPT_TARGET_LL_ADDR, dev->dev_addr); ndisc_send_skb(skb, daddr, src_addr); } static void ndisc_send_unsol_na(struct net_device *dev) { struct inet6_dev *idev; struct inet6_ifaddr *ifa; idev = in6_dev_get(dev); if (!idev) return; read_lock_bh(&idev->lock); list_for_each_entry(ifa, &idev->addr_list, if_list) { ndisc_send_na(dev, NULL, &in6addr_linklocal_allnodes, &ifa->addr, /*router=*/ !!idev->cnf.forwarding, /*solicited=*/ false, /*override=*/ true, /*inc_opt=*/ true); } read_unlock_bh(&idev->lock); in6_dev_put(idev); } void ndisc_send_ns(struct net_device *dev, struct neighbour *neigh, const struct in6_addr *solicit, const struct in6_addr *daddr, const struct in6_addr *saddr) { struct sk_buff *skb; struct in6_addr addr_buf; int inc_opt = dev->addr_len; int optlen = 0; struct nd_msg *msg; if (saddr == NULL) { if (ipv6_get_lladdr(dev, &addr_buf, (IFA_F_TENTATIVE|IFA_F_OPTIMISTIC))) return; saddr = &addr_buf; } if (ipv6_addr_any(saddr)) inc_opt = false; if (inc_opt) optlen += ndisc_opt_addr_space(dev); skb = ndisc_alloc_skb(dev, sizeof(*msg) + optlen); if (!skb) return; msg = (struct nd_msg *)skb_put(skb, sizeof(*msg)); *msg = (struct nd_msg) { .icmph = { .icmp6_type = NDISC_NEIGHBOUR_SOLICITATION, }, .target = *solicit, }; if (inc_opt) ndisc_fill_addr_option(skb, ND_OPT_SOURCE_LL_ADDR, dev->dev_addr); ndisc_send_skb(skb, daddr, saddr); } void ndisc_send_rs(struct net_device *dev, const struct in6_addr *saddr, const struct in6_addr *daddr) { struct sk_buff *skb; struct rs_msg *msg; int send_sllao = dev->addr_len; int optlen = 0; #ifdef CONFIG_IPV6_OPTIMISTIC_DAD /* * According to section 2.2 of RFC 4429, we must not * send router solicitations with a sllao from * optimistic addresses, but we may send the solicitation * if we don't include the sllao. So here we check * if our address is optimistic, and if so, we * suppress the inclusion of the sllao. */ if (send_sllao) { struct inet6_ifaddr *ifp = ipv6_get_ifaddr(dev_net(dev), saddr, dev, 1); if (ifp) { if (ifp->flags & IFA_F_OPTIMISTIC) { send_sllao = 0; } in6_ifa_put(ifp); } else { send_sllao = 0; } } #endif if (send_sllao) optlen += ndisc_opt_addr_space(dev); skb = ndisc_alloc_skb(dev, sizeof(*msg) + optlen); if (!skb) return; msg = (struct rs_msg *)skb_put(skb, sizeof(*msg)); *msg = (struct rs_msg) { .icmph = { .icmp6_type = NDISC_ROUTER_SOLICITATION, }, }; if (send_sllao) ndisc_fill_addr_option(skb, ND_OPT_SOURCE_LL_ADDR, dev->dev_addr); ndisc_send_skb(skb, daddr, saddr); } static void ndisc_error_report(struct neighbour *neigh, struct sk_buff *skb) { /* * "The sender MUST return an ICMP * destination unreachable" */ dst_link_failure(skb); kfree_skb(skb); } /* Called with locked neigh: either read or both */ static void ndisc_solicit(struct neighbour *neigh, struct sk_buff *skb) { struct in6_addr *saddr = NULL; struct in6_addr mcaddr; struct net_device *dev = neigh->dev; struct in6_addr *target = (struct in6_addr *)&neigh->primary_key; int probes = atomic_read(&neigh->probes); if (skb && ipv6_chk_addr_and_flags(dev_net(dev), &ipv6_hdr(skb)->saddr, dev, 1, IFA_F_TENTATIVE|IFA_F_OPTIMISTIC)) saddr = &ipv6_hdr(skb)->saddr; probes -= NEIGH_VAR(neigh->parms, UCAST_PROBES); if (probes < 0) { if (!(neigh->nud_state & NUD_VALID)) { ND_PRINTK(1, dbg, "%s: trying to ucast probe in NUD_INVALID: %pI6\n", __func__, target); } ndisc_send_ns(dev, neigh, target, target, saddr); } else if ((probes -= NEIGH_VAR(neigh->parms, APP_PROBES)) < 0) { neigh_app_ns(neigh); } else { addrconf_addr_solict_mult(target, &mcaddr); ndisc_send_ns(dev, NULL, target, &mcaddr, saddr); } } static int pndisc_is_router(const void *pkey, struct net_device *dev) { struct pneigh_entry *n; int ret = -1; read_lock_bh(&nd_tbl.lock); n = __pneigh_lookup(&nd_tbl, dev_net(dev), pkey, dev); if (n) ret = !!(n->flags & NTF_ROUTER); read_unlock_bh(&nd_tbl.lock); return ret; } static void ndisc_recv_ns(struct sk_buff *skb) { struct nd_msg *msg = (struct nd_msg *)skb_transport_header(skb); const struct in6_addr *saddr = &ipv6_hdr(skb)->saddr; const struct in6_addr *daddr = &ipv6_hdr(skb)->daddr; u8 *lladdr = NULL; u32 ndoptlen = skb_tail_pointer(skb) - (skb_transport_header(skb) + offsetof(struct nd_msg, opt)); struct ndisc_options ndopts; struct net_device *dev = skb->dev; struct inet6_ifaddr *ifp; struct inet6_dev *idev = NULL; struct neighbour *neigh; int dad = ipv6_addr_any(saddr); bool inc; int is_router = -1; if (skb->len < sizeof(struct nd_msg)) { ND_PRINTK(2, warn, "NS: packet too short\n"); return; } if (ipv6_addr_is_multicast(&msg->target)) { ND_PRINTK(2, warn, "NS: multicast target address\n"); return; } /* * RFC2461 7.1.1: * DAD has to be destined for solicited node multicast address. */ if (dad && !ipv6_addr_is_solict_mult(daddr)) { ND_PRINTK(2, warn, "NS: bad DAD packet (wrong destination)\n"); return; } if (!ndisc_parse_options(msg->opt, ndoptlen, &ndopts)) { ND_PRINTK(2, warn, "NS: invalid ND options\n"); return; } if (ndopts.nd_opts_src_lladdr) { lladdr = ndisc_opt_addr_data(ndopts.nd_opts_src_lladdr, dev); if (!lladdr) { ND_PRINTK(2, warn, "NS: invalid link-layer address length\n"); return; } /* RFC2461 7.1.1: * If the IP source address is the unspecified address, * there MUST NOT be source link-layer address option * in the message. */ if (dad) { ND_PRINTK(2, warn, "NS: bad DAD packet (link-layer address option)\n"); return; } } inc = ipv6_addr_is_multicast(daddr); ifp = ipv6_get_ifaddr(dev_net(dev), &msg->target, dev, 1); if (ifp) { if (ifp->flags & (IFA_F_TENTATIVE|IFA_F_OPTIMISTIC)) { if (dad) { /* * We are colliding with another node * who is doing DAD * so fail our DAD process */ addrconf_dad_failure(ifp); return; } else { /* * This is not a dad solicitation. * If we are an optimistic node, * we should respond. * Otherwise, we should ignore it. */ if (!(ifp->flags & IFA_F_OPTIMISTIC)) goto out; } } idev = ifp->idev; } else { struct net *net = dev_net(dev); idev = in6_dev_get(dev); if (!idev) { /* XXX: count this drop? */ return; } if (ipv6_chk_acast_addr(net, dev, &msg->target) || (idev->cnf.forwarding && (net->ipv6.devconf_all->proxy_ndp || idev->cnf.proxy_ndp) && (is_router = pndisc_is_router(&msg->target, dev)) >= 0)) { if (!(NEIGH_CB(skb)->flags & LOCALLY_ENQUEUED) && skb->pkt_type != PACKET_HOST && inc && NEIGH_VAR(idev->nd_parms, PROXY_DELAY) != 0) { /* * for anycast or proxy, * sender should delay its response * by a random time between 0 and * MAX_ANYCAST_DELAY_TIME seconds. * (RFC2461) -- yoshfuji */ struct sk_buff *n = skb_clone(skb, GFP_ATOMIC); if (n) pneigh_enqueue(&nd_tbl, idev->nd_parms, n); goto out; } } else goto out; } if (is_router < 0) is_router = idev->cnf.forwarding; if (dad) { ndisc_send_na(dev, NULL, &in6addr_linklocal_allnodes, &msg->target, !!is_router, false, (ifp != NULL), true); goto out; } if (inc) NEIGH_CACHE_STAT_INC(&nd_tbl, rcv_probes_mcast); else NEIGH_CACHE_STAT_INC(&nd_tbl, rcv_probes_ucast); /* * update / create cache entry * for the source address */ neigh = __neigh_lookup(&nd_tbl, saddr, dev, !inc || lladdr || !dev->addr_len); if (neigh) neigh_update(neigh, lladdr, NUD_STALE, NEIGH_UPDATE_F_WEAK_OVERRIDE| NEIGH_UPDATE_F_OVERRIDE); if (neigh || !dev->header_ops) { ndisc_send_na(dev, neigh, saddr, &msg->target, !!is_router, true, (ifp != NULL && inc), inc); if (neigh) neigh_release(neigh); } out: if (ifp) in6_ifa_put(ifp); else in6_dev_put(idev); } static void ndisc_recv_na(struct sk_buff *skb) { struct nd_msg *msg = (struct nd_msg *)skb_transport_header(skb); struct in6_addr *saddr = &ipv6_hdr(skb)->saddr; const struct in6_addr *daddr = &ipv6_hdr(skb)->daddr; u8 *lladdr = NULL; u32 ndoptlen = skb_tail_pointer(skb) - (skb_transport_header(skb) + offsetof(struct nd_msg, opt)); struct ndisc_options ndopts; struct net_device *dev = skb->dev; struct inet6_ifaddr *ifp; struct neighbour *neigh; if (skb->len < sizeof(struct nd_msg)) { ND_PRINTK(2, warn, "NA: packet too short\n"); return; } if (ipv6_addr_is_multicast(&msg->target)) { ND_PRINTK(2, warn, "NA: target address is multicast\n"); return; } if (ipv6_addr_is_multicast(daddr) && msg->icmph.icmp6_solicited) { ND_PRINTK(2, warn, "NA: solicited NA is multicasted\n"); return; } if (!ndisc_parse_options(msg->opt, ndoptlen, &ndopts)) { ND_PRINTK(2, warn, "NS: invalid ND option\n"); return; } if (ndopts.nd_opts_tgt_lladdr) { lladdr = ndisc_opt_addr_data(ndopts.nd_opts_tgt_lladdr, dev); if (!lladdr) { ND_PRINTK(2, warn, "NA: invalid link-layer address length\n"); return; } } ifp = ipv6_get_ifaddr(dev_net(dev), &msg->target, dev, 1); if (ifp) { if (skb->pkt_type != PACKET_LOOPBACK && (ifp->flags & IFA_F_TENTATIVE)) { addrconf_dad_failure(ifp); return; } /* What should we make now? The advertisement is invalid, but ndisc specs say nothing about it. It could be misconfiguration, or an smart proxy agent tries to help us :-) We should not print the error if NA has been received from loopback - it is just our own unsolicited advertisement. */ if (skb->pkt_type != PACKET_LOOPBACK) ND_PRINTK(1, warn, "NA: someone advertises our address %pI6 on %s!\n", &ifp->addr, ifp->idev->dev->name); in6_ifa_put(ifp); return; } neigh = neigh_lookup(&nd_tbl, &msg->target, dev); if (neigh) { u8 old_flags = neigh->flags; struct net *net = dev_net(dev); if (neigh->nud_state & NUD_FAILED) goto out; /* * Don't update the neighbor cache entry on a proxy NA from * ourselves because either the proxied node is off link or it * has already sent a NA to us. */ if (lladdr && !memcmp(lladdr, dev->dev_addr, dev->addr_len) && net->ipv6.devconf_all->forwarding && net->ipv6.devconf_all->proxy_ndp && pneigh_lookup(&nd_tbl, net, &msg->target, dev, 0)) { /* XXX: idev->cnf.proxy_ndp */ goto out; } neigh_update(neigh, lladdr, msg->icmph.icmp6_solicited ? NUD_REACHABLE : NUD_STALE, NEIGH_UPDATE_F_WEAK_OVERRIDE| (msg->icmph.icmp6_override ? NEIGH_UPDATE_F_OVERRIDE : 0)| NEIGH_UPDATE_F_OVERRIDE_ISROUTER| (msg->icmph.icmp6_router ? NEIGH_UPDATE_F_ISROUTER : 0)); if ((old_flags & ~neigh->flags) & NTF_ROUTER) { /* * Change: router to host */ rt6_clean_tohost(dev_net(dev), saddr); } out: neigh_release(neigh); } } static void ndisc_recv_rs(struct sk_buff *skb) { struct rs_msg *rs_msg = (struct rs_msg *)skb_transport_header(skb); unsigned long ndoptlen = skb->len - sizeof(*rs_msg); struct neighbour *neigh; struct inet6_dev *idev; const struct in6_addr *saddr = &ipv6_hdr(skb)->saddr; struct ndisc_options ndopts; u8 *lladdr = NULL; if (skb->len < sizeof(*rs_msg)) return; idev = __in6_dev_get(skb->dev); if (!idev) { ND_PRINTK(1, err, "RS: can't find in6 device\n"); return; } /* Don't accept RS if we're not in router mode */ if (!idev->cnf.forwarding) goto out; /* * Don't update NCE if src = ::; * this implies that the source node has no ip address assigned yet. */ if (ipv6_addr_any(saddr)) goto out; /* Parse ND options */ if (!ndisc_parse_options(rs_msg->opt, ndoptlen, &ndopts)) { ND_PRINTK(2, notice, "NS: invalid ND option, ignored\n"); goto out; } if (ndopts.nd_opts_src_lladdr) { lladdr = ndisc_opt_addr_data(ndopts.nd_opts_src_lladdr, skb->dev); if (!lladdr) goto out; } neigh = __neigh_lookup(&nd_tbl, saddr, skb->dev, 1); if (neigh) { neigh_update(neigh, lladdr, NUD_STALE, NEIGH_UPDATE_F_WEAK_OVERRIDE| NEIGH_UPDATE_F_OVERRIDE| NEIGH_UPDATE_F_OVERRIDE_ISROUTER); neigh_release(neigh); } out: return; } static void ndisc_ra_useropt(struct sk_buff *ra, struct nd_opt_hdr *opt) { struct icmp6hdr *icmp6h = (struct icmp6hdr *)skb_transport_header(ra); struct sk_buff *skb; struct nlmsghdr *nlh; struct nduseroptmsg *ndmsg; struct net *net = dev_net(ra->dev); int err; int base_size = NLMSG_ALIGN(sizeof(struct nduseroptmsg) + (opt->nd_opt_len << 3)); size_t msg_size = base_size + nla_total_size(sizeof(struct in6_addr)); skb = nlmsg_new(msg_size, GFP_ATOMIC); if (skb == NULL) { err = -ENOBUFS; goto errout; } nlh = nlmsg_put(skb, 0, 0, RTM_NEWNDUSEROPT, base_size, 0); if (nlh == NULL) { goto nla_put_failure; } ndmsg = nlmsg_data(nlh); ndmsg->nduseropt_family = AF_INET6; ndmsg->nduseropt_ifindex = ra->dev->ifindex; ndmsg->nduseropt_icmp_type = icmp6h->icmp6_type; ndmsg->nduseropt_icmp_code = icmp6h->icmp6_code; ndmsg->nduseropt_opts_len = opt->nd_opt_len << 3; memcpy(ndmsg + 1, opt, opt->nd_opt_len << 3); if (nla_put(skb, NDUSEROPT_SRCADDR, sizeof(struct in6_addr), &ipv6_hdr(ra)->saddr)) goto nla_put_failure; nlmsg_end(skb, nlh); rtnl_notify(skb, net, 0, RTNLGRP_ND_USEROPT, NULL, GFP_ATOMIC); return; nla_put_failure: nlmsg_free(skb); err = -EMSGSIZE; errout: rtnl_set_sk_err(net, RTNLGRP_ND_USEROPT, err); } static void ndisc_router_discovery(struct sk_buff *skb) { struct ra_msg *ra_msg = (struct ra_msg *)skb_transport_header(skb); struct neighbour *neigh = NULL; struct inet6_dev *in6_dev; struct rt6_info *rt = NULL; int lifetime; struct ndisc_options ndopts; int optlen; unsigned int pref = 0; __u8 *opt = (__u8 *)(ra_msg + 1); optlen = (skb_tail_pointer(skb) - skb_transport_header(skb)) - sizeof(struct ra_msg); ND_PRINTK(2, info, "RA: %s, dev: %s\n", __func__, skb->dev->name); if (!(ipv6_addr_type(&ipv6_hdr(skb)->saddr) & IPV6_ADDR_LINKLOCAL)) { ND_PRINTK(2, warn, "RA: source address is not link-local\n"); return; } if (optlen < 0) { ND_PRINTK(2, warn, "RA: packet too short\n"); return; } #ifdef CONFIG_IPV6_NDISC_NODETYPE if (skb->ndisc_nodetype == NDISC_NODETYPE_HOST) { ND_PRINTK(2, warn, "RA: from host or unauthorized router\n"); return; } #endif /* * set the RA_RECV flag in the interface */ in6_dev = __in6_dev_get(skb->dev); if (in6_dev == NULL) { ND_PRINTK(0, err, "RA: can't find inet6 device for %s\n", skb->dev->name); return; } if (!ndisc_parse_options(opt, optlen, &ndopts)) { ND_PRINTK(2, warn, "RA: invalid ND options\n"); return; } if (!ipv6_accept_ra(in6_dev)) { ND_PRINTK(2, info, "RA: %s, did not accept ra for dev: %s\n", __func__, skb->dev->name); goto skip_linkparms; } #ifdef CONFIG_IPV6_NDISC_NODETYPE /* skip link-specific parameters from interior routers */ if (skb->ndisc_nodetype == NDISC_NODETYPE_NODEFAULT) { ND_PRINTK(2, info, "RA: %s, nodetype is NODEFAULT, dev: %s\n", __func__, skb->dev->name); goto skip_linkparms; } #endif if (in6_dev->if_flags & IF_RS_SENT) { /* * flag that an RA was received after an RS was sent * out on this interface. */ in6_dev->if_flags |= IF_RA_RCVD; } /* * Remember the managed/otherconf flags from most recently * received RA message (RFC 2462) -- yoshfuji */ in6_dev->if_flags = (in6_dev->if_flags & ~(IF_RA_MANAGED | IF_RA_OTHERCONF)) | (ra_msg->icmph.icmp6_addrconf_managed ? IF_RA_MANAGED : 0) | (ra_msg->icmph.icmp6_addrconf_other ? IF_RA_OTHERCONF : 0); if (!in6_dev->cnf.accept_ra_defrtr) { ND_PRINTK(2, info, "RA: %s, defrtr is false for dev: %s\n", __func__, skb->dev->name); goto skip_defrtr; } /* Do not accept RA with source-addr found on local machine unless * accept_ra_from_local is set to true. */ if (!in6_dev->cnf.accept_ra_from_local && ipv6_chk_addr(dev_net(in6_dev->dev), &ipv6_hdr(skb)->saddr, NULL, 0)) { ND_PRINTK(2, info, "RA from local address detected on dev: %s: default router ignored\n", skb->dev->name); goto skip_defrtr; } lifetime = ntohs(ra_msg->icmph.icmp6_rt_lifetime); #ifdef CONFIG_IPV6_ROUTER_PREF pref = ra_msg->icmph.icmp6_router_pref; /* 10b is handled as if it were 00b (medium) */ if (pref == ICMPV6_ROUTER_PREF_INVALID || !in6_dev->cnf.accept_ra_rtr_pref) pref = ICMPV6_ROUTER_PREF_MEDIUM; #endif rt = rt6_get_dflt_router(&ipv6_hdr(skb)->saddr, skb->dev); if (rt) { neigh = dst_neigh_lookup(&rt->dst, &ipv6_hdr(skb)->saddr); if (!neigh) { ND_PRINTK(0, err, "RA: %s got default router without neighbour\n", __func__); ip6_rt_put(rt); return; } } if (rt && lifetime == 0) { ip6_del_rt(rt); rt = NULL; } ND_PRINTK(3, info, "RA: rt: %p lifetime: %d, for dev: %s\n", rt, lifetime, skb->dev->name); if (rt == NULL && lifetime) { ND_PRINTK(3, info, "RA: adding default router\n"); rt = rt6_add_dflt_router(&ipv6_hdr(skb)->saddr, skb->dev, pref); if (rt == NULL) { ND_PRINTK(0, err, "RA: %s failed to add default route\n", __func__); return; } neigh = dst_neigh_lookup(&rt->dst, &ipv6_hdr(skb)->saddr); if (neigh == NULL) { ND_PRINTK(0, err, "RA: %s got default router without neighbour\n", __func__); ip6_rt_put(rt); return; } neigh->flags |= NTF_ROUTER; } else if (rt) { rt->rt6i_flags = (rt->rt6i_flags & ~RTF_PREF_MASK) | RTF_PREF(pref); } if (rt) rt6_set_expires(rt, jiffies + (HZ * lifetime)); if (ra_msg->icmph.icmp6_hop_limit) { in6_dev->cnf.hop_limit = ra_msg->icmph.icmp6_hop_limit; if (rt) dst_metric_set(&rt->dst, RTAX_HOPLIMIT, ra_msg->icmph.icmp6_hop_limit); } skip_defrtr: /* * Update Reachable Time and Retrans Timer */ if (in6_dev->nd_parms) { unsigned long rtime = ntohl(ra_msg->retrans_timer); if (rtime && rtime/1000 < MAX_SCHEDULE_TIMEOUT/HZ) { rtime = (rtime*HZ)/1000; if (rtime < HZ/10) rtime = HZ/10; NEIGH_VAR_SET(in6_dev->nd_parms, RETRANS_TIME, rtime); in6_dev->tstamp = jiffies; inet6_ifinfo_notify(RTM_NEWLINK, in6_dev); } rtime = ntohl(ra_msg->reachable_time); if (rtime && rtime/1000 < MAX_SCHEDULE_TIMEOUT/(3*HZ)) { rtime = (rtime*HZ)/1000; if (rtime < HZ/10) rtime = HZ/10; if (rtime != NEIGH_VAR(in6_dev->nd_parms, BASE_REACHABLE_TIME)) { NEIGH_VAR_SET(in6_dev->nd_parms, BASE_REACHABLE_TIME, rtime); NEIGH_VAR_SET(in6_dev->nd_parms, GC_STALETIME, 3 * rtime); in6_dev->nd_parms->reachable_time = neigh_rand_reach_time(rtime); in6_dev->tstamp = jiffies; inet6_ifinfo_notify(RTM_NEWLINK, in6_dev); } } } skip_linkparms: /* * Process options. */ if (!neigh) neigh = __neigh_lookup(&nd_tbl, &ipv6_hdr(skb)->saddr, skb->dev, 1); if (neigh) { u8 *lladdr = NULL; if (ndopts.nd_opts_src_lladdr) { lladdr = ndisc_opt_addr_data(ndopts.nd_opts_src_lladdr, skb->dev); if (!lladdr) { ND_PRINTK(2, warn, "RA: invalid link-layer address length\n"); goto out; } } neigh_update(neigh, lladdr, NUD_STALE, NEIGH_UPDATE_F_WEAK_OVERRIDE| NEIGH_UPDATE_F_OVERRIDE| NEIGH_UPDATE_F_OVERRIDE_ISROUTER| NEIGH_UPDATE_F_ISROUTER); } if (!ipv6_accept_ra(in6_dev)) { ND_PRINTK(2, info, "RA: %s, accept_ra is false for dev: %s\n", __func__, skb->dev->name); goto out; } #ifdef CONFIG_IPV6_ROUTE_INFO if (!in6_dev->cnf.accept_ra_from_local && ipv6_chk_addr(dev_net(in6_dev->dev), &ipv6_hdr(skb)->saddr, NULL, 0)) { ND_PRINTK(2, info, "RA from local address detected on dev: %s: router info ignored.\n", skb->dev->name); goto skip_routeinfo; } if (in6_dev->cnf.accept_ra_rtr_pref && ndopts.nd_opts_ri) { struct nd_opt_hdr *p; for (p = ndopts.nd_opts_ri; p; p = ndisc_next_option(p, ndopts.nd_opts_ri_end)) { struct route_info *ri = (struct route_info *)p; #ifdef CONFIG_IPV6_NDISC_NODETYPE if (skb->ndisc_nodetype == NDISC_NODETYPE_NODEFAULT && ri->prefix_len == 0) continue; #endif if (ri->prefix_len == 0 && !in6_dev->cnf.accept_ra_defrtr) continue; if (ri->prefix_len > in6_dev->cnf.accept_ra_rt_info_max_plen) continue; rt6_route_rcv(skb->dev, (u8 *)p, (p->nd_opt_len) << 3, &ipv6_hdr(skb)->saddr); } } skip_routeinfo: #endif #ifdef CONFIG_IPV6_NDISC_NODETYPE /* skip link-specific ndopts from interior routers */ if (skb->ndisc_nodetype == NDISC_NODETYPE_NODEFAULT) { ND_PRINTK(2, info, "RA: %s, nodetype is NODEFAULT (interior routes), dev: %s\n", __func__, skb->dev->name); goto out; } #endif if (in6_dev->cnf.accept_ra_pinfo && ndopts.nd_opts_pi) { struct nd_opt_hdr *p; for (p = ndopts.nd_opts_pi; p; p = ndisc_next_option(p, ndopts.nd_opts_pi_end)) { addrconf_prefix_rcv(skb->dev, (u8 *)p, (p->nd_opt_len) << 3, ndopts.nd_opts_src_lladdr != NULL); } } if (ndopts.nd_opts_mtu && in6_dev->cnf.accept_ra_mtu) { __be32 n; u32 mtu; memcpy(&n, ((u8 *)(ndopts.nd_opts_mtu+1))+2, sizeof(mtu)); mtu = ntohl(n); if (mtu < IPV6_MIN_MTU || mtu > skb->dev->mtu) { ND_PRINTK(2, warn, "RA: invalid mtu: %d\n", mtu); } else if (in6_dev->cnf.mtu6 != mtu) { in6_dev->cnf.mtu6 = mtu; if (rt) dst_metric_set(&rt->dst, RTAX_MTU, mtu); rt6_mtu_change(skb->dev, mtu); } } if (ndopts.nd_useropts) { struct nd_opt_hdr *p; for (p = ndopts.nd_useropts; p; p = ndisc_next_useropt(p, ndopts.nd_useropts_end)) { ndisc_ra_useropt(skb, p); } } if (ndopts.nd_opts_tgt_lladdr || ndopts.nd_opts_rh) { ND_PRINTK(2, warn, "RA: invalid RA options\n"); } out: ip6_rt_put(rt); if (neigh) neigh_release(neigh); } static void ndisc_redirect_rcv(struct sk_buff *skb) { u8 *hdr; struct ndisc_options ndopts; struct rd_msg *msg = (struct rd_msg *)skb_transport_header(skb); u32 ndoptlen = skb_tail_pointer(skb) - (skb_transport_header(skb) + offsetof(struct rd_msg, opt)); #ifdef CONFIG_IPV6_NDISC_NODETYPE switch (skb->ndisc_nodetype) { case NDISC_NODETYPE_HOST: case NDISC_NODETYPE_NODEFAULT: ND_PRINTK(2, warn, "Redirect: from host or unauthorized router\n"); return; } #endif if (!(ipv6_addr_type(&ipv6_hdr(skb)->saddr) & IPV6_ADDR_LINKLOCAL)) { ND_PRINTK(2, warn, "Redirect: source address is not link-local\n"); return; } if (!ndisc_parse_options(msg->opt, ndoptlen, &ndopts)) return; if (!ndopts.nd_opts_rh) { ip6_redirect_no_header(skb, dev_net(skb->dev), skb->dev->ifindex, 0); return; } hdr = (u8 *)ndopts.nd_opts_rh; hdr += 8; if (!pskb_pull(skb, hdr - skb_transport_header(skb))) return; icmpv6_notify(skb, NDISC_REDIRECT, 0, 0); } static void ndisc_fill_redirect_hdr_option(struct sk_buff *skb, struct sk_buff *orig_skb, int rd_len) { u8 *opt = skb_put(skb, rd_len); memset(opt, 0, 8); *(opt++) = ND_OPT_REDIRECT_HDR; *(opt++) = (rd_len >> 3); opt += 6; memcpy(opt, ipv6_hdr(orig_skb), rd_len - 8); } void ndisc_send_redirect(struct sk_buff *skb, const struct in6_addr *target) { struct net_device *dev = skb->dev; struct net *net = dev_net(dev); struct sock *sk = net->ipv6.ndisc_sk; int optlen = 0; struct inet_peer *peer; struct sk_buff *buff; struct rd_msg *msg; struct in6_addr saddr_buf; struct rt6_info *rt; struct dst_entry *dst; struct flowi6 fl6; int rd_len; u8 ha_buf[MAX_ADDR_LEN], *ha = NULL; bool ret; if (ipv6_get_lladdr(dev, &saddr_buf, IFA_F_TENTATIVE)) { ND_PRINTK(2, warn, "Redirect: no link-local address on %s\n", dev->name); return; } if (!ipv6_addr_equal(&ipv6_hdr(skb)->daddr, target) && ipv6_addr_type(target) != (IPV6_ADDR_UNICAST|IPV6_ADDR_LINKLOCAL)) { ND_PRINTK(2, warn, "Redirect: target address is not link-local unicast\n"); return; } icmpv6_flow_init(sk, &fl6, NDISC_REDIRECT, &saddr_buf, &ipv6_hdr(skb)->saddr, dev->ifindex); dst = ip6_route_output(net, NULL, &fl6); if (dst->error) { dst_release(dst); return; } dst = xfrm_lookup(net, dst, flowi6_to_flowi(&fl6), NULL, 0); if (IS_ERR(dst)) return; rt = (struct rt6_info *) dst; if (rt->rt6i_flags & RTF_GATEWAY) { ND_PRINTK(2, warn, "Redirect: destination is not a neighbour\n"); goto release; } peer = inet_getpeer_v6(net->ipv6.peers, &rt->rt6i_dst.addr, 1); ret = inet_peer_xrlim_allow(peer, 1*HZ); if (peer) inet_putpeer(peer); if (!ret) goto release; if (dev->addr_len) { struct neighbour *neigh = dst_neigh_lookup(skb_dst(skb), target); if (!neigh) { ND_PRINTK(2, warn, "Redirect: no neigh for target address\n"); goto release; } read_lock_bh(&neigh->lock); if (neigh->nud_state & NUD_VALID) { memcpy(ha_buf, neigh->ha, dev->addr_len); read_unlock_bh(&neigh->lock); ha = ha_buf; optlen += ndisc_opt_addr_space(dev); } else read_unlock_bh(&neigh->lock); neigh_release(neigh); } rd_len = min_t(unsigned int, IPV6_MIN_MTU - sizeof(struct ipv6hdr) - sizeof(*msg) - optlen, skb->len + 8); rd_len &= ~0x7; optlen += rd_len; buff = ndisc_alloc_skb(dev, sizeof(*msg) + optlen); if (!buff) goto release; msg = (struct rd_msg *)skb_put(buff, sizeof(*msg)); *msg = (struct rd_msg) { .icmph = { .icmp6_type = NDISC_REDIRECT, }, .target = *target, .dest = ipv6_hdr(skb)->daddr, }; /* * include target_address option */ if (ha) ndisc_fill_addr_option(buff, ND_OPT_TARGET_LL_ADDR, ha); /* * build redirect option and copy skb over to the new packet. */ if (rd_len) ndisc_fill_redirect_hdr_option(buff, skb, rd_len); skb_dst_set(buff, dst); ndisc_send_skb(buff, &ipv6_hdr(skb)->saddr, &saddr_buf); return; release: dst_release(dst); } static void pndisc_redo(struct sk_buff *skb) { ndisc_recv_ns(skb); kfree_skb(skb); } static bool ndisc_suppress_frag_ndisc(struct sk_buff *skb) { struct inet6_dev *idev = __in6_dev_get(skb->dev); if (!idev) return true; if (IP6CB(skb)->flags & IP6SKB_FRAGMENTED && idev->cnf.suppress_frag_ndisc) { net_warn_ratelimited("Received fragmented ndisc packet. Carefully consider disabling suppress_frag_ndisc.\n"); return true; } return false; } int ndisc_rcv(struct sk_buff *skb) { struct nd_msg *msg; if (ndisc_suppress_frag_ndisc(skb)) return 0; if (skb_linearize(skb)) return 0; msg = (struct nd_msg *)skb_transport_header(skb); __skb_push(skb, skb->data - skb_transport_header(skb)); if (ipv6_hdr(skb)->hop_limit != 255) { ND_PRINTK(2, warn, "NDISC: invalid hop-limit: %d\n", ipv6_hdr(skb)->hop_limit); return 0; } if (msg->icmph.icmp6_code != 0) { ND_PRINTK(2, warn, "NDISC: invalid ICMPv6 code: %d\n", msg->icmph.icmp6_code); return 0; } memset(NEIGH_CB(skb), 0, sizeof(struct neighbour_cb)); switch (msg->icmph.icmp6_type) { case NDISC_NEIGHBOUR_SOLICITATION: ndisc_recv_ns(skb); break; case NDISC_NEIGHBOUR_ADVERTISEMENT: ndisc_recv_na(skb); break; case NDISC_ROUTER_SOLICITATION: ndisc_recv_rs(skb); break; case NDISC_ROUTER_ADVERTISEMENT: ndisc_router_discovery(skb); break; case NDISC_REDIRECT: ndisc_redirect_rcv(skb); break; } return 0; } static int ndisc_netdev_event(struct notifier_block *this, unsigned long event, void *ptr) { struct net_device *dev = netdev_notifier_info_to_dev(ptr); struct net *net = dev_net(dev); struct inet6_dev *idev; switch (event) { case NETDEV_CHANGEADDR: neigh_changeaddr(&nd_tbl, dev); fib6_run_gc(0, net, false); idev = in6_dev_get(dev); if (!idev) break; if (idev->cnf.ndisc_notify) ndisc_send_unsol_na(dev); in6_dev_put(idev); break; case NETDEV_DOWN: neigh_ifdown(&nd_tbl, dev); fib6_run_gc(0, net, false); break; case NETDEV_NOTIFY_PEERS: ndisc_send_unsol_na(dev); break; default: break; } return NOTIFY_DONE; } static struct notifier_block ndisc_netdev_notifier = { .notifier_call = ndisc_netdev_event, }; #ifdef CONFIG_SYSCTL static void ndisc_warn_deprecated_sysctl(struct ctl_table *ctl, const char *func, const char *dev_name) { static char warncomm[TASK_COMM_LEN]; static int warned; if (strcmp(warncomm, current->comm) && warned < 5) { strcpy(warncomm, current->comm); pr_warn("process `%s' is using deprecated sysctl (%s) net.ipv6.neigh.%s.%s - use net.ipv6.neigh.%s.%s_ms instead\n", warncomm, func, dev_name, ctl->procname, dev_name, ctl->procname); warned++; } } int ndisc_ifinfo_sysctl_change(struct ctl_table *ctl, int write, void __user *buffer, size_t *lenp, loff_t *ppos) { struct net_device *dev = ctl->extra1; struct inet6_dev *idev; int ret; if ((strcmp(ctl->procname, "retrans_time") == 0) || (strcmp(ctl->procname, "base_reachable_time") == 0)) ndisc_warn_deprecated_sysctl(ctl, "syscall", dev ? dev->name : "default"); if (strcmp(ctl->procname, "retrans_time") == 0) ret = neigh_proc_dointvec(ctl, write, buffer, lenp, ppos); else if (strcmp(ctl->procname, "base_reachable_time") == 0) ret = neigh_proc_dointvec_jiffies(ctl, write, buffer, lenp, ppos); else if ((strcmp(ctl->procname, "retrans_time_ms") == 0) || (strcmp(ctl->procname, "base_reachable_time_ms") == 0)) ret = neigh_proc_dointvec_ms_jiffies(ctl, write, buffer, lenp, ppos); else ret = -1; if (write && ret == 0 && dev && (idev = in6_dev_get(dev)) != NULL) { if (ctl->data == &NEIGH_VAR(idev->nd_parms, BASE_REACHABLE_TIME)) idev->nd_parms->reachable_time = neigh_rand_reach_time(NEIGH_VAR(idev->nd_parms, BASE_REACHABLE_TIME)); idev->tstamp = jiffies; inet6_ifinfo_notify(RTM_NEWLINK, idev); in6_dev_put(idev); } return ret; } #endif static int __net_init ndisc_net_init(struct net *net) { struct ipv6_pinfo *np; struct sock *sk; int err; err = inet_ctl_sock_create(&sk, PF_INET6, SOCK_RAW, IPPROTO_ICMPV6, net); if (err < 0) { ND_PRINTK(0, err, "NDISC: Failed to initialize the control socket (err %d)\n", err); return err; } net->ipv6.ndisc_sk = sk; np = inet6_sk(sk); np->hop_limit = 255; /* Do not loopback ndisc messages */ np->mc_loop = 0; return 0; } static void __net_exit ndisc_net_exit(struct net *net) { inet_ctl_sock_destroy(net->ipv6.ndisc_sk); } static struct pernet_operations ndisc_net_ops = { .init = ndisc_net_init, .exit = ndisc_net_exit, }; int __init ndisc_init(void) { int err; err = register_pernet_subsys(&ndisc_net_ops); if (err) return err; /* * Initialize the neighbour table */ neigh_table_init(NEIGH_ND_TABLE, &nd_tbl); #ifdef CONFIG_SYSCTL err = neigh_sysctl_register(NULL, &nd_tbl.parms, ndisc_ifinfo_sysctl_change); if (err) goto out_unregister_pernet; out: #endif return err; #ifdef CONFIG_SYSCTL out_unregister_pernet: unregister_pernet_subsys(&ndisc_net_ops); goto out; #endif } int __init ndisc_late_init(void) { return register_netdevice_notifier(&ndisc_netdev_notifier); } void ndisc_late_cleanup(void) { unregister_netdevice_notifier(&ndisc_netdev_notifier); } void ndisc_cleanup(void) { #ifdef CONFIG_SYSCTL neigh_sysctl_unregister(&nd_tbl.parms); #endif neigh_table_clear(NEIGH_ND_TABLE, &nd_tbl); unregister_pernet_subsys(&ndisc_net_ops); }
./CrossVul/dataset_final_sorted/CWE-17/c/bad_1546_0
crossvul-cpp_data_bad_1499_2
#include <linux/export.h> #include <linux/uio.h> #include <linux/pagemap.h> #include <linux/slab.h> #include <linux/vmalloc.h> size_t copy_page_to_iter(struct page *page, size_t offset, size_t bytes, struct iov_iter *i) { size_t skip, copy, left, wanted; const struct iovec *iov; char __user *buf; void *kaddr, *from; if (unlikely(bytes > i->count)) bytes = i->count; if (unlikely(!bytes)) return 0; wanted = bytes; iov = i->iov; skip = i->iov_offset; buf = iov->iov_base + skip; copy = min(bytes, iov->iov_len - skip); if (!fault_in_pages_writeable(buf, copy)) { kaddr = kmap_atomic(page); from = kaddr + offset; /* first chunk, usually the only one */ left = __copy_to_user_inatomic(buf, from, copy); copy -= left; skip += copy; from += copy; bytes -= copy; while (unlikely(!left && bytes)) { iov++; buf = iov->iov_base; copy = min(bytes, iov->iov_len); left = __copy_to_user_inatomic(buf, from, copy); copy -= left; skip = copy; from += copy; bytes -= copy; } if (likely(!bytes)) { kunmap_atomic(kaddr); goto done; } offset = from - kaddr; buf += copy; kunmap_atomic(kaddr); copy = min(bytes, iov->iov_len - skip); } /* Too bad - revert to non-atomic kmap */ kaddr = kmap(page); from = kaddr + offset; left = __copy_to_user(buf, from, copy); copy -= left; skip += copy; from += copy; bytes -= copy; while (unlikely(!left && bytes)) { iov++; buf = iov->iov_base; copy = min(bytes, iov->iov_len); left = __copy_to_user(buf, from, copy); copy -= left; skip = copy; from += copy; bytes -= copy; } kunmap(page); done: i->count -= wanted - bytes; i->nr_segs -= iov - i->iov; i->iov = iov; i->iov_offset = skip; return wanted - bytes; } EXPORT_SYMBOL(copy_page_to_iter); static size_t __iovec_copy_from_user_inatomic(char *vaddr, const struct iovec *iov, size_t base, size_t bytes) { size_t copied = 0, left = 0; while (bytes) { char __user *buf = iov->iov_base + base; int copy = min(bytes, iov->iov_len - base); base = 0; left = __copy_from_user_inatomic(vaddr, buf, copy); copied += copy; bytes -= copy; vaddr += copy; iov++; if (unlikely(left)) break; } return copied - left; } /* * Copy as much as we can into the page and return the number of bytes which * were successfully copied. If a fault is encountered then return the number of * bytes which were copied. */ size_t iov_iter_copy_from_user_atomic(struct page *page, struct iov_iter *i, unsigned long offset, size_t bytes) { char *kaddr; size_t copied; kaddr = kmap_atomic(page); if (likely(i->nr_segs == 1)) { int left; char __user *buf = i->iov->iov_base + i->iov_offset; left = __copy_from_user_inatomic(kaddr + offset, buf, bytes); copied = bytes - left; } else { copied = __iovec_copy_from_user_inatomic(kaddr + offset, i->iov, i->iov_offset, bytes); } kunmap_atomic(kaddr); return copied; } EXPORT_SYMBOL(iov_iter_copy_from_user_atomic); void iov_iter_advance(struct iov_iter *i, size_t bytes) { BUG_ON(i->count < bytes); if (likely(i->nr_segs == 1)) { i->iov_offset += bytes; i->count -= bytes; } else { const struct iovec *iov = i->iov; size_t base = i->iov_offset; unsigned long nr_segs = i->nr_segs; /* * The !iov->iov_len check ensures we skip over unlikely * zero-length segments (without overruning the iovec). */ while (bytes || unlikely(i->count && !iov->iov_len)) { int copy; copy = min(bytes, iov->iov_len - base); BUG_ON(!i->count || i->count < copy); i->count -= copy; bytes -= copy; base += copy; if (iov->iov_len == base) { iov++; nr_segs--; base = 0; } } i->iov = iov; i->iov_offset = base; i->nr_segs = nr_segs; } } EXPORT_SYMBOL(iov_iter_advance); /* * Fault in the first iovec of the given iov_iter, to a maximum length * of bytes. Returns 0 on success, or non-zero if the memory could not be * accessed (ie. because it is an invalid address). * * writev-intensive code may want this to prefault several iovecs -- that * would be possible (callers must not rely on the fact that _only_ the * first iovec will be faulted with the current implementation). */ int iov_iter_fault_in_readable(struct iov_iter *i, size_t bytes) { char __user *buf = i->iov->iov_base + i->iov_offset; bytes = min(bytes, i->iov->iov_len - i->iov_offset); return fault_in_pages_readable(buf, bytes); } EXPORT_SYMBOL(iov_iter_fault_in_readable); /* * Return the count of just the current iov_iter segment. */ size_t iov_iter_single_seg_count(const struct iov_iter *i) { const struct iovec *iov = i->iov; if (i->nr_segs == 1) return i->count; else return min(i->count, iov->iov_len - i->iov_offset); } EXPORT_SYMBOL(iov_iter_single_seg_count); unsigned long iov_iter_alignment(const struct iov_iter *i) { const struct iovec *iov = i->iov; unsigned long res; size_t size = i->count; size_t n; if (!size) return 0; res = (unsigned long)iov->iov_base + i->iov_offset; n = iov->iov_len - i->iov_offset; if (n >= size) return res | size; size -= n; res |= n; while (size > (++iov)->iov_len) { res |= (unsigned long)iov->iov_base | iov->iov_len; size -= iov->iov_len; } res |= (unsigned long)iov->iov_base | size; return res; } EXPORT_SYMBOL(iov_iter_alignment); void iov_iter_init(struct iov_iter *i, int direction, const struct iovec *iov, unsigned long nr_segs, size_t count) { /* It will get better. Eventually... */ if (segment_eq(get_fs(), KERNEL_DS)) direction |= REQ_KERNEL; i->type = direction; i->iov = iov; i->nr_segs = nr_segs; i->iov_offset = 0; i->count = count; } EXPORT_SYMBOL(iov_iter_init); ssize_t iov_iter_get_pages(struct iov_iter *i, struct page **pages, size_t maxsize, size_t *start) { size_t offset = i->iov_offset; const struct iovec *iov = i->iov; size_t len; unsigned long addr; int n; int res; len = iov->iov_len - offset; if (len > i->count) len = i->count; if (len > maxsize) len = maxsize; addr = (unsigned long)iov->iov_base + offset; len += *start = addr & (PAGE_SIZE - 1); addr &= ~(PAGE_SIZE - 1); n = (len + PAGE_SIZE - 1) / PAGE_SIZE; res = get_user_pages_fast(addr, n, (i->type & WRITE) != WRITE, pages); if (unlikely(res < 0)) return res; return (res == n ? len : res * PAGE_SIZE) - *start; } EXPORT_SYMBOL(iov_iter_get_pages); ssize_t iov_iter_get_pages_alloc(struct iov_iter *i, struct page ***pages, size_t maxsize, size_t *start) { size_t offset = i->iov_offset; const struct iovec *iov = i->iov; size_t len; unsigned long addr; void *p; int n; int res; len = iov->iov_len - offset; if (len > i->count) len = i->count; if (len > maxsize) len = maxsize; addr = (unsigned long)iov->iov_base + offset; len += *start = addr & (PAGE_SIZE - 1); addr &= ~(PAGE_SIZE - 1); n = (len + PAGE_SIZE - 1) / PAGE_SIZE; p = kmalloc(n * sizeof(struct page *), GFP_KERNEL); if (!p) p = vmalloc(n * sizeof(struct page *)); if (!p) return -ENOMEM; res = get_user_pages_fast(addr, n, (i->type & WRITE) != WRITE, p); if (unlikely(res < 0)) { kvfree(p); return res; } *pages = p; return (res == n ? len : res * PAGE_SIZE) - *start; } EXPORT_SYMBOL(iov_iter_get_pages_alloc); int iov_iter_npages(const struct iov_iter *i, int maxpages) { size_t offset = i->iov_offset; size_t size = i->count; const struct iovec *iov = i->iov; int npages = 0; int n; for (n = 0; size && n < i->nr_segs; n++, iov++) { unsigned long addr = (unsigned long)iov->iov_base + offset; size_t len = iov->iov_len - offset; offset = 0; if (unlikely(!len)) /* empty segment */ continue; if (len > size) len = size; npages += (addr + len + PAGE_SIZE - 1) / PAGE_SIZE - addr / PAGE_SIZE; if (npages >= maxpages) /* don't bother going further */ return maxpages; size -= len; offset = 0; } return min(npages, maxpages); } EXPORT_SYMBOL(iov_iter_npages);
./CrossVul/dataset_final_sorted/CWE-17/c/bad_1499_2
crossvul-cpp_data_good_2415_2
/* * symlink.c * * PURPOSE * Symlink handling routines for the OSTA-UDF(tm) filesystem. * * COPYRIGHT * This file is distributed under the terms of the GNU General Public * License (GPL). Copies of the GPL can be obtained from: * ftp://prep.ai.mit.edu/pub/gnu/GPL * Each contributing author retains all rights to their own work. * * (C) 1998-2001 Ben Fennema * (C) 1999 Stelias Computing Inc * * HISTORY * * 04/16/99 blf Created. * */ #include "udfdecl.h" #include <linux/uaccess.h> #include <linux/errno.h> #include <linux/fs.h> #include <linux/time.h> #include <linux/mm.h> #include <linux/stat.h> #include <linux/pagemap.h> #include <linux/buffer_head.h> #include "udf_i.h" static int udf_pc_to_char(struct super_block *sb, unsigned char *from, int fromlen, unsigned char *to, int tolen) { struct pathComponent *pc; int elen = 0; int comp_len; unsigned char *p = to; /* Reserve one byte for terminating \0 */ tolen--; while (elen < fromlen) { pc = (struct pathComponent *)(from + elen); switch (pc->componentType) { case 1: /* * Symlink points to some place which should be agreed * upon between originator and receiver of the media. Ignore. */ if (pc->lengthComponentIdent > 0) break; /* Fall through */ case 2: if (tolen == 0) return -ENAMETOOLONG; p = to; *p++ = '/'; tolen--; break; case 3: if (tolen < 3) return -ENAMETOOLONG; memcpy(p, "../", 3); p += 3; tolen -= 3; break; case 4: if (tolen < 2) return -ENAMETOOLONG; memcpy(p, "./", 2); p += 2; tolen -= 2; /* that would be . - just ignore */ break; case 5: comp_len = udf_get_filename(sb, pc->componentIdent, pc->lengthComponentIdent, p, tolen); p += comp_len; tolen -= comp_len; if (tolen == 0) return -ENAMETOOLONG; *p++ = '/'; tolen--; break; } elen += sizeof(struct pathComponent) + pc->lengthComponentIdent; } if (p > to + 1) p[-1] = '\0'; else p[0] = '\0'; return 0; } static int udf_symlink_filler(struct file *file, struct page *page) { struct inode *inode = page->mapping->host; struct buffer_head *bh = NULL; unsigned char *symlink; int err; unsigned char *p = kmap(page); struct udf_inode_info *iinfo; uint32_t pos; /* We don't support symlinks longer than one block */ if (inode->i_size > inode->i_sb->s_blocksize) { err = -ENAMETOOLONG; goto out_unmap; } iinfo = UDF_I(inode); pos = udf_block_map(inode, 0); down_read(&iinfo->i_data_sem); if (iinfo->i_alloc_type == ICBTAG_FLAG_AD_IN_ICB) { symlink = iinfo->i_ext.i_data + iinfo->i_lenEAttr; } else { bh = sb_bread(inode->i_sb, pos); if (!bh) { err = -EIO; goto out_unlock_inode; } symlink = bh->b_data; } err = udf_pc_to_char(inode->i_sb, symlink, inode->i_size, p, PAGE_SIZE); brelse(bh); if (err) goto out_unlock_inode; up_read(&iinfo->i_data_sem); SetPageUptodate(page); kunmap(page); unlock_page(page); return 0; out_unlock_inode: up_read(&iinfo->i_data_sem); SetPageError(page); out_unmap: kunmap(page); unlock_page(page); return err; } /* * symlinks can't do much... */ const struct address_space_operations udf_symlink_aops = { .readpage = udf_symlink_filler, };
./CrossVul/dataset_final_sorted/CWE-17/c/good_2415_2
crossvul-cpp_data_bad_1499_0
/* * linux/fs/pipe.c * * Copyright (C) 1991, 1992, 1999 Linus Torvalds */ #include <linux/mm.h> #include <linux/file.h> #include <linux/poll.h> #include <linux/slab.h> #include <linux/module.h> #include <linux/init.h> #include <linux/fs.h> #include <linux/log2.h> #include <linux/mount.h> #include <linux/magic.h> #include <linux/pipe_fs_i.h> #include <linux/uio.h> #include <linux/highmem.h> #include <linux/pagemap.h> #include <linux/audit.h> #include <linux/syscalls.h> #include <linux/fcntl.h> #include <linux/aio.h> #include <asm/uaccess.h> #include <asm/ioctls.h> #include "internal.h" /* * The max size that a non-root user is allowed to grow the pipe. Can * be set by root in /proc/sys/fs/pipe-max-size */ unsigned int pipe_max_size = 1048576; /* * Minimum pipe size, as required by POSIX */ unsigned int pipe_min_size = PAGE_SIZE; /* * We use a start+len construction, which provides full use of the * allocated memory. * -- Florian Coosmann (FGC) * * Reads with count = 0 should always return 0. * -- Julian Bradfield 1999-06-07. * * FIFOs and Pipes now generate SIGIO for both readers and writers. * -- Jeremy Elson <jelson@circlemud.org> 2001-08-16 * * pipe_read & write cleanup * -- Manfred Spraul <manfred@colorfullife.com> 2002-05-09 */ static void pipe_lock_nested(struct pipe_inode_info *pipe, int subclass) { if (pipe->files) mutex_lock_nested(&pipe->mutex, subclass); } void pipe_lock(struct pipe_inode_info *pipe) { /* * pipe_lock() nests non-pipe inode locks (for writing to a file) */ pipe_lock_nested(pipe, I_MUTEX_PARENT); } EXPORT_SYMBOL(pipe_lock); void pipe_unlock(struct pipe_inode_info *pipe) { if (pipe->files) mutex_unlock(&pipe->mutex); } EXPORT_SYMBOL(pipe_unlock); static inline void __pipe_lock(struct pipe_inode_info *pipe) { mutex_lock_nested(&pipe->mutex, I_MUTEX_PARENT); } static inline void __pipe_unlock(struct pipe_inode_info *pipe) { mutex_unlock(&pipe->mutex); } void pipe_double_lock(struct pipe_inode_info *pipe1, struct pipe_inode_info *pipe2) { BUG_ON(pipe1 == pipe2); if (pipe1 < pipe2) { pipe_lock_nested(pipe1, I_MUTEX_PARENT); pipe_lock_nested(pipe2, I_MUTEX_CHILD); } else { pipe_lock_nested(pipe2, I_MUTEX_PARENT); pipe_lock_nested(pipe1, I_MUTEX_CHILD); } } /* Drop the inode semaphore and wait for a pipe event, atomically */ void pipe_wait(struct pipe_inode_info *pipe) { DEFINE_WAIT(wait); /* * Pipes are system-local resources, so sleeping on them * is considered a noninteractive wait: */ prepare_to_wait(&pipe->wait, &wait, TASK_INTERRUPTIBLE); pipe_unlock(pipe); schedule(); finish_wait(&pipe->wait, &wait); pipe_lock(pipe); } static int pipe_iov_copy_from_user(void *to, struct iovec *iov, unsigned long len, int atomic) { unsigned long copy; while (len > 0) { while (!iov->iov_len) iov++; copy = min_t(unsigned long, len, iov->iov_len); if (atomic) { if (__copy_from_user_inatomic(to, iov->iov_base, copy)) return -EFAULT; } else { if (copy_from_user(to, iov->iov_base, copy)) return -EFAULT; } to += copy; len -= copy; iov->iov_base += copy; iov->iov_len -= copy; } return 0; } /* * Pre-fault in the user memory, so we can use atomic copies. */ static void iov_fault_in_pages_read(struct iovec *iov, unsigned long len) { while (!iov->iov_len) iov++; while (len > 0) { unsigned long this_len; this_len = min_t(unsigned long, len, iov->iov_len); fault_in_pages_readable(iov->iov_base, this_len); len -= this_len; iov++; } } static void anon_pipe_buf_release(struct pipe_inode_info *pipe, struct pipe_buffer *buf) { struct page *page = buf->page; /* * If nobody else uses this page, and we don't already have a * temporary page, let's keep track of it as a one-deep * allocation cache. (Otherwise just release our reference to it) */ if (page_count(page) == 1 && !pipe->tmp_page) pipe->tmp_page = page; else page_cache_release(page); } /** * generic_pipe_buf_steal - attempt to take ownership of a &pipe_buffer * @pipe: the pipe that the buffer belongs to * @buf: the buffer to attempt to steal * * Description: * This function attempts to steal the &struct page attached to * @buf. If successful, this function returns 0 and returns with * the page locked. The caller may then reuse the page for whatever * he wishes; the typical use is insertion into a different file * page cache. */ int generic_pipe_buf_steal(struct pipe_inode_info *pipe, struct pipe_buffer *buf) { struct page *page = buf->page; /* * A reference of one is golden, that means that the owner of this * page is the only one holding a reference to it. lock the page * and return OK. */ if (page_count(page) == 1) { lock_page(page); return 0; } return 1; } EXPORT_SYMBOL(generic_pipe_buf_steal); /** * generic_pipe_buf_get - get a reference to a &struct pipe_buffer * @pipe: the pipe that the buffer belongs to * @buf: the buffer to get a reference to * * Description: * This function grabs an extra reference to @buf. It's used in * in the tee() system call, when we duplicate the buffers in one * pipe into another. */ void generic_pipe_buf_get(struct pipe_inode_info *pipe, struct pipe_buffer *buf) { page_cache_get(buf->page); } EXPORT_SYMBOL(generic_pipe_buf_get); /** * generic_pipe_buf_confirm - verify contents of the pipe buffer * @info: the pipe that the buffer belongs to * @buf: the buffer to confirm * * Description: * This function does nothing, because the generic pipe code uses * pages that are always good when inserted into the pipe. */ int generic_pipe_buf_confirm(struct pipe_inode_info *info, struct pipe_buffer *buf) { return 0; } EXPORT_SYMBOL(generic_pipe_buf_confirm); /** * generic_pipe_buf_release - put a reference to a &struct pipe_buffer * @pipe: the pipe that the buffer belongs to * @buf: the buffer to put a reference to * * Description: * This function releases a reference to @buf. */ void generic_pipe_buf_release(struct pipe_inode_info *pipe, struct pipe_buffer *buf) { page_cache_release(buf->page); } EXPORT_SYMBOL(generic_pipe_buf_release); static const struct pipe_buf_operations anon_pipe_buf_ops = { .can_merge = 1, .confirm = generic_pipe_buf_confirm, .release = anon_pipe_buf_release, .steal = generic_pipe_buf_steal, .get = generic_pipe_buf_get, }; static const struct pipe_buf_operations packet_pipe_buf_ops = { .can_merge = 0, .confirm = generic_pipe_buf_confirm, .release = anon_pipe_buf_release, .steal = generic_pipe_buf_steal, .get = generic_pipe_buf_get, }; static ssize_t pipe_read(struct kiocb *iocb, struct iov_iter *to) { size_t total_len = iov_iter_count(to); struct file *filp = iocb->ki_filp; struct pipe_inode_info *pipe = filp->private_data; int do_wakeup; ssize_t ret; /* Null read succeeds. */ if (unlikely(total_len == 0)) return 0; do_wakeup = 0; ret = 0; __pipe_lock(pipe); for (;;) { int bufs = pipe->nrbufs; if (bufs) { int curbuf = pipe->curbuf; struct pipe_buffer *buf = pipe->bufs + curbuf; const struct pipe_buf_operations *ops = buf->ops; size_t chars = buf->len; size_t written; int error; if (chars > total_len) chars = total_len; error = ops->confirm(pipe, buf); if (error) { if (!ret) ret = error; break; } written = copy_page_to_iter(buf->page, buf->offset, chars, to); if (unlikely(written < chars)) { if (!ret) ret = -EFAULT; break; } ret += chars; buf->offset += chars; buf->len -= chars; /* Was it a packet buffer? Clean up and exit */ if (buf->flags & PIPE_BUF_FLAG_PACKET) { total_len = chars; buf->len = 0; } if (!buf->len) { buf->ops = NULL; ops->release(pipe, buf); curbuf = (curbuf + 1) & (pipe->buffers - 1); pipe->curbuf = curbuf; pipe->nrbufs = --bufs; do_wakeup = 1; } total_len -= chars; if (!total_len) break; /* common path: read succeeded */ } if (bufs) /* More to do? */ continue; if (!pipe->writers) break; if (!pipe->waiting_writers) { /* syscall merging: Usually we must not sleep * if O_NONBLOCK is set, or if we got some data. * But if a writer sleeps in kernel space, then * we can wait for that data without violating POSIX. */ if (ret) break; if (filp->f_flags & O_NONBLOCK) { ret = -EAGAIN; break; } } if (signal_pending(current)) { if (!ret) ret = -ERESTARTSYS; break; } if (do_wakeup) { wake_up_interruptible_sync_poll(&pipe->wait, POLLOUT | POLLWRNORM); kill_fasync(&pipe->fasync_writers, SIGIO, POLL_OUT); } pipe_wait(pipe); } __pipe_unlock(pipe); /* Signal writers asynchronously that there is more room. */ if (do_wakeup) { wake_up_interruptible_sync_poll(&pipe->wait, POLLOUT | POLLWRNORM); kill_fasync(&pipe->fasync_writers, SIGIO, POLL_OUT); } if (ret > 0) file_accessed(filp); return ret; } static inline int is_packetized(struct file *file) { return (file->f_flags & O_DIRECT) != 0; } static ssize_t pipe_write(struct kiocb *iocb, const struct iovec *_iov, unsigned long nr_segs, loff_t ppos) { struct file *filp = iocb->ki_filp; struct pipe_inode_info *pipe = filp->private_data; ssize_t ret; int do_wakeup; struct iovec *iov = (struct iovec *)_iov; size_t total_len; ssize_t chars; total_len = iov_length(iov, nr_segs); /* Null write succeeds. */ if (unlikely(total_len == 0)) return 0; do_wakeup = 0; ret = 0; __pipe_lock(pipe); if (!pipe->readers) { send_sig(SIGPIPE, current, 0); ret = -EPIPE; goto out; } /* We try to merge small writes */ chars = total_len & (PAGE_SIZE-1); /* size of the last buffer */ if (pipe->nrbufs && chars != 0) { int lastbuf = (pipe->curbuf + pipe->nrbufs - 1) & (pipe->buffers - 1); struct pipe_buffer *buf = pipe->bufs + lastbuf; const struct pipe_buf_operations *ops = buf->ops; int offset = buf->offset + buf->len; if (ops->can_merge && offset + chars <= PAGE_SIZE) { int error, atomic = 1; void *addr; error = ops->confirm(pipe, buf); if (error) goto out; iov_fault_in_pages_read(iov, chars); redo1: if (atomic) addr = kmap_atomic(buf->page); else addr = kmap(buf->page); error = pipe_iov_copy_from_user(offset + addr, iov, chars, atomic); if (atomic) kunmap_atomic(addr); else kunmap(buf->page); ret = error; do_wakeup = 1; if (error) { if (atomic) { atomic = 0; goto redo1; } goto out; } buf->len += chars; total_len -= chars; ret = chars; if (!total_len) goto out; } } for (;;) { int bufs; if (!pipe->readers) { send_sig(SIGPIPE, current, 0); if (!ret) ret = -EPIPE; break; } bufs = pipe->nrbufs; if (bufs < pipe->buffers) { int newbuf = (pipe->curbuf + bufs) & (pipe->buffers-1); struct pipe_buffer *buf = pipe->bufs + newbuf; struct page *page = pipe->tmp_page; char *src; int error, atomic = 1; if (!page) { page = alloc_page(GFP_HIGHUSER); if (unlikely(!page)) { ret = ret ? : -ENOMEM; break; } pipe->tmp_page = page; } /* Always wake up, even if the copy fails. Otherwise * we lock up (O_NONBLOCK-)readers that sleep due to * syscall merging. * FIXME! Is this really true? */ do_wakeup = 1; chars = PAGE_SIZE; if (chars > total_len) chars = total_len; iov_fault_in_pages_read(iov, chars); redo2: if (atomic) src = kmap_atomic(page); else src = kmap(page); error = pipe_iov_copy_from_user(src, iov, chars, atomic); if (atomic) kunmap_atomic(src); else kunmap(page); if (unlikely(error)) { if (atomic) { atomic = 0; goto redo2; } if (!ret) ret = error; break; } ret += chars; /* Insert it into the buffer array */ buf->page = page; buf->ops = &anon_pipe_buf_ops; buf->offset = 0; buf->len = chars; buf->flags = 0; if (is_packetized(filp)) { buf->ops = &packet_pipe_buf_ops; buf->flags = PIPE_BUF_FLAG_PACKET; } pipe->nrbufs = ++bufs; pipe->tmp_page = NULL; total_len -= chars; if (!total_len) break; } if (bufs < pipe->buffers) continue; if (filp->f_flags & O_NONBLOCK) { if (!ret) ret = -EAGAIN; break; } if (signal_pending(current)) { if (!ret) ret = -ERESTARTSYS; break; } if (do_wakeup) { wake_up_interruptible_sync_poll(&pipe->wait, POLLIN | POLLRDNORM); kill_fasync(&pipe->fasync_readers, SIGIO, POLL_IN); do_wakeup = 0; } pipe->waiting_writers++; pipe_wait(pipe); pipe->waiting_writers--; } out: __pipe_unlock(pipe); if (do_wakeup) { wake_up_interruptible_sync_poll(&pipe->wait, POLLIN | POLLRDNORM); kill_fasync(&pipe->fasync_readers, SIGIO, POLL_IN); } if (ret > 0 && sb_start_write_trylock(file_inode(filp)->i_sb)) { int err = file_update_time(filp); if (err) ret = err; sb_end_write(file_inode(filp)->i_sb); } return ret; } static long pipe_ioctl(struct file *filp, unsigned int cmd, unsigned long arg) { struct pipe_inode_info *pipe = filp->private_data; int count, buf, nrbufs; switch (cmd) { case FIONREAD: __pipe_lock(pipe); count = 0; buf = pipe->curbuf; nrbufs = pipe->nrbufs; while (--nrbufs >= 0) { count += pipe->bufs[buf].len; buf = (buf+1) & (pipe->buffers - 1); } __pipe_unlock(pipe); return put_user(count, (int __user *)arg); default: return -ENOIOCTLCMD; } } /* No kernel lock held - fine */ static unsigned int pipe_poll(struct file *filp, poll_table *wait) { unsigned int mask; struct pipe_inode_info *pipe = filp->private_data; int nrbufs; poll_wait(filp, &pipe->wait, wait); /* Reading only -- no need for acquiring the semaphore. */ nrbufs = pipe->nrbufs; mask = 0; if (filp->f_mode & FMODE_READ) { mask = (nrbufs > 0) ? POLLIN | POLLRDNORM : 0; if (!pipe->writers && filp->f_version != pipe->w_counter) mask |= POLLHUP; } if (filp->f_mode & FMODE_WRITE) { mask |= (nrbufs < pipe->buffers) ? POLLOUT | POLLWRNORM : 0; /* * Most Unices do not set POLLERR for FIFOs but on Linux they * behave exactly like pipes for poll(). */ if (!pipe->readers) mask |= POLLERR; } return mask; } static void put_pipe_info(struct inode *inode, struct pipe_inode_info *pipe) { int kill = 0; spin_lock(&inode->i_lock); if (!--pipe->files) { inode->i_pipe = NULL; kill = 1; } spin_unlock(&inode->i_lock); if (kill) free_pipe_info(pipe); } static int pipe_release(struct inode *inode, struct file *file) { struct pipe_inode_info *pipe = file->private_data; __pipe_lock(pipe); if (file->f_mode & FMODE_READ) pipe->readers--; if (file->f_mode & FMODE_WRITE) pipe->writers--; if (pipe->readers || pipe->writers) { wake_up_interruptible_sync_poll(&pipe->wait, POLLIN | POLLOUT | POLLRDNORM | POLLWRNORM | POLLERR | POLLHUP); kill_fasync(&pipe->fasync_readers, SIGIO, POLL_IN); kill_fasync(&pipe->fasync_writers, SIGIO, POLL_OUT); } __pipe_unlock(pipe); put_pipe_info(inode, pipe); return 0; } static int pipe_fasync(int fd, struct file *filp, int on) { struct pipe_inode_info *pipe = filp->private_data; int retval = 0; __pipe_lock(pipe); if (filp->f_mode & FMODE_READ) retval = fasync_helper(fd, filp, on, &pipe->fasync_readers); if ((filp->f_mode & FMODE_WRITE) && retval >= 0) { retval = fasync_helper(fd, filp, on, &pipe->fasync_writers); if (retval < 0 && (filp->f_mode & FMODE_READ)) /* this can happen only if on == T */ fasync_helper(-1, filp, 0, &pipe->fasync_readers); } __pipe_unlock(pipe); return retval; } struct pipe_inode_info *alloc_pipe_info(void) { struct pipe_inode_info *pipe; pipe = kzalloc(sizeof(struct pipe_inode_info), GFP_KERNEL); if (pipe) { pipe->bufs = kzalloc(sizeof(struct pipe_buffer) * PIPE_DEF_BUFFERS, GFP_KERNEL); if (pipe->bufs) { init_waitqueue_head(&pipe->wait); pipe->r_counter = pipe->w_counter = 1; pipe->buffers = PIPE_DEF_BUFFERS; mutex_init(&pipe->mutex); return pipe; } kfree(pipe); } return NULL; } void free_pipe_info(struct pipe_inode_info *pipe) { int i; for (i = 0; i < pipe->buffers; i++) { struct pipe_buffer *buf = pipe->bufs + i; if (buf->ops) buf->ops->release(pipe, buf); } if (pipe->tmp_page) __free_page(pipe->tmp_page); kfree(pipe->bufs); kfree(pipe); } static struct vfsmount *pipe_mnt __read_mostly; /* * pipefs_dname() is called from d_path(). */ static char *pipefs_dname(struct dentry *dentry, char *buffer, int buflen) { return dynamic_dname(dentry, buffer, buflen, "pipe:[%lu]", dentry->d_inode->i_ino); } static const struct dentry_operations pipefs_dentry_operations = { .d_dname = pipefs_dname, }; static struct inode * get_pipe_inode(void) { struct inode *inode = new_inode_pseudo(pipe_mnt->mnt_sb); struct pipe_inode_info *pipe; if (!inode) goto fail_inode; inode->i_ino = get_next_ino(); pipe = alloc_pipe_info(); if (!pipe) goto fail_iput; inode->i_pipe = pipe; pipe->files = 2; pipe->readers = pipe->writers = 1; inode->i_fop = &pipefifo_fops; /* * Mark the inode dirty from the very beginning, * that way it will never be moved to the dirty * list because "mark_inode_dirty()" will think * that it already _is_ on the dirty list. */ inode->i_state = I_DIRTY; inode->i_mode = S_IFIFO | S_IRUSR | S_IWUSR; inode->i_uid = current_fsuid(); inode->i_gid = current_fsgid(); inode->i_atime = inode->i_mtime = inode->i_ctime = CURRENT_TIME; return inode; fail_iput: iput(inode); fail_inode: return NULL; } int create_pipe_files(struct file **res, int flags) { int err; struct inode *inode = get_pipe_inode(); struct file *f; struct path path; static struct qstr name = { .name = "" }; if (!inode) return -ENFILE; err = -ENOMEM; path.dentry = d_alloc_pseudo(pipe_mnt->mnt_sb, &name); if (!path.dentry) goto err_inode; path.mnt = mntget(pipe_mnt); d_instantiate(path.dentry, inode); err = -ENFILE; f = alloc_file(&path, FMODE_WRITE, &pipefifo_fops); if (IS_ERR(f)) goto err_dentry; f->f_flags = O_WRONLY | (flags & (O_NONBLOCK | O_DIRECT)); f->private_data = inode->i_pipe; res[0] = alloc_file(&path, FMODE_READ, &pipefifo_fops); if (IS_ERR(res[0])) goto err_file; path_get(&path); res[0]->private_data = inode->i_pipe; res[0]->f_flags = O_RDONLY | (flags & O_NONBLOCK); res[1] = f; return 0; err_file: put_filp(f); err_dentry: free_pipe_info(inode->i_pipe); path_put(&path); return err; err_inode: free_pipe_info(inode->i_pipe); iput(inode); return err; } static int __do_pipe_flags(int *fd, struct file **files, int flags) { int error; int fdw, fdr; if (flags & ~(O_CLOEXEC | O_NONBLOCK | O_DIRECT)) return -EINVAL; error = create_pipe_files(files, flags); if (error) return error; error = get_unused_fd_flags(flags); if (error < 0) goto err_read_pipe; fdr = error; error = get_unused_fd_flags(flags); if (error < 0) goto err_fdr; fdw = error; audit_fd_pair(fdr, fdw); fd[0] = fdr; fd[1] = fdw; return 0; err_fdr: put_unused_fd(fdr); err_read_pipe: fput(files[0]); fput(files[1]); return error; } int do_pipe_flags(int *fd, int flags) { struct file *files[2]; int error = __do_pipe_flags(fd, files, flags); if (!error) { fd_install(fd[0], files[0]); fd_install(fd[1], files[1]); } return error; } /* * sys_pipe() is the normal C calling standard for creating * a pipe. It's not the way Unix traditionally does this, though. */ SYSCALL_DEFINE2(pipe2, int __user *, fildes, int, flags) { struct file *files[2]; int fd[2]; int error; error = __do_pipe_flags(fd, files, flags); if (!error) { if (unlikely(copy_to_user(fildes, fd, sizeof(fd)))) { fput(files[0]); fput(files[1]); put_unused_fd(fd[0]); put_unused_fd(fd[1]); error = -EFAULT; } else { fd_install(fd[0], files[0]); fd_install(fd[1], files[1]); } } return error; } SYSCALL_DEFINE1(pipe, int __user *, fildes) { return sys_pipe2(fildes, 0); } static int wait_for_partner(struct pipe_inode_info *pipe, unsigned int *cnt) { int cur = *cnt; while (cur == *cnt) { pipe_wait(pipe); if (signal_pending(current)) break; } return cur == *cnt ? -ERESTARTSYS : 0; } static void wake_up_partner(struct pipe_inode_info *pipe) { wake_up_interruptible(&pipe->wait); } static int fifo_open(struct inode *inode, struct file *filp) { struct pipe_inode_info *pipe; bool is_pipe = inode->i_sb->s_magic == PIPEFS_MAGIC; int ret; filp->f_version = 0; spin_lock(&inode->i_lock); if (inode->i_pipe) { pipe = inode->i_pipe; pipe->files++; spin_unlock(&inode->i_lock); } else { spin_unlock(&inode->i_lock); pipe = alloc_pipe_info(); if (!pipe) return -ENOMEM; pipe->files = 1; spin_lock(&inode->i_lock); if (unlikely(inode->i_pipe)) { inode->i_pipe->files++; spin_unlock(&inode->i_lock); free_pipe_info(pipe); pipe = inode->i_pipe; } else { inode->i_pipe = pipe; spin_unlock(&inode->i_lock); } } filp->private_data = pipe; /* OK, we have a pipe and it's pinned down */ __pipe_lock(pipe); /* We can only do regular read/write on fifos */ filp->f_mode &= (FMODE_READ | FMODE_WRITE); switch (filp->f_mode) { case FMODE_READ: /* * O_RDONLY * POSIX.1 says that O_NONBLOCK means return with the FIFO * opened, even when there is no process writing the FIFO. */ pipe->r_counter++; if (pipe->readers++ == 0) wake_up_partner(pipe); if (!is_pipe && !pipe->writers) { if ((filp->f_flags & O_NONBLOCK)) { /* suppress POLLHUP until we have * seen a writer */ filp->f_version = pipe->w_counter; } else { if (wait_for_partner(pipe, &pipe->w_counter)) goto err_rd; } } break; case FMODE_WRITE: /* * O_WRONLY * POSIX.1 says that O_NONBLOCK means return -1 with * errno=ENXIO when there is no process reading the FIFO. */ ret = -ENXIO; if (!is_pipe && (filp->f_flags & O_NONBLOCK) && !pipe->readers) goto err; pipe->w_counter++; if (!pipe->writers++) wake_up_partner(pipe); if (!is_pipe && !pipe->readers) { if (wait_for_partner(pipe, &pipe->r_counter)) goto err_wr; } break; case FMODE_READ | FMODE_WRITE: /* * O_RDWR * POSIX.1 leaves this case "undefined" when O_NONBLOCK is set. * This implementation will NEVER block on a O_RDWR open, since * the process can at least talk to itself. */ pipe->readers++; pipe->writers++; pipe->r_counter++; pipe->w_counter++; if (pipe->readers == 1 || pipe->writers == 1) wake_up_partner(pipe); break; default: ret = -EINVAL; goto err; } /* Ok! */ __pipe_unlock(pipe); return 0; err_rd: if (!--pipe->readers) wake_up_interruptible(&pipe->wait); ret = -ERESTARTSYS; goto err; err_wr: if (!--pipe->writers) wake_up_interruptible(&pipe->wait); ret = -ERESTARTSYS; goto err; err: __pipe_unlock(pipe); put_pipe_info(inode, pipe); return ret; } const struct file_operations pipefifo_fops = { .open = fifo_open, .llseek = no_llseek, .read = new_sync_read, .read_iter = pipe_read, .write = do_sync_write, .aio_write = pipe_write, .poll = pipe_poll, .unlocked_ioctl = pipe_ioctl, .release = pipe_release, .fasync = pipe_fasync, }; /* * Allocate a new array of pipe buffers and copy the info over. Returns the * pipe size if successful, or return -ERROR on error. */ static long pipe_set_size(struct pipe_inode_info *pipe, unsigned long nr_pages) { struct pipe_buffer *bufs; /* * We can shrink the pipe, if arg >= pipe->nrbufs. Since we don't * expect a lot of shrink+grow operations, just free and allocate * again like we would do for growing. If the pipe currently * contains more buffers than arg, then return busy. */ if (nr_pages < pipe->nrbufs) return -EBUSY; bufs = kcalloc(nr_pages, sizeof(*bufs), GFP_KERNEL | __GFP_NOWARN); if (unlikely(!bufs)) return -ENOMEM; /* * The pipe array wraps around, so just start the new one at zero * and adjust the indexes. */ if (pipe->nrbufs) { unsigned int tail; unsigned int head; tail = pipe->curbuf + pipe->nrbufs; if (tail < pipe->buffers) tail = 0; else tail &= (pipe->buffers - 1); head = pipe->nrbufs - tail; if (head) memcpy(bufs, pipe->bufs + pipe->curbuf, head * sizeof(struct pipe_buffer)); if (tail) memcpy(bufs + head, pipe->bufs, tail * sizeof(struct pipe_buffer)); } pipe->curbuf = 0; kfree(pipe->bufs); pipe->bufs = bufs; pipe->buffers = nr_pages; return nr_pages * PAGE_SIZE; } /* * Currently we rely on the pipe array holding a power-of-2 number * of pages. */ static inline unsigned int round_pipe_size(unsigned int size) { unsigned long nr_pages; nr_pages = (size + PAGE_SIZE - 1) >> PAGE_SHIFT; return roundup_pow_of_two(nr_pages) << PAGE_SHIFT; } /* * This should work even if CONFIG_PROC_FS isn't set, as proc_dointvec_minmax * will return an error. */ int pipe_proc_fn(struct ctl_table *table, int write, void __user *buf, size_t *lenp, loff_t *ppos) { int ret; ret = proc_dointvec_minmax(table, write, buf, lenp, ppos); if (ret < 0 || !write) return ret; pipe_max_size = round_pipe_size(pipe_max_size); return ret; } /* * After the inode slimming patch, i_pipe/i_bdev/i_cdev share the same * location, so checking ->i_pipe is not enough to verify that this is a * pipe. */ struct pipe_inode_info *get_pipe_info(struct file *file) { return file->f_op == &pipefifo_fops ? file->private_data : NULL; } long pipe_fcntl(struct file *file, unsigned int cmd, unsigned long arg) { struct pipe_inode_info *pipe; long ret; pipe = get_pipe_info(file); if (!pipe) return -EBADF; __pipe_lock(pipe); switch (cmd) { case F_SETPIPE_SZ: { unsigned int size, nr_pages; size = round_pipe_size(arg); nr_pages = size >> PAGE_SHIFT; ret = -EINVAL; if (!nr_pages) goto out; if (!capable(CAP_SYS_RESOURCE) && size > pipe_max_size) { ret = -EPERM; goto out; } ret = pipe_set_size(pipe, nr_pages); break; } case F_GETPIPE_SZ: ret = pipe->buffers * PAGE_SIZE; break; default: ret = -EINVAL; break; } out: __pipe_unlock(pipe); return ret; } static const struct super_operations pipefs_ops = { .destroy_inode = free_inode_nonrcu, .statfs = simple_statfs, }; /* * pipefs should _never_ be mounted by userland - too much of security hassle, * no real gain from having the whole whorehouse mounted. So we don't need * any operations on the root directory. However, we need a non-trivial * d_name - pipe: will go nicely and kill the special-casing in procfs. */ static struct dentry *pipefs_mount(struct file_system_type *fs_type, int flags, const char *dev_name, void *data) { return mount_pseudo(fs_type, "pipe:", &pipefs_ops, &pipefs_dentry_operations, PIPEFS_MAGIC); } static struct file_system_type pipe_fs_type = { .name = "pipefs", .mount = pipefs_mount, .kill_sb = kill_anon_super, }; static int __init init_pipe_fs(void) { int err = register_filesystem(&pipe_fs_type); if (!err) { pipe_mnt = kern_mount(&pipe_fs_type); if (IS_ERR(pipe_mnt)) { err = PTR_ERR(pipe_mnt); unregister_filesystem(&pipe_fs_type); } } return err; } fs_initcall(init_pipe_fs);
./CrossVul/dataset_final_sorted/CWE-17/c/bad_1499_0
crossvul-cpp_data_bad_1511_0
/* * Copyright (c) 2006 Oracle. All rights reserved. * * This software is available to you under a choice of one of two * licenses. You may choose to be licensed under the terms of the GNU * General Public License (GPL) Version 2, available from the file * COPYING in the main directory of this source tree, or the * OpenIB.org BSD license below: * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * - Redistributions of source code must retain the above * copyright notice, this list of conditions and the following * disclaimer. * * - Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ #include <linux/kernel.h> #include <linux/sysctl.h> #include <linux/proc_fs.h> #include "rds.h" static struct ctl_table_header *rds_sysctl_reg_table; static unsigned long rds_sysctl_reconnect_min = 1; static unsigned long rds_sysctl_reconnect_max = ~0UL; unsigned long rds_sysctl_reconnect_min_jiffies; unsigned long rds_sysctl_reconnect_max_jiffies = HZ; unsigned int rds_sysctl_max_unacked_packets = 8; unsigned int rds_sysctl_max_unacked_bytes = (16 << 20); unsigned int rds_sysctl_ping_enable = 1; static struct ctl_table rds_sysctl_rds_table[] = { { .procname = "reconnect_min_delay_ms", .data = &rds_sysctl_reconnect_min_jiffies, .maxlen = sizeof(unsigned long), .mode = 0644, .proc_handler = proc_doulongvec_ms_jiffies_minmax, .extra1 = &rds_sysctl_reconnect_min, .extra2 = &rds_sysctl_reconnect_max_jiffies, }, { .procname = "reconnect_max_delay_ms", .data = &rds_sysctl_reconnect_max_jiffies, .maxlen = sizeof(unsigned long), .mode = 0644, .proc_handler = proc_doulongvec_ms_jiffies_minmax, .extra1 = &rds_sysctl_reconnect_min_jiffies, .extra2 = &rds_sysctl_reconnect_max, }, { .procname = "max_unacked_packets", .data = &rds_sysctl_max_unacked_packets, .maxlen = sizeof(unsigned long), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "max_unacked_bytes", .data = &rds_sysctl_max_unacked_bytes, .maxlen = sizeof(unsigned long), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "ping_enable", .data = &rds_sysctl_ping_enable, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { } }; void rds_sysctl_exit(void) { unregister_net_sysctl_table(rds_sysctl_reg_table); } int rds_sysctl_init(void) { rds_sysctl_reconnect_min = msecs_to_jiffies(1); rds_sysctl_reconnect_min_jiffies = rds_sysctl_reconnect_min; rds_sysctl_reg_table = register_net_sysctl(&init_net,"net/rds", rds_sysctl_rds_table); if (!rds_sysctl_reg_table) return -ENOMEM; return 0; }
./CrossVul/dataset_final_sorted/CWE-17/c/bad_1511_0
crossvul-cpp_data_good_1546_0
/* * Neighbour Discovery for IPv6 * Linux INET6 implementation * * Authors: * Pedro Roque <roque@di.fc.ul.pt> * Mike Shaver <shaver@ingenia.com> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ /* * Changes: * * Alexey I. Froloff : RFC6106 (DNSSL) support * Pierre Ynard : export userland ND options * through netlink (RDNSS support) * Lars Fenneberg : fixed MTU setting on receipt * of an RA. * Janos Farkas : kmalloc failure checks * Alexey Kuznetsov : state machine reworked * and moved to net/core. * Pekka Savola : RFC2461 validation * YOSHIFUJI Hideaki @USAGI : Verify ND options properly */ #define pr_fmt(fmt) "ICMPv6: " fmt #include <linux/module.h> #include <linux/errno.h> #include <linux/types.h> #include <linux/socket.h> #include <linux/sockios.h> #include <linux/sched.h> #include <linux/net.h> #include <linux/in6.h> #include <linux/route.h> #include <linux/init.h> #include <linux/rcupdate.h> #include <linux/slab.h> #ifdef CONFIG_SYSCTL #include <linux/sysctl.h> #endif #include <linux/if_addr.h> #include <linux/if_arp.h> #include <linux/ipv6.h> #include <linux/icmpv6.h> #include <linux/jhash.h> #include <net/sock.h> #include <net/snmp.h> #include <net/ipv6.h> #include <net/protocol.h> #include <net/ndisc.h> #include <net/ip6_route.h> #include <net/addrconf.h> #include <net/icmp.h> #include <net/netlink.h> #include <linux/rtnetlink.h> #include <net/flow.h> #include <net/ip6_checksum.h> #include <net/inet_common.h> #include <linux/proc_fs.h> #include <linux/netfilter.h> #include <linux/netfilter_ipv6.h> /* Set to 3 to get tracing... */ #define ND_DEBUG 1 #define ND_PRINTK(val, level, fmt, ...) \ do { \ if (val <= ND_DEBUG) \ net_##level##_ratelimited(fmt, ##__VA_ARGS__); \ } while (0) static u32 ndisc_hash(const void *pkey, const struct net_device *dev, __u32 *hash_rnd); static int ndisc_constructor(struct neighbour *neigh); static void ndisc_solicit(struct neighbour *neigh, struct sk_buff *skb); static void ndisc_error_report(struct neighbour *neigh, struct sk_buff *skb); static int pndisc_constructor(struct pneigh_entry *n); static void pndisc_destructor(struct pneigh_entry *n); static void pndisc_redo(struct sk_buff *skb); static const struct neigh_ops ndisc_generic_ops = { .family = AF_INET6, .solicit = ndisc_solicit, .error_report = ndisc_error_report, .output = neigh_resolve_output, .connected_output = neigh_connected_output, }; static const struct neigh_ops ndisc_hh_ops = { .family = AF_INET6, .solicit = ndisc_solicit, .error_report = ndisc_error_report, .output = neigh_resolve_output, .connected_output = neigh_resolve_output, }; static const struct neigh_ops ndisc_direct_ops = { .family = AF_INET6, .output = neigh_direct_output, .connected_output = neigh_direct_output, }; struct neigh_table nd_tbl = { .family = AF_INET6, .key_len = sizeof(struct in6_addr), .hash = ndisc_hash, .constructor = ndisc_constructor, .pconstructor = pndisc_constructor, .pdestructor = pndisc_destructor, .proxy_redo = pndisc_redo, .id = "ndisc_cache", .parms = { .tbl = &nd_tbl, .reachable_time = ND_REACHABLE_TIME, .data = { [NEIGH_VAR_MCAST_PROBES] = 3, [NEIGH_VAR_UCAST_PROBES] = 3, [NEIGH_VAR_RETRANS_TIME] = ND_RETRANS_TIMER, [NEIGH_VAR_BASE_REACHABLE_TIME] = ND_REACHABLE_TIME, [NEIGH_VAR_DELAY_PROBE_TIME] = 5 * HZ, [NEIGH_VAR_GC_STALETIME] = 60 * HZ, [NEIGH_VAR_QUEUE_LEN_BYTES] = 64 * 1024, [NEIGH_VAR_PROXY_QLEN] = 64, [NEIGH_VAR_ANYCAST_DELAY] = 1 * HZ, [NEIGH_VAR_PROXY_DELAY] = (8 * HZ) / 10, }, }, .gc_interval = 30 * HZ, .gc_thresh1 = 128, .gc_thresh2 = 512, .gc_thresh3 = 1024, }; static void ndisc_fill_addr_option(struct sk_buff *skb, int type, void *data) { int pad = ndisc_addr_option_pad(skb->dev->type); int data_len = skb->dev->addr_len; int space = ndisc_opt_addr_space(skb->dev); u8 *opt = skb_put(skb, space); opt[0] = type; opt[1] = space>>3; memset(opt + 2, 0, pad); opt += pad; space -= pad; memcpy(opt+2, data, data_len); data_len += 2; opt += data_len; space -= data_len; if (space > 0) memset(opt, 0, space); } static struct nd_opt_hdr *ndisc_next_option(struct nd_opt_hdr *cur, struct nd_opt_hdr *end) { int type; if (!cur || !end || cur >= end) return NULL; type = cur->nd_opt_type; do { cur = ((void *)cur) + (cur->nd_opt_len << 3); } while (cur < end && cur->nd_opt_type != type); return cur <= end && cur->nd_opt_type == type ? cur : NULL; } static inline int ndisc_is_useropt(struct nd_opt_hdr *opt) { return opt->nd_opt_type == ND_OPT_RDNSS || opt->nd_opt_type == ND_OPT_DNSSL; } static struct nd_opt_hdr *ndisc_next_useropt(struct nd_opt_hdr *cur, struct nd_opt_hdr *end) { if (!cur || !end || cur >= end) return NULL; do { cur = ((void *)cur) + (cur->nd_opt_len << 3); } while (cur < end && !ndisc_is_useropt(cur)); return cur <= end && ndisc_is_useropt(cur) ? cur : NULL; } struct ndisc_options *ndisc_parse_options(u8 *opt, int opt_len, struct ndisc_options *ndopts) { struct nd_opt_hdr *nd_opt = (struct nd_opt_hdr *)opt; if (!nd_opt || opt_len < 0 || !ndopts) return NULL; memset(ndopts, 0, sizeof(*ndopts)); while (opt_len) { int l; if (opt_len < sizeof(struct nd_opt_hdr)) return NULL; l = nd_opt->nd_opt_len << 3; if (opt_len < l || l == 0) return NULL; switch (nd_opt->nd_opt_type) { case ND_OPT_SOURCE_LL_ADDR: case ND_OPT_TARGET_LL_ADDR: case ND_OPT_MTU: case ND_OPT_REDIRECT_HDR: if (ndopts->nd_opt_array[nd_opt->nd_opt_type]) { ND_PRINTK(2, warn, "%s: duplicated ND6 option found: type=%d\n", __func__, nd_opt->nd_opt_type); } else { ndopts->nd_opt_array[nd_opt->nd_opt_type] = nd_opt; } break; case ND_OPT_PREFIX_INFO: ndopts->nd_opts_pi_end = nd_opt; if (!ndopts->nd_opt_array[nd_opt->nd_opt_type]) ndopts->nd_opt_array[nd_opt->nd_opt_type] = nd_opt; break; #ifdef CONFIG_IPV6_ROUTE_INFO case ND_OPT_ROUTE_INFO: ndopts->nd_opts_ri_end = nd_opt; if (!ndopts->nd_opts_ri) ndopts->nd_opts_ri = nd_opt; break; #endif default: if (ndisc_is_useropt(nd_opt)) { ndopts->nd_useropts_end = nd_opt; if (!ndopts->nd_useropts) ndopts->nd_useropts = nd_opt; } else { /* * Unknown options must be silently ignored, * to accommodate future extension to the * protocol. */ ND_PRINTK(2, notice, "%s: ignored unsupported option; type=%d, len=%d\n", __func__, nd_opt->nd_opt_type, nd_opt->nd_opt_len); } } opt_len -= l; nd_opt = ((void *)nd_opt) + l; } return ndopts; } int ndisc_mc_map(const struct in6_addr *addr, char *buf, struct net_device *dev, int dir) { switch (dev->type) { case ARPHRD_ETHER: case ARPHRD_IEEE802: /* Not sure. Check it later. --ANK */ case ARPHRD_FDDI: ipv6_eth_mc_map(addr, buf); return 0; case ARPHRD_ARCNET: ipv6_arcnet_mc_map(addr, buf); return 0; case ARPHRD_INFINIBAND: ipv6_ib_mc_map(addr, dev->broadcast, buf); return 0; case ARPHRD_IPGRE: return ipv6_ipgre_mc_map(addr, dev->broadcast, buf); default: if (dir) { memcpy(buf, dev->broadcast, dev->addr_len); return 0; } } return -EINVAL; } EXPORT_SYMBOL(ndisc_mc_map); static u32 ndisc_hash(const void *pkey, const struct net_device *dev, __u32 *hash_rnd) { return ndisc_hashfn(pkey, dev, hash_rnd); } static int ndisc_constructor(struct neighbour *neigh) { struct in6_addr *addr = (struct in6_addr *)&neigh->primary_key; struct net_device *dev = neigh->dev; struct inet6_dev *in6_dev; struct neigh_parms *parms; bool is_multicast = ipv6_addr_is_multicast(addr); in6_dev = in6_dev_get(dev); if (in6_dev == NULL) { return -EINVAL; } parms = in6_dev->nd_parms; __neigh_parms_put(neigh->parms); neigh->parms = neigh_parms_clone(parms); neigh->type = is_multicast ? RTN_MULTICAST : RTN_UNICAST; if (!dev->header_ops) { neigh->nud_state = NUD_NOARP; neigh->ops = &ndisc_direct_ops; neigh->output = neigh_direct_output; } else { if (is_multicast) { neigh->nud_state = NUD_NOARP; ndisc_mc_map(addr, neigh->ha, dev, 1); } else if (dev->flags&(IFF_NOARP|IFF_LOOPBACK)) { neigh->nud_state = NUD_NOARP; memcpy(neigh->ha, dev->dev_addr, dev->addr_len); if (dev->flags&IFF_LOOPBACK) neigh->type = RTN_LOCAL; } else if (dev->flags&IFF_POINTOPOINT) { neigh->nud_state = NUD_NOARP; memcpy(neigh->ha, dev->broadcast, dev->addr_len); } if (dev->header_ops->cache) neigh->ops = &ndisc_hh_ops; else neigh->ops = &ndisc_generic_ops; if (neigh->nud_state&NUD_VALID) neigh->output = neigh->ops->connected_output; else neigh->output = neigh->ops->output; } in6_dev_put(in6_dev); return 0; } static int pndisc_constructor(struct pneigh_entry *n) { struct in6_addr *addr = (struct in6_addr *)&n->key; struct in6_addr maddr; struct net_device *dev = n->dev; if (dev == NULL || __in6_dev_get(dev) == NULL) return -EINVAL; addrconf_addr_solict_mult(addr, &maddr); ipv6_dev_mc_inc(dev, &maddr); return 0; } static void pndisc_destructor(struct pneigh_entry *n) { struct in6_addr *addr = (struct in6_addr *)&n->key; struct in6_addr maddr; struct net_device *dev = n->dev; if (dev == NULL || __in6_dev_get(dev) == NULL) return; addrconf_addr_solict_mult(addr, &maddr); ipv6_dev_mc_dec(dev, &maddr); } static struct sk_buff *ndisc_alloc_skb(struct net_device *dev, int len) { int hlen = LL_RESERVED_SPACE(dev); int tlen = dev->needed_tailroom; struct sock *sk = dev_net(dev)->ipv6.ndisc_sk; struct sk_buff *skb; skb = alloc_skb(hlen + sizeof(struct ipv6hdr) + len + tlen, GFP_ATOMIC); if (!skb) { ND_PRINTK(0, err, "ndisc: %s failed to allocate an skb\n", __func__); return NULL; } skb->protocol = htons(ETH_P_IPV6); skb->dev = dev; skb_reserve(skb, hlen + sizeof(struct ipv6hdr)); skb_reset_transport_header(skb); /* Manually assign socket ownership as we avoid calling * sock_alloc_send_pskb() to bypass wmem buffer limits */ skb_set_owner_w(skb, sk); return skb; } static void ip6_nd_hdr(struct sk_buff *skb, const struct in6_addr *saddr, const struct in6_addr *daddr, int hop_limit, int len) { struct ipv6hdr *hdr; skb_push(skb, sizeof(*hdr)); skb_reset_network_header(skb); hdr = ipv6_hdr(skb); ip6_flow_hdr(hdr, 0, 0); hdr->payload_len = htons(len); hdr->nexthdr = IPPROTO_ICMPV6; hdr->hop_limit = hop_limit; hdr->saddr = *saddr; hdr->daddr = *daddr; } static void ndisc_send_skb(struct sk_buff *skb, const struct in6_addr *daddr, const struct in6_addr *saddr) { struct dst_entry *dst = skb_dst(skb); struct net *net = dev_net(skb->dev); struct sock *sk = net->ipv6.ndisc_sk; struct inet6_dev *idev; int err; struct icmp6hdr *icmp6h = icmp6_hdr(skb); u8 type; type = icmp6h->icmp6_type; if (!dst) { struct flowi6 fl6; icmpv6_flow_init(sk, &fl6, type, saddr, daddr, skb->dev->ifindex); dst = icmp6_dst_alloc(skb->dev, &fl6); if (IS_ERR(dst)) { kfree_skb(skb); return; } skb_dst_set(skb, dst); } icmp6h->icmp6_cksum = csum_ipv6_magic(saddr, daddr, skb->len, IPPROTO_ICMPV6, csum_partial(icmp6h, skb->len, 0)); ip6_nd_hdr(skb, saddr, daddr, inet6_sk(sk)->hop_limit, skb->len); rcu_read_lock(); idev = __in6_dev_get(dst->dev); IP6_UPD_PO_STATS(net, idev, IPSTATS_MIB_OUT, skb->len); err = NF_HOOK(NFPROTO_IPV6, NF_INET_LOCAL_OUT, skb, NULL, dst->dev, dst_output); if (!err) { ICMP6MSGOUT_INC_STATS(net, idev, type); ICMP6_INC_STATS(net, idev, ICMP6_MIB_OUTMSGS); } rcu_read_unlock(); } void ndisc_send_na(struct net_device *dev, struct neighbour *neigh, const struct in6_addr *daddr, const struct in6_addr *solicited_addr, bool router, bool solicited, bool override, bool inc_opt) { struct sk_buff *skb; struct in6_addr tmpaddr; struct inet6_ifaddr *ifp; const struct in6_addr *src_addr; struct nd_msg *msg; int optlen = 0; /* for anycast or proxy, solicited_addr != src_addr */ ifp = ipv6_get_ifaddr(dev_net(dev), solicited_addr, dev, 1); if (ifp) { src_addr = solicited_addr; if (ifp->flags & IFA_F_OPTIMISTIC) override = false; inc_opt |= ifp->idev->cnf.force_tllao; in6_ifa_put(ifp); } else { if (ipv6_dev_get_saddr(dev_net(dev), dev, daddr, inet6_sk(dev_net(dev)->ipv6.ndisc_sk)->srcprefs, &tmpaddr)) return; src_addr = &tmpaddr; } if (!dev->addr_len) inc_opt = 0; if (inc_opt) optlen += ndisc_opt_addr_space(dev); skb = ndisc_alloc_skb(dev, sizeof(*msg) + optlen); if (!skb) return; msg = (struct nd_msg *)skb_put(skb, sizeof(*msg)); *msg = (struct nd_msg) { .icmph = { .icmp6_type = NDISC_NEIGHBOUR_ADVERTISEMENT, .icmp6_router = router, .icmp6_solicited = solicited, .icmp6_override = override, }, .target = *solicited_addr, }; if (inc_opt) ndisc_fill_addr_option(skb, ND_OPT_TARGET_LL_ADDR, dev->dev_addr); ndisc_send_skb(skb, daddr, src_addr); } static void ndisc_send_unsol_na(struct net_device *dev) { struct inet6_dev *idev; struct inet6_ifaddr *ifa; idev = in6_dev_get(dev); if (!idev) return; read_lock_bh(&idev->lock); list_for_each_entry(ifa, &idev->addr_list, if_list) { ndisc_send_na(dev, NULL, &in6addr_linklocal_allnodes, &ifa->addr, /*router=*/ !!idev->cnf.forwarding, /*solicited=*/ false, /*override=*/ true, /*inc_opt=*/ true); } read_unlock_bh(&idev->lock); in6_dev_put(idev); } void ndisc_send_ns(struct net_device *dev, struct neighbour *neigh, const struct in6_addr *solicit, const struct in6_addr *daddr, const struct in6_addr *saddr) { struct sk_buff *skb; struct in6_addr addr_buf; int inc_opt = dev->addr_len; int optlen = 0; struct nd_msg *msg; if (saddr == NULL) { if (ipv6_get_lladdr(dev, &addr_buf, (IFA_F_TENTATIVE|IFA_F_OPTIMISTIC))) return; saddr = &addr_buf; } if (ipv6_addr_any(saddr)) inc_opt = false; if (inc_opt) optlen += ndisc_opt_addr_space(dev); skb = ndisc_alloc_skb(dev, sizeof(*msg) + optlen); if (!skb) return; msg = (struct nd_msg *)skb_put(skb, sizeof(*msg)); *msg = (struct nd_msg) { .icmph = { .icmp6_type = NDISC_NEIGHBOUR_SOLICITATION, }, .target = *solicit, }; if (inc_opt) ndisc_fill_addr_option(skb, ND_OPT_SOURCE_LL_ADDR, dev->dev_addr); ndisc_send_skb(skb, daddr, saddr); } void ndisc_send_rs(struct net_device *dev, const struct in6_addr *saddr, const struct in6_addr *daddr) { struct sk_buff *skb; struct rs_msg *msg; int send_sllao = dev->addr_len; int optlen = 0; #ifdef CONFIG_IPV6_OPTIMISTIC_DAD /* * According to section 2.2 of RFC 4429, we must not * send router solicitations with a sllao from * optimistic addresses, but we may send the solicitation * if we don't include the sllao. So here we check * if our address is optimistic, and if so, we * suppress the inclusion of the sllao. */ if (send_sllao) { struct inet6_ifaddr *ifp = ipv6_get_ifaddr(dev_net(dev), saddr, dev, 1); if (ifp) { if (ifp->flags & IFA_F_OPTIMISTIC) { send_sllao = 0; } in6_ifa_put(ifp); } else { send_sllao = 0; } } #endif if (send_sllao) optlen += ndisc_opt_addr_space(dev); skb = ndisc_alloc_skb(dev, sizeof(*msg) + optlen); if (!skb) return; msg = (struct rs_msg *)skb_put(skb, sizeof(*msg)); *msg = (struct rs_msg) { .icmph = { .icmp6_type = NDISC_ROUTER_SOLICITATION, }, }; if (send_sllao) ndisc_fill_addr_option(skb, ND_OPT_SOURCE_LL_ADDR, dev->dev_addr); ndisc_send_skb(skb, daddr, saddr); } static void ndisc_error_report(struct neighbour *neigh, struct sk_buff *skb) { /* * "The sender MUST return an ICMP * destination unreachable" */ dst_link_failure(skb); kfree_skb(skb); } /* Called with locked neigh: either read or both */ static void ndisc_solicit(struct neighbour *neigh, struct sk_buff *skb) { struct in6_addr *saddr = NULL; struct in6_addr mcaddr; struct net_device *dev = neigh->dev; struct in6_addr *target = (struct in6_addr *)&neigh->primary_key; int probes = atomic_read(&neigh->probes); if (skb && ipv6_chk_addr_and_flags(dev_net(dev), &ipv6_hdr(skb)->saddr, dev, 1, IFA_F_TENTATIVE|IFA_F_OPTIMISTIC)) saddr = &ipv6_hdr(skb)->saddr; probes -= NEIGH_VAR(neigh->parms, UCAST_PROBES); if (probes < 0) { if (!(neigh->nud_state & NUD_VALID)) { ND_PRINTK(1, dbg, "%s: trying to ucast probe in NUD_INVALID: %pI6\n", __func__, target); } ndisc_send_ns(dev, neigh, target, target, saddr); } else if ((probes -= NEIGH_VAR(neigh->parms, APP_PROBES)) < 0) { neigh_app_ns(neigh); } else { addrconf_addr_solict_mult(target, &mcaddr); ndisc_send_ns(dev, NULL, target, &mcaddr, saddr); } } static int pndisc_is_router(const void *pkey, struct net_device *dev) { struct pneigh_entry *n; int ret = -1; read_lock_bh(&nd_tbl.lock); n = __pneigh_lookup(&nd_tbl, dev_net(dev), pkey, dev); if (n) ret = !!(n->flags & NTF_ROUTER); read_unlock_bh(&nd_tbl.lock); return ret; } static void ndisc_recv_ns(struct sk_buff *skb) { struct nd_msg *msg = (struct nd_msg *)skb_transport_header(skb); const struct in6_addr *saddr = &ipv6_hdr(skb)->saddr; const struct in6_addr *daddr = &ipv6_hdr(skb)->daddr; u8 *lladdr = NULL; u32 ndoptlen = skb_tail_pointer(skb) - (skb_transport_header(skb) + offsetof(struct nd_msg, opt)); struct ndisc_options ndopts; struct net_device *dev = skb->dev; struct inet6_ifaddr *ifp; struct inet6_dev *idev = NULL; struct neighbour *neigh; int dad = ipv6_addr_any(saddr); bool inc; int is_router = -1; if (skb->len < sizeof(struct nd_msg)) { ND_PRINTK(2, warn, "NS: packet too short\n"); return; } if (ipv6_addr_is_multicast(&msg->target)) { ND_PRINTK(2, warn, "NS: multicast target address\n"); return; } /* * RFC2461 7.1.1: * DAD has to be destined for solicited node multicast address. */ if (dad && !ipv6_addr_is_solict_mult(daddr)) { ND_PRINTK(2, warn, "NS: bad DAD packet (wrong destination)\n"); return; } if (!ndisc_parse_options(msg->opt, ndoptlen, &ndopts)) { ND_PRINTK(2, warn, "NS: invalid ND options\n"); return; } if (ndopts.nd_opts_src_lladdr) { lladdr = ndisc_opt_addr_data(ndopts.nd_opts_src_lladdr, dev); if (!lladdr) { ND_PRINTK(2, warn, "NS: invalid link-layer address length\n"); return; } /* RFC2461 7.1.1: * If the IP source address is the unspecified address, * there MUST NOT be source link-layer address option * in the message. */ if (dad) { ND_PRINTK(2, warn, "NS: bad DAD packet (link-layer address option)\n"); return; } } inc = ipv6_addr_is_multicast(daddr); ifp = ipv6_get_ifaddr(dev_net(dev), &msg->target, dev, 1); if (ifp) { if (ifp->flags & (IFA_F_TENTATIVE|IFA_F_OPTIMISTIC)) { if (dad) { /* * We are colliding with another node * who is doing DAD * so fail our DAD process */ addrconf_dad_failure(ifp); return; } else { /* * This is not a dad solicitation. * If we are an optimistic node, * we should respond. * Otherwise, we should ignore it. */ if (!(ifp->flags & IFA_F_OPTIMISTIC)) goto out; } } idev = ifp->idev; } else { struct net *net = dev_net(dev); idev = in6_dev_get(dev); if (!idev) { /* XXX: count this drop? */ return; } if (ipv6_chk_acast_addr(net, dev, &msg->target) || (idev->cnf.forwarding && (net->ipv6.devconf_all->proxy_ndp || idev->cnf.proxy_ndp) && (is_router = pndisc_is_router(&msg->target, dev)) >= 0)) { if (!(NEIGH_CB(skb)->flags & LOCALLY_ENQUEUED) && skb->pkt_type != PACKET_HOST && inc && NEIGH_VAR(idev->nd_parms, PROXY_DELAY) != 0) { /* * for anycast or proxy, * sender should delay its response * by a random time between 0 and * MAX_ANYCAST_DELAY_TIME seconds. * (RFC2461) -- yoshfuji */ struct sk_buff *n = skb_clone(skb, GFP_ATOMIC); if (n) pneigh_enqueue(&nd_tbl, idev->nd_parms, n); goto out; } } else goto out; } if (is_router < 0) is_router = idev->cnf.forwarding; if (dad) { ndisc_send_na(dev, NULL, &in6addr_linklocal_allnodes, &msg->target, !!is_router, false, (ifp != NULL), true); goto out; } if (inc) NEIGH_CACHE_STAT_INC(&nd_tbl, rcv_probes_mcast); else NEIGH_CACHE_STAT_INC(&nd_tbl, rcv_probes_ucast); /* * update / create cache entry * for the source address */ neigh = __neigh_lookup(&nd_tbl, saddr, dev, !inc || lladdr || !dev->addr_len); if (neigh) neigh_update(neigh, lladdr, NUD_STALE, NEIGH_UPDATE_F_WEAK_OVERRIDE| NEIGH_UPDATE_F_OVERRIDE); if (neigh || !dev->header_ops) { ndisc_send_na(dev, neigh, saddr, &msg->target, !!is_router, true, (ifp != NULL && inc), inc); if (neigh) neigh_release(neigh); } out: if (ifp) in6_ifa_put(ifp); else in6_dev_put(idev); } static void ndisc_recv_na(struct sk_buff *skb) { struct nd_msg *msg = (struct nd_msg *)skb_transport_header(skb); struct in6_addr *saddr = &ipv6_hdr(skb)->saddr; const struct in6_addr *daddr = &ipv6_hdr(skb)->daddr; u8 *lladdr = NULL; u32 ndoptlen = skb_tail_pointer(skb) - (skb_transport_header(skb) + offsetof(struct nd_msg, opt)); struct ndisc_options ndopts; struct net_device *dev = skb->dev; struct inet6_ifaddr *ifp; struct neighbour *neigh; if (skb->len < sizeof(struct nd_msg)) { ND_PRINTK(2, warn, "NA: packet too short\n"); return; } if (ipv6_addr_is_multicast(&msg->target)) { ND_PRINTK(2, warn, "NA: target address is multicast\n"); return; } if (ipv6_addr_is_multicast(daddr) && msg->icmph.icmp6_solicited) { ND_PRINTK(2, warn, "NA: solicited NA is multicasted\n"); return; } if (!ndisc_parse_options(msg->opt, ndoptlen, &ndopts)) { ND_PRINTK(2, warn, "NS: invalid ND option\n"); return; } if (ndopts.nd_opts_tgt_lladdr) { lladdr = ndisc_opt_addr_data(ndopts.nd_opts_tgt_lladdr, dev); if (!lladdr) { ND_PRINTK(2, warn, "NA: invalid link-layer address length\n"); return; } } ifp = ipv6_get_ifaddr(dev_net(dev), &msg->target, dev, 1); if (ifp) { if (skb->pkt_type != PACKET_LOOPBACK && (ifp->flags & IFA_F_TENTATIVE)) { addrconf_dad_failure(ifp); return; } /* What should we make now? The advertisement is invalid, but ndisc specs say nothing about it. It could be misconfiguration, or an smart proxy agent tries to help us :-) We should not print the error if NA has been received from loopback - it is just our own unsolicited advertisement. */ if (skb->pkt_type != PACKET_LOOPBACK) ND_PRINTK(1, warn, "NA: someone advertises our address %pI6 on %s!\n", &ifp->addr, ifp->idev->dev->name); in6_ifa_put(ifp); return; } neigh = neigh_lookup(&nd_tbl, &msg->target, dev); if (neigh) { u8 old_flags = neigh->flags; struct net *net = dev_net(dev); if (neigh->nud_state & NUD_FAILED) goto out; /* * Don't update the neighbor cache entry on a proxy NA from * ourselves because either the proxied node is off link or it * has already sent a NA to us. */ if (lladdr && !memcmp(lladdr, dev->dev_addr, dev->addr_len) && net->ipv6.devconf_all->forwarding && net->ipv6.devconf_all->proxy_ndp && pneigh_lookup(&nd_tbl, net, &msg->target, dev, 0)) { /* XXX: idev->cnf.proxy_ndp */ goto out; } neigh_update(neigh, lladdr, msg->icmph.icmp6_solicited ? NUD_REACHABLE : NUD_STALE, NEIGH_UPDATE_F_WEAK_OVERRIDE| (msg->icmph.icmp6_override ? NEIGH_UPDATE_F_OVERRIDE : 0)| NEIGH_UPDATE_F_OVERRIDE_ISROUTER| (msg->icmph.icmp6_router ? NEIGH_UPDATE_F_ISROUTER : 0)); if ((old_flags & ~neigh->flags) & NTF_ROUTER) { /* * Change: router to host */ rt6_clean_tohost(dev_net(dev), saddr); } out: neigh_release(neigh); } } static void ndisc_recv_rs(struct sk_buff *skb) { struct rs_msg *rs_msg = (struct rs_msg *)skb_transport_header(skb); unsigned long ndoptlen = skb->len - sizeof(*rs_msg); struct neighbour *neigh; struct inet6_dev *idev; const struct in6_addr *saddr = &ipv6_hdr(skb)->saddr; struct ndisc_options ndopts; u8 *lladdr = NULL; if (skb->len < sizeof(*rs_msg)) return; idev = __in6_dev_get(skb->dev); if (!idev) { ND_PRINTK(1, err, "RS: can't find in6 device\n"); return; } /* Don't accept RS if we're not in router mode */ if (!idev->cnf.forwarding) goto out; /* * Don't update NCE if src = ::; * this implies that the source node has no ip address assigned yet. */ if (ipv6_addr_any(saddr)) goto out; /* Parse ND options */ if (!ndisc_parse_options(rs_msg->opt, ndoptlen, &ndopts)) { ND_PRINTK(2, notice, "NS: invalid ND option, ignored\n"); goto out; } if (ndopts.nd_opts_src_lladdr) { lladdr = ndisc_opt_addr_data(ndopts.nd_opts_src_lladdr, skb->dev); if (!lladdr) goto out; } neigh = __neigh_lookup(&nd_tbl, saddr, skb->dev, 1); if (neigh) { neigh_update(neigh, lladdr, NUD_STALE, NEIGH_UPDATE_F_WEAK_OVERRIDE| NEIGH_UPDATE_F_OVERRIDE| NEIGH_UPDATE_F_OVERRIDE_ISROUTER); neigh_release(neigh); } out: return; } static void ndisc_ra_useropt(struct sk_buff *ra, struct nd_opt_hdr *opt) { struct icmp6hdr *icmp6h = (struct icmp6hdr *)skb_transport_header(ra); struct sk_buff *skb; struct nlmsghdr *nlh; struct nduseroptmsg *ndmsg; struct net *net = dev_net(ra->dev); int err; int base_size = NLMSG_ALIGN(sizeof(struct nduseroptmsg) + (opt->nd_opt_len << 3)); size_t msg_size = base_size + nla_total_size(sizeof(struct in6_addr)); skb = nlmsg_new(msg_size, GFP_ATOMIC); if (skb == NULL) { err = -ENOBUFS; goto errout; } nlh = nlmsg_put(skb, 0, 0, RTM_NEWNDUSEROPT, base_size, 0); if (nlh == NULL) { goto nla_put_failure; } ndmsg = nlmsg_data(nlh); ndmsg->nduseropt_family = AF_INET6; ndmsg->nduseropt_ifindex = ra->dev->ifindex; ndmsg->nduseropt_icmp_type = icmp6h->icmp6_type; ndmsg->nduseropt_icmp_code = icmp6h->icmp6_code; ndmsg->nduseropt_opts_len = opt->nd_opt_len << 3; memcpy(ndmsg + 1, opt, opt->nd_opt_len << 3); if (nla_put(skb, NDUSEROPT_SRCADDR, sizeof(struct in6_addr), &ipv6_hdr(ra)->saddr)) goto nla_put_failure; nlmsg_end(skb, nlh); rtnl_notify(skb, net, 0, RTNLGRP_ND_USEROPT, NULL, GFP_ATOMIC); return; nla_put_failure: nlmsg_free(skb); err = -EMSGSIZE; errout: rtnl_set_sk_err(net, RTNLGRP_ND_USEROPT, err); } static void ndisc_router_discovery(struct sk_buff *skb) { struct ra_msg *ra_msg = (struct ra_msg *)skb_transport_header(skb); struct neighbour *neigh = NULL; struct inet6_dev *in6_dev; struct rt6_info *rt = NULL; int lifetime; struct ndisc_options ndopts; int optlen; unsigned int pref = 0; __u8 *opt = (__u8 *)(ra_msg + 1); optlen = (skb_tail_pointer(skb) - skb_transport_header(skb)) - sizeof(struct ra_msg); ND_PRINTK(2, info, "RA: %s, dev: %s\n", __func__, skb->dev->name); if (!(ipv6_addr_type(&ipv6_hdr(skb)->saddr) & IPV6_ADDR_LINKLOCAL)) { ND_PRINTK(2, warn, "RA: source address is not link-local\n"); return; } if (optlen < 0) { ND_PRINTK(2, warn, "RA: packet too short\n"); return; } #ifdef CONFIG_IPV6_NDISC_NODETYPE if (skb->ndisc_nodetype == NDISC_NODETYPE_HOST) { ND_PRINTK(2, warn, "RA: from host or unauthorized router\n"); return; } #endif /* * set the RA_RECV flag in the interface */ in6_dev = __in6_dev_get(skb->dev); if (in6_dev == NULL) { ND_PRINTK(0, err, "RA: can't find inet6 device for %s\n", skb->dev->name); return; } if (!ndisc_parse_options(opt, optlen, &ndopts)) { ND_PRINTK(2, warn, "RA: invalid ND options\n"); return; } if (!ipv6_accept_ra(in6_dev)) { ND_PRINTK(2, info, "RA: %s, did not accept ra for dev: %s\n", __func__, skb->dev->name); goto skip_linkparms; } #ifdef CONFIG_IPV6_NDISC_NODETYPE /* skip link-specific parameters from interior routers */ if (skb->ndisc_nodetype == NDISC_NODETYPE_NODEFAULT) { ND_PRINTK(2, info, "RA: %s, nodetype is NODEFAULT, dev: %s\n", __func__, skb->dev->name); goto skip_linkparms; } #endif if (in6_dev->if_flags & IF_RS_SENT) { /* * flag that an RA was received after an RS was sent * out on this interface. */ in6_dev->if_flags |= IF_RA_RCVD; } /* * Remember the managed/otherconf flags from most recently * received RA message (RFC 2462) -- yoshfuji */ in6_dev->if_flags = (in6_dev->if_flags & ~(IF_RA_MANAGED | IF_RA_OTHERCONF)) | (ra_msg->icmph.icmp6_addrconf_managed ? IF_RA_MANAGED : 0) | (ra_msg->icmph.icmp6_addrconf_other ? IF_RA_OTHERCONF : 0); if (!in6_dev->cnf.accept_ra_defrtr) { ND_PRINTK(2, info, "RA: %s, defrtr is false for dev: %s\n", __func__, skb->dev->name); goto skip_defrtr; } /* Do not accept RA with source-addr found on local machine unless * accept_ra_from_local is set to true. */ if (!in6_dev->cnf.accept_ra_from_local && ipv6_chk_addr(dev_net(in6_dev->dev), &ipv6_hdr(skb)->saddr, NULL, 0)) { ND_PRINTK(2, info, "RA from local address detected on dev: %s: default router ignored\n", skb->dev->name); goto skip_defrtr; } lifetime = ntohs(ra_msg->icmph.icmp6_rt_lifetime); #ifdef CONFIG_IPV6_ROUTER_PREF pref = ra_msg->icmph.icmp6_router_pref; /* 10b is handled as if it were 00b (medium) */ if (pref == ICMPV6_ROUTER_PREF_INVALID || !in6_dev->cnf.accept_ra_rtr_pref) pref = ICMPV6_ROUTER_PREF_MEDIUM; #endif rt = rt6_get_dflt_router(&ipv6_hdr(skb)->saddr, skb->dev); if (rt) { neigh = dst_neigh_lookup(&rt->dst, &ipv6_hdr(skb)->saddr); if (!neigh) { ND_PRINTK(0, err, "RA: %s got default router without neighbour\n", __func__); ip6_rt_put(rt); return; } } if (rt && lifetime == 0) { ip6_del_rt(rt); rt = NULL; } ND_PRINTK(3, info, "RA: rt: %p lifetime: %d, for dev: %s\n", rt, lifetime, skb->dev->name); if (rt == NULL && lifetime) { ND_PRINTK(3, info, "RA: adding default router\n"); rt = rt6_add_dflt_router(&ipv6_hdr(skb)->saddr, skb->dev, pref); if (rt == NULL) { ND_PRINTK(0, err, "RA: %s failed to add default route\n", __func__); return; } neigh = dst_neigh_lookup(&rt->dst, &ipv6_hdr(skb)->saddr); if (neigh == NULL) { ND_PRINTK(0, err, "RA: %s got default router without neighbour\n", __func__); ip6_rt_put(rt); return; } neigh->flags |= NTF_ROUTER; } else if (rt) { rt->rt6i_flags = (rt->rt6i_flags & ~RTF_PREF_MASK) | RTF_PREF(pref); } if (rt) rt6_set_expires(rt, jiffies + (HZ * lifetime)); if (ra_msg->icmph.icmp6_hop_limit) { /* Only set hop_limit on the interface if it is higher than * the current hop_limit. */ if (in6_dev->cnf.hop_limit < ra_msg->icmph.icmp6_hop_limit) { in6_dev->cnf.hop_limit = ra_msg->icmph.icmp6_hop_limit; } else { ND_PRINTK(2, warn, "RA: Got route advertisement with lower hop_limit than current\n"); } if (rt) dst_metric_set(&rt->dst, RTAX_HOPLIMIT, ra_msg->icmph.icmp6_hop_limit); } skip_defrtr: /* * Update Reachable Time and Retrans Timer */ if (in6_dev->nd_parms) { unsigned long rtime = ntohl(ra_msg->retrans_timer); if (rtime && rtime/1000 < MAX_SCHEDULE_TIMEOUT/HZ) { rtime = (rtime*HZ)/1000; if (rtime < HZ/10) rtime = HZ/10; NEIGH_VAR_SET(in6_dev->nd_parms, RETRANS_TIME, rtime); in6_dev->tstamp = jiffies; inet6_ifinfo_notify(RTM_NEWLINK, in6_dev); } rtime = ntohl(ra_msg->reachable_time); if (rtime && rtime/1000 < MAX_SCHEDULE_TIMEOUT/(3*HZ)) { rtime = (rtime*HZ)/1000; if (rtime < HZ/10) rtime = HZ/10; if (rtime != NEIGH_VAR(in6_dev->nd_parms, BASE_REACHABLE_TIME)) { NEIGH_VAR_SET(in6_dev->nd_parms, BASE_REACHABLE_TIME, rtime); NEIGH_VAR_SET(in6_dev->nd_parms, GC_STALETIME, 3 * rtime); in6_dev->nd_parms->reachable_time = neigh_rand_reach_time(rtime); in6_dev->tstamp = jiffies; inet6_ifinfo_notify(RTM_NEWLINK, in6_dev); } } } skip_linkparms: /* * Process options. */ if (!neigh) neigh = __neigh_lookup(&nd_tbl, &ipv6_hdr(skb)->saddr, skb->dev, 1); if (neigh) { u8 *lladdr = NULL; if (ndopts.nd_opts_src_lladdr) { lladdr = ndisc_opt_addr_data(ndopts.nd_opts_src_lladdr, skb->dev); if (!lladdr) { ND_PRINTK(2, warn, "RA: invalid link-layer address length\n"); goto out; } } neigh_update(neigh, lladdr, NUD_STALE, NEIGH_UPDATE_F_WEAK_OVERRIDE| NEIGH_UPDATE_F_OVERRIDE| NEIGH_UPDATE_F_OVERRIDE_ISROUTER| NEIGH_UPDATE_F_ISROUTER); } if (!ipv6_accept_ra(in6_dev)) { ND_PRINTK(2, info, "RA: %s, accept_ra is false for dev: %s\n", __func__, skb->dev->name); goto out; } #ifdef CONFIG_IPV6_ROUTE_INFO if (!in6_dev->cnf.accept_ra_from_local && ipv6_chk_addr(dev_net(in6_dev->dev), &ipv6_hdr(skb)->saddr, NULL, 0)) { ND_PRINTK(2, info, "RA from local address detected on dev: %s: router info ignored.\n", skb->dev->name); goto skip_routeinfo; } if (in6_dev->cnf.accept_ra_rtr_pref && ndopts.nd_opts_ri) { struct nd_opt_hdr *p; for (p = ndopts.nd_opts_ri; p; p = ndisc_next_option(p, ndopts.nd_opts_ri_end)) { struct route_info *ri = (struct route_info *)p; #ifdef CONFIG_IPV6_NDISC_NODETYPE if (skb->ndisc_nodetype == NDISC_NODETYPE_NODEFAULT && ri->prefix_len == 0) continue; #endif if (ri->prefix_len == 0 && !in6_dev->cnf.accept_ra_defrtr) continue; if (ri->prefix_len > in6_dev->cnf.accept_ra_rt_info_max_plen) continue; rt6_route_rcv(skb->dev, (u8 *)p, (p->nd_opt_len) << 3, &ipv6_hdr(skb)->saddr); } } skip_routeinfo: #endif #ifdef CONFIG_IPV6_NDISC_NODETYPE /* skip link-specific ndopts from interior routers */ if (skb->ndisc_nodetype == NDISC_NODETYPE_NODEFAULT) { ND_PRINTK(2, info, "RA: %s, nodetype is NODEFAULT (interior routes), dev: %s\n", __func__, skb->dev->name); goto out; } #endif if (in6_dev->cnf.accept_ra_pinfo && ndopts.nd_opts_pi) { struct nd_opt_hdr *p; for (p = ndopts.nd_opts_pi; p; p = ndisc_next_option(p, ndopts.nd_opts_pi_end)) { addrconf_prefix_rcv(skb->dev, (u8 *)p, (p->nd_opt_len) << 3, ndopts.nd_opts_src_lladdr != NULL); } } if (ndopts.nd_opts_mtu && in6_dev->cnf.accept_ra_mtu) { __be32 n; u32 mtu; memcpy(&n, ((u8 *)(ndopts.nd_opts_mtu+1))+2, sizeof(mtu)); mtu = ntohl(n); if (mtu < IPV6_MIN_MTU || mtu > skb->dev->mtu) { ND_PRINTK(2, warn, "RA: invalid mtu: %d\n", mtu); } else if (in6_dev->cnf.mtu6 != mtu) { in6_dev->cnf.mtu6 = mtu; if (rt) dst_metric_set(&rt->dst, RTAX_MTU, mtu); rt6_mtu_change(skb->dev, mtu); } } if (ndopts.nd_useropts) { struct nd_opt_hdr *p; for (p = ndopts.nd_useropts; p; p = ndisc_next_useropt(p, ndopts.nd_useropts_end)) { ndisc_ra_useropt(skb, p); } } if (ndopts.nd_opts_tgt_lladdr || ndopts.nd_opts_rh) { ND_PRINTK(2, warn, "RA: invalid RA options\n"); } out: ip6_rt_put(rt); if (neigh) neigh_release(neigh); } static void ndisc_redirect_rcv(struct sk_buff *skb) { u8 *hdr; struct ndisc_options ndopts; struct rd_msg *msg = (struct rd_msg *)skb_transport_header(skb); u32 ndoptlen = skb_tail_pointer(skb) - (skb_transport_header(skb) + offsetof(struct rd_msg, opt)); #ifdef CONFIG_IPV6_NDISC_NODETYPE switch (skb->ndisc_nodetype) { case NDISC_NODETYPE_HOST: case NDISC_NODETYPE_NODEFAULT: ND_PRINTK(2, warn, "Redirect: from host or unauthorized router\n"); return; } #endif if (!(ipv6_addr_type(&ipv6_hdr(skb)->saddr) & IPV6_ADDR_LINKLOCAL)) { ND_PRINTK(2, warn, "Redirect: source address is not link-local\n"); return; } if (!ndisc_parse_options(msg->opt, ndoptlen, &ndopts)) return; if (!ndopts.nd_opts_rh) { ip6_redirect_no_header(skb, dev_net(skb->dev), skb->dev->ifindex, 0); return; } hdr = (u8 *)ndopts.nd_opts_rh; hdr += 8; if (!pskb_pull(skb, hdr - skb_transport_header(skb))) return; icmpv6_notify(skb, NDISC_REDIRECT, 0, 0); } static void ndisc_fill_redirect_hdr_option(struct sk_buff *skb, struct sk_buff *orig_skb, int rd_len) { u8 *opt = skb_put(skb, rd_len); memset(opt, 0, 8); *(opt++) = ND_OPT_REDIRECT_HDR; *(opt++) = (rd_len >> 3); opt += 6; memcpy(opt, ipv6_hdr(orig_skb), rd_len - 8); } void ndisc_send_redirect(struct sk_buff *skb, const struct in6_addr *target) { struct net_device *dev = skb->dev; struct net *net = dev_net(dev); struct sock *sk = net->ipv6.ndisc_sk; int optlen = 0; struct inet_peer *peer; struct sk_buff *buff; struct rd_msg *msg; struct in6_addr saddr_buf; struct rt6_info *rt; struct dst_entry *dst; struct flowi6 fl6; int rd_len; u8 ha_buf[MAX_ADDR_LEN], *ha = NULL; bool ret; if (ipv6_get_lladdr(dev, &saddr_buf, IFA_F_TENTATIVE)) { ND_PRINTK(2, warn, "Redirect: no link-local address on %s\n", dev->name); return; } if (!ipv6_addr_equal(&ipv6_hdr(skb)->daddr, target) && ipv6_addr_type(target) != (IPV6_ADDR_UNICAST|IPV6_ADDR_LINKLOCAL)) { ND_PRINTK(2, warn, "Redirect: target address is not link-local unicast\n"); return; } icmpv6_flow_init(sk, &fl6, NDISC_REDIRECT, &saddr_buf, &ipv6_hdr(skb)->saddr, dev->ifindex); dst = ip6_route_output(net, NULL, &fl6); if (dst->error) { dst_release(dst); return; } dst = xfrm_lookup(net, dst, flowi6_to_flowi(&fl6), NULL, 0); if (IS_ERR(dst)) return; rt = (struct rt6_info *) dst; if (rt->rt6i_flags & RTF_GATEWAY) { ND_PRINTK(2, warn, "Redirect: destination is not a neighbour\n"); goto release; } peer = inet_getpeer_v6(net->ipv6.peers, &rt->rt6i_dst.addr, 1); ret = inet_peer_xrlim_allow(peer, 1*HZ); if (peer) inet_putpeer(peer); if (!ret) goto release; if (dev->addr_len) { struct neighbour *neigh = dst_neigh_lookup(skb_dst(skb), target); if (!neigh) { ND_PRINTK(2, warn, "Redirect: no neigh for target address\n"); goto release; } read_lock_bh(&neigh->lock); if (neigh->nud_state & NUD_VALID) { memcpy(ha_buf, neigh->ha, dev->addr_len); read_unlock_bh(&neigh->lock); ha = ha_buf; optlen += ndisc_opt_addr_space(dev); } else read_unlock_bh(&neigh->lock); neigh_release(neigh); } rd_len = min_t(unsigned int, IPV6_MIN_MTU - sizeof(struct ipv6hdr) - sizeof(*msg) - optlen, skb->len + 8); rd_len &= ~0x7; optlen += rd_len; buff = ndisc_alloc_skb(dev, sizeof(*msg) + optlen); if (!buff) goto release; msg = (struct rd_msg *)skb_put(buff, sizeof(*msg)); *msg = (struct rd_msg) { .icmph = { .icmp6_type = NDISC_REDIRECT, }, .target = *target, .dest = ipv6_hdr(skb)->daddr, }; /* * include target_address option */ if (ha) ndisc_fill_addr_option(buff, ND_OPT_TARGET_LL_ADDR, ha); /* * build redirect option and copy skb over to the new packet. */ if (rd_len) ndisc_fill_redirect_hdr_option(buff, skb, rd_len); skb_dst_set(buff, dst); ndisc_send_skb(buff, &ipv6_hdr(skb)->saddr, &saddr_buf); return; release: dst_release(dst); } static void pndisc_redo(struct sk_buff *skb) { ndisc_recv_ns(skb); kfree_skb(skb); } static bool ndisc_suppress_frag_ndisc(struct sk_buff *skb) { struct inet6_dev *idev = __in6_dev_get(skb->dev); if (!idev) return true; if (IP6CB(skb)->flags & IP6SKB_FRAGMENTED && idev->cnf.suppress_frag_ndisc) { net_warn_ratelimited("Received fragmented ndisc packet. Carefully consider disabling suppress_frag_ndisc.\n"); return true; } return false; } int ndisc_rcv(struct sk_buff *skb) { struct nd_msg *msg; if (ndisc_suppress_frag_ndisc(skb)) return 0; if (skb_linearize(skb)) return 0; msg = (struct nd_msg *)skb_transport_header(skb); __skb_push(skb, skb->data - skb_transport_header(skb)); if (ipv6_hdr(skb)->hop_limit != 255) { ND_PRINTK(2, warn, "NDISC: invalid hop-limit: %d\n", ipv6_hdr(skb)->hop_limit); return 0; } if (msg->icmph.icmp6_code != 0) { ND_PRINTK(2, warn, "NDISC: invalid ICMPv6 code: %d\n", msg->icmph.icmp6_code); return 0; } memset(NEIGH_CB(skb), 0, sizeof(struct neighbour_cb)); switch (msg->icmph.icmp6_type) { case NDISC_NEIGHBOUR_SOLICITATION: ndisc_recv_ns(skb); break; case NDISC_NEIGHBOUR_ADVERTISEMENT: ndisc_recv_na(skb); break; case NDISC_ROUTER_SOLICITATION: ndisc_recv_rs(skb); break; case NDISC_ROUTER_ADVERTISEMENT: ndisc_router_discovery(skb); break; case NDISC_REDIRECT: ndisc_redirect_rcv(skb); break; } return 0; } static int ndisc_netdev_event(struct notifier_block *this, unsigned long event, void *ptr) { struct net_device *dev = netdev_notifier_info_to_dev(ptr); struct net *net = dev_net(dev); struct inet6_dev *idev; switch (event) { case NETDEV_CHANGEADDR: neigh_changeaddr(&nd_tbl, dev); fib6_run_gc(0, net, false); idev = in6_dev_get(dev); if (!idev) break; if (idev->cnf.ndisc_notify) ndisc_send_unsol_na(dev); in6_dev_put(idev); break; case NETDEV_DOWN: neigh_ifdown(&nd_tbl, dev); fib6_run_gc(0, net, false); break; case NETDEV_NOTIFY_PEERS: ndisc_send_unsol_na(dev); break; default: break; } return NOTIFY_DONE; } static struct notifier_block ndisc_netdev_notifier = { .notifier_call = ndisc_netdev_event, }; #ifdef CONFIG_SYSCTL static void ndisc_warn_deprecated_sysctl(struct ctl_table *ctl, const char *func, const char *dev_name) { static char warncomm[TASK_COMM_LEN]; static int warned; if (strcmp(warncomm, current->comm) && warned < 5) { strcpy(warncomm, current->comm); pr_warn("process `%s' is using deprecated sysctl (%s) net.ipv6.neigh.%s.%s - use net.ipv6.neigh.%s.%s_ms instead\n", warncomm, func, dev_name, ctl->procname, dev_name, ctl->procname); warned++; } } int ndisc_ifinfo_sysctl_change(struct ctl_table *ctl, int write, void __user *buffer, size_t *lenp, loff_t *ppos) { struct net_device *dev = ctl->extra1; struct inet6_dev *idev; int ret; if ((strcmp(ctl->procname, "retrans_time") == 0) || (strcmp(ctl->procname, "base_reachable_time") == 0)) ndisc_warn_deprecated_sysctl(ctl, "syscall", dev ? dev->name : "default"); if (strcmp(ctl->procname, "retrans_time") == 0) ret = neigh_proc_dointvec(ctl, write, buffer, lenp, ppos); else if (strcmp(ctl->procname, "base_reachable_time") == 0) ret = neigh_proc_dointvec_jiffies(ctl, write, buffer, lenp, ppos); else if ((strcmp(ctl->procname, "retrans_time_ms") == 0) || (strcmp(ctl->procname, "base_reachable_time_ms") == 0)) ret = neigh_proc_dointvec_ms_jiffies(ctl, write, buffer, lenp, ppos); else ret = -1; if (write && ret == 0 && dev && (idev = in6_dev_get(dev)) != NULL) { if (ctl->data == &NEIGH_VAR(idev->nd_parms, BASE_REACHABLE_TIME)) idev->nd_parms->reachable_time = neigh_rand_reach_time(NEIGH_VAR(idev->nd_parms, BASE_REACHABLE_TIME)); idev->tstamp = jiffies; inet6_ifinfo_notify(RTM_NEWLINK, idev); in6_dev_put(idev); } return ret; } #endif static int __net_init ndisc_net_init(struct net *net) { struct ipv6_pinfo *np; struct sock *sk; int err; err = inet_ctl_sock_create(&sk, PF_INET6, SOCK_RAW, IPPROTO_ICMPV6, net); if (err < 0) { ND_PRINTK(0, err, "NDISC: Failed to initialize the control socket (err %d)\n", err); return err; } net->ipv6.ndisc_sk = sk; np = inet6_sk(sk); np->hop_limit = 255; /* Do not loopback ndisc messages */ np->mc_loop = 0; return 0; } static void __net_exit ndisc_net_exit(struct net *net) { inet_ctl_sock_destroy(net->ipv6.ndisc_sk); } static struct pernet_operations ndisc_net_ops = { .init = ndisc_net_init, .exit = ndisc_net_exit, }; int __init ndisc_init(void) { int err; err = register_pernet_subsys(&ndisc_net_ops); if (err) return err; /* * Initialize the neighbour table */ neigh_table_init(NEIGH_ND_TABLE, &nd_tbl); #ifdef CONFIG_SYSCTL err = neigh_sysctl_register(NULL, &nd_tbl.parms, ndisc_ifinfo_sysctl_change); if (err) goto out_unregister_pernet; out: #endif return err; #ifdef CONFIG_SYSCTL out_unregister_pernet: unregister_pernet_subsys(&ndisc_net_ops); goto out; #endif } int __init ndisc_late_init(void) { return register_netdevice_notifier(&ndisc_netdev_notifier); } void ndisc_late_cleanup(void) { unregister_netdevice_notifier(&ndisc_netdev_notifier); } void ndisc_cleanup(void) { #ifdef CONFIG_SYSCTL neigh_sysctl_unregister(&nd_tbl.parms); #endif neigh_table_clear(NEIGH_ND_TABLE, &nd_tbl); unregister_pernet_subsys(&ndisc_net_ops); }
./CrossVul/dataset_final_sorted/CWE-17/c/good_1546_0
crossvul-cpp_data_good_1510_0
/* * sysctl_net_llc.c: sysctl interface to LLC net subsystem. * * Arnaldo Carvalho de Melo <acme@conectiva.com.br> */ #include <linux/mm.h> #include <linux/init.h> #include <linux/sysctl.h> #include <net/net_namespace.h> #include <net/llc.h> #ifndef CONFIG_SYSCTL #error This file should not be compiled without CONFIG_SYSCTL defined #endif static struct ctl_table llc2_timeout_table[] = { { .procname = "ack", .data = &sysctl_llc2_ack_timeout, .maxlen = sizeof(sysctl_llc2_ack_timeout), .mode = 0644, .proc_handler = proc_dointvec_jiffies, }, { .procname = "busy", .data = &sysctl_llc2_busy_timeout, .maxlen = sizeof(sysctl_llc2_busy_timeout), .mode = 0644, .proc_handler = proc_dointvec_jiffies, }, { .procname = "p", .data = &sysctl_llc2_p_timeout, .maxlen = sizeof(sysctl_llc2_p_timeout), .mode = 0644, .proc_handler = proc_dointvec_jiffies, }, { .procname = "rej", .data = &sysctl_llc2_rej_timeout, .maxlen = sizeof(sysctl_llc2_rej_timeout), .mode = 0644, .proc_handler = proc_dointvec_jiffies, }, { }, }; static struct ctl_table llc_station_table[] = { { }, }; static struct ctl_table_header *llc2_timeout_header; static struct ctl_table_header *llc_station_header; int __init llc_sysctl_init(void) { llc2_timeout_header = register_net_sysctl(&init_net, "net/llc/llc2/timeout", llc2_timeout_table); llc_station_header = register_net_sysctl(&init_net, "net/llc/station", llc_station_table); if (!llc2_timeout_header || !llc_station_header) { llc_sysctl_exit(); return -ENOMEM; } return 0; } void llc_sysctl_exit(void) { if (llc2_timeout_header) { unregister_net_sysctl_table(llc2_timeout_header); llc2_timeout_header = NULL; } if (llc_station_header) { unregister_net_sysctl_table(llc_station_header); llc_station_header = NULL; } }
./CrossVul/dataset_final_sorted/CWE-17/c/good_1510_0
crossvul-cpp_data_good_1629_0
/* ** $Id: ldo.c,v 2.38.1.4 2012/01/18 02:27:10 roberto Exp $ ** Stack and Call structure of Lua ** See Copyright Notice in lua.h */ #include <setjmp.h> #include <stdlib.h> #include <string.h> #define ldo_c #define LUA_CORE #include "lua.h" #include "ldebug.h" #include "ldo.h" #include "lfunc.h" #include "lgc.h" #include "lmem.h" #include "lobject.h" #include "lopcodes.h" #include "lparser.h" #include "lstate.h" #include "lstring.h" #include "ltable.h" #include "ltm.h" #include "lundump.h" #include "lvm.h" #include "lzio.h" /* ** {====================================================== ** Error-recovery functions ** ======================================================= */ /* chain list of long jump buffers */ struct lua_longjmp { struct lua_longjmp *previous; luai_jmpbuf b; volatile int status; /* error code */ }; void luaD_seterrorobj (lua_State *L, int errcode, StkId oldtop) { switch (errcode) { case LUA_ERRMEM: { setsvalue2s(L, oldtop, luaS_newliteral(L, MEMERRMSG)); break; } case LUA_ERRERR: { setsvalue2s(L, oldtop, luaS_newliteral(L, "error in error handling")); break; } case LUA_ERRSYNTAX: case LUA_ERRRUN: { setobjs2s(L, oldtop, L->top - 1); /* error message on current top */ break; } } L->top = oldtop + 1; } static void restore_stack_limit (lua_State *L) { lua_assert(L->stack_last - L->stack == L->stacksize - EXTRA_STACK - 1); if (L->size_ci > LUAI_MAXCALLS) { /* there was an overflow? */ int inuse = cast_int(L->ci - L->base_ci); if (inuse + 1 < LUAI_MAXCALLS) /* can `undo' overflow? */ luaD_reallocCI(L, LUAI_MAXCALLS); } } static void resetstack (lua_State *L, int status) { L->ci = L->base_ci; L->base = L->ci->base; luaF_close(L, L->base); /* close eventual pending closures */ luaD_seterrorobj(L, status, L->base); L->nCcalls = L->baseCcalls; L->allowhook = 1; restore_stack_limit(L); L->errfunc = 0; L->errorJmp = NULL; } void luaD_throw (lua_State *L, int errcode) { if (L->errorJmp) { L->errorJmp->status = errcode; LUAI_THROW(L, L->errorJmp); } else { L->status = cast_byte(errcode); if (G(L)->panic) { resetstack(L, errcode); lua_unlock(L); G(L)->panic(L); } exit(EXIT_FAILURE); } } int luaD_rawrunprotected (lua_State *L, Pfunc f, void *ud) { struct lua_longjmp lj; lj.status = 0; lj.previous = L->errorJmp; /* chain new error handler */ L->errorJmp = &lj; LUAI_TRY(L, &lj, (*f)(L, ud); ); L->errorJmp = lj.previous; /* restore old error handler */ return lj.status; } /* }====================================================== */ static void correctstack (lua_State *L, TValue *oldstack) { CallInfo *ci; GCObject *up; L->top = (L->top - oldstack) + L->stack; for (up = L->openupval; up != NULL; up = up->gch.next) gco2uv(up)->v = (gco2uv(up)->v - oldstack) + L->stack; for (ci = L->base_ci; ci <= L->ci; ci++) { ci->top = (ci->top - oldstack) + L->stack; ci->base = (ci->base - oldstack) + L->stack; ci->func = (ci->func - oldstack) + L->stack; } L->base = (L->base - oldstack) + L->stack; } void luaD_reallocstack (lua_State *L, int newsize) { TValue *oldstack = L->stack; int realsize = newsize + 1 + EXTRA_STACK; lua_assert(L->stack_last - L->stack == L->stacksize - EXTRA_STACK - 1); luaM_reallocvector(L, L->stack, L->stacksize, realsize, TValue); L->stacksize = realsize; L->stack_last = L->stack+newsize; correctstack(L, oldstack); } void luaD_reallocCI (lua_State *L, int newsize) { CallInfo *oldci = L->base_ci; luaM_reallocvector(L, L->base_ci, L->size_ci, newsize, CallInfo); L->size_ci = newsize; L->ci = (L->ci - oldci) + L->base_ci; L->end_ci = L->base_ci + L->size_ci - 1; } void luaD_growstack (lua_State *L, int n) { if (n <= L->stacksize) /* double size is enough? */ luaD_reallocstack(L, 2*L->stacksize); else luaD_reallocstack(L, L->stacksize + n); } static CallInfo *growCI (lua_State *L) { if (L->size_ci > LUAI_MAXCALLS) /* overflow while handling overflow? */ luaD_throw(L, LUA_ERRERR); else { luaD_reallocCI(L, 2*L->size_ci); if (L->size_ci > LUAI_MAXCALLS) luaG_runerror(L, "stack overflow"); } return ++L->ci; } void luaD_callhook (lua_State *L, int event, int line) { lua_Hook hook = L->hook; if (hook && L->allowhook) { ptrdiff_t top = savestack(L, L->top); ptrdiff_t ci_top = savestack(L, L->ci->top); lua_Debug ar; ar.event = event; ar.currentline = line; if (event == LUA_HOOKTAILRET) ar.i_ci = 0; /* tail call; no debug information about it */ else ar.i_ci = cast_int(L->ci - L->base_ci); luaD_checkstack(L, LUA_MINSTACK); /* ensure minimum stack size */ L->ci->top = L->top + LUA_MINSTACK; lua_assert(L->ci->top <= L->stack_last); L->allowhook = 0; /* cannot call hooks inside a hook */ lua_unlock(L); (*hook)(L, &ar); lua_lock(L); lua_assert(!L->allowhook); L->allowhook = 1; L->ci->top = restorestack(L, ci_top); L->top = restorestack(L, top); } } static StkId adjust_varargs (lua_State *L, Proto *p, int actual) { int i; int nfixargs = p->numparams; Table *htab = NULL; StkId base, fixed; for (; actual < nfixargs; ++actual) setnilvalue(L->top++); #if defined(LUA_COMPAT_VARARG) if (p->is_vararg & VARARG_NEEDSARG) { /* compat. with old-style vararg? */ int nvar = actual - nfixargs; /* number of extra arguments */ lua_assert(p->is_vararg & VARARG_HASARG); luaC_checkGC(L); luaD_checkstack(L, p->maxstacksize); htab = luaH_new(L, nvar, 1); /* create `arg' table */ for (i=0; i<nvar; i++) /* put extra arguments into `arg' table */ setobj2n(L, luaH_setnum(L, htab, i+1), L->top - nvar + i); /* store counter in field `n' */ setnvalue(luaH_setstr(L, htab, luaS_newliteral(L, "n")), cast_num(nvar)); } #endif /* move fixed parameters to final position */ fixed = L->top - actual; /* first fixed argument */ base = L->top; /* final position of first argument */ for (i=0; i<nfixargs; i++) { setobjs2s(L, L->top++, fixed+i); setnilvalue(fixed+i); } /* add `arg' parameter */ if (htab) { sethvalue(L, L->top++, htab); lua_assert(iswhite(obj2gco(htab))); } return base; } static StkId tryfuncTM (lua_State *L, StkId func) { const TValue *tm = luaT_gettmbyobj(L, func, TM_CALL); StkId p; ptrdiff_t funcr = savestack(L, func); if (!ttisfunction(tm)) luaG_typeerror(L, func, "call"); /* Open a hole inside the stack at `func' */ for (p = L->top; p > func; p--) setobjs2s(L, p, p-1); incr_top(L); func = restorestack(L, funcr); /* previous call may change stack */ setobj2s(L, func, tm); /* tag method is the new function to be called */ return func; } #define inc_ci(L) \ ((L->ci == L->end_ci) ? growCI(L) : \ (condhardstacktests(luaD_reallocCI(L, L->size_ci)), ++L->ci)) int luaD_precall (lua_State *L, StkId func, int nresults) { LClosure *cl; ptrdiff_t funcr; if (!ttisfunction(func)) /* `func' is not a function? */ func = tryfuncTM(L, func); /* check the `function' tag method */ funcr = savestack(L, func); cl = &clvalue(func)->l; L->ci->savedpc = L->savedpc; if (!cl->isC) { /* Lua function? prepare its call */ CallInfo *ci; StkId st, base; Proto *p = cl->p; luaD_checkstack(L, p->maxstacksize); func = restorestack(L, funcr); if (!p->is_vararg) { /* no varargs? */ base = func + 1; if (L->top > base + p->numparams) L->top = base + p->numparams; } else { /* vararg function */ int nargs = cast_int(L->top - func) - 1; base = adjust_varargs(L, p, nargs); func = restorestack(L, funcr); /* previous call may change the stack */ } ci = inc_ci(L); /* now `enter' new function */ ci->func = func; L->base = ci->base = base; ci->top = L->base + p->maxstacksize; lua_assert(ci->top <= L->stack_last); L->savedpc = p->code; /* starting point */ ci->tailcalls = 0; ci->nresults = nresults; for (st = L->top; st < ci->top; st++) setnilvalue(st); L->top = ci->top; if (L->hookmask & LUA_MASKCALL) { L->savedpc++; /* hooks assume 'pc' is already incremented */ luaD_callhook(L, LUA_HOOKCALL, -1); L->savedpc--; /* correct 'pc' */ } return PCRLUA; } else { /* if is a C function, call it */ CallInfo *ci; int n; luaD_checkstack(L, LUA_MINSTACK); /* ensure minimum stack size */ ci = inc_ci(L); /* now `enter' new function */ ci->func = restorestack(L, funcr); L->base = ci->base = ci->func + 1; ci->top = L->top + LUA_MINSTACK; lua_assert(ci->top <= L->stack_last); ci->nresults = nresults; if (L->hookmask & LUA_MASKCALL) luaD_callhook(L, LUA_HOOKCALL, -1); lua_unlock(L); n = (*curr_func(L)->c.f)(L); /* do the actual call */ lua_lock(L); if (n < 0) /* yielding? */ return PCRYIELD; else { luaD_poscall(L, L->top - n); return PCRC; } } } static StkId callrethooks (lua_State *L, StkId firstResult) { ptrdiff_t fr = savestack(L, firstResult); /* next call may change stack */ luaD_callhook(L, LUA_HOOKRET, -1); if (f_isLua(L->ci)) { /* Lua function? */ while ((L->hookmask & LUA_MASKRET) && L->ci->tailcalls--) /* tail calls */ luaD_callhook(L, LUA_HOOKTAILRET, -1); } return restorestack(L, fr); } int luaD_poscall (lua_State *L, StkId firstResult) { StkId res; int wanted, i; CallInfo *ci; if (L->hookmask & LUA_MASKRET) firstResult = callrethooks(L, firstResult); ci = L->ci--; res = ci->func; /* res == final position of 1st result */ wanted = ci->nresults; L->base = (ci - 1)->base; /* restore base */ L->savedpc = (ci - 1)->savedpc; /* restore savedpc */ /* move results to correct place */ for (i = wanted; i != 0 && firstResult < L->top; i--) setobjs2s(L, res++, firstResult++); while (i-- > 0) setnilvalue(res++); L->top = res; return (wanted - LUA_MULTRET); /* 0 iff wanted == LUA_MULTRET */ } /* ** Call a function (C or Lua). The function to be called is at *func. ** The arguments are on the stack, right after the function. ** When returns, all the results are on the stack, starting at the original ** function position. */ void luaD_call (lua_State *L, StkId func, int nResults) { if (++L->nCcalls >= LUAI_MAXCCALLS) { if (L->nCcalls == LUAI_MAXCCALLS) luaG_runerror(L, "C stack overflow"); else if (L->nCcalls >= (LUAI_MAXCCALLS + (LUAI_MAXCCALLS>>3))) luaD_throw(L, LUA_ERRERR); /* error while handing stack error */ } if (luaD_precall(L, func, nResults) == PCRLUA) /* is a Lua function? */ luaV_execute(L, 1); /* call it */ L->nCcalls--; luaC_checkGC(L); } static void resume (lua_State *L, void *ud) { StkId firstArg = cast(StkId, ud); CallInfo *ci = L->ci; if (L->status == 0) { /* start coroutine? */ lua_assert(ci == L->base_ci && firstArg > L->base); if (luaD_precall(L, firstArg - 1, LUA_MULTRET) != PCRLUA) return; } else { /* resuming from previous yield */ lua_assert(L->status == LUA_YIELD); L->status = 0; if (!f_isLua(ci)) { /* `common' yield? */ /* finish interrupted execution of `OP_CALL' */ lua_assert(GET_OPCODE(*((ci-1)->savedpc - 1)) == OP_CALL || GET_OPCODE(*((ci-1)->savedpc - 1)) == OP_TAILCALL); if (luaD_poscall(L, firstArg)) /* complete it... */ L->top = L->ci->top; /* and correct top if not multiple results */ } else /* yielded inside a hook: just continue its execution */ L->base = L->ci->base; } luaV_execute(L, cast_int(L->ci - L->base_ci)); } static int resume_error (lua_State *L, const char *msg) { L->top = L->ci->base; setsvalue2s(L, L->top, luaS_new(L, msg)); incr_top(L); lua_unlock(L); return LUA_ERRRUN; } LUA_API int lua_resume (lua_State *L, int nargs) { int status; lua_lock(L); if (L->status != LUA_YIELD && (L->status != 0 || L->ci != L->base_ci)) return resume_error(L, "cannot resume non-suspended coroutine"); if (L->nCcalls >= LUAI_MAXCCALLS) return resume_error(L, "C stack overflow"); luai_userstateresume(L, nargs); lua_assert(L->errfunc == 0); L->baseCcalls = ++L->nCcalls; status = luaD_rawrunprotected(L, resume, L->top - nargs); if (status != 0) { /* error? */ L->status = cast_byte(status); /* mark thread as `dead' */ luaD_seterrorobj(L, status, L->top); L->ci->top = L->top; } else { lua_assert(L->nCcalls == L->baseCcalls); status = L->status; } --L->nCcalls; lua_unlock(L); return status; } LUA_API int lua_yield (lua_State *L, int nresults) { luai_userstateyield(L, nresults); lua_lock(L); if (L->nCcalls > L->baseCcalls) luaG_runerror(L, "attempt to yield across metamethod/C-call boundary"); L->base = L->top - nresults; /* protect stack slots below */ L->status = LUA_YIELD; lua_unlock(L); return -1; } int luaD_pcall (lua_State *L, Pfunc func, void *u, ptrdiff_t old_top, ptrdiff_t ef) { int status; unsigned short oldnCcalls = L->nCcalls; ptrdiff_t old_ci = saveci(L, L->ci); lu_byte old_allowhooks = L->allowhook; ptrdiff_t old_errfunc = L->errfunc; L->errfunc = ef; status = luaD_rawrunprotected(L, func, u); if (status != 0) { /* an error occurred? */ StkId oldtop = restorestack(L, old_top); luaF_close(L, oldtop); /* close eventual pending closures */ luaD_seterrorobj(L, status, oldtop); L->nCcalls = oldnCcalls; L->ci = restoreci(L, old_ci); L->base = L->ci->base; L->savedpc = L->ci->savedpc; L->allowhook = old_allowhooks; restore_stack_limit(L); } L->errfunc = old_errfunc; return status; } /* ** Execute a protected parser. */ struct SParser { /* data to `f_parser' */ ZIO *z; Mbuffer buff; /* buffer to be used by the scanner */ const char *name; }; static void f_parser (lua_State *L, void *ud) { int i; Proto *tf; Closure *cl; struct SParser *p = cast(struct SParser *, ud); int c = luaZ_lookahead(p->z); luaC_checkGC(L); tf = (luaY_parser)(L, p->z, &p->buff, p->name); cl = luaF_newLclosure(L, tf->nups, hvalue(gt(L))); cl->l.p = tf; for (i = 0; i < tf->nups; i++) /* initialize eventual upvalues */ cl->l.upvals[i] = luaF_newupval(L); setclvalue(L, L->top, cl); incr_top(L); } int luaD_protectedparser (lua_State *L, ZIO *z, const char *name) { struct SParser p; int status; p.z = z; p.name = name; luaZ_initbuffer(L, &p.buff); status = luaD_pcall(L, f_parser, &p, savestack(L, L->top), L->errfunc); luaZ_freebuffer(L, &p.buff); return status; }
./CrossVul/dataset_final_sorted/CWE-17/c/good_1629_0
crossvul-cpp_data_good_536_2
/* SPDX-License-Identifier: LGPL-2.1+ */ /*** Copyright © 2016 Michal Soltys <soltys@ziu.info> ***/ #include <errno.h> #include <fcntl.h> #include <limits.h> #include <linux/kd.h> #include <linux/tiocl.h> #include <linux/vt.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <sys/ioctl.h> #include <sysexits.h> #include <termios.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include "alloc-util.h" #include "env-file.h" #include "fd-util.h" #include "fileio.h" #include "io-util.h" #include "locale-util.h" #include "log.h" #include "proc-cmdline.h" #include "process-util.h" #include "signal-util.h" #include "stdio-util.h" #include "string-util.h" #include "strv.h" #include "terminal-util.h" #include "util.h" #include "virt.h" static int verify_vc_device(int fd) { unsigned char data[] = { TIOCL_GETFGCONSOLE, }; int r; r = ioctl(fd, TIOCLINUX, data); if (r < 0) return -errno; return r; } static int verify_vc_allocation(unsigned idx) { char vcname[sizeof("/dev/vcs") + DECIMAL_STR_MAX(unsigned) - 2]; xsprintf(vcname, "/dev/vcs%u", idx); if (access(vcname, F_OK) < 0) return -errno; return 0; } static int verify_vc_allocation_byfd(int fd) { struct vt_stat vcs = {}; if (ioctl(fd, VT_GETSTATE, &vcs) < 0) return -errno; return verify_vc_allocation(vcs.v_active); } static int toggle_utf8(const char *name, int fd, bool utf8) { int r; struct termios tc = {}; assert(name); r = vt_verify_kbmode(fd); if (r == -EBUSY) { log_warning_errno(r, "Virtual console %s is not in K_XLATE or K_UNICODE: %m", name); return 0; } else if (r < 0) return log_warning_errno(r, "Failed to verify kbdmode on %s: %m", name); r = ioctl(fd, KDSKBMODE, utf8 ? K_UNICODE : K_XLATE); if (r < 0) return log_warning_errno(errno, "Failed to %s UTF-8 kbdmode on %s: %m", enable_disable(utf8), name); r = loop_write(fd, utf8 ? "\033%G" : "\033%@", 3, false); if (r < 0) return log_warning_errno(r, "Failed to %s UTF-8 term processing on %s: %m", enable_disable(utf8), name); r = tcgetattr(fd, &tc); if (r >= 0) { SET_FLAG(tc.c_iflag, IUTF8, utf8); r = tcsetattr(fd, TCSANOW, &tc); } if (r < 0) return log_warning_errno(errno, "Failed to %s iutf8 flag on %s: %m", enable_disable(utf8), name); log_debug("UTF-8 kbdmode %sd on %s", enable_disable(utf8), name); return 0; } static int toggle_utf8_sysfs(bool utf8) { int r; r = write_string_file("/sys/module/vt/parameters/default_utf8", one_zero(utf8), WRITE_STRING_FILE_DISABLE_BUFFER); if (r < 0) return log_warning_errno(r, "Failed to %s sysfs UTF-8 flag: %m", enable_disable(utf8)); log_debug("Sysfs UTF-8 flag %sd", enable_disable(utf8)); return 0; } static int keyboard_load_and_wait(const char *vc, const char *map, const char *map_toggle, bool utf8) { const char *args[8]; unsigned i = 0; pid_t pid; int r; /* An empty map means kernel map */ if (isempty(map)) return 0; args[i++] = KBD_LOADKEYS; args[i++] = "-q"; args[i++] = "-C"; args[i++] = vc; if (utf8) args[i++] = "-u"; args[i++] = map; if (map_toggle) args[i++] = map_toggle; args[i++] = NULL; if (DEBUG_LOGGING) { _cleanup_free_ char *cmd; cmd = strv_join((char**) args, " "); log_debug("Executing \"%s\"...", strnull(cmd)); } r = safe_fork("(loadkeys)", FORK_RESET_SIGNALS|FORK_CLOSE_ALL_FDS|FORK_RLIMIT_NOFILE_SAFE|FORK_LOG, &pid); if (r < 0) return r; if (r == 0) { execv(args[0], (char **) args); _exit(EXIT_FAILURE); } return wait_for_terminate_and_check(KBD_LOADKEYS, pid, WAIT_LOG); } static int font_load_and_wait(const char *vc, const char *font, const char *map, const char *unimap) { const char *args[9]; unsigned i = 0; pid_t pid; int r; /* Any part can be set independently */ if (isempty(font) && isempty(map) && isempty(unimap)) return 0; args[i++] = KBD_SETFONT; args[i++] = "-C"; args[i++] = vc; if (!isempty(map)) { args[i++] = "-m"; args[i++] = map; } if (!isempty(unimap)) { args[i++] = "-u"; args[i++] = unimap; } if (!isempty(font)) args[i++] = font; args[i++] = NULL; if (DEBUG_LOGGING) { _cleanup_free_ char *cmd; cmd = strv_join((char**) args, " "); log_debug("Executing \"%s\"...", strnull(cmd)); } r = safe_fork("(setfont)", FORK_RESET_SIGNALS|FORK_CLOSE_ALL_FDS|FORK_RLIMIT_NOFILE_SAFE|FORK_LOG, &pid); if (r < 0) return r; if (r == 0) { execv(args[0], (char **) args); _exit(EXIT_FAILURE); } return wait_for_terminate_and_check(KBD_SETFONT, pid, WAIT_LOG); } /* * A newly allocated VT uses the font from the source VT. Here * we update all possibly already allocated VTs with the configured * font. It also allows to restart systemd-vconsole-setup.service, * to apply a new font to all VTs. * * We also setup per-console utf8 related stuff: kbdmode, term * processing, stty iutf8. */ static void setup_remaining_vcs(int src_fd, unsigned src_idx, bool utf8) { struct console_font_op cfo = { .op = KD_FONT_OP_GET, .width = UINT_MAX, .height = UINT_MAX, .charcount = UINT_MAX, }; struct unimapinit adv = {}; struct unimapdesc unimapd; _cleanup_free_ struct unipair* unipairs = NULL; _cleanup_free_ void *fontbuf = NULL; unsigned i; int r; unipairs = new(struct unipair, USHRT_MAX); if (!unipairs) { log_oom(); return; } /* get metadata of the current font (width, height, count) */ r = ioctl(src_fd, KDFONTOP, &cfo); if (r < 0) log_warning_errno(errno, "KD_FONT_OP_GET failed while trying to get the font metadata: %m"); else { /* verify parameter sanity first */ if (cfo.width > 32 || cfo.height > 32 || cfo.charcount > 512) log_warning("Invalid font metadata - width: %u (max 32), height: %u (max 32), count: %u (max 512)", cfo.width, cfo.height, cfo.charcount); else { /* * Console fonts supported by the kernel are limited in size to 32 x 32 and maximum 512 * characters. Thus with 1 bit per pixel it requires up to 65536 bytes. The height always * requires 32 per glyph, regardless of the actual height - see the comment above #define * max_font_size 65536 in drivers/tty/vt/vt.c for more details. */ fontbuf = malloc_multiply((cfo.width + 7) / 8 * 32, cfo.charcount); if (!fontbuf) { log_oom(); return; } /* get fonts from the source console */ cfo.data = fontbuf; r = ioctl(src_fd, KDFONTOP, &cfo); if (r < 0) log_warning_errno(errno, "KD_FONT_OP_GET failed while trying to read the font data: %m"); else { unimapd.entries = unipairs; unimapd.entry_ct = USHRT_MAX; r = ioctl(src_fd, GIO_UNIMAP, &unimapd); if (r < 0) log_warning_errno(errno, "GIO_UNIMAP failed while trying to read unicode mappings: %m"); else cfo.op = KD_FONT_OP_SET; } } } if (cfo.op != KD_FONT_OP_SET) log_warning("Fonts will not be copied to remaining consoles"); for (i = 1; i <= 63; i++) { char ttyname[sizeof("/dev/tty63")]; _cleanup_close_ int fd_d = -1; if (i == src_idx || verify_vc_allocation(i) < 0) continue; /* try to open terminal */ xsprintf(ttyname, "/dev/tty%u", i); fd_d = open_terminal(ttyname, O_RDWR|O_CLOEXEC|O_NOCTTY); if (fd_d < 0) { log_warning_errno(fd_d, "Unable to open tty%u, fonts will not be copied: %m", i); continue; } if (vt_verify_kbmode(fd_d) < 0) continue; toggle_utf8(ttyname, fd_d, utf8); if (cfo.op != KD_FONT_OP_SET) continue; r = ioctl(fd_d, KDFONTOP, &cfo); if (r < 0) { int last_errno, mode; /* The fonts couldn't have been copied. It might be due to the * terminal being in graphical mode. In this case the kernel * returns -EINVAL which is too generic for distinguishing this * specific case. So we need to retrieve the terminal mode and if * the graphical mode is in used, let's assume that something else * is using the terminal and the failure was expected as we * shouldn't have tried to copy the fonts. */ last_errno = errno; if (ioctl(fd_d, KDGETMODE, &mode) >= 0 && mode != KD_TEXT) log_debug("KD_FONT_OP_SET skipped: tty%u is not in text mode", i); else log_warning_errno(last_errno, "KD_FONT_OP_SET failed, fonts will not be copied to tty%u: %m", i); continue; } /* * copy unicode translation table unimapd is a ushort count and a pointer * to an array of struct unipair { ushort, ushort } */ r = ioctl(fd_d, PIO_UNIMAPCLR, &adv); if (r < 0) { log_warning_errno(errno, "PIO_UNIMAPCLR failed, unimaps might be incorrect for tty%u: %m", i); continue; } r = ioctl(fd_d, PIO_UNIMAP, &unimapd); if (r < 0) { log_warning_errno(errno, "PIO_UNIMAP failed, unimaps might be incorrect for tty%u: %m", i); continue; } log_debug("Font and unimap successfully copied to %s", ttyname); } } static int find_source_vc(char **ret_path, unsigned *ret_idx) { _cleanup_free_ char *path = NULL; int r, err = 0; unsigned i; path = new(char, sizeof("/dev/tty63")); if (!path) return log_oom(); for (i = 1; i <= 63; i++) { _cleanup_close_ int fd = -1; r = verify_vc_allocation(i); if (r < 0) { if (!err) err = -r; continue; } sprintf(path, "/dev/tty%u", i); fd = open_terminal(path, O_RDWR|O_CLOEXEC|O_NOCTTY); if (fd < 0) { if (!err) err = -fd; continue; } r = vt_verify_kbmode(fd); if (r < 0) { if (!err) err = -r; continue; } /* all checks passed, return this one as a source console */ *ret_idx = i; *ret_path = TAKE_PTR(path); return TAKE_FD(fd); } return log_error_errno(err, "No usable source console found: %m"); } static int verify_source_vc(char **ret_path, const char *src_vc) { _cleanup_close_ int fd = -1; char *path; int r; fd = open_terminal(src_vc, O_RDWR|O_CLOEXEC|O_NOCTTY); if (fd < 0) return log_error_errno(fd, "Failed to open %s: %m", src_vc); r = verify_vc_device(fd); if (r < 0) return log_error_errno(r, "Device %s is not a virtual console: %m", src_vc); r = verify_vc_allocation_byfd(fd); if (r < 0) return log_error_errno(r, "Virtual console %s is not allocated: %m", src_vc); r = vt_verify_kbmode(fd); if (r < 0) return log_error_errno(r, "Virtual console %s is not in K_XLATE or K_UNICODE: %m", src_vc); path = strdup(src_vc); if (!path) return log_oom(); *ret_path = path; return TAKE_FD(fd); } int main(int argc, char **argv) { _cleanup_free_ char *vc = NULL, *vc_keymap = NULL, *vc_keymap_toggle = NULL, *vc_font = NULL, *vc_font_map = NULL, *vc_font_unimap = NULL; _cleanup_close_ int fd = -1; bool utf8, keyboard_ok; unsigned idx = 0; int r; log_setup_service(); umask(0022); if (argv[1]) fd = verify_source_vc(&vc, argv[1]); else fd = find_source_vc(&vc, &idx); if (fd < 0) return EXIT_FAILURE; utf8 = is_locale_utf8(); r = parse_env_file(NULL, "/etc/vconsole.conf", "KEYMAP", &vc_keymap, "KEYMAP_TOGGLE", &vc_keymap_toggle, "FONT", &vc_font, "FONT_MAP", &vc_font_map, "FONT_UNIMAP", &vc_font_unimap); if (r < 0 && r != -ENOENT) log_warning_errno(r, "Failed to read /etc/vconsole.conf: %m"); /* Let the kernel command line override /etc/vconsole.conf */ r = proc_cmdline_get_key_many( PROC_CMDLINE_STRIP_RD_PREFIX, "vconsole.keymap", &vc_keymap, "vconsole.keymap_toggle", &vc_keymap_toggle, "vconsole.font", &vc_font, "vconsole.font_map", &vc_font_map, "vconsole.font_unimap", &vc_font_unimap, /* compatibility with obsolete multiple-dot scheme */ "vconsole.keymap.toggle", &vc_keymap_toggle, "vconsole.font.map", &vc_font_map, "vconsole.font.unimap", &vc_font_unimap); if (r < 0 && r != -ENOENT) log_warning_errno(r, "Failed to read /proc/cmdline: %m"); (void) toggle_utf8_sysfs(utf8); (void) toggle_utf8(vc, fd, utf8); r = font_load_and_wait(vc, vc_font, vc_font_map, vc_font_unimap); keyboard_ok = keyboard_load_and_wait(vc, vc_keymap, vc_keymap_toggle, utf8) == 0; if (idx > 0) { if (r == 0) setup_remaining_vcs(fd, idx, utf8); else if (r == EX_OSERR) /* setfont returns EX_OSERR when ioctl(KDFONTOP/PIO_FONTX/PIO_FONTX) fails. * This might mean various things, but in particular lack of a graphical * console. Let's be generous and not treat this as an error. */ log_notice("Setting fonts failed with a \"system error\", ignoring."); else log_warning("Setting source virtual console failed, ignoring remaining ones"); } return IN_SET(r, 0, EX_OSERR) && keyboard_ok ? EXIT_SUCCESS : EXIT_FAILURE; }
./CrossVul/dataset_final_sorted/CWE-255/c/good_536_2
crossvul-cpp_data_bad_536_0
/* SPDX-License-Identifier: LGPL-2.1+ */ #include <errno.h> #include <fcntl.h> #include <limits.h> #include <linux/kd.h> #include <linux/tiocl.h> #include <linux/vt.h> #include <poll.h> #include <signal.h> #include <stdarg.h> #include <stddef.h> #include <stdlib.h> #include <string.h> #include <sys/inotify.h> #include <sys/ioctl.h> #include <sys/socket.h> #include <sys/sysmacros.h> #include <sys/time.h> #include <sys/types.h> #include <sys/utsname.h> #include <termios.h> #include <unistd.h> #include "alloc-util.h" #include "copy.h" #include "def.h" #include "env-util.h" #include "fd-util.h" #include "fileio.h" #include "fs-util.h" #include "io-util.h" #include "log.h" #include "macro.h" #include "namespace-util.h" #include "parse-util.h" #include "path-util.h" #include "proc-cmdline.h" #include "process-util.h" #include "socket-util.h" #include "stat-util.h" #include "string-util.h" #include "strv.h" #include "terminal-util.h" #include "time-util.h" #include "util.h" static volatile unsigned cached_columns = 0; static volatile unsigned cached_lines = 0; static volatile int cached_on_tty = -1; static volatile int cached_colors_enabled = -1; static volatile int cached_underline_enabled = -1; int chvt(int vt) { _cleanup_close_ int fd; /* Switch to the specified vt number. If the VT is specified <= 0 switch to the VT the kernel log messages go, * if that's configured. */ fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK); if (fd < 0) return -errno; if (vt <= 0) { int tiocl[2] = { TIOCL_GETKMSGREDIRECT, 0 }; if (ioctl(fd, TIOCLINUX, tiocl) < 0) return -errno; vt = tiocl[0] <= 0 ? 1 : tiocl[0]; } if (ioctl(fd, VT_ACTIVATE, vt) < 0) return -errno; return 0; } int read_one_char(FILE *f, char *ret, usec_t t, bool *need_nl) { _cleanup_free_ char *line = NULL; struct termios old_termios; int r; assert(f); assert(ret); /* If this is a terminal, then switch canonical mode off, so that we can read a single character */ if (tcgetattr(fileno(f), &old_termios) >= 0) { struct termios new_termios = old_termios; new_termios.c_lflag &= ~ICANON; new_termios.c_cc[VMIN] = 1; new_termios.c_cc[VTIME] = 0; if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) { char c; if (t != USEC_INFINITY) { if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0) { (void) tcsetattr(fileno(f), TCSADRAIN, &old_termios); return -ETIMEDOUT; } } r = safe_fgetc(f, &c); (void) tcsetattr(fileno(f), TCSADRAIN, &old_termios); if (r < 0) return r; if (r == 0) return -EIO; if (need_nl) *need_nl = c != '\n'; *ret = c; return 0; } } if (t != USEC_INFINITY) { if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0) return -ETIMEDOUT; } /* If this is not a terminal, then read a full line instead */ r = read_line(f, 16, &line); /* longer than necessary, to eat up UTF-8 chars/vt100 key sequences */ if (r < 0) return r; if (r == 0) return -EIO; if (strlen(line) != 1) return -EBADMSG; if (need_nl) *need_nl = false; *ret = line[0]; return 0; } #define DEFAULT_ASK_REFRESH_USEC (2*USEC_PER_SEC) int ask_char(char *ret, const char *replies, const char *fmt, ...) { int r; assert(ret); assert(replies); assert(fmt); for (;;) { va_list ap; char c; bool need_nl = true; if (colors_enabled()) fputs(ANSI_HIGHLIGHT, stdout); putchar('\r'); va_start(ap, fmt); vprintf(fmt, ap); va_end(ap); if (colors_enabled()) fputs(ANSI_NORMAL, stdout); fflush(stdout); r = read_one_char(stdin, &c, DEFAULT_ASK_REFRESH_USEC, &need_nl); if (r < 0) { if (r == -ETIMEDOUT) continue; if (r == -EBADMSG) { puts("Bad input, please try again."); continue; } putchar('\n'); return r; } if (need_nl) putchar('\n'); if (strchr(replies, c)) { *ret = c; return 0; } puts("Read unexpected character, please try again."); } } int ask_string(char **ret, const char *text, ...) { int r; assert(ret); assert(text); for (;;) { _cleanup_free_ char *line = NULL; va_list ap; if (colors_enabled()) fputs(ANSI_HIGHLIGHT, stdout); va_start(ap, text); vprintf(text, ap); va_end(ap); if (colors_enabled()) fputs(ANSI_NORMAL, stdout); fflush(stdout); r = read_line(stdin, LONG_LINE_MAX, &line); if (r < 0) return r; if (r == 0) return -EIO; if (!isempty(line)) { *ret = TAKE_PTR(line); return 0; } } } int reset_terminal_fd(int fd, bool switch_to_text) { struct termios termios; int r = 0; /* Set terminal to some sane defaults */ assert(fd >= 0); /* We leave locked terminal attributes untouched, so that * Plymouth may set whatever it wants to set, and we don't * interfere with that. */ /* Disable exclusive mode, just in case */ (void) ioctl(fd, TIOCNXCL); /* Switch to text mode */ if (switch_to_text) (void) ioctl(fd, KDSETMODE, KD_TEXT); /* Set default keyboard mode */ (void) vt_reset_keyboard(fd); if (tcgetattr(fd, &termios) < 0) { r = -errno; goto finish; } /* We only reset the stuff that matters to the software. How * hardware is set up we don't touch assuming that somebody * else will do that for us */ termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC); termios.c_iflag |= ICRNL | IMAXBEL | IUTF8; termios.c_oflag |= ONLCR; termios.c_cflag |= CREAD; termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE; termios.c_cc[VINTR] = 03; /* ^C */ termios.c_cc[VQUIT] = 034; /* ^\ */ termios.c_cc[VERASE] = 0177; termios.c_cc[VKILL] = 025; /* ^X */ termios.c_cc[VEOF] = 04; /* ^D */ termios.c_cc[VSTART] = 021; /* ^Q */ termios.c_cc[VSTOP] = 023; /* ^S */ termios.c_cc[VSUSP] = 032; /* ^Z */ termios.c_cc[VLNEXT] = 026; /* ^V */ termios.c_cc[VWERASE] = 027; /* ^W */ termios.c_cc[VREPRINT] = 022; /* ^R */ termios.c_cc[VEOL] = 0; termios.c_cc[VEOL2] = 0; termios.c_cc[VTIME] = 0; termios.c_cc[VMIN] = 1; if (tcsetattr(fd, TCSANOW, &termios) < 0) r = -errno; finish: /* Just in case, flush all crap out */ (void) tcflush(fd, TCIOFLUSH); return r; } int reset_terminal(const char *name) { _cleanup_close_ int fd = -1; /* We open the terminal with O_NONBLOCK here, to ensure we * don't block on carrier if this is a terminal with carrier * configured. */ fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK); if (fd < 0) return fd; return reset_terminal_fd(fd, true); } int open_terminal(const char *name, int mode) { unsigned c = 0; int fd; /* * If a TTY is in the process of being closed opening it might * cause EIO. This is horribly awful, but unlikely to be * changed in the kernel. Hence we work around this problem by * retrying a couple of times. * * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245 */ if (mode & O_CREAT) return -EINVAL; for (;;) { fd = open(name, mode, 0); if (fd >= 0) break; if (errno != EIO) return -errno; /* Max 1s in total */ if (c >= 20) return -errno; usleep(50 * USEC_PER_MSEC); c++; } if (isatty(fd) <= 0) { safe_close(fd); return -ENOTTY; } return fd; } int acquire_terminal( const char *name, AcquireTerminalFlags flags, usec_t timeout) { _cleanup_close_ int notify = -1, fd = -1; usec_t ts = USEC_INFINITY; int r, wd = -1; assert(name); assert(IN_SET(flags & ~ACQUIRE_TERMINAL_PERMISSIVE, ACQUIRE_TERMINAL_TRY, ACQUIRE_TERMINAL_FORCE, ACQUIRE_TERMINAL_WAIT)); /* We use inotify to be notified when the tty is closed. We create the watch before checking if we can actually * acquire it, so that we don't lose any event. * * Note: strictly speaking this actually watches for the device being closed, it does *not* really watch * whether a tty loses its controlling process. However, unless some rogue process uses TIOCNOTTY on /dev/tty * *after* closing its tty otherwise this will not become a problem. As long as the administrator makes sure to * not configure any service on the same tty as an untrusted user this should not be a problem. (Which they * probably should not do anyway.) */ if ((flags & ~ACQUIRE_TERMINAL_PERMISSIVE) == ACQUIRE_TERMINAL_WAIT) { notify = inotify_init1(IN_CLOEXEC | (timeout != USEC_INFINITY ? IN_NONBLOCK : 0)); if (notify < 0) return -errno; wd = inotify_add_watch(notify, name, IN_CLOSE); if (wd < 0) return -errno; if (timeout != USEC_INFINITY) ts = now(CLOCK_MONOTONIC); } for (;;) { struct sigaction sa_old, sa_new = { .sa_handler = SIG_IGN, .sa_flags = SA_RESTART, }; if (notify >= 0) { r = flush_fd(notify); if (r < 0) return r; } /* We pass here O_NOCTTY only so that we can check the return value TIOCSCTTY and have a reliable way * to figure out if we successfully became the controlling process of the tty */ fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC); if (fd < 0) return fd; /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed if we already own the tty. */ assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0); /* First, try to get the tty */ r = ioctl(fd, TIOCSCTTY, (flags & ~ACQUIRE_TERMINAL_PERMISSIVE) == ACQUIRE_TERMINAL_FORCE) < 0 ? -errno : 0; /* Reset signal handler to old value */ assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0); /* Success? Exit the loop now! */ if (r >= 0) break; /* Any failure besides -EPERM? Fail, regardless of the mode. */ if (r != -EPERM) return r; if (flags & ACQUIRE_TERMINAL_PERMISSIVE) /* If we are in permissive mode, then EPERM is fine, turn this * into a success. Note that EPERM is also returned if we * already are the owner of the TTY. */ break; if (flags != ACQUIRE_TERMINAL_WAIT) /* If we are in TRY or FORCE mode, then propagate EPERM as EPERM */ return r; assert(notify >= 0); assert(wd >= 0); for (;;) { union inotify_event_buffer buffer; struct inotify_event *e; ssize_t l; if (timeout != USEC_INFINITY) { usec_t n; assert(ts != USEC_INFINITY); n = now(CLOCK_MONOTONIC); if (ts + timeout < n) return -ETIMEDOUT; r = fd_wait_for_event(notify, POLLIN, ts + timeout - n); if (r < 0) return r; if (r == 0) return -ETIMEDOUT; } l = read(notify, &buffer, sizeof(buffer)); if (l < 0) { if (IN_SET(errno, EINTR, EAGAIN)) continue; return -errno; } FOREACH_INOTIFY_EVENT(e, buffer, l) { if (e->mask & IN_Q_OVERFLOW) /* If we hit an inotify queue overflow, simply check if the terminal is up for grabs now. */ break; if (e->wd != wd || !(e->mask & IN_CLOSE)) /* Safety checks */ return -EIO; } break; } /* We close the tty fd here since if the old session ended our handle will be dead. It's important that * we do this after sleeping, so that we don't enter an endless loop. */ fd = safe_close(fd); } return TAKE_FD(fd); } int release_terminal(void) { static const struct sigaction sa_new = { .sa_handler = SIG_IGN, .sa_flags = SA_RESTART, }; _cleanup_close_ int fd = -1; struct sigaction sa_old; int r; fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK); if (fd < 0) return -errno; /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed * by our own TIOCNOTTY */ assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0); r = ioctl(fd, TIOCNOTTY) < 0 ? -errno : 0; assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0); return r; } int terminal_vhangup_fd(int fd) { assert(fd >= 0); if (ioctl(fd, TIOCVHANGUP) < 0) return -errno; return 0; } int terminal_vhangup(const char *name) { _cleanup_close_ int fd; fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK); if (fd < 0) return fd; return terminal_vhangup_fd(fd); } int vt_disallocate(const char *name) { _cleanup_close_ int fd = -1; const char *e, *n; unsigned u; int r; /* Deallocate the VT if possible. If not possible * (i.e. because it is the active one), at least clear it * entirely (including the scrollback buffer) */ e = path_startswith(name, "/dev/"); if (!e) return -EINVAL; if (!tty_is_vc(name)) { /* So this is not a VT. I guess we cannot deallocate * it then. But let's at least clear the screen */ fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC); if (fd < 0) return fd; loop_write(fd, "\033[r" /* clear scrolling region */ "\033[H" /* move home */ "\033[2J", /* clear screen */ 10, false); return 0; } n = startswith(e, "tty"); if (!n) return -EINVAL; r = safe_atou(n, &u); if (r < 0) return r; if (u <= 0) return -EINVAL; /* Try to deallocate */ fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK); if (fd < 0) return fd; r = ioctl(fd, VT_DISALLOCATE, u); fd = safe_close(fd); if (r >= 0) return 0; if (errno != EBUSY) return -errno; /* Couldn't deallocate, so let's clear it fully with * scrollback */ fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC); if (fd < 0) return fd; loop_write(fd, "\033[r" /* clear scrolling region */ "\033[H" /* move home */ "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */ 10, false); return 0; } int make_console_stdio(void) { int fd, r; /* Make /dev/console the controlling terminal and stdin/stdout/stderr */ fd = acquire_terminal("/dev/console", ACQUIRE_TERMINAL_FORCE|ACQUIRE_TERMINAL_PERMISSIVE, USEC_INFINITY); if (fd < 0) return log_error_errno(fd, "Failed to acquire terminal: %m"); r = reset_terminal_fd(fd, true); if (r < 0) log_warning_errno(r, "Failed to reset terminal, ignoring: %m"); r = rearrange_stdio(fd, fd, fd); /* This invalidates 'fd' both on success and on failure. */ if (r < 0) return log_error_errno(r, "Failed to make terminal stdin/stdout/stderr: %m"); reset_terminal_feature_caches(); return 0; } bool tty_is_vc(const char *tty) { assert(tty); return vtnr_from_tty(tty) >= 0; } bool tty_is_console(const char *tty) { assert(tty); return streq(skip_dev_prefix(tty), "console"); } int vtnr_from_tty(const char *tty) { int i, r; assert(tty); tty = skip_dev_prefix(tty); if (!startswith(tty, "tty") ) return -EINVAL; if (tty[3] < '0' || tty[3] > '9') return -EINVAL; r = safe_atoi(tty+3, &i); if (r < 0) return r; if (i < 0 || i > 63) return -EINVAL; return i; } int resolve_dev_console(char **ret) { _cleanup_free_ char *active = NULL; char *tty; int r; assert(ret); /* Resolve where /dev/console is pointing to, if /sys is actually ours (i.e. not read-only-mounted which is a * sign for container setups) */ if (path_is_read_only_fs("/sys") > 0) return -ENOMEDIUM; r = read_one_line_file("/sys/class/tty/console/active", &active); if (r < 0) return r; /* If multiple log outputs are configured the last one is what /dev/console points to */ tty = strrchr(active, ' '); if (tty) tty++; else tty = active; if (streq(tty, "tty0")) { active = mfree(active); /* Get the active VC (e.g. tty1) */ r = read_one_line_file("/sys/class/tty/tty0/active", &active); if (r < 0) return r; tty = active; } if (tty == active) *ret = TAKE_PTR(active); else { char *tmp; tmp = strdup(tty); if (!tmp) return -ENOMEM; *ret = tmp; } return 0; } int get_kernel_consoles(char ***ret) { _cleanup_strv_free_ char **l = NULL; _cleanup_free_ char *line = NULL; const char *p; int r; assert(ret); /* If /sys is mounted read-only this means we are running in some kind of container environment. In that * case /sys would reflect the host system, not us, hence ignore the data we can read from it. */ if (path_is_read_only_fs("/sys") > 0) goto fallback; r = read_one_line_file("/sys/class/tty/console/active", &line); if (r < 0) return r; p = line; for (;;) { _cleanup_free_ char *tty = NULL; char *path; r = extract_first_word(&p, &tty, NULL, 0); if (r < 0) return r; if (r == 0) break; if (streq(tty, "tty0")) { tty = mfree(tty); r = read_one_line_file("/sys/class/tty/tty0/active", &tty); if (r < 0) return r; } path = strappend("/dev/", tty); if (!path) return -ENOMEM; if (access(path, F_OK) < 0) { log_debug_errno(errno, "Console device %s is not accessible, skipping: %m", path); free(path); continue; } r = strv_consume(&l, path); if (r < 0) return r; } if (strv_isempty(l)) { log_debug("No devices found for system console"); goto fallback; } *ret = TAKE_PTR(l); return 0; fallback: r = strv_extend(&l, "/dev/console"); if (r < 0) return r; *ret = TAKE_PTR(l); return 0; } bool tty_is_vc_resolve(const char *tty) { _cleanup_free_ char *resolved = NULL; assert(tty); tty = skip_dev_prefix(tty); if (streq(tty, "console")) { if (resolve_dev_console(&resolved) < 0) return false; tty = resolved; } return tty_is_vc(tty); } const char *default_term_for_tty(const char *tty) { return tty && tty_is_vc_resolve(tty) ? "linux" : "vt220"; } int fd_columns(int fd) { struct winsize ws = {}; if (ioctl(fd, TIOCGWINSZ, &ws) < 0) return -errno; if (ws.ws_col <= 0) return -EIO; return ws.ws_col; } unsigned columns(void) { const char *e; int c; if (cached_columns > 0) return cached_columns; c = 0; e = getenv("COLUMNS"); if (e) (void) safe_atoi(e, &c); if (c <= 0 || c > USHRT_MAX) { c = fd_columns(STDOUT_FILENO); if (c <= 0) c = 80; } cached_columns = c; return cached_columns; } int fd_lines(int fd) { struct winsize ws = {}; if (ioctl(fd, TIOCGWINSZ, &ws) < 0) return -errno; if (ws.ws_row <= 0) return -EIO; return ws.ws_row; } unsigned lines(void) { const char *e; int l; if (cached_lines > 0) return cached_lines; l = 0; e = getenv("LINES"); if (e) (void) safe_atoi(e, &l); if (l <= 0 || l > USHRT_MAX) { l = fd_lines(STDOUT_FILENO); if (l <= 0) l = 24; } cached_lines = l; return cached_lines; } /* intended to be used as a SIGWINCH sighandler */ void columns_lines_cache_reset(int signum) { cached_columns = 0; cached_lines = 0; } void reset_terminal_feature_caches(void) { cached_columns = 0; cached_lines = 0; cached_colors_enabled = -1; cached_underline_enabled = -1; cached_on_tty = -1; } bool on_tty(void) { /* We check both stdout and stderr, so that situations where pipes on the shell are used are reliably * recognized, regardless if only the output or the errors are piped to some place. Since on_tty() is generally * used to default to a safer, non-interactive, non-color mode of operation it's probably good to be defensive * here, and check for both. Note that we don't check for STDIN_FILENO, because it should fine to use fancy * terminal functionality when outputting stuff, even if the input is piped to us. */ if (cached_on_tty < 0) cached_on_tty = isatty(STDOUT_FILENO) > 0 && isatty(STDERR_FILENO) > 0; return cached_on_tty; } int getttyname_malloc(int fd, char **ret) { char path[PATH_MAX], *c; /* PATH_MAX is counted *with* the trailing NUL byte */ int r; assert(fd >= 0); assert(ret); r = ttyname_r(fd, path, sizeof path); /* positive error */ assert(r >= 0); if (r == ERANGE) return -ENAMETOOLONG; if (r > 0) return -r; c = strdup(skip_dev_prefix(path)); if (!c) return -ENOMEM; *ret = c; return 0; } int getttyname_harder(int fd, char **ret) { _cleanup_free_ char *s = NULL; int r; r = getttyname_malloc(fd, &s); if (r < 0) return r; if (streq(s, "tty")) return get_ctty(0, NULL, ret); *ret = TAKE_PTR(s); return 0; } int get_ctty_devnr(pid_t pid, dev_t *d) { int r; _cleanup_free_ char *line = NULL; const char *p; unsigned long ttynr; assert(pid >= 0); p = procfs_file_alloca(pid, "stat"); r = read_one_line_file(p, &line); if (r < 0) return r; p = strrchr(line, ')'); if (!p) return -EIO; p++; if (sscanf(p, " " "%*c " /* state */ "%*d " /* ppid */ "%*d " /* pgrp */ "%*d " /* session */ "%lu ", /* ttynr */ &ttynr) != 1) return -EIO; if (major(ttynr) == 0 && minor(ttynr) == 0) return -ENXIO; if (d) *d = (dev_t) ttynr; return 0; } int get_ctty(pid_t pid, dev_t *ret_devnr, char **ret) { _cleanup_free_ char *fn = NULL, *b = NULL; dev_t devnr; int r; r = get_ctty_devnr(pid, &devnr); if (r < 0) return r; r = device_path_make_canonical(S_IFCHR, devnr, &fn); if (r < 0) { if (r != -ENOENT) /* No symlink for this in /dev/char/? */ return r; if (major(devnr) == 136) { /* This is an ugly hack: PTY devices are not listed in /dev/char/, as they don't follow the * Linux device model. This means we have no nice way to match them up against their actual * device node. Let's hence do the check by the fixed, assigned major number. Normally we try * to avoid such fixed major/minor matches, but there appears to nother nice way to handle * this. */ if (asprintf(&b, "pts/%u", minor(devnr)) < 0) return -ENOMEM; } else { /* Probably something similar to the ptys which have no symlink in /dev/char/. Let's return * something vaguely useful. */ r = device_path_make_major_minor(S_IFCHR, devnr, &fn); if (r < 0) return r; } } if (!b) { const char *w; w = path_startswith(fn, "/dev/"); if (w) { b = strdup(w); if (!b) return -ENOMEM; } else b = TAKE_PTR(fn); } if (ret) *ret = TAKE_PTR(b); if (ret_devnr) *ret_devnr = devnr; return 0; } int ptsname_malloc(int fd, char **ret) { size_t l = 100; assert(fd >= 0); assert(ret); for (;;) { char *c; c = new(char, l); if (!c) return -ENOMEM; if (ptsname_r(fd, c, l) == 0) { *ret = c; return 0; } if (errno != ERANGE) { free(c); return -errno; } free(c); if (l > SIZE_MAX / 2) return -ENOMEM; l *= 2; } } int ptsname_namespace(int pty, char **ret) { int no = -1, r; /* Like ptsname(), but doesn't assume that the path is * accessible in the local namespace. */ r = ioctl(pty, TIOCGPTN, &no); if (r < 0) return -errno; if (no < 0) return -EIO; if (asprintf(ret, "/dev/pts/%i", no) < 0) return -ENOMEM; return 0; } int openpt_in_namespace(pid_t pid, int flags) { _cleanup_close_ int pidnsfd = -1, mntnsfd = -1, usernsfd = -1, rootfd = -1; _cleanup_close_pair_ int pair[2] = { -1, -1 }; pid_t child; int r; assert(pid > 0); r = namespace_open(pid, &pidnsfd, &mntnsfd, NULL, &usernsfd, &rootfd); if (r < 0) return r; if (socketpair(AF_UNIX, SOCK_DGRAM, 0, pair) < 0) return -errno; r = namespace_fork("(sd-openptns)", "(sd-openpt)", NULL, 0, FORK_RESET_SIGNALS|FORK_DEATHSIG, pidnsfd, mntnsfd, -1, usernsfd, rootfd, &child); if (r < 0) return r; if (r == 0) { int master; pair[0] = safe_close(pair[0]); master = posix_openpt(flags|O_NOCTTY|O_CLOEXEC); if (master < 0) _exit(EXIT_FAILURE); if (unlockpt(master) < 0) _exit(EXIT_FAILURE); if (send_one_fd(pair[1], master, 0) < 0) _exit(EXIT_FAILURE); _exit(EXIT_SUCCESS); } pair[1] = safe_close(pair[1]); r = wait_for_terminate_and_check("(sd-openptns)", child, 0); if (r < 0) return r; if (r != EXIT_SUCCESS) return -EIO; return receive_one_fd(pair[0], 0); } int open_terminal_in_namespace(pid_t pid, const char *name, int mode) { _cleanup_close_ int pidnsfd = -1, mntnsfd = -1, usernsfd = -1, rootfd = -1; _cleanup_close_pair_ int pair[2] = { -1, -1 }; pid_t child; int r; r = namespace_open(pid, &pidnsfd, &mntnsfd, NULL, &usernsfd, &rootfd); if (r < 0) return r; if (socketpair(AF_UNIX, SOCK_DGRAM, 0, pair) < 0) return -errno; r = namespace_fork("(sd-terminalns)", "(sd-terminal)", NULL, 0, FORK_RESET_SIGNALS|FORK_DEATHSIG, pidnsfd, mntnsfd, -1, usernsfd, rootfd, &child); if (r < 0) return r; if (r == 0) { int master; pair[0] = safe_close(pair[0]); master = open_terminal(name, mode|O_NOCTTY|O_CLOEXEC); if (master < 0) _exit(EXIT_FAILURE); if (send_one_fd(pair[1], master, 0) < 0) _exit(EXIT_FAILURE); _exit(EXIT_SUCCESS); } pair[1] = safe_close(pair[1]); r = wait_for_terminate_and_check("(sd-terminalns)", child, 0); if (r < 0) return r; if (r != EXIT_SUCCESS) return -EIO; return receive_one_fd(pair[0], 0); } static bool getenv_terminal_is_dumb(void) { const char *e; e = getenv("TERM"); if (!e) return true; return streq(e, "dumb"); } bool terminal_is_dumb(void) { if (!on_tty()) return true; return getenv_terminal_is_dumb(); } bool colors_enabled(void) { /* Returns true if colors are considered supported on our stdout. For that we check $SYSTEMD_COLORS first * (which is the explicit way to turn colors on/off). If that didn't work we turn colors off unless we are on a * TTY. And if we are on a TTY we turn it off if $TERM is set to "dumb". There's one special tweak though: if * we are PID 1 then we do not check whether we are connected to a TTY, because we don't keep /dev/console open * continuously due to fear of SAK, and hence things are a bit weird. */ if (cached_colors_enabled < 0) { int val; val = getenv_bool("SYSTEMD_COLORS"); if (val >= 0) cached_colors_enabled = val; else if (getpid_cached() == 1) /* PID1 outputs to the console without holding it open all the time */ cached_colors_enabled = !getenv_terminal_is_dumb(); else cached_colors_enabled = !terminal_is_dumb(); } return cached_colors_enabled; } bool dev_console_colors_enabled(void) { _cleanup_free_ char *s = NULL; int b; /* Returns true if we assume that color is supported on /dev/console. * * For that we first check if we explicitly got told to use colors or not, by checking $SYSTEMD_COLORS. If that * isn't set we check whether PID 1 has $TERM set, and if not, whether TERM is set on the kernel command * line. If we find $TERM set we assume color if it's not set to "dumb", similarly to how regular * colors_enabled() operates. */ b = getenv_bool("SYSTEMD_COLORS"); if (b >= 0) return b; if (getenv_for_pid(1, "TERM", &s) <= 0) (void) proc_cmdline_get_key("TERM", 0, &s); return !streq_ptr(s, "dumb"); } bool underline_enabled(void) { if (cached_underline_enabled < 0) { /* The Linux console doesn't support underlining, turn it off, but only there. */ if (colors_enabled()) cached_underline_enabled = !streq_ptr(getenv("TERM"), "linux"); else cached_underline_enabled = false; } return cached_underline_enabled; } int vt_default_utf8(void) { _cleanup_free_ char *b = NULL; int r; /* Read the default VT UTF8 setting from the kernel */ r = read_one_line_file("/sys/module/vt/parameters/default_utf8", &b); if (r < 0) return r; return parse_boolean(b); } int vt_reset_keyboard(int fd) { int kb; /* If we can't read the default, then default to unicode. It's 2017 after all. */ kb = vt_default_utf8() != 0 ? K_UNICODE : K_XLATE; if (ioctl(fd, KDSKBMODE, kb) < 0) return -errno; return 0; } int vt_restore(int fd) { static const struct vt_mode mode = { .mode = VT_AUTO, }; int r, q = 0; r = ioctl(fd, KDSETMODE, KD_TEXT); if (r < 0) q = log_debug_errno(errno, "Failed to set VT in text mode, ignoring: %m"); r = vt_reset_keyboard(fd); if (r < 0) { log_debug_errno(r, "Failed to reset keyboard mode, ignoring: %m"); if (q >= 0) q = r; } r = ioctl(fd, VT_SETMODE, &mode); if (r < 0) { log_debug_errno(errno, "Failed to set VT_AUTO mode, ignoring: %m"); if (q >= 0) q = -errno; } r = fchown(fd, 0, (gid_t) -1); if (r < 0) { log_debug_errno(errno, "Failed to chown VT, ignoring: %m"); if (q >= 0) q = -errno; } return q; } int vt_release(int fd, bool restore) { assert(fd >= 0); /* This function releases the VT by acknowledging the VT-switch signal * sent by the kernel and optionally reset the VT in text and auto * VT-switching modes. */ if (ioctl(fd, VT_RELDISP, 1) < 0) return -errno; if (restore) return vt_restore(fd); return 0; } void get_log_colors(int priority, const char **on, const char **off, const char **highlight) { /* Note that this will initialize output variables only when there's something to output. * The caller must pre-initalize to "" or NULL as appropriate. */ if (priority <= LOG_ERR) { if (on) *on = ANSI_HIGHLIGHT_RED; if (off) *off = ANSI_NORMAL; if (highlight) *highlight = ANSI_HIGHLIGHT; } else if (priority <= LOG_WARNING) { if (on) *on = ANSI_HIGHLIGHT_YELLOW; if (off) *off = ANSI_NORMAL; if (highlight) *highlight = ANSI_HIGHLIGHT; } else if (priority <= LOG_NOTICE) { if (on) *on = ANSI_HIGHLIGHT; if (off) *off = ANSI_NORMAL; if (highlight) *highlight = ANSI_HIGHLIGHT_RED; } else if (priority >= LOG_DEBUG) { if (on) *on = ANSI_GREY; if (off) *off = ANSI_NORMAL; if (highlight) *highlight = ANSI_HIGHLIGHT_RED; } }
./CrossVul/dataset_final_sorted/CWE-255/c/bad_536_0
crossvul-cpp_data_good_3557_0
/* * rlm_unix.c authentication: Unix user authentication * accounting: Functions to write radwtmp file. * Also contains handler for "Group". * * Version: $Id$ * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA * * Copyright 2000,2006 The FreeRADIUS server project * Copyright 2000 Jeff Carneal <jeff@apex.net> * Copyright 2000 Alan Curry <pacman@world.std.com> */ #include <freeradius-devel/ident.h> RCSID("$Id$") #include <freeradius-devel/radiusd.h> #include <grp.h> #include <pwd.h> #include <sys/stat.h> #include "config.h" #ifdef HAVE_SHADOW_H # include <shadow.h> #endif #ifdef OSFC2 # include <sys/security.h> # include <prot.h> #endif #ifdef OSFSIA # include <sia.h> # include <siad.h> #endif #include <freeradius-devel/modules.h> #include <freeradius-devel/sysutmp.h> static char trans[64] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; #define ENC(c) trans[c] struct unix_instance { const char *radwtmp; }; static const CONF_PARSER module_config[] = { { "radwtmp", PW_TYPE_STRING_PTR, offsetof(struct unix_instance,radwtmp), NULL, "NULL" }, { NULL, -1, 0, NULL, NULL } /* end the list */ }; /* * The Group = handler. */ static int groupcmp(void *instance, REQUEST *req, UNUSED VALUE_PAIR *request, VALUE_PAIR *check, VALUE_PAIR *check_pairs, VALUE_PAIR **reply_pairs) { struct passwd *pwd; struct group *grp; char **member; int retval; instance = instance; check_pairs = check_pairs; reply_pairs = reply_pairs; /* * No user name, doesn't compare. */ if (!req->username) { return -1; } pwd = getpwnam(req->username->vp_strvalue); if (pwd == NULL) return -1; grp = getgrnam(check->vp_strvalue); if (grp == NULL) return -1; retval = (pwd->pw_gid == grp->gr_gid) ? 0 : -1; if (retval < 0) { for (member = grp->gr_mem; *member && retval; member++) { if (strcmp(*member, pwd->pw_name) == 0) retval = 0; } } return retval; } /* * Detach. */ static int unix_detach(void *instance) { #define inst ((struct unix_instance *)instance) paircompare_unregister(PW_GROUP, groupcmp); #ifdef PW_GROUP_NAME paircompare_unregister(PW_GROUP_NAME, groupcmp); #endif #undef inst free(instance); return 0; } /* * Read the config */ static int unix_instantiate(CONF_SECTION *conf, void **instance) { struct unix_instance *inst; /* * Allocate room for the instance. */ inst = *instance = rad_malloc(sizeof(*inst)); if (!inst) { return -1; } memset(inst, 0, sizeof(*inst)); /* * Parse the configuration, failing if we can't do so. */ if (cf_section_parse(conf, inst, module_config) < 0) { unix_detach(inst); return -1; } /* FIXME - delay these until a group file has been read so we know * groupcmp can actually do something */ paircompare_register(PW_GROUP, PW_USER_NAME, groupcmp, NULL); #ifdef PW_GROUP_NAME /* compat */ paircompare_register(PW_GROUP_NAME, PW_USER_NAME, groupcmp, NULL); #endif #undef inst return 0; } /* * Pull the users password from where-ever, and add it to * the given vp list. */ static int unix_getpw(UNUSED void *instance, REQUEST *request, VALUE_PAIR **vp_list) { const char *name; const char *encrypted_pass; #ifdef HAVE_GETSPNAM struct spwd *spwd = NULL; #endif #ifdef OSFC2 struct pr_passwd *pr_pw; #else struct passwd *pwd; #endif #ifdef HAVE_GETUSERSHELL char *shell; #endif VALUE_PAIR *vp; /* * We can only authenticate user requests which HAVE * a User-Name attribute. */ if (!request->username) { return RLM_MODULE_NOOP; } name = (char *)request->username->vp_strvalue; encrypted_pass = NULL; #ifdef OSFC2 if ((pr_pw = getprpwnam(name)) == NULL) return RLM_MODULE_NOTFOUND; encrypted_pass = pr_pw->ufld.fd_encrypt; /* * Check if account is locked. */ if (pr_pw->uflg.fg_lock!=1) { radlog(L_AUTH, "rlm_unix: [%s]: account locked", name); return RLM_MODULE_USERLOCK; } #else /* OSFC2 */ if ((pwd = getpwnam(name)) == NULL) { return RLM_MODULE_NOTFOUND; } encrypted_pass = pwd->pw_passwd; #endif /* OSFC2 */ #ifdef HAVE_GETSPNAM /* * See if there is a shadow password. * * Only query the _system_ shadow file if the encrypted * password from the passwd file is < 10 characters (i.e. * a valid password would never crypt() to it). This will * prevents users from using NULL password fields as things * stand right now. */ if ((encrypted_pass == NULL) || (strlen(encrypted_pass) < 10)) { if ((spwd = getspnam(name)) == NULL) { return RLM_MODULE_NOTFOUND; } encrypted_pass = spwd->sp_pwdp; } #endif /* HAVE_GETSPNAM */ /* * These require 'pwd != NULL', which isn't true on OSFC2 */ #ifndef OSFC2 #ifdef DENY_SHELL /* * Users with a particular shell are denied access */ if (strcmp(pwd->pw_shell, DENY_SHELL) == 0) { radlog_request(L_AUTH, 0, request, "rlm_unix: [%s]: invalid shell", name); return RLM_MODULE_REJECT; } #endif #ifdef HAVE_GETUSERSHELL /* * Check /etc/shells for a valid shell. If that file * contains /RADIUSD/ANY/SHELL then any shell will do. */ while ((shell = getusershell()) != NULL) { if (strcmp(shell, pwd->pw_shell) == 0 || strcmp(shell, "/RADIUSD/ANY/SHELL") == 0) { break; } } endusershell(); if (shell == NULL) { radlog_request(L_AUTH, 0, request, "[%s]: invalid shell [%s]", name, pwd->pw_shell); return RLM_MODULE_REJECT; } #endif #endif /* OSFC2 */ #if defined(HAVE_GETSPNAM) && !defined(M_UNIX) /* * Check if password has expired. */ if (spwd && spwd->sp_lstchg > 0 && spwd->sp_max >= 0 && (request->timestamp / 86400) > (spwd->sp_lstchg + spwd->sp_max)) { radlog_request(L_AUTH, 0, request, "[%s]: password has expired", name); return RLM_MODULE_REJECT; } /* * Check if account has expired. */ if (spwd && spwd->sp_expire > 0 && (request->timestamp / 86400) > spwd->sp_expire) { radlog_request(L_AUTH, 0, request, "[%s]: account has expired", name); return RLM_MODULE_REJECT; } #endif #if defined(__FreeBSD__) || defined(bsdi) || defined(_PWF_EXPIRE) /* * Check if password has expired. */ if ((pwd->pw_expire > 0) && (request->timestamp > pwd->pw_expire)) { radlog_request(L_AUTH, 0, request, "[%s]: password has expired", name); return RLM_MODULE_REJECT; } #endif /* * We might have a passwordless account. * * FIXME: Maybe add Auth-Type := Accept? */ if (encrypted_pass[0] == 0) return RLM_MODULE_NOOP; vp = pairmake("Crypt-Password", encrypted_pass, T_OP_SET); if (!vp) return RLM_MODULE_FAIL; pairmove(vp_list, &vp); pairfree(&vp); /* might not be NULL; */ return RLM_MODULE_UPDATED; } /* * Pull the users password from where-ever, and add it to * the given vp list. */ static int unix_authorize(void *instance, REQUEST *request) { return unix_getpw(instance, request, &request->config_items); } /* * Pull the users password from where-ever, and add it to * the given vp list. */ static int unix_authenticate(void *instance, REQUEST *request) { #ifdef OSFSIA char *info[2]; char *progname = "radius"; SIAENTITY *ent = NULL; info[0] = progname; info[1] = NULL; if (sia_ses_init (&ent, 1, info, NULL, name, NULL, 0, NULL) != SIASUCCESS) return RLM_MODULE_NOTFOUND; if ((ret = sia_ses_authent (NULL, passwd, ent)) != SIASUCCESS) { if (ret & SIASTOP) sia_ses_release (&ent); return RLM_MODULE_NOTFOUND; } if (sia_ses_estab (NULL, ent) != SIASUCCESS) { sia_ses_release (&ent); return RLM_MODULE_NOTFOUND; } #else /* OSFSIA */ int rcode; VALUE_PAIR *vp = NULL; if (!request->password || (request->password->attribute != PW_USER_PASSWORD)) { radlog_request(L_AUTH, 0, request, "Attribute \"User-Password\" is required for authentication."); return RLM_MODULE_INVALID; } rcode = unix_getpw(instance, request, &vp); if (rcode != RLM_MODULE_UPDATED) return rcode; /* * 0 means "ok" */ if (fr_crypt_check((char *) request->password->vp_strvalue, (char *) vp->vp_strvalue) != 0) { radlog_request(L_AUTH, 0, request, "invalid password \"%s\"", request->password->vp_strvalue); return RLM_MODULE_REJECT; } #endif /* OSFFIA */ return RLM_MODULE_OK; } /* * UUencode 4 bits base64. We use this to turn a 4 byte field * (an IP address) into 6 bytes of ASCII. This is used for the * wtmp file if we didn't find a short name in the naslist file. */ static char *uue(void *in) { int i; static unsigned char res[7]; unsigned char *data = (unsigned char *)in; res[0] = ENC( data[0] >> 2 ); res[1] = ENC( ((data[0] << 4) & 060) + ((data[1] >> 4) & 017) ); res[2] = ENC( ((data[1] << 2) & 074) + ((data[2] >> 6) & 03) ); res[3] = ENC( data[2] & 077 ); res[4] = ENC( data[3] >> 2 ); res[5] = ENC( (data[3] << 4) & 060 ); res[6] = 0; for(i = 0; i < 6; i++) { if (res[i] == ' ') res[i] = '`'; if (res[i] < 32 || res[i] > 127) printf("uue: protocol error ?!\n"); } return (char *)res; } /* * Unix accounting - write a wtmp file. */ static int unix_accounting(void *instance, REQUEST *request) { VALUE_PAIR *vp; FILE *fp; struct utmp ut; time_t t; char buf[64]; const char *s; int delay = 0; int status = -1; int nas_address = 0; int framed_address = 0; #ifdef USER_PROCESS int protocol = -1; #endif int nas_port = 0; int port_seen = 0; struct unix_instance *inst = (struct unix_instance *) instance; /* * No radwtmp. Don't do anything. */ if (!inst->radwtmp) { RDEBUG2("No radwtmp file configured. Ignoring accounting request."); return RLM_MODULE_NOOP; } if (request->packet->src_ipaddr.af != AF_INET) { RDEBUG2("IPv6 is not supported!"); return RLM_MODULE_NOOP; } /* * Which type is this. */ if ((vp = pairfind(request->packet->vps, PW_ACCT_STATUS_TYPE, 0))==NULL) { RDEBUG("no Accounting-Status-Type attribute in request."); return RLM_MODULE_NOOP; } status = vp->vp_integer; /* * FIXME: handle PW_STATUS_ALIVE like 1.5.4.3 did. */ if (status != PW_STATUS_START && status != PW_STATUS_STOP) return RLM_MODULE_NOOP; /* * We're only interested in accounting messages * with a username in it. */ if (pairfind(request->packet->vps, PW_USER_NAME, 0) == NULL) return RLM_MODULE_NOOP; t = request->timestamp; memset(&ut, 0, sizeof(ut)); /* * First, find the interesting attributes. */ for (vp = request->packet->vps; vp; vp = vp->next) { switch (vp->attribute) { case PW_USER_NAME: if (vp->length >= sizeof(ut.ut_name)) { memcpy(ut.ut_name, (char *)vp->vp_strvalue, sizeof(ut.ut_name)); } else { strlcpy(ut.ut_name, (char *)vp->vp_strvalue, sizeof(ut.ut_name)); } break; case PW_LOGIN_IP_HOST: case PW_FRAMED_IP_ADDRESS: framed_address = vp->vp_ipaddr; break; #ifdef USER_PROCESS case PW_FRAMED_PROTOCOL: protocol = vp->vp_integer; break; #endif case PW_NAS_IP_ADDRESS: nas_address = vp->vp_ipaddr; break; case PW_NAS_PORT: nas_port = vp->vp_integer; port_seen = 1; break; case PW_ACCT_DELAY_TIME: delay = vp->vp_ipaddr; break; } } /* * We don't store !root sessions, or sessions * where we didn't see a NAS-Port attribute. */ if (strncmp(ut.ut_name, "!root", sizeof(ut.ut_name)) == 0 || !port_seen) return RLM_MODULE_NOOP; /* * If we didn't find out the NAS address, use the * originator's IP address. */ if (nas_address == 0) { nas_address = request->packet->src_ipaddr.ipaddr.ip4addr.s_addr; } s = request->client->shortname; if (!s || s[0] == 0) s = uue(&(nas_address)); #ifdef __linux__ /* * Linux has a field for the client address. */ ut.ut_addr = framed_address; #endif /* * We use the tty field to store the terminal servers' port * and address so that the tty field is unique. */ snprintf(buf, sizeof(buf), "%03d:%s", nas_port, s); strlcpy(ut.ut_line, buf, sizeof(ut.ut_line)); /* * We store the dynamic IP address in the hostname field. */ #ifdef UT_HOSTSIZE if (framed_address) { ip_ntoa(buf, framed_address); strlcpy(ut.ut_host, buf, sizeof(ut.ut_host)); } #endif #ifdef HAVE_UTMPX_H ut.ut_xtime = t- delay; #else ut.ut_time = t - delay; #endif #ifdef USER_PROCESS /* * And we can use the ID field to store * the protocol. */ if (protocol == PW_PPP) strcpy(ut.ut_id, "P"); else if (protocol == PW_SLIP) strcpy(ut.ut_id, "S"); else strcpy(ut.ut_id, "T"); ut.ut_type = status == PW_STATUS_STOP ? DEAD_PROCESS : USER_PROCESS; #endif if (status == PW_STATUS_STOP) ut.ut_name[0] = 0; /* * Write a RADIUS wtmp log file. * * Try to open the file if we can't, we don't write the * wtmp file. If we can try to write. If we fail, * return RLM_MODULE_FAIL .. */ if ((fp = fopen(inst->radwtmp, "a")) != NULL) { if ((fwrite(&ut, sizeof(ut), 1, fp)) != 1) { fclose(fp); return RLM_MODULE_FAIL; } fclose(fp); } else return RLM_MODULE_FAIL; return RLM_MODULE_OK; } /* globally exported name */ module_t rlm_unix = { RLM_MODULE_INIT, "System", RLM_TYPE_THREAD_UNSAFE | RLM_TYPE_CHECK_CONFIG_SAFE, unix_instantiate, /* instantiation */ unix_detach, /* detach */ { unix_authenticate, /* authentication */ unix_authorize, /* authorization */ NULL, /* preaccounting */ unix_accounting, /* accounting */ NULL, /* checksimul */ NULL, /* pre-proxy */ NULL, /* post-proxy */ NULL /* post-auth */ }, };
./CrossVul/dataset_final_sorted/CWE-255/c/good_3557_0
crossvul-cpp_data_bad_2254_0
/* -*- mode: c; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 1993 OpenVision Technologies, Inc., All Rights Reserved * * $Header$ */ #include "k5-int.h" #include <sys/time.h> #include <kadm5/admin.h> #include <kdb.h> #include "server_internal.h" #ifdef USE_PASSWORD_SERVER #include <sys/wait.h> #include <signal.h> #endif #include <krb5/kadm5_hook_plugin.h> #ifdef USE_VALGRIND #include <valgrind/memcheck.h> #else #define VALGRIND_CHECK_DEFINED(LVALUE) ((void)0) #endif extern krb5_principal master_princ; extern krb5_principal hist_princ; extern krb5_keyblock master_keyblock; extern krb5_db_entry master_db; static int decrypt_key_data(krb5_context context, int n_key_data, krb5_key_data *key_data, krb5_keyblock **keyblocks, int *n_keys); static krb5_error_code kadm5_copy_principal(krb5_context context, krb5_const_principal inprinc, krb5_principal *outprinc) { register krb5_principal tempprinc; register int i, nelems; tempprinc = (krb5_principal)krb5_db_alloc(context, NULL, sizeof(krb5_principal_data)); if (tempprinc == 0) return ENOMEM; VALGRIND_CHECK_DEFINED(*inprinc); *tempprinc = *inprinc; nelems = (int) krb5_princ_size(context, inprinc); tempprinc->data = krb5_db_alloc(context, NULL, nelems * sizeof(krb5_data)); if (tempprinc->data == 0) { krb5_db_free(context, (char *)tempprinc); return ENOMEM; } for (i = 0; i < nelems; i++) { unsigned int len = krb5_princ_component(context, inprinc, i)->length; krb5_princ_component(context, tempprinc, i)->length = len; if (((krb5_princ_component(context, tempprinc, i)->data = krb5_db_alloc(context, NULL, len)) == 0) && len) { while (--i >= 0) krb5_db_free(context, krb5_princ_component(context, tempprinc, i)->data); krb5_db_free (context, tempprinc->data); krb5_db_free (context, tempprinc); return ENOMEM; } if (len) memcpy(krb5_princ_component(context, tempprinc, i)->data, krb5_princ_component(context, inprinc, i)->data, len); krb5_princ_component(context, tempprinc, i)->magic = KV5M_DATA; } tempprinc->realm.data = krb5_db_alloc(context, NULL, tempprinc->realm.length = inprinc->realm.length); if (!tempprinc->realm.data && tempprinc->realm.length) { for (i = 0; i < nelems; i++) krb5_db_free(context, krb5_princ_component(context, tempprinc, i)->data); krb5_db_free(context, tempprinc->data); krb5_db_free(context, tempprinc); return ENOMEM; } if (tempprinc->realm.length) memcpy(tempprinc->realm.data, inprinc->realm.data, inprinc->realm.length); *outprinc = tempprinc; return 0; } static void kadm5_free_principal(krb5_context context, krb5_principal val) { register krb5_int32 i; if (!val) return; if (val->data) { i = krb5_princ_size(context, val); while(--i >= 0) krb5_db_free(context, krb5_princ_component(context, val, i)->data); krb5_db_free(context, val->data); } if (val->realm.data) krb5_db_free(context, val->realm.data); krb5_db_free(context, val); } /* * XXX Functions that ought to be in libkrb5.a, but aren't. */ kadm5_ret_t krb5_copy_key_data_contents(context, from, to) krb5_context context; krb5_key_data *from, *to; { int i, idx; *to = *from; idx = (from->key_data_ver == 1 ? 1 : 2); for (i = 0; i < idx; i++) { if ( from->key_data_length[i] ) { to->key_data_contents[i] = malloc(from->key_data_length[i]); if (to->key_data_contents[i] == NULL) { for (i = 0; i < idx; i++) { if (to->key_data_contents[i]) { memset(to->key_data_contents[i], 0, to->key_data_length[i]); free(to->key_data_contents[i]); } } return ENOMEM; } memcpy(to->key_data_contents[i], from->key_data_contents[i], from->key_data_length[i]); } } return 0; } static krb5_tl_data *dup_tl_data(krb5_tl_data *tl) { krb5_tl_data *n; n = (krb5_tl_data *) malloc(sizeof(krb5_tl_data)); if (n == NULL) return NULL; n->tl_data_contents = malloc(tl->tl_data_length); if (n->tl_data_contents == NULL) { free(n); return NULL; } memcpy(n->tl_data_contents, tl->tl_data_contents, tl->tl_data_length); n->tl_data_type = tl->tl_data_type; n->tl_data_length = tl->tl_data_length; n->tl_data_next = NULL; return n; } /* This is in lib/kdb/kdb_cpw.c, but is static */ static void cleanup_key_data(context, count, data) krb5_context context; int count; krb5_key_data * data; { int i, j; for (i = 0; i < count; i++) for (j = 0; j < data[i].key_data_ver; j++) if (data[i].key_data_length[j]) krb5_db_free(context, data[i].key_data_contents[j]); krb5_db_free(context, data); } /* Check whether a ks_tuple is present in an array of ks_tuples. */ static krb5_boolean ks_tuple_present(int n_ks_tuple, krb5_key_salt_tuple *ks_tuple, krb5_key_salt_tuple *looking_for) { int i; for (i = 0; i < n_ks_tuple; i++) { if (ks_tuple[i].ks_enctype == looking_for->ks_enctype && ks_tuple[i].ks_salttype == looking_for->ks_salttype) return TRUE; } return FALSE; } /* Fetch a policy if it exists; set *have_pol_out appropriately. Return * success whether or not the policy exists. */ static kadm5_ret_t get_policy(kadm5_server_handle_t handle, const char *name, kadm5_policy_ent_t policy_out, krb5_boolean *have_pol_out) { kadm5_ret_t ret; *have_pol_out = FALSE; if (name == NULL) return 0; ret = kadm5_get_policy(handle->lhandle, (char *)name, policy_out); if (ret == 0) *have_pol_out = TRUE; return (ret == KADM5_UNK_POLICY) ? 0 : ret; } /* * Apply the -allowedkeysalts policy (see kadmin(1)'s addpol/modpol * commands). We use the allowed key/salt tuple list as a default if * no ks tuples as provided by the caller. We reject lists that include * key/salts outside the policy. We re-order the requested ks tuples * (which may be a subset of the policy) to reflect the policy order. */ static kadm5_ret_t apply_keysalt_policy(kadm5_server_handle_t handle, const char *policy, int n_ks_tuple, krb5_key_salt_tuple *ks_tuple, int *new_n_kstp, krb5_key_salt_tuple **new_kstp) { kadm5_ret_t ret; kadm5_policy_ent_rec polent; krb5_boolean have_polent; int ak_n_ks_tuple = 0; int new_n_ks_tuple = 0; krb5_key_salt_tuple *ak_ks_tuple = NULL; krb5_key_salt_tuple *new_ks_tuple = NULL; krb5_key_salt_tuple *subset; int i, m; if (new_n_kstp != NULL) { *new_n_kstp = 0; *new_kstp = NULL; } memset(&polent, 0, sizeof(polent)); ret = get_policy(handle, policy, &polent, &have_polent); if (ret) goto cleanup; if (polent.allowed_keysalts == NULL) { /* Requested keysalts allowed or default to supported_enctypes. */ if (n_ks_tuple == 0) { /* Default to supported_enctypes. */ n_ks_tuple = handle->params.num_keysalts; ks_tuple = handle->params.keysalts; } /* Dup the requested or defaulted keysalt tuples. */ new_ks_tuple = malloc(n_ks_tuple * sizeof(*new_ks_tuple)); if (new_ks_tuple == NULL) { ret = ENOMEM; goto cleanup; } memcpy(new_ks_tuple, ks_tuple, n_ks_tuple * sizeof(*new_ks_tuple)); new_n_ks_tuple = n_ks_tuple; ret = 0; goto cleanup; } ret = krb5_string_to_keysalts(polent.allowed_keysalts, ",", /* Tuple separators */ NULL, /* Key/salt separators */ 0, /* No duplicates */ &ak_ks_tuple, &ak_n_ks_tuple); /* * Malformed policy? Shouldn't happen, but it's remotely possible * someday, so we don't assert, just bail. */ if (ret) goto cleanup; /* Check that the requested ks_tuples are within policy, if we have one. */ for (i = 0; i < n_ks_tuple; i++) { if (!ks_tuple_present(ak_n_ks_tuple, ak_ks_tuple, &ks_tuple[i])) { ret = KADM5_BAD_KEYSALTS; goto cleanup; } } /* Have policy but no ks_tuple input? Output the policy. */ if (n_ks_tuple == 0) { new_n_ks_tuple = ak_n_ks_tuple; new_ks_tuple = ak_ks_tuple; ak_ks_tuple = NULL; goto cleanup; } /* * Now filter the policy ks tuples by the requested ones so as to * preserve in the requested sub-set the relative ordering from the * policy. We could optimize this (if (n_ks_tuple == ak_n_ks_tuple) * then skip this), but we don't bother. */ subset = calloc(n_ks_tuple, sizeof(*subset)); if (subset == NULL) { ret = ENOMEM; goto cleanup; } for (m = 0, i = 0; i < ak_n_ks_tuple && m < n_ks_tuple; i++) { if (ks_tuple_present(n_ks_tuple, ks_tuple, &ak_ks_tuple[i])) subset[m++] = ak_ks_tuple[i]; } new_ks_tuple = subset; new_n_ks_tuple = m; ret = 0; cleanup: if (have_polent) kadm5_free_policy_ent(handle->lhandle, &polent); free(ak_ks_tuple); if (new_n_kstp != NULL) { *new_n_kstp = new_n_ks_tuple; *new_kstp = new_ks_tuple; } else { free(new_ks_tuple); } return ret; } /* * Set *passptr to NULL if the request looks like the first part of a krb5 1.6 * addprinc -randkey operation. The krb5 1.6 dummy password for these requests * was invalid UTF-8, which runs afoul of the arcfour string-to-key. */ static void check_1_6_dummy(kadm5_principal_ent_t entry, long mask, int n_ks_tuple, krb5_key_salt_tuple *ks_tuple, char **passptr) { int i; char *password = *passptr; /* Old-style randkey operations disallowed tickets to start. */ if (password == NULL || !(mask & KADM5_ATTRIBUTES) || !(entry->attributes & KRB5_KDB_DISALLOW_ALL_TIX)) return; /* The 1.6 dummy password was the octets 1..255. */ for (i = 0; (unsigned char) password[i] == i + 1; i++); if (password[i] != '\0' || i != 255) return; /* This will make the caller use a random password instead. */ *passptr = NULL; } kadm5_ret_t kadm5_create_principal(void *server_handle, kadm5_principal_ent_t entry, long mask, char *password) { return kadm5_create_principal_3(server_handle, entry, mask, 0, NULL, password); } kadm5_ret_t kadm5_create_principal_3(void *server_handle, kadm5_principal_ent_t entry, long mask, int n_ks_tuple, krb5_key_salt_tuple *ks_tuple, char *password) { krb5_db_entry *kdb; osa_princ_ent_rec adb; kadm5_policy_ent_rec polent; krb5_boolean have_polent = FALSE; krb5_int32 now; krb5_tl_data *tl_data_tail; unsigned int ret; kadm5_server_handle_t handle = server_handle; krb5_keyblock *act_mkey; krb5_kvno act_kvno; int new_n_ks_tuple = 0; krb5_key_salt_tuple *new_ks_tuple = NULL; CHECK_HANDLE(server_handle); krb5_clear_error_message(handle->context); check_1_6_dummy(entry, mask, n_ks_tuple, ks_tuple, &password); /* * Argument sanity checking, and opening up the DB */ if(!(mask & KADM5_PRINCIPAL) || (mask & KADM5_MOD_NAME) || (mask & KADM5_MOD_TIME) || (mask & KADM5_LAST_PWD_CHANGE) || (mask & KADM5_MKVNO) || (mask & KADM5_AUX_ATTRIBUTES) || (mask & KADM5_LAST_SUCCESS) || (mask & KADM5_LAST_FAILED) || (mask & KADM5_FAIL_AUTH_COUNT)) return KADM5_BAD_MASK; if ((mask & KADM5_KEY_DATA) && entry->n_key_data != 0) return KADM5_BAD_MASK; if((mask & KADM5_POLICY) && (mask & KADM5_POLICY_CLR)) return KADM5_BAD_MASK; if((mask & ~ALL_PRINC_MASK)) return KADM5_BAD_MASK; if (entry == NULL) return EINVAL; /* * Check to see if the principal exists */ ret = kdb_get_entry(handle, entry->principal, &kdb, &adb); switch(ret) { case KADM5_UNK_PRINC: break; case 0: kdb_free_entry(handle, kdb, &adb); return KADM5_DUP; default: return ret; } kdb = krb5_db_alloc(handle->context, NULL, sizeof(*kdb)); if (kdb == NULL) return ENOMEM; memset(kdb, 0, sizeof(*kdb)); memset(&adb, 0, sizeof(osa_princ_ent_rec)); /* * If a policy was specified, load it. * If we can not find the one specified return an error */ if ((mask & KADM5_POLICY)) { ret = get_policy(handle, entry->policy, &polent, &have_polent); if (ret) goto cleanup; } if (password) { ret = passwd_check(handle, password, have_polent ? &polent : NULL, entry->principal); if (ret) goto cleanup; } /* * Start populating the various DB fields, using the * "defaults" for fields that were not specified by the * mask. */ if ((ret = krb5_timeofday(handle->context, &now))) goto cleanup; kdb->magic = KRB5_KDB_MAGIC_NUMBER; kdb->len = KRB5_KDB_V1_BASE_LENGTH; /* gag me with a chainsaw */ if ((mask & KADM5_ATTRIBUTES)) kdb->attributes = entry->attributes; else kdb->attributes = handle->params.flags; if ((mask & KADM5_MAX_LIFE)) kdb->max_life = entry->max_life; else kdb->max_life = handle->params.max_life; if (mask & KADM5_MAX_RLIFE) kdb->max_renewable_life = entry->max_renewable_life; else kdb->max_renewable_life = handle->params.max_rlife; if ((mask & KADM5_PRINC_EXPIRE_TIME)) kdb->expiration = entry->princ_expire_time; else kdb->expiration = handle->params.expiration; kdb->pw_expiration = 0; if (have_polent) { if(polent.pw_max_life) kdb->pw_expiration = now + polent.pw_max_life; else kdb->pw_expiration = 0; } if ((mask & KADM5_PW_EXPIRATION)) kdb->pw_expiration = entry->pw_expiration; kdb->last_success = 0; kdb->last_failed = 0; kdb->fail_auth_count = 0; /* this is kind of gross, but in order to free the tl data, I need to free the entire kdb entry, and that will try to free the principal. */ if ((ret = kadm5_copy_principal(handle->context, entry->principal, &(kdb->princ)))) goto cleanup; if ((ret = krb5_dbe_update_last_pwd_change(handle->context, kdb, now))) goto cleanup; if (mask & KADM5_TL_DATA) { /* splice entry->tl_data onto the front of kdb->tl_data */ for (tl_data_tail = entry->tl_data; tl_data_tail; tl_data_tail = tl_data_tail->tl_data_next) { ret = krb5_dbe_update_tl_data(handle->context, kdb, tl_data_tail); if( ret ) goto cleanup; } } /* * We need to have setup the TL data, so we have strings, so we can * check enctype policy, which is why we check/initialize ks_tuple * this late. */ ret = apply_keysalt_policy(handle, entry->policy, n_ks_tuple, ks_tuple, &new_n_ks_tuple, &new_ks_tuple); if (ret) goto cleanup; /* initialize the keys */ ret = kdb_get_active_mkey(handle, &act_kvno, &act_mkey); if (ret) goto cleanup; if (mask & KADM5_KEY_DATA) { /* The client requested no keys for this principal. */ assert(entry->n_key_data == 0); } else if (password) { ret = krb5_dbe_cpw(handle->context, act_mkey, new_ks_tuple, new_n_ks_tuple, password, (mask & KADM5_KVNO)?entry->kvno:1, FALSE, kdb); } else { /* Null password means create with random key (new in 1.8). */ ret = krb5_dbe_crk(handle->context, &master_keyblock, new_ks_tuple, new_n_ks_tuple, FALSE, kdb); } if (ret) goto cleanup; /* Record the master key VNO used to encrypt this entry's keys */ ret = krb5_dbe_update_mkvno(handle->context, kdb, act_kvno); if (ret) goto cleanup; ret = k5_kadm5_hook_create(handle->context, handle->hook_handles, KADM5_HOOK_STAGE_PRECOMMIT, entry, mask, new_n_ks_tuple, new_ks_tuple, password); if (ret) goto cleanup; /* populate the admin-server-specific fields. In the OV server, this used to be in a separate database. Since there's already marshalling code for the admin fields, to keep things simple, I'm going to keep it, and make all the admin stuff occupy a single tl_data record, */ adb.admin_history_kvno = INITIAL_HIST_KVNO; if (mask & KADM5_POLICY) { adb.aux_attributes = KADM5_POLICY; /* this does *not* need to be strdup'ed, because adb is xdr */ /* encoded in osa_adb_create_princ, and not ever freed */ adb.policy = entry->policy; } /* In all cases key and the principal data is set, let the database provider know */ kdb->mask = mask | KADM5_KEY_DATA | KADM5_PRINCIPAL ; /* store the new db entry */ ret = kdb_put_entry(handle, kdb, &adb); (void) k5_kadm5_hook_create(handle->context, handle->hook_handles, KADM5_HOOK_STAGE_POSTCOMMIT, entry, mask, new_n_ks_tuple, new_ks_tuple, password); cleanup: free(new_ks_tuple); krb5_db_free_principal(handle->context, kdb); if (have_polent) (void) kadm5_free_policy_ent(handle->lhandle, &polent); return ret; } kadm5_ret_t kadm5_delete_principal(void *server_handle, krb5_principal principal) { unsigned int ret; krb5_db_entry *kdb; osa_princ_ent_rec adb; kadm5_server_handle_t handle = server_handle; CHECK_HANDLE(server_handle); krb5_clear_error_message(handle->context); if (principal == NULL) return EINVAL; if ((ret = kdb_get_entry(handle, principal, &kdb, &adb))) return(ret); ret = k5_kadm5_hook_remove(handle->context, handle->hook_handles, KADM5_HOOK_STAGE_PRECOMMIT, principal); if (ret) { kdb_free_entry(handle, kdb, &adb); return ret; } ret = kdb_delete_entry(handle, principal); kdb_free_entry(handle, kdb, &adb); if (ret == 0) (void) k5_kadm5_hook_remove(handle->context, handle->hook_handles, KADM5_HOOK_STAGE_POSTCOMMIT, principal); return ret; } kadm5_ret_t kadm5_modify_principal(void *server_handle, kadm5_principal_ent_t entry, long mask) { int ret, ret2, i; kadm5_policy_ent_rec pol; krb5_boolean have_pol = FALSE; krb5_db_entry *kdb; krb5_tl_data *tl_data_orig; osa_princ_ent_rec adb; kadm5_server_handle_t handle = server_handle; CHECK_HANDLE(server_handle); krb5_clear_error_message(handle->context); if((mask & KADM5_PRINCIPAL) || (mask & KADM5_LAST_PWD_CHANGE) || (mask & KADM5_MOD_TIME) || (mask & KADM5_MOD_NAME) || (mask & KADM5_MKVNO) || (mask & KADM5_AUX_ATTRIBUTES) || (mask & KADM5_KEY_DATA) || (mask & KADM5_LAST_SUCCESS) || (mask & KADM5_LAST_FAILED)) return KADM5_BAD_MASK; if((mask & ~ALL_PRINC_MASK)) return KADM5_BAD_MASK; if((mask & KADM5_POLICY) && (mask & KADM5_POLICY_CLR)) return KADM5_BAD_MASK; if(entry == (kadm5_principal_ent_t) NULL) return EINVAL; if (mask & KADM5_TL_DATA) { tl_data_orig = entry->tl_data; while (tl_data_orig) { if (tl_data_orig->tl_data_type < 256) return KADM5_BAD_TL_TYPE; tl_data_orig = tl_data_orig->tl_data_next; } } ret = kdb_get_entry(handle, entry->principal, &kdb, &adb); if (ret) return(ret); /* * This is pretty much the same as create ... */ if ((mask & KADM5_POLICY)) { ret = get_policy(handle, entry->policy, &pol, &have_pol); if (ret) goto done; /* set us up to use the new policy */ adb.aux_attributes |= KADM5_POLICY; if (adb.policy) free(adb.policy); adb.policy = strdup(entry->policy); } if (have_pol) { /* set pw_max_life based on new policy */ if (pol.pw_max_life) { ret = krb5_dbe_lookup_last_pwd_change(handle->context, kdb, &(kdb->pw_expiration)); if (ret) goto done; kdb->pw_expiration += pol.pw_max_life; } else { kdb->pw_expiration = 0; } } if ((mask & KADM5_POLICY_CLR) && (adb.aux_attributes & KADM5_POLICY)) { free(adb.policy); adb.policy = NULL; adb.aux_attributes &= ~KADM5_POLICY; kdb->pw_expiration = 0; } if ((mask & KADM5_ATTRIBUTES)) kdb->attributes = entry->attributes; if ((mask & KADM5_MAX_LIFE)) kdb->max_life = entry->max_life; if ((mask & KADM5_PRINC_EXPIRE_TIME)) kdb->expiration = entry->princ_expire_time; if (mask & KADM5_PW_EXPIRATION) kdb->pw_expiration = entry->pw_expiration; if (mask & KADM5_MAX_RLIFE) kdb->max_renewable_life = entry->max_renewable_life; if((mask & KADM5_KVNO)) { for (i = 0; i < kdb->n_key_data; i++) kdb->key_data[i].key_data_kvno = entry->kvno; } if (mask & KADM5_TL_DATA) { krb5_tl_data *tl; /* may have to change the version number of the API. Updates the list with the given tl_data rather than over-writting */ for (tl = entry->tl_data; tl; tl = tl->tl_data_next) { ret = krb5_dbe_update_tl_data(handle->context, kdb, tl); if( ret ) { goto done; } } } /* * Setting entry->fail_auth_count to 0 can be used to manually unlock * an account. It is not possible to set fail_auth_count to any other * value using kadmin. */ if (mask & KADM5_FAIL_AUTH_COUNT) { if (entry->fail_auth_count != 0) { ret = KADM5_BAD_SERVER_PARAMS; goto done; } kdb->fail_auth_count = 0; } /* let the mask propagate to the database provider */ kdb->mask = mask; ret = k5_kadm5_hook_modify(handle->context, handle->hook_handles, KADM5_HOOK_STAGE_PRECOMMIT, entry, mask); if (ret) goto done; ret = kdb_put_entry(handle, kdb, &adb); if (ret) goto done; (void) k5_kadm5_hook_modify(handle->context, handle->hook_handles, KADM5_HOOK_STAGE_POSTCOMMIT, entry, mask); ret = KADM5_OK; done: if (have_pol) { ret2 = kadm5_free_policy_ent(handle->lhandle, &pol); ret = ret ? ret : ret2; } kdb_free_entry(handle, kdb, &adb); return ret; } kadm5_ret_t kadm5_rename_principal(void *server_handle, krb5_principal source, krb5_principal target) { krb5_db_entry *kdb; osa_princ_ent_rec adb; krb5_error_code ret; kadm5_server_handle_t handle = server_handle; krb5_int16 stype, i; krb5_data *salt = NULL; CHECK_HANDLE(server_handle); krb5_clear_error_message(handle->context); if (source == NULL || target == NULL) return EINVAL; if ((ret = kdb_get_entry(handle, target, &kdb, &adb)) == 0) { kdb_free_entry(handle, kdb, &adb); return(KADM5_DUP); } if ((ret = kdb_get_entry(handle, source, &kdb, &adb))) return ret; /* Transform salts as necessary. */ for (i = 0; i < kdb->n_key_data; i++) { ret = krb5_dbe_compute_salt(handle->context, &kdb->key_data[i], kdb->princ, &stype, &salt); if (ret == KRB5_KDB_BAD_SALTTYPE) ret = KADM5_NO_RENAME_SALT; if (ret) goto done; kdb->key_data[i].key_data_type[1] = KRB5_KDB_SALTTYPE_SPECIAL; free(kdb->key_data[i].key_data_contents[1]); kdb->key_data[i].key_data_contents[1] = (krb5_octet *)salt->data; kdb->key_data[i].key_data_length[1] = salt->length; kdb->key_data[i].key_data_ver = 2; free(salt); salt = NULL; } kadm5_free_principal(handle->context, kdb->princ); ret = kadm5_copy_principal(handle->context, target, &kdb->princ); if (ret) { kdb->princ = NULL; /* so freeing the dbe doesn't lose */ goto done; } if ((ret = kdb_put_entry(handle, kdb, &adb))) goto done; ret = kdb_delete_entry(handle, source); done: krb5_free_data(handle->context, salt); kdb_free_entry(handle, kdb, &adb); return ret; } kadm5_ret_t kadm5_get_principal(void *server_handle, krb5_principal principal, kadm5_principal_ent_t entry, long in_mask) { krb5_db_entry *kdb; osa_princ_ent_rec adb; krb5_error_code ret = 0; long mask; int i; kadm5_server_handle_t handle = server_handle; CHECK_HANDLE(server_handle); krb5_clear_error_message(handle->context); /* * In version 1, all the defined fields are always returned. * entry is a pointer to a kadm5_principal_ent_t_v1 that should be * filled with allocated memory. */ mask = in_mask; memset(entry, 0, sizeof(*entry)); if (principal == NULL) return EINVAL; if ((ret = kdb_get_entry(handle, principal, &kdb, &adb))) return ret; if ((mask & KADM5_POLICY) && adb.policy && (adb.aux_attributes & KADM5_POLICY)) { if ((entry->policy = strdup(adb.policy)) == NULL) { ret = ENOMEM; goto done; } } if (mask & KADM5_AUX_ATTRIBUTES) entry->aux_attributes = adb.aux_attributes; if ((mask & KADM5_PRINCIPAL) && (ret = krb5_copy_principal(handle->context, kdb->princ, &entry->principal))) { goto done; } if (mask & KADM5_PRINC_EXPIRE_TIME) entry->princ_expire_time = kdb->expiration; if ((mask & KADM5_LAST_PWD_CHANGE) && (ret = krb5_dbe_lookup_last_pwd_change(handle->context, kdb, &(entry->last_pwd_change)))) { goto done; } if (mask & KADM5_PW_EXPIRATION) entry->pw_expiration = kdb->pw_expiration; if (mask & KADM5_MAX_LIFE) entry->max_life = kdb->max_life; /* this is a little non-sensical because the function returns two */ /* values that must be checked separately against the mask */ if ((mask & KADM5_MOD_NAME) || (mask & KADM5_MOD_TIME)) { ret = krb5_dbe_lookup_mod_princ_data(handle->context, kdb, &(entry->mod_date), &(entry->mod_name)); if (ret) { goto done; } if (! (mask & KADM5_MOD_TIME)) entry->mod_date = 0; if (! (mask & KADM5_MOD_NAME)) { krb5_free_principal(handle->context, entry->mod_name); entry->mod_name = NULL; } } if (mask & KADM5_ATTRIBUTES) entry->attributes = kdb->attributes; if (mask & KADM5_KVNO) for (entry->kvno = 0, i=0; i<kdb->n_key_data; i++) if ((krb5_kvno) kdb->key_data[i].key_data_kvno > entry->kvno) entry->kvno = kdb->key_data[i].key_data_kvno; if (mask & KADM5_MKVNO) { ret = krb5_dbe_get_mkvno(handle->context, kdb, &entry->mkvno); if (ret) goto done; } if (mask & KADM5_MAX_RLIFE) entry->max_renewable_life = kdb->max_renewable_life; if (mask & KADM5_LAST_SUCCESS) entry->last_success = kdb->last_success; if (mask & KADM5_LAST_FAILED) entry->last_failed = kdb->last_failed; if (mask & KADM5_FAIL_AUTH_COUNT) entry->fail_auth_count = kdb->fail_auth_count; if (mask & KADM5_TL_DATA) { krb5_tl_data *tl, *tl2; entry->tl_data = NULL; tl = kdb->tl_data; while (tl) { if (tl->tl_data_type > 255) { if ((tl2 = dup_tl_data(tl)) == NULL) { ret = ENOMEM; goto done; } tl2->tl_data_next = entry->tl_data; entry->tl_data = tl2; entry->n_tl_data++; } tl = tl->tl_data_next; } } if (mask & KADM5_KEY_DATA) { entry->n_key_data = kdb->n_key_data; if(entry->n_key_data) { entry->key_data = k5calloc(entry->n_key_data, sizeof(krb5_key_data), &ret); if (entry->key_data == NULL) goto done; } else entry->key_data = NULL; for (i = 0; i < entry->n_key_data; i++) ret = krb5_copy_key_data_contents(handle->context, &kdb->key_data[i], &entry->key_data[i]); if (ret) goto done; } ret = KADM5_OK; done: if (ret && entry->principal) { krb5_free_principal(handle->context, entry->principal); entry->principal = NULL; } kdb_free_entry(handle, kdb, &adb); return ret; } /* * Function: check_pw_reuse * * Purpose: Check if a key appears in a list of keys, in order to * enforce password history. * * Arguments: * * context (r) the krb5 context * hist_keyblock (r) the key that hist_key_data is * encrypted in * n_new_key_data (r) length of new_key_data * new_key_data (r) keys to check against * pw_hist_data, encrypted in hist_keyblock * n_pw_hist_data (r) length of pw_hist_data * pw_hist_data (r) passwords to check new_key_data against * * Effects: * For each new_key in new_key_data: * decrypt new_key with the master_keyblock * for each password in pw_hist_data: * for each hist_key in password: * decrypt hist_key with hist_keyblock * compare the new_key and hist_key * * Returns krb5 errors, KADM5_PASS_RESUSE if a key in * new_key_data is the same as a key in pw_hist_data, or 0. */ static kadm5_ret_t check_pw_reuse(krb5_context context, krb5_keyblock *hist_keyblocks, int n_new_key_data, krb5_key_data *new_key_data, unsigned int n_pw_hist_data, osa_pw_hist_ent *pw_hist_data) { unsigned int x, y, z; krb5_keyblock newkey, histkey, *kb; krb5_key_data *key_data; krb5_error_code ret; assert (n_new_key_data >= 0); for (x = 0; x < (unsigned) n_new_key_data; x++) { /* Check only entries with the most recent kvno. */ if (new_key_data[x].key_data_kvno != new_key_data[0].key_data_kvno) break; ret = krb5_dbe_decrypt_key_data(context, NULL, &(new_key_data[x]), &newkey, NULL); if (ret) return(ret); for (y = 0; y < n_pw_hist_data; y++) { for (z = 0; z < (unsigned int) pw_hist_data[y].n_key_data; z++) { for (kb = hist_keyblocks; kb->enctype != 0; kb++) { key_data = &pw_hist_data[y].key_data[z]; ret = krb5_dbe_decrypt_key_data(context, kb, key_data, &histkey, NULL); if (ret) continue; if (newkey.length == histkey.length && newkey.enctype == histkey.enctype && memcmp(newkey.contents, histkey.contents, histkey.length) == 0) { krb5_free_keyblock_contents(context, &histkey); krb5_free_keyblock_contents(context, &newkey); return KADM5_PASS_REUSE; } krb5_free_keyblock_contents(context, &histkey); } } } krb5_free_keyblock_contents(context, &newkey); } return(0); } /* * Function: create_history_entry * * Purpose: Creates a password history entry from an array of * key_data. * * Arguments: * * context (r) krb5_context to use * mkey (r) master keyblock to decrypt key data with * hist_key (r) history keyblock to encrypt key data with * n_key_data (r) number of elements in key_data * key_data (r) keys to add to the history entry * hist (w) history entry to fill in * * Effects: * * hist->key_data is allocated to store n_key_data key_datas. Each * element of key_data is decrypted with master_keyblock, re-encrypted * in hist_key, and added to hist->key_data. hist->n_key_data is * set to n_key_data. */ static int create_history_entry(krb5_context context, krb5_keyblock *hist_key, int n_key_data, krb5_key_data *key_data, osa_pw_hist_ent *hist) { krb5_error_code ret; krb5_keyblock key; krb5_keysalt salt; int i; hist->key_data = k5calloc(n_key_data, sizeof(krb5_key_data), &ret); if (hist->key_data == NULL) return ret; for (i = 0; i < n_key_data; i++) { ret = krb5_dbe_decrypt_key_data(context, NULL, &key_data[i], &key, &salt); if (ret) return ret; ret = krb5_dbe_encrypt_key_data(context, hist_key, &key, &salt, key_data[i].key_data_kvno, &hist->key_data[i]); if (ret) return ret; krb5_free_keyblock_contents(context, &key); /* krb5_free_keysalt(context, &salt); */ } hist->n_key_data = n_key_data; return 0; } static void free_history_entry(krb5_context context, osa_pw_hist_ent *hist) { int i; for (i = 0; i < hist->n_key_data; i++) krb5_free_key_data_contents(context, &hist->key_data[i]); free(hist->key_data); } /* * Function: add_to_history * * Purpose: Adds a password to a principal's password history. * * Arguments: * * context (r) krb5_context to use * hist_kvno (r) kvno of current history key * adb (r/w) admin principal entry to add keys to * pol (r) adb's policy * pw (r) keys for the password to add to adb's key history * * Effects: * * add_to_history adds a single password to adb's password history. * pw contains n_key_data keys in its key_data, in storage should be * allocated but not freed by the caller (XXX blech!). * * This function maintains adb->old_keys as a circular queue. It * starts empty, and grows each time this function is called until it * is pol->pw_history_num items long. adb->old_key_len holds the * number of allocated entries in the array, and must therefore be [0, * pol->pw_history_num). adb->old_key_next is the index into the * array where the next element should be written, and must be [0, * adb->old_key_len). */ static kadm5_ret_t add_to_history(krb5_context context, krb5_kvno hist_kvno, osa_princ_ent_t adb, kadm5_policy_ent_t pol, osa_pw_hist_ent *pw) { osa_pw_hist_ent *histp; uint32_t nhist; unsigned int i, knext, nkeys; nhist = pol->pw_history_num; /* A history of 1 means just check the current password */ if (nhist <= 1) return 0; if (adb->admin_history_kvno != hist_kvno) { /* The history key has changed since the last password change, so we * have to reset the password history. */ free(adb->old_keys); adb->old_keys = NULL; adb->old_key_len = 0; adb->old_key_next = 0; adb->admin_history_kvno = hist_kvno; } nkeys = adb->old_key_len; knext = adb->old_key_next; /* resize the adb->old_keys array if necessary */ if (nkeys + 1 < nhist) { if (adb->old_keys == NULL) { adb->old_keys = (osa_pw_hist_ent *) malloc((nkeys + 1) * sizeof (osa_pw_hist_ent)); } else { adb->old_keys = (osa_pw_hist_ent *) realloc(adb->old_keys, (nkeys + 1) * sizeof (osa_pw_hist_ent)); } if (adb->old_keys == NULL) return(ENOMEM); memset(&adb->old_keys[nkeys], 0, sizeof(osa_pw_hist_ent)); nkeys = ++adb->old_key_len; /* * To avoid losing old keys, shift forward each entry after * knext. */ for (i = nkeys - 1; i > knext; i--) { adb->old_keys[i] = adb->old_keys[i - 1]; } memset(&adb->old_keys[knext], 0, sizeof(osa_pw_hist_ent)); } else if (nkeys + 1 > nhist) { /* * The policy must have changed! Shrink the array. * Can't simply realloc() down, since it might be wrapped. * To understand the arithmetic below, note that we are * copying into new positions 0 .. N-1 from old positions * old_key_next-N .. old_key_next-1, modulo old_key_len, * where N = pw_history_num - 1 is the length of the * shortened list. Matt Crawford, FNAL */ /* * M = adb->old_key_len, N = pol->pw_history_num - 1 * * tmp[0] .. tmp[N-1] = old[(knext-N)%M] .. old[(knext-1)%M] */ int j; osa_pw_hist_t tmp; tmp = (osa_pw_hist_ent *) malloc((nhist - 1) * sizeof (osa_pw_hist_ent)); if (tmp == NULL) return ENOMEM; for (i = 0; i < nhist - 1; i++) { /* * Add nkeys once before taking remainder to avoid * negative values. */ j = (i + nkeys + knext - (nhist - 1)) % nkeys; tmp[i] = adb->old_keys[j]; } /* Now free the ones we don't keep (the oldest ones) */ for (i = 0; i < nkeys - (nhist - 1); i++) { j = (i + nkeys + knext) % nkeys; histp = &adb->old_keys[j]; for (j = 0; j < histp->n_key_data; j++) { krb5_free_key_data_contents(context, &histp->key_data[j]); } free(histp->key_data); } free(adb->old_keys); adb->old_keys = tmp; nkeys = adb->old_key_len = nhist - 1; knext = adb->old_key_next = 0; } /* * If nhist decreased since the last password change, and nkeys+1 * is less than the previous nhist, it is possible for knext to * index into unallocated space. This condition would not be * caught by the resizing code above. */ if (knext + 1 > nkeys) knext = adb->old_key_next = 0; /* free the old pw history entry if it contains data */ histp = &adb->old_keys[knext]; for (i = 0; i < (unsigned int) histp->n_key_data; i++) krb5_free_key_data_contents(context, &histp->key_data[i]); free(histp->key_data); /* store the new entry */ adb->old_keys[knext] = *pw; /* update the next pointer */ if (++adb->old_key_next == nhist - 1) adb->old_key_next = 0; return(0); } /* FIXME: don't use global variable for this */ krb5_boolean use_password_server = 0; #ifdef USE_PASSWORD_SERVER static krb5_boolean kadm5_use_password_server (void) { return use_password_server; } #endif void kadm5_set_use_password_server (void); void kadm5_set_use_password_server (void) { use_password_server = 1; } #ifdef USE_PASSWORD_SERVER /* * kadm5_launch_task () runs a program (task_path) to synchronize the * Apple password server with the Kerberos database. Password server * programs can receive arguments on the command line (task_argv) * and a block of data via stdin (data_buffer). * * Because a failure to communicate with the tool results in the * password server falling out of sync with the database, * kadm5_launch_task() always fails if it can't talk to the tool. */ static kadm5_ret_t kadm5_launch_task (krb5_context context, const char *task_path, char * const task_argv[], const char *buffer) { kadm5_ret_t ret; int data_pipe[2]; ret = pipe (data_pipe); if (ret) ret = errno; if (!ret) { pid_t pid = fork (); if (pid == -1) { ret = errno; close (data_pipe[0]); close (data_pipe[1]); } else if (pid == 0) { /* The child: */ if (dup2 (data_pipe[0], STDIN_FILENO) == -1) _exit (1); close (data_pipe[0]); close (data_pipe[1]); execv (task_path, task_argv); _exit (1); /* Fail if execv fails */ } else { /* The parent: */ int status; ret = 0; close (data_pipe[0]); /* Write out the buffer to the child, add \n */ if (buffer) { if (krb5_net_write (context, data_pipe[1], buffer, strlen (buffer)) < 0 || krb5_net_write (context, data_pipe[1], "\n", 1) < 0) { /* kill the child to make sure waitpid() won't hang later */ ret = errno; kill (pid, SIGKILL); } } close (data_pipe[1]); waitpid (pid, &status, 0); if (!ret) { if (WIFEXITED (status)) { /* child read password and exited. Check the return value. */ if ((WEXITSTATUS (status) != 0) && (WEXITSTATUS (status) != 252)) { ret = KRB5KDC_ERR_POLICY; /* password change rejected */ } } else { /* child read password but crashed or was killed */ ret = KRB5KRB_ERR_GENERIC; /* FIXME: better error */ } } } } return ret; } #endif kadm5_ret_t kadm5_chpass_principal(void *server_handle, krb5_principal principal, char *password) { return kadm5_chpass_principal_3(server_handle, principal, FALSE, 0, NULL, password); } kadm5_ret_t kadm5_chpass_principal_3(void *server_handle, krb5_principal principal, krb5_boolean keepold, int n_ks_tuple, krb5_key_salt_tuple *ks_tuple, char *password) { krb5_int32 now; kadm5_policy_ent_rec pol; osa_princ_ent_rec adb; krb5_db_entry *kdb; int ret, ret2, last_pwd, hist_added; krb5_boolean have_pol = FALSE; kadm5_server_handle_t handle = server_handle; osa_pw_hist_ent hist; krb5_keyblock *act_mkey, *hist_keyblocks = NULL; krb5_kvno act_kvno, hist_kvno; int new_n_ks_tuple = 0; krb5_key_salt_tuple *new_ks_tuple = NULL; CHECK_HANDLE(server_handle); krb5_clear_error_message(handle->context); hist_added = 0; memset(&hist, 0, sizeof(hist)); if (principal == NULL || password == NULL) return EINVAL; if ((krb5_principal_compare(handle->context, principal, hist_princ)) == TRUE) return KADM5_PROTECT_PRINCIPAL; if ((ret = kdb_get_entry(handle, principal, &kdb, &adb))) return(ret); ret = apply_keysalt_policy(handle, adb.policy, n_ks_tuple, ks_tuple, &new_n_ks_tuple, &new_ks_tuple); if (ret) goto done; if ((adb.aux_attributes & KADM5_POLICY)) { ret = get_policy(handle, adb.policy, &pol, &have_pol); if (ret) goto done; } if (have_pol) { /* Create a password history entry before we change kdb's key_data. */ ret = kdb_get_hist_key(handle, &hist_keyblocks, &hist_kvno); if (ret) goto done; ret = create_history_entry(handle->context, &hist_keyblocks[0], kdb->n_key_data, kdb->key_data, &hist); if (ret) goto done; } if ((ret = passwd_check(handle, password, have_pol ? &pol : NULL, principal))) goto done; ret = kdb_get_active_mkey(handle, &act_kvno, &act_mkey); if (ret) goto done; ret = krb5_dbe_cpw(handle->context, act_mkey, new_ks_tuple, new_n_ks_tuple, password, 0 /* increment kvno */, keepold, kdb); if (ret) goto done; ret = krb5_dbe_update_mkvno(handle->context, kdb, act_kvno); if (ret) goto done; kdb->attributes &= ~KRB5_KDB_REQUIRES_PWCHANGE; ret = krb5_timeofday(handle->context, &now); if (ret) goto done; if ((adb.aux_attributes & KADM5_POLICY)) { /* the policy was loaded before */ ret = krb5_dbe_lookup_last_pwd_change(handle->context, kdb, &last_pwd); if (ret) goto done; #if 0 /* * The spec says this check is overridden if the caller has * modify privilege. The admin server therefore makes this * check itself (in chpass_principal_wrapper, misc.c). A * local caller implicitly has all authorization bits. */ if ((now - last_pwd) < pol.pw_min_life && !(kdb->attributes & KRB5_KDB_REQUIRES_PWCHANGE)) { ret = KADM5_PASS_TOOSOON; goto done; } #endif ret = check_pw_reuse(handle->context, hist_keyblocks, kdb->n_key_data, kdb->key_data, 1, &hist); if (ret) goto done; if (pol.pw_history_num > 1) { /* If hist_kvno has changed since the last password change, we * can't check the history. */ if (adb.admin_history_kvno == hist_kvno) { ret = check_pw_reuse(handle->context, hist_keyblocks, kdb->n_key_data, kdb->key_data, adb.old_key_len, adb.old_keys); if (ret) goto done; } ret = add_to_history(handle->context, hist_kvno, &adb, &pol, &hist); if (ret) goto done; hist_added = 1; } if (pol.pw_max_life) kdb->pw_expiration = now + pol.pw_max_life; else kdb->pw_expiration = 0; } else { kdb->pw_expiration = 0; } #ifdef USE_PASSWORD_SERVER if (kadm5_use_password_server () && (krb5_princ_size (handle->context, principal) == 1)) { krb5_data *princ = krb5_princ_component (handle->context, principal, 0); const char *path = "/usr/sbin/mkpassdb"; char *argv[] = { "mkpassdb", "-setpassword", NULL, NULL }; char *pstring = NULL; if (!ret) { pstring = malloc ((princ->length + 1) * sizeof (char)); if (pstring == NULL) { ret = ENOMEM; } } if (!ret) { memcpy (pstring, princ->data, princ->length); pstring [princ->length] = '\0'; argv[2] = pstring; ret = kadm5_launch_task (handle->context, path, argv, password); } if (pstring != NULL) free (pstring); if (ret) goto done; } #endif ret = krb5_dbe_update_last_pwd_change(handle->context, kdb, now); if (ret) goto done; /* unlock principal on this KDC */ kdb->fail_auth_count = 0; /* key data and attributes changed, let the database provider know */ kdb->mask = KADM5_KEY_DATA | KADM5_ATTRIBUTES | KADM5_FAIL_AUTH_COUNT; /* | KADM5_CPW_FUNCTION */ ret = k5_kadm5_hook_chpass(handle->context, handle->hook_handles, KADM5_HOOK_STAGE_PRECOMMIT, principal, keepold, new_n_ks_tuple, new_ks_tuple, password); if (ret) goto done; if ((ret = kdb_put_entry(handle, kdb, &adb))) goto done; (void) k5_kadm5_hook_chpass(handle->context, handle->hook_handles, KADM5_HOOK_STAGE_POSTCOMMIT, principal, keepold, new_n_ks_tuple, new_ks_tuple, password); ret = KADM5_OK; done: free(new_ks_tuple); if (!hist_added && hist.key_data) free_history_entry(handle->context, &hist); kdb_free_entry(handle, kdb, &adb); kdb_free_keyblocks(handle, hist_keyblocks); if (have_pol && (ret2 = kadm5_free_policy_ent(handle->lhandle, &pol)) && !ret) ret = ret2; return ret; } kadm5_ret_t kadm5_randkey_principal(void *server_handle, krb5_principal principal, krb5_keyblock **keyblocks, int *n_keys) { return kadm5_randkey_principal_3(server_handle, principal, FALSE, 0, NULL, keyblocks, n_keys); } kadm5_ret_t kadm5_randkey_principal_3(void *server_handle, krb5_principal principal, krb5_boolean keepold, int n_ks_tuple, krb5_key_salt_tuple *ks_tuple, krb5_keyblock **keyblocks, int *n_keys) { krb5_db_entry *kdb; osa_princ_ent_rec adb; krb5_int32 now; kadm5_policy_ent_rec pol; int ret, last_pwd; krb5_boolean have_pol = FALSE; kadm5_server_handle_t handle = server_handle; krb5_keyblock *act_mkey; krb5_kvno act_kvno; int new_n_ks_tuple = 0; krb5_key_salt_tuple *new_ks_tuple = NULL; if (keyblocks) *keyblocks = NULL; CHECK_HANDLE(server_handle); krb5_clear_error_message(handle->context); if (principal == NULL) return EINVAL; if ((ret = kdb_get_entry(handle, principal, &kdb, &adb))) return(ret); ret = apply_keysalt_policy(handle, adb.policy, n_ks_tuple, ks_tuple, &new_n_ks_tuple, &new_ks_tuple); if (ret) goto done; if (krb5_principal_compare(handle->context, principal, hist_princ)) { /* If changing the history entry, the new entry must have exactly one * key. */ if (keepold) return KADM5_PROTECT_PRINCIPAL; new_n_ks_tuple = 1; } ret = kdb_get_active_mkey(handle, &act_kvno, &act_mkey); if (ret) goto done; ret = krb5_dbe_crk(handle->context, act_mkey, new_ks_tuple, new_n_ks_tuple, keepold, kdb); if (ret) goto done; ret = krb5_dbe_update_mkvno(handle->context, kdb, act_kvno); if (ret) goto done; kdb->attributes &= ~KRB5_KDB_REQUIRES_PWCHANGE; ret = krb5_timeofday(handle->context, &now); if (ret) goto done; if ((adb.aux_attributes & KADM5_POLICY)) { ret = get_policy(handle, adb.policy, &pol, &have_pol); if (ret) goto done; } if (have_pol) { ret = krb5_dbe_lookup_last_pwd_change(handle->context, kdb, &last_pwd); if (ret) goto done; #if 0 /* * The spec says this check is overridden if the caller has * modify privilege. The admin server therefore makes this * check itself (in chpass_principal_wrapper, misc.c). A * local caller implicitly has all authorization bits. */ if((now - last_pwd) < pol.pw_min_life && !(kdb->attributes & KRB5_KDB_REQUIRES_PWCHANGE)) { ret = KADM5_PASS_TOOSOON; goto done; } #endif if (pol.pw_max_life) kdb->pw_expiration = now + pol.pw_max_life; else kdb->pw_expiration = 0; } else { kdb->pw_expiration = 0; } ret = krb5_dbe_update_last_pwd_change(handle->context, kdb, now); if (ret) goto done; /* unlock principal on this KDC */ kdb->fail_auth_count = 0; if (keyblocks) { ret = decrypt_key_data(handle->context, kdb->n_key_data, kdb->key_data, keyblocks, n_keys); if (ret) goto done; } /* key data changed, let the database provider know */ kdb->mask = KADM5_KEY_DATA | KADM5_FAIL_AUTH_COUNT; /* | KADM5_RANDKEY_USED */; ret = k5_kadm5_hook_chpass(handle->context, handle->hook_handles, KADM5_HOOK_STAGE_PRECOMMIT, principal, keepold, new_n_ks_tuple, new_ks_tuple, NULL); if (ret) goto done; if ((ret = kdb_put_entry(handle, kdb, &adb))) goto done; (void) k5_kadm5_hook_chpass(handle->context, handle->hook_handles, KADM5_HOOK_STAGE_POSTCOMMIT, principal, keepold, new_n_ks_tuple, new_ks_tuple, NULL); ret = KADM5_OK; done: free(new_ks_tuple); kdb_free_entry(handle, kdb, &adb); if (have_pol) kadm5_free_policy_ent(handle->lhandle, &pol); return ret; } /* * kadm5_setv4key_principal: * * Set only ONE key of the principal, removing all others. This key * must have the DES_CBC_CRC enctype and is entered as having the * krb4 salttype. This is to enable things like kadmind4 to work. */ kadm5_ret_t kadm5_setv4key_principal(void *server_handle, krb5_principal principal, krb5_keyblock *keyblock) { krb5_db_entry *kdb; osa_princ_ent_rec adb; krb5_int32 now; kadm5_policy_ent_rec pol; krb5_keysalt keysalt; int i, k, kvno, ret; krb5_boolean have_pol = FALSE; #if 0 int last_pwd; #endif kadm5_server_handle_t handle = server_handle; krb5_key_data tmp_key_data; krb5_keyblock *act_mkey; memset( &tmp_key_data, 0, sizeof(tmp_key_data)); CHECK_HANDLE(server_handle); krb5_clear_error_message(handle->context); if (principal == NULL || keyblock == NULL) return EINVAL; if (hist_princ && /* this will be NULL when initializing the databse */ ((krb5_principal_compare(handle->context, principal, hist_princ)) == TRUE)) return KADM5_PROTECT_PRINCIPAL; if (keyblock->enctype != ENCTYPE_DES_CBC_CRC) return KADM5_SETV4KEY_INVAL_ENCTYPE; if ((ret = kdb_get_entry(handle, principal, &kdb, &adb))) return(ret); for (kvno = 0, i=0; i<kdb->n_key_data; i++) if (kdb->key_data[i].key_data_kvno > kvno) kvno = kdb->key_data[i].key_data_kvno; if (kdb->key_data != NULL) cleanup_key_data(handle->context, kdb->n_key_data, kdb->key_data); kdb->key_data = (krb5_key_data*)krb5_db_alloc(handle->context, NULL, sizeof(krb5_key_data)); if (kdb->key_data == NULL) return ENOMEM; memset(kdb->key_data, 0, sizeof(krb5_key_data)); kdb->n_key_data = 1; keysalt.type = KRB5_KDB_SALTTYPE_V4; /* XXX data.magic? */ keysalt.data.length = 0; keysalt.data.data = NULL; ret = kdb_get_active_mkey(handle, NULL, &act_mkey); if (ret) goto done; /* use tmp_key_data as temporary location and reallocate later */ ret = krb5_dbe_encrypt_key_data(handle->context, act_mkey, keyblock, &keysalt, kvno + 1, &tmp_key_data); if (ret) { goto done; } for (k = 0; k < tmp_key_data.key_data_ver; k++) { kdb->key_data->key_data_type[k] = tmp_key_data.key_data_type[k]; kdb->key_data->key_data_length[k] = tmp_key_data.key_data_length[k]; if (tmp_key_data.key_data_contents[k]) { kdb->key_data->key_data_contents[k] = krb5_db_alloc(handle->context, NULL, tmp_key_data.key_data_length[k]); if (kdb->key_data->key_data_contents[k] == NULL) { cleanup_key_data(handle->context, kdb->n_key_data, kdb->key_data); kdb->key_data = NULL; kdb->n_key_data = 0; ret = ENOMEM; goto done; } memcpy (kdb->key_data->key_data_contents[k], tmp_key_data.key_data_contents[k], tmp_key_data.key_data_length[k]); memset (tmp_key_data.key_data_contents[k], 0, tmp_key_data.key_data_length[k]); free (tmp_key_data.key_data_contents[k]); tmp_key_data.key_data_contents[k] = NULL; } } kdb->attributes &= ~KRB5_KDB_REQUIRES_PWCHANGE; ret = krb5_timeofday(handle->context, &now); if (ret) goto done; if ((adb.aux_attributes & KADM5_POLICY)) { ret = get_policy(handle, adb.policy, &pol, &have_pol); if (ret) goto done; } if (have_pol) { #if 0 /* * The spec says this check is overridden if the caller has * modify privilege. The admin server therefore makes this * check itself (in chpass_principal_wrapper, misc.c). A * local caller implicitly has all authorization bits. */ if (ret = krb5_dbe_lookup_last_pwd_change(handle->context, kdb, &last_pwd)) goto done; if((now - last_pwd) < pol.pw_min_life && !(kdb->attributes & KRB5_KDB_REQUIRES_PWCHANGE)) { ret = KADM5_PASS_TOOSOON; goto done; } #endif if (pol.pw_max_life) kdb->pw_expiration = now + pol.pw_max_life; else kdb->pw_expiration = 0; } else { kdb->pw_expiration = 0; } ret = krb5_dbe_update_last_pwd_change(handle->context, kdb, now); if (ret) goto done; /* unlock principal on this KDC */ kdb->fail_auth_count = 0; if ((ret = kdb_put_entry(handle, kdb, &adb))) goto done; ret = KADM5_OK; done: for (i = 0; i < tmp_key_data.key_data_ver; i++) { if (tmp_key_data.key_data_contents[i]) { memset (tmp_key_data.key_data_contents[i], 0, tmp_key_data.key_data_length[i]); free (tmp_key_data.key_data_contents[i]); } } kdb_free_entry(handle, kdb, &adb); if (have_pol) kadm5_free_policy_ent(handle->lhandle, &pol); return ret; } kadm5_ret_t kadm5_setkey_principal(void *server_handle, krb5_principal principal, krb5_keyblock *keyblocks, int n_keys) { return kadm5_setkey_principal_3(server_handle, principal, FALSE, 0, NULL, keyblocks, n_keys); } /* Make key/salt list from keys for kadm5_setkey_principal_3() */ static kadm5_ret_t make_ks_from_keys(krb5_context context, int n_keys, krb5_keyblock *keyblocks, krb5_key_salt_tuple **ks_tuple) { int i; *ks_tuple = calloc(n_keys, sizeof(**ks_tuple)); if (*ks_tuple == NULL) return ENOMEM; for (i = 0; i < n_keys; i++) { (*ks_tuple)[i].ks_enctype = keyblocks[i].enctype; (*ks_tuple)[i].ks_salttype = KRB5_KDB_SALTTYPE_NORMAL; } return 0; } kadm5_ret_t kadm5_setkey_principal_3(void *server_handle, krb5_principal principal, krb5_boolean keepold, int n_ks_tuple, krb5_key_salt_tuple *ks_tuple, krb5_keyblock *keyblocks, int n_keys) { krb5_db_entry *kdb; osa_princ_ent_rec adb; krb5_int32 now; kadm5_policy_ent_rec pol; krb5_key_data *old_key_data; int n_old_keys; int i, j, k, kvno, ret; krb5_boolean have_pol = FALSE; #if 0 int last_pwd; #endif kadm5_server_handle_t handle = server_handle; krb5_boolean similar; krb5_keysalt keysalt; krb5_key_data tmp_key_data; krb5_key_data *tptr; krb5_keyblock *act_mkey; krb5_key_salt_tuple *ks_from_keys = NULL; CHECK_HANDLE(server_handle); krb5_clear_error_message(handle->context); if (principal == NULL || keyblocks == NULL) return EINVAL; if (hist_princ && /* this will be NULL when initializing the databse */ ((krb5_principal_compare(handle->context, principal, hist_princ)) == TRUE)) return KADM5_PROTECT_PRINCIPAL; if ((ret = kdb_get_entry(handle, principal, &kdb, &adb))) return(ret); if (!n_ks_tuple) { /* Apply policy to the key/salt types implied by the given keys */ ret = make_ks_from_keys(handle->context, n_keys, keyblocks, &ks_from_keys); if (ret) goto done; ret = apply_keysalt_policy(handle, adb.policy, n_keys, ks_from_keys, NULL, NULL); free(ks_from_keys); } else { /* * Apply policy to the given ks_tuples. Note that further below * we enforce keyblocks[i].enctype == ks_tuple[i].ks_enctype for * all i from 0 to n_keys, and that n_ks_tuple == n_keys if ks * tuples are given. */ ret = apply_keysalt_policy(handle, adb.policy, n_ks_tuple, ks_tuple, NULL, NULL); } if (ret) goto done; for (i = 0; i < n_keys; i++) { for (j = i+1; j < n_keys; j++) { if ((ret = krb5_c_enctype_compare(handle->context, keyblocks[i].enctype, keyblocks[j].enctype, &similar))) return(ret); if (similar) { if (n_ks_tuple) { if (ks_tuple[i].ks_salttype == ks_tuple[j].ks_salttype) return KADM5_SETKEY_DUP_ENCTYPES; } else return KADM5_SETKEY_DUP_ENCTYPES; } } } if (n_ks_tuple && n_ks_tuple != n_keys) return KADM5_SETKEY3_ETYPE_MISMATCH; for (kvno = 0, i=0; i<kdb->n_key_data; i++) if (kdb->key_data[i].key_data_kvno > kvno) kvno = kdb->key_data[i].key_data_kvno; if (keepold) { old_key_data = kdb->key_data; n_old_keys = kdb->n_key_data; } else { if (kdb->key_data != NULL) cleanup_key_data(handle->context, kdb->n_key_data, kdb->key_data); n_old_keys = 0; old_key_data = NULL; } /* Allocate one extra key_data to avoid allocating 0 bytes. */ kdb->key_data = krb5_db_alloc(handle->context, NULL, (n_keys + n_old_keys + 1) * sizeof(krb5_key_data)); if (kdb->key_data == NULL) { ret = ENOMEM; goto done; } memset(kdb->key_data, 0, (n_keys+n_old_keys)*sizeof(krb5_key_data)); kdb->n_key_data = 0; for (i = 0; i < n_keys; i++) { if (n_ks_tuple) { keysalt.type = ks_tuple[i].ks_salttype; keysalt.data.length = 0; keysalt.data.data = NULL; if (ks_tuple[i].ks_enctype != keyblocks[i].enctype) { ret = KADM5_SETKEY3_ETYPE_MISMATCH; goto done; } } memset (&tmp_key_data, 0, sizeof(tmp_key_data)); ret = kdb_get_active_mkey(handle, NULL, &act_mkey); if (ret) goto done; ret = krb5_dbe_encrypt_key_data(handle->context, act_mkey, &keyblocks[i], n_ks_tuple ? &keysalt : NULL, kvno + 1, &tmp_key_data); if (ret) goto done; tptr = &kdb->key_data[i]; tptr->key_data_ver = tmp_key_data.key_data_ver; tptr->key_data_kvno = tmp_key_data.key_data_kvno; for (k = 0; k < tmp_key_data.key_data_ver; k++) { tptr->key_data_type[k] = tmp_key_data.key_data_type[k]; tptr->key_data_length[k] = tmp_key_data.key_data_length[k]; if (tmp_key_data.key_data_contents[k]) { tptr->key_data_contents[k] = krb5_db_alloc(handle->context, NULL, tmp_key_data.key_data_length[k]); if (tptr->key_data_contents[k] == NULL) { int i1; for (i1 = k; i1 < tmp_key_data.key_data_ver; i1++) { if (tmp_key_data.key_data_contents[i1]) { memset (tmp_key_data.key_data_contents[i1], 0, tmp_key_data.key_data_length[i1]); free (tmp_key_data.key_data_contents[i1]); } } ret = ENOMEM; goto done; } memcpy (tptr->key_data_contents[k], tmp_key_data.key_data_contents[k], tmp_key_data.key_data_length[k]); memset (tmp_key_data.key_data_contents[k], 0, tmp_key_data.key_data_length[k]); free (tmp_key_data.key_data_contents[k]); tmp_key_data.key_data_contents[k] = NULL; } } kdb->n_key_data++; } /* copy old key data if necessary */ for (i = 0; i < n_old_keys; i++) { kdb->key_data[i+n_keys] = old_key_data[i]; memset(&old_key_data[i], 0, sizeof (krb5_key_data)); kdb->n_key_data++; } if (old_key_data) krb5_db_free(handle->context, old_key_data); /* assert(kdb->n_key_data == n_keys + n_old_keys) */ kdb->attributes &= ~KRB5_KDB_REQUIRES_PWCHANGE; if ((ret = krb5_timeofday(handle->context, &now))) goto done; if ((adb.aux_attributes & KADM5_POLICY)) { ret = get_policy(handle, adb.policy, &pol, &have_pol); if (ret) goto done; } if (have_pol) { #if 0 /* * The spec says this check is overridden if the caller has * modify privilege. The admin server therefore makes this * check itself (in chpass_principal_wrapper, misc.c). A * local caller implicitly has all authorization bits. */ if (ret = krb5_dbe_lookup_last_pwd_change(handle->context, kdb, &last_pwd)) goto done; if((now - last_pwd) < pol.pw_min_life && !(kdb->attributes & KRB5_KDB_REQUIRES_PWCHANGE)) { ret = KADM5_PASS_TOOSOON; goto done; } #endif if (pol.pw_max_life) kdb->pw_expiration = now + pol.pw_max_life; else kdb->pw_expiration = 0; } else { kdb->pw_expiration = 0; } if ((ret = krb5_dbe_update_last_pwd_change(handle->context, kdb, now))) goto done; /* unlock principal on this KDC */ kdb->fail_auth_count = 0; if ((ret = kdb_put_entry(handle, kdb, &adb))) goto done; ret = KADM5_OK; done: kdb_free_entry(handle, kdb, &adb); if (have_pol) kadm5_free_policy_ent(handle->lhandle, &pol); return ret; } /* * Return the list of keys like kadm5_randkey_principal, * but don't modify the principal. */ kadm5_ret_t kadm5_get_principal_keys(void *server_handle /* IN */, krb5_principal principal /* IN */, krb5_keyblock **keyblocks /* OUT */, int *n_keys /* OUT */) { krb5_db_entry *kdb; osa_princ_ent_rec adb; kadm5_ret_t ret; kadm5_server_handle_t handle = server_handle; if (keyblocks) *keyblocks = NULL; CHECK_HANDLE(server_handle); if (principal == NULL) return EINVAL; if ((ret = kdb_get_entry(handle, principal, &kdb, &adb))) return(ret); if (keyblocks) { ret = decrypt_key_data(handle->context, kdb->n_key_data, kdb->key_data, keyblocks, n_keys); if (ret) goto done; } ret = KADM5_OK; done: kdb_free_entry(handle, kdb, &adb); return ret; } /* * Allocate an array of n_key_data krb5_keyblocks, fill in each * element with the results of decrypting the nth key in key_data, * and if n_keys is not NULL fill it in with the * number of keys decrypted. */ static int decrypt_key_data(krb5_context context, int n_key_data, krb5_key_data *key_data, krb5_keyblock **keyblocks, int *n_keys) { krb5_keyblock *keys; int ret, i; keys = (krb5_keyblock *) malloc(n_key_data*sizeof(krb5_keyblock)); if (keys == NULL) return ENOMEM; memset(keys, 0, n_key_data*sizeof(krb5_keyblock)); for (i = 0; i < n_key_data; i++) { ret = krb5_dbe_decrypt_key_data(context, NULL, &key_data[i], &keys[i], NULL); if (ret) { for (; i >= 0; i--) { if (keys[i].contents) { memset (keys[i].contents, 0, keys[i].length); free( keys[i].contents ); } } memset(keys, 0, n_key_data*sizeof(krb5_keyblock)); free(keys); return ret; } } *keyblocks = keys; if (n_keys) *n_keys = n_key_data; return 0; } /* * Function: kadm5_decrypt_key * * Purpose: Retrieves and decrypts a principal key. * * Arguments: * * server_handle (r) kadm5 handle * entry (r) principal retrieved with kadm5_get_principal * ktype (r) enctype to search for, or -1 to ignore * stype (r) salt type to search for, or -1 to ignore * kvno (r) kvno to search for, -1 for max, 0 for max * only if it also matches ktype and stype * keyblock (w) keyblock to fill in * keysalt (w) keysalt to fill in, or NULL * kvnop (w) kvno to fill in, or NULL * * Effects: Searches the key_data array of entry, which must have been * retrived with kadm5_get_principal with the KADM5_KEY_DATA mask, to * find a key with a specified enctype, salt type, and kvno in a * principal entry. If not found, return ENOENT. Otherwise, decrypt * it with the master key, and return the key in keyblock, the salt * in salttype, and the key version number in kvno. * * If ktype or stype is -1, it is ignored for the search. If kvno is * -1, ktype and stype are ignored and the key with the max kvno is * returned. If kvno is 0, only the key with the max kvno is returned * and only if it matches the ktype and stype; otherwise, ENOENT is * returned. */ kadm5_ret_t kadm5_decrypt_key(void *server_handle, kadm5_principal_ent_t entry, krb5_int32 ktype, krb5_int32 stype, krb5_int32 kvno, krb5_keyblock *keyblock, krb5_keysalt *keysalt, int *kvnop) { kadm5_server_handle_t handle = server_handle; krb5_db_entry dbent; krb5_key_data *key_data; krb5_keyblock *mkey_ptr; int ret; CHECK_HANDLE(server_handle); if (entry->n_key_data == 0 || entry->key_data == NULL) return EINVAL; /* find_enctype only uses these two fields */ dbent.n_key_data = entry->n_key_data; dbent.key_data = entry->key_data; if ((ret = krb5_dbe_find_enctype(handle->context, &dbent, ktype, stype, kvno, &key_data))) return ret; /* find_mkey only uses this field */ dbent.tl_data = entry->tl_data; if ((ret = krb5_dbe_find_mkey(handle->context, &dbent, &mkey_ptr))) { /* try refreshing master key list */ /* XXX it would nice if we had the mkvno here for optimization */ if (krb5_db_fetch_mkey_list(handle->context, master_princ, &master_keyblock) == 0) { if ((ret = krb5_dbe_find_mkey(handle->context, &dbent, &mkey_ptr))) { return ret; } } else { return ret; } } if ((ret = krb5_dbe_decrypt_key_data(handle->context, NULL, key_data, keyblock, keysalt))) return ret; /* * Coerce the enctype of the output keyblock in case we got an * inexact match on the enctype; this behavior will go away when * the key storage architecture gets redesigned for 1.3. */ if (ktype != -1) keyblock->enctype = ktype; if (kvnop) *kvnop = key_data->key_data_kvno; return KADM5_OK; } kadm5_ret_t kadm5_purgekeys(void *server_handle, krb5_principal principal, int keepkvno) { kadm5_server_handle_t handle = server_handle; kadm5_ret_t ret; krb5_db_entry *kdb; osa_princ_ent_rec adb; krb5_key_data *old_keydata; int n_old_keydata; int i, j, k; CHECK_HANDLE(server_handle); if (principal == NULL) return EINVAL; ret = kdb_get_entry(handle, principal, &kdb, &adb); if (ret) return(ret); if (keepkvno <= 0) { keepkvno = krb5_db_get_key_data_kvno(handle->context, kdb->n_key_data, kdb->key_data); } old_keydata = kdb->key_data; n_old_keydata = kdb->n_key_data; kdb->n_key_data = 0; /* Allocate one extra key_data to avoid allocating 0 bytes. */ kdb->key_data = krb5_db_alloc(handle->context, NULL, (n_old_keydata + 1) * sizeof(krb5_key_data)); if (kdb->key_data == NULL) { ret = ENOMEM; goto done; } memset(kdb->key_data, 0, n_old_keydata * sizeof(krb5_key_data)); for (i = 0, j = 0; i < n_old_keydata; i++) { if (old_keydata[i].key_data_kvno < keepkvno) continue; /* Alias the key_data_contents pointers; we null them out in the * source array immediately after. */ kdb->key_data[j] = old_keydata[i]; for (k = 0; k < old_keydata[i].key_data_ver; k++) { old_keydata[i].key_data_contents[k] = NULL; } j++; } kdb->n_key_data = j; cleanup_key_data(handle->context, n_old_keydata, old_keydata); kdb->mask = KADM5_KEY_DATA; ret = kdb_put_entry(handle, kdb, &adb); if (ret) goto done; done: kdb_free_entry(handle, kdb, &adb); return ret; } kadm5_ret_t kadm5_get_strings(void *server_handle, krb5_principal principal, krb5_string_attr **strings_out, int *count_out) { kadm5_server_handle_t handle = server_handle; kadm5_ret_t ret; krb5_db_entry *kdb = NULL; *strings_out = NULL; *count_out = 0; CHECK_HANDLE(server_handle); if (principal == NULL) return EINVAL; ret = kdb_get_entry(handle, principal, &kdb, NULL); if (ret) return ret; ret = krb5_dbe_get_strings(handle->context, kdb, strings_out, count_out); kdb_free_entry(handle, kdb, NULL); return ret; } kadm5_ret_t kadm5_set_string(void *server_handle, krb5_principal principal, const char *key, const char *value) { kadm5_server_handle_t handle = server_handle; kadm5_ret_t ret; krb5_db_entry *kdb; osa_princ_ent_rec adb; CHECK_HANDLE(server_handle); if (principal == NULL || key == NULL) return EINVAL; ret = kdb_get_entry(handle, principal, &kdb, &adb); if (ret) return ret; ret = krb5_dbe_set_string(handle->context, kdb, key, value); if (ret) goto done; kdb->mask = KADM5_TL_DATA; ret = kdb_put_entry(handle, kdb, &adb); done: kdb_free_entry(handle, kdb, &adb); return ret; }
./CrossVul/dataset_final_sorted/CWE-255/c/bad_2254_0
crossvul-cpp_data_bad_3557_0
404: Not Found
./CrossVul/dataset_final_sorted/CWE-255/c/bad_3557_0
crossvul-cpp_data_good_536_0
/* SPDX-License-Identifier: LGPL-2.1+ */ #include <errno.h> #include <fcntl.h> #include <limits.h> #include <linux/kd.h> #include <linux/tiocl.h> #include <linux/vt.h> #include <poll.h> #include <signal.h> #include <stdarg.h> #include <stddef.h> #include <stdlib.h> #include <string.h> #include <sys/inotify.h> #include <sys/ioctl.h> #include <sys/socket.h> #include <sys/sysmacros.h> #include <sys/time.h> #include <sys/types.h> #include <sys/utsname.h> #include <termios.h> #include <unistd.h> #include "alloc-util.h" #include "copy.h" #include "def.h" #include "env-util.h" #include "fd-util.h" #include "fileio.h" #include "fs-util.h" #include "io-util.h" #include "log.h" #include "macro.h" #include "namespace-util.h" #include "parse-util.h" #include "path-util.h" #include "proc-cmdline.h" #include "process-util.h" #include "socket-util.h" #include "stat-util.h" #include "string-util.h" #include "strv.h" #include "terminal-util.h" #include "time-util.h" #include "util.h" static volatile unsigned cached_columns = 0; static volatile unsigned cached_lines = 0; static volatile int cached_on_tty = -1; static volatile int cached_colors_enabled = -1; static volatile int cached_underline_enabled = -1; int chvt(int vt) { _cleanup_close_ int fd; /* Switch to the specified vt number. If the VT is specified <= 0 switch to the VT the kernel log messages go, * if that's configured. */ fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK); if (fd < 0) return -errno; if (vt <= 0) { int tiocl[2] = { TIOCL_GETKMSGREDIRECT, 0 }; if (ioctl(fd, TIOCLINUX, tiocl) < 0) return -errno; vt = tiocl[0] <= 0 ? 1 : tiocl[0]; } if (ioctl(fd, VT_ACTIVATE, vt) < 0) return -errno; return 0; } int read_one_char(FILE *f, char *ret, usec_t t, bool *need_nl) { _cleanup_free_ char *line = NULL; struct termios old_termios; int r; assert(f); assert(ret); /* If this is a terminal, then switch canonical mode off, so that we can read a single character */ if (tcgetattr(fileno(f), &old_termios) >= 0) { struct termios new_termios = old_termios; new_termios.c_lflag &= ~ICANON; new_termios.c_cc[VMIN] = 1; new_termios.c_cc[VTIME] = 0; if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) { char c; if (t != USEC_INFINITY) { if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0) { (void) tcsetattr(fileno(f), TCSADRAIN, &old_termios); return -ETIMEDOUT; } } r = safe_fgetc(f, &c); (void) tcsetattr(fileno(f), TCSADRAIN, &old_termios); if (r < 0) return r; if (r == 0) return -EIO; if (need_nl) *need_nl = c != '\n'; *ret = c; return 0; } } if (t != USEC_INFINITY) { if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0) return -ETIMEDOUT; } /* If this is not a terminal, then read a full line instead */ r = read_line(f, 16, &line); /* longer than necessary, to eat up UTF-8 chars/vt100 key sequences */ if (r < 0) return r; if (r == 0) return -EIO; if (strlen(line) != 1) return -EBADMSG; if (need_nl) *need_nl = false; *ret = line[0]; return 0; } #define DEFAULT_ASK_REFRESH_USEC (2*USEC_PER_SEC) int ask_char(char *ret, const char *replies, const char *fmt, ...) { int r; assert(ret); assert(replies); assert(fmt); for (;;) { va_list ap; char c; bool need_nl = true; if (colors_enabled()) fputs(ANSI_HIGHLIGHT, stdout); putchar('\r'); va_start(ap, fmt); vprintf(fmt, ap); va_end(ap); if (colors_enabled()) fputs(ANSI_NORMAL, stdout); fflush(stdout); r = read_one_char(stdin, &c, DEFAULT_ASK_REFRESH_USEC, &need_nl); if (r < 0) { if (r == -ETIMEDOUT) continue; if (r == -EBADMSG) { puts("Bad input, please try again."); continue; } putchar('\n'); return r; } if (need_nl) putchar('\n'); if (strchr(replies, c)) { *ret = c; return 0; } puts("Read unexpected character, please try again."); } } int ask_string(char **ret, const char *text, ...) { int r; assert(ret); assert(text); for (;;) { _cleanup_free_ char *line = NULL; va_list ap; if (colors_enabled()) fputs(ANSI_HIGHLIGHT, stdout); va_start(ap, text); vprintf(text, ap); va_end(ap); if (colors_enabled()) fputs(ANSI_NORMAL, stdout); fflush(stdout); r = read_line(stdin, LONG_LINE_MAX, &line); if (r < 0) return r; if (r == 0) return -EIO; if (!isempty(line)) { *ret = TAKE_PTR(line); return 0; } } } int reset_terminal_fd(int fd, bool switch_to_text) { struct termios termios; int r = 0; /* Set terminal to some sane defaults */ assert(fd >= 0); /* We leave locked terminal attributes untouched, so that * Plymouth may set whatever it wants to set, and we don't * interfere with that. */ /* Disable exclusive mode, just in case */ (void) ioctl(fd, TIOCNXCL); /* Switch to text mode */ if (switch_to_text) (void) ioctl(fd, KDSETMODE, KD_TEXT); /* Set default keyboard mode */ (void) vt_reset_keyboard(fd); if (tcgetattr(fd, &termios) < 0) { r = -errno; goto finish; } /* We only reset the stuff that matters to the software. How * hardware is set up we don't touch assuming that somebody * else will do that for us */ termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC); termios.c_iflag |= ICRNL | IMAXBEL | IUTF8; termios.c_oflag |= ONLCR; termios.c_cflag |= CREAD; termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE; termios.c_cc[VINTR] = 03; /* ^C */ termios.c_cc[VQUIT] = 034; /* ^\ */ termios.c_cc[VERASE] = 0177; termios.c_cc[VKILL] = 025; /* ^X */ termios.c_cc[VEOF] = 04; /* ^D */ termios.c_cc[VSTART] = 021; /* ^Q */ termios.c_cc[VSTOP] = 023; /* ^S */ termios.c_cc[VSUSP] = 032; /* ^Z */ termios.c_cc[VLNEXT] = 026; /* ^V */ termios.c_cc[VWERASE] = 027; /* ^W */ termios.c_cc[VREPRINT] = 022; /* ^R */ termios.c_cc[VEOL] = 0; termios.c_cc[VEOL2] = 0; termios.c_cc[VTIME] = 0; termios.c_cc[VMIN] = 1; if (tcsetattr(fd, TCSANOW, &termios) < 0) r = -errno; finish: /* Just in case, flush all crap out */ (void) tcflush(fd, TCIOFLUSH); return r; } int reset_terminal(const char *name) { _cleanup_close_ int fd = -1; /* We open the terminal with O_NONBLOCK here, to ensure we * don't block on carrier if this is a terminal with carrier * configured. */ fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK); if (fd < 0) return fd; return reset_terminal_fd(fd, true); } int open_terminal(const char *name, int mode) { unsigned c = 0; int fd; /* * If a TTY is in the process of being closed opening it might * cause EIO. This is horribly awful, but unlikely to be * changed in the kernel. Hence we work around this problem by * retrying a couple of times. * * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245 */ if (mode & O_CREAT) return -EINVAL; for (;;) { fd = open(name, mode, 0); if (fd >= 0) break; if (errno != EIO) return -errno; /* Max 1s in total */ if (c >= 20) return -errno; usleep(50 * USEC_PER_MSEC); c++; } if (isatty(fd) <= 0) { safe_close(fd); return -ENOTTY; } return fd; } int acquire_terminal( const char *name, AcquireTerminalFlags flags, usec_t timeout) { _cleanup_close_ int notify = -1, fd = -1; usec_t ts = USEC_INFINITY; int r, wd = -1; assert(name); assert(IN_SET(flags & ~ACQUIRE_TERMINAL_PERMISSIVE, ACQUIRE_TERMINAL_TRY, ACQUIRE_TERMINAL_FORCE, ACQUIRE_TERMINAL_WAIT)); /* We use inotify to be notified when the tty is closed. We create the watch before checking if we can actually * acquire it, so that we don't lose any event. * * Note: strictly speaking this actually watches for the device being closed, it does *not* really watch * whether a tty loses its controlling process. However, unless some rogue process uses TIOCNOTTY on /dev/tty * *after* closing its tty otherwise this will not become a problem. As long as the administrator makes sure to * not configure any service on the same tty as an untrusted user this should not be a problem. (Which they * probably should not do anyway.) */ if ((flags & ~ACQUIRE_TERMINAL_PERMISSIVE) == ACQUIRE_TERMINAL_WAIT) { notify = inotify_init1(IN_CLOEXEC | (timeout != USEC_INFINITY ? IN_NONBLOCK : 0)); if (notify < 0) return -errno; wd = inotify_add_watch(notify, name, IN_CLOSE); if (wd < 0) return -errno; if (timeout != USEC_INFINITY) ts = now(CLOCK_MONOTONIC); } for (;;) { struct sigaction sa_old, sa_new = { .sa_handler = SIG_IGN, .sa_flags = SA_RESTART, }; if (notify >= 0) { r = flush_fd(notify); if (r < 0) return r; } /* We pass here O_NOCTTY only so that we can check the return value TIOCSCTTY and have a reliable way * to figure out if we successfully became the controlling process of the tty */ fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC); if (fd < 0) return fd; /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed if we already own the tty. */ assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0); /* First, try to get the tty */ r = ioctl(fd, TIOCSCTTY, (flags & ~ACQUIRE_TERMINAL_PERMISSIVE) == ACQUIRE_TERMINAL_FORCE) < 0 ? -errno : 0; /* Reset signal handler to old value */ assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0); /* Success? Exit the loop now! */ if (r >= 0) break; /* Any failure besides -EPERM? Fail, regardless of the mode. */ if (r != -EPERM) return r; if (flags & ACQUIRE_TERMINAL_PERMISSIVE) /* If we are in permissive mode, then EPERM is fine, turn this * into a success. Note that EPERM is also returned if we * already are the owner of the TTY. */ break; if (flags != ACQUIRE_TERMINAL_WAIT) /* If we are in TRY or FORCE mode, then propagate EPERM as EPERM */ return r; assert(notify >= 0); assert(wd >= 0); for (;;) { union inotify_event_buffer buffer; struct inotify_event *e; ssize_t l; if (timeout != USEC_INFINITY) { usec_t n; assert(ts != USEC_INFINITY); n = now(CLOCK_MONOTONIC); if (ts + timeout < n) return -ETIMEDOUT; r = fd_wait_for_event(notify, POLLIN, ts + timeout - n); if (r < 0) return r; if (r == 0) return -ETIMEDOUT; } l = read(notify, &buffer, sizeof(buffer)); if (l < 0) { if (IN_SET(errno, EINTR, EAGAIN)) continue; return -errno; } FOREACH_INOTIFY_EVENT(e, buffer, l) { if (e->mask & IN_Q_OVERFLOW) /* If we hit an inotify queue overflow, simply check if the terminal is up for grabs now. */ break; if (e->wd != wd || !(e->mask & IN_CLOSE)) /* Safety checks */ return -EIO; } break; } /* We close the tty fd here since if the old session ended our handle will be dead. It's important that * we do this after sleeping, so that we don't enter an endless loop. */ fd = safe_close(fd); } return TAKE_FD(fd); } int release_terminal(void) { static const struct sigaction sa_new = { .sa_handler = SIG_IGN, .sa_flags = SA_RESTART, }; _cleanup_close_ int fd = -1; struct sigaction sa_old; int r; fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK); if (fd < 0) return -errno; /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed * by our own TIOCNOTTY */ assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0); r = ioctl(fd, TIOCNOTTY) < 0 ? -errno : 0; assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0); return r; } int terminal_vhangup_fd(int fd) { assert(fd >= 0); if (ioctl(fd, TIOCVHANGUP) < 0) return -errno; return 0; } int terminal_vhangup(const char *name) { _cleanup_close_ int fd; fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK); if (fd < 0) return fd; return terminal_vhangup_fd(fd); } int vt_disallocate(const char *name) { _cleanup_close_ int fd = -1; const char *e, *n; unsigned u; int r; /* Deallocate the VT if possible. If not possible * (i.e. because it is the active one), at least clear it * entirely (including the scrollback buffer) */ e = path_startswith(name, "/dev/"); if (!e) return -EINVAL; if (!tty_is_vc(name)) { /* So this is not a VT. I guess we cannot deallocate * it then. But let's at least clear the screen */ fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC); if (fd < 0) return fd; loop_write(fd, "\033[r" /* clear scrolling region */ "\033[H" /* move home */ "\033[2J", /* clear screen */ 10, false); return 0; } n = startswith(e, "tty"); if (!n) return -EINVAL; r = safe_atou(n, &u); if (r < 0) return r; if (u <= 0) return -EINVAL; /* Try to deallocate */ fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK); if (fd < 0) return fd; r = ioctl(fd, VT_DISALLOCATE, u); fd = safe_close(fd); if (r >= 0) return 0; if (errno != EBUSY) return -errno; /* Couldn't deallocate, so let's clear it fully with * scrollback */ fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC); if (fd < 0) return fd; loop_write(fd, "\033[r" /* clear scrolling region */ "\033[H" /* move home */ "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */ 10, false); return 0; } int make_console_stdio(void) { int fd, r; /* Make /dev/console the controlling terminal and stdin/stdout/stderr */ fd = acquire_terminal("/dev/console", ACQUIRE_TERMINAL_FORCE|ACQUIRE_TERMINAL_PERMISSIVE, USEC_INFINITY); if (fd < 0) return log_error_errno(fd, "Failed to acquire terminal: %m"); r = reset_terminal_fd(fd, true); if (r < 0) log_warning_errno(r, "Failed to reset terminal, ignoring: %m"); r = rearrange_stdio(fd, fd, fd); /* This invalidates 'fd' both on success and on failure. */ if (r < 0) return log_error_errno(r, "Failed to make terminal stdin/stdout/stderr: %m"); reset_terminal_feature_caches(); return 0; } bool tty_is_vc(const char *tty) { assert(tty); return vtnr_from_tty(tty) >= 0; } bool tty_is_console(const char *tty) { assert(tty); return streq(skip_dev_prefix(tty), "console"); } int vtnr_from_tty(const char *tty) { int i, r; assert(tty); tty = skip_dev_prefix(tty); if (!startswith(tty, "tty") ) return -EINVAL; if (tty[3] < '0' || tty[3] > '9') return -EINVAL; r = safe_atoi(tty+3, &i); if (r < 0) return r; if (i < 0 || i > 63) return -EINVAL; return i; } int resolve_dev_console(char **ret) { _cleanup_free_ char *active = NULL; char *tty; int r; assert(ret); /* Resolve where /dev/console is pointing to, if /sys is actually ours (i.e. not read-only-mounted which is a * sign for container setups) */ if (path_is_read_only_fs("/sys") > 0) return -ENOMEDIUM; r = read_one_line_file("/sys/class/tty/console/active", &active); if (r < 0) return r; /* If multiple log outputs are configured the last one is what /dev/console points to */ tty = strrchr(active, ' '); if (tty) tty++; else tty = active; if (streq(tty, "tty0")) { active = mfree(active); /* Get the active VC (e.g. tty1) */ r = read_one_line_file("/sys/class/tty/tty0/active", &active); if (r < 0) return r; tty = active; } if (tty == active) *ret = TAKE_PTR(active); else { char *tmp; tmp = strdup(tty); if (!tmp) return -ENOMEM; *ret = tmp; } return 0; } int get_kernel_consoles(char ***ret) { _cleanup_strv_free_ char **l = NULL; _cleanup_free_ char *line = NULL; const char *p; int r; assert(ret); /* If /sys is mounted read-only this means we are running in some kind of container environment. In that * case /sys would reflect the host system, not us, hence ignore the data we can read from it. */ if (path_is_read_only_fs("/sys") > 0) goto fallback; r = read_one_line_file("/sys/class/tty/console/active", &line); if (r < 0) return r; p = line; for (;;) { _cleanup_free_ char *tty = NULL; char *path; r = extract_first_word(&p, &tty, NULL, 0); if (r < 0) return r; if (r == 0) break; if (streq(tty, "tty0")) { tty = mfree(tty); r = read_one_line_file("/sys/class/tty/tty0/active", &tty); if (r < 0) return r; } path = strappend("/dev/", tty); if (!path) return -ENOMEM; if (access(path, F_OK) < 0) { log_debug_errno(errno, "Console device %s is not accessible, skipping: %m", path); free(path); continue; } r = strv_consume(&l, path); if (r < 0) return r; } if (strv_isempty(l)) { log_debug("No devices found for system console"); goto fallback; } *ret = TAKE_PTR(l); return 0; fallback: r = strv_extend(&l, "/dev/console"); if (r < 0) return r; *ret = TAKE_PTR(l); return 0; } bool tty_is_vc_resolve(const char *tty) { _cleanup_free_ char *resolved = NULL; assert(tty); tty = skip_dev_prefix(tty); if (streq(tty, "console")) { if (resolve_dev_console(&resolved) < 0) return false; tty = resolved; } return tty_is_vc(tty); } const char *default_term_for_tty(const char *tty) { return tty && tty_is_vc_resolve(tty) ? "linux" : "vt220"; } int fd_columns(int fd) { struct winsize ws = {}; if (ioctl(fd, TIOCGWINSZ, &ws) < 0) return -errno; if (ws.ws_col <= 0) return -EIO; return ws.ws_col; } unsigned columns(void) { const char *e; int c; if (cached_columns > 0) return cached_columns; c = 0; e = getenv("COLUMNS"); if (e) (void) safe_atoi(e, &c); if (c <= 0 || c > USHRT_MAX) { c = fd_columns(STDOUT_FILENO); if (c <= 0) c = 80; } cached_columns = c; return cached_columns; } int fd_lines(int fd) { struct winsize ws = {}; if (ioctl(fd, TIOCGWINSZ, &ws) < 0) return -errno; if (ws.ws_row <= 0) return -EIO; return ws.ws_row; } unsigned lines(void) { const char *e; int l; if (cached_lines > 0) return cached_lines; l = 0; e = getenv("LINES"); if (e) (void) safe_atoi(e, &l); if (l <= 0 || l > USHRT_MAX) { l = fd_lines(STDOUT_FILENO); if (l <= 0) l = 24; } cached_lines = l; return cached_lines; } /* intended to be used as a SIGWINCH sighandler */ void columns_lines_cache_reset(int signum) { cached_columns = 0; cached_lines = 0; } void reset_terminal_feature_caches(void) { cached_columns = 0; cached_lines = 0; cached_colors_enabled = -1; cached_underline_enabled = -1; cached_on_tty = -1; } bool on_tty(void) { /* We check both stdout and stderr, so that situations where pipes on the shell are used are reliably * recognized, regardless if only the output or the errors are piped to some place. Since on_tty() is generally * used to default to a safer, non-interactive, non-color mode of operation it's probably good to be defensive * here, and check for both. Note that we don't check for STDIN_FILENO, because it should fine to use fancy * terminal functionality when outputting stuff, even if the input is piped to us. */ if (cached_on_tty < 0) cached_on_tty = isatty(STDOUT_FILENO) > 0 && isatty(STDERR_FILENO) > 0; return cached_on_tty; } int getttyname_malloc(int fd, char **ret) { char path[PATH_MAX], *c; /* PATH_MAX is counted *with* the trailing NUL byte */ int r; assert(fd >= 0); assert(ret); r = ttyname_r(fd, path, sizeof path); /* positive error */ assert(r >= 0); if (r == ERANGE) return -ENAMETOOLONG; if (r > 0) return -r; c = strdup(skip_dev_prefix(path)); if (!c) return -ENOMEM; *ret = c; return 0; } int getttyname_harder(int fd, char **ret) { _cleanup_free_ char *s = NULL; int r; r = getttyname_malloc(fd, &s); if (r < 0) return r; if (streq(s, "tty")) return get_ctty(0, NULL, ret); *ret = TAKE_PTR(s); return 0; } int get_ctty_devnr(pid_t pid, dev_t *d) { int r; _cleanup_free_ char *line = NULL; const char *p; unsigned long ttynr; assert(pid >= 0); p = procfs_file_alloca(pid, "stat"); r = read_one_line_file(p, &line); if (r < 0) return r; p = strrchr(line, ')'); if (!p) return -EIO; p++; if (sscanf(p, " " "%*c " /* state */ "%*d " /* ppid */ "%*d " /* pgrp */ "%*d " /* session */ "%lu ", /* ttynr */ &ttynr) != 1) return -EIO; if (major(ttynr) == 0 && minor(ttynr) == 0) return -ENXIO; if (d) *d = (dev_t) ttynr; return 0; } int get_ctty(pid_t pid, dev_t *ret_devnr, char **ret) { _cleanup_free_ char *fn = NULL, *b = NULL; dev_t devnr; int r; r = get_ctty_devnr(pid, &devnr); if (r < 0) return r; r = device_path_make_canonical(S_IFCHR, devnr, &fn); if (r < 0) { if (r != -ENOENT) /* No symlink for this in /dev/char/? */ return r; if (major(devnr) == 136) { /* This is an ugly hack: PTY devices are not listed in /dev/char/, as they don't follow the * Linux device model. This means we have no nice way to match them up against their actual * device node. Let's hence do the check by the fixed, assigned major number. Normally we try * to avoid such fixed major/minor matches, but there appears to nother nice way to handle * this. */ if (asprintf(&b, "pts/%u", minor(devnr)) < 0) return -ENOMEM; } else { /* Probably something similar to the ptys which have no symlink in /dev/char/. Let's return * something vaguely useful. */ r = device_path_make_major_minor(S_IFCHR, devnr, &fn); if (r < 0) return r; } } if (!b) { const char *w; w = path_startswith(fn, "/dev/"); if (w) { b = strdup(w); if (!b) return -ENOMEM; } else b = TAKE_PTR(fn); } if (ret) *ret = TAKE_PTR(b); if (ret_devnr) *ret_devnr = devnr; return 0; } int ptsname_malloc(int fd, char **ret) { size_t l = 100; assert(fd >= 0); assert(ret); for (;;) { char *c; c = new(char, l); if (!c) return -ENOMEM; if (ptsname_r(fd, c, l) == 0) { *ret = c; return 0; } if (errno != ERANGE) { free(c); return -errno; } free(c); if (l > SIZE_MAX / 2) return -ENOMEM; l *= 2; } } int ptsname_namespace(int pty, char **ret) { int no = -1, r; /* Like ptsname(), but doesn't assume that the path is * accessible in the local namespace. */ r = ioctl(pty, TIOCGPTN, &no); if (r < 0) return -errno; if (no < 0) return -EIO; if (asprintf(ret, "/dev/pts/%i", no) < 0) return -ENOMEM; return 0; } int openpt_in_namespace(pid_t pid, int flags) { _cleanup_close_ int pidnsfd = -1, mntnsfd = -1, usernsfd = -1, rootfd = -1; _cleanup_close_pair_ int pair[2] = { -1, -1 }; pid_t child; int r; assert(pid > 0); r = namespace_open(pid, &pidnsfd, &mntnsfd, NULL, &usernsfd, &rootfd); if (r < 0) return r; if (socketpair(AF_UNIX, SOCK_DGRAM, 0, pair) < 0) return -errno; r = namespace_fork("(sd-openptns)", "(sd-openpt)", NULL, 0, FORK_RESET_SIGNALS|FORK_DEATHSIG, pidnsfd, mntnsfd, -1, usernsfd, rootfd, &child); if (r < 0) return r; if (r == 0) { int master; pair[0] = safe_close(pair[0]); master = posix_openpt(flags|O_NOCTTY|O_CLOEXEC); if (master < 0) _exit(EXIT_FAILURE); if (unlockpt(master) < 0) _exit(EXIT_FAILURE); if (send_one_fd(pair[1], master, 0) < 0) _exit(EXIT_FAILURE); _exit(EXIT_SUCCESS); } pair[1] = safe_close(pair[1]); r = wait_for_terminate_and_check("(sd-openptns)", child, 0); if (r < 0) return r; if (r != EXIT_SUCCESS) return -EIO; return receive_one_fd(pair[0], 0); } int open_terminal_in_namespace(pid_t pid, const char *name, int mode) { _cleanup_close_ int pidnsfd = -1, mntnsfd = -1, usernsfd = -1, rootfd = -1; _cleanup_close_pair_ int pair[2] = { -1, -1 }; pid_t child; int r; r = namespace_open(pid, &pidnsfd, &mntnsfd, NULL, &usernsfd, &rootfd); if (r < 0) return r; if (socketpair(AF_UNIX, SOCK_DGRAM, 0, pair) < 0) return -errno; r = namespace_fork("(sd-terminalns)", "(sd-terminal)", NULL, 0, FORK_RESET_SIGNALS|FORK_DEATHSIG, pidnsfd, mntnsfd, -1, usernsfd, rootfd, &child); if (r < 0) return r; if (r == 0) { int master; pair[0] = safe_close(pair[0]); master = open_terminal(name, mode|O_NOCTTY|O_CLOEXEC); if (master < 0) _exit(EXIT_FAILURE); if (send_one_fd(pair[1], master, 0) < 0) _exit(EXIT_FAILURE); _exit(EXIT_SUCCESS); } pair[1] = safe_close(pair[1]); r = wait_for_terminate_and_check("(sd-terminalns)", child, 0); if (r < 0) return r; if (r != EXIT_SUCCESS) return -EIO; return receive_one_fd(pair[0], 0); } static bool getenv_terminal_is_dumb(void) { const char *e; e = getenv("TERM"); if (!e) return true; return streq(e, "dumb"); } bool terminal_is_dumb(void) { if (!on_tty()) return true; return getenv_terminal_is_dumb(); } bool colors_enabled(void) { /* Returns true if colors are considered supported on our stdout. For that we check $SYSTEMD_COLORS first * (which is the explicit way to turn colors on/off). If that didn't work we turn colors off unless we are on a * TTY. And if we are on a TTY we turn it off if $TERM is set to "dumb". There's one special tweak though: if * we are PID 1 then we do not check whether we are connected to a TTY, because we don't keep /dev/console open * continuously due to fear of SAK, and hence things are a bit weird. */ if (cached_colors_enabled < 0) { int val; val = getenv_bool("SYSTEMD_COLORS"); if (val >= 0) cached_colors_enabled = val; else if (getpid_cached() == 1) /* PID1 outputs to the console without holding it open all the time */ cached_colors_enabled = !getenv_terminal_is_dumb(); else cached_colors_enabled = !terminal_is_dumb(); } return cached_colors_enabled; } bool dev_console_colors_enabled(void) { _cleanup_free_ char *s = NULL; int b; /* Returns true if we assume that color is supported on /dev/console. * * For that we first check if we explicitly got told to use colors or not, by checking $SYSTEMD_COLORS. If that * isn't set we check whether PID 1 has $TERM set, and if not, whether TERM is set on the kernel command * line. If we find $TERM set we assume color if it's not set to "dumb", similarly to how regular * colors_enabled() operates. */ b = getenv_bool("SYSTEMD_COLORS"); if (b >= 0) return b; if (getenv_for_pid(1, "TERM", &s) <= 0) (void) proc_cmdline_get_key("TERM", 0, &s); return !streq_ptr(s, "dumb"); } bool underline_enabled(void) { if (cached_underline_enabled < 0) { /* The Linux console doesn't support underlining, turn it off, but only there. */ if (colors_enabled()) cached_underline_enabled = !streq_ptr(getenv("TERM"), "linux"); else cached_underline_enabled = false; } return cached_underline_enabled; } int vt_default_utf8(void) { _cleanup_free_ char *b = NULL; int r; /* Read the default VT UTF8 setting from the kernel */ r = read_one_line_file("/sys/module/vt/parameters/default_utf8", &b); if (r < 0) return r; return parse_boolean(b); } int vt_verify_kbmode(int fd) { int curr_mode; /* * Make sure we only adjust consoles in K_XLATE or K_UNICODE mode. * Otherwise we would (likely) interfere with X11's processing of the * key events. * * http://lists.freedesktop.org/archives/systemd-devel/2013-February/008573.html */ if (ioctl(fd, KDGKBMODE, &curr_mode) < 0) return -errno; return IN_SET(curr_mode, K_XLATE, K_UNICODE) ? 0 : -EBUSY; } int vt_reset_keyboard(int fd) { int kb, r; /* If we can't read the default, then default to unicode. It's 2017 after all. */ kb = vt_default_utf8() != 0 ? K_UNICODE : K_XLATE; r = vt_verify_kbmode(fd); if (r == -EBUSY) { log_debug_errno(r, "Keyboard is not in XLATE or UNICODE mode, not resetting: %m"); return 0; } else if (r < 0) return r; if (ioctl(fd, KDSKBMODE, kb) < 0) return -errno; return 0; } int vt_restore(int fd) { static const struct vt_mode mode = { .mode = VT_AUTO, }; int r, q = 0; r = ioctl(fd, KDSETMODE, KD_TEXT); if (r < 0) q = log_debug_errno(errno, "Failed to set VT in text mode, ignoring: %m"); r = vt_reset_keyboard(fd); if (r < 0) { log_debug_errno(r, "Failed to reset keyboard mode, ignoring: %m"); if (q >= 0) q = r; } r = ioctl(fd, VT_SETMODE, &mode); if (r < 0) { log_debug_errno(errno, "Failed to set VT_AUTO mode, ignoring: %m"); if (q >= 0) q = -errno; } r = fchown(fd, 0, (gid_t) -1); if (r < 0) { log_debug_errno(errno, "Failed to chown VT, ignoring: %m"); if (q >= 0) q = -errno; } return q; } int vt_release(int fd, bool restore) { assert(fd >= 0); /* This function releases the VT by acknowledging the VT-switch signal * sent by the kernel and optionally reset the VT in text and auto * VT-switching modes. */ if (ioctl(fd, VT_RELDISP, 1) < 0) return -errno; if (restore) return vt_restore(fd); return 0; } void get_log_colors(int priority, const char **on, const char **off, const char **highlight) { /* Note that this will initialize output variables only when there's something to output. * The caller must pre-initalize to "" or NULL as appropriate. */ if (priority <= LOG_ERR) { if (on) *on = ANSI_HIGHLIGHT_RED; if (off) *off = ANSI_NORMAL; if (highlight) *highlight = ANSI_HIGHLIGHT; } else if (priority <= LOG_WARNING) { if (on) *on = ANSI_HIGHLIGHT_YELLOW; if (off) *off = ANSI_NORMAL; if (highlight) *highlight = ANSI_HIGHLIGHT; } else if (priority <= LOG_NOTICE) { if (on) *on = ANSI_HIGHLIGHT; if (off) *off = ANSI_NORMAL; if (highlight) *highlight = ANSI_HIGHLIGHT_RED; } else if (priority >= LOG_DEBUG) { if (on) *on = ANSI_GREY; if (off) *off = ANSI_NORMAL; if (highlight) *highlight = ANSI_HIGHLIGHT_RED; } }
./CrossVul/dataset_final_sorted/CWE-255/c/good_536_0
crossvul-cpp_data_good_2254_0
/* -*- mode: c; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 1993 OpenVision Technologies, Inc., All Rights Reserved * * $Header$ */ #include "k5-int.h" #include <sys/time.h> #include <kadm5/admin.h> #include <kdb.h> #include "server_internal.h" #ifdef USE_PASSWORD_SERVER #include <sys/wait.h> #include <signal.h> #endif #include <krb5/kadm5_hook_plugin.h> #ifdef USE_VALGRIND #include <valgrind/memcheck.h> #else #define VALGRIND_CHECK_DEFINED(LVALUE) ((void)0) #endif extern krb5_principal master_princ; extern krb5_principal hist_princ; extern krb5_keyblock master_keyblock; extern krb5_db_entry master_db; static int decrypt_key_data(krb5_context context, int n_key_data, krb5_key_data *key_data, krb5_keyblock **keyblocks, int *n_keys); static krb5_error_code kadm5_copy_principal(krb5_context context, krb5_const_principal inprinc, krb5_principal *outprinc) { register krb5_principal tempprinc; register int i, nelems; tempprinc = (krb5_principal)krb5_db_alloc(context, NULL, sizeof(krb5_principal_data)); if (tempprinc == 0) return ENOMEM; VALGRIND_CHECK_DEFINED(*inprinc); *tempprinc = *inprinc; nelems = (int) krb5_princ_size(context, inprinc); tempprinc->data = krb5_db_alloc(context, NULL, nelems * sizeof(krb5_data)); if (tempprinc->data == 0) { krb5_db_free(context, (char *)tempprinc); return ENOMEM; } for (i = 0; i < nelems; i++) { unsigned int len = krb5_princ_component(context, inprinc, i)->length; krb5_princ_component(context, tempprinc, i)->length = len; if (((krb5_princ_component(context, tempprinc, i)->data = krb5_db_alloc(context, NULL, len)) == 0) && len) { while (--i >= 0) krb5_db_free(context, krb5_princ_component(context, tempprinc, i)->data); krb5_db_free (context, tempprinc->data); krb5_db_free (context, tempprinc); return ENOMEM; } if (len) memcpy(krb5_princ_component(context, tempprinc, i)->data, krb5_princ_component(context, inprinc, i)->data, len); krb5_princ_component(context, tempprinc, i)->magic = KV5M_DATA; } tempprinc->realm.data = krb5_db_alloc(context, NULL, tempprinc->realm.length = inprinc->realm.length); if (!tempprinc->realm.data && tempprinc->realm.length) { for (i = 0; i < nelems; i++) krb5_db_free(context, krb5_princ_component(context, tempprinc, i)->data); krb5_db_free(context, tempprinc->data); krb5_db_free(context, tempprinc); return ENOMEM; } if (tempprinc->realm.length) memcpy(tempprinc->realm.data, inprinc->realm.data, inprinc->realm.length); *outprinc = tempprinc; return 0; } static void kadm5_free_principal(krb5_context context, krb5_principal val) { register krb5_int32 i; if (!val) return; if (val->data) { i = krb5_princ_size(context, val); while(--i >= 0) krb5_db_free(context, krb5_princ_component(context, val, i)->data); krb5_db_free(context, val->data); } if (val->realm.data) krb5_db_free(context, val->realm.data); krb5_db_free(context, val); } /* * XXX Functions that ought to be in libkrb5.a, but aren't. */ kadm5_ret_t krb5_copy_key_data_contents(context, from, to) krb5_context context; krb5_key_data *from, *to; { int i, idx; *to = *from; idx = (from->key_data_ver == 1 ? 1 : 2); for (i = 0; i < idx; i++) { if ( from->key_data_length[i] ) { to->key_data_contents[i] = malloc(from->key_data_length[i]); if (to->key_data_contents[i] == NULL) { for (i = 0; i < idx; i++) { if (to->key_data_contents[i]) { memset(to->key_data_contents[i], 0, to->key_data_length[i]); free(to->key_data_contents[i]); } } return ENOMEM; } memcpy(to->key_data_contents[i], from->key_data_contents[i], from->key_data_length[i]); } } return 0; } static krb5_tl_data *dup_tl_data(krb5_tl_data *tl) { krb5_tl_data *n; n = (krb5_tl_data *) malloc(sizeof(krb5_tl_data)); if (n == NULL) return NULL; n->tl_data_contents = malloc(tl->tl_data_length); if (n->tl_data_contents == NULL) { free(n); return NULL; } memcpy(n->tl_data_contents, tl->tl_data_contents, tl->tl_data_length); n->tl_data_type = tl->tl_data_type; n->tl_data_length = tl->tl_data_length; n->tl_data_next = NULL; return n; } /* This is in lib/kdb/kdb_cpw.c, but is static */ static void cleanup_key_data(context, count, data) krb5_context context; int count; krb5_key_data * data; { int i, j; for (i = 0; i < count; i++) for (j = 0; j < data[i].key_data_ver; j++) if (data[i].key_data_length[j]) krb5_db_free(context, data[i].key_data_contents[j]); krb5_db_free(context, data); } /* Check whether a ks_tuple is present in an array of ks_tuples. */ static krb5_boolean ks_tuple_present(int n_ks_tuple, krb5_key_salt_tuple *ks_tuple, krb5_key_salt_tuple *looking_for) { int i; for (i = 0; i < n_ks_tuple; i++) { if (ks_tuple[i].ks_enctype == looking_for->ks_enctype && ks_tuple[i].ks_salttype == looking_for->ks_salttype) return TRUE; } return FALSE; } /* Fetch a policy if it exists; set *have_pol_out appropriately. Return * success whether or not the policy exists. */ static kadm5_ret_t get_policy(kadm5_server_handle_t handle, const char *name, kadm5_policy_ent_t policy_out, krb5_boolean *have_pol_out) { kadm5_ret_t ret; *have_pol_out = FALSE; if (name == NULL) return 0; ret = kadm5_get_policy(handle->lhandle, (char *)name, policy_out); if (ret == 0) *have_pol_out = TRUE; return (ret == KADM5_UNK_POLICY) ? 0 : ret; } /* * Apply the -allowedkeysalts policy (see kadmin(1)'s addpol/modpol * commands). We use the allowed key/salt tuple list as a default if * no ks tuples as provided by the caller. We reject lists that include * key/salts outside the policy. We re-order the requested ks tuples * (which may be a subset of the policy) to reflect the policy order. */ static kadm5_ret_t apply_keysalt_policy(kadm5_server_handle_t handle, const char *policy, int n_ks_tuple, krb5_key_salt_tuple *ks_tuple, int *new_n_kstp, krb5_key_salt_tuple **new_kstp) { kadm5_ret_t ret; kadm5_policy_ent_rec polent; krb5_boolean have_polent; int ak_n_ks_tuple = 0; int new_n_ks_tuple = 0; krb5_key_salt_tuple *ak_ks_tuple = NULL; krb5_key_salt_tuple *new_ks_tuple = NULL; krb5_key_salt_tuple *subset; int i, m; if (new_n_kstp != NULL) { *new_n_kstp = 0; *new_kstp = NULL; } memset(&polent, 0, sizeof(polent)); ret = get_policy(handle, policy, &polent, &have_polent); if (ret) goto cleanup; if (polent.allowed_keysalts == NULL) { /* Requested keysalts allowed or default to supported_enctypes. */ if (n_ks_tuple == 0) { /* Default to supported_enctypes. */ n_ks_tuple = handle->params.num_keysalts; ks_tuple = handle->params.keysalts; } /* Dup the requested or defaulted keysalt tuples. */ new_ks_tuple = malloc(n_ks_tuple * sizeof(*new_ks_tuple)); if (new_ks_tuple == NULL) { ret = ENOMEM; goto cleanup; } memcpy(new_ks_tuple, ks_tuple, n_ks_tuple * sizeof(*new_ks_tuple)); new_n_ks_tuple = n_ks_tuple; ret = 0; goto cleanup; } ret = krb5_string_to_keysalts(polent.allowed_keysalts, ",", /* Tuple separators */ NULL, /* Key/salt separators */ 0, /* No duplicates */ &ak_ks_tuple, &ak_n_ks_tuple); /* * Malformed policy? Shouldn't happen, but it's remotely possible * someday, so we don't assert, just bail. */ if (ret) goto cleanup; /* Check that the requested ks_tuples are within policy, if we have one. */ for (i = 0; i < n_ks_tuple; i++) { if (!ks_tuple_present(ak_n_ks_tuple, ak_ks_tuple, &ks_tuple[i])) { ret = KADM5_BAD_KEYSALTS; goto cleanup; } } /* Have policy but no ks_tuple input? Output the policy. */ if (n_ks_tuple == 0) { new_n_ks_tuple = ak_n_ks_tuple; new_ks_tuple = ak_ks_tuple; ak_ks_tuple = NULL; goto cleanup; } /* * Now filter the policy ks tuples by the requested ones so as to * preserve in the requested sub-set the relative ordering from the * policy. We could optimize this (if (n_ks_tuple == ak_n_ks_tuple) * then skip this), but we don't bother. */ subset = calloc(n_ks_tuple, sizeof(*subset)); if (subset == NULL) { ret = ENOMEM; goto cleanup; } for (m = 0, i = 0; i < ak_n_ks_tuple && m < n_ks_tuple; i++) { if (ks_tuple_present(n_ks_tuple, ks_tuple, &ak_ks_tuple[i])) subset[m++] = ak_ks_tuple[i]; } new_ks_tuple = subset; new_n_ks_tuple = m; ret = 0; cleanup: if (have_polent) kadm5_free_policy_ent(handle->lhandle, &polent); free(ak_ks_tuple); if (new_n_kstp != NULL) { *new_n_kstp = new_n_ks_tuple; *new_kstp = new_ks_tuple; } else { free(new_ks_tuple); } return ret; } /* * Set *passptr to NULL if the request looks like the first part of a krb5 1.6 * addprinc -randkey operation. The krb5 1.6 dummy password for these requests * was invalid UTF-8, which runs afoul of the arcfour string-to-key. */ static void check_1_6_dummy(kadm5_principal_ent_t entry, long mask, int n_ks_tuple, krb5_key_salt_tuple *ks_tuple, char **passptr) { int i; char *password = *passptr; /* Old-style randkey operations disallowed tickets to start. */ if (password == NULL || !(mask & KADM5_ATTRIBUTES) || !(entry->attributes & KRB5_KDB_DISALLOW_ALL_TIX)) return; /* The 1.6 dummy password was the octets 1..255. */ for (i = 0; (unsigned char) password[i] == i + 1; i++); if (password[i] != '\0' || i != 255) return; /* This will make the caller use a random password instead. */ *passptr = NULL; } /* Return the number of keys with the newest kvno. Assumes that all key data * with the newest kvno are at the front of the key data array. */ static int count_new_keys(int n_key_data, krb5_key_data *key_data) { int n; for (n = 1; n < n_key_data; n++) { if (key_data[n - 1].key_data_kvno != key_data[n].key_data_kvno) return n; } return n_key_data; } kadm5_ret_t kadm5_create_principal(void *server_handle, kadm5_principal_ent_t entry, long mask, char *password) { return kadm5_create_principal_3(server_handle, entry, mask, 0, NULL, password); } kadm5_ret_t kadm5_create_principal_3(void *server_handle, kadm5_principal_ent_t entry, long mask, int n_ks_tuple, krb5_key_salt_tuple *ks_tuple, char *password) { krb5_db_entry *kdb; osa_princ_ent_rec adb; kadm5_policy_ent_rec polent; krb5_boolean have_polent = FALSE; krb5_int32 now; krb5_tl_data *tl_data_tail; unsigned int ret; kadm5_server_handle_t handle = server_handle; krb5_keyblock *act_mkey; krb5_kvno act_kvno; int new_n_ks_tuple = 0; krb5_key_salt_tuple *new_ks_tuple = NULL; CHECK_HANDLE(server_handle); krb5_clear_error_message(handle->context); check_1_6_dummy(entry, mask, n_ks_tuple, ks_tuple, &password); /* * Argument sanity checking, and opening up the DB */ if(!(mask & KADM5_PRINCIPAL) || (mask & KADM5_MOD_NAME) || (mask & KADM5_MOD_TIME) || (mask & KADM5_LAST_PWD_CHANGE) || (mask & KADM5_MKVNO) || (mask & KADM5_AUX_ATTRIBUTES) || (mask & KADM5_LAST_SUCCESS) || (mask & KADM5_LAST_FAILED) || (mask & KADM5_FAIL_AUTH_COUNT)) return KADM5_BAD_MASK; if ((mask & KADM5_KEY_DATA) && entry->n_key_data != 0) return KADM5_BAD_MASK; if((mask & KADM5_POLICY) && (mask & KADM5_POLICY_CLR)) return KADM5_BAD_MASK; if((mask & ~ALL_PRINC_MASK)) return KADM5_BAD_MASK; if (entry == NULL) return EINVAL; /* * Check to see if the principal exists */ ret = kdb_get_entry(handle, entry->principal, &kdb, &adb); switch(ret) { case KADM5_UNK_PRINC: break; case 0: kdb_free_entry(handle, kdb, &adb); return KADM5_DUP; default: return ret; } kdb = krb5_db_alloc(handle->context, NULL, sizeof(*kdb)); if (kdb == NULL) return ENOMEM; memset(kdb, 0, sizeof(*kdb)); memset(&adb, 0, sizeof(osa_princ_ent_rec)); /* * If a policy was specified, load it. * If we can not find the one specified return an error */ if ((mask & KADM5_POLICY)) { ret = get_policy(handle, entry->policy, &polent, &have_polent); if (ret) goto cleanup; } if (password) { ret = passwd_check(handle, password, have_polent ? &polent : NULL, entry->principal); if (ret) goto cleanup; } /* * Start populating the various DB fields, using the * "defaults" for fields that were not specified by the * mask. */ if ((ret = krb5_timeofday(handle->context, &now))) goto cleanup; kdb->magic = KRB5_KDB_MAGIC_NUMBER; kdb->len = KRB5_KDB_V1_BASE_LENGTH; /* gag me with a chainsaw */ if ((mask & KADM5_ATTRIBUTES)) kdb->attributes = entry->attributes; else kdb->attributes = handle->params.flags; if ((mask & KADM5_MAX_LIFE)) kdb->max_life = entry->max_life; else kdb->max_life = handle->params.max_life; if (mask & KADM5_MAX_RLIFE) kdb->max_renewable_life = entry->max_renewable_life; else kdb->max_renewable_life = handle->params.max_rlife; if ((mask & KADM5_PRINC_EXPIRE_TIME)) kdb->expiration = entry->princ_expire_time; else kdb->expiration = handle->params.expiration; kdb->pw_expiration = 0; if (have_polent) { if(polent.pw_max_life) kdb->pw_expiration = now + polent.pw_max_life; else kdb->pw_expiration = 0; } if ((mask & KADM5_PW_EXPIRATION)) kdb->pw_expiration = entry->pw_expiration; kdb->last_success = 0; kdb->last_failed = 0; kdb->fail_auth_count = 0; /* this is kind of gross, but in order to free the tl data, I need to free the entire kdb entry, and that will try to free the principal. */ if ((ret = kadm5_copy_principal(handle->context, entry->principal, &(kdb->princ)))) goto cleanup; if ((ret = krb5_dbe_update_last_pwd_change(handle->context, kdb, now))) goto cleanup; if (mask & KADM5_TL_DATA) { /* splice entry->tl_data onto the front of kdb->tl_data */ for (tl_data_tail = entry->tl_data; tl_data_tail; tl_data_tail = tl_data_tail->tl_data_next) { ret = krb5_dbe_update_tl_data(handle->context, kdb, tl_data_tail); if( ret ) goto cleanup; } } /* * We need to have setup the TL data, so we have strings, so we can * check enctype policy, which is why we check/initialize ks_tuple * this late. */ ret = apply_keysalt_policy(handle, entry->policy, n_ks_tuple, ks_tuple, &new_n_ks_tuple, &new_ks_tuple); if (ret) goto cleanup; /* initialize the keys */ ret = kdb_get_active_mkey(handle, &act_kvno, &act_mkey); if (ret) goto cleanup; if (mask & KADM5_KEY_DATA) { /* The client requested no keys for this principal. */ assert(entry->n_key_data == 0); } else if (password) { ret = krb5_dbe_cpw(handle->context, act_mkey, new_ks_tuple, new_n_ks_tuple, password, (mask & KADM5_KVNO)?entry->kvno:1, FALSE, kdb); } else { /* Null password means create with random key (new in 1.8). */ ret = krb5_dbe_crk(handle->context, &master_keyblock, new_ks_tuple, new_n_ks_tuple, FALSE, kdb); } if (ret) goto cleanup; /* Record the master key VNO used to encrypt this entry's keys */ ret = krb5_dbe_update_mkvno(handle->context, kdb, act_kvno); if (ret) goto cleanup; ret = k5_kadm5_hook_create(handle->context, handle->hook_handles, KADM5_HOOK_STAGE_PRECOMMIT, entry, mask, new_n_ks_tuple, new_ks_tuple, password); if (ret) goto cleanup; /* populate the admin-server-specific fields. In the OV server, this used to be in a separate database. Since there's already marshalling code for the admin fields, to keep things simple, I'm going to keep it, and make all the admin stuff occupy a single tl_data record, */ adb.admin_history_kvno = INITIAL_HIST_KVNO; if (mask & KADM5_POLICY) { adb.aux_attributes = KADM5_POLICY; /* this does *not* need to be strdup'ed, because adb is xdr */ /* encoded in osa_adb_create_princ, and not ever freed */ adb.policy = entry->policy; } /* In all cases key and the principal data is set, let the database provider know */ kdb->mask = mask | KADM5_KEY_DATA | KADM5_PRINCIPAL ; /* store the new db entry */ ret = kdb_put_entry(handle, kdb, &adb); (void) k5_kadm5_hook_create(handle->context, handle->hook_handles, KADM5_HOOK_STAGE_POSTCOMMIT, entry, mask, new_n_ks_tuple, new_ks_tuple, password); cleanup: free(new_ks_tuple); krb5_db_free_principal(handle->context, kdb); if (have_polent) (void) kadm5_free_policy_ent(handle->lhandle, &polent); return ret; } kadm5_ret_t kadm5_delete_principal(void *server_handle, krb5_principal principal) { unsigned int ret; krb5_db_entry *kdb; osa_princ_ent_rec adb; kadm5_server_handle_t handle = server_handle; CHECK_HANDLE(server_handle); krb5_clear_error_message(handle->context); if (principal == NULL) return EINVAL; if ((ret = kdb_get_entry(handle, principal, &kdb, &adb))) return(ret); ret = k5_kadm5_hook_remove(handle->context, handle->hook_handles, KADM5_HOOK_STAGE_PRECOMMIT, principal); if (ret) { kdb_free_entry(handle, kdb, &adb); return ret; } ret = kdb_delete_entry(handle, principal); kdb_free_entry(handle, kdb, &adb); if (ret == 0) (void) k5_kadm5_hook_remove(handle->context, handle->hook_handles, KADM5_HOOK_STAGE_POSTCOMMIT, principal); return ret; } kadm5_ret_t kadm5_modify_principal(void *server_handle, kadm5_principal_ent_t entry, long mask) { int ret, ret2, i; kadm5_policy_ent_rec pol; krb5_boolean have_pol = FALSE; krb5_db_entry *kdb; krb5_tl_data *tl_data_orig; osa_princ_ent_rec adb; kadm5_server_handle_t handle = server_handle; CHECK_HANDLE(server_handle); krb5_clear_error_message(handle->context); if((mask & KADM5_PRINCIPAL) || (mask & KADM5_LAST_PWD_CHANGE) || (mask & KADM5_MOD_TIME) || (mask & KADM5_MOD_NAME) || (mask & KADM5_MKVNO) || (mask & KADM5_AUX_ATTRIBUTES) || (mask & KADM5_KEY_DATA) || (mask & KADM5_LAST_SUCCESS) || (mask & KADM5_LAST_FAILED)) return KADM5_BAD_MASK; if((mask & ~ALL_PRINC_MASK)) return KADM5_BAD_MASK; if((mask & KADM5_POLICY) && (mask & KADM5_POLICY_CLR)) return KADM5_BAD_MASK; if(entry == (kadm5_principal_ent_t) NULL) return EINVAL; if (mask & KADM5_TL_DATA) { tl_data_orig = entry->tl_data; while (tl_data_orig) { if (tl_data_orig->tl_data_type < 256) return KADM5_BAD_TL_TYPE; tl_data_orig = tl_data_orig->tl_data_next; } } ret = kdb_get_entry(handle, entry->principal, &kdb, &adb); if (ret) return(ret); /* * This is pretty much the same as create ... */ if ((mask & KADM5_POLICY)) { ret = get_policy(handle, entry->policy, &pol, &have_pol); if (ret) goto done; /* set us up to use the new policy */ adb.aux_attributes |= KADM5_POLICY; if (adb.policy) free(adb.policy); adb.policy = strdup(entry->policy); } if (have_pol) { /* set pw_max_life based on new policy */ if (pol.pw_max_life) { ret = krb5_dbe_lookup_last_pwd_change(handle->context, kdb, &(kdb->pw_expiration)); if (ret) goto done; kdb->pw_expiration += pol.pw_max_life; } else { kdb->pw_expiration = 0; } } if ((mask & KADM5_POLICY_CLR) && (adb.aux_attributes & KADM5_POLICY)) { free(adb.policy); adb.policy = NULL; adb.aux_attributes &= ~KADM5_POLICY; kdb->pw_expiration = 0; } if ((mask & KADM5_ATTRIBUTES)) kdb->attributes = entry->attributes; if ((mask & KADM5_MAX_LIFE)) kdb->max_life = entry->max_life; if ((mask & KADM5_PRINC_EXPIRE_TIME)) kdb->expiration = entry->princ_expire_time; if (mask & KADM5_PW_EXPIRATION) kdb->pw_expiration = entry->pw_expiration; if (mask & KADM5_MAX_RLIFE) kdb->max_renewable_life = entry->max_renewable_life; if((mask & KADM5_KVNO)) { for (i = 0; i < kdb->n_key_data; i++) kdb->key_data[i].key_data_kvno = entry->kvno; } if (mask & KADM5_TL_DATA) { krb5_tl_data *tl; /* may have to change the version number of the API. Updates the list with the given tl_data rather than over-writting */ for (tl = entry->tl_data; tl; tl = tl->tl_data_next) { ret = krb5_dbe_update_tl_data(handle->context, kdb, tl); if( ret ) { goto done; } } } /* * Setting entry->fail_auth_count to 0 can be used to manually unlock * an account. It is not possible to set fail_auth_count to any other * value using kadmin. */ if (mask & KADM5_FAIL_AUTH_COUNT) { if (entry->fail_auth_count != 0) { ret = KADM5_BAD_SERVER_PARAMS; goto done; } kdb->fail_auth_count = 0; } /* let the mask propagate to the database provider */ kdb->mask = mask; ret = k5_kadm5_hook_modify(handle->context, handle->hook_handles, KADM5_HOOK_STAGE_PRECOMMIT, entry, mask); if (ret) goto done; ret = kdb_put_entry(handle, kdb, &adb); if (ret) goto done; (void) k5_kadm5_hook_modify(handle->context, handle->hook_handles, KADM5_HOOK_STAGE_POSTCOMMIT, entry, mask); ret = KADM5_OK; done: if (have_pol) { ret2 = kadm5_free_policy_ent(handle->lhandle, &pol); ret = ret ? ret : ret2; } kdb_free_entry(handle, kdb, &adb); return ret; } kadm5_ret_t kadm5_rename_principal(void *server_handle, krb5_principal source, krb5_principal target) { krb5_db_entry *kdb; osa_princ_ent_rec adb; krb5_error_code ret; kadm5_server_handle_t handle = server_handle; krb5_int16 stype, i; krb5_data *salt = NULL; CHECK_HANDLE(server_handle); krb5_clear_error_message(handle->context); if (source == NULL || target == NULL) return EINVAL; if ((ret = kdb_get_entry(handle, target, &kdb, &adb)) == 0) { kdb_free_entry(handle, kdb, &adb); return(KADM5_DUP); } if ((ret = kdb_get_entry(handle, source, &kdb, &adb))) return ret; /* Transform salts as necessary. */ for (i = 0; i < kdb->n_key_data; i++) { ret = krb5_dbe_compute_salt(handle->context, &kdb->key_data[i], kdb->princ, &stype, &salt); if (ret == KRB5_KDB_BAD_SALTTYPE) ret = KADM5_NO_RENAME_SALT; if (ret) goto done; kdb->key_data[i].key_data_type[1] = KRB5_KDB_SALTTYPE_SPECIAL; free(kdb->key_data[i].key_data_contents[1]); kdb->key_data[i].key_data_contents[1] = (krb5_octet *)salt->data; kdb->key_data[i].key_data_length[1] = salt->length; kdb->key_data[i].key_data_ver = 2; free(salt); salt = NULL; } kadm5_free_principal(handle->context, kdb->princ); ret = kadm5_copy_principal(handle->context, target, &kdb->princ); if (ret) { kdb->princ = NULL; /* so freeing the dbe doesn't lose */ goto done; } if ((ret = kdb_put_entry(handle, kdb, &adb))) goto done; ret = kdb_delete_entry(handle, source); done: krb5_free_data(handle->context, salt); kdb_free_entry(handle, kdb, &adb); return ret; } kadm5_ret_t kadm5_get_principal(void *server_handle, krb5_principal principal, kadm5_principal_ent_t entry, long in_mask) { krb5_db_entry *kdb; osa_princ_ent_rec adb; krb5_error_code ret = 0; long mask; int i; kadm5_server_handle_t handle = server_handle; CHECK_HANDLE(server_handle); krb5_clear_error_message(handle->context); /* * In version 1, all the defined fields are always returned. * entry is a pointer to a kadm5_principal_ent_t_v1 that should be * filled with allocated memory. */ mask = in_mask; memset(entry, 0, sizeof(*entry)); if (principal == NULL) return EINVAL; if ((ret = kdb_get_entry(handle, principal, &kdb, &adb))) return ret; if ((mask & KADM5_POLICY) && adb.policy && (adb.aux_attributes & KADM5_POLICY)) { if ((entry->policy = strdup(adb.policy)) == NULL) { ret = ENOMEM; goto done; } } if (mask & KADM5_AUX_ATTRIBUTES) entry->aux_attributes = adb.aux_attributes; if ((mask & KADM5_PRINCIPAL) && (ret = krb5_copy_principal(handle->context, kdb->princ, &entry->principal))) { goto done; } if (mask & KADM5_PRINC_EXPIRE_TIME) entry->princ_expire_time = kdb->expiration; if ((mask & KADM5_LAST_PWD_CHANGE) && (ret = krb5_dbe_lookup_last_pwd_change(handle->context, kdb, &(entry->last_pwd_change)))) { goto done; } if (mask & KADM5_PW_EXPIRATION) entry->pw_expiration = kdb->pw_expiration; if (mask & KADM5_MAX_LIFE) entry->max_life = kdb->max_life; /* this is a little non-sensical because the function returns two */ /* values that must be checked separately against the mask */ if ((mask & KADM5_MOD_NAME) || (mask & KADM5_MOD_TIME)) { ret = krb5_dbe_lookup_mod_princ_data(handle->context, kdb, &(entry->mod_date), &(entry->mod_name)); if (ret) { goto done; } if (! (mask & KADM5_MOD_TIME)) entry->mod_date = 0; if (! (mask & KADM5_MOD_NAME)) { krb5_free_principal(handle->context, entry->mod_name); entry->mod_name = NULL; } } if (mask & KADM5_ATTRIBUTES) entry->attributes = kdb->attributes; if (mask & KADM5_KVNO) for (entry->kvno = 0, i=0; i<kdb->n_key_data; i++) if ((krb5_kvno) kdb->key_data[i].key_data_kvno > entry->kvno) entry->kvno = kdb->key_data[i].key_data_kvno; if (mask & KADM5_MKVNO) { ret = krb5_dbe_get_mkvno(handle->context, kdb, &entry->mkvno); if (ret) goto done; } if (mask & KADM5_MAX_RLIFE) entry->max_renewable_life = kdb->max_renewable_life; if (mask & KADM5_LAST_SUCCESS) entry->last_success = kdb->last_success; if (mask & KADM5_LAST_FAILED) entry->last_failed = kdb->last_failed; if (mask & KADM5_FAIL_AUTH_COUNT) entry->fail_auth_count = kdb->fail_auth_count; if (mask & KADM5_TL_DATA) { krb5_tl_data *tl, *tl2; entry->tl_data = NULL; tl = kdb->tl_data; while (tl) { if (tl->tl_data_type > 255) { if ((tl2 = dup_tl_data(tl)) == NULL) { ret = ENOMEM; goto done; } tl2->tl_data_next = entry->tl_data; entry->tl_data = tl2; entry->n_tl_data++; } tl = tl->tl_data_next; } } if (mask & KADM5_KEY_DATA) { entry->n_key_data = kdb->n_key_data; if(entry->n_key_data) { entry->key_data = k5calloc(entry->n_key_data, sizeof(krb5_key_data), &ret); if (entry->key_data == NULL) goto done; } else entry->key_data = NULL; for (i = 0; i < entry->n_key_data; i++) ret = krb5_copy_key_data_contents(handle->context, &kdb->key_data[i], &entry->key_data[i]); if (ret) goto done; } ret = KADM5_OK; done: if (ret && entry->principal) { krb5_free_principal(handle->context, entry->principal); entry->principal = NULL; } kdb_free_entry(handle, kdb, &adb); return ret; } /* * Function: check_pw_reuse * * Purpose: Check if a key appears in a list of keys, in order to * enforce password history. * * Arguments: * * context (r) the krb5 context * hist_keyblock (r) the key that hist_key_data is * encrypted in * n_new_key_data (r) length of new_key_data * new_key_data (r) keys to check against * pw_hist_data, encrypted in hist_keyblock * n_pw_hist_data (r) length of pw_hist_data * pw_hist_data (r) passwords to check new_key_data against * * Effects: * For each new_key in new_key_data: * decrypt new_key with the master_keyblock * for each password in pw_hist_data: * for each hist_key in password: * decrypt hist_key with hist_keyblock * compare the new_key and hist_key * * Returns krb5 errors, KADM5_PASS_RESUSE if a key in * new_key_data is the same as a key in pw_hist_data, or 0. */ static kadm5_ret_t check_pw_reuse(krb5_context context, krb5_keyblock *hist_keyblocks, int n_new_key_data, krb5_key_data *new_key_data, unsigned int n_pw_hist_data, osa_pw_hist_ent *pw_hist_data) { unsigned int x, y, z; krb5_keyblock newkey, histkey, *kb; krb5_key_data *key_data; krb5_error_code ret; assert (n_new_key_data >= 0); for (x = 0; x < (unsigned) n_new_key_data; x++) { /* Check only entries with the most recent kvno. */ if (new_key_data[x].key_data_kvno != new_key_data[0].key_data_kvno) break; ret = krb5_dbe_decrypt_key_data(context, NULL, &(new_key_data[x]), &newkey, NULL); if (ret) return(ret); for (y = 0; y < n_pw_hist_data; y++) { for (z = 0; z < (unsigned int) pw_hist_data[y].n_key_data; z++) { for (kb = hist_keyblocks; kb->enctype != 0; kb++) { key_data = &pw_hist_data[y].key_data[z]; ret = krb5_dbe_decrypt_key_data(context, kb, key_data, &histkey, NULL); if (ret) continue; if (newkey.length == histkey.length && newkey.enctype == histkey.enctype && memcmp(newkey.contents, histkey.contents, histkey.length) == 0) { krb5_free_keyblock_contents(context, &histkey); krb5_free_keyblock_contents(context, &newkey); return KADM5_PASS_REUSE; } krb5_free_keyblock_contents(context, &histkey); } } } krb5_free_keyblock_contents(context, &newkey); } return(0); } /* * Function: create_history_entry * * Purpose: Creates a password history entry from an array of * key_data. * * Arguments: * * context (r) krb5_context to use * mkey (r) master keyblock to decrypt key data with * hist_key (r) history keyblock to encrypt key data with * n_key_data (r) number of elements in key_data * key_data (r) keys to add to the history entry * hist (w) history entry to fill in * * Effects: * * hist->key_data is allocated to store n_key_data key_datas. Each * element of key_data is decrypted with master_keyblock, re-encrypted * in hist_key, and added to hist->key_data. hist->n_key_data is * set to n_key_data. */ static int create_history_entry(krb5_context context, krb5_keyblock *hist_key, int n_key_data, krb5_key_data *key_data, osa_pw_hist_ent *hist) { krb5_error_code ret; krb5_keyblock key; krb5_keysalt salt; int i; hist->key_data = k5calloc(n_key_data, sizeof(krb5_key_data), &ret); if (hist->key_data == NULL) return ret; for (i = 0; i < n_key_data; i++) { ret = krb5_dbe_decrypt_key_data(context, NULL, &key_data[i], &key, &salt); if (ret) return ret; ret = krb5_dbe_encrypt_key_data(context, hist_key, &key, &salt, key_data[i].key_data_kvno, &hist->key_data[i]); if (ret) return ret; krb5_free_keyblock_contents(context, &key); /* krb5_free_keysalt(context, &salt); */ } hist->n_key_data = n_key_data; return 0; } static void free_history_entry(krb5_context context, osa_pw_hist_ent *hist) { int i; for (i = 0; i < hist->n_key_data; i++) krb5_free_key_data_contents(context, &hist->key_data[i]); free(hist->key_data); } /* * Function: add_to_history * * Purpose: Adds a password to a principal's password history. * * Arguments: * * context (r) krb5_context to use * hist_kvno (r) kvno of current history key * adb (r/w) admin principal entry to add keys to * pol (r) adb's policy * pw (r) keys for the password to add to adb's key history * * Effects: * * add_to_history adds a single password to adb's password history. * pw contains n_key_data keys in its key_data, in storage should be * allocated but not freed by the caller (XXX blech!). * * This function maintains adb->old_keys as a circular queue. It * starts empty, and grows each time this function is called until it * is pol->pw_history_num items long. adb->old_key_len holds the * number of allocated entries in the array, and must therefore be [0, * pol->pw_history_num). adb->old_key_next is the index into the * array where the next element should be written, and must be [0, * adb->old_key_len). */ static kadm5_ret_t add_to_history(krb5_context context, krb5_kvno hist_kvno, osa_princ_ent_t adb, kadm5_policy_ent_t pol, osa_pw_hist_ent *pw) { osa_pw_hist_ent *histp; uint32_t nhist; unsigned int i, knext, nkeys; nhist = pol->pw_history_num; /* A history of 1 means just check the current password */ if (nhist <= 1) return 0; if (adb->admin_history_kvno != hist_kvno) { /* The history key has changed since the last password change, so we * have to reset the password history. */ free(adb->old_keys); adb->old_keys = NULL; adb->old_key_len = 0; adb->old_key_next = 0; adb->admin_history_kvno = hist_kvno; } nkeys = adb->old_key_len; knext = adb->old_key_next; /* resize the adb->old_keys array if necessary */ if (nkeys + 1 < nhist) { if (adb->old_keys == NULL) { adb->old_keys = (osa_pw_hist_ent *) malloc((nkeys + 1) * sizeof (osa_pw_hist_ent)); } else { adb->old_keys = (osa_pw_hist_ent *) realloc(adb->old_keys, (nkeys + 1) * sizeof (osa_pw_hist_ent)); } if (adb->old_keys == NULL) return(ENOMEM); memset(&adb->old_keys[nkeys], 0, sizeof(osa_pw_hist_ent)); nkeys = ++adb->old_key_len; /* * To avoid losing old keys, shift forward each entry after * knext. */ for (i = nkeys - 1; i > knext; i--) { adb->old_keys[i] = adb->old_keys[i - 1]; } memset(&adb->old_keys[knext], 0, sizeof(osa_pw_hist_ent)); } else if (nkeys + 1 > nhist) { /* * The policy must have changed! Shrink the array. * Can't simply realloc() down, since it might be wrapped. * To understand the arithmetic below, note that we are * copying into new positions 0 .. N-1 from old positions * old_key_next-N .. old_key_next-1, modulo old_key_len, * where N = pw_history_num - 1 is the length of the * shortened list. Matt Crawford, FNAL */ /* * M = adb->old_key_len, N = pol->pw_history_num - 1 * * tmp[0] .. tmp[N-1] = old[(knext-N)%M] .. old[(knext-1)%M] */ int j; osa_pw_hist_t tmp; tmp = (osa_pw_hist_ent *) malloc((nhist - 1) * sizeof (osa_pw_hist_ent)); if (tmp == NULL) return ENOMEM; for (i = 0; i < nhist - 1; i++) { /* * Add nkeys once before taking remainder to avoid * negative values. */ j = (i + nkeys + knext - (nhist - 1)) % nkeys; tmp[i] = adb->old_keys[j]; } /* Now free the ones we don't keep (the oldest ones) */ for (i = 0; i < nkeys - (nhist - 1); i++) { j = (i + nkeys + knext) % nkeys; histp = &adb->old_keys[j]; for (j = 0; j < histp->n_key_data; j++) { krb5_free_key_data_contents(context, &histp->key_data[j]); } free(histp->key_data); } free(adb->old_keys); adb->old_keys = tmp; nkeys = adb->old_key_len = nhist - 1; knext = adb->old_key_next = 0; } /* * If nhist decreased since the last password change, and nkeys+1 * is less than the previous nhist, it is possible for knext to * index into unallocated space. This condition would not be * caught by the resizing code above. */ if (knext + 1 > nkeys) knext = adb->old_key_next = 0; /* free the old pw history entry if it contains data */ histp = &adb->old_keys[knext]; for (i = 0; i < (unsigned int) histp->n_key_data; i++) krb5_free_key_data_contents(context, &histp->key_data[i]); free(histp->key_data); /* store the new entry */ adb->old_keys[knext] = *pw; /* update the next pointer */ if (++adb->old_key_next == nhist - 1) adb->old_key_next = 0; return(0); } /* FIXME: don't use global variable for this */ krb5_boolean use_password_server = 0; #ifdef USE_PASSWORD_SERVER static krb5_boolean kadm5_use_password_server (void) { return use_password_server; } #endif void kadm5_set_use_password_server (void); void kadm5_set_use_password_server (void) { use_password_server = 1; } #ifdef USE_PASSWORD_SERVER /* * kadm5_launch_task () runs a program (task_path) to synchronize the * Apple password server with the Kerberos database. Password server * programs can receive arguments on the command line (task_argv) * and a block of data via stdin (data_buffer). * * Because a failure to communicate with the tool results in the * password server falling out of sync with the database, * kadm5_launch_task() always fails if it can't talk to the tool. */ static kadm5_ret_t kadm5_launch_task (krb5_context context, const char *task_path, char * const task_argv[], const char *buffer) { kadm5_ret_t ret; int data_pipe[2]; ret = pipe (data_pipe); if (ret) ret = errno; if (!ret) { pid_t pid = fork (); if (pid == -1) { ret = errno; close (data_pipe[0]); close (data_pipe[1]); } else if (pid == 0) { /* The child: */ if (dup2 (data_pipe[0], STDIN_FILENO) == -1) _exit (1); close (data_pipe[0]); close (data_pipe[1]); execv (task_path, task_argv); _exit (1); /* Fail if execv fails */ } else { /* The parent: */ int status; ret = 0; close (data_pipe[0]); /* Write out the buffer to the child, add \n */ if (buffer) { if (krb5_net_write (context, data_pipe[1], buffer, strlen (buffer)) < 0 || krb5_net_write (context, data_pipe[1], "\n", 1) < 0) { /* kill the child to make sure waitpid() won't hang later */ ret = errno; kill (pid, SIGKILL); } } close (data_pipe[1]); waitpid (pid, &status, 0); if (!ret) { if (WIFEXITED (status)) { /* child read password and exited. Check the return value. */ if ((WEXITSTATUS (status) != 0) && (WEXITSTATUS (status) != 252)) { ret = KRB5KDC_ERR_POLICY; /* password change rejected */ } } else { /* child read password but crashed or was killed */ ret = KRB5KRB_ERR_GENERIC; /* FIXME: better error */ } } } } return ret; } #endif kadm5_ret_t kadm5_chpass_principal(void *server_handle, krb5_principal principal, char *password) { return kadm5_chpass_principal_3(server_handle, principal, FALSE, 0, NULL, password); } kadm5_ret_t kadm5_chpass_principal_3(void *server_handle, krb5_principal principal, krb5_boolean keepold, int n_ks_tuple, krb5_key_salt_tuple *ks_tuple, char *password) { krb5_int32 now; kadm5_policy_ent_rec pol; osa_princ_ent_rec adb; krb5_db_entry *kdb; int ret, ret2, last_pwd, hist_added; krb5_boolean have_pol = FALSE; kadm5_server_handle_t handle = server_handle; osa_pw_hist_ent hist; krb5_keyblock *act_mkey, *hist_keyblocks = NULL; krb5_kvno act_kvno, hist_kvno; int new_n_ks_tuple = 0; krb5_key_salt_tuple *new_ks_tuple = NULL; CHECK_HANDLE(server_handle); krb5_clear_error_message(handle->context); hist_added = 0; memset(&hist, 0, sizeof(hist)); if (principal == NULL || password == NULL) return EINVAL; if ((krb5_principal_compare(handle->context, principal, hist_princ)) == TRUE) return KADM5_PROTECT_PRINCIPAL; if ((ret = kdb_get_entry(handle, principal, &kdb, &adb))) return(ret); ret = apply_keysalt_policy(handle, adb.policy, n_ks_tuple, ks_tuple, &new_n_ks_tuple, &new_ks_tuple); if (ret) goto done; if ((adb.aux_attributes & KADM5_POLICY)) { ret = get_policy(handle, adb.policy, &pol, &have_pol); if (ret) goto done; } if (have_pol) { /* Create a password history entry before we change kdb's key_data. */ ret = kdb_get_hist_key(handle, &hist_keyblocks, &hist_kvno); if (ret) goto done; ret = create_history_entry(handle->context, &hist_keyblocks[0], kdb->n_key_data, kdb->key_data, &hist); if (ret) goto done; } if ((ret = passwd_check(handle, password, have_pol ? &pol : NULL, principal))) goto done; ret = kdb_get_active_mkey(handle, &act_kvno, &act_mkey); if (ret) goto done; ret = krb5_dbe_cpw(handle->context, act_mkey, new_ks_tuple, new_n_ks_tuple, password, 0 /* increment kvno */, keepold, kdb); if (ret) goto done; ret = krb5_dbe_update_mkvno(handle->context, kdb, act_kvno); if (ret) goto done; kdb->attributes &= ~KRB5_KDB_REQUIRES_PWCHANGE; ret = krb5_timeofday(handle->context, &now); if (ret) goto done; if ((adb.aux_attributes & KADM5_POLICY)) { /* the policy was loaded before */ ret = krb5_dbe_lookup_last_pwd_change(handle->context, kdb, &last_pwd); if (ret) goto done; #if 0 /* * The spec says this check is overridden if the caller has * modify privilege. The admin server therefore makes this * check itself (in chpass_principal_wrapper, misc.c). A * local caller implicitly has all authorization bits. */ if ((now - last_pwd) < pol.pw_min_life && !(kdb->attributes & KRB5_KDB_REQUIRES_PWCHANGE)) { ret = KADM5_PASS_TOOSOON; goto done; } #endif ret = check_pw_reuse(handle->context, hist_keyblocks, kdb->n_key_data, kdb->key_data, 1, &hist); if (ret) goto done; if (pol.pw_history_num > 1) { /* If hist_kvno has changed since the last password change, we * can't check the history. */ if (adb.admin_history_kvno == hist_kvno) { ret = check_pw_reuse(handle->context, hist_keyblocks, kdb->n_key_data, kdb->key_data, adb.old_key_len, adb.old_keys); if (ret) goto done; } ret = add_to_history(handle->context, hist_kvno, &adb, &pol, &hist); if (ret) goto done; hist_added = 1; } if (pol.pw_max_life) kdb->pw_expiration = now + pol.pw_max_life; else kdb->pw_expiration = 0; } else { kdb->pw_expiration = 0; } #ifdef USE_PASSWORD_SERVER if (kadm5_use_password_server () && (krb5_princ_size (handle->context, principal) == 1)) { krb5_data *princ = krb5_princ_component (handle->context, principal, 0); const char *path = "/usr/sbin/mkpassdb"; char *argv[] = { "mkpassdb", "-setpassword", NULL, NULL }; char *pstring = NULL; if (!ret) { pstring = malloc ((princ->length + 1) * sizeof (char)); if (pstring == NULL) { ret = ENOMEM; } } if (!ret) { memcpy (pstring, princ->data, princ->length); pstring [princ->length] = '\0'; argv[2] = pstring; ret = kadm5_launch_task (handle->context, path, argv, password); } if (pstring != NULL) free (pstring); if (ret) goto done; } #endif ret = krb5_dbe_update_last_pwd_change(handle->context, kdb, now); if (ret) goto done; /* unlock principal on this KDC */ kdb->fail_auth_count = 0; /* key data and attributes changed, let the database provider know */ kdb->mask = KADM5_KEY_DATA | KADM5_ATTRIBUTES | KADM5_FAIL_AUTH_COUNT; /* | KADM5_CPW_FUNCTION */ ret = k5_kadm5_hook_chpass(handle->context, handle->hook_handles, KADM5_HOOK_STAGE_PRECOMMIT, principal, keepold, new_n_ks_tuple, new_ks_tuple, password); if (ret) goto done; if ((ret = kdb_put_entry(handle, kdb, &adb))) goto done; (void) k5_kadm5_hook_chpass(handle->context, handle->hook_handles, KADM5_HOOK_STAGE_POSTCOMMIT, principal, keepold, new_n_ks_tuple, new_ks_tuple, password); ret = KADM5_OK; done: free(new_ks_tuple); if (!hist_added && hist.key_data) free_history_entry(handle->context, &hist); kdb_free_entry(handle, kdb, &adb); kdb_free_keyblocks(handle, hist_keyblocks); if (have_pol && (ret2 = kadm5_free_policy_ent(handle->lhandle, &pol)) && !ret) ret = ret2; return ret; } kadm5_ret_t kadm5_randkey_principal(void *server_handle, krb5_principal principal, krb5_keyblock **keyblocks, int *n_keys) { return kadm5_randkey_principal_3(server_handle, principal, FALSE, 0, NULL, keyblocks, n_keys); } kadm5_ret_t kadm5_randkey_principal_3(void *server_handle, krb5_principal principal, krb5_boolean keepold, int n_ks_tuple, krb5_key_salt_tuple *ks_tuple, krb5_keyblock **keyblocks, int *n_keys) { krb5_db_entry *kdb; osa_princ_ent_rec adb; krb5_int32 now; kadm5_policy_ent_rec pol; int ret, last_pwd, n_new_keys; krb5_boolean have_pol = FALSE; kadm5_server_handle_t handle = server_handle; krb5_keyblock *act_mkey; krb5_kvno act_kvno; int new_n_ks_tuple = 0; krb5_key_salt_tuple *new_ks_tuple = NULL; if (keyblocks) *keyblocks = NULL; CHECK_HANDLE(server_handle); krb5_clear_error_message(handle->context); if (principal == NULL) return EINVAL; if ((ret = kdb_get_entry(handle, principal, &kdb, &adb))) return(ret); ret = apply_keysalt_policy(handle, adb.policy, n_ks_tuple, ks_tuple, &new_n_ks_tuple, &new_ks_tuple); if (ret) goto done; if (krb5_principal_compare(handle->context, principal, hist_princ)) { /* If changing the history entry, the new entry must have exactly one * key. */ if (keepold) return KADM5_PROTECT_PRINCIPAL; new_n_ks_tuple = 1; } ret = kdb_get_active_mkey(handle, &act_kvno, &act_mkey); if (ret) goto done; ret = krb5_dbe_crk(handle->context, act_mkey, new_ks_tuple, new_n_ks_tuple, keepold, kdb); if (ret) goto done; ret = krb5_dbe_update_mkvno(handle->context, kdb, act_kvno); if (ret) goto done; kdb->attributes &= ~KRB5_KDB_REQUIRES_PWCHANGE; ret = krb5_timeofday(handle->context, &now); if (ret) goto done; if ((adb.aux_attributes & KADM5_POLICY)) { ret = get_policy(handle, adb.policy, &pol, &have_pol); if (ret) goto done; } if (have_pol) { ret = krb5_dbe_lookup_last_pwd_change(handle->context, kdb, &last_pwd); if (ret) goto done; #if 0 /* * The spec says this check is overridden if the caller has * modify privilege. The admin server therefore makes this * check itself (in chpass_principal_wrapper, misc.c). A * local caller implicitly has all authorization bits. */ if((now - last_pwd) < pol.pw_min_life && !(kdb->attributes & KRB5_KDB_REQUIRES_PWCHANGE)) { ret = KADM5_PASS_TOOSOON; goto done; } #endif if (pol.pw_max_life) kdb->pw_expiration = now + pol.pw_max_life; else kdb->pw_expiration = 0; } else { kdb->pw_expiration = 0; } ret = krb5_dbe_update_last_pwd_change(handle->context, kdb, now); if (ret) goto done; /* unlock principal on this KDC */ kdb->fail_auth_count = 0; if (keyblocks) { /* Return only the new keys added by krb5_dbe_crk. */ n_new_keys = count_new_keys(kdb->n_key_data, kdb->key_data); ret = decrypt_key_data(handle->context, n_new_keys, kdb->key_data, keyblocks, n_keys); if (ret) goto done; } /* key data changed, let the database provider know */ kdb->mask = KADM5_KEY_DATA | KADM5_FAIL_AUTH_COUNT; /* | KADM5_RANDKEY_USED */; ret = k5_kadm5_hook_chpass(handle->context, handle->hook_handles, KADM5_HOOK_STAGE_PRECOMMIT, principal, keepold, new_n_ks_tuple, new_ks_tuple, NULL); if (ret) goto done; if ((ret = kdb_put_entry(handle, kdb, &adb))) goto done; (void) k5_kadm5_hook_chpass(handle->context, handle->hook_handles, KADM5_HOOK_STAGE_POSTCOMMIT, principal, keepold, new_n_ks_tuple, new_ks_tuple, NULL); ret = KADM5_OK; done: free(new_ks_tuple); kdb_free_entry(handle, kdb, &adb); if (have_pol) kadm5_free_policy_ent(handle->lhandle, &pol); return ret; } /* * kadm5_setv4key_principal: * * Set only ONE key of the principal, removing all others. This key * must have the DES_CBC_CRC enctype and is entered as having the * krb4 salttype. This is to enable things like kadmind4 to work. */ kadm5_ret_t kadm5_setv4key_principal(void *server_handle, krb5_principal principal, krb5_keyblock *keyblock) { krb5_db_entry *kdb; osa_princ_ent_rec adb; krb5_int32 now; kadm5_policy_ent_rec pol; krb5_keysalt keysalt; int i, k, kvno, ret; krb5_boolean have_pol = FALSE; #if 0 int last_pwd; #endif kadm5_server_handle_t handle = server_handle; krb5_key_data tmp_key_data; krb5_keyblock *act_mkey; memset( &tmp_key_data, 0, sizeof(tmp_key_data)); CHECK_HANDLE(server_handle); krb5_clear_error_message(handle->context); if (principal == NULL || keyblock == NULL) return EINVAL; if (hist_princ && /* this will be NULL when initializing the databse */ ((krb5_principal_compare(handle->context, principal, hist_princ)) == TRUE)) return KADM5_PROTECT_PRINCIPAL; if (keyblock->enctype != ENCTYPE_DES_CBC_CRC) return KADM5_SETV4KEY_INVAL_ENCTYPE; if ((ret = kdb_get_entry(handle, principal, &kdb, &adb))) return(ret); for (kvno = 0, i=0; i<kdb->n_key_data; i++) if (kdb->key_data[i].key_data_kvno > kvno) kvno = kdb->key_data[i].key_data_kvno; if (kdb->key_data != NULL) cleanup_key_data(handle->context, kdb->n_key_data, kdb->key_data); kdb->key_data = (krb5_key_data*)krb5_db_alloc(handle->context, NULL, sizeof(krb5_key_data)); if (kdb->key_data == NULL) return ENOMEM; memset(kdb->key_data, 0, sizeof(krb5_key_data)); kdb->n_key_data = 1; keysalt.type = KRB5_KDB_SALTTYPE_V4; /* XXX data.magic? */ keysalt.data.length = 0; keysalt.data.data = NULL; ret = kdb_get_active_mkey(handle, NULL, &act_mkey); if (ret) goto done; /* use tmp_key_data as temporary location and reallocate later */ ret = krb5_dbe_encrypt_key_data(handle->context, act_mkey, keyblock, &keysalt, kvno + 1, &tmp_key_data); if (ret) { goto done; } for (k = 0; k < tmp_key_data.key_data_ver; k++) { kdb->key_data->key_data_type[k] = tmp_key_data.key_data_type[k]; kdb->key_data->key_data_length[k] = tmp_key_data.key_data_length[k]; if (tmp_key_data.key_data_contents[k]) { kdb->key_data->key_data_contents[k] = krb5_db_alloc(handle->context, NULL, tmp_key_data.key_data_length[k]); if (kdb->key_data->key_data_contents[k] == NULL) { cleanup_key_data(handle->context, kdb->n_key_data, kdb->key_data); kdb->key_data = NULL; kdb->n_key_data = 0; ret = ENOMEM; goto done; } memcpy (kdb->key_data->key_data_contents[k], tmp_key_data.key_data_contents[k], tmp_key_data.key_data_length[k]); memset (tmp_key_data.key_data_contents[k], 0, tmp_key_data.key_data_length[k]); free (tmp_key_data.key_data_contents[k]); tmp_key_data.key_data_contents[k] = NULL; } } kdb->attributes &= ~KRB5_KDB_REQUIRES_PWCHANGE; ret = krb5_timeofday(handle->context, &now); if (ret) goto done; if ((adb.aux_attributes & KADM5_POLICY)) { ret = get_policy(handle, adb.policy, &pol, &have_pol); if (ret) goto done; } if (have_pol) { #if 0 /* * The spec says this check is overridden if the caller has * modify privilege. The admin server therefore makes this * check itself (in chpass_principal_wrapper, misc.c). A * local caller implicitly has all authorization bits. */ if (ret = krb5_dbe_lookup_last_pwd_change(handle->context, kdb, &last_pwd)) goto done; if((now - last_pwd) < pol.pw_min_life && !(kdb->attributes & KRB5_KDB_REQUIRES_PWCHANGE)) { ret = KADM5_PASS_TOOSOON; goto done; } #endif if (pol.pw_max_life) kdb->pw_expiration = now + pol.pw_max_life; else kdb->pw_expiration = 0; } else { kdb->pw_expiration = 0; } ret = krb5_dbe_update_last_pwd_change(handle->context, kdb, now); if (ret) goto done; /* unlock principal on this KDC */ kdb->fail_auth_count = 0; if ((ret = kdb_put_entry(handle, kdb, &adb))) goto done; ret = KADM5_OK; done: for (i = 0; i < tmp_key_data.key_data_ver; i++) { if (tmp_key_data.key_data_contents[i]) { memset (tmp_key_data.key_data_contents[i], 0, tmp_key_data.key_data_length[i]); free (tmp_key_data.key_data_contents[i]); } } kdb_free_entry(handle, kdb, &adb); if (have_pol) kadm5_free_policy_ent(handle->lhandle, &pol); return ret; } kadm5_ret_t kadm5_setkey_principal(void *server_handle, krb5_principal principal, krb5_keyblock *keyblocks, int n_keys) { return kadm5_setkey_principal_3(server_handle, principal, FALSE, 0, NULL, keyblocks, n_keys); } /* Make key/salt list from keys for kadm5_setkey_principal_3() */ static kadm5_ret_t make_ks_from_keys(krb5_context context, int n_keys, krb5_keyblock *keyblocks, krb5_key_salt_tuple **ks_tuple) { int i; *ks_tuple = calloc(n_keys, sizeof(**ks_tuple)); if (*ks_tuple == NULL) return ENOMEM; for (i = 0; i < n_keys; i++) { (*ks_tuple)[i].ks_enctype = keyblocks[i].enctype; (*ks_tuple)[i].ks_salttype = KRB5_KDB_SALTTYPE_NORMAL; } return 0; } kadm5_ret_t kadm5_setkey_principal_3(void *server_handle, krb5_principal principal, krb5_boolean keepold, int n_ks_tuple, krb5_key_salt_tuple *ks_tuple, krb5_keyblock *keyblocks, int n_keys) { krb5_db_entry *kdb; osa_princ_ent_rec adb; krb5_int32 now; kadm5_policy_ent_rec pol; krb5_key_data *old_key_data; int n_old_keys; int i, j, k, kvno, ret; krb5_boolean have_pol = FALSE; #if 0 int last_pwd; #endif kadm5_server_handle_t handle = server_handle; krb5_boolean similar; krb5_keysalt keysalt; krb5_key_data tmp_key_data; krb5_key_data *tptr; krb5_keyblock *act_mkey; krb5_key_salt_tuple *ks_from_keys = NULL; CHECK_HANDLE(server_handle); krb5_clear_error_message(handle->context); if (principal == NULL || keyblocks == NULL) return EINVAL; if (hist_princ && /* this will be NULL when initializing the databse */ ((krb5_principal_compare(handle->context, principal, hist_princ)) == TRUE)) return KADM5_PROTECT_PRINCIPAL; if ((ret = kdb_get_entry(handle, principal, &kdb, &adb))) return(ret); if (!n_ks_tuple) { /* Apply policy to the key/salt types implied by the given keys */ ret = make_ks_from_keys(handle->context, n_keys, keyblocks, &ks_from_keys); if (ret) goto done; ret = apply_keysalt_policy(handle, adb.policy, n_keys, ks_from_keys, NULL, NULL); free(ks_from_keys); } else { /* * Apply policy to the given ks_tuples. Note that further below * we enforce keyblocks[i].enctype == ks_tuple[i].ks_enctype for * all i from 0 to n_keys, and that n_ks_tuple == n_keys if ks * tuples are given. */ ret = apply_keysalt_policy(handle, adb.policy, n_ks_tuple, ks_tuple, NULL, NULL); } if (ret) goto done; for (i = 0; i < n_keys; i++) { for (j = i+1; j < n_keys; j++) { if ((ret = krb5_c_enctype_compare(handle->context, keyblocks[i].enctype, keyblocks[j].enctype, &similar))) return(ret); if (similar) { if (n_ks_tuple) { if (ks_tuple[i].ks_salttype == ks_tuple[j].ks_salttype) return KADM5_SETKEY_DUP_ENCTYPES; } else return KADM5_SETKEY_DUP_ENCTYPES; } } } if (n_ks_tuple && n_ks_tuple != n_keys) return KADM5_SETKEY3_ETYPE_MISMATCH; for (kvno = 0, i=0; i<kdb->n_key_data; i++) if (kdb->key_data[i].key_data_kvno > kvno) kvno = kdb->key_data[i].key_data_kvno; if (keepold) { old_key_data = kdb->key_data; n_old_keys = kdb->n_key_data; } else { if (kdb->key_data != NULL) cleanup_key_data(handle->context, kdb->n_key_data, kdb->key_data); n_old_keys = 0; old_key_data = NULL; } /* Allocate one extra key_data to avoid allocating 0 bytes. */ kdb->key_data = krb5_db_alloc(handle->context, NULL, (n_keys + n_old_keys + 1) * sizeof(krb5_key_data)); if (kdb->key_data == NULL) { ret = ENOMEM; goto done; } memset(kdb->key_data, 0, (n_keys+n_old_keys)*sizeof(krb5_key_data)); kdb->n_key_data = 0; for (i = 0; i < n_keys; i++) { if (n_ks_tuple) { keysalt.type = ks_tuple[i].ks_salttype; keysalt.data.length = 0; keysalt.data.data = NULL; if (ks_tuple[i].ks_enctype != keyblocks[i].enctype) { ret = KADM5_SETKEY3_ETYPE_MISMATCH; goto done; } } memset (&tmp_key_data, 0, sizeof(tmp_key_data)); ret = kdb_get_active_mkey(handle, NULL, &act_mkey); if (ret) goto done; ret = krb5_dbe_encrypt_key_data(handle->context, act_mkey, &keyblocks[i], n_ks_tuple ? &keysalt : NULL, kvno + 1, &tmp_key_data); if (ret) goto done; tptr = &kdb->key_data[i]; tptr->key_data_ver = tmp_key_data.key_data_ver; tptr->key_data_kvno = tmp_key_data.key_data_kvno; for (k = 0; k < tmp_key_data.key_data_ver; k++) { tptr->key_data_type[k] = tmp_key_data.key_data_type[k]; tptr->key_data_length[k] = tmp_key_data.key_data_length[k]; if (tmp_key_data.key_data_contents[k]) { tptr->key_data_contents[k] = krb5_db_alloc(handle->context, NULL, tmp_key_data.key_data_length[k]); if (tptr->key_data_contents[k] == NULL) { int i1; for (i1 = k; i1 < tmp_key_data.key_data_ver; i1++) { if (tmp_key_data.key_data_contents[i1]) { memset (tmp_key_data.key_data_contents[i1], 0, tmp_key_data.key_data_length[i1]); free (tmp_key_data.key_data_contents[i1]); } } ret = ENOMEM; goto done; } memcpy (tptr->key_data_contents[k], tmp_key_data.key_data_contents[k], tmp_key_data.key_data_length[k]); memset (tmp_key_data.key_data_contents[k], 0, tmp_key_data.key_data_length[k]); free (tmp_key_data.key_data_contents[k]); tmp_key_data.key_data_contents[k] = NULL; } } kdb->n_key_data++; } /* copy old key data if necessary */ for (i = 0; i < n_old_keys; i++) { kdb->key_data[i+n_keys] = old_key_data[i]; memset(&old_key_data[i], 0, sizeof (krb5_key_data)); kdb->n_key_data++; } if (old_key_data) krb5_db_free(handle->context, old_key_data); /* assert(kdb->n_key_data == n_keys + n_old_keys) */ kdb->attributes &= ~KRB5_KDB_REQUIRES_PWCHANGE; if ((ret = krb5_timeofday(handle->context, &now))) goto done; if ((adb.aux_attributes & KADM5_POLICY)) { ret = get_policy(handle, adb.policy, &pol, &have_pol); if (ret) goto done; } if (have_pol) { #if 0 /* * The spec says this check is overridden if the caller has * modify privilege. The admin server therefore makes this * check itself (in chpass_principal_wrapper, misc.c). A * local caller implicitly has all authorization bits. */ if (ret = krb5_dbe_lookup_last_pwd_change(handle->context, kdb, &last_pwd)) goto done; if((now - last_pwd) < pol.pw_min_life && !(kdb->attributes & KRB5_KDB_REQUIRES_PWCHANGE)) { ret = KADM5_PASS_TOOSOON; goto done; } #endif if (pol.pw_max_life) kdb->pw_expiration = now + pol.pw_max_life; else kdb->pw_expiration = 0; } else { kdb->pw_expiration = 0; } if ((ret = krb5_dbe_update_last_pwd_change(handle->context, kdb, now))) goto done; /* unlock principal on this KDC */ kdb->fail_auth_count = 0; if ((ret = kdb_put_entry(handle, kdb, &adb))) goto done; ret = KADM5_OK; done: kdb_free_entry(handle, kdb, &adb); if (have_pol) kadm5_free_policy_ent(handle->lhandle, &pol); return ret; } /* * Return the list of keys like kadm5_randkey_principal, * but don't modify the principal. */ kadm5_ret_t kadm5_get_principal_keys(void *server_handle /* IN */, krb5_principal principal /* IN */, krb5_keyblock **keyblocks /* OUT */, int *n_keys /* OUT */) { krb5_db_entry *kdb; osa_princ_ent_rec adb; kadm5_ret_t ret; kadm5_server_handle_t handle = server_handle; if (keyblocks) *keyblocks = NULL; CHECK_HANDLE(server_handle); if (principal == NULL) return EINVAL; if ((ret = kdb_get_entry(handle, principal, &kdb, &adb))) return(ret); if (keyblocks) { ret = decrypt_key_data(handle->context, kdb->n_key_data, kdb->key_data, keyblocks, n_keys); if (ret) goto done; } ret = KADM5_OK; done: kdb_free_entry(handle, kdb, &adb); return ret; } /* * Allocate an array of n_key_data krb5_keyblocks, fill in each * element with the results of decrypting the nth key in key_data, * and if n_keys is not NULL fill it in with the * number of keys decrypted. */ static int decrypt_key_data(krb5_context context, int n_key_data, krb5_key_data *key_data, krb5_keyblock **keyblocks, int *n_keys) { krb5_keyblock *keys; int ret, i; keys = (krb5_keyblock *) malloc(n_key_data*sizeof(krb5_keyblock)); if (keys == NULL) return ENOMEM; memset(keys, 0, n_key_data*sizeof(krb5_keyblock)); for (i = 0; i < n_key_data; i++) { ret = krb5_dbe_decrypt_key_data(context, NULL, &key_data[i], &keys[i], NULL); if (ret) { for (; i >= 0; i--) { if (keys[i].contents) { memset (keys[i].contents, 0, keys[i].length); free( keys[i].contents ); } } memset(keys, 0, n_key_data*sizeof(krb5_keyblock)); free(keys); return ret; } } *keyblocks = keys; if (n_keys) *n_keys = n_key_data; return 0; } /* * Function: kadm5_decrypt_key * * Purpose: Retrieves and decrypts a principal key. * * Arguments: * * server_handle (r) kadm5 handle * entry (r) principal retrieved with kadm5_get_principal * ktype (r) enctype to search for, or -1 to ignore * stype (r) salt type to search for, or -1 to ignore * kvno (r) kvno to search for, -1 for max, 0 for max * only if it also matches ktype and stype * keyblock (w) keyblock to fill in * keysalt (w) keysalt to fill in, or NULL * kvnop (w) kvno to fill in, or NULL * * Effects: Searches the key_data array of entry, which must have been * retrived with kadm5_get_principal with the KADM5_KEY_DATA mask, to * find a key with a specified enctype, salt type, and kvno in a * principal entry. If not found, return ENOENT. Otherwise, decrypt * it with the master key, and return the key in keyblock, the salt * in salttype, and the key version number in kvno. * * If ktype or stype is -1, it is ignored for the search. If kvno is * -1, ktype and stype are ignored and the key with the max kvno is * returned. If kvno is 0, only the key with the max kvno is returned * and only if it matches the ktype and stype; otherwise, ENOENT is * returned. */ kadm5_ret_t kadm5_decrypt_key(void *server_handle, kadm5_principal_ent_t entry, krb5_int32 ktype, krb5_int32 stype, krb5_int32 kvno, krb5_keyblock *keyblock, krb5_keysalt *keysalt, int *kvnop) { kadm5_server_handle_t handle = server_handle; krb5_db_entry dbent; krb5_key_data *key_data; krb5_keyblock *mkey_ptr; int ret; CHECK_HANDLE(server_handle); if (entry->n_key_data == 0 || entry->key_data == NULL) return EINVAL; /* find_enctype only uses these two fields */ dbent.n_key_data = entry->n_key_data; dbent.key_data = entry->key_data; if ((ret = krb5_dbe_find_enctype(handle->context, &dbent, ktype, stype, kvno, &key_data))) return ret; /* find_mkey only uses this field */ dbent.tl_data = entry->tl_data; if ((ret = krb5_dbe_find_mkey(handle->context, &dbent, &mkey_ptr))) { /* try refreshing master key list */ /* XXX it would nice if we had the mkvno here for optimization */ if (krb5_db_fetch_mkey_list(handle->context, master_princ, &master_keyblock) == 0) { if ((ret = krb5_dbe_find_mkey(handle->context, &dbent, &mkey_ptr))) { return ret; } } else { return ret; } } if ((ret = krb5_dbe_decrypt_key_data(handle->context, NULL, key_data, keyblock, keysalt))) return ret; /* * Coerce the enctype of the output keyblock in case we got an * inexact match on the enctype; this behavior will go away when * the key storage architecture gets redesigned for 1.3. */ if (ktype != -1) keyblock->enctype = ktype; if (kvnop) *kvnop = key_data->key_data_kvno; return KADM5_OK; } kadm5_ret_t kadm5_purgekeys(void *server_handle, krb5_principal principal, int keepkvno) { kadm5_server_handle_t handle = server_handle; kadm5_ret_t ret; krb5_db_entry *kdb; osa_princ_ent_rec adb; krb5_key_data *old_keydata; int n_old_keydata; int i, j, k; CHECK_HANDLE(server_handle); if (principal == NULL) return EINVAL; ret = kdb_get_entry(handle, principal, &kdb, &adb); if (ret) return(ret); if (keepkvno <= 0) { keepkvno = krb5_db_get_key_data_kvno(handle->context, kdb->n_key_data, kdb->key_data); } old_keydata = kdb->key_data; n_old_keydata = kdb->n_key_data; kdb->n_key_data = 0; /* Allocate one extra key_data to avoid allocating 0 bytes. */ kdb->key_data = krb5_db_alloc(handle->context, NULL, (n_old_keydata + 1) * sizeof(krb5_key_data)); if (kdb->key_data == NULL) { ret = ENOMEM; goto done; } memset(kdb->key_data, 0, n_old_keydata * sizeof(krb5_key_data)); for (i = 0, j = 0; i < n_old_keydata; i++) { if (old_keydata[i].key_data_kvno < keepkvno) continue; /* Alias the key_data_contents pointers; we null them out in the * source array immediately after. */ kdb->key_data[j] = old_keydata[i]; for (k = 0; k < old_keydata[i].key_data_ver; k++) { old_keydata[i].key_data_contents[k] = NULL; } j++; } kdb->n_key_data = j; cleanup_key_data(handle->context, n_old_keydata, old_keydata); kdb->mask = KADM5_KEY_DATA; ret = kdb_put_entry(handle, kdb, &adb); if (ret) goto done; done: kdb_free_entry(handle, kdb, &adb); return ret; } kadm5_ret_t kadm5_get_strings(void *server_handle, krb5_principal principal, krb5_string_attr **strings_out, int *count_out) { kadm5_server_handle_t handle = server_handle; kadm5_ret_t ret; krb5_db_entry *kdb = NULL; *strings_out = NULL; *count_out = 0; CHECK_HANDLE(server_handle); if (principal == NULL) return EINVAL; ret = kdb_get_entry(handle, principal, &kdb, NULL); if (ret) return ret; ret = krb5_dbe_get_strings(handle->context, kdb, strings_out, count_out); kdb_free_entry(handle, kdb, NULL); return ret; } kadm5_ret_t kadm5_set_string(void *server_handle, krb5_principal principal, const char *key, const char *value) { kadm5_server_handle_t handle = server_handle; kadm5_ret_t ret; krb5_db_entry *kdb; osa_princ_ent_rec adb; CHECK_HANDLE(server_handle); if (principal == NULL || key == NULL) return EINVAL; ret = kdb_get_entry(handle, principal, &kdb, &adb); if (ret) return ret; ret = krb5_dbe_set_string(handle->context, kdb, key, value); if (ret) goto done; kdb->mask = KADM5_TL_DATA; ret = kdb_put_entry(handle, kdb, &adb); done: kdb_free_entry(handle, kdb, &adb); return ret; }
./CrossVul/dataset_final_sorted/CWE-255/c/good_2254_0
crossvul-cpp_data_bad_536_2
/* SPDX-License-Identifier: LGPL-2.1+ */ /*** Copyright © 2016 Michal Soltys <soltys@ziu.info> ***/ #include <errno.h> #include <fcntl.h> #include <limits.h> #include <linux/kd.h> #include <linux/tiocl.h> #include <linux/vt.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <sys/ioctl.h> #include <sysexits.h> #include <termios.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include "alloc-util.h" #include "env-file.h" #include "fd-util.h" #include "fileio.h" #include "io-util.h" #include "locale-util.h" #include "log.h" #include "proc-cmdline.h" #include "process-util.h" #include "signal-util.h" #include "stdio-util.h" #include "string-util.h" #include "strv.h" #include "terminal-util.h" #include "util.h" #include "virt.h" static int verify_vc_device(int fd) { unsigned char data[] = { TIOCL_GETFGCONSOLE, }; int r; r = ioctl(fd, TIOCLINUX, data); if (r < 0) return -errno; return r; } static int verify_vc_allocation(unsigned idx) { char vcname[sizeof("/dev/vcs") + DECIMAL_STR_MAX(unsigned) - 2]; xsprintf(vcname, "/dev/vcs%u", idx); if (access(vcname, F_OK) < 0) return -errno; return 0; } static int verify_vc_allocation_byfd(int fd) { struct vt_stat vcs = {}; if (ioctl(fd, VT_GETSTATE, &vcs) < 0) return -errno; return verify_vc_allocation(vcs.v_active); } static int verify_vc_kbmode(int fd) { int curr_mode; /* * Make sure we only adjust consoles in K_XLATE or K_UNICODE mode. * Otherwise we would (likely) interfere with X11's processing of the * key events. * * http://lists.freedesktop.org/archives/systemd-devel/2013-February/008573.html */ if (ioctl(fd, KDGKBMODE, &curr_mode) < 0) return -errno; return IN_SET(curr_mode, K_XLATE, K_UNICODE) ? 0 : -EBUSY; } static int toggle_utf8(const char *name, int fd, bool utf8) { int r; struct termios tc = {}; assert(name); r = ioctl(fd, KDSKBMODE, utf8 ? K_UNICODE : K_XLATE); if (r < 0) return log_warning_errno(errno, "Failed to %s UTF-8 kbdmode on %s: %m", enable_disable(utf8), name); r = loop_write(fd, utf8 ? "\033%G" : "\033%@", 3, false); if (r < 0) return log_warning_errno(r, "Failed to %s UTF-8 term processing on %s: %m", enable_disable(utf8), name); r = tcgetattr(fd, &tc); if (r >= 0) { SET_FLAG(tc.c_iflag, IUTF8, utf8); r = tcsetattr(fd, TCSANOW, &tc); } if (r < 0) return log_warning_errno(errno, "Failed to %s iutf8 flag on %s: %m", enable_disable(utf8), name); log_debug("UTF-8 kbdmode %sd on %s", enable_disable(utf8), name); return 0; } static int toggle_utf8_sysfs(bool utf8) { int r; r = write_string_file("/sys/module/vt/parameters/default_utf8", one_zero(utf8), WRITE_STRING_FILE_DISABLE_BUFFER); if (r < 0) return log_warning_errno(r, "Failed to %s sysfs UTF-8 flag: %m", enable_disable(utf8)); log_debug("Sysfs UTF-8 flag %sd", enable_disable(utf8)); return 0; } static int keyboard_load_and_wait(const char *vc, const char *map, const char *map_toggle, bool utf8) { const char *args[8]; unsigned i = 0; pid_t pid; int r; /* An empty map means kernel map */ if (isempty(map)) return 0; args[i++] = KBD_LOADKEYS; args[i++] = "-q"; args[i++] = "-C"; args[i++] = vc; if (utf8) args[i++] = "-u"; args[i++] = map; if (map_toggle) args[i++] = map_toggle; args[i++] = NULL; if (DEBUG_LOGGING) { _cleanup_free_ char *cmd; cmd = strv_join((char**) args, " "); log_debug("Executing \"%s\"...", strnull(cmd)); } r = safe_fork("(loadkeys)", FORK_RESET_SIGNALS|FORK_CLOSE_ALL_FDS|FORK_RLIMIT_NOFILE_SAFE|FORK_LOG, &pid); if (r < 0) return r; if (r == 0) { execv(args[0], (char **) args); _exit(EXIT_FAILURE); } return wait_for_terminate_and_check(KBD_LOADKEYS, pid, WAIT_LOG); } static int font_load_and_wait(const char *vc, const char *font, const char *map, const char *unimap) { const char *args[9]; unsigned i = 0; pid_t pid; int r; /* Any part can be set independently */ if (isempty(font) && isempty(map) && isempty(unimap)) return 0; args[i++] = KBD_SETFONT; args[i++] = "-C"; args[i++] = vc; if (!isempty(map)) { args[i++] = "-m"; args[i++] = map; } if (!isempty(unimap)) { args[i++] = "-u"; args[i++] = unimap; } if (!isempty(font)) args[i++] = font; args[i++] = NULL; if (DEBUG_LOGGING) { _cleanup_free_ char *cmd; cmd = strv_join((char**) args, " "); log_debug("Executing \"%s\"...", strnull(cmd)); } r = safe_fork("(setfont)", FORK_RESET_SIGNALS|FORK_CLOSE_ALL_FDS|FORK_RLIMIT_NOFILE_SAFE|FORK_LOG, &pid); if (r < 0) return r; if (r == 0) { execv(args[0], (char **) args); _exit(EXIT_FAILURE); } return wait_for_terminate_and_check(KBD_SETFONT, pid, WAIT_LOG); } /* * A newly allocated VT uses the font from the source VT. Here * we update all possibly already allocated VTs with the configured * font. It also allows to restart systemd-vconsole-setup.service, * to apply a new font to all VTs. * * We also setup per-console utf8 related stuff: kbdmode, term * processing, stty iutf8. */ static void setup_remaining_vcs(int src_fd, unsigned src_idx, bool utf8) { struct console_font_op cfo = { .op = KD_FONT_OP_GET, .width = UINT_MAX, .height = UINT_MAX, .charcount = UINT_MAX, }; struct unimapinit adv = {}; struct unimapdesc unimapd; _cleanup_free_ struct unipair* unipairs = NULL; _cleanup_free_ void *fontbuf = NULL; unsigned i; int r; unipairs = new(struct unipair, USHRT_MAX); if (!unipairs) { log_oom(); return; } /* get metadata of the current font (width, height, count) */ r = ioctl(src_fd, KDFONTOP, &cfo); if (r < 0) log_warning_errno(errno, "KD_FONT_OP_GET failed while trying to get the font metadata: %m"); else { /* verify parameter sanity first */ if (cfo.width > 32 || cfo.height > 32 || cfo.charcount > 512) log_warning("Invalid font metadata - width: %u (max 32), height: %u (max 32), count: %u (max 512)", cfo.width, cfo.height, cfo.charcount); else { /* * Console fonts supported by the kernel are limited in size to 32 x 32 and maximum 512 * characters. Thus with 1 bit per pixel it requires up to 65536 bytes. The height always * requires 32 per glyph, regardless of the actual height - see the comment above #define * max_font_size 65536 in drivers/tty/vt/vt.c for more details. */ fontbuf = malloc_multiply((cfo.width + 7) / 8 * 32, cfo.charcount); if (!fontbuf) { log_oom(); return; } /* get fonts from the source console */ cfo.data = fontbuf; r = ioctl(src_fd, KDFONTOP, &cfo); if (r < 0) log_warning_errno(errno, "KD_FONT_OP_GET failed while trying to read the font data: %m"); else { unimapd.entries = unipairs; unimapd.entry_ct = USHRT_MAX; r = ioctl(src_fd, GIO_UNIMAP, &unimapd); if (r < 0) log_warning_errno(errno, "GIO_UNIMAP failed while trying to read unicode mappings: %m"); else cfo.op = KD_FONT_OP_SET; } } } if (cfo.op != KD_FONT_OP_SET) log_warning("Fonts will not be copied to remaining consoles"); for (i = 1; i <= 63; i++) { char ttyname[sizeof("/dev/tty63")]; _cleanup_close_ int fd_d = -1; if (i == src_idx || verify_vc_allocation(i) < 0) continue; /* try to open terminal */ xsprintf(ttyname, "/dev/tty%u", i); fd_d = open_terminal(ttyname, O_RDWR|O_CLOEXEC|O_NOCTTY); if (fd_d < 0) { log_warning_errno(fd_d, "Unable to open tty%u, fonts will not be copied: %m", i); continue; } if (verify_vc_kbmode(fd_d) < 0) continue; toggle_utf8(ttyname, fd_d, utf8); if (cfo.op != KD_FONT_OP_SET) continue; r = ioctl(fd_d, KDFONTOP, &cfo); if (r < 0) { int last_errno, mode; /* The fonts couldn't have been copied. It might be due to the * terminal being in graphical mode. In this case the kernel * returns -EINVAL which is too generic for distinguishing this * specific case. So we need to retrieve the terminal mode and if * the graphical mode is in used, let's assume that something else * is using the terminal and the failure was expected as we * shouldn't have tried to copy the fonts. */ last_errno = errno; if (ioctl(fd_d, KDGETMODE, &mode) >= 0 && mode != KD_TEXT) log_debug("KD_FONT_OP_SET skipped: tty%u is not in text mode", i); else log_warning_errno(last_errno, "KD_FONT_OP_SET failed, fonts will not be copied to tty%u: %m", i); continue; } /* * copy unicode translation table unimapd is a ushort count and a pointer * to an array of struct unipair { ushort, ushort } */ r = ioctl(fd_d, PIO_UNIMAPCLR, &adv); if (r < 0) { log_warning_errno(errno, "PIO_UNIMAPCLR failed, unimaps might be incorrect for tty%u: %m", i); continue; } r = ioctl(fd_d, PIO_UNIMAP, &unimapd); if (r < 0) { log_warning_errno(errno, "PIO_UNIMAP failed, unimaps might be incorrect for tty%u: %m", i); continue; } log_debug("Font and unimap successfully copied to %s", ttyname); } } static int find_source_vc(char **ret_path, unsigned *ret_idx) { _cleanup_free_ char *path = NULL; int r, err = 0; unsigned i; path = new(char, sizeof("/dev/tty63")); if (!path) return log_oom(); for (i = 1; i <= 63; i++) { _cleanup_close_ int fd = -1; r = verify_vc_allocation(i); if (r < 0) { if (!err) err = -r; continue; } sprintf(path, "/dev/tty%u", i); fd = open_terminal(path, O_RDWR|O_CLOEXEC|O_NOCTTY); if (fd < 0) { if (!err) err = -fd; continue; } r = verify_vc_kbmode(fd); if (r < 0) { if (!err) err = -r; continue; } /* all checks passed, return this one as a source console */ *ret_idx = i; *ret_path = TAKE_PTR(path); return TAKE_FD(fd); } return log_error_errno(err, "No usable source console found: %m"); } static int verify_source_vc(char **ret_path, const char *src_vc) { _cleanup_close_ int fd = -1; char *path; int r; fd = open_terminal(src_vc, O_RDWR|O_CLOEXEC|O_NOCTTY); if (fd < 0) return log_error_errno(fd, "Failed to open %s: %m", src_vc); r = verify_vc_device(fd); if (r < 0) return log_error_errno(r, "Device %s is not a virtual console: %m", src_vc); r = verify_vc_allocation_byfd(fd); if (r < 0) return log_error_errno(r, "Virtual console %s is not allocated: %m", src_vc); r = verify_vc_kbmode(fd); if (r < 0) return log_error_errno(r, "Virtual console %s is not in K_XLATE or K_UNICODE: %m", src_vc); path = strdup(src_vc); if (!path) return log_oom(); *ret_path = path; return TAKE_FD(fd); } int main(int argc, char **argv) { _cleanup_free_ char *vc = NULL, *vc_keymap = NULL, *vc_keymap_toggle = NULL, *vc_font = NULL, *vc_font_map = NULL, *vc_font_unimap = NULL; _cleanup_close_ int fd = -1; bool utf8, keyboard_ok; unsigned idx = 0; int r; log_setup_service(); umask(0022); if (argv[1]) fd = verify_source_vc(&vc, argv[1]); else fd = find_source_vc(&vc, &idx); if (fd < 0) return EXIT_FAILURE; utf8 = is_locale_utf8(); r = parse_env_file(NULL, "/etc/vconsole.conf", "KEYMAP", &vc_keymap, "KEYMAP_TOGGLE", &vc_keymap_toggle, "FONT", &vc_font, "FONT_MAP", &vc_font_map, "FONT_UNIMAP", &vc_font_unimap); if (r < 0 && r != -ENOENT) log_warning_errno(r, "Failed to read /etc/vconsole.conf: %m"); /* Let the kernel command line override /etc/vconsole.conf */ r = proc_cmdline_get_key_many( PROC_CMDLINE_STRIP_RD_PREFIX, "vconsole.keymap", &vc_keymap, "vconsole.keymap_toggle", &vc_keymap_toggle, "vconsole.font", &vc_font, "vconsole.font_map", &vc_font_map, "vconsole.font_unimap", &vc_font_unimap, /* compatibility with obsolete multiple-dot scheme */ "vconsole.keymap.toggle", &vc_keymap_toggle, "vconsole.font.map", &vc_font_map, "vconsole.font.unimap", &vc_font_unimap); if (r < 0 && r != -ENOENT) log_warning_errno(r, "Failed to read /proc/cmdline: %m"); (void) toggle_utf8_sysfs(utf8); (void) toggle_utf8(vc, fd, utf8); r = font_load_and_wait(vc, vc_font, vc_font_map, vc_font_unimap); keyboard_ok = keyboard_load_and_wait(vc, vc_keymap, vc_keymap_toggle, utf8) == 0; if (idx > 0) { if (r == 0) setup_remaining_vcs(fd, idx, utf8); else if (r == EX_OSERR) /* setfont returns EX_OSERR when ioctl(KDFONTOP/PIO_FONTX/PIO_FONTX) fails. * This might mean various things, but in particular lack of a graphical * console. Let's be generous and not treat this as an error. */ log_notice("Setting fonts failed with a \"system error\", ignoring."); else log_warning("Setting source virtual console failed, ignoring remaining ones"); } return IN_SET(r, 0, EX_OSERR) && keyboard_ok ? EXIT_SUCCESS : EXIT_FAILURE; }
./CrossVul/dataset_final_sorted/CWE-255/c/bad_536_2
crossvul-cpp_data_good_915_1
/* * Copyright (C) 2017 ~ 2017 Deepin Technology Co., Ltd. * * Author: zccrs <zccrs@live.com> * * Maintainer: zccrs <zhangjide@deepin.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "helper.h" #include "dpartinfo.h" #include "dglobal.h" #include "ddevicepartinfo.h" #include "ddiskinfo.h" #include <QProcess> #include <QEventLoop> #include <QTimer> #include <QJsonDocument> #include <QJsonObject> #include <QFile> #include <QDebug> #include <QLoggingCategory> #include <QRegularExpression> #include <QUuid> #define COMMAND_LSBLK QStringLiteral("/bin/lsblk -J -b -p -o NAME,KNAME,PKNAME,FSTYPE,MOUNTPOINT,LABEL,UUID,SIZE,TYPE,PARTTYPE,PARTLABEL,PARTUUID,MODEL,PHY-SEC,RO,RM,TRAN,SERIAL %1") QByteArray Helper::m_processStandardError; QByteArray Helper::m_processStandardOutput; Q_LOGGING_CATEGORY(lcDeepinGhost, "deepin.ghost") Q_GLOBAL_STATIC(Helper, _g_globalHelper) Helper *Helper::instance() { return _g_globalHelper; } int Helper::processExec(QProcess *process, const QString &command, int timeout, QIODevice::OpenMode mode) { m_processStandardOutput.clear(); m_processStandardError.clear(); QEventLoop loop; QTimer timer; timer.setSingleShot(true); timer.setInterval(timeout); timer.connect(&timer, &QTimer::timeout, &loop, &QEventLoop::quit); loop.connect(process, static_cast<void(QProcess::*)(int)>(&QProcess::finished), &loop, &QEventLoop::exit); // 防止子进程输出信息将管道塞满导致进程阻塞 process->connect(process, &QProcess::readyReadStandardError, process, [process] { m_processStandardError.append(process->readAllStandardError()); }); process->connect(process, &QProcess::readyReadStandardOutput, process, [process] { m_processStandardOutput.append(process->readAllStandardOutput()); }); if (timeout > 0) { timer.start(); } else { QTimer::singleShot(10000, process, [process] { dCWarning("\"%s %s\" running for more than 10 seconds, state=%d, pid_file_exist=%d", qPrintable(process->program()), qPrintable(process->arguments().join(" ")), (int)process->state(), (int)QFile::exists(QString("/proc/%1").arg(process->pid()))); }); } if (Global::debugLevel > 1) dCDebug("Exec: \"%s\", timeout: %d", qPrintable(command), timeout); process->start(command, mode); process->waitForStarted(); if (process->error() != QProcess::UnknownError) { dCError(process->errorString()); return -1; } if (process->state() == QProcess::Running) { loop.exec(); } if (process->state() != QProcess::NotRunning) { dCDebug("The \"%s\" timeout, timeout: %d", qPrintable(command), timeout); // QT Bug,某种情况下(未知) QProcess::state 返回的状态有误,导致进程已退出却未能正确获取到其当前状态 // 因此,额外通过系统文件判断进程是否还存在 if (QFile::exists(QString("/proc/%1").arg(process->pid()))) { process->terminate(); process->waitForFinished(); } else { dCDebug("The \"%s\" is quit, but the QProcess object state is not NotRunning"); } } m_processStandardOutput.append(process->readAllStandardOutput()); m_processStandardError.append(process->readAllStandardError()); if (Global::debugLevel > 1) { dCDebug("Done: \"%s\", exit code: %d", qPrintable(command), process->exitCode()); if (process->exitCode() != 0) { dCError("error: \"%s\"\nstdout: \"%s\"", qPrintable(m_processStandardError), qPrintable(m_processStandardOutput)); } } return process->exitCode(); } int Helper::processExec(const QString &command, int timeout) { QProcess process; return processExec(&process, command, timeout); } QByteArray Helper::lastProcessStandardOutput() { return m_processStandardOutput; } QByteArray Helper::lastProcessStandardError() { return m_processStandardError; } const QLoggingCategory &Helper::loggerCategory() { return lcDeepinGhost(); } void Helper::warning(const QString &message) { m_warningString = message; emit newWarning(message); } void Helper::error(const QString &message) { m_errorString = message; emit newError(message); } QString Helper::lastWarningString() { return m_warningString; } QString Helper::lastErrorString() { return m_errorString; } QString Helper::sizeDisplay(qint64 size) { constexpr qreal kb = 1024; constexpr qreal mb = kb * 1024; constexpr qreal gb = mb * 1024; constexpr qreal tb = gb * 1024; if (size > tb) return QString::asprintf("%.2f TB", size / tb); if (size > gb) return QString::asprintf("%.2f GB", size / gb); if (size > mb) return QString::asprintf("%.2f MB", size / mb); if (size > kb) return QString::asprintf("%.2f KB", size / kb); return QString("%1 B").arg(size); } QString Helper::secondsToString(qint64 seconds) { int days = seconds / 86400; seconds = seconds % 86400; int hours = seconds / 3600; seconds = seconds % 3600; int minutes = seconds / 60; seconds = seconds % 60; if (days > 0) return QObject::tr("%1 d %2 h %3 m").arg(days).arg(hours).arg(minutes + 1); if (hours > 0) return QObject::tr("%1 h %2 m").arg(hours).arg(minutes + 1); if (minutes > 0) return QObject::tr("%1 m").arg(minutes + 1); return QObject::tr("%1 s").arg(seconds); } bool Helper::refreshSystemPartList(const QString &device) { int code = device.isEmpty() ? processExec("partprobe") : processExec(QString("partprobe %1").arg(device)); if (code != 0) return false; QThread::sleep(1); return true; } QString Helper::getPartcloneExecuter(const DPartInfo &info) { QString executor; switch (info.fileSystemType()) { case DPartInfo::Invalid: break; case DPartInfo::Btrfs: executor = "btrfs"; break; case DPartInfo::EXT2: case DPartInfo::EXT3: case DPartInfo::EXT4: executor = "extfs"; break; case DPartInfo::F2FS: executor = "f2fs"; break; case DPartInfo::FAT12: case DPartInfo::FAT16: case DPartInfo::FAT32: executor = "fat"; break; case DPartInfo::HFS_Plus: executor = "hfsplus"; break; case DPartInfo::Minix: executor = "minix"; break; case DPartInfo::Nilfs2: executor = "nilfs2"; break; case DPartInfo::NTFS: executor = "ntfs -I"; break; case DPartInfo::Reiser4: executor = "reiser4"; break; case DPartInfo::VFAT: executor = "vfat"; break; case DPartInfo::XFS: executor = "xfs"; break; default: if (!QStandardPaths::findExecutable("partclone." + info.fileSystemTypeName().toLower()).isEmpty()) executor = info.fileSystemTypeName().toLower(); break; } if (executor.isEmpty()) return "partclone.imager"; return "partclone." + executor; } bool Helper::getPartitionSizeInfo(const QString &partDevice, qint64 *used, qint64 *free, int *blockSize) { QProcess process; QStringList env_list = QProcess::systemEnvironment(); env_list.append("LANG=C"); process.setEnvironment(env_list); if (Helper::isMounted(partDevice)) { process.start(QString("df -B1 -P %1").arg(partDevice)); process.waitForFinished(); if (process.exitCode() != 0) { dCError("Call df failed: %s", qPrintable(process.readAllStandardError())); return false; } QByteArray output = process.readAll(); const QByteArrayList &lines = output.trimmed().split('\n'); if (lines.count() != 2) return false; output = lines.last().simplified(); const QByteArrayList &values = output.split(' '); if (values.count() != 6) return false; bool ok = false; if (used) *used = values.at(2).toLongLong(&ok); if (!ok) return false; if (free) *free = values.at(3).toLongLong(&ok); if (!ok) return false; return true; } else { process.start(QString("%1 -s %2 -c -q -C -L /var/log/partclone.log").arg(getPartcloneExecuter(DDevicePartInfo(partDevice))).arg(partDevice)); process.setStandardOutputFile("/dev/null"); process.setReadChannel(QProcess::StandardError); process.waitForStarted(); qint64 used_block = -1; qint64 free_block = -1; while (process.waitForReadyRead(5000)) { const QByteArray &data = process.readAll(); for (QByteArray line : data.split('\n')) { line = line.simplified(); if (QString::fromLatin1(line).contains(QRegularExpression("\\berror\\b"))) { dCError("Call \"%s %s\" failed: \"%s\"", qPrintable(process.program()), qPrintable(process.arguments().join(' ')), line.constData()); } if (line.startsWith("Space in use:")) { bool ok = false; const QByteArray &value = line.split(' ').value(6, "-1"); used_block = value.toLongLong(&ok); if (!ok) { dCError("String to LongLong failed, String: %s", value.constData()); return false; } } else if (line.startsWith("Free Space:")) { bool ok = false; const QByteArray &value = line.split(' ').value(5, "-1"); free_block = value.toLongLong(&ok); if (!ok) { dCError("String to LongLong failed, String: %s", value.constData()); return false; } } else if (line.startsWith("Block size:")) { bool ok = false; const QByteArray &value = line.split(' ').value(2, "-1"); int block_size = value.toInt(&ok); if (!ok) { dCError("String to Int failed, String: %s", value.constData()); return false; } if (used_block < 0 || free_block < 0 || block_size < 0) return false; if (used) *used = used_block * block_size; if (free) *free = free_block * block_size; if (blockSize) *blockSize = block_size; process.terminate(); process.waitForFinished(); return true; } } } } return false; } QByteArray Helper::callLsblk(const QString &extraArg) { processExec(COMMAND_LSBLK.arg(extraArg)); return lastProcessStandardOutput(); } QJsonArray Helper::getBlockDevices(const QString &commandExtraArg) { const QByteArray &array = Helper::callLsblk(commandExtraArg); QJsonParseError error; const QJsonDocument &jd = QJsonDocument::fromJson(QString::fromUtf8(array).toUtf8(), &error); if (error.error != QJsonParseError::NoError) { dCError(error.errorString()); } return jd.object().value("blockdevices").toArray(); } QString Helper::mountPoint(const QString &device) { const QJsonArray &array = getBlockDevices(device); if (array.isEmpty()) return QString(); return array.first().toObject().value("mountpoint").toString(); } bool Helper::isMounted(const QString &device) { const QJsonArray &array = getBlockDevices("-l " + device); for (const QJsonValue &part : array) { const QJsonObject &obj = part.toObject(); if (!obj.value("mountpoint").isNull()) return true; } return false; } bool Helper::umountDevice(const QString &device) { const QJsonArray &array = getBlockDevices("-l " + device); for (const QJsonValue &device : array) { const QJsonObject &obj = device.toObject(); if (!obj.value("mountpoint").isNull()) { if (processExec(QString("umount -d %1").arg(obj.value("name").toString())) != 0) return false; } } return true; } bool Helper::tryUmountDevice(const QString &device) { const QJsonArray &array = getBlockDevices("-l " + device); for (const QJsonValue &device : array) { const QJsonObject &obj = device.toObject(); if (!obj.value("mountpoint").isNull()) { if (processExec(QString("umount -d %1 --fake").arg(obj.value("name").toString())) != 0) return false; } } return true; } bool Helper::mountDevice(const QString &device, const QString &path, bool readonly) { if (readonly) return processExec(QString("mount -r %1 %2").arg(device, path)) == 0; return processExec(QString("mount %1 %2").arg(device, path)) == 0; } QString Helper::temporaryMountDevice(const QString &device, const QString &name, bool readonly) { QString mount_point = mountPoint(device); if (!mount_point.isEmpty()) return mount_point; mount_point = "%1/.%2/mount/%3"; const QStringList &tmp_paths = QStandardPaths::standardLocations(QStandardPaths::RuntimeLocation); mount_point = mount_point.arg(tmp_paths.isEmpty() ? "/run/user/0" : tmp_paths.first()).arg(qApp->applicationName()).arg(name); if (!QDir::current().mkpath(mount_point)) { dCError("mkpath \"%s\" failed", qPrintable(mount_point)); return QString(); } if (!mountDevice(device, mount_point, readonly)) { dCError("Mount the device \"%s\" to \"%s\" failed", qPrintable(device), qPrintable(mount_point)); return QString(); } return mount_point; } QString Helper::findDiskBySerialIndexNumber(const QString &serialNumber, int partIndexNumber) { const QJsonArray &array = getBlockDevices(); for (const QJsonValue &disk : array) { const QJsonObject &obj = disk.toObject(); if (obj.value("serial").toString().compare(serialNumber, Qt::CaseInsensitive) != 0) { continue; } if (partIndexNumber <= 0) return obj.value("name").toString(); const QJsonArray &children = obj.value("children").toArray(); for (const QJsonValue &v : children) { const QJsonObject &obj = v.toObject(); const QString &name = obj.value("name").toString(); if (DDevicePartInfo(name).indexNumber() == partIndexNumber) return name; } } return QString(); } int Helper::partitionIndexNumber(const QString &partDevice) { const QJsonArray &array = getBlockDevices(partDevice); if (array.isEmpty()) return -1; const QJsonArray &p_array = getBlockDevices(array.first().toObject().value("pkname").toString() + " -x NAME"); if (p_array.isEmpty()) return -1; const QJsonArray &part_list = p_array.first().toObject().value("children").toArray(); for (int i = 0; i < part_list.count(); ++i) { const QJsonObject &obj = part_list.at(i).toObject(); if (obj.value("name").toString() == partDevice || obj.value("kname").toString() == partDevice) return i; } return -1; } QByteArray Helper::getPartitionTable(const QString &devicePath) { processExec(QStringLiteral("/sbin/sfdisk -d %1").arg(devicePath)); return lastProcessStandardOutput(); } bool Helper::setPartitionTable(const QString &devicePath, const QString &ptFile) { QProcess process; process.setStandardInputFile(ptFile); if (processExec(&process, QStringLiteral("/sbin/sfdisk %1").arg(devicePath)) != 0) return false; int code = processExec(QStringLiteral("/sbin/partprobe %1").arg(devicePath)); processExec("sleep 1"); return code == 0; } bool Helper::saveToFile(const QString &fileName, const QByteArray &data, bool override) { if (!override && QFile::exists(fileName)) return false; QFile file(fileName); if (!file.open(QIODevice::WriteOnly)) { dCError(file.errorString()); return false; } qint64 size = file.write(data); file.flush(); file.close(); return size == data.size(); } bool Helper::isBlockSpecialFile(const QString &fileName) { if (fileName.startsWith("/dev/")) return true; processExec(QStringLiteral("env LANG=C stat -c %F %1").arg(fileName)); return lastProcessStandardOutput() == "block special file\n"; } bool Helper::isPartcloneFile(const QString &fileName) { return processExec(QStringLiteral("partclone.info %1").arg(fileName)) == 0; } bool Helper::isDiskDevice(const QString &devicePath) { const QJsonArray &blocks = getBlockDevices(devicePath); if (blocks.isEmpty()) return false; if (!blocks.first().isObject()) return false; return blocks.first().toObject().value("pkname").isNull(); } bool Helper::isPartitionDevice(const QString &devicePath) { const QJsonArray &blocks = getBlockDevices(devicePath); if (blocks.isEmpty()) return false; if (!blocks.first().isObject()) return false; return !blocks.first().toObject().value("pkname").isString(); } QString Helper::parentDevice(const QString &device) { const QJsonArray &blocks = getBlockDevices(device); if (blocks.isEmpty()) return device; const QString &parent = blocks.first().toObject().value("pkname").toString(); if (parent.isEmpty()) return device; return parent; } bool Helper::deviceHaveKinship(const QString &device1, const QString &device2) { return device1 == device2 || parentDevice(device1) == parentDevice(device2); } int Helper::clonePartition(const DPartInfo &part, const QString &to, bool override) { QString executor = getPartcloneExecuter(part); QString command; if (executor.isEmpty() || executor == "partclone.imager") { if (part.guidType() == DPartInfo::InvalidGUID) return -1; command = QStringLiteral("dd if=%1 of=%2 status=none conv=fsync").arg(part.filePath()).arg(to); } else if (isBlockSpecialFile(to)) { command = QStringLiteral("/usr/sbin/%1 -b -c -s %2 -%3 %4").arg(executor).arg(part.filePath()).arg(override ? "O" : "o").arg(to); } else { command = QStringLiteral("/usr/sbin/%1 -c -s %2 -%3 %4").arg(executor).arg(part.filePath()).arg(override ? "O" : "o").arg(to); } int code = processExec(command); if (code != 0) qDebug() << command << QString::fromUtf8(lastProcessStandardOutput()); return code; } int Helper::restorePartition(const QString &from, const DPartInfo &to) { QString command; if (isPartcloneFile(from)) { command = QStringLiteral("/usr/sbin/partclone.restore -s %1 -o %2").arg(from).arg(to.filePath()); } else { command = QStringLiteral("dd if=%1 of=%2 status=none conv=fsync").arg(from).arg(to.filePath()); } int code = processExec(command); if (code != 0) qDebug() << command << QString::fromUtf8(lastProcessStandardOutput()); return code; } bool Helper::existLiveSystem() { return QFile::exists("/recovery"); } bool Helper::restartToLiveSystem(const QStringList &arguments) { if (!existLiveSystem()) { dCDebug("Not install live system"); return false; } if (!QDir::current().mkpath("/recovery/.tmp")) { dCDebug("mkpath failed"); return false; } QFile file("/recovery/.tmp/deepin-clone.arguments"); if (!file.open(QIODevice::WriteOnly)) { dCDebug("Open file failed: \"%s\"", qPrintable(file.fileName())); return false; } file.write(arguments.join('\n').toUtf8()); file.close(); if (processExec("grub-reboot \"Deepin Recovery\"") != 0) { dCDebug("Exec grub-reboot \"Deepin Recovery\" failed"); file.remove(); return false; } if (processExec("reboot") != 0) file.remove(); return true; } bool Helper::isDeepinSystem(const DPartInfo &part) { QString mout_root = part.mountPoint(); bool umount_device = false; if (mout_root.isEmpty()) { mout_root = temporaryMountDevice(part.name(), QFileInfo(part.name()).fileName(), true); if (mout_root.isEmpty()) return false; umount_device = true; } bool is = QFile::exists(mout_root + "/etc/deepin-version"); if (umount_device) umountDevice(part.name()); return is; } bool Helper::resetPartUUID(const DPartInfo &part, QByteArray uuid) { QString command; if (uuid.isEmpty()) { uuid = QUuid::createUuid().toByteArray().mid(1, 36); } switch (part.fileSystemType()) { case DPartInfo::EXT2: case DPartInfo::EXT3: case DPartInfo::EXT4: command = QString("tune2fs -U %1 %2").arg(QString::fromLatin1(uuid)).arg(part.filePath()); break; case DPartInfo::JFS: command = QString("jfs_tune -U %1 %2").arg(QString::fromLatin1(uuid)).arg(part.filePath()); break; case DPartInfo::NTFS: command = QString("ntfslabel --new-half-serial %1").arg(part.filePath()); break; case DPartInfo::XFS: command = QString("xfs_admin -U %1 %2").arg(QString::fromLatin1(uuid)).arg(part.filePath()); break; default: dCDebug("Not support the file system type: %s", qPrintable(part.fileSystemTypeName())); return false; } if (!umountDevice(part.filePath())) { dCDebug("Failed to umount the partition: %s", qPrintable(part.filePath())); return false; } // check the partition processExec("fsck -f -y " + part.filePath()); bool ok = processExec(command) == 0; if (!ok) { dCError("Failed reset part uuid"); dCDebug(qPrintable(lastProcessStandardOutput())); dCError(qPrintable(lastProcessStandardError())); } return ok; } QString Helper::parseSerialUrl(const QString &urlString, QString *errorString) { if (urlString.isEmpty()) return QString(); const QUrl url(urlString); const QString serial_number = urlString.split("//").at(1).split(":").first(); const int part_index = url.port(); const QString &path = url.path(); const QString &device = Helper::findDiskBySerialIndexNumber(serial_number, part_index); const QString &device_url = part_index > 0 ? QString("serial://%1:%2").arg(serial_number).arg(part_index) : "serial://" + serial_number; if (device.isEmpty()) { if (errorString) { if (part_index > 0) *errorString = QObject::tr("Partition \"%1\" not found").arg(device_url); else *errorString = QObject::tr("Disk \"%1\" not found").arg(device_url); } return device; } if (path.isEmpty()) return device; const QString &mp = Helper::mountPoint(device); QDir mount_point(mp); if (mp.isEmpty()) { QString mount_name; if (part_index >= 0) mount_name = QString("%1-%2").arg(serial_number).arg(part_index); else mount_name = serial_number; const QString &_mount_point = Helper::temporaryMountDevice(device, mount_name); if (_mount_point.isEmpty()) { if (errorString) *errorString = QObject::tr("Failed to mount partition \"%1\"").arg(device_url); return QString(); } mount_point.setPath(_mount_point); } if (mount_point.absolutePath() == "/") return path; return mount_point.absolutePath() + path; } QString Helper::getDeviceForFile(const QString &file, QString *rootPath) { if (file.isEmpty()) return QString(); if (Helper::isBlockSpecialFile(file)) return file; QFileInfo info(file); while (!info.exists() && info.absoluteFilePath() != "/") info.setFile(info.absolutePath()); QStorageInfo storage_info(info.absoluteFilePath()); if (rootPath) *rootPath = storage_info.rootPath(); return QString::fromUtf8(storage_info.device()); } QString Helper::toSerialUrl(const QString &file) { if (file.isEmpty()) return QString(); if (Helper::isBlockSpecialFile(file)) { DDiskInfo info; if (Helper::isDiskDevice(file)) info = DDiskInfo::getInfo(file); else info = DDiskInfo::getInfo(Helper::parentDevice(file)); if (!info) return QString(); if (info.serial().isEmpty()) return QString(); int index = DDevicePartInfo(file).indexNumber(); if (index == 0) return "serial://" + info.serial(); return QString("serial://%1:%2").arg(info.serial()).arg(index); } QString root_path; QString url = toSerialUrl(getDeviceForFile(file, &root_path)); if (root_path == "/") return url + QFileInfo(file).absoluteFilePath(); return url + QFileInfo(file).absoluteFilePath().mid(root_path.length()); }
./CrossVul/dataset_final_sorted/CWE-59/cpp/good_915_1
crossvul-cpp_data_bad_5719_2
#include "TestSupport.h" #include "ServerInstanceDir.h" using namespace Passenger; using namespace std; namespace tut { struct ServerInstanceDirTest { string parentDir; TempDir tmpDir; string nobodyGroup; ServerInstanceDirTest(): tmpDir("server_instance_dir_test.tmp") { parentDir = "server_instance_dir_test.tmp"; nobodyGroup = getPrimaryGroupName("nobody"); } void createGenerationDir(const string &instanceDir, unsigned int number) { string command = "mkdir " + instanceDir + "/generation-" + toString(number); runShellCommand(command.c_str()); } }; DEFINE_TEST_GROUP(ServerInstanceDirTest); TEST_METHOD(2) { // The (string) constructor creates a ServerInstanceDir object that's // associated with the given directory, and creates the directory // if it doesn't exist. ServerInstanceDir dir(parentDir + "/passenger-test.1234"); ServerInstanceDir dir2(dir.getPath()); ServerInstanceDir dir3(parentDir + "/foo"); ensure_equals(dir2.getPath(), dir.getPath()); ensure_equals(dir3.getPath(), parentDir + "/foo"); ensure_equals(getFileType(dir3.getPath()), FT_DIRECTORY); } TEST_METHOD(3) { // A ServerInstanceDir object removes the server instance directory // upon destruction, but only if there are no more generations in it. { ServerInstanceDir dir(parentDir + "/passenger-test.1234"); } ensure_equals(listDir(parentDir).size(), 0u); { ServerInstanceDir dir(parentDir + "/passenger-test.1234"); createGenerationDir(dir.getPath(), 1); } ensure_equals(listDir(parentDir).size(), 1u); } TEST_METHOD(4) { // The destructor does not throw any exceptions if the server instance // directory doesn't exist anymore. ServerInstanceDir dir(parentDir + "/passenger-test.1234"); removeDirTree(dir.getPath()); } TEST_METHOD(5) { // The destructor doesnn't remove the server instance directory if it // wasn't created with the ownership flag or if it's been detached. string path, path2; { ServerInstanceDir dir(parentDir + "/passenger-test.1234", false); ServerInstanceDir dir2(parentDir + "/passenger-test.5678", false); dir2.detach(); path = dir.getPath(); path2 = dir2.getPath(); } ensure_equals(getFileType(path), FT_DIRECTORY); ensure_equals(getFileType(path2), FT_DIRECTORY); } TEST_METHOD(6) { // If there are no existing generations, newGeneration() creates a new // generation directory with number 0. ServerInstanceDir dir(parentDir + "/passenger-test.1234"); unsigned int ncontents = listDir(dir.getPath()).size(); ServerInstanceDir::GenerationPtr generation = dir.newGeneration(true, "nobody", nobodyGroup, 0, 0); ensure_equals(generation->getNumber(), 0u); ensure_equals(getFileType(generation->getPath()), FT_DIRECTORY); ensure_equals(listDir(dir.getPath()).size(), ncontents + 1); } TEST_METHOD(7) { // A Generation object returned by newGeneration() deletes the associated // generation directory upon destruction. ServerInstanceDir dir(parentDir + "/passenger-test.1234"); ServerInstanceDir::GenerationPtr generation = dir.newGeneration(true, "nobody", nobodyGroup, 0, 0); string path = generation->getPath(); generation.reset(); ensure_equals(getFileType(path), FT_NONEXISTANT); } TEST_METHOD(8) { // getNewestGeneration() returns the newest generation. ServerInstanceDir dir(parentDir + "/passenger-test.1234"); ServerInstanceDir::GenerationPtr generation0 = dir.newGeneration(true, "nobody", nobodyGroup, 0, 0); ServerInstanceDir::GenerationPtr generation1 = dir.newGeneration(true, "nobody", nobodyGroup, 0, 0); ServerInstanceDir::GenerationPtr generation2 = dir.newGeneration(true, "nobody", nobodyGroup, 0, 0); ServerInstanceDir::GenerationPtr generation3 = dir.newGeneration(true, "nobody", nobodyGroup, 0, 0); generation2.reset(); ensure_equals(dir.getNewestGeneration()->getNumber(), 3u); generation3.reset(); ensure_equals(dir.getNewestGeneration()->getNumber(), 1u); } TEST_METHOD(9) { // getNewestGeneration returns null if there are no generations. ServerInstanceDir dir(parentDir + "/passenger-test.1234"); ensure(dir.getNewestGeneration() == NULL); } TEST_METHOD(10) { // A Generation object returned by getNewestGeneration() doesn't delete // the associated generation directory upon destruction. ServerInstanceDir dir(parentDir + "/passenger-test.1234"); ServerInstanceDir::GenerationPtr generation = dir.newGeneration(true, "nobody", nobodyGroup, 0, 0); ServerInstanceDir::GenerationPtr newestGeneration = dir.getNewestGeneration(); newestGeneration.reset(); ensure_equals(getFileType(generation->getPath()), FT_DIRECTORY); } TEST_METHOD(11) { // getGeneration() returns the given generation. ServerInstanceDir dir(parentDir + "/passenger-test.1234"); ServerInstanceDir::GenerationPtr generation0 = dir.newGeneration(true, "nobody", nobodyGroup, 0, 0); ServerInstanceDir::GenerationPtr generation1 = dir.newGeneration(true, "nobody", nobodyGroup, 0, 0); ServerInstanceDir::GenerationPtr generation2 = dir.newGeneration(true, "nobody", nobodyGroup, 0, 0); ServerInstanceDir::GenerationPtr generation3 = dir.newGeneration(true, "nobody", nobodyGroup, 0, 0); ensure_equals(dir.getGeneration(0)->getNumber(), 0u); ensure_equals(dir.getGeneration(3)->getNumber(), 3u); } TEST_METHOD(12) { // A Generation object returned by getGeneration() doesn't delete the // associated generation directory upon destruction. ServerInstanceDir dir(parentDir + "/passenger-test.1234"); ServerInstanceDir::GenerationPtr generation0 = dir.newGeneration(true, "nobody", nobodyGroup, 0, 0); ServerInstanceDir::GenerationPtr generation1 = dir.newGeneration(true, "nobody", nobodyGroup, 0, 0); dir.getGeneration(0).reset(); dir.getGeneration(1).reset(); ensure_equals(getFileType(generation0->getPath()), FT_DIRECTORY); ensure_equals(getFileType(generation1->getPath()), FT_DIRECTORY); } TEST_METHOD(13) { // A detached Generation doesn't delete the associated generation // directory upon destruction. ServerInstanceDir dir(parentDir + "/passenger-test.1234"); ServerInstanceDir::GenerationPtr generation = dir.newGeneration(true, "nobody", nobodyGroup, 0, 0); string path = generation->getPath(); generation->detach(); generation.reset(); ensure_equals(getFileType(path), FT_DIRECTORY); } TEST_METHOD(14) { // It's possible to have two ServerInstanceDir objects constructed // with the same (pid_t, string) constructor arguments. ServerInstanceDir dir(parentDir + "/passenger-test.1234"); ServerInstanceDir dir2(parentDir + "/passenger-test.1234"); } }
./CrossVul/dataset_final_sorted/CWE-59/cpp/bad_5719_2
crossvul-cpp_data_good_915_0
/* * Copyright (C) 2017 ~ 2017 Deepin Technology Co., Ltd. * * Author: zccrs <zccrs@live.com> * * Maintainer: zccrs <zhangjide@deepin.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #define private public #include <private/qiodevice_p.h> #undef private #include "ddevicediskinfo.h" #include "ddiskinfo_p.h" #include "helper.h" #include "ddevicepartinfo.h" #include "dpartinfo_p.h" #include <QJsonObject> #include <QJsonArray> #include <QJsonDocument> #include <QProcess> #include <QBuffer> static QString getPTName(const QString &device) { Helper::processExec(QStringLiteral("/sbin/blkid -p -s PTTYPE -d -i %1").arg(device)); const QByteArray &data = Helper::lastProcessStandardOutput(); if (data.isEmpty()) return QString(); const QByteArrayList &list = data.split('='); if (list.count() != 3) return QString(); return list.last().simplified(); } class DDeviceDiskInfoPrivate : public DDiskInfoPrivate { public: DDeviceDiskInfoPrivate(DDeviceDiskInfo *qq); ~DDeviceDiskInfoPrivate(); void init(const QJsonObject &obj); QString filePath() const Q_DECL_OVERRIDE; void refresh() Q_DECL_OVERRIDE; bool hasScope(DDiskInfo::DataScope scope, DDiskInfo::ScopeMode mode, int index = 0) const Q_DECL_OVERRIDE; bool openDataStream(int index) Q_DECL_OVERRIDE; void closeDataStream() Q_DECL_OVERRIDE; // Unfulfilled qint64 readableDataSize(DDiskInfo::DataScope scope) const Q_DECL_OVERRIDE; qint64 totalReadableDataSize() const Q_DECL_OVERRIDE; qint64 maxReadableDataSize() const Q_DECL_OVERRIDE; qint64 totalWritableDataSize() const Q_DECL_OVERRIDE; qint64 read(char *data, qint64 maxSize) Q_DECL_OVERRIDE; qint64 write(const char *data, qint64 maxSize) Q_DECL_OVERRIDE; bool atEnd() const Q_DECL_OVERRIDE; QString errorString() const Q_DECL_OVERRIDE; bool isClosing() const; QProcess *process = NULL; QBuffer buffer; bool closing = false; }; DDeviceDiskInfoPrivate::DDeviceDiskInfoPrivate(DDeviceDiskInfo *qq) : DDiskInfoPrivate(qq) { } DDeviceDiskInfoPrivate::~DDeviceDiskInfoPrivate() { closeDataStream(); if (process) process->deleteLater(); } void DDeviceDiskInfoPrivate::init(const QJsonObject &obj) { model = obj.value("model").toString(); name = obj.value("name").toString(); kname = obj.value("kname").toString(); size = obj.value("size").toString().toLongLong(); typeName = obj.value("type").toString(); readonly = obj.value("ro").toString() == "1" || typeName == "rom"; removeable = obj.value("rm").toString() == "1"; transport = obj.value("tran").toString(); serial = obj.value("serial").toString(); if (obj.value("pkname").isNull()) type = DDiskInfo::Disk; else type = DDiskInfo::Part; const QJsonArray &list = obj.value("children").toArray(); QStringList children_uuids; for (const QJsonValue &part : list) { const QJsonObject &obj = part.toObject(); const QString &uuid = obj.value("partuuid").toString(); if (!uuid.isEmpty() && children_uuids.contains(uuid)) continue; DDevicePartInfo info; info.init(obj); if (!info.partUUID().isEmpty() && children_uuids.contains(info.partUUID())) continue; info.d->transport = transport; children << info; children_uuids << info.partUUID(); } qSort(children.begin(), children.end(), [] (const DPartInfo &info1, const DPartInfo &info2) { return info1.sizeStart() < info2.sizeStart(); }); if (type == DDiskInfo::Disk) ptTypeName = getPTName(name); else ptTypeName = getPTName(obj.value("pkname").toString()); if (ptTypeName == "dos") { ptType = DDiskInfo::MBR; } else if (ptTypeName == "gpt") { ptType = DDiskInfo::GPT; } else { ptType = DDiskInfo::Unknow; havePartitionTable = false; } if (type == DDiskInfo::Part) havePartitionTable = false; if ((!havePartitionTable && children.isEmpty()) || type == DDiskInfo::Part) { DDevicePartInfo info; info.init(obj); info.d->transport = transport; info.d->index = 0; children << info; } } QString DDeviceDiskInfoPrivate::filePath() const { return name; } void DDeviceDiskInfoPrivate::refresh() { children.clear(); const QJsonArray &block_devices = Helper::getBlockDevices(name); if (!block_devices.isEmpty()) init(block_devices.first().toObject()); } bool DDeviceDiskInfoPrivate::hasScope(DDiskInfo::DataScope scope, DDiskInfo::ScopeMode mode, int index) const { if (mode == DDiskInfo::Read) { if (scope == DDiskInfo::Headgear) { return havePartitionTable && (children.isEmpty() || children.first().sizeStart() >= 1048576); } else if (scope == DDiskInfo::JsonInfo) { return true; } if (scope == DDiskInfo::PartitionTable) return havePartitionTable; } else if (readonly || scope == DDiskInfo::JsonInfo) { return false; } if (scope == DDiskInfo::Partition) { if (index == 0 && mode == DDiskInfo::Write) return true; const DPartInfo &info = q->getPartByNumber(index); if (!info) { dCDebug("Can not find parition by number(device: \"%s\"): %d", qPrintable(q->filePath()), index); return false; } if (info.isExtended() || (mode == DDiskInfo::Read && info.type() == DPartInfo::Unknow && info.fileSystemType() == DPartInfo::Invalid && info.guidType() == DPartInfo::InvalidGUID)) { dCDebug("Skip the \"%s\" partition, type: %s", qPrintable(info.filePath()), qPrintable(info.typeDescription(info.type()))); return false; } return mode != DDiskInfo::Write || !info.isReadonly(); } return (scope == DDiskInfo::Headgear || scope == DDiskInfo::PartitionTable) ? type == DDiskInfo::Disk : true; } bool DDeviceDiskInfoPrivate::openDataStream(int index) { if (process) { process->deleteLater(); } process = new QProcess(); QObject::connect(process, static_cast<void (QProcess::*)(int, QProcess::ExitStatus)>(&QProcess::finished), process, [this] (int code, QProcess::ExitStatus status) { if (isClosing()) return; if (status == QProcess::CrashExit) { setErrorString(QObject::tr("process \"%1 %2\" crashed").arg(process->program()).arg(process->arguments().join(" "))); } else if (code != 0) { setErrorString(QObject::tr("Failed to perform process \"%1 %2\", error: %3").arg(process->program()).arg(process->arguments().join(" ")).arg(QString::fromUtf8(process->readAllStandardError()))); } }); switch (currentScope) { case DDiskInfo::Headgear: { if (type != DDiskInfo::Disk) { setErrorString(QObject::tr("\"%1\" is not a disk device").arg(filePath())); return false; } if (currentMode == DDiskInfo::Read) { process->start(QStringLiteral("dd if=%1 bs=512 count=2048 status=none").arg(filePath()), QIODevice::ReadOnly); } else { process->start(QStringLiteral("dd of=%1 bs=512 status=none conv=fsync").arg(filePath())); } break; } case DDiskInfo::PartitionTable: { if (type != DDiskInfo::Disk) { setErrorString(QObject::tr("\"%1\" is not a disk device").arg(filePath())); return false; } if (currentMode == DDiskInfo::Read) process->start(QStringLiteral("sfdisk -d %1").arg(filePath()), QIODevice::ReadOnly); else process->start(QStringLiteral("sfdisk %1 --no-reread").arg(filePath())); break; } case DDiskInfo::Partition: { const DPartInfo &part = (index == 0 && currentMode == DDiskInfo::Write) ? DDevicePartInfo(filePath()) : q->getPartByNumber(index); if (!part) { dCDebug("Part is null(index: %d)", index); return false; } dCDebug("Try open device: %s, mode: %s", qPrintable(part.filePath()), currentMode == DDiskInfo::Read ? "Read" : "Write"); if (Helper::isMounted(part.filePath())) { if (Helper::umountDevice(part.filePath())) { part.d->mountPoint.clear(); } else { setErrorString(QObject::tr("\"%1\" is busy").arg(part.filePath())); return false; } } if (currentMode == DDiskInfo::Read) { const QString &executer = Helper::getPartcloneExecuter(part); process->start(QStringLiteral("%1 -s %2 -o - -c -z %3 -L /var/log/partclone.log").arg(executer).arg(part.filePath()).arg(Global::bufferSize), QIODevice::ReadOnly); } else { process->start(QStringLiteral("partclone.restore -s - -o %2 -z %3 -L /var/log/partclone.log").arg(part.filePath()).arg(Global::bufferSize)); } break; } case DDiskInfo::JsonInfo: { process->deleteLater(); process = 0; buffer.setData(q->toJson()); break; } default: return false; } if (process) { if (!process->waitForStarted()) { setErrorString(QObject::tr("Failed to start \"%1 %2\", error: %3").arg(process->program()).arg(process->arguments().join(" ")).arg(process->errorString())); return false; } dCDebug("The \"%s %s\" command start finished", qPrintable(process->program()), qPrintable(process->arguments().join(" "))); } bool ok = process ? process->isOpen() : buffer.open(QIODevice::ReadOnly); if (!ok) { setErrorString(QObject::tr("Failed to open process, error: %1").arg(process ? process->errorString(): buffer.errorString())); } return ok; } void DDeviceDiskInfoPrivate::closeDataStream() { closing = true; if (process) { if (process->state() != QProcess::NotRunning) { if (currentMode == DDiskInfo::Read) { process->closeReadChannel(QProcess::StandardOutput); process->terminate(); } else { process->closeWriteChannel(); } while (process->state() != QProcess::NotRunning) { QThread::currentThread()->sleep(1); if (!QFile::exists(QString("/proc/%2").arg(process->pid()))) { process->waitForFinished(-1); if (process->error() == QProcess::Timedout) process->QIODevice::d_func()->errorString.clear(); break; } } } dCDebug("Process exit code: %d(%s %s)", process->exitCode(), qPrintable(process->program()), qPrintable(process->arguments().join(' '))); } if (currentMode == DDiskInfo::Write && currentScope == DDiskInfo::PartitionTable) { Helper::umountDevice(filePath()); if (Helper::refreshSystemPartList(filePath())) { refresh(); } else { dCWarning("Refresh the devcie %s failed", qPrintable(filePath())); } } if (currentScope == DDiskInfo::JsonInfo) buffer.close(); closing = false; } qint64 DDeviceDiskInfoPrivate::readableDataSize(DDiskInfo::DataScope scope) const { Q_UNUSED(scope) return -1; } qint64 DDeviceDiskInfoPrivate::totalReadableDataSize() const { qint64 size = 0; if (hasScope(DDiskInfo::PartitionTable, DDiskInfo::Read)) { if (hasScope(DDiskInfo::Headgear, DDiskInfo::Read)) { size += 1048576; } else if (!children.isEmpty()) { size += children.first().sizeStart(); } if (ptType == DDiskInfo::MBR) { size += 512; } else if (ptType == DDiskInfo::GPT) { size += 17408; size += 16896; } } for (const DPartInfo &part : children) { if (!part.isExtended()) size += part.usedSize(); } return size; } qint64 DDeviceDiskInfoPrivate::maxReadableDataSize() const { if (children.isEmpty()) { return totalReadableDataSize(); } if (type == DDiskInfo::Disk) return children.last().sizeEnd() + 1; return children.first().totalSize(); } qint64 DDeviceDiskInfoPrivate::totalWritableDataSize() const { return size; } qint64 DDeviceDiskInfoPrivate::read(char *data, qint64 maxSize) { if (!process) { return buffer.read(data, maxSize); } process->waitForReadyRead(-1); if (process->bytesAvailable() > Global::bufferSize) { dCWarning("The \"%s %s\" process bytes available: %s", qPrintable(process->program()), qPrintable(process->arguments().join(" ")), qPrintable(Helper::sizeDisplay(process->bytesAvailable()))); } return process->read(data, maxSize); } qint64 DDeviceDiskInfoPrivate::write(const char *data, qint64 maxSize) { if (!process) return -1; if (process->state() != QProcess::Running) return -1; qint64 size = process->write(data, maxSize); QElapsedTimer timer; timer.start(); int timeout = 5000; while (process->state() == QProcess::Running && process->bytesToWrite() > 0) { process->waitForBytesWritten(); if (timer.elapsed() > timeout) { timeout += 5000; dCWarning("Wait for bytes written timeout, elapsed: %lld, bytes to write: %lld", timer.elapsed(), process->bytesToWrite()); } } return size; } bool DDeviceDiskInfoPrivate::atEnd() const { if (!process) { return buffer.atEnd(); } process->waitForReadyRead(-1); return process->atEnd(); } QString DDeviceDiskInfoPrivate::errorString() const { if (error.isEmpty()) { if (process) { if (process->error() == QProcess::UnknownError) return QString(); return QString("%1 %2: %3").arg(process->program()).arg(process->arguments().join(' ')).arg(process->errorString()); } if (!buffer.QIODevice::d_func()->errorString.isEmpty()) return buffer.errorString(); } return error; } bool DDeviceDiskInfoPrivate::isClosing() const { return closing; } DDeviceDiskInfo::DDeviceDiskInfo() { } DDeviceDiskInfo::DDeviceDiskInfo(const QString &filePath) { const QJsonArray &block_devices = Helper::getBlockDevices(filePath); if (!block_devices.isEmpty()) { const QJsonObject &obj = block_devices.first().toObject(); d = new DDeviceDiskInfoPrivate(this); d_func()->init(obj); if (d->type == Part) { const QJsonArray &parent = Helper::getBlockDevices(obj.value("pkname").toString()); if (!parent.isEmpty()) { const QJsonObject &parent_obj = parent.first().toObject(); d->transport = parent_obj.value("tran").toString(); d->model = parent_obj.value("model").toString(); d->serial = parent_obj.value("serial").toString(); } if (!d->children.isEmpty()) d->children.first().d->transport = d->transport; } } } QList<DDeviceDiskInfo> DDeviceDiskInfo::localeDiskList() { const QJsonArray &block_devices = Helper::getBlockDevices(); QList<DDeviceDiskInfo> list; for (const QJsonValue &value : block_devices) { const QJsonObject &obj = value.toObject(); if (Global::disableLoopDevice && obj.value("type").toString() == "loop") continue; DDeviceDiskInfo info; info.d = new DDeviceDiskInfoPrivate(&info); info.d_func()->init(obj); list << info; } return list; }
./CrossVul/dataset_final_sorted/CWE-59/cpp/good_915_0
crossvul-cpp_data_bad_915_4
/* * Copyright (C) 2017 ~ 2017 Deepin Technology Co., Ltd. * * Author: zccrs <zccrs@live.com> * * Maintainer: zccrs <zhangjide@deepin.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <QDebug> #include <DLog> #ifdef ENABLE_GUI #include <DApplication> #include <DTitlebar> #include <DThemeManager> #include <QDesktopServices> #include "mainwindow.h" #include "dvirtualimagefileio.h" #include <pwd.h> #include <unistd.h> DWIDGET_USE_NAMESPACE #else #include <QCoreApplication> #endif #include "helper.h" #include "dglobal.h" #include "clonejob.h" #include "commandlineparser.h" bool Global::isOverride = true; bool Global::disableMD5CheckForDimFile = false; bool Global::disableLoopDevice = true; bool Global::fixBoot = false; #ifdef ENABLE_GUI bool Global::isTUIMode = false; #else bool Global::isTUIMode = true; #endif int Global::bufferSize = 1024 * 1024; int Global::compressionLevel = 0; int Global::debugLevel = 1; DCORE_USE_NAMESPACE inline static bool isTUIMode(int argc, char *argv[]) { #ifndef ENABLE_GUI Q_UNUSED(argc) Q_UNUSED(argv) return true; #endif if (qEnvironmentVariableIsEmpty("DISPLAY")) return true; const QByteArrayList in_tui_args = { "--tui", "-i", "--info", "--dim-info", "--to-serial-url", "--from-serial-url", "-f", "--fix-boot", "-v", "--version", "-h", "--help", "--re-checksum" }; for (int i = 1; i < argc; ++i) if (in_tui_args.contains(argv[i])) return true; return false; } static QString logFormat = "[%{time}{yyyy-MM-dd, HH:mm:ss.zzz}] [%{type:-7}] [%{file}=>%{function}: %{line}] %{message}\n"; int main(int argc, char *argv[]) { QCoreApplication *a; if (isTUIMode(argc, argv)) { Global::isTUIMode = true; a = new QCoreApplication(argc, argv); } #ifdef ENABLE_GUI else { ConsoleAppender *consoleAppender = new ConsoleAppender; consoleAppender->setFormat(logFormat); RollingFileAppender *rollingFileAppender = new RollingFileAppender("/tmp/.deepin-clone.log"); rollingFileAppender->setFormat(logFormat); rollingFileAppender->setLogFilesLimit(5); rollingFileAppender->setDatePattern(RollingFileAppender::DailyRollover); logger->registerAppender(consoleAppender); logger->registerAppender(rollingFileAppender); if (qEnvironmentVariableIsSet("PKEXEC_UID")) { const quint32 pkexec_uid = qgetenv("PKEXEC_UID").toUInt(); const QDir user_home(getpwuid(pkexec_uid)->pw_dir); QFile pam_file(user_home.absoluteFilePath(".pam_environment")); if (pam_file.open(QIODevice::ReadOnly)) { while (!pam_file.atEnd()) { const QByteArray &line = pam_file.readLine().simplified(); if (line.startsWith("QT_SCALE_FACTOR")) { const QByteArrayList &list = line.split('='); if (list.count() == 2) { qputenv("QT_SCALE_FACTOR", list.last()); break; } } } pam_file.close(); } } DApplication::loadDXcbPlugin(); DApplication *app = new DApplication(argc, argv); app->setAttribute(Qt::AA_UseHighDpiPixmaps); if (!qApp->setSingleInstance("_deepin_clone_")) { qCritical() << "As well as the process is running"; return -1; } if (!app->loadTranslator()) { dError("Load translator failed"); } app->setApplicationDisplayName(QObject::tr("Deepin Clone")); app->setApplicationDescription(QObject::tr("Deepin Clone is a backup and restore tool in deepin. " "It supports disk or partition clone, backup and restore, and other functions.")); app->setApplicationAcknowledgementPage("https://www.deepin.org/acknowledgments/deepin-clone/"); app->setTheme("light"); a = app; } #endif a->setApplicationName("deepin-clone"); #ifdef ENABLE_GUI a->setApplicationVersion(DApplication::buildVersion("1.0.0.1")); #else a->setApplicationVersion("1.0.0.1"); #endif a->setOrganizationName("deepin"); CommandLineParser parser; QFile arguments_file("/lib/live/mount/medium/.tmp/deepin-clone.arguments"); QStringList arguments; bool load_arg_from_file = arguments_file.exists() && !Global::isTUIMode && !a->arguments().contains("--tui"); if (load_arg_from_file) { arguments.append(a->arguments().first()); if (!arguments_file.open(QIODevice::ReadOnly)) { qCritical() << "Open \"/lib/live/mount/medium/.tmp/deepin-clone.arguments\" failed, error:" << arguments_file.errorString(); } else { while (!arguments_file.atEnd()) { const QString &arg = QString::fromUtf8(arguments_file.readLine().trimmed()); if (!arg.isEmpty()) arguments.append(arg); } arguments_file.close(); arguments_file.remove(); } qDebug() << arguments; } else { arguments = a->arguments(); } parser.process(arguments); ConsoleAppender *consoleAppender = new ConsoleAppender; consoleAppender->setFormat(logFormat); RollingFileAppender *rollingFileAppender = new RollingFileAppender(parser.logFile()); rollingFileAppender->setFormat(logFormat); rollingFileAppender->setLogFilesLimit(5); rollingFileAppender->setDatePattern(RollingFileAppender::DailyRollover); logger->registerCategoryAppender("deepin.ghost", consoleAppender); logger->registerCategoryAppender("deepin.ghost", rollingFileAppender); parser.parse(); if (load_arg_from_file) { dCDebug("Load arguments from \"%s\"", qPrintable(arguments_file.fileName())); } dCInfo("Application command line: %s", qPrintable(arguments.join(' '))); if (Global::debugLevel == 0) { QLoggingCategory::setFilterRules("deepin.ghost.debug=false"); } if (Global::isTUIMode) { if (!parser.target().isEmpty()) { CloneJob *job = new CloneJob; QObject::connect(job, &QThread::finished, a, &QCoreApplication::quit); job->start(parser.source(), parser.target()); } } #ifdef ENABLE_GUI else { if (!parser.isSetOverride()) Global::isOverride = true; if (!parser.isSetDebug()) Global::debugLevel = 2; MainWindow *window = new MainWindow; window->setFixedSize(860, 660); window->setStyleSheet(DThemeManager::instance()->getQssForWidget("main", window)); window->setWindowIcon(QIcon::fromTheme("deepin-clone")); window->setWindowFlags(Qt::WindowCloseButtonHint | Qt::WindowMinimizeButtonHint | Qt::WindowSystemMenuHint); window->titlebar()->setIcon(window->windowIcon()); window->titlebar()->setTitle(QString()); #if DTK_VERSION > DTK_VERSION_CHECK(2, 0, 6, 0) window->titlebar()->setBackgroundTransparent(true); #endif window->show(); qApp->setProductIcon(window->windowIcon()); if (!parser.source().isEmpty()) { window->startWithFile(parser.source(), parser.target()); } QObject::connect(a, &QCoreApplication::aboutToQuit, window, &MainWindow::deleteLater); QDesktopServices::setUrlHandler("https", window, "openUrl"); } #endif int exitCode = Global::isTUIMode ? a->exec() : qApp->exec(); QString log_backup_file = parser.logBackupFile(); if (log_backup_file.startsWith("serial://")) { log_backup_file = Helper::parseSerialUrl(log_backup_file); } if (log_backup_file.isEmpty()) { return exitCode; } if (!QFile::copy(parser.logFile(), log_backup_file)) { dCWarning("failed to copy log file to \"%s\"", qPrintable(log_backup_file)); } return exitCode; }
./CrossVul/dataset_final_sorted/CWE-59/cpp/bad_915_4
crossvul-cpp_data_bad_915_3
/* * Copyright (C) 2017 ~ 2017 Deepin Technology Co., Ltd. * * Author: zccrs <zccrs@live.com> * * Maintainer: zccrs <zhangjide@deepin.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "bootdoctor.h" #include "helper.h" #include "ddevicediskinfo.h" #include "ddevicepartinfo.h" QString BootDoctor::m_lastErrorString; bool BootDoctor::fix(const QString &partDevice) { m_lastErrorString.clear(); DDevicePartInfo part_info(partDevice); const QString part_old_uuid = part_info.uuid(); if (Helper::processExec("lsblk -s -d -n -o UUID") == 0) { if (Helper::lastProcessStandardOutput().contains(part_old_uuid.toLatin1())) { // reset uuid if (Helper::resetPartUUID(part_info)) { QThread::sleep(1); part_info.refresh(); qDebug() << part_old_uuid << part_info.uuid(); } else { dCWarning("Failed to reset uuid"); } } } bool device_is_mounted = Helper::isMounted(partDevice); const QString &mount_root = Helper::temporaryMountDevice(partDevice, QFileInfo(partDevice).fileName()); if (mount_root.isEmpty()) { m_lastErrorString = QObject::tr("Failed to mount partition \"%1\"").arg(partDevice); goto failed; } { const QStringList &tmp_paths = QStandardPaths::standardLocations(QStandardPaths::TempLocation); const QString tmp_dir = (tmp_paths.isEmpty() ? "/tmp" : tmp_paths.first()) + "/.deepin-clone"; if (!QDir::current().mkpath(tmp_dir)) { dCError("mkpath \"%s\" failed", qPrintable(tmp_dir)); goto failed; } const QString &repo_path = tmp_dir + "/repo.iso"; if (!QFile::exists(repo_path) && !QFile::copy(QString(":/repo_%1.iso").arg(HOST_ARCH), repo_path)) { dCError("copy file failed, new name: %s", qPrintable(repo_path)); goto failed; } bool ok = false; const QString &repo_mount_point = mount_root + "/deepin-clone"; QFile file_boot_fix(mount_root + "/boot_fix.sh"); do { if (!QDir(mount_root).exists("deepin-clone") && !QDir(mount_root).mkdir("deepin-clone")) { dCError("Create \"deepin-clone\" dir failed(\"%s\")", qPrintable(mount_root)); break; } if (!Helper::mountDevice(repo_path, repo_mount_point, true)) { m_lastErrorString = QObject::tr("Failed to mount partition \"%1\"").arg(repo_path); break; } if (file_boot_fix.exists()) { file_boot_fix.remove(); } if (!QFile::copy(QString(":/scripts/boot_fix_%1.sh").arg( #if defined(HOST_ARCH_x86_64) || defined(HOST_ARCH_i386) || defined(HOST_ARCH_i686) "x86" #elif defined(HOST_ARCH_mips64) || defined(HOST_ARCH_mips32) "mips" #elif defined(HOST_ARCH_sw_64) "sw_64" #elif defined(HOST_ARCH_aarch64) "aarch64" #else #pragma message "Machine: " HOST_ARCH "unknow" #endif ), file_boot_fix.fileName())) { dCError("copy file failed, new name: %s", qPrintable(file_boot_fix.fileName())); break; } if (!file_boot_fix.setPermissions(file_boot_fix.permissions() | QFile::ExeUser)) { dCError("Set \"%s\" permissions failed", qPrintable(file_boot_fix.fileName())); break; } if (Helper::processExec(QString("mount --bind -v --bind /dev %1/dev").arg(mount_root)) != 0) { dCError("Failed to bind /dev"); break; } if (Helper::processExec(QString("mount --bind -v --bind /dev/pts %1/dev/pts").arg(mount_root)) != 0) { dCError("Failed to bind /dev/pts"); break; } if (Helper::processExec(QString("mount --bind -v --bind /proc %1/proc").arg(mount_root)) != 0) { dCError("Failed to bind /proc"); break; } if (Helper::processExec(QString("mount --bind -v --bind /sys %1/sys").arg(mount_root)) != 0) { dCError("Failed to bind /sys"); break; } ok = true; } while (0); QProcess process; if (ok) { const QString &parent_device = Helper::parentDevice(partDevice); bool is_efi = false; if (!parent_device.isEmpty()) { DDeviceDiskInfo info(parent_device); dCDebug("Disk partition table type: %d", info.ptType()); if (info.ptType() == DDeviceDiskInfo::GPT) { for (const DPartInfo &part : info.childrenPartList()) { if (part.guidType() == DPartInfo::EFI_SP_None) { const QString &efi_path = mount_root + "/boot/efi"; QDir::current().mkpath(efi_path); if (Helper::processExec(QString("mount %1 %2").arg(part.filePath()).arg(efi_path)) != 0) { dCError("Failed to mount EFI partition"); m_lastErrorString = QObject::tr("Failed to mount partition \"%1\"").arg(part.filePath()); ok = false; break; } is_efi = true; break; } } if (!is_efi && m_lastErrorString.isEmpty()) { m_lastErrorString = QObject::tr("EFI partition not found"); ok = false; } } else if (info.ptType() == DDeviceDiskInfo::Unknow) { m_lastErrorString = QObject::tr("Unknown partition style"); ok = false; } } if (ok) { process.setProcessChannelMode(QProcess::MergedChannels); process.start(QString("chroot %1 ./boot_fix.sh %2 %3 /deepin-clone") .arg(mount_root) .arg(parent_device) .arg(is_efi ? "true" : "false")); while (process.waitForReadyRead()) { const QByteArray &data = process.readAll().simplified().constData(); dCDebug(data.constData()); } process.waitForFinished(-1); switch (process.exitCode()) { case 1: m_lastErrorString = QObject::tr("Boot for install system failed"); break; case 2: m_lastErrorString = QObject::tr("Boot for update system failed"); break; default: break; } } } // clear Helper::processExec("umount " + repo_mount_point); QDir(mount_root).rmdir("deepin-clone"); file_boot_fix.remove(); Helper::processExec("umount " + mount_root + "/dev/pts"); Helper::processExec("umount " + mount_root + "/dev"); Helper::processExec("umount " + mount_root + "/proc"); Helper::processExec("umount " + mount_root + "/sys"); Helper::processExec("umount " + mount_root + "/boot/efi"); if (ok && process.exitCode() == 0) { if (part_old_uuid != part_info.uuid()) { dCDebug("Reset the uuid from \"%s\" to \"%s\"", qPrintable(part_old_uuid), qPrintable(part_info.uuid())); // update /etc/fstab QFile file(mount_root + "/etc/fstab"); if (file.exists() && file.open(QIODevice::ReadWrite)) { QByteArray data = file.readAll(); if (file.seek(0)) { file.write(data.replace(part_old_uuid.toLatin1(), part_info.uuid().toLatin1())); } file.close(); } else { dCWarning("Failed to update /etc/fstab, error: %s", qPrintable(file.errorString())); } file.setFileName(mount_root + "/etc/crypttab"); if (file.exists() && file.open(QIODevice::ReadWrite)) { QByteArray data = file.readAll(); if (file.seek(0)) { file.write(data.replace(part_old_uuid.toLatin1(), part_info.uuid().toLatin1())); } file.close(); } else { dCWarning("Failed to update /etc/crypttab, error: %s", qPrintable(file.errorString())); } } if (!device_is_mounted) Helper::umountDevice(partDevice); return true; } } failed: if (!device_is_mounted) Helper::umountDevice(partDevice); if (m_lastErrorString.isEmpty()) m_lastErrorString = QObject::tr("Boot for repair system failed"); dCDebug("Restore partition uuid"); if (!Helper::resetPartUUID(part_info, part_old_uuid.toLatin1())) { dCWarning("Failed to restore partition uuid, part: %s, uuid: %s", qPrintable(partDevice), qPrintable(part_old_uuid)); } return false; } QString BootDoctor::errorString() { return m_lastErrorString; }
./CrossVul/dataset_final_sorted/CWE-59/cpp/bad_915_3
crossvul-cpp_data_bad_4278_0
/* * Copyright (c) 2007 Henrique Pinto <henrique.pinto@kdemail.net> * Copyright (c) 2008-2009 Harald Hvaal <haraldhv@stud.ntnu.no> * Copyright (c) 2010 Raphael Kubo da Costa <rakuco@FreeBSD.org> * Copyright (c) 2016 Vladyslav Batyrenko <mvlabat@gmail.com> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES ( INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * ( INCLUDING NEGLIGENCE OR OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libarchiveplugin.h" #include "ark_debug.h" #include "queries.h" #include <KLocalizedString> #include <QThread> #include <QFileInfo> #include <QDir> #include <archive_entry.h> LibarchivePlugin::LibarchivePlugin(QObject *parent, const QVariantList &args) : ReadWriteArchiveInterface(parent, args) , m_archiveReadDisk(archive_read_disk_new()) , m_cachedArchiveEntryCount(0) , m_emitNoEntries(false) , m_extractedFilesSize(0) { qCDebug(ARK) << "Initializing libarchive plugin"; archive_read_disk_set_standard_lookup(m_archiveReadDisk.data()); connect(this, &ReadOnlyArchiveInterface::error, this, &LibarchivePlugin::slotRestoreWorkingDir); connect(this, &ReadOnlyArchiveInterface::cancelled, this, &LibarchivePlugin::slotRestoreWorkingDir); } LibarchivePlugin::~LibarchivePlugin() { for (const auto e : qAsConst(m_emittedEntries)) { // Entries might be passed to pending slots, so we just schedule their deletion. e->deleteLater(); } } bool LibarchivePlugin::list() { qCDebug(ARK) << "Listing archive contents"; if (!initializeReader()) { return false; } qCDebug(ARK) << "Detected compression filter:" << archive_filter_name(m_archiveReader.data(), 0); QString compMethod = convertCompressionName(QString::fromUtf8(archive_filter_name(m_archiveReader.data(), 0))); if (!compMethod.isEmpty()) { emit compressionMethodFound(compMethod); } m_cachedArchiveEntryCount = 0; m_extractedFilesSize = 0; m_numberOfEntries = 0; auto compressedArchiveSize = QFileInfo(filename()).size(); struct archive_entry *aentry; int result = ARCHIVE_RETRY; bool firstEntry = true; while (!QThread::currentThread()->isInterruptionRequested() && (result = archive_read_next_header(m_archiveReader.data(), &aentry)) == ARCHIVE_OK) { if (firstEntry) { qCDebug(ARK) << "Detected format for first entry:" << archive_format_name(m_archiveReader.data()); firstEntry = false; } if (!m_emitNoEntries) { emitEntryFromArchiveEntry(aentry); } m_extractedFilesSize += (qlonglong)archive_entry_size(aentry); emit progress(float(archive_filter_bytes(m_archiveReader.data(), -1))/float(compressedArchiveSize)); m_cachedArchiveEntryCount++; // Skip the entry data. int readSkipResult = archive_read_data_skip(m_archiveReader.data()); if (readSkipResult != ARCHIVE_OK) { qCCritical(ARK) << "Error while skipping data for entry:" << QString::fromWCharArray(archive_entry_pathname_w(aentry)) << readSkipResult << QLatin1String(archive_error_string(m_archiveReader.data())); if (!emitCorruptArchive()) { return false; } } } if (result != ARCHIVE_EOF) { qCCritical(ARK) << "Error while reading archive:" << result << QLatin1String(archive_error_string(m_archiveReader.data())); if (!emitCorruptArchive()) { return false; } } return archive_read_close(m_archiveReader.data()) == ARCHIVE_OK; } bool LibarchivePlugin::emitCorruptArchive() { Kerfuffle::LoadCorruptQuery query(filename()); emit userQuery(&query); query.waitForResponse(); if (!query.responseYes()) { emit cancelled(); archive_read_close(m_archiveReader.data()); return false; } else { emit progress(1.0); return true; } } bool LibarchivePlugin::addFiles(const QVector<Archive::Entry*> &files, const Archive::Entry *destination, const CompressionOptions &options, uint numberOfEntriesToAdd) { Q_UNUSED(files) Q_UNUSED(destination) Q_UNUSED(options) Q_UNUSED(numberOfEntriesToAdd) return false; } bool LibarchivePlugin::moveFiles(const QVector<Archive::Entry*> &files, Archive::Entry *destination, const CompressionOptions &options) { Q_UNUSED(files) Q_UNUSED(destination) Q_UNUSED(options) return false; } bool LibarchivePlugin::copyFiles(const QVector<Archive::Entry*> &files, Archive::Entry *destination, const CompressionOptions &options) { Q_UNUSED(files) Q_UNUSED(destination) Q_UNUSED(options) return false; } bool LibarchivePlugin::deleteFiles(const QVector<Archive::Entry*> &files) { Q_UNUSED(files) return false; } bool LibarchivePlugin::addComment(const QString &comment) { Q_UNUSED(comment) return false; } bool LibarchivePlugin::testArchive() { return false; } bool LibarchivePlugin::hasBatchExtractionProgress() const { return true; } bool LibarchivePlugin::doKill() { return false; } bool LibarchivePlugin::extractFiles(const QVector<Archive::Entry*> &files, const QString &destinationDirectory, const ExtractionOptions &options) { if (!initializeReader()) { return false; } ArchiveWrite writer(archive_write_disk_new()); if (!writer.data()) { return false; } archive_write_disk_set_options(writer.data(), extractionFlags()); int totalEntriesCount = 0; const bool extractAll = files.isEmpty(); if (extractAll) { if (!m_cachedArchiveEntryCount) { emit progress(0); //TODO: once information progress has been implemented, send //feedback here that the archive is being read qCDebug(ARK) << "For getting progress information, the archive will be listed once"; m_emitNoEntries = true; list(); m_emitNoEntries = false; } totalEntriesCount = m_cachedArchiveEntryCount; } else { totalEntriesCount = files.size(); } qCDebug(ARK) << "Going to extract" << totalEntriesCount << "entries"; qCDebug(ARK) << "Changing current directory to " << destinationDirectory; m_oldWorkingDir = QDir::currentPath(); QDir::setCurrent(destinationDirectory); // Initialize variables. const bool preservePaths = options.preservePaths(); const bool removeRootNode = options.isDragAndDropEnabled(); bool overwriteAll = false; // Whether to overwrite all files bool skipAll = false; // Whether to skip all files bool dontPromptErrors = false; // Whether to prompt for errors m_currentExtractedFilesSize = 0; int extractedEntriesCount = 0; int progressEntryCount = 0; struct archive_entry *entry; QString fileBeingRenamed; // To avoid traversing the entire archive when extracting a limited set of // entries, we maintain a list of remaining entries and stop when it's empty. const QStringList fullPaths = entryFullPaths(files); QStringList remainingFiles = entryFullPaths(files); // Iterate through all entries in archive. while (!QThread::currentThread()->isInterruptionRequested() && (archive_read_next_header(m_archiveReader.data(), &entry) == ARCHIVE_OK)) { if (!extractAll && remainingFiles.isEmpty()) { break; } fileBeingRenamed.clear(); int index = -1; // Retry with renamed entry, fire an overwrite query again // if the new entry also exists. retry: const bool entryIsDir = S_ISDIR(archive_entry_mode(entry)); // Skip directories if not preserving paths. if (!preservePaths && entryIsDir) { archive_read_data_skip(m_archiveReader.data()); continue; } // entryName is the name inside the archive, full path QString entryName = QDir::fromNativeSeparators(QFile::decodeName(archive_entry_pathname(entry))); // Some archive types e.g. AppImage prepend all entries with "./" so remove this part. if (entryName.startsWith(QLatin1String("./"))) { entryName.remove(0, 2); } // Static libraries (*.a) contain the two entries "/" and "//". // We just skip these to allow extracting this archive type. if (entryName == QLatin1String("/") || entryName == QLatin1String("//")) { archive_read_data_skip(m_archiveReader.data()); continue; } // For now we just can't handle absolute filenames in a tar archive. // TODO: find out what to do here!! if (entryName.startsWith(QLatin1Char( '/' ))) { emit error(i18n("This archive contains archive entries with absolute paths, " "which are not supported by Ark.")); return false; } // Should the entry be extracted? if (extractAll || remainingFiles.contains(entryName) || entryName == fileBeingRenamed) { // Find the index of entry. if (entryName != fileBeingRenamed) { index = fullPaths.indexOf(entryName); } if (!extractAll && index == -1) { // If entry is not found in files, skip entry. continue; } // entryFI is the fileinfo pointing to where the file will be // written from the archive. QFileInfo entryFI(entryName); //qCDebug(ARK) << "setting path to " << archive_entry_pathname( entry ); const QString fileWithoutPath(entryFI.fileName()); // If we DON'T preserve paths, we cut the path and set the entryFI // fileinfo to the one without the path. if (!preservePaths) { // Empty filenames (ie dirs) should have been skipped already, // so asserting. Q_ASSERT(!fileWithoutPath.isEmpty()); archive_entry_copy_pathname(entry, QFile::encodeName(fileWithoutPath).constData()); entryFI = QFileInfo(fileWithoutPath); // OR, if the file has a rootNode attached, remove it from file path. } else if (!extractAll && removeRootNode && entryName != fileBeingRenamed) { const QString &rootNode = files.at(index)->rootNode; if (!rootNode.isEmpty()) { const QString truncatedFilename(entryName.remove(entryName.indexOf(rootNode), rootNode.size())); archive_entry_copy_pathname(entry, QFile::encodeName(truncatedFilename).constData()); entryFI = QFileInfo(truncatedFilename); } } // Check if the file about to be written already exists. if (!entryIsDir && entryFI.exists()) { if (skipAll) { archive_read_data_skip(m_archiveReader.data()); archive_entry_clear(entry); continue; } else if (!overwriteAll && !skipAll) { Kerfuffle::OverwriteQuery query(entryName); emit userQuery(&query); query.waitForResponse(); if (query.responseCancelled()) { emit cancelled(); archive_read_data_skip(m_archiveReader.data()); archive_entry_clear(entry); break; } else if (query.responseSkip()) { archive_read_data_skip(m_archiveReader.data()); archive_entry_clear(entry); continue; } else if (query.responseAutoSkip()) { archive_read_data_skip(m_archiveReader.data()); archive_entry_clear(entry); skipAll = true; continue; } else if (query.responseRename()) { const QString newName(query.newFilename()); fileBeingRenamed = newName; archive_entry_copy_pathname(entry, QFile::encodeName(newName).constData()); goto retry; } else if (query.responseOverwriteAll()) { overwriteAll = true; } } } // If there is an already existing directory. if (entryIsDir && entryFI.exists()) { if (entryFI.isWritable()) { qCWarning(ARK) << "Warning, existing, but writable dir"; } else { qCWarning(ARK) << "Warning, existing, but non-writable dir. skipping"; archive_entry_clear(entry); archive_read_data_skip(m_archiveReader.data()); continue; } } // Write the entry header and check return value. const int returnCode = archive_write_header(writer.data(), entry); switch (returnCode) { case ARCHIVE_OK: // If the whole archive is extracted and the total filesize is // available, we use partial progress. copyData(entryName, m_archiveReader.data(), writer.data(), (extractAll && m_extractedFilesSize)); break; case ARCHIVE_FAILED: qCCritical(ARK) << "archive_write_header() has returned" << returnCode << "with errno" << archive_errno(writer.data()); // If they user previously decided to ignore future errors, // don't bother prompting again. if (!dontPromptErrors) { // Ask the user if he wants to continue extraction despite an error for this entry. Kerfuffle::ContinueExtractionQuery query(QLatin1String(archive_error_string(writer.data())), entryName); emit userQuery(&query); query.waitForResponse(); if (query.responseCancelled()) { emit cancelled(); return false; } dontPromptErrors = query.dontAskAgain(); } break; case ARCHIVE_FATAL: qCCritical(ARK) << "archive_write_header() has returned" << returnCode << "with errno" << archive_errno(writer.data()); emit error(i18nc("@info", "Fatal error, extraction aborted.")); return false; default: qCDebug(ARK) << "archive_write_header() returned" << returnCode << "which will be ignored."; break; } // If we only partially extract the archive and the number of // archive entries is available we use a simple progress based on // number of items extracted. if (!extractAll && m_cachedArchiveEntryCount) { ++progressEntryCount; emit progress(float(progressEntryCount) / totalEntriesCount); } extractedEntriesCount++; remainingFiles.removeOne(entryName); } else { // Archive entry not among selected files, skip it. archive_read_data_skip(m_archiveReader.data()); } } qCDebug(ARK) << "Extracted" << extractedEntriesCount << "entries"; slotRestoreWorkingDir(); return archive_read_close(m_archiveReader.data()) == ARCHIVE_OK; } bool LibarchivePlugin::initializeReader() { m_archiveReader.reset(archive_read_new()); if (!(m_archiveReader.data())) { emit error(i18n("The archive reader could not be initialized.")); return false; } if (archive_read_support_filter_all(m_archiveReader.data()) != ARCHIVE_OK) { return false; } if (archive_read_support_format_all(m_archiveReader.data()) != ARCHIVE_OK) { return false; } if (archive_read_open_filename(m_archiveReader.data(), QFile::encodeName(filename()).constData(), 10240) != ARCHIVE_OK) { qCWarning(ARK) << "Could not open the archive:" << archive_error_string(m_archiveReader.data()); emit error(i18nc("@info", "Archive corrupted or insufficient permissions.")); return false; } return true; } void LibarchivePlugin::emitEntryFromArchiveEntry(struct archive_entry *aentry) { auto e = new Archive::Entry(); #ifdef Q_OS_WIN e->setProperty("fullPath", QDir::fromNativeSeparators(QString::fromUtf16((ushort*)archive_entry_pathname_w(aentry)))); #else e->setProperty("fullPath", QDir::fromNativeSeparators(QString::fromWCharArray(archive_entry_pathname_w(aentry)))); #endif const QString owner = QString::fromLatin1(archive_entry_uname(aentry)); if (!owner.isEmpty()) { e->setProperty("owner", owner); } else { e->setProperty("owner", static_cast<qlonglong>(archive_entry_uid(aentry))); } const QString group = QString::fromLatin1(archive_entry_gname(aentry)); if (!group.isEmpty()) { e->setProperty("group", group); } else { e->setProperty("group", static_cast<qlonglong>(archive_entry_gid(aentry))); } const mode_t mode = archive_entry_mode(aentry); if (mode != 0) { e->setProperty("permissions", QString::number(mode, 8)); } e->setProperty("isExecutable", mode & (S_IXUSR | S_IXGRP | S_IXOTH)); e->compressedSizeIsSet = false; e->setProperty("size", (qlonglong)archive_entry_size(aentry)); e->setProperty("isDirectory", S_ISDIR(archive_entry_mode(aentry))); if (archive_entry_symlink(aentry)) { e->setProperty("link", QLatin1String( archive_entry_symlink(aentry) )); } auto time = static_cast<uint>(archive_entry_mtime(aentry)); e->setProperty("timestamp", QDateTime::fromSecsSinceEpoch(time)); emit entry(e); m_emittedEntries << e; } int LibarchivePlugin::extractionFlags() const { int result = ARCHIVE_EXTRACT_TIME; result |= ARCHIVE_EXTRACT_SECURE_NODOTDOT; // TODO: Don't use arksettings here /*if ( ArkSettings::preservePerms() ) { result &= ARCHIVE_EXTRACT_PERM; } if ( !ArkSettings::extractOverwrite() ) { result &= ARCHIVE_EXTRACT_NO_OVERWRITE; }*/ return result; } void LibarchivePlugin::copyData(const QString& filename, struct archive *dest, bool partialprogress) { char buff[10240]; QFile file(filename); if (!file.open(QIODevice::ReadOnly)) { return; } auto readBytes = file.read(buff, sizeof(buff)); while (readBytes > 0 && !QThread::currentThread()->isInterruptionRequested()) { archive_write_data(dest, buff, static_cast<size_t>(readBytes)); if (archive_errno(dest) != ARCHIVE_OK) { qCCritical(ARK) << "Error while writing" << filename << ":" << archive_error_string(dest) << "(error no =" << archive_errno(dest) << ')'; return; } if (partialprogress) { m_currentExtractedFilesSize += readBytes; emit progress(float(m_currentExtractedFilesSize) / m_extractedFilesSize); } readBytes = file.read(buff, sizeof(buff)); } file.close(); } void LibarchivePlugin::copyData(const QString& filename, struct archive *source, struct archive *dest, bool partialprogress) { char buff[10240]; auto readBytes = archive_read_data(source, buff, sizeof(buff)); while (readBytes > 0 && !QThread::currentThread()->isInterruptionRequested()) { archive_write_data(dest, buff, static_cast<size_t>(readBytes)); if (archive_errno(dest) != ARCHIVE_OK) { qCCritical(ARK) << "Error while extracting" << filename << ":" << archive_error_string(dest) << "(error no =" << archive_errno(dest) << ')'; return; } if (partialprogress) { m_currentExtractedFilesSize += readBytes; emit progress(float(m_currentExtractedFilesSize) / m_extractedFilesSize); } readBytes = archive_read_data(source, buff, sizeof(buff)); } } void LibarchivePlugin::slotRestoreWorkingDir() { if (m_oldWorkingDir.isEmpty()) { return; } if (!QDir::setCurrent(m_oldWorkingDir)) { qCWarning(ARK) << "Failed to restore old working directory:" << m_oldWorkingDir; } else { m_oldWorkingDir.clear(); } } QString LibarchivePlugin::convertCompressionName(const QString &method) { if (method == QLatin1String("gzip")) { return QStringLiteral("GZip"); } else if (method == QLatin1String("bzip2")) { return QStringLiteral("BZip2"); } else if (method == QLatin1String("xz")) { return QStringLiteral("XZ"); } else if (method == QLatin1String("compress (.Z)")) { return QStringLiteral("Compress"); } else if (method == QLatin1String("lrzip")) { return QStringLiteral("LRZip"); } else if (method == QLatin1String("lzip")) { return QStringLiteral("LZip"); } else if (method == QLatin1String("lz4")) { return QStringLiteral("LZ4"); } else if (method == QLatin1String("lzop")) { return QStringLiteral("lzop"); } else if (method == QLatin1String("lzma")) { return QStringLiteral("LZMA"); } else if (method == QLatin1String("zstd")) { return QStringLiteral("Zstandard"); } return QString(); }
./CrossVul/dataset_final_sorted/CWE-59/cpp/bad_4278_0
crossvul-cpp_data_good_5719_2
#include "TestSupport.h" #include "ServerInstanceDir.h" using namespace Passenger; using namespace std; namespace tut { struct ServerInstanceDirTest { string parentDir; TempDir tmpDir; string nobodyGroup; ServerInstanceDirTest(): tmpDir("server_instance_dir_test.tmp") { parentDir = "server_instance_dir_test.tmp"; nobodyGroup = getPrimaryGroupName("nobody"); } void createGenerationDir(const string &instanceDir, unsigned int number) { string command = "mkdir " + instanceDir + "/generation-" + toString(number); runShellCommand(command.c_str()); } }; DEFINE_TEST_GROUP(ServerInstanceDirTest); TEST_METHOD(2) { // The (string) constructor creates a ServerInstanceDir object that's // associated with the given directory, and creates the directory // if it doesn't exist. ServerInstanceDir dir(parentDir + "/passenger-test.1234"); ServerInstanceDir dir2(dir.getPath()); ServerInstanceDir dir3(parentDir + "/foo"); ensure_equals(dir2.getPath(), dir.getPath()); ensure_equals(dir3.getPath(), parentDir + "/foo"); ensure_equals(getFileType(dir3.getPath()), FT_DIRECTORY); } TEST_METHOD(3) { // A ServerInstanceDir object removes the server instance directory // upon destruction, but only if there are no more generations in it. { ServerInstanceDir dir(parentDir + "/passenger-test.1234"); } ensure_equals(listDir(parentDir).size(), 0u); { ServerInstanceDir dir(parentDir + "/passenger-test.1234"); createGenerationDir(dir.getPath(), 1); } ensure_equals(listDir(parentDir).size(), 1u); } TEST_METHOD(4) { // The destructor does not throw any exceptions if the server instance // directory doesn't exist anymore. ServerInstanceDir dir(parentDir + "/passenger-test.1234"); removeDirTree(dir.getPath()); } TEST_METHOD(5) { // The destructor doesn't remove the server instance directory if it // wasn't created with the ownership flag or if it's been detached. string path, path2; makeDirTree(parentDir + "/passenger-test.1234"); makeDirTree(parentDir + "/passenger-test.5678"); { ServerInstanceDir dir(parentDir + "/passenger-test.1234", false); ServerInstanceDir dir2(parentDir + "/passenger-test.5678", false); dir2.detach(); path = dir.getPath(); path2 = dir2.getPath(); } ensure_equals(getFileType(path), FT_DIRECTORY); ensure_equals(getFileType(path2), FT_DIRECTORY); } TEST_METHOD(6) { // If there are no existing generations, newGeneration() creates a new // generation directory with number 0. ServerInstanceDir dir(parentDir + "/passenger-test.1234"); unsigned int ncontents = listDir(dir.getPath()).size(); ServerInstanceDir::GenerationPtr generation = dir.newGeneration(true, "nobody", nobodyGroup, 0, 0); ensure_equals(generation->getNumber(), 0u); ensure_equals(getFileType(generation->getPath()), FT_DIRECTORY); ensure_equals(listDir(dir.getPath()).size(), ncontents + 1); } TEST_METHOD(7) { // A Generation object returned by newGeneration() deletes the associated // generation directory upon destruction. ServerInstanceDir dir(parentDir + "/passenger-test.1234"); ServerInstanceDir::GenerationPtr generation = dir.newGeneration(true, "nobody", nobodyGroup, 0, 0); string path = generation->getPath(); generation.reset(); ensure_equals(getFileType(path), FT_NONEXISTANT); } TEST_METHOD(8) { // getNewestGeneration() returns the newest generation. ServerInstanceDir dir(parentDir + "/passenger-test.1234"); ServerInstanceDir::GenerationPtr generation0 = dir.newGeneration(true, "nobody", nobodyGroup, 0, 0); ServerInstanceDir::GenerationPtr generation1 = dir.newGeneration(true, "nobody", nobodyGroup, 0, 0); ServerInstanceDir::GenerationPtr generation2 = dir.newGeneration(true, "nobody", nobodyGroup, 0, 0); ServerInstanceDir::GenerationPtr generation3 = dir.newGeneration(true, "nobody", nobodyGroup, 0, 0); generation2.reset(); ensure_equals(dir.getNewestGeneration()->getNumber(), 3u); generation3.reset(); ensure_equals(dir.getNewestGeneration()->getNumber(), 1u); } TEST_METHOD(9) { // getNewestGeneration returns null if there are no generations. ServerInstanceDir dir(parentDir + "/passenger-test.1234"); ensure(dir.getNewestGeneration() == NULL); } TEST_METHOD(10) { // A Generation object returned by getNewestGeneration() doesn't delete // the associated generation directory upon destruction. ServerInstanceDir dir(parentDir + "/passenger-test.1234"); ServerInstanceDir::GenerationPtr generation = dir.newGeneration(true, "nobody", nobodyGroup, 0, 0); ServerInstanceDir::GenerationPtr newestGeneration = dir.getNewestGeneration(); newestGeneration.reset(); ensure_equals(getFileType(generation->getPath()), FT_DIRECTORY); } TEST_METHOD(11) { // getGeneration() returns the given generation. ServerInstanceDir dir(parentDir + "/passenger-test.1234"); ServerInstanceDir::GenerationPtr generation0 = dir.newGeneration(true, "nobody", nobodyGroup, 0, 0); ServerInstanceDir::GenerationPtr generation1 = dir.newGeneration(true, "nobody", nobodyGroup, 0, 0); ServerInstanceDir::GenerationPtr generation2 = dir.newGeneration(true, "nobody", nobodyGroup, 0, 0); ServerInstanceDir::GenerationPtr generation3 = dir.newGeneration(true, "nobody", nobodyGroup, 0, 0); ensure_equals(dir.getGeneration(0)->getNumber(), 0u); ensure_equals(dir.getGeneration(3)->getNumber(), 3u); } TEST_METHOD(12) { // A Generation object returned by getGeneration() doesn't delete the // associated generation directory upon destruction. ServerInstanceDir dir(parentDir + "/passenger-test.1234"); ServerInstanceDir::GenerationPtr generation0 = dir.newGeneration(true, "nobody", nobodyGroup, 0, 0); ServerInstanceDir::GenerationPtr generation1 = dir.newGeneration(true, "nobody", nobodyGroup, 0, 0); dir.getGeneration(0).reset(); dir.getGeneration(1).reset(); ensure_equals(getFileType(generation0->getPath()), FT_DIRECTORY); ensure_equals(getFileType(generation1->getPath()), FT_DIRECTORY); } TEST_METHOD(13) { // A detached Generation doesn't delete the associated generation // directory upon destruction. ServerInstanceDir dir(parentDir + "/passenger-test.1234"); ServerInstanceDir::GenerationPtr generation = dir.newGeneration(true, "nobody", nobodyGroup, 0, 0); string path = generation->getPath(); generation->detach(); generation.reset(); ensure_equals(getFileType(path), FT_DIRECTORY); } TEST_METHOD(14) { // It's possible to have two ServerInstanceDir objects constructed // with the same (pid_t, string) constructor arguments. ServerInstanceDir dir(parentDir + "/passenger-test.1234"); ServerInstanceDir dir2(parentDir + "/passenger-test.1234"); } }
./CrossVul/dataset_final_sorted/CWE-59/cpp/good_5719_2
crossvul-cpp_data_good_2134_0
/** \file env.c Functions for setting and getting environment variables. */ #include "config.h" #include <stdlib.h> #include <wchar.h> #include <string.h> #include <stdio.h> #include <locale.h> #include <unistd.h> #include <signal.h> #include <assert.h> #include <sys/types.h> #include <sys/stat.h> #include <pthread.h> #include <pwd.h> #include <set> #include <map> #include <algorithm> #if HAVE_NCURSES_H #include <ncurses.h> #else #include <curses.h> #endif #if HAVE_TERM_H #include <term.h> #elif HAVE_NCURSES_TERM_H #include <ncurses/term.h> #endif #if HAVE_LIBINTL_H #include <libintl.h> #endif #include <errno.h> #include "fallback.h" #include "util.h" #include "wutil.h" #include "proc.h" #include "common.h" #include "env.h" #include "sanity.h" #include "expand.h" #include "history.h" #include "reader.h" #include "parser.h" #include "env_universal.h" #include "input.h" #include "event.h" #include "path.h" #include "complete.h" #include "fish_version.h" /** Command used to start fishd */ #define FISHD_CMD L"fishd ^ /dev/null" // Version for easier debugging //#define FISHD_CMD L"fishd" /** Value denoting a null string */ #define ENV_NULL L"\x1d" /** Some configuration path environment variables */ #define FISH_DATADIR_VAR L"__fish_datadir" #define FISH_SYSCONFDIR_VAR L"__fish_sysconfdir" #define FISH_HELPDIR_VAR L"__fish_help_dir" #define FISH_BIN_DIR L"__fish_bin_dir" /** At init, we read all the environment variables from this array. */ extern char **environ; /** This should be the same thing as \c environ, but it is possible only one of the two work... */ extern char **__environ; bool g_log_forks = false; bool g_use_posix_spawn = false; //will usually be set to true /** Struct representing one level in the function variable stack */ struct env_node_t { /** Variable table */ var_table_t env; /** Does this node imply a new variable scope? If yes, all non-global variables below this one in the stack are invisible. If new_scope is set for the global variable node, the universe will explode. */ bool new_scope; /** Does this node contain any variables which are exported to subshells */ bool exportv; /** Pointer to next level */ struct env_node_t *next; env_node_t() : new_scope(false), exportv(false), next(NULL) { } /* Returns a pointer to the given entry if present, or NULL. */ const var_entry_t *find_entry(const wcstring &key); /* Returns the next scope to search in order, respecting the new_scope flag, or NULL if we're done. */ env_node_t *next_scope_to_search(void); }; class variable_entry_t { wcstring value; /**< Value of the variable */ }; static pthread_mutex_t env_lock = PTHREAD_MUTEX_INITIALIZER; /** Top node on the function stack */ static env_node_t *top = NULL; /** Bottom node on the function stack */ static env_node_t *global_env = NULL; /** Table for global variables */ static var_table_t *global; /* Helper class for storing constant strings, without needing to wrap them in a wcstring */ /* Comparer for const string set */ struct const_string_set_comparer { bool operator()(const wchar_t *a, const wchar_t *b) { return wcscmp(a, b) < 0; } }; typedef std::set<const wchar_t *, const_string_set_comparer> const_string_set_t; /** Table of variables that may not be set using the set command. */ static const_string_set_t env_read_only; static bool is_read_only(const wcstring &key) { return env_read_only.find(key.c_str()) != env_read_only.end(); } /** Table of variables whose value is dynamically calculated, such as umask, status, etc */ static const_string_set_t env_electric; static bool is_electric(const wcstring &key) { return env_electric.find(key.c_str()) != env_electric.end(); } /** Exported variable array used by execv */ static null_terminated_array_t<char> export_array; /** Flag for checking if we need to regenerate the exported variable array */ static bool has_changed_exported = true; static void mark_changed_exported() { has_changed_exported = true; } /** List of all locale variable names */ static const wchar_t * const locale_variable[] = { L"LANG", L"LC_ALL", L"LC_COLLATE", L"LC_CTYPE", L"LC_MESSAGES", L"LC_MONETARY", L"LC_NUMERIC", L"LC_TIME", NULL }; const var_entry_t *env_node_t::find_entry(const wcstring &key) { const var_entry_t *result = NULL; var_table_t::const_iterator where = env.find(key); if (where != env.end()) { result = &where->second; } return result; } env_node_t *env_node_t::next_scope_to_search(void) { return this->new_scope ? global_env : this->next; } /** When fishd isn't started, this function is provided to env_universal as a callback, it tries to start up fishd. It's implementation is a bit of a hack, since it evaluates a bit of shellscript, and it might be used at times when that might not be the best idea. */ static void start_fishd() { struct passwd *pw = getpwuid(getuid()); debug(3, L"Spawning new copy of fishd"); if (!pw) { debug(0, _(L"Could not get user information")); return; } wcstring cmd = format_string(FISHD_CMD, pw->pw_name); /* Prefer the fishd in __fish_bin_dir, if exists */ const env_var_t bin_dir = env_get_string(L"__fish_bin_dir"); if (! bin_dir.missing_or_empty()) { wcstring path = bin_dir + L"/fishd"; if (waccess(path, X_OK) == 0) { /* The path command just looks like 'fishd', so insert the bin path to make it absolute */ cmd.insert(0, bin_dir + L"/"); } } parser_t &parser = parser_t::principal_parser(); parser.eval(cmd, io_chain_t(), TOP); } /** Return the current umask value. */ static mode_t get_umask() { mode_t res; res = umask(0); umask(res); return res; } /** Checks if the specified variable is a locale variable */ static bool var_is_locale(const wcstring &key) { for (size_t i=0; locale_variable[i]; i++) { if (key == locale_variable[i]) { return true; } } return false; } /** Properly sets all locale information */ static void handle_locale() { const env_var_t lc_all = env_get_string(L"LC_ALL"); const wcstring old_locale = wsetlocale(LC_MESSAGES, NULL); /* Array of locale constants corresponding to the local variable names defined in locale_variable */ static const int cat[] = { 0, LC_ALL, LC_COLLATE, LC_CTYPE, LC_MESSAGES, LC_MONETARY, LC_NUMERIC, LC_TIME } ; if (!lc_all.missing()) { wsetlocale(LC_ALL, lc_all.c_str()); } else { const env_var_t lang = env_get_string(L"LANG"); if (!lang.missing()) { wsetlocale(LC_ALL, lang.c_str()); } for (int i=2; locale_variable[i]; i++) { const env_var_t val = env_get_string(locale_variable[i]); if (!val.missing()) { wsetlocale(cat[i], val.c_str()); } } } const wcstring new_locale = wsetlocale(LC_MESSAGES, NULL); if (old_locale != new_locale) { /* Try to make change known to gettext. Both changing _nl_msg_cat_cntr and calling dcgettext might potentially tell some gettext implementation that the translation strings should be reloaded. We do both and hope for the best. */ extern int _nl_msg_cat_cntr; _nl_msg_cat_cntr++; fish_dcgettext("fish", "Changing language to English", LC_MESSAGES); if (get_is_interactive()) { debug(0, _(L"Changing language to English")); } } } /** React to modifying hte given variable */ static void react_to_variable_change(const wcstring &key) { if (var_is_locale(key)) { handle_locale(); } else if (key == L"fish_term256") { update_fish_term256(); reader_react_to_color_change(); } else if (string_prefixes_string(L"fish_color_", key)) { reader_react_to_color_change(); } } /** Universal variable callback function. This function makes sure the proper events are triggered when an event occurs. */ static void universal_callback(fish_message_type_t type, const wchar_t *name, const wchar_t *val) { const wchar_t *str = NULL; switch (type) { case SET: case SET_EXPORT: { str=L"SET"; break; } case ERASE: { str=L"ERASE"; break; } default: break; } if (str) { mark_changed_exported(); event_t ev = event_t::variable_event(name); ev.arguments.push_back(L"VARIABLE"); ev.arguments.push_back(str); ev.arguments.push_back(name); event_fire(&ev); } if (name) react_to_variable_change(name); } /** Make sure the PATH variable contains something */ static void setup_path() { const env_var_t path = env_get_string(L"PATH"); if (path.missing_or_empty()) { const wchar_t *value = L"/usr/bin" ARRAY_SEP_STR L"/bin"; env_set(L"PATH", value, ENV_GLOBAL | ENV_EXPORT); } } int env_set_pwd() { wchar_t dir_path[4096]; wchar_t *res = wgetcwd(dir_path, 4096); if (!res) { return 0; } env_set(L"PWD", dir_path, ENV_EXPORT | ENV_GLOBAL); return 1; } wcstring env_get_pwd_slash(void) { env_var_t pwd = env_get_string(L"PWD"); if (pwd.missing_or_empty()) { return L""; } if (! string_suffixes_string(L"/", pwd)) { pwd.push_back(L'/'); } return pwd; } /** Set up default values for various variables if not defined. */ static void env_set_defaults() { if (env_get_string(L"USER").missing()) { struct passwd *pw = getpwuid(getuid()); if (pw->pw_name != NULL) { const wcstring wide_name = str2wcstring(pw->pw_name); env_set(L"USER", wide_name.c_str(), ENV_GLOBAL); } } if (env_get_string(L"HOME").missing()) { const env_var_t unam = env_get_string(L"USER"); char *unam_narrow = wcs2str(unam.c_str()); struct passwd *pw = getpwnam(unam_narrow); if (pw->pw_dir != NULL) { const wcstring dir = str2wcstring(pw->pw_dir); env_set(L"HOME", dir.c_str(), ENV_GLOBAL); } free(unam_narrow); } env_set_pwd(); } // Some variables should not be arrays. This used to be handled by a startup script, but we'd like to get down to 0 forks for startup, so handle it here. static bool variable_can_be_array(const wcstring &key) { if (key == L"DISPLAY") { return false; } else { return true; } } void env_init(const struct config_paths_t *paths /* or NULL */) { /* env_read_only variables can not be altered directly by the user */ const wchar_t * const ro_keys[] = { L"status", L"history", L"version", L"_", L"LINES", L"COLUMNS", L"PWD", L"SHLVL", L"FISH_VERSION", }; for (size_t i=0; i < sizeof ro_keys / sizeof *ro_keys; i++) { env_read_only.insert(ro_keys[i]); } /* HOME and USER should be writeable by root, since this can be a convenient way to install software. */ if (getuid() != 0) { env_read_only.insert(L"HOME"); env_read_only.insert(L"USER"); } /* Names of all dynamically calculated variables */ env_electric.insert(L"history"); env_electric.insert(L"status"); env_electric.insert(L"umask"); top = new env_node_t; global_env = top; global = &top->env; /* Now the environemnt variable handling is set up, the next step is to insert valid data */ /* Import environment variables */ for (char **p = (environ ? environ : __environ); p && *p; p++) { const wcstring key_and_val = str2wcstring(*p); //like foo=bar size_t eql = key_and_val.find(L'='); if (eql == wcstring::npos) { // no equals found env_set(key_and_val, L"", ENV_EXPORT); } else { wcstring key = key_and_val.substr(0, eql); wcstring val = key_and_val.substr(eql + 1); if (variable_can_be_array(val)) { std::replace(val.begin(), val.end(), L':', ARRAY_SEP); } env_set(key, val.c_str(), ENV_EXPORT | ENV_GLOBAL); } } /* Set the given paths in the environment, if we have any */ if (paths != NULL) { env_set(FISH_DATADIR_VAR, paths->data.c_str(), ENV_GLOBAL | ENV_EXPORT); env_set(FISH_SYSCONFDIR_VAR, paths->sysconf.c_str(), ENV_GLOBAL | ENV_EXPORT); env_set(FISH_HELPDIR_VAR, paths->doc.c_str(), ENV_GLOBAL | ENV_EXPORT); env_set(FISH_BIN_DIR, paths->bin.c_str(), ENV_GLOBAL | ENV_EXPORT); } /* Set up the PATH variable */ setup_path(); /* Set up the USER variable */ const struct passwd *pw = getpwuid(getuid()); if (pw && pw->pw_name) { const wcstring uname = str2wcstring(pw->pw_name); env_set(L"USER", uname.c_str(), ENV_GLOBAL | ENV_EXPORT); } /* Set up the version variables */ wcstring version = str2wcstring(get_fish_version()); env_set(L"version", version.c_str(), ENV_GLOBAL); env_set(L"FISH_VERSION", version.c_str(), ENV_GLOBAL); const env_var_t fishd_dir_wstr = env_get_string(L"FISHD_SOCKET_DIR"); const env_var_t user_dir_wstr = env_get_string(L"USER"); wchar_t * fishd_dir = fishd_dir_wstr.missing()?NULL:const_cast<wchar_t*>(fishd_dir_wstr.c_str()); wchar_t * user_dir = user_dir_wstr.missing()?NULL:const_cast<wchar_t*>(user_dir_wstr.c_str()); env_universal_init(fishd_dir , user_dir , &start_fishd, &universal_callback); /* Set up SHLVL variable */ const env_var_t shlvl_str = env_get_string(L"SHLVL"); wcstring nshlvl_str = L"1"; if (! shlvl_str.missing()) { long shlvl_i = wcstol(shlvl_str.c_str(), NULL, 10); if (shlvl_i >= 0) { nshlvl_str = to_string<long>(shlvl_i + 1); } } env_set(L"SHLVL", nshlvl_str.c_str(), ENV_GLOBAL | ENV_EXPORT); /* Set correct defaults for e.g. USER and HOME variables */ env_set_defaults(); /* Set g_log_forks */ env_var_t log_forks = env_get_string(L"fish_log_forks"); g_log_forks = ! log_forks.missing_or_empty() && from_string<bool>(log_forks); /* Set g_use_posix_spawn. Default to true. */ env_var_t use_posix_spawn = env_get_string(L"fish_use_posix_spawn"); g_use_posix_spawn = (use_posix_spawn.missing_or_empty() ? true : from_string<bool>(use_posix_spawn)); /* Set fish_bind_mode to "default" */ env_set(FISH_BIND_MODE_VAR, DEFAULT_BIND_MODE, ENV_GLOBAL); } void env_destroy() { env_universal_destroy(); while (&top->env != global) { env_pop(); } env_read_only.clear(); env_electric.clear(); var_table_t::iterator iter; for (iter = global->begin(); iter != global->end(); ++iter) { const var_entry_t &entry = iter->second; if (entry.exportv) { mark_changed_exported(); break; } } delete top; } /** Search all visible scopes in order for the specified key. Return the first scope in which it was found. */ static env_node_t *env_get_node(const wcstring &key) { env_node_t *env = top; while (env != NULL) { if (env->find_entry(key) != NULL) { break; } env = env->next_scope_to_search(); } return env; } int env_set(const wcstring &key, const wchar_t *val, int var_mode) { ASSERT_IS_MAIN_THREAD(); bool has_changed_old = has_changed_exported; bool has_changed_new = false; int done=0; int is_universal = 0; if (val && contains(key, L"PWD", L"HOME")) { /* Canoncalize our path; if it changes, recurse and try again. */ wcstring val_canonical = val; path_make_canonical(val_canonical); if (val != val_canonical) { return env_set(key, val_canonical.c_str(), var_mode); } } if ((var_mode & ENV_USER) && is_read_only(key)) { return ENV_PERM; } if (key == L"umask") { wchar_t *end; /* Set the new umask */ if (val && wcslen(val)) { errno=0; long mask = wcstol(val, &end, 8); if (!errno && (!*end) && (mask <= 0777) && (mask >= 0)) { umask(mask); } } /* Do not actually create a umask variable, on env_get, it will be calculated dynamically */ return 0; } /* Zero element arrays are internaly not coded as null but as this placeholder string */ if (!val) { val = ENV_NULL; } if (var_mode & ENV_UNIVERSAL) { bool exportv; if (var_mode & ENV_EXPORT) { // export exportv = true; } else if (var_mode & ENV_UNEXPORT) { // unexport exportv = false; } else { // not changing the export exportv = env_universal_get_export(key); } env_universal_set(key, val, exportv); is_universal = 1; } else { // Determine the node env_node_t *preexisting_node = env_get_node(key); bool preexisting_entry_exportv = false; if (preexisting_node != NULL) { var_table_t::const_iterator result = preexisting_node->env.find(key); assert(result != preexisting_node->env.end()); const var_entry_t &entry = result->second; if (entry.exportv) { preexisting_entry_exportv = true; has_changed_new = true; } } env_node_t *node = NULL; if (var_mode & ENV_GLOBAL) { node = global_env; } else if (var_mode & ENV_LOCAL) { node = top; } else if (preexisting_node != NULL) { node = preexisting_node; if ((var_mode & (ENV_EXPORT | ENV_UNEXPORT)) == 0) { // use existing entry's exportv var_mode = preexisting_entry_exportv ? ENV_EXPORT : 0; } } else { if (! get_proc_had_barrier()) { set_proc_had_barrier(true); env_universal_barrier(); } if (! env_universal_get(key).missing()) { bool exportv; if (var_mode & ENV_EXPORT) { exportv = true; } else if (var_mode & ENV_UNEXPORT) { exportv = false; } else { exportv = env_universal_get_export(key); } env_universal_set(key, val, exportv); is_universal = 1; done = 1; } else { /* New variable with unspecified scope. The default scope is the innermost scope that is shadowing, which will be either the current function or the global scope. */ node = top; while (node->next && !node->new_scope) { node = node->next; } } } if (!done) { // Set the entry in the node // Note that operator[] accesses the existing entry, or creates a new one var_entry_t &entry = node->env[key]; if (entry.exportv) { // this variable already existed, and was exported has_changed_new = true; } entry.val = val; if (var_mode & ENV_EXPORT) { // the new variable is exported entry.exportv = true; node->exportv = true; has_changed_new = true; } else { entry.exportv = false; } if (has_changed_old || has_changed_new) mark_changed_exported(); } } if (!is_universal) { event_t ev = event_t::variable_event(key); ev.arguments.reserve(3); ev.arguments.push_back(L"VARIABLE"); ev.arguments.push_back(L"SET"); ev.arguments.push_back(key); // debug( 1, L"env_set: fire events on variable %ls", key ); event_fire(&ev); // debug( 1, L"env_set: return from event firing" ); } react_to_variable_change(key); return 0; } /** Attempt to remove/free the specified key/value pair from the specified map. \return zero if the variable was not found, non-zero otherwise */ static bool try_remove(env_node_t *n, const wchar_t *key, int var_mode) { if (n == NULL) { return false; } var_table_t::iterator result = n->env.find(key); if (result != n->env.end()) { if (result->second.exportv) { mark_changed_exported(); } n->env.erase(result); return true; } if (var_mode & ENV_LOCAL) { return false; } if (n->new_scope) { return try_remove(global_env, key, var_mode); } else { return try_remove(n->next, key, var_mode); } } int env_remove(const wcstring &key, int var_mode) { ASSERT_IS_MAIN_THREAD(); env_node_t *first_node; int erased = 0; if ((var_mode & ENV_USER) && is_read_only(key)) { return 2; } first_node = top; if (!(var_mode & ENV_UNIVERSAL)) { if (var_mode & ENV_GLOBAL) { first_node = global_env; } if (try_remove(first_node, key.c_str(), var_mode)) { event_t ev = event_t::variable_event(key); ev.arguments.push_back(L"VARIABLE"); ev.arguments.push_back(L"ERASE"); ev.arguments.push_back(key); event_fire(&ev); erased = 1; } } if (!erased && !(var_mode & ENV_GLOBAL) && !(var_mode & ENV_LOCAL)) { erased = ! env_universal_remove(key.c_str()); } react_to_variable_change(key); return !erased; } const wchar_t *env_var_t::c_str(void) const { assert(! is_missing); return wcstring::c_str(); } env_var_t env_get_string(const wcstring &key) { /* Big hack...we only allow getting the history on the main thread. Note that history_t may ask for an environment variable, so don't take the lock here (we don't need it) */ const bool is_main = is_main_thread(); if (key == L"history" && is_main) { env_var_t result; history_t *history = reader_get_history(); if (! history) { history = &history_t::history_with_name(L"fish"); } if (history) history->get_string_representation(result, ARRAY_SEP_STR); return result; } else if (key == L"COLUMNS") { return to_string(common_get_width()); } else if (key == L"LINES") { return to_string(common_get_height()); } else if (key == L"status") { return to_string(proc_get_last_status()); } else if (key == L"umask") { return format_string(L"0%0.3o", get_umask()); } else { { /* Lock around a local region */ scoped_lock lock(env_lock); env_node_t *env = top; wcstring result; while (env != NULL) { const var_entry_t *entry = env->find_entry(key); if (entry != NULL) { if (entry->val == ENV_NULL) { return env_var_t::missing_var(); } else { return entry->val; } } env = env->next_scope_to_search(); } } /* Another big hack - only do a universal barrier on the main thread (since it can change variable values) Make sure we do this outside the env_lock because it may itself call env_get_string */ if (is_main && ! get_proc_had_barrier()) { set_proc_had_barrier(true); env_universal_barrier(); } env_var_t item = env_universal_get(key); if (item.missing() || (wcscmp(item.c_str(), ENV_NULL)==0)) { return env_var_t::missing_var(); } else { return item; } } } bool env_exist(const wchar_t *key, int mode) { env_node_t *env; CHECK(key, false); /* Read only variables all exist, and they are all global. A local version can not exist. */ if (!(mode & ENV_LOCAL) && !(mode & ENV_UNIVERSAL)) { if (is_read_only(key) || is_electric(key)) { //Such variables are never exported if (mode & ENV_EXPORT) { return false; } else if (mode & ENV_UNEXPORT) { return true; } return true; } } if (!(mode & ENV_UNIVERSAL)) { env = (mode & ENV_GLOBAL)?global_env:top; while (env != 0) { var_table_t::iterator result = env->env.find(key); if (result != env->env.end()) { const var_entry_t &res = result->second; if (mode & ENV_EXPORT) { return res.exportv; } else if (mode & ENV_UNEXPORT) { return ! res.exportv; } return true; } if (mode & ENV_LOCAL) break; env = env->next_scope_to_search(); } } if (!(mode & ENV_LOCAL) && !(mode & ENV_GLOBAL)) { if (! get_proc_had_barrier()) { set_proc_had_barrier(true); env_universal_barrier(); } if (! env_universal_get(key).missing()) { if (mode & ENV_EXPORT) { return env_universal_get_export(key) == 1; } else if (mode & ENV_UNEXPORT) { return env_universal_get_export(key) == 0; } return 1; } } return 0; } /** Returns true if the specified scope or any non-shadowed non-global subscopes contain an exported variable. */ static int local_scope_exports(env_node_t *n) { if (n==global_env) return 0; if (n->exportv) return 1; if (n->new_scope) return 0; return local_scope_exports(n->next); } void env_push(bool new_scope) { env_node_t *node = new env_node_t; node->next = top; node->new_scope=new_scope; if (new_scope) { if (local_scope_exports(top)) mark_changed_exported(); } top = node; } void env_pop() { if (&top->env != global) { int i; int locale_changed = 0; env_node_t *killme = top; for (i=0; locale_variable[i]; i++) { var_table_t::iterator result = killme->env.find(locale_variable[i]); if (result != killme->env.end()) { locale_changed = 1; break; } } if (killme->new_scope) { if (killme->exportv || local_scope_exports(killme->next)) mark_changed_exported(); } top = top->next; var_table_t::iterator iter; for (iter = killme->env.begin(); iter != killme->env.end(); ++iter) { const var_entry_t &entry = iter->second; if (entry.exportv) { mark_changed_exported(); break; } } delete killme; if (locale_changed) handle_locale(); } else { debug(0, _(L"Tried to pop empty environment stack.")); sanity_lose(); } } /** Function used with to insert keys of one table into a set::set<wcstring> */ static void add_key_to_string_set(const var_table_t &envs, std::set<wcstring> *str_set, bool show_exported, bool show_unexported) { var_table_t::const_iterator iter; for (iter = envs.begin(); iter != envs.end(); ++iter) { const var_entry_t &e = iter->second; if ((e.exportv && show_exported) || (!e.exportv && show_unexported)) { /* Insert this key */ str_set->insert(iter->first); } } } wcstring_list_t env_get_names(int flags) { scoped_lock lock(env_lock); wcstring_list_t result; std::set<wcstring> names; int show_local = flags & ENV_LOCAL; int show_global = flags & ENV_GLOBAL; int show_universal = flags & ENV_UNIVERSAL; env_node_t *n=top; const bool show_exported = (flags & ENV_EXPORT) || !(flags & ENV_UNEXPORT); const bool show_unexported = (flags & ENV_UNEXPORT) || !(flags & ENV_EXPORT); if (!show_local && !show_global && !show_universal) { show_local =show_universal = show_global=1; } if (show_local) { while (n) { if (n == global_env) break; add_key_to_string_set(n->env, &names, show_exported, show_unexported); if (n->new_scope) break; else n = n->next; } } if (show_global) { add_key_to_string_set(global_env->env, &names, show_exported, show_unexported); if (show_unexported) { result.insert(result.end(), env_electric.begin(), env_electric.end()); } if (show_exported) { result.push_back(L"COLUMNS"); result.push_back(L"LINES"); } } if (show_universal) { wcstring_list_t uni_list; env_universal_get_names(uni_list, show_exported, show_unexported); names.insert(uni_list.begin(), uni_list.end()); } result.insert(result.end(), names.begin(), names.end()); return result; } /** Get list of all exported variables */ static void get_exported(const env_node_t *n, std::map<wcstring, wcstring> &h) { if (!n) return; if (n->new_scope) get_exported(global_env, h); else get_exported(n->next, h); var_table_t::const_iterator iter; for (iter = n->env.begin(); iter != n->env.end(); ++iter) { const wcstring &key = iter->first; const var_entry_t &val_entry = iter->second; if (val_entry.exportv && (val_entry.val != ENV_NULL)) { // Don't use std::map::insert here, since we need to overwrite existing values from previous scopes h[key] = val_entry.val; } } } static void export_func(const std::map<wcstring, wcstring> &envs, std::vector<std::string> &out) { std::map<wcstring, wcstring>::const_iterator iter; for (iter = envs.begin(); iter != envs.end(); ++iter) { const std::string ks = wcs2string(iter->first); std::string vs = wcs2string(iter->second); for (size_t i=0; i < vs.size(); i++) { char &vc = vs.at(i); if (vc == ARRAY_SEP) vc = ':'; } /* Put a string on the vector */ out.push_back(std::string()); std::string &str = out.back(); str.reserve(ks.size() + 1 + vs.size()); /* Append our environment variable data to it */ str.append(ks); str.append("="); str.append(vs); } } static void update_export_array_if_necessary(bool recalc) { ASSERT_IS_MAIN_THREAD(); if (recalc && ! get_proc_had_barrier()) { set_proc_had_barrier(true); env_universal_barrier(); } if (has_changed_exported) { std::map<wcstring, wcstring> vals; size_t i; debug(4, L"env_export_arr() recalc"); get_exported(top, vals); wcstring_list_t uni; env_universal_get_names(uni, 1, 0); for (i=0; i<uni.size(); i++) { const wcstring &key = uni.at(i); const env_var_t val = env_universal_get(key); if (! val.missing() && wcscmp(val.c_str(), ENV_NULL)) { // Note that std::map::insert does NOT overwrite a value already in the map, // which we depend on here vals.insert(std::pair<wcstring, wcstring>(key, val)); } } std::vector<std::string> local_export_buffer; export_func(vals, local_export_buffer); export_array.set(local_export_buffer); has_changed_exported=false; } } const char * const *env_export_arr(bool recalc) { ASSERT_IS_MAIN_THREAD(); update_export_array_if_necessary(recalc); return export_array.get(); } env_vars_snapshot_t::env_vars_snapshot_t(const wchar_t * const *keys) { ASSERT_IS_MAIN_THREAD(); wcstring key; for (size_t i=0; keys[i]; i++) { key.assign(keys[i]); const env_var_t val = env_get_string(key); if (! val.missing()) { vars[key] = val; } } } env_vars_snapshot_t::env_vars_snapshot_t() { } /* The "current" variables are not a snapshot at all, but instead trampoline to env_get_string, etc. We identify the current snapshot based on pointer values. */ static const env_vars_snapshot_t sCurrentSnapshot; const env_vars_snapshot_t &env_vars_snapshot_t::current() { return sCurrentSnapshot; } bool env_vars_snapshot_t::is_current() const { return this == &sCurrentSnapshot; } env_var_t env_vars_snapshot_t::get(const wcstring &key) const { /* If we represent the current state, bounce to env_get_string */ if (this->is_current()) { return env_get_string(key); } else { std::map<wcstring, wcstring>::const_iterator iter = vars.find(key); return (iter == vars.end() ? env_var_t::missing_var() : env_var_t(iter->second)); } } const wchar_t * const env_vars_snapshot_t::highlighting_keys[] = {L"PATH", L"CDPATH", L"fish_function_path", NULL};
./CrossVul/dataset_final_sorted/CWE-59/cpp/good_2134_0
crossvul-cpp_data_bad_2134_0
/** \file env.c Functions for setting and getting environment variables. */ #include "config.h" #include <stdlib.h> #include <wchar.h> #include <string.h> #include <stdio.h> #include <locale.h> #include <unistd.h> #include <signal.h> #include <assert.h> #include <sys/types.h> #include <sys/stat.h> #include <pthread.h> #include <pwd.h> #include <set> #include <map> #include <algorithm> #if HAVE_NCURSES_H #include <ncurses.h> #else #include <curses.h> #endif #if HAVE_TERM_H #include <term.h> #elif HAVE_NCURSES_TERM_H #include <ncurses/term.h> #endif #if HAVE_LIBINTL_H #include <libintl.h> #endif #include <errno.h> #include "fallback.h" #include "util.h" #include "wutil.h" #include "proc.h" #include "common.h" #include "env.h" #include "sanity.h" #include "expand.h" #include "history.h" #include "reader.h" #include "parser.h" #include "env_universal.h" #include "input.h" #include "event.h" #include "path.h" #include "complete.h" #include "fish_version.h" /** Command used to start fishd */ #define FISHD_CMD L"fishd ^ /tmp/fishd.log.%s" // Version for easier debugging //#define FISHD_CMD L"fishd" /** Value denoting a null string */ #define ENV_NULL L"\x1d" /** Some configuration path environment variables */ #define FISH_DATADIR_VAR L"__fish_datadir" #define FISH_SYSCONFDIR_VAR L"__fish_sysconfdir" #define FISH_HELPDIR_VAR L"__fish_help_dir" #define FISH_BIN_DIR L"__fish_bin_dir" /** At init, we read all the environment variables from this array. */ extern char **environ; /** This should be the same thing as \c environ, but it is possible only one of the two work... */ extern char **__environ; bool g_log_forks = false; bool g_use_posix_spawn = false; //will usually be set to true /** Struct representing one level in the function variable stack */ struct env_node_t { /** Variable table */ var_table_t env; /** Does this node imply a new variable scope? If yes, all non-global variables below this one in the stack are invisible. If new_scope is set for the global variable node, the universe will explode. */ bool new_scope; /** Does this node contain any variables which are exported to subshells */ bool exportv; /** Pointer to next level */ struct env_node_t *next; env_node_t() : new_scope(false), exportv(false), next(NULL) { } /* Returns a pointer to the given entry if present, or NULL. */ const var_entry_t *find_entry(const wcstring &key); /* Returns the next scope to search in order, respecting the new_scope flag, or NULL if we're done. */ env_node_t *next_scope_to_search(void); }; class variable_entry_t { wcstring value; /**< Value of the variable */ }; static pthread_mutex_t env_lock = PTHREAD_MUTEX_INITIALIZER; /** Top node on the function stack */ static env_node_t *top = NULL; /** Bottom node on the function stack */ static env_node_t *global_env = NULL; /** Table for global variables */ static var_table_t *global; /* Helper class for storing constant strings, without needing to wrap them in a wcstring */ /* Comparer for const string set */ struct const_string_set_comparer { bool operator()(const wchar_t *a, const wchar_t *b) { return wcscmp(a, b) < 0; } }; typedef std::set<const wchar_t *, const_string_set_comparer> const_string_set_t; /** Table of variables that may not be set using the set command. */ static const_string_set_t env_read_only; static bool is_read_only(const wcstring &key) { return env_read_only.find(key.c_str()) != env_read_only.end(); } /** Table of variables whose value is dynamically calculated, such as umask, status, etc */ static const_string_set_t env_electric; static bool is_electric(const wcstring &key) { return env_electric.find(key.c_str()) != env_electric.end(); } /** Exported variable array used by execv */ static null_terminated_array_t<char> export_array; /** Flag for checking if we need to regenerate the exported variable array */ static bool has_changed_exported = true; static void mark_changed_exported() { has_changed_exported = true; } /** List of all locale variable names */ static const wchar_t * const locale_variable[] = { L"LANG", L"LC_ALL", L"LC_COLLATE", L"LC_CTYPE", L"LC_MESSAGES", L"LC_MONETARY", L"LC_NUMERIC", L"LC_TIME", NULL }; const var_entry_t *env_node_t::find_entry(const wcstring &key) { const var_entry_t *result = NULL; var_table_t::const_iterator where = env.find(key); if (where != env.end()) { result = &where->second; } return result; } env_node_t *env_node_t::next_scope_to_search(void) { return this->new_scope ? global_env : this->next; } /** When fishd isn't started, this function is provided to env_universal as a callback, it tries to start up fishd. It's implementation is a bit of a hack, since it evaluates a bit of shellscript, and it might be used at times when that might not be the best idea. */ static void start_fishd() { struct passwd *pw = getpwuid(getuid()); debug(3, L"Spawning new copy of fishd"); if (!pw) { debug(0, _(L"Could not get user information")); return; } wcstring cmd = format_string(FISHD_CMD, pw->pw_name); /* Prefer the fishd in __fish_bin_dir, if exists */ const env_var_t bin_dir = env_get_string(L"__fish_bin_dir"); if (! bin_dir.missing_or_empty()) { wcstring path = bin_dir + L"/fishd"; if (waccess(path, X_OK) == 0) { /* The path command just looks like 'fishd', so insert the bin path to make it absolute */ cmd.insert(0, bin_dir + L"/"); } } parser_t &parser = parser_t::principal_parser(); parser.eval(cmd, io_chain_t(), TOP); } /** Return the current umask value. */ static mode_t get_umask() { mode_t res; res = umask(0); umask(res); return res; } /** Checks if the specified variable is a locale variable */ static bool var_is_locale(const wcstring &key) { for (size_t i=0; locale_variable[i]; i++) { if (key == locale_variable[i]) { return true; } } return false; } /** Properly sets all locale information */ static void handle_locale() { const env_var_t lc_all = env_get_string(L"LC_ALL"); const wcstring old_locale = wsetlocale(LC_MESSAGES, NULL); /* Array of locale constants corresponding to the local variable names defined in locale_variable */ static const int cat[] = { 0, LC_ALL, LC_COLLATE, LC_CTYPE, LC_MESSAGES, LC_MONETARY, LC_NUMERIC, LC_TIME } ; if (!lc_all.missing()) { wsetlocale(LC_ALL, lc_all.c_str()); } else { const env_var_t lang = env_get_string(L"LANG"); if (!lang.missing()) { wsetlocale(LC_ALL, lang.c_str()); } for (int i=2; locale_variable[i]; i++) { const env_var_t val = env_get_string(locale_variable[i]); if (!val.missing()) { wsetlocale(cat[i], val.c_str()); } } } const wcstring new_locale = wsetlocale(LC_MESSAGES, NULL); if (old_locale != new_locale) { /* Try to make change known to gettext. Both changing _nl_msg_cat_cntr and calling dcgettext might potentially tell some gettext implementation that the translation strings should be reloaded. We do both and hope for the best. */ extern int _nl_msg_cat_cntr; _nl_msg_cat_cntr++; fish_dcgettext("fish", "Changing language to English", LC_MESSAGES); if (get_is_interactive()) { debug(0, _(L"Changing language to English")); } } } /** React to modifying hte given variable */ static void react_to_variable_change(const wcstring &key) { if (var_is_locale(key)) { handle_locale(); } else if (key == L"fish_term256") { update_fish_term256(); reader_react_to_color_change(); } else if (string_prefixes_string(L"fish_color_", key)) { reader_react_to_color_change(); } } /** Universal variable callback function. This function makes sure the proper events are triggered when an event occurs. */ static void universal_callback(fish_message_type_t type, const wchar_t *name, const wchar_t *val) { const wchar_t *str = NULL; switch (type) { case SET: case SET_EXPORT: { str=L"SET"; break; } case ERASE: { str=L"ERASE"; break; } default: break; } if (str) { mark_changed_exported(); event_t ev = event_t::variable_event(name); ev.arguments.push_back(L"VARIABLE"); ev.arguments.push_back(str); ev.arguments.push_back(name); event_fire(&ev); } if (name) react_to_variable_change(name); } /** Make sure the PATH variable contains something */ static void setup_path() { const env_var_t path = env_get_string(L"PATH"); if (path.missing_or_empty()) { const wchar_t *value = L"/usr/bin" ARRAY_SEP_STR L"/bin"; env_set(L"PATH", value, ENV_GLOBAL | ENV_EXPORT); } } int env_set_pwd() { wchar_t dir_path[4096]; wchar_t *res = wgetcwd(dir_path, 4096); if (!res) { return 0; } env_set(L"PWD", dir_path, ENV_EXPORT | ENV_GLOBAL); return 1; } wcstring env_get_pwd_slash(void) { env_var_t pwd = env_get_string(L"PWD"); if (pwd.missing_or_empty()) { return L""; } if (! string_suffixes_string(L"/", pwd)) { pwd.push_back(L'/'); } return pwd; } /** Set up default values for various variables if not defined. */ static void env_set_defaults() { if (env_get_string(L"USER").missing()) { struct passwd *pw = getpwuid(getuid()); if (pw->pw_name != NULL) { const wcstring wide_name = str2wcstring(pw->pw_name); env_set(L"USER", wide_name.c_str(), ENV_GLOBAL); } } if (env_get_string(L"HOME").missing()) { const env_var_t unam = env_get_string(L"USER"); char *unam_narrow = wcs2str(unam.c_str()); struct passwd *pw = getpwnam(unam_narrow); if (pw->pw_dir != NULL) { const wcstring dir = str2wcstring(pw->pw_dir); env_set(L"HOME", dir.c_str(), ENV_GLOBAL); } free(unam_narrow); } env_set_pwd(); } // Some variables should not be arrays. This used to be handled by a startup script, but we'd like to get down to 0 forks for startup, so handle it here. static bool variable_can_be_array(const wcstring &key) { if (key == L"DISPLAY") { return false; } else { return true; } } void env_init(const struct config_paths_t *paths /* or NULL */) { /* env_read_only variables can not be altered directly by the user */ const wchar_t * const ro_keys[] = { L"status", L"history", L"version", L"_", L"LINES", L"COLUMNS", L"PWD", L"SHLVL", L"FISH_VERSION", }; for (size_t i=0; i < sizeof ro_keys / sizeof *ro_keys; i++) { env_read_only.insert(ro_keys[i]); } /* HOME and USER should be writeable by root, since this can be a convenient way to install software. */ if (getuid() != 0) { env_read_only.insert(L"HOME"); env_read_only.insert(L"USER"); } /* Names of all dynamically calculated variables */ env_electric.insert(L"history"); env_electric.insert(L"status"); env_electric.insert(L"umask"); top = new env_node_t; global_env = top; global = &top->env; /* Now the environemnt variable handling is set up, the next step is to insert valid data */ /* Import environment variables */ for (char **p = (environ ? environ : __environ); p && *p; p++) { const wcstring key_and_val = str2wcstring(*p); //like foo=bar size_t eql = key_and_val.find(L'='); if (eql == wcstring::npos) { // no equals found env_set(key_and_val, L"", ENV_EXPORT); } else { wcstring key = key_and_val.substr(0, eql); wcstring val = key_and_val.substr(eql + 1); if (variable_can_be_array(val)) { std::replace(val.begin(), val.end(), L':', ARRAY_SEP); } env_set(key, val.c_str(), ENV_EXPORT | ENV_GLOBAL); } } /* Set the given paths in the environment, if we have any */ if (paths != NULL) { env_set(FISH_DATADIR_VAR, paths->data.c_str(), ENV_GLOBAL | ENV_EXPORT); env_set(FISH_SYSCONFDIR_VAR, paths->sysconf.c_str(), ENV_GLOBAL | ENV_EXPORT); env_set(FISH_HELPDIR_VAR, paths->doc.c_str(), ENV_GLOBAL | ENV_EXPORT); env_set(FISH_BIN_DIR, paths->bin.c_str(), ENV_GLOBAL | ENV_EXPORT); } /* Set up the PATH variable */ setup_path(); /* Set up the USER variable */ const struct passwd *pw = getpwuid(getuid()); if (pw && pw->pw_name) { const wcstring uname = str2wcstring(pw->pw_name); env_set(L"USER", uname.c_str(), ENV_GLOBAL | ENV_EXPORT); } /* Set up the version variables */ wcstring version = str2wcstring(get_fish_version()); env_set(L"version", version.c_str(), ENV_GLOBAL); env_set(L"FISH_VERSION", version.c_str(), ENV_GLOBAL); const env_var_t fishd_dir_wstr = env_get_string(L"FISHD_SOCKET_DIR"); const env_var_t user_dir_wstr = env_get_string(L"USER"); wchar_t * fishd_dir = fishd_dir_wstr.missing()?NULL:const_cast<wchar_t*>(fishd_dir_wstr.c_str()); wchar_t * user_dir = user_dir_wstr.missing()?NULL:const_cast<wchar_t*>(user_dir_wstr.c_str()); env_universal_init(fishd_dir , user_dir , &start_fishd, &universal_callback); /* Set up SHLVL variable */ const env_var_t shlvl_str = env_get_string(L"SHLVL"); wcstring nshlvl_str = L"1"; if (! shlvl_str.missing()) { long shlvl_i = wcstol(shlvl_str.c_str(), NULL, 10); if (shlvl_i >= 0) { nshlvl_str = to_string<long>(shlvl_i + 1); } } env_set(L"SHLVL", nshlvl_str.c_str(), ENV_GLOBAL | ENV_EXPORT); /* Set correct defaults for e.g. USER and HOME variables */ env_set_defaults(); /* Set g_log_forks */ env_var_t log_forks = env_get_string(L"fish_log_forks"); g_log_forks = ! log_forks.missing_or_empty() && from_string<bool>(log_forks); /* Set g_use_posix_spawn. Default to true. */ env_var_t use_posix_spawn = env_get_string(L"fish_use_posix_spawn"); g_use_posix_spawn = (use_posix_spawn.missing_or_empty() ? true : from_string<bool>(use_posix_spawn)); /* Set fish_bind_mode to "default" */ env_set(FISH_BIND_MODE_VAR, DEFAULT_BIND_MODE, ENV_GLOBAL); } void env_destroy() { env_universal_destroy(); while (&top->env != global) { env_pop(); } env_read_only.clear(); env_electric.clear(); var_table_t::iterator iter; for (iter = global->begin(); iter != global->end(); ++iter) { const var_entry_t &entry = iter->second; if (entry.exportv) { mark_changed_exported(); break; } } delete top; } /** Search all visible scopes in order for the specified key. Return the first scope in which it was found. */ static env_node_t *env_get_node(const wcstring &key) { env_node_t *env = top; while (env != NULL) { if (env->find_entry(key) != NULL) { break; } env = env->next_scope_to_search(); } return env; } int env_set(const wcstring &key, const wchar_t *val, int var_mode) { ASSERT_IS_MAIN_THREAD(); bool has_changed_old = has_changed_exported; bool has_changed_new = false; int done=0; int is_universal = 0; if (val && contains(key, L"PWD", L"HOME")) { /* Canoncalize our path; if it changes, recurse and try again. */ wcstring val_canonical = val; path_make_canonical(val_canonical); if (val != val_canonical) { return env_set(key, val_canonical.c_str(), var_mode); } } if ((var_mode & ENV_USER) && is_read_only(key)) { return ENV_PERM; } if (key == L"umask") { wchar_t *end; /* Set the new umask */ if (val && wcslen(val)) { errno=0; long mask = wcstol(val, &end, 8); if (!errno && (!*end) && (mask <= 0777) && (mask >= 0)) { umask(mask); } } /* Do not actually create a umask variable, on env_get, it will be calculated dynamically */ return 0; } /* Zero element arrays are internaly not coded as null but as this placeholder string */ if (!val) { val = ENV_NULL; } if (var_mode & ENV_UNIVERSAL) { bool exportv; if (var_mode & ENV_EXPORT) { // export exportv = true; } else if (var_mode & ENV_UNEXPORT) { // unexport exportv = false; } else { // not changing the export exportv = env_universal_get_export(key); } env_universal_set(key, val, exportv); is_universal = 1; } else { // Determine the node env_node_t *preexisting_node = env_get_node(key); bool preexisting_entry_exportv = false; if (preexisting_node != NULL) { var_table_t::const_iterator result = preexisting_node->env.find(key); assert(result != preexisting_node->env.end()); const var_entry_t &entry = result->second; if (entry.exportv) { preexisting_entry_exportv = true; has_changed_new = true; } } env_node_t *node = NULL; if (var_mode & ENV_GLOBAL) { node = global_env; } else if (var_mode & ENV_LOCAL) { node = top; } else if (preexisting_node != NULL) { node = preexisting_node; if ((var_mode & (ENV_EXPORT | ENV_UNEXPORT)) == 0) { // use existing entry's exportv var_mode = preexisting_entry_exportv ? ENV_EXPORT : 0; } } else { if (! get_proc_had_barrier()) { set_proc_had_barrier(true); env_universal_barrier(); } if (! env_universal_get(key).missing()) { bool exportv; if (var_mode & ENV_EXPORT) { exportv = true; } else if (var_mode & ENV_UNEXPORT) { exportv = false; } else { exportv = env_universal_get_export(key); } env_universal_set(key, val, exportv); is_universal = 1; done = 1; } else { /* New variable with unspecified scope. The default scope is the innermost scope that is shadowing, which will be either the current function or the global scope. */ node = top; while (node->next && !node->new_scope) { node = node->next; } } } if (!done) { // Set the entry in the node // Note that operator[] accesses the existing entry, or creates a new one var_entry_t &entry = node->env[key]; if (entry.exportv) { // this variable already existed, and was exported has_changed_new = true; } entry.val = val; if (var_mode & ENV_EXPORT) { // the new variable is exported entry.exportv = true; node->exportv = true; has_changed_new = true; } else { entry.exportv = false; } if (has_changed_old || has_changed_new) mark_changed_exported(); } } if (!is_universal) { event_t ev = event_t::variable_event(key); ev.arguments.reserve(3); ev.arguments.push_back(L"VARIABLE"); ev.arguments.push_back(L"SET"); ev.arguments.push_back(key); // debug( 1, L"env_set: fire events on variable %ls", key ); event_fire(&ev); // debug( 1, L"env_set: return from event firing" ); } react_to_variable_change(key); return 0; } /** Attempt to remove/free the specified key/value pair from the specified map. \return zero if the variable was not found, non-zero otherwise */ static bool try_remove(env_node_t *n, const wchar_t *key, int var_mode) { if (n == NULL) { return false; } var_table_t::iterator result = n->env.find(key); if (result != n->env.end()) { if (result->second.exportv) { mark_changed_exported(); } n->env.erase(result); return true; } if (var_mode & ENV_LOCAL) { return false; } if (n->new_scope) { return try_remove(global_env, key, var_mode); } else { return try_remove(n->next, key, var_mode); } } int env_remove(const wcstring &key, int var_mode) { ASSERT_IS_MAIN_THREAD(); env_node_t *first_node; int erased = 0; if ((var_mode & ENV_USER) && is_read_only(key)) { return 2; } first_node = top; if (!(var_mode & ENV_UNIVERSAL)) { if (var_mode & ENV_GLOBAL) { first_node = global_env; } if (try_remove(first_node, key.c_str(), var_mode)) { event_t ev = event_t::variable_event(key); ev.arguments.push_back(L"VARIABLE"); ev.arguments.push_back(L"ERASE"); ev.arguments.push_back(key); event_fire(&ev); erased = 1; } } if (!erased && !(var_mode & ENV_GLOBAL) && !(var_mode & ENV_LOCAL)) { erased = ! env_universal_remove(key.c_str()); } react_to_variable_change(key); return !erased; } const wchar_t *env_var_t::c_str(void) const { assert(! is_missing); return wcstring::c_str(); } env_var_t env_get_string(const wcstring &key) { /* Big hack...we only allow getting the history on the main thread. Note that history_t may ask for an environment variable, so don't take the lock here (we don't need it) */ const bool is_main = is_main_thread(); if (key == L"history" && is_main) { env_var_t result; history_t *history = reader_get_history(); if (! history) { history = &history_t::history_with_name(L"fish"); } if (history) history->get_string_representation(result, ARRAY_SEP_STR); return result; } else if (key == L"COLUMNS") { return to_string(common_get_width()); } else if (key == L"LINES") { return to_string(common_get_height()); } else if (key == L"status") { return to_string(proc_get_last_status()); } else if (key == L"umask") { return format_string(L"0%0.3o", get_umask()); } else { { /* Lock around a local region */ scoped_lock lock(env_lock); env_node_t *env = top; wcstring result; while (env != NULL) { const var_entry_t *entry = env->find_entry(key); if (entry != NULL) { if (entry->val == ENV_NULL) { return env_var_t::missing_var(); } else { return entry->val; } } env = env->next_scope_to_search(); } } /* Another big hack - only do a universal barrier on the main thread (since it can change variable values) Make sure we do this outside the env_lock because it may itself call env_get_string */ if (is_main && ! get_proc_had_barrier()) { set_proc_had_barrier(true); env_universal_barrier(); } env_var_t item = env_universal_get(key); if (item.missing() || (wcscmp(item.c_str(), ENV_NULL)==0)) { return env_var_t::missing_var(); } else { return item; } } } bool env_exist(const wchar_t *key, int mode) { env_node_t *env; CHECK(key, false); /* Read only variables all exist, and they are all global. A local version can not exist. */ if (!(mode & ENV_LOCAL) && !(mode & ENV_UNIVERSAL)) { if (is_read_only(key) || is_electric(key)) { //Such variables are never exported if (mode & ENV_EXPORT) { return false; } else if (mode & ENV_UNEXPORT) { return true; } return true; } } if (!(mode & ENV_UNIVERSAL)) { env = (mode & ENV_GLOBAL)?global_env:top; while (env != 0) { var_table_t::iterator result = env->env.find(key); if (result != env->env.end()) { const var_entry_t &res = result->second; if (mode & ENV_EXPORT) { return res.exportv; } else if (mode & ENV_UNEXPORT) { return ! res.exportv; } return true; } if (mode & ENV_LOCAL) break; env = env->next_scope_to_search(); } } if (!(mode & ENV_LOCAL) && !(mode & ENV_GLOBAL)) { if (! get_proc_had_barrier()) { set_proc_had_barrier(true); env_universal_barrier(); } if (! env_universal_get(key).missing()) { if (mode & ENV_EXPORT) { return env_universal_get_export(key) == 1; } else if (mode & ENV_UNEXPORT) { return env_universal_get_export(key) == 0; } return 1; } } return 0; } /** Returns true if the specified scope or any non-shadowed non-global subscopes contain an exported variable. */ static int local_scope_exports(env_node_t *n) { if (n==global_env) return 0; if (n->exportv) return 1; if (n->new_scope) return 0; return local_scope_exports(n->next); } void env_push(bool new_scope) { env_node_t *node = new env_node_t; node->next = top; node->new_scope=new_scope; if (new_scope) { if (local_scope_exports(top)) mark_changed_exported(); } top = node; } void env_pop() { if (&top->env != global) { int i; int locale_changed = 0; env_node_t *killme = top; for (i=0; locale_variable[i]; i++) { var_table_t::iterator result = killme->env.find(locale_variable[i]); if (result != killme->env.end()) { locale_changed = 1; break; } } if (killme->new_scope) { if (killme->exportv || local_scope_exports(killme->next)) mark_changed_exported(); } top = top->next; var_table_t::iterator iter; for (iter = killme->env.begin(); iter != killme->env.end(); ++iter) { const var_entry_t &entry = iter->second; if (entry.exportv) { mark_changed_exported(); break; } } delete killme; if (locale_changed) handle_locale(); } else { debug(0, _(L"Tried to pop empty environment stack.")); sanity_lose(); } } /** Function used with to insert keys of one table into a set::set<wcstring> */ static void add_key_to_string_set(const var_table_t &envs, std::set<wcstring> *str_set, bool show_exported, bool show_unexported) { var_table_t::const_iterator iter; for (iter = envs.begin(); iter != envs.end(); ++iter) { const var_entry_t &e = iter->second; if ((e.exportv && show_exported) || (!e.exportv && show_unexported)) { /* Insert this key */ str_set->insert(iter->first); } } } wcstring_list_t env_get_names(int flags) { scoped_lock lock(env_lock); wcstring_list_t result; std::set<wcstring> names; int show_local = flags & ENV_LOCAL; int show_global = flags & ENV_GLOBAL; int show_universal = flags & ENV_UNIVERSAL; env_node_t *n=top; const bool show_exported = (flags & ENV_EXPORT) || !(flags & ENV_UNEXPORT); const bool show_unexported = (flags & ENV_UNEXPORT) || !(flags & ENV_EXPORT); if (!show_local && !show_global && !show_universal) { show_local =show_universal = show_global=1; } if (show_local) { while (n) { if (n == global_env) break; add_key_to_string_set(n->env, &names, show_exported, show_unexported); if (n->new_scope) break; else n = n->next; } } if (show_global) { add_key_to_string_set(global_env->env, &names, show_exported, show_unexported); if (show_unexported) { result.insert(result.end(), env_electric.begin(), env_electric.end()); } if (show_exported) { result.push_back(L"COLUMNS"); result.push_back(L"LINES"); } } if (show_universal) { wcstring_list_t uni_list; env_universal_get_names(uni_list, show_exported, show_unexported); names.insert(uni_list.begin(), uni_list.end()); } result.insert(result.end(), names.begin(), names.end()); return result; } /** Get list of all exported variables */ static void get_exported(const env_node_t *n, std::map<wcstring, wcstring> &h) { if (!n) return; if (n->new_scope) get_exported(global_env, h); else get_exported(n->next, h); var_table_t::const_iterator iter; for (iter = n->env.begin(); iter != n->env.end(); ++iter) { const wcstring &key = iter->first; const var_entry_t &val_entry = iter->second; if (val_entry.exportv && (val_entry.val != ENV_NULL)) { // Don't use std::map::insert here, since we need to overwrite existing values from previous scopes h[key] = val_entry.val; } } } static void export_func(const std::map<wcstring, wcstring> &envs, std::vector<std::string> &out) { std::map<wcstring, wcstring>::const_iterator iter; for (iter = envs.begin(); iter != envs.end(); ++iter) { const std::string ks = wcs2string(iter->first); std::string vs = wcs2string(iter->second); for (size_t i=0; i < vs.size(); i++) { char &vc = vs.at(i); if (vc == ARRAY_SEP) vc = ':'; } /* Put a string on the vector */ out.push_back(std::string()); std::string &str = out.back(); str.reserve(ks.size() + 1 + vs.size()); /* Append our environment variable data to it */ str.append(ks); str.append("="); str.append(vs); } } static void update_export_array_if_necessary(bool recalc) { ASSERT_IS_MAIN_THREAD(); if (recalc && ! get_proc_had_barrier()) { set_proc_had_barrier(true); env_universal_barrier(); } if (has_changed_exported) { std::map<wcstring, wcstring> vals; size_t i; debug(4, L"env_export_arr() recalc"); get_exported(top, vals); wcstring_list_t uni; env_universal_get_names(uni, 1, 0); for (i=0; i<uni.size(); i++) { const wcstring &key = uni.at(i); const env_var_t val = env_universal_get(key); if (! val.missing() && wcscmp(val.c_str(), ENV_NULL)) { // Note that std::map::insert does NOT overwrite a value already in the map, // which we depend on here vals.insert(std::pair<wcstring, wcstring>(key, val)); } } std::vector<std::string> local_export_buffer; export_func(vals, local_export_buffer); export_array.set(local_export_buffer); has_changed_exported=false; } } const char * const *env_export_arr(bool recalc) { ASSERT_IS_MAIN_THREAD(); update_export_array_if_necessary(recalc); return export_array.get(); } env_vars_snapshot_t::env_vars_snapshot_t(const wchar_t * const *keys) { ASSERT_IS_MAIN_THREAD(); wcstring key; for (size_t i=0; keys[i]; i++) { key.assign(keys[i]); const env_var_t val = env_get_string(key); if (! val.missing()) { vars[key] = val; } } } env_vars_snapshot_t::env_vars_snapshot_t() { } /* The "current" variables are not a snapshot at all, but instead trampoline to env_get_string, etc. We identify the current snapshot based on pointer values. */ static const env_vars_snapshot_t sCurrentSnapshot; const env_vars_snapshot_t &env_vars_snapshot_t::current() { return sCurrentSnapshot; } bool env_vars_snapshot_t::is_current() const { return this == &sCurrentSnapshot; } env_var_t env_vars_snapshot_t::get(const wcstring &key) const { /* If we represent the current state, bounce to env_get_string */ if (this->is_current()) { return env_get_string(key); } else { std::map<wcstring, wcstring>::const_iterator iter = vars.find(key); return (iter == vars.end() ? env_var_t::missing_var() : env_var_t(iter->second)); } } const wchar_t * const env_vars_snapshot_t::highlighting_keys[] = {L"PATH", L"CDPATH", L"fish_function_path", NULL};
./CrossVul/dataset_final_sorted/CWE-59/cpp/bad_2134_0
crossvul-cpp_data_good_915_4
/* * Copyright (C) 2017 ~ 2017 Deepin Technology Co., Ltd. * * Author: zccrs <zccrs@live.com> * * Maintainer: zccrs <zhangjide@deepin.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <QDebug> #include <DLog> #ifdef ENABLE_GUI #include <DApplication> #include <DTitlebar> #include <DThemeManager> #include <QDesktopServices> #include "mainwindow.h" #include "dvirtualimagefileio.h" #include <pwd.h> #include <unistd.h> DWIDGET_USE_NAMESPACE #else #include <QCoreApplication> #endif #include "helper.h" #include "dglobal.h" #include "clonejob.h" #include "commandlineparser.h" bool Global::isOverride = true; bool Global::disableMD5CheckForDimFile = false; bool Global::disableLoopDevice = true; bool Global::fixBoot = false; #ifdef ENABLE_GUI bool Global::isTUIMode = false; #else bool Global::isTUIMode = true; #endif int Global::bufferSize = 1024 * 1024; int Global::compressionLevel = 0; int Global::debugLevel = 1; DCORE_USE_NAMESPACE inline static bool isTUIMode(int argc, char *argv[]) { #ifndef ENABLE_GUI Q_UNUSED(argc) Q_UNUSED(argv) return true; #endif if (qEnvironmentVariableIsEmpty("DISPLAY")) return true; const QByteArrayList in_tui_args = { "--tui", "-i", "--info", "--dim-info", "--to-serial-url", "--from-serial-url", "-f", "--fix-boot", "-v", "--version", "-h", "--help", "--re-checksum" }; for (int i = 1; i < argc; ++i) if (in_tui_args.contains(argv[i])) return true; return false; } static QString logFormat = "[%{time}{yyyy-MM-dd, HH:mm:ss.zzz}] [%{type:-7}] [%{file}=>%{function}: %{line}] %{message}\n"; int main(int argc, char *argv[]) { QCoreApplication *a; if (isTUIMode(argc, argv)) { Global::isTUIMode = true; a = new QCoreApplication(argc, argv); } #ifdef ENABLE_GUI else { ConsoleAppender *consoleAppender = new ConsoleAppender; consoleAppender->setFormat(logFormat); const QString log_file("/var/log/deepin-clone.log"); RollingFileAppender *rollingFileAppender = new RollingFileAppender(log_file); rollingFileAppender->setFormat(logFormat); rollingFileAppender->setLogFilesLimit(5); rollingFileAppender->setDatePattern(RollingFileAppender::DailyRollover); logger->registerAppender(rollingFileAppender); logger->registerAppender(consoleAppender); if (qEnvironmentVariableIsSet("PKEXEC_UID")) { const quint32 pkexec_uid = qgetenv("PKEXEC_UID").toUInt(); DApplication::customQtThemeConfigPathByUserHome(getpwuid(pkexec_uid)->pw_dir); } DApplication::loadDXcbPlugin(); DApplication *app = new DApplication(argc, argv); app->setAttribute(Qt::AA_UseHighDpiPixmaps); if (!qApp->setSingleInstance("_deepin_clone_")) { qCritical() << "As well as the process is running"; return -1; } if (!app->loadTranslator()) { dError("Load translator failed"); } app->setApplicationDisplayName(QObject::tr("Deepin Clone")); app->setApplicationDescription(QObject::tr("Deepin Clone is a backup and restore tool in deepin. " "It supports disk or partition clone, backup and restore, and other functions.")); app->setApplicationAcknowledgementPage("https://www.deepin.org/acknowledgments/deepin-clone/"); app->setTheme("light"); a = app; } #endif a->setApplicationName("deepin-clone"); #ifdef ENABLE_GUI a->setApplicationVersion(DApplication::buildVersion("1.0.0.1")); #else a->setApplicationVersion("1.0.0.1"); #endif a->setOrganizationName("deepin"); CommandLineParser parser; QFile arguments_file("/lib/live/mount/medium/.tmp/deepin-clone.arguments"); QStringList arguments; bool load_arg_from_file = arguments_file.exists() && !Global::isTUIMode && !a->arguments().contains("--tui"); if (load_arg_from_file) { arguments.append(a->arguments().first()); if (!arguments_file.open(QIODevice::ReadOnly)) { qCritical() << "Open \"/lib/live/mount/medium/.tmp/deepin-clone.arguments\" failed, error:" << arguments_file.errorString(); } else { while (!arguments_file.atEnd()) { const QString &arg = QString::fromUtf8(arguments_file.readLine().trimmed()); if (!arg.isEmpty()) arguments.append(arg); } arguments_file.close(); arguments_file.remove(); } qDebug() << arguments; } else { arguments = a->arguments(); } parser.process(arguments); ConsoleAppender *consoleAppender = new ConsoleAppender; consoleAppender->setFormat(logFormat); RollingFileAppender *rollingFileAppender = new RollingFileAppender(parser.logFile()); rollingFileAppender->setFormat(logFormat); rollingFileAppender->setLogFilesLimit(5); rollingFileAppender->setDatePattern(RollingFileAppender::DailyRollover); logger->registerCategoryAppender("deepin.ghost", consoleAppender); logger->registerCategoryAppender("deepin.ghost", rollingFileAppender); parser.parse(); if (load_arg_from_file) { dCDebug("Load arguments from \"%s\"", qPrintable(arguments_file.fileName())); } dCInfo("Application command line: %s", qPrintable(arguments.join(' '))); if (Global::debugLevel == 0) { QLoggingCategory::setFilterRules("deepin.ghost.debug=false"); } if (Global::isTUIMode) { if (!parser.target().isEmpty()) { CloneJob *job = new CloneJob; QObject::connect(job, &QThread::finished, a, &QCoreApplication::quit); job->start(parser.source(), parser.target()); } } #ifdef ENABLE_GUI else { if (!parser.isSetOverride()) Global::isOverride = true; if (!parser.isSetDebug()) Global::debugLevel = 2; MainWindow *window = new MainWindow; window->setFixedSize(860, 660); window->setStyleSheet(DThemeManager::instance()->getQssForWidget("main", window)); window->setWindowIcon(QIcon::fromTheme("deepin-clone")); window->setWindowFlags(Qt::WindowCloseButtonHint | Qt::WindowMinimizeButtonHint | Qt::WindowSystemMenuHint); window->titlebar()->setIcon(window->windowIcon()); window->titlebar()->setTitle(QString()); #if DTK_VERSION > DTK_VERSION_CHECK(2, 0, 6, 0) window->titlebar()->setBackgroundTransparent(true); #endif window->show(); qApp->setProductIcon(window->windowIcon()); if (!parser.source().isEmpty()) { window->startWithFile(parser.source(), parser.target()); } QObject::connect(a, &QCoreApplication::aboutToQuit, window, &MainWindow::deleteLater); QDesktopServices::setUrlHandler("https", window, "openUrl"); } #endif int exitCode = Global::isTUIMode ? a->exec() : qApp->exec(); QString log_backup_file = parser.logBackupFile(); if (log_backup_file.startsWith("serial://")) { log_backup_file = Helper::parseSerialUrl(log_backup_file); } if (log_backup_file.isEmpty()) { return exitCode; } if (!QFile::copy(parser.logFile(), log_backup_file)) { dCWarning("failed to copy log file to \"%s\"", qPrintable(log_backup_file)); } return exitCode; }
./CrossVul/dataset_final_sorted/CWE-59/cpp/good_915_4
crossvul-cpp_data_bad_915_1
/* * Copyright (C) 2017 ~ 2017 Deepin Technology Co., Ltd. * * Author: zccrs <zccrs@live.com> * * Maintainer: zccrs <zhangjide@deepin.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "helper.h" #include "dpartinfo.h" #include "dglobal.h" #include "ddevicepartinfo.h" #include "ddiskinfo.h" #include <QProcess> #include <QEventLoop> #include <QTimer> #include <QJsonDocument> #include <QJsonObject> #include <QFile> #include <QDebug> #include <QLoggingCategory> #include <QRegularExpression> #include <QUuid> #define COMMAND_LSBLK QStringLiteral("/bin/lsblk -J -b -p -o NAME,KNAME,PKNAME,FSTYPE,MOUNTPOINT,LABEL,UUID,SIZE,TYPE,PARTTYPE,PARTLABEL,PARTUUID,MODEL,PHY-SEC,RO,RM,TRAN,SERIAL %1") QByteArray Helper::m_processStandardError; QByteArray Helper::m_processStandardOutput; Q_LOGGING_CATEGORY(lcDeepinGhost, "deepin.ghost") Q_GLOBAL_STATIC(Helper, _g_globalHelper) Helper *Helper::instance() { return _g_globalHelper; } int Helper::processExec(QProcess *process, const QString &command, int timeout, QIODevice::OpenMode mode) { m_processStandardOutput.clear(); m_processStandardError.clear(); QEventLoop loop; QTimer timer; timer.setSingleShot(true); timer.setInterval(timeout); timer.connect(&timer, &QTimer::timeout, &loop, &QEventLoop::quit); loop.connect(process, static_cast<void(QProcess::*)(int)>(&QProcess::finished), &loop, &QEventLoop::exit); // 防止子进程输出信息将管道塞满导致进程阻塞 process->connect(process, &QProcess::readyReadStandardError, process, [process] { m_processStandardError.append(process->readAllStandardError()); }); process->connect(process, &QProcess::readyReadStandardOutput, process, [process] { m_processStandardOutput.append(process->readAllStandardOutput()); }); if (timeout > 0) { timer.start(); } else { QTimer::singleShot(10000, process, [process] { dCWarning("\"%s %s\" running for more than 10 seconds, state=%d, pid_file_exist=%d", qPrintable(process->program()), qPrintable(process->arguments().join(" ")), (int)process->state(), (int)QFile::exists(QString("/proc/%1").arg(process->pid()))); }); } if (Global::debugLevel > 1) dCDebug("Exec: \"%s\", timeout: %d", qPrintable(command), timeout); process->start(command, mode); process->waitForStarted(); if (process->error() != QProcess::UnknownError) { dCError(process->errorString()); return -1; } if (process->state() == QProcess::Running) { loop.exec(); } if (process->state() != QProcess::NotRunning) { dCDebug("The \"%s\" timeout, timeout: %d", qPrintable(command), timeout); if (QFile::exists(QString("/proc/%1").arg(process->pid()))) { process->terminate(); process->waitForFinished(); } else { dCDebug("The \"%s\" is quit, but the QProcess object state is not NotRunning"); } } m_processStandardOutput.append(process->readAllStandardOutput()); m_processStandardError.append(process->readAllStandardError()); if (Global::debugLevel > 1) { dCDebug("Done: \"%s\", exit code: %d", qPrintable(command), process->exitCode()); if (process->exitCode() != 0) { dCError("error: \"%s\"\nstdout: \"%s\"", qPrintable(m_processStandardError), qPrintable(m_processStandardOutput)); } } return process->exitCode(); } int Helper::processExec(const QString &command, int timeout) { QProcess process; return processExec(&process, command, timeout); } QByteArray Helper::lastProcessStandardOutput() { return m_processStandardOutput; } QByteArray Helper::lastProcessStandardError() { return m_processStandardError; } const QLoggingCategory &Helper::loggerCategory() { return lcDeepinGhost(); } void Helper::warning(const QString &message) { m_warningString = message; emit newWarning(message); } void Helper::error(const QString &message) { m_errorString = message; emit newError(message); } QString Helper::lastWarningString() { return m_warningString; } QString Helper::lastErrorString() { return m_errorString; } QString Helper::sizeDisplay(qint64 size) { constexpr qreal kb = 1024; constexpr qreal mb = kb * 1024; constexpr qreal gb = mb * 1024; constexpr qreal tb = gb * 1024; if (size > tb) return QString::asprintf("%.2f TB", size / tb); if (size > gb) return QString::asprintf("%.2f GB", size / gb); if (size > mb) return QString::asprintf("%.2f MB", size / mb); if (size > kb) return QString::asprintf("%.2f KB", size / kb); return QString("%1 B").arg(size); } QString Helper::secondsToString(qint64 seconds) { int days = seconds / 86400; seconds = seconds % 86400; int hours = seconds / 3600; seconds = seconds % 3600; int minutes = seconds / 60; seconds = seconds % 60; if (days > 0) return QObject::tr("%1 d %2 h %3 m").arg(days).arg(hours).arg(minutes + 1); if (hours > 0) return QObject::tr("%1 h %2 m").arg(hours).arg(minutes + 1); if (minutes > 0) return QObject::tr("%1 m").arg(minutes + 1); return QObject::tr("%1 s").arg(seconds); } bool Helper::refreshSystemPartList(const QString &device) { int code = device.isEmpty() ? processExec("partprobe") : processExec(QString("partprobe %1").arg(device)); if (code != 0) return false; QThread::sleep(1); return true; } QString Helper::getPartcloneExecuter(const DPartInfo &info) { QString executor; switch (info.fileSystemType()) { case DPartInfo::Invalid: break; case DPartInfo::Btrfs: executor = "btrfs"; break; case DPartInfo::EXT2: case DPartInfo::EXT3: case DPartInfo::EXT4: executor = "extfs"; break; case DPartInfo::F2FS: executor = "f2fs"; break; case DPartInfo::FAT12: case DPartInfo::FAT16: case DPartInfo::FAT32: executor = "fat"; break; case DPartInfo::HFS_Plus: executor = "hfsplus"; break; case DPartInfo::Minix: executor = "minix"; break; case DPartInfo::Nilfs2: executor = "nilfs2"; break; case DPartInfo::NTFS: executor = "ntfs -I"; break; case DPartInfo::Reiser4: executor = "reiser4"; break; case DPartInfo::VFAT: executor = "vfat"; break; case DPartInfo::XFS: executor = "xfs"; break; default: if (!QStandardPaths::findExecutable("partclone." + info.fileSystemTypeName().toLower()).isEmpty()) executor = info.fileSystemTypeName().toLower(); break; } if (executor.isEmpty()) return "partclone.imager"; return "partclone." + executor; } bool Helper::getPartitionSizeInfo(const QString &partDevice, qint64 *used, qint64 *free, int *blockSize) { QProcess process; QStringList env_list = QProcess::systemEnvironment(); env_list.append("LANG=C"); process.setEnvironment(env_list); if (Helper::isMounted(partDevice)) { process.start(QString("df -B1 -P %1").arg(partDevice)); process.waitForFinished(); if (process.exitCode() != 0) { dCError("Call df failed: %s", qPrintable(process.readAllStandardError())); return false; } QByteArray output = process.readAll(); const QByteArrayList &lines = output.trimmed().split('\n'); if (lines.count() != 2) return false; output = lines.last().simplified(); const QByteArrayList &values = output.split(' '); if (values.count() != 6) return false; bool ok = false; if (used) *used = values.at(2).toLongLong(&ok); if (!ok) return false; if (free) *free = values.at(3).toLongLong(&ok); if (!ok) return false; return true; } else { process.start(QString("%1 -s %2 -c -q -C -L /tmp/partclone.log").arg(getPartcloneExecuter(DDevicePartInfo(partDevice))).arg(partDevice)); process.setStandardOutputFile("/dev/null"); process.setReadChannel(QProcess::StandardError); process.waitForStarted(); qint64 used_block = -1; qint64 free_block = -1; while (process.waitForReadyRead(5000)) { const QByteArray &data = process.readAll(); for (QByteArray line : data.split('\n')) { line = line.simplified(); if (QString::fromLatin1(line).contains(QRegularExpression("\\berror\\b"))) { dCError("Call \"%s %s\" failed: \"%s\"", qPrintable(process.program()), qPrintable(process.arguments().join(' ')), line.constData()); } if (line.startsWith("Space in use:")) { bool ok = false; const QByteArray &value = line.split(' ').value(6, "-1"); used_block = value.toLongLong(&ok); if (!ok) { dCError("String to LongLong failed, String: %s", value.constData()); return false; } } else if (line.startsWith("Free Space:")) { bool ok = false; const QByteArray &value = line.split(' ').value(5, "-1"); free_block = value.toLongLong(&ok); if (!ok) { dCError("String to LongLong failed, String: %s", value.constData()); return false; } } else if (line.startsWith("Block size:")) { bool ok = false; const QByteArray &value = line.split(' ').value(2, "-1"); int block_size = value.toInt(&ok); if (!ok) { dCError("String to Int failed, String: %s", value.constData()); return false; } if (used_block < 0 || free_block < 0 || block_size < 0) return false; if (used) *used = used_block * block_size; if (free) *free = free_block * block_size; if (blockSize) *blockSize = block_size; process.terminate(); process.waitForFinished(); return true; } } } } return false; } QByteArray Helper::callLsblk(const QString &extraArg) { processExec(COMMAND_LSBLK.arg(extraArg)); return lastProcessStandardOutput(); } QJsonArray Helper::getBlockDevices(const QString &commandExtraArg) { const QByteArray &array = Helper::callLsblk(commandExtraArg); QJsonParseError error; const QJsonDocument &jd = QJsonDocument::fromJson(QString::fromUtf8(array).toUtf8(), &error); if (error.error != QJsonParseError::NoError) { dCError(error.errorString()); } return jd.object().value("blockdevices").toArray(); } QString Helper::mountPoint(const QString &device) { const QJsonArray &array = getBlockDevices(device); if (array.isEmpty()) return QString(); return array.first().toObject().value("mountpoint").toString(); } bool Helper::isMounted(const QString &device) { const QJsonArray &array = getBlockDevices("-l " + device); for (const QJsonValue &part : array) { const QJsonObject &obj = part.toObject(); if (!obj.value("mountpoint").isNull()) return true; } return false; } bool Helper::umountDevice(const QString &device) { const QJsonArray &array = getBlockDevices("-l " + device); for (const QJsonValue &device : array) { const QJsonObject &obj = device.toObject(); if (!obj.value("mountpoint").isNull()) { if (processExec(QString("umount -d %1").arg(obj.value("name").toString())) != 0) return false; } } return true; } bool Helper::tryUmountDevice(const QString &device) { const QJsonArray &array = getBlockDevices("-l " + device); for (const QJsonValue &device : array) { const QJsonObject &obj = device.toObject(); if (!obj.value("mountpoint").isNull()) { if (processExec(QString("umount -d %1 --fake").arg(obj.value("name").toString())) != 0) return false; } } return true; } bool Helper::mountDevice(const QString &device, const QString &path, bool readonly) { if (readonly) return processExec(QString("mount -r %1 %2").arg(device, path)) == 0; return processExec(QString("mount %1 %2").arg(device, path)) == 0; } QString Helper::temporaryMountDevice(const QString &device, const QString &name, bool readonly) { QString mount_point = mountPoint(device); if (!mount_point.isEmpty()) return mount_point; mount_point = "%1/.%2/mount/%3"; const QStringList &tmp_paths = QStandardPaths::standardLocations(QStandardPaths::TempLocation); mount_point = mount_point.arg(tmp_paths.isEmpty() ? "/tmp" : tmp_paths.first()).arg(qApp->applicationName()).arg(name); if (!QDir::current().mkpath(mount_point)) { dCError("mkpath \"%s\" failed", qPrintable(mount_point)); return QString(); } if (!mountDevice(device, mount_point, readonly)) { dCError("Mount the device \"%s\" to \"%s\" failed", qPrintable(device), qPrintable(mount_point)); return QString(); } return mount_point; } QString Helper::findDiskBySerialIndexNumber(const QString &serialNumber, int partIndexNumber) { const QJsonArray &array = getBlockDevices(); for (const QJsonValue &disk : array) { const QJsonObject &obj = disk.toObject(); if (obj.value("serial").toString().compare(serialNumber, Qt::CaseInsensitive) != 0) { continue; } if (partIndexNumber <= 0) return obj.value("name").toString(); const QJsonArray &children = obj.value("children").toArray(); for (const QJsonValue &v : children) { const QJsonObject &obj = v.toObject(); const QString &name = obj.value("name").toString(); if (DDevicePartInfo(name).indexNumber() == partIndexNumber) return name; } } return QString(); } int Helper::partitionIndexNumber(const QString &partDevice) { const QJsonArray &array = getBlockDevices(partDevice); if (array.isEmpty()) return -1; const QJsonArray &p_array = getBlockDevices(array.first().toObject().value("pkname").toString() + " -x NAME"); if (p_array.isEmpty()) return -1; const QJsonArray &part_list = p_array.first().toObject().value("children").toArray(); for (int i = 0; i < part_list.count(); ++i) { const QJsonObject &obj = part_list.at(i).toObject(); if (obj.value("name").toString() == partDevice || obj.value("kname").toString() == partDevice) return i; } return -1; } QByteArray Helper::getPartitionTable(const QString &devicePath) { processExec(QStringLiteral("/sbin/sfdisk -d %1").arg(devicePath)); return lastProcessStandardOutput(); } bool Helper::setPartitionTable(const QString &devicePath, const QString &ptFile) { QProcess process; process.setStandardInputFile(ptFile); if (processExec(&process, QStringLiteral("/sbin/sfdisk %1").arg(devicePath)) != 0) return false; int code = processExec(QStringLiteral("/sbin/partprobe %1").arg(devicePath)); processExec("sleep 1"); return code == 0; } bool Helper::saveToFile(const QString &fileName, const QByteArray &data, bool override) { if (!override && QFile::exists(fileName)) return false; QFile file(fileName); if (!file.open(QIODevice::WriteOnly)) { dCError(file.errorString()); return false; } qint64 size = file.write(data); file.flush(); file.close(); return size == data.size(); } bool Helper::isBlockSpecialFile(const QString &fileName) { if (fileName.startsWith("/dev/")) return true; processExec(QStringLiteral("env LANG=C stat -c %F %1").arg(fileName)); return lastProcessStandardOutput() == "block special file\n"; } bool Helper::isPartcloneFile(const QString &fileName) { return processExec(QStringLiteral("partclone.info %1").arg(fileName)) == 0; } bool Helper::isDiskDevice(const QString &devicePath) { const QJsonArray &blocks = getBlockDevices(devicePath); if (blocks.isEmpty()) return false; if (!blocks.first().isObject()) return false; return blocks.first().toObject().value("pkname").isNull(); } bool Helper::isPartitionDevice(const QString &devicePath) { const QJsonArray &blocks = getBlockDevices(devicePath); if (blocks.isEmpty()) return false; if (!blocks.first().isObject()) return false; return !blocks.first().toObject().value("pkname").isString(); } QString Helper::parentDevice(const QString &device) { const QJsonArray &blocks = getBlockDevices(device); if (blocks.isEmpty()) return device; const QString &parent = blocks.first().toObject().value("pkname").toString(); if (parent.isEmpty()) return device; return parent; } bool Helper::deviceHaveKinship(const QString &device1, const QString &device2) { return device1 == device2 || parentDevice(device1) == parentDevice(device2); } int Helper::clonePartition(const DPartInfo &part, const QString &to, bool override) { QString executor = getPartcloneExecuter(part); QString command; if (executor.isEmpty() || executor == "partclone.imager") { if (part.guidType() == DPartInfo::InvalidGUID) return -1; command = QStringLiteral("dd if=%1 of=%2 status=none conv=fsync").arg(part.filePath()).arg(to); } else if (isBlockSpecialFile(to)) { command = QStringLiteral("/usr/sbin/%1 -b -c -s %2 -%3 %4").arg(executor).arg(part.filePath()).arg(override ? "O" : "o").arg(to); } else { command = QStringLiteral("/usr/sbin/%1 -c -s %2 -%3 %4").arg(executor).arg(part.filePath()).arg(override ? "O" : "o").arg(to); } int code = processExec(command); if (code != 0) qDebug() << command << QString::fromUtf8(lastProcessStandardOutput()); return code; } int Helper::restorePartition(const QString &from, const DPartInfo &to) { QString command; if (isPartcloneFile(from)) { command = QStringLiteral("/usr/sbin/partclone.restore -s %1 -o %2").arg(from).arg(to.filePath()); } else { command = QStringLiteral("dd if=%1 of=%2 status=none conv=fsync").arg(from).arg(to.filePath()); } int code = processExec(command); if (code != 0) qDebug() << command << QString::fromUtf8(lastProcessStandardOutput()); return code; } bool Helper::existLiveSystem() { return QFile::exists("/recovery"); } bool Helper::restartToLiveSystem(const QStringList &arguments) { if (!existLiveSystem()) { dCDebug("Not install live system"); return false; } if (!QDir::current().mkpath("/recovery/.tmp")) { dCDebug("mkpath failed"); return false; } QFile file("/recovery/.tmp/deepin-clone.arguments"); if (!file.open(QIODevice::WriteOnly)) { dCDebug("Open file failed: \"%s\"", qPrintable(file.fileName())); return false; } file.write(arguments.join('\n').toUtf8()); file.close(); if (processExec("grub-reboot \"Deepin Recovery\"") != 0) { dCDebug("Exec grub-reboot \"Deepin Recovery\" failed"); file.remove(); return false; } if (processExec("reboot") != 0) file.remove(); return true; } bool Helper::isDeepinSystem(const DPartInfo &part) { QString mout_root = part.mountPoint(); bool umount_device = false; if (mout_root.isEmpty()) { mout_root = temporaryMountDevice(part.name(), QFileInfo(part.name()).fileName(), true); if (mout_root.isEmpty()) return false; umount_device = true; } bool is = QFile::exists(mout_root + "/etc/deepin-version"); if (umount_device) umountDevice(part.name()); return is; } bool Helper::resetPartUUID(const DPartInfo &part, QByteArray uuid) { QString command; if (uuid.isEmpty()) { uuid = QUuid::createUuid().toByteArray().mid(1, 36); } switch (part.fileSystemType()) { case DPartInfo::EXT2: case DPartInfo::EXT3: case DPartInfo::EXT4: command = QString("tune2fs -U %1 %2").arg(QString::fromLatin1(uuid)).arg(part.filePath()); break; case DPartInfo::JFS: command = QString("jfs_tune -U %1 %2").arg(QString::fromLatin1(uuid)).arg(part.filePath()); break; case DPartInfo::NTFS: command = QString("ntfslabel --new-half-serial %1").arg(part.filePath()); break; case DPartInfo::XFS: command = QString("xfs_admin -U %1 %2").arg(QString::fromLatin1(uuid)).arg(part.filePath()); break; default: dCDebug("Not support the file system type: %s", qPrintable(part.fileSystemTypeName())); return false; } if (!umountDevice(part.filePath())) { dCDebug("Failed to umount the partition: %s", qPrintable(part.filePath())); return false; } // check the partition processExec("fsck -f -y " + part.filePath()); bool ok = processExec(command) == 0; if (!ok) { dCError("Failed reset part uuid"); dCDebug(qPrintable(lastProcessStandardOutput())); dCError(qPrintable(lastProcessStandardError())); } return ok; } QString Helper::parseSerialUrl(const QString &urlString, QString *errorString) { if (urlString.isEmpty()) return QString(); const QUrl url(urlString); const QString serial_number = urlString.split("//").at(1).split(":").first(); const int part_index = url.port(); const QString &path = url.path(); const QString &device = Helper::findDiskBySerialIndexNumber(serial_number, part_index); const QString &device_url = part_index > 0 ? QString("serial://%1:%2").arg(serial_number).arg(part_index) : "serial://" + serial_number; if (device.isEmpty()) { if (errorString) { if (part_index > 0) *errorString = QObject::tr("Partition \"%1\" not found").arg(device_url); else *errorString = QObject::tr("Disk \"%1\" not found").arg(device_url); } return device; } if (path.isEmpty()) return device; const QString &mp = Helper::mountPoint(device); QDir mount_point(mp); if (mp.isEmpty()) { QString mount_name; if (part_index >= 0) mount_name = QString("%1-%2").arg(serial_number).arg(part_index); else mount_name = serial_number; const QString &_mount_point = Helper::temporaryMountDevice(device, mount_name); if (_mount_point.isEmpty()) { if (errorString) *errorString = QObject::tr("Failed to mount partition \"%1\"").arg(device_url); return QString(); } mount_point.setPath(_mount_point); } if (mount_point.absolutePath() == "/") return path; return mount_point.absolutePath() + path; } QString Helper::getDeviceForFile(const QString &file, QString *rootPath) { if (file.isEmpty()) return QString(); if (Helper::isBlockSpecialFile(file)) return file; QFileInfo info(file); while (!info.exists() && info.absoluteFilePath() != "/") info.setFile(info.absolutePath()); QStorageInfo storage_info(info.absoluteFilePath()); if (rootPath) *rootPath = storage_info.rootPath(); return QString::fromUtf8(storage_info.device()); } QString Helper::toSerialUrl(const QString &file) { if (file.isEmpty()) return QString(); if (Helper::isBlockSpecialFile(file)) { DDiskInfo info; if (Helper::isDiskDevice(file)) info = DDiskInfo::getInfo(file); else info = DDiskInfo::getInfo(Helper::parentDevice(file)); if (!info) return QString(); if (info.serial().isEmpty()) return QString(); int index = DDevicePartInfo(file).indexNumber(); if (index == 0) return "serial://" + info.serial(); return QString("serial://%1:%2").arg(info.serial()).arg(index); } QString root_path; QString url = toSerialUrl(getDeviceForFile(file, &root_path)); if (root_path == "/") return url + QFileInfo(file).absoluteFilePath(); return url + QFileInfo(file).absoluteFilePath().mid(root_path.length()); }
./CrossVul/dataset_final_sorted/CWE-59/cpp/bad_915_1
crossvul-cpp_data_good_4278_0
/* * Copyright (c) 2007 Henrique Pinto <henrique.pinto@kdemail.net> * Copyright (c) 2008-2009 Harald Hvaal <haraldhv@stud.ntnu.no> * Copyright (c) 2010 Raphael Kubo da Costa <rakuco@FreeBSD.org> * Copyright (c) 2016 Vladyslav Batyrenko <mvlabat@gmail.com> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES ( INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * ( INCLUDING NEGLIGENCE OR OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libarchiveplugin.h" #include "ark_debug.h" #include "queries.h" #include <KLocalizedString> #include <QThread> #include <QFileInfo> #include <QDir> #include <archive_entry.h> LibarchivePlugin::LibarchivePlugin(QObject *parent, const QVariantList &args) : ReadWriteArchiveInterface(parent, args) , m_archiveReadDisk(archive_read_disk_new()) , m_cachedArchiveEntryCount(0) , m_emitNoEntries(false) , m_extractedFilesSize(0) { qCDebug(ARK) << "Initializing libarchive plugin"; archive_read_disk_set_standard_lookup(m_archiveReadDisk.data()); connect(this, &ReadOnlyArchiveInterface::error, this, &LibarchivePlugin::slotRestoreWorkingDir); connect(this, &ReadOnlyArchiveInterface::cancelled, this, &LibarchivePlugin::slotRestoreWorkingDir); } LibarchivePlugin::~LibarchivePlugin() { for (const auto e : qAsConst(m_emittedEntries)) { // Entries might be passed to pending slots, so we just schedule their deletion. e->deleteLater(); } } bool LibarchivePlugin::list() { qCDebug(ARK) << "Listing archive contents"; if (!initializeReader()) { return false; } qCDebug(ARK) << "Detected compression filter:" << archive_filter_name(m_archiveReader.data(), 0); QString compMethod = convertCompressionName(QString::fromUtf8(archive_filter_name(m_archiveReader.data(), 0))); if (!compMethod.isEmpty()) { emit compressionMethodFound(compMethod); } m_cachedArchiveEntryCount = 0; m_extractedFilesSize = 0; m_numberOfEntries = 0; auto compressedArchiveSize = QFileInfo(filename()).size(); struct archive_entry *aentry; int result = ARCHIVE_RETRY; bool firstEntry = true; while (!QThread::currentThread()->isInterruptionRequested() && (result = archive_read_next_header(m_archiveReader.data(), &aentry)) == ARCHIVE_OK) { if (firstEntry) { qCDebug(ARK) << "Detected format for first entry:" << archive_format_name(m_archiveReader.data()); firstEntry = false; } if (!m_emitNoEntries) { emitEntryFromArchiveEntry(aentry); } m_extractedFilesSize += (qlonglong)archive_entry_size(aentry); emit progress(float(archive_filter_bytes(m_archiveReader.data(), -1))/float(compressedArchiveSize)); m_cachedArchiveEntryCount++; // Skip the entry data. int readSkipResult = archive_read_data_skip(m_archiveReader.data()); if (readSkipResult != ARCHIVE_OK) { qCCritical(ARK) << "Error while skipping data for entry:" << QString::fromWCharArray(archive_entry_pathname_w(aentry)) << readSkipResult << QLatin1String(archive_error_string(m_archiveReader.data())); if (!emitCorruptArchive()) { return false; } } } if (result != ARCHIVE_EOF) { qCCritical(ARK) << "Error while reading archive:" << result << QLatin1String(archive_error_string(m_archiveReader.data())); if (!emitCorruptArchive()) { return false; } } return archive_read_close(m_archiveReader.data()) == ARCHIVE_OK; } bool LibarchivePlugin::emitCorruptArchive() { Kerfuffle::LoadCorruptQuery query(filename()); emit userQuery(&query); query.waitForResponse(); if (!query.responseYes()) { emit cancelled(); archive_read_close(m_archiveReader.data()); return false; } else { emit progress(1.0); return true; } } bool LibarchivePlugin::addFiles(const QVector<Archive::Entry*> &files, const Archive::Entry *destination, const CompressionOptions &options, uint numberOfEntriesToAdd) { Q_UNUSED(files) Q_UNUSED(destination) Q_UNUSED(options) Q_UNUSED(numberOfEntriesToAdd) return false; } bool LibarchivePlugin::moveFiles(const QVector<Archive::Entry*> &files, Archive::Entry *destination, const CompressionOptions &options) { Q_UNUSED(files) Q_UNUSED(destination) Q_UNUSED(options) return false; } bool LibarchivePlugin::copyFiles(const QVector<Archive::Entry*> &files, Archive::Entry *destination, const CompressionOptions &options) { Q_UNUSED(files) Q_UNUSED(destination) Q_UNUSED(options) return false; } bool LibarchivePlugin::deleteFiles(const QVector<Archive::Entry*> &files) { Q_UNUSED(files) return false; } bool LibarchivePlugin::addComment(const QString &comment) { Q_UNUSED(comment) return false; } bool LibarchivePlugin::testArchive() { return false; } bool LibarchivePlugin::hasBatchExtractionProgress() const { return true; } bool LibarchivePlugin::doKill() { return false; } bool LibarchivePlugin::extractFiles(const QVector<Archive::Entry*> &files, const QString &destinationDirectory, const ExtractionOptions &options) { if (!initializeReader()) { return false; } ArchiveWrite writer(archive_write_disk_new()); if (!writer.data()) { return false; } archive_write_disk_set_options(writer.data(), extractionFlags()); int totalEntriesCount = 0; const bool extractAll = files.isEmpty(); if (extractAll) { if (!m_cachedArchiveEntryCount) { emit progress(0); //TODO: once information progress has been implemented, send //feedback here that the archive is being read qCDebug(ARK) << "For getting progress information, the archive will be listed once"; m_emitNoEntries = true; list(); m_emitNoEntries = false; } totalEntriesCount = m_cachedArchiveEntryCount; } else { totalEntriesCount = files.size(); } qCDebug(ARK) << "Going to extract" << totalEntriesCount << "entries"; qCDebug(ARK) << "Changing current directory to " << destinationDirectory; m_oldWorkingDir = QDir::currentPath(); QDir::setCurrent(destinationDirectory); // Initialize variables. const bool preservePaths = options.preservePaths(); const bool removeRootNode = options.isDragAndDropEnabled(); bool overwriteAll = false; // Whether to overwrite all files bool skipAll = false; // Whether to skip all files bool dontPromptErrors = false; // Whether to prompt for errors m_currentExtractedFilesSize = 0; int extractedEntriesCount = 0; int progressEntryCount = 0; struct archive_entry *entry; QString fileBeingRenamed; // To avoid traversing the entire archive when extracting a limited set of // entries, we maintain a list of remaining entries and stop when it's empty. const QStringList fullPaths = entryFullPaths(files); QStringList remainingFiles = entryFullPaths(files); // Iterate through all entries in archive. while (!QThread::currentThread()->isInterruptionRequested() && (archive_read_next_header(m_archiveReader.data(), &entry) == ARCHIVE_OK)) { if (!extractAll && remainingFiles.isEmpty()) { break; } fileBeingRenamed.clear(); int index = -1; // Retry with renamed entry, fire an overwrite query again // if the new entry also exists. retry: const bool entryIsDir = S_ISDIR(archive_entry_mode(entry)); // Skip directories if not preserving paths. if (!preservePaths && entryIsDir) { archive_read_data_skip(m_archiveReader.data()); continue; } // entryName is the name inside the archive, full path QString entryName = QDir::fromNativeSeparators(QFile::decodeName(archive_entry_pathname(entry))); // Some archive types e.g. AppImage prepend all entries with "./" so remove this part. if (entryName.startsWith(QLatin1String("./"))) { entryName.remove(0, 2); } // Static libraries (*.a) contain the two entries "/" and "//". // We just skip these to allow extracting this archive type. if (entryName == QLatin1String("/") || entryName == QLatin1String("//")) { archive_read_data_skip(m_archiveReader.data()); continue; } // For now we just can't handle absolute filenames in a tar archive. // TODO: find out what to do here!! if (entryName.startsWith(QLatin1Char( '/' ))) { emit error(i18n("This archive contains archive entries with absolute paths, " "which are not supported by Ark.")); return false; } // Should the entry be extracted? if (extractAll || remainingFiles.contains(entryName) || entryName == fileBeingRenamed) { // Find the index of entry. if (entryName != fileBeingRenamed) { index = fullPaths.indexOf(entryName); } if (!extractAll && index == -1) { // If entry is not found in files, skip entry. continue; } // entryFI is the fileinfo pointing to where the file will be // written from the archive. QFileInfo entryFI(entryName); //qCDebug(ARK) << "setting path to " << archive_entry_pathname( entry ); const QString fileWithoutPath(entryFI.fileName()); // If we DON'T preserve paths, we cut the path and set the entryFI // fileinfo to the one without the path. if (!preservePaths) { // Empty filenames (ie dirs) should have been skipped already, // so asserting. Q_ASSERT(!fileWithoutPath.isEmpty()); archive_entry_copy_pathname(entry, QFile::encodeName(fileWithoutPath).constData()); entryFI = QFileInfo(fileWithoutPath); // OR, if the file has a rootNode attached, remove it from file path. } else if (!extractAll && removeRootNode && entryName != fileBeingRenamed) { const QString &rootNode = files.at(index)->rootNode; if (!rootNode.isEmpty()) { const QString truncatedFilename(entryName.remove(entryName.indexOf(rootNode), rootNode.size())); archive_entry_copy_pathname(entry, QFile::encodeName(truncatedFilename).constData()); entryFI = QFileInfo(truncatedFilename); } } // Check if the file about to be written already exists. if (!entryIsDir && entryFI.exists()) { if (skipAll) { archive_read_data_skip(m_archiveReader.data()); archive_entry_clear(entry); continue; } else if (!overwriteAll && !skipAll) { Kerfuffle::OverwriteQuery query(entryName); emit userQuery(&query); query.waitForResponse(); if (query.responseCancelled()) { emit cancelled(); archive_read_data_skip(m_archiveReader.data()); archive_entry_clear(entry); break; } else if (query.responseSkip()) { archive_read_data_skip(m_archiveReader.data()); archive_entry_clear(entry); continue; } else if (query.responseAutoSkip()) { archive_read_data_skip(m_archiveReader.data()); archive_entry_clear(entry); skipAll = true; continue; } else if (query.responseRename()) { const QString newName(query.newFilename()); fileBeingRenamed = newName; archive_entry_copy_pathname(entry, QFile::encodeName(newName).constData()); goto retry; } else if (query.responseOverwriteAll()) { overwriteAll = true; } } } // If there is an already existing directory. if (entryIsDir && entryFI.exists()) { if (entryFI.isWritable()) { qCWarning(ARK) << "Warning, existing, but writable dir"; } else { qCWarning(ARK) << "Warning, existing, but non-writable dir. skipping"; archive_entry_clear(entry); archive_read_data_skip(m_archiveReader.data()); continue; } } // Write the entry header and check return value. const int returnCode = archive_write_header(writer.data(), entry); switch (returnCode) { case ARCHIVE_OK: // If the whole archive is extracted and the total filesize is // available, we use partial progress. copyData(entryName, m_archiveReader.data(), writer.data(), (extractAll && m_extractedFilesSize)); break; case ARCHIVE_FAILED: qCCritical(ARK) << "archive_write_header() has returned" << returnCode << "with errno" << archive_errno(writer.data()); // If they user previously decided to ignore future errors, // don't bother prompting again. if (!dontPromptErrors) { // Ask the user if he wants to continue extraction despite an error for this entry. Kerfuffle::ContinueExtractionQuery query(QLatin1String(archive_error_string(writer.data())), entryName); emit userQuery(&query); query.waitForResponse(); if (query.responseCancelled()) { emit cancelled(); return false; } dontPromptErrors = query.dontAskAgain(); } break; case ARCHIVE_FATAL: qCCritical(ARK) << "archive_write_header() has returned" << returnCode << "with errno" << archive_errno(writer.data()); emit error(i18nc("@info", "Fatal error, extraction aborted.")); return false; default: qCDebug(ARK) << "archive_write_header() returned" << returnCode << "which will be ignored."; break; } // If we only partially extract the archive and the number of // archive entries is available we use a simple progress based on // number of items extracted. if (!extractAll && m_cachedArchiveEntryCount) { ++progressEntryCount; emit progress(float(progressEntryCount) / totalEntriesCount); } extractedEntriesCount++; remainingFiles.removeOne(entryName); } else { // Archive entry not among selected files, skip it. archive_read_data_skip(m_archiveReader.data()); } } qCDebug(ARK) << "Extracted" << extractedEntriesCount << "entries"; slotRestoreWorkingDir(); return archive_read_close(m_archiveReader.data()) == ARCHIVE_OK; } bool LibarchivePlugin::initializeReader() { m_archiveReader.reset(archive_read_new()); if (!(m_archiveReader.data())) { emit error(i18n("The archive reader could not be initialized.")); return false; } if (archive_read_support_filter_all(m_archiveReader.data()) != ARCHIVE_OK) { return false; } if (archive_read_support_format_all(m_archiveReader.data()) != ARCHIVE_OK) { return false; } if (archive_read_open_filename(m_archiveReader.data(), QFile::encodeName(filename()).constData(), 10240) != ARCHIVE_OK) { qCWarning(ARK) << "Could not open the archive:" << archive_error_string(m_archiveReader.data()); emit error(i18nc("@info", "Archive corrupted or insufficient permissions.")); return false; } return true; } void LibarchivePlugin::emitEntryFromArchiveEntry(struct archive_entry *aentry) { auto e = new Archive::Entry(); #ifdef Q_OS_WIN e->setProperty("fullPath", QDir::fromNativeSeparators(QString::fromUtf16((ushort*)archive_entry_pathname_w(aentry)))); #else e->setProperty("fullPath", QDir::fromNativeSeparators(QString::fromWCharArray(archive_entry_pathname_w(aentry)))); #endif const QString owner = QString::fromLatin1(archive_entry_uname(aentry)); if (!owner.isEmpty()) { e->setProperty("owner", owner); } else { e->setProperty("owner", static_cast<qlonglong>(archive_entry_uid(aentry))); } const QString group = QString::fromLatin1(archive_entry_gname(aentry)); if (!group.isEmpty()) { e->setProperty("group", group); } else { e->setProperty("group", static_cast<qlonglong>(archive_entry_gid(aentry))); } const mode_t mode = archive_entry_mode(aentry); if (mode != 0) { e->setProperty("permissions", QString::number(mode, 8)); } e->setProperty("isExecutable", mode & (S_IXUSR | S_IXGRP | S_IXOTH)); e->compressedSizeIsSet = false; e->setProperty("size", (qlonglong)archive_entry_size(aentry)); e->setProperty("isDirectory", S_ISDIR(archive_entry_mode(aentry))); if (archive_entry_symlink(aentry)) { e->setProperty("link", QLatin1String( archive_entry_symlink(aentry) )); } auto time = static_cast<uint>(archive_entry_mtime(aentry)); e->setProperty("timestamp", QDateTime::fromSecsSinceEpoch(time)); emit entry(e); m_emittedEntries << e; } int LibarchivePlugin::extractionFlags() const { return ARCHIVE_EXTRACT_TIME | ARCHIVE_EXTRACT_SECURE_NODOTDOT | ARCHIVE_EXTRACT_SECURE_SYMLINKS; } void LibarchivePlugin::copyData(const QString& filename, struct archive *dest, bool partialprogress) { char buff[10240]; QFile file(filename); if (!file.open(QIODevice::ReadOnly)) { return; } auto readBytes = file.read(buff, sizeof(buff)); while (readBytes > 0 && !QThread::currentThread()->isInterruptionRequested()) { archive_write_data(dest, buff, static_cast<size_t>(readBytes)); if (archive_errno(dest) != ARCHIVE_OK) { qCCritical(ARK) << "Error while writing" << filename << ":" << archive_error_string(dest) << "(error no =" << archive_errno(dest) << ')'; return; } if (partialprogress) { m_currentExtractedFilesSize += readBytes; emit progress(float(m_currentExtractedFilesSize) / m_extractedFilesSize); } readBytes = file.read(buff, sizeof(buff)); } file.close(); } void LibarchivePlugin::copyData(const QString& filename, struct archive *source, struct archive *dest, bool partialprogress) { char buff[10240]; auto readBytes = archive_read_data(source, buff, sizeof(buff)); while (readBytes > 0 && !QThread::currentThread()->isInterruptionRequested()) { archive_write_data(dest, buff, static_cast<size_t>(readBytes)); if (archive_errno(dest) != ARCHIVE_OK) { qCCritical(ARK) << "Error while extracting" << filename << ":" << archive_error_string(dest) << "(error no =" << archive_errno(dest) << ')'; return; } if (partialprogress) { m_currentExtractedFilesSize += readBytes; emit progress(float(m_currentExtractedFilesSize) / m_extractedFilesSize); } readBytes = archive_read_data(source, buff, sizeof(buff)); } } void LibarchivePlugin::slotRestoreWorkingDir() { if (m_oldWorkingDir.isEmpty()) { return; } if (!QDir::setCurrent(m_oldWorkingDir)) { qCWarning(ARK) << "Failed to restore old working directory:" << m_oldWorkingDir; } else { m_oldWorkingDir.clear(); } } QString LibarchivePlugin::convertCompressionName(const QString &method) { if (method == QLatin1String("gzip")) { return QStringLiteral("GZip"); } else if (method == QLatin1String("bzip2")) { return QStringLiteral("BZip2"); } else if (method == QLatin1String("xz")) { return QStringLiteral("XZ"); } else if (method == QLatin1String("compress (.Z)")) { return QStringLiteral("Compress"); } else if (method == QLatin1String("lrzip")) { return QStringLiteral("LRZip"); } else if (method == QLatin1String("lzip")) { return QStringLiteral("LZip"); } else if (method == QLatin1String("lz4")) { return QStringLiteral("LZ4"); } else if (method == QLatin1String("lzop")) { return QStringLiteral("lzop"); } else if (method == QLatin1String("lzma")) { return QStringLiteral("LZMA"); } else if (method == QLatin1String("zstd")) { return QStringLiteral("Zstandard"); } return QString(); }
./CrossVul/dataset_final_sorted/CWE-59/cpp/good_4278_0
crossvul-cpp_data_good_1993_0
// Copyright 2005-2019 The Mumble Developers. All rights reserved. // Use of this source code is governed by a BSD-style license // that can be found in the LICENSE file at the root of the // Mumble source tree or at <https://www.mumble.info/LICENSE>. #include "mumble_pch.hpp" #include "ConnectDialog.h" #ifdef USE_BONJOUR #include "BonjourClient.h" #include "BonjourServiceBrowser.h" #include "BonjourServiceResolver.h" #endif #include "Channel.h" #include "Database.h" #include "ServerHandler.h" #include "WebFetch.h" #include "ServerResolver.h" // We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name (like protobuf 3.7 does). As such, for now, we have to make this our last include. #include "Global.h" QMap<QString, QIcon> ServerItem::qmIcons; QList<PublicInfo> ConnectDialog::qlPublicServers; QString ConnectDialog::qsUserCountry, ConnectDialog::qsUserCountryCode, ConnectDialog::qsUserContinentCode; Timer ConnectDialog::tPublicServers; PingStats::PingStats() { init(); } PingStats::~PingStats() { delete asQuantile; } void PingStats::init() { boost::array<double, 3> probs = {{0.75, 0.80, 0.95 }}; asQuantile = new asQuantileType(boost::accumulators::tag::extended_p_square::probabilities = probs); dPing = 0.0; uiPing = 0; uiPingSort = 0; uiUsers = 0; uiMaxUsers = 0; uiBandwidth = 0; uiSent = 0; uiRecv = 0; uiVersion = 0; } void PingStats::reset() { delete asQuantile; init(); } ServerViewDelegate::ServerViewDelegate(QObject *p) : QStyledItemDelegate(p) { } ServerViewDelegate::~ServerViewDelegate() { } void ServerViewDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { // Allow a ServerItem's BackgroundRole to override the current theme's default color. QVariant bg = index.data(Qt::BackgroundRole); if (bg.isValid()) { painter->fillRect(option.rect, bg.value<QBrush>()); } QStyledItemDelegate::paint(painter, option, index); } ServerView::ServerView(QWidget *p) : QTreeWidget(p) { siFavorite = new ServerItem(tr("Favorite"), ServerItem::FavoriteType); addTopLevelItem(siFavorite); siFavorite->setExpanded(true); siFavorite->setHidden(true); #ifdef USE_BONJOUR siLAN = new ServerItem(tr("LAN"), ServerItem::LANType); addTopLevelItem(siLAN); siLAN->setExpanded(true); siLAN->setHidden(true); #else siLAN = NULL; #endif if (!g.s.disablePublicList) { siPublic = new ServerItem(tr("Public Internet"), ServerItem::PublicType); siPublic->setChildIndicatorPolicy(QTreeWidgetItem::ShowIndicator); addTopLevelItem(siPublic); siPublic->setExpanded(false); // The continent code is empty when the server's IP address is not in the GeoIP database qmContinentNames.insert(QLatin1String(""), tr("Unknown")); qmContinentNames.insert(QLatin1String("af"), tr("Africa")); qmContinentNames.insert(QLatin1String("as"), tr("Asia")); qmContinentNames.insert(QLatin1String("na"), tr("North America")); qmContinentNames.insert(QLatin1String("sa"), tr("South America")); qmContinentNames.insert(QLatin1String("eu"), tr("Europe")); qmContinentNames.insert(QLatin1String("oc"), tr("Oceania")); } else { qWarning()<< "Public list disabled"; siPublic = NULL; } } ServerView::~ServerView() { delete siFavorite; delete siLAN; delete siPublic; } QMimeData *ServerView::mimeData(const QList<QTreeWidgetItem *> mimeitems) const { if (mimeitems.isEmpty()) return NULL; ServerItem *si = static_cast<ServerItem *>(mimeitems.first()); return si->toMimeData(); } QStringList ServerView::mimeTypes() const { QStringList qsl; qsl << QStringList(QLatin1String("text/uri-list")); qsl << QStringList(QLatin1String("text/plain")); return qsl; } Qt::DropActions ServerView::supportedDropActions() const { return Qt::CopyAction | Qt::LinkAction; } /* Extract and append (2), (3) etc to the end of a servers name if it is cloned. */ void ServerView::fixupName(ServerItem *si) { QString name = si->qsName; int tag = 1; QRegExp tmatch(QLatin1String("(.+)\\((\\d+)\\)")); tmatch.setMinimal(true); if (tmatch.exactMatch(name)) { name = tmatch.capturedTexts().at(1).trimmed(); tag = tmatch.capturedTexts().at(2).toInt(); } bool found; QString cmpname; do { found = false; if (tag > 1) cmpname = name + QString::fromLatin1(" (%1)").arg(tag); else cmpname = name; foreach(ServerItem *f, siFavorite->qlChildren) if (f->qsName == cmpname) found = true; ++tag; } while (found); si->qsName = cmpname; } bool ServerView::dropMimeData(QTreeWidgetItem *, int, const QMimeData *mime, Qt::DropAction) { ServerItem *si = ServerItem::fromMimeData(mime); if (! si) return false; fixupName(si); qobject_cast<ConnectDialog *>(parent())->qlItems << si; siFavorite->addServerItem(si); qobject_cast<ConnectDialog *>(parent())->startDns(si); setCurrentItem(si); return true; } ServerItem *ServerView::getParent(const QString &continentcode, const QString &countrycode, const QString &countryname, const QString &usercontinent, const QString &usercountry) { ServerItem *continent = qmContinent.value(continentcode); if (!continent) { QString name = qmContinentNames.value(continentcode); if (name.isEmpty()) name = continentcode; continent = new ServerItem(name, ServerItem::PublicType, continentcode); qmContinent.insert(continentcode, continent); siPublic->addServerItem(continent); if (!continentcode.isEmpty()) { if (continentcode == usercontinent) { continent->setExpanded(true); scrollToItem(continent, QAbstractItemView::PositionAtTop); } } else { continent->setChildIndicatorPolicy(QTreeWidgetItem::ShowIndicator); } } // If the continent code is empty, we put the server directly into the "Unknown" continent if (continentcode.isEmpty()) { return continent; } ServerItem *country = qmCountry.value(countrycode); if (!country) { country = new ServerItem(countryname, ServerItem::PublicType, continentcode, countrycode); qmCountry.insert(countrycode, country); country->setChildIndicatorPolicy(QTreeWidgetItem::ShowIndicator); continent->addServerItem(country); if (!countrycode.isEmpty() && countrycode == usercountry) { country->setExpanded(true); scrollToItem(country, QAbstractItemView::PositionAtTop); } } return country; } void ServerItem::init() { // Without this, columncount is wrong. setData(0, Qt::DisplayRole, QVariant()); setData(1, Qt::DisplayRole, QVariant()); setData(2, Qt::DisplayRole, QVariant()); emitDataChanged(); } ServerItem::ServerItem(const FavoriteServer &fs) : QTreeWidgetItem(QTreeWidgetItem::UserType) { siParent = NULL; bParent = false; itType = FavoriteType; qsName = fs.qsName; usPort = fs.usPort; qsUsername = fs.qsUsername; qsPassword = fs.qsPassword; qsUrl = fs.qsUrl; bCA = false; if (fs.qsHostname.startsWith(QLatin1Char('@'))) { qsBonjourHost = fs.qsHostname.mid(1); brRecord = BonjourRecord(qsBonjourHost, QLatin1String("_mumble._tcp."), QLatin1String("local.")); } else { qsHostname = fs.qsHostname; } init(); } ServerItem::ServerItem(const PublicInfo &pi) : QTreeWidgetItem(QTreeWidgetItem::UserType) { siParent = NULL; bParent = false; itType = PublicType; qsName = pi.qsName; qsHostname = pi.qsIp; usPort = pi.usPort; qsUrl = pi.quUrl.toString(); qsCountry = pi.qsCountry; qsCountryCode = pi.qsCountryCode; qsContinentCode = pi.qsContinentCode; bCA = pi.bCA; init(); } ServerItem::ServerItem(const QString &name, const QString &host, unsigned short port, const QString &username, const QString &password) : QTreeWidgetItem(QTreeWidgetItem::UserType) { siParent = NULL; bParent = false; itType = FavoriteType; qsName = name; usPort = port; qsUsername = username; qsPassword = password; bCA = false; if (host.startsWith(QLatin1Char('@'))) { qsBonjourHost = host.mid(1); brRecord = BonjourRecord(qsBonjourHost, QLatin1String("_mumble._tcp."), QLatin1String("local.")); } else { qsHostname = host; } init(); } ServerItem::ServerItem(const BonjourRecord &br) : QTreeWidgetItem(QTreeWidgetItem::UserType) { siParent = NULL; bParent = false; itType = LANType; qsName = br.serviceName; qsBonjourHost = qsName; brRecord = br; usPort = 0; bCA = false; init(); } ServerItem::ServerItem(const QString &name, ItemType itype, const QString &continent, const QString &country) { siParent = NULL; bParent = true; qsName = name; itType = itype; if (itType == PublicType) { qsCountryCode = country; qsContinentCode = continent; } setFlags(flags() & ~Qt::ItemIsDragEnabled); bCA = false; init(); } ServerItem::ServerItem(const ServerItem *si) { siParent = NULL; bParent = false; itType = FavoriteType; qsName = si->qsName; qsHostname = si->qsHostname; usPort = si->usPort; qsUsername = si->qsUsername; qsPassword = si->qsPassword; qsCountry = si->qsCountry; qsCountryCode = si->qsCountryCode; qsContinentCode = si->qsContinentCode; qsUrl = si->qsUrl; qsBonjourHost = si->qsBonjourHost; brRecord = si->brRecord; qlAddresses = si->qlAddresses; bCA = si->bCA; uiVersion = si->uiVersion; uiPing = si->uiPing; uiPingSort = si->uiPing; uiUsers = si->uiUsers; uiMaxUsers = si->uiMaxUsers; uiBandwidth = si->uiBandwidth; uiSent = si->uiSent; dPing = si->dPing; *asQuantile = * si->asQuantile; } ServerItem::~ServerItem() { if (siParent) { siParent->qlChildren.removeAll(this); if (siParent->bParent && siParent->qlChildren.isEmpty()) siParent->setHidden(true); } // This is just for cleanup when exiting the dialog, it won't stop pending DNS for the children. foreach(ServerItem *si, qlChildren) delete si; } ServerItem *ServerItem::fromMimeData(const QMimeData *mime, bool default_name, QWidget *p, bool convertHttpUrls) { if (mime->hasFormat(QLatin1String("OriginatedInMumble"))) return NULL; QUrl url; if (mime->hasUrls() && ! mime->urls().isEmpty()) url = mime->urls().at(0); else if (mime->hasText()) url = QUrl::fromEncoded(mime->text().toUtf8()); QString qsFile = url.toLocalFile(); if (! qsFile.isEmpty()) { QFile f(qsFile); // Make sure we don't accidently read something big the user // happened to have in his clipboard. We only want to look // at small link files. if (f.open(QIODevice::ReadOnly) && f.size() < 10240) { QByteArray qba = f.readAll(); f.close(); url = QUrl::fromEncoded(qba, QUrl::StrictMode); if (! url.isValid()) { // Windows internet shortcut files (.url) are an ini with an URL value QSettings qs(qsFile, QSettings::IniFormat); url = QUrl::fromEncoded(qs.value(QLatin1String("InternetShortcut/URL")).toByteArray(), QUrl::StrictMode); } } } if (default_name) { #if QT_VERSION >= 0x050000 QUrlQuery query(url); if (! query.hasQueryItem(QLatin1String("title"))) { query.addQueryItem(QLatin1String("title"), url.host()); } #else if (! url.hasQueryItem(QLatin1String("title"))) { url.addQueryItem(QLatin1String("title"), url.host()); } #endif } if (! url.isValid()) { return NULL; } // An URL from text without a scheme will have the hostname text // in the QUrl scheme and no hostname. We do not want to use that. if (url.host().isEmpty()) { return NULL; } // Some communication programs automatically create http links from domains. // When a user sends another user a domain to connect to, and http is added wrongly, // we do our best to remove it again. if (convertHttpUrls && ( url.scheme() == QLatin1String("http") || url.scheme() == QLatin1String("https"))) { url.setScheme(QLatin1String("mumble")); } return fromUrl(url, p); } ServerItem *ServerItem::fromUrl(QUrl url, QWidget *p) { if (! url.isValid() || (url.scheme() != QLatin1String("mumble"))) { return NULL; } #if QT_VERSION >= 0x050000 QUrlQuery query(url); #endif if (url.userName().isEmpty()) { if (g.s.qsUsername.isEmpty()) { bool ok; QString defUserName = QInputDialog::getText(p, ConnectDialog::tr("Adding host %1").arg(url.host()), ConnectDialog::tr("Enter username"), QLineEdit::Normal, g.s.qsUsername, &ok).trimmed(); if (! ok) return NULL; if (defUserName.isEmpty()) return NULL; g.s.qsUsername = defUserName; } url.setUserName(g.s.qsUsername); } #if QT_VERSION >= 0x050000 ServerItem *si = new ServerItem(query.queryItemValue(QLatin1String("title")), url.host(), static_cast<unsigned short>(url.port(DEFAULT_MUMBLE_PORT)), url.userName(), url.password()); if (query.hasQueryItem(QLatin1String("url"))) si->qsUrl = query.queryItemValue(QLatin1String("url")); #else ServerItem *si = new ServerItem(url.queryItemValue(QLatin1String("title")), url.host(), static_cast<unsigned short>(url.port(DEFAULT_MUMBLE_PORT)), url.userName(), url.password()); if (url.hasQueryItem(QLatin1String("url"))) si->qsUrl = url.queryItemValue(QLatin1String("url")); #endif return si; } QVariant ServerItem::data(int column, int role) const { if (bParent) { if (column == 0) { switch (role) { case Qt::DisplayRole: return qsName; case Qt::DecorationRole: if (itType == FavoriteType) return loadIcon(QLatin1String("skin:emblems/emblem-favorite.svg")); else if (itType == LANType) return loadIcon(QLatin1String("skin:places/network-workgroup.svg")); else if (! qsCountryCode.isEmpty()) { QString flag = QString::fromLatin1(":/flags/%1.svg").arg(qsCountryCode); if (!QFileInfo(flag).exists()) { flag = QLatin1String("skin:categories/applications-internet.svg"); } return loadIcon(flag); } else return loadIcon(QLatin1String("skin:categories/applications-internet.svg")); } } } else { if (role == Qt::DisplayRole) { switch (column) { case 0: return qsName; case 1: return (dPing > 0.0) ? QString::number(uiPing) : QVariant(); case 2: return uiUsers ? QString::fromLatin1("%1/%2 ").arg(uiUsers).arg(uiMaxUsers) : QVariant(); } } else if (role == Qt::ToolTipRole) { QStringList qsl; foreach(const ServerAddress &addr, qlAddresses) { qsl << Qt::escape(addr.host.toString() + QLatin1String(":") + QString::number(static_cast<unsigned long>(addr.port))); } double ploss = 100.0; if (uiSent > 0) ploss = (uiSent - qMin(uiRecv, uiSent)) * 100. / uiSent; QString qs; qs += QLatin1String("<table>") + QString::fromLatin1("<tr><th align=left>%1</th><td>%2</td></tr>").arg(ConnectDialog::tr("Servername"), Qt::escape(qsName)) + QString::fromLatin1("<tr><th align=left>%1</th><td>%2</td></tr>").arg(ConnectDialog::tr("Hostname"), Qt::escape(qsHostname)); if (! qsBonjourHost.isEmpty()) qs += QString::fromLatin1("<tr><th align=left>%1</th><td>%2</td></tr>").arg(ConnectDialog::tr("Bonjour name"), Qt::escape(qsBonjourHost)); qs += QString::fromLatin1("<tr><th align=left>%1</th><td>%2</td></tr>").arg(ConnectDialog::tr("Port")).arg(usPort) + QString::fromLatin1("<tr><th align=left>%1</th><td>%2</td></tr>").arg(ConnectDialog::tr("Addresses"), qsl.join(QLatin1String(", "))); if (! qsUrl.isEmpty()) qs += QString::fromLatin1("<tr><th align=left>%1</th><td>%2</td></tr>").arg(ConnectDialog::tr("Website"), Qt::escape(qsUrl)); if (uiSent > 0) { qs += QString::fromLatin1("<tr><th align=left>%1</th><td>%2</td></tr>").arg(ConnectDialog::tr("Packet loss"), QString::fromLatin1("%1% (%2/%3)").arg(ploss, 0, 'f', 1).arg(uiRecv).arg(uiSent)); if (uiRecv > 0) { qs += QString::fromLatin1("<tr><th align=left>%1</th><td>%2</td></tr>").arg(ConnectDialog::tr("Ping (80%)"), ConnectDialog::tr("%1 ms"). arg(boost::accumulators::extended_p_square(* asQuantile)[1] / 1000., 0, 'f', 2)) + QString::fromLatin1("<tr><th align=left>%1</th><td>%2</td></tr>").arg(ConnectDialog::tr("Ping (95%)"), ConnectDialog::tr("%1 ms"). arg(boost::accumulators::extended_p_square(* asQuantile)[2] / 1000., 0, 'f', 2)) + QString::fromLatin1("<tr><th align=left>%1</th><td>%2</td></tr>").arg(ConnectDialog::tr("Bandwidth"), ConnectDialog::tr("%1 kbit/s").arg(uiBandwidth / 1000)) + QString::fromLatin1("<tr><th align=left>%1</th><td>%2</td></tr>").arg(ConnectDialog::tr("Users"), QString::fromLatin1("%1/%2").arg(uiUsers).arg(uiMaxUsers)) + QString::fromLatin1("<tr><th align=left>%1</th><td>%2</td></tr>").arg(ConnectDialog::tr("Version")).arg(MumbleVersion::toString(uiVersion)); } } qs += QLatin1String("</table>"); return qs; } else if (role == Qt::BackgroundRole) { if (bCA) { QColor qc(Qt::green); qc.setAlpha(32); return qc; } } } return QTreeWidgetItem::data(column, role); } void ServerItem::addServerItem(ServerItem *childitem) { Q_ASSERT(childitem->siParent == NULL); childitem->siParent = this; qlChildren.append(childitem); childitem->hideCheck(); if (bParent && (itType != PublicType) && isHidden()) setHidden(false); } // If all child items are hidden, there is no child indicator, regardless of policy, so we have to add/remove instead. void ServerItem::hideCheck() { bool hide = false; bool ishidden = (parent() == NULL); if (! bParent && (itType == PublicType)) { if (g.s.ssFilter == Settings::ShowReachable) hide = (dPing == 0.0); else if (g.s.ssFilter == Settings::ShowPopulated) hide = (uiUsers == 0); } if (hide != ishidden) { if (hide) siParent->removeChild(this); else siParent->addChild(this); } } void ServerItem::setDatas(double elapsed, quint32 users, quint32 maxusers) { if (elapsed == 0.0) { emitDataChanged(); return; } (*asQuantile)(static_cast<double>(elapsed)); dPing = boost::accumulators::extended_p_square(*asQuantile)[0]; if (dPing == 0.0) dPing = elapsed; quint32 ping = static_cast<quint32>(lround(dPing / 1000.)); uiRecv = static_cast<quint32>(boost::accumulators::count(* asQuantile)); bool changed = (ping != uiPing) || (users != uiUsers) || (maxusers != uiMaxUsers); uiUsers = users; uiMaxUsers = maxusers; uiPing = ping; double grace = qMax(5000., 50. * uiPingSort); double diff = fabs(1000. * uiPingSort - dPing); if ((uiPingSort == 0) || ((uiSent >= 10) && (diff >= grace))) uiPingSort = ping; if (changed) emitDataChanged(); } FavoriteServer ServerItem::toFavoriteServer() const { FavoriteServer fs; fs.qsName = qsName; if (! qsBonjourHost.isEmpty()) fs.qsHostname = QLatin1Char('@') + qsBonjourHost; else fs.qsHostname = qsHostname; fs.usPort = usPort; fs.qsUsername = qsUsername; fs.qsPassword = qsPassword; fs.qsUrl = qsUrl; return fs; } /** * This function turns a ServerItem object into a QMimeData object holding a URL to the server. */ QMimeData *ServerItem::toMimeData() const { QMimeData *mime = ServerItem::toMimeData(qsName, qsHostname, usPort); if (itType == FavoriteType) mime->setData(QLatin1String("OriginatedInMumble"), QByteArray()); return mime; } /** * This function creates a QMimeData object containing a URL to the server at host and port. name is passed in the * query string as "title", which is used for adding a server to favorites. channel may be omitted, but if specified it * should be in the format of "/path/to/channel". */ QMimeData *ServerItem::toMimeData(const QString &name, const QString &host, unsigned short port, const QString &channel) { QUrl url; url.setScheme(QLatin1String("mumble")); url.setHost(host); if (port != DEFAULT_MUMBLE_PORT) url.setPort(port); url.setPath(channel); #if QT_VERSION >= 0x050000 QUrlQuery query; query.addQueryItem(QLatin1String("title"), name); query.addQueryItem(QLatin1String("version"), QLatin1String("1.2.0")); url.setQuery(query); #else url.addQueryItem(QLatin1String("title"), name); url.addQueryItem(QLatin1String("version"), QLatin1String("1.2.0")); #endif QString qs = QLatin1String(url.toEncoded()); QMimeData *mime = new QMimeData; #ifdef Q_OS_WIN QString contents = QString::fromLatin1("[InternetShortcut]\r\nURL=%1\r\n").arg(qs); QString urlname = QString::fromLatin1("%1.url").arg(name); FILEGROUPDESCRIPTORA fgda; ZeroMemory(&fgda, sizeof(fgda)); fgda.cItems = 1; fgda.fgd[0].dwFlags = FD_LINKUI | FD_FILESIZE; fgda.fgd[0].nFileSizeLow=contents.length(); strcpy_s(fgda.fgd[0].cFileName, MAX_PATH, urlname.toLocal8Bit().constData()); mime->setData(QLatin1String("FileGroupDescriptor"), QByteArray(reinterpret_cast<const char *>(&fgda), sizeof(fgda))); FILEGROUPDESCRIPTORW fgdw; ZeroMemory(&fgdw, sizeof(fgdw)); fgdw.cItems = 1; fgdw.fgd[0].dwFlags = FD_LINKUI | FD_FILESIZE; fgdw.fgd[0].nFileSizeLow=contents.length(); wcscpy_s(fgdw.fgd[0].cFileName, MAX_PATH, urlname.toStdWString().c_str()); mime->setData(QLatin1String("FileGroupDescriptorW"), QByteArray(reinterpret_cast<const char *>(&fgdw), sizeof(fgdw))); mime->setData(QString::fromWCharArray(CFSTR_FILECONTENTS), contents.toLocal8Bit()); DWORD context[4]; context[0] = 0; context[1] = 1; context[2] = 0; context[3] = 0; mime->setData(QLatin1String("DragContext"), QByteArray(reinterpret_cast<const char *>(&context[0]), sizeof(context))); DWORD dropaction; dropaction = DROPEFFECT_LINK; mime->setData(QString::fromWCharArray(CFSTR_PREFERREDDROPEFFECT), QByteArray(reinterpret_cast<const char *>(&dropaction), sizeof(dropaction))); #endif QList<QUrl> urls; urls << url; mime->setUrls(urls); mime->setText(qs); mime->setHtml(QString::fromLatin1("<a href=\"%1\">%2</a>").arg(qs).arg(Qt::escape(name))); return mime; } bool ServerItem::operator <(const QTreeWidgetItem &o) const { const ServerItem &other = static_cast<const ServerItem &>(o); const QTreeWidget *w = treeWidget(); const int column = w ? w->sortColumn() : 0; if (itType != other.itType) { const bool inverse = w ? (w->header()->sortIndicatorOrder() == Qt::DescendingOrder) : false; bool less; if (itType == FavoriteType) less = true; else if ((itType == LANType) && (other.itType == PublicType)) less = true; else less = false; return less ^ inverse; } if (bParent) { const bool inverse = w ? (w->header()->sortIndicatorOrder() == Qt::DescendingOrder) : false; return (qsName < other.qsName) ^ inverse; } if (column == 0) { QString a = qsName.toLower(); QString b = other.qsName.toLower(); QRegExp re(QLatin1String("[^0-9a-z]")); a.remove(re); b.remove(re); return a < b; } else if (column == 1) { quint32 a = uiPingSort ? uiPingSort : UINT_MAX; quint32 b = other.uiPingSort ? other.uiPingSort : UINT_MAX; return a < b; } else if (column == 2) { return uiUsers < other.uiUsers; } return false; } QIcon ServerItem::loadIcon(const QString &name) { if (! qmIcons.contains(name)) qmIcons.insert(name, QIcon(name)); return qmIcons.value(name); } ConnectDialogEdit::ConnectDialogEdit(QWidget *p, const QString &name, const QString &host, const QString &user, unsigned short port, const QString &password) : QDialog(p) { setupUi(this); init(); bCustomLabel = ! name.simplified().isEmpty(); qleName->setText(name); qleServer->setText(host); qleUsername->setText(user); qlePort->setText(QString::number(port)); qlePassword->setText(password); validate(); } ConnectDialogEdit::ConnectDialogEdit(QWidget *parent) : QDialog(parent) { setupUi(this); setWindowTitle(tr("Add Server")); init(); if (!updateFromClipboard()) { // If connected to a server assume the user wants to add it if (g.sh && g.sh->isRunning()) { QString host, name, user, pw; unsigned short port = DEFAULT_MUMBLE_PORT; g.sh->getConnectionInfo(host, port, user, pw); Channel *c = Channel::get(0); if (c && c->qsName != QLatin1String("Root")) { name = c->qsName; } showNotice(tr("You are currently connected to a server.\nDo you want to fill the dialog with the connection data of this server?\nHost: %1 Port: %2").arg(host).arg(port)); m_si = new ServerItem(name, host, port, user, pw); } } qleUsername->setText(g.s.qsUsername); } void ConnectDialogEdit::init() { m_si = NULL; usPort = 0; bOk = true; bCustomLabel = false; qwInlineNotice->hide(); qlePort->setValidator(new QIntValidator(1, 65535, qlePort)); qlePort->setText(QString::number(DEFAULT_MUMBLE_PORT)); qlePassword->setEchoMode(QLineEdit::Password); connect(qleName, SIGNAL(textChanged(const QString &)), this, SLOT(validate())); connect(qleServer, SIGNAL(textChanged(const QString &)), this, SLOT(validate())); connect(qlePort, SIGNAL(textChanged(const QString &)), this, SLOT(validate())); connect(qleUsername, SIGNAL(textChanged(const QString &)), this, SLOT(validate())); connect(qlePassword, SIGNAL(textChanged(const QString &)), this, SLOT(validate())); validate(); } ConnectDialogEdit::~ConnectDialogEdit() { delete m_si; } void ConnectDialogEdit::showNotice(const QString &text) { QLabel *label = qwInlineNotice->findChild<QLabel *>(QLatin1String("qlPasteNotice")); Q_ASSERT(label); label->setText(text); qwInlineNotice->show(); adjustSize(); } bool ConnectDialogEdit::updateFromClipboard() { delete m_si; m_si = ServerItem::fromMimeData(QApplication::clipboard()->mimeData(), false, NULL, true); bool hasServerData = m_si != NULL; if (hasServerData) { showNotice(tr("You have an URL in your clipboard.\nDo you want to fill the dialog with this data?\nHost: %1 Port: %2").arg(m_si->qsHostname).arg(m_si->usPort)); return true; } else { qwInlineNotice->hide(); adjustSize(); return false; } } void ConnectDialogEdit::on_qbFill_clicked() { Q_ASSERT(m_si); qwInlineNotice->hide(); adjustSize(); qleName->setText(m_si->qsName); qleServer->setText(m_si->qsHostname); qleUsername->setText(m_si->qsUsername); qlePort->setText(QString::number(m_si->usPort)); qlePassword->setText(m_si->qsPassword); delete m_si; m_si = NULL; } void ConnectDialogEdit::on_qbDiscard_clicked() { qwInlineNotice->hide(); adjustSize(); } void ConnectDialogEdit::on_qleName_textEdited(const QString& name) { if (bCustomLabel) { // If empty, then reset to automatic label. // NOTE(nik@jnstw.us): You may be tempted to set qleName to qleServer, but that results in the odd // UI behavior that clearing the field doesn't clear it; it'll immediately equal qleServer. Instead, // leave it empty and let it update the next time qleServer updates. Code in accept will default it // to qleServer if it isn't updated beforehand. if (name.simplified().isEmpty()) { bCustomLabel = false; } } else { // If manually edited, set to Custom bCustomLabel = true; } } void ConnectDialogEdit::on_qleServer_textEdited(const QString& server) { // If using automatic label, update it if (!bCustomLabel) { qleName->setText(server); } } void ConnectDialogEdit::validate() { qsName = qleName->text().simplified(); qsHostname = qleServer->text().simplified(); usPort = qlePort->text().toUShort(); qsUsername = qleUsername->text().simplified(); qsPassword = qlePassword->text(); // For bonjour hosts disable the port field as it's auto-detected qlePort->setDisabled(!qsHostname.isEmpty() && qsHostname.startsWith(QLatin1Char('@'))); // For SuperUser show password edit if (qsUsername.toLower() == QLatin1String("superuser")) { qliPassword->setVisible(true); qlePassword->setVisible(true); qcbShowPassword->setVisible(true); adjustSize(); } else if (qsPassword.isEmpty()) { qliPassword->setVisible(false); qlePassword->setVisible(false); qcbShowPassword->setVisible(false); adjustSize(); } bOk = ! qsHostname.isEmpty() && ! qsUsername.isEmpty() && usPort; qdbbButtonBox->button(QDialogButtonBox::Ok)->setEnabled(bOk); } void ConnectDialogEdit::accept() { validate(); if (bOk) { QString server = qleServer->text().simplified(); // If the user accidentally added a schema or path part, drop it now. // We can't do so during editing as that is quite jarring. const int schemaPos = server.indexOf(QLatin1String("://")); if (schemaPos != -1) { server.remove(0, schemaPos + 3); } const int pathPos = server.indexOf(QLatin1Char('/')); if (pathPos != -1) { server.resize(pathPos); } qleServer->setText(server); if (qleName->text().simplified().isEmpty() || !bCustomLabel) { qleName->setText(server); } QDialog::accept(); } } void ConnectDialogEdit::on_qcbShowPassword_toggled(bool checked) { qlePassword->setEchoMode(checked ? QLineEdit::Normal : QLineEdit::Password); } ConnectDialog::ConnectDialog(QWidget *p, bool autoconnect) : QDialog(p), bAutoConnect(autoconnect) { setupUi(this); #ifdef Q_OS_MAC setWindowModality(Qt::WindowModal); #endif bPublicInit = false; siAutoConnect = NULL; bAllowPing = g.s.ptProxyType == Settings::NoProxy; bAllowHostLookup = g.s.ptProxyType == Settings::NoProxy; bAllowBonjour = g.s.ptProxyType == Settings::NoProxy; bAllowFilters = g.s.ptProxyType == Settings::NoProxy; if (tPublicServers.elapsed() >= 60 * 24 * 1000000ULL) { qlPublicServers.clear(); } qdbbButtonBox->button(QDialogButtonBox::Ok)->setEnabled(false); qdbbButtonBox->button(QDialogButtonBox::Ok)->setText(tr("&Connect")); QPushButton *qpbAdd = new QPushButton(tr("&Add New..."), this); qpbAdd->setDefault(false); qpbAdd->setAutoDefault(false); connect(qpbAdd, SIGNAL(clicked()), qaFavoriteAddNew, SIGNAL(triggered())); qdbbButtonBox->addButton(qpbAdd, QDialogButtonBox::ActionRole); qpbEdit = new QPushButton(tr("&Edit..."), this); qpbEdit->setEnabled(false); qpbEdit->setDefault(false); qpbEdit->setAutoDefault(false); connect(qpbEdit, SIGNAL(clicked()), qaFavoriteEdit, SIGNAL(triggered())); qdbbButtonBox->addButton(qpbEdit, QDialogButtonBox::ActionRole); qpbAdd->setHidden(g.s.disableConnectDialogEditing); qpbEdit->setHidden(g.s.disableConnectDialogEditing); qtwServers->setItemDelegate(new ServerViewDelegate()); // Hide ping and user count if we are not allowed to ping. if (!bAllowPing) { qtwServers->setColumnCount(1); } qtwServers->sortItems(1, Qt::AscendingOrder); #if QT_VERSION >= 0x050000 qtwServers->header()->setSectionResizeMode(0, QHeaderView::Stretch); if (qtwServers->columnCount() >= 2) { qtwServers->header()->setSectionResizeMode(1, QHeaderView::ResizeToContents); } if (qtwServers->columnCount() >= 3) { qtwServers->header()->setSectionResizeMode(2, QHeaderView::ResizeToContents); } #else qtwServers->header()->setResizeMode(0, QHeaderView::Stretch); if (qtwServers->columnCount() >= 2) { qtwServers->header()->setResizeMode(1, QHeaderView::ResizeToContents); } if (qtwServers->columnCount() >= 3) { qtwServers->header()->setResizeMode(2, QHeaderView::ResizeToContents); } #endif connect(qtwServers->header(), SIGNAL(sortIndicatorChanged(int, Qt::SortOrder)), this, SLOT(OnSortChanged(int, Qt::SortOrder))); qaShowAll->setChecked(false); qaShowReachable->setChecked(false); qaShowPopulated->setChecked(false); if (bAllowFilters) { switch (g.s.ssFilter) { case Settings::ShowPopulated: qaShowPopulated->setChecked(true); break; case Settings::ShowReachable: qaShowReachable->setChecked(true); break; default: qaShowAll->setChecked(true); break; } } else { qaShowAll->setChecked(true); } qagFilters = new QActionGroup(this); qagFilters->addAction(qaShowAll); qagFilters->addAction(qaShowReachable); qagFilters->addAction(qaShowPopulated); connect(qagFilters, SIGNAL(triggered(QAction *)), this, SLOT(onFiltersTriggered(QAction *))); qmPopup = new QMenu(this); qmFilters = new QMenu(tr("&Filters"), this); qmFilters->addAction(qaShowAll); qmFilters->addAction(qaShowReachable); qmFilters->addAction(qaShowPopulated); if (!bAllowFilters) { qmFilters->setEnabled(false); } QList<QTreeWidgetItem *> ql; QList<FavoriteServer> favorites = g.db->getFavorites(); foreach(const FavoriteServer &fs, favorites) { ServerItem *si = new ServerItem(fs); qlItems << si; startDns(si); qtwServers->siFavorite->addServerItem(si); } #ifdef USE_BONJOUR // Make sure the we got the objects we need, then wire them up if (bAllowBonjour && g.bc->bsbBrowser && g.bc->bsrResolver) { connect(g.bc->bsbBrowser, SIGNAL(error(DNSServiceErrorType)), this, SLOT(onLanBrowseError(DNSServiceErrorType))); connect(g.bc->bsbBrowser, SIGNAL(currentBonjourRecordsChanged(const QList<BonjourRecord> &)), this, SLOT(onUpdateLanList(const QList<BonjourRecord> &))); connect(g.bc->bsrResolver, SIGNAL(error(BonjourRecord, DNSServiceErrorType)), this, SLOT(onLanResolveError(BonjourRecord, DNSServiceErrorType))); connect(g.bc->bsrResolver, SIGNAL(bonjourRecordResolved(BonjourRecord, QString, int)), this, SLOT(onResolved(BonjourRecord, QString, int))); onUpdateLanList(g.bc->bsbBrowser->currentRecords()); } #endif qtPingTick = new QTimer(this); connect(qtPingTick, SIGNAL(timeout()), this, SLOT(timeTick())); qusSocket4 = new QUdpSocket(this); qusSocket6 = new QUdpSocket(this); bIPv4 = qusSocket4->bind(QHostAddress(QHostAddress::Any), 0); bIPv6 = qusSocket6->bind(QHostAddress(QHostAddress::AnyIPv6), 0); connect(qusSocket4, SIGNAL(readyRead()), this, SLOT(udpReply())); connect(qusSocket6, SIGNAL(readyRead()), this, SLOT(udpReply())); if (qtwServers->siFavorite->isHidden() && (!qtwServers->siLAN || qtwServers->siLAN->isHidden()) && qtwServers->siPublic != NULL) { qtwServers->siPublic->setExpanded(true); } iPingIndex = -1; qtPingTick->start(50); new QShortcut(QKeySequence(QKeySequence::Copy), this, SLOT(on_qaFavoriteCopy_triggered())); new QShortcut(QKeySequence(QKeySequence::Paste), this, SLOT(on_qaFavoritePaste_triggered())); qtwServers->setCurrentItem(NULL); bLastFound = false; qmPingCache = g.db->getPingCache(); if (! g.s.qbaConnectDialogGeometry.isEmpty()) restoreGeometry(g.s.qbaConnectDialogGeometry); if (! g.s.qbaConnectDialogHeader.isEmpty()) qtwServers->header()->restoreState(g.s.qbaConnectDialogHeader); } ConnectDialog::~ConnectDialog() { ServerItem::qmIcons.clear(); QList<FavoriteServer> ql; qmPingCache.clear(); foreach(ServerItem *si, qlItems) { if (si->uiPing) qmPingCache.insert(UnresolvedServerAddress(si->qsHostname, si->usPort), si->uiPing); if (si->itType != ServerItem::FavoriteType) continue; ql << si->toFavoriteServer(); } g.db->setFavorites(ql); g.db->setPingCache(qmPingCache); g.s.qbaConnectDialogHeader = qtwServers->header()->saveState(); g.s.qbaConnectDialogGeometry = saveGeometry(); } void ConnectDialog::accept() { ServerItem *si = static_cast<ServerItem *>(qtwServers->currentItem()); if (! si || (bAllowHostLookup && si->qlAddresses.isEmpty()) || si->qsHostname.isEmpty()) { qWarning() << "Invalid server"; return; } qsPassword = si->qsPassword; qsServer = si->qsHostname; usPort = si->usPort; if (si->qsUsername.isEmpty()) { bool ok; QString defUserName = QInputDialog::getText(this, tr("Connecting to %1").arg(si->qsName), tr("Enter username"), QLineEdit::Normal, g.s.qsUsername, &ok).trimmed(); if (! ok) return; g.s.qsUsername = si->qsUsername = defUserName; } qsUsername = si->qsUsername; g.s.qsLastServer = si->qsName; QDialog::accept(); } void ConnectDialog::OnSortChanged(int logicalIndex, Qt::SortOrder) { if (logicalIndex != 2) { return; } foreach(ServerItem *si, qlItems) { if (si->uiPing && (si->uiPing != si->uiPingSort)) { si->uiPingSort = si->uiPing; si->setDatas(); } } } void ConnectDialog::on_qaFavoriteAdd_triggered() { ServerItem *si = static_cast<ServerItem *>(qtwServers->currentItem()); if (! si || (si->itType == ServerItem::FavoriteType)) return; si = new ServerItem(si); qtwServers->fixupName(si); qlItems << si; qtwServers->siFavorite->addServerItem(si); qtwServers->setCurrentItem(si); startDns(si); } void ConnectDialog::on_qaFavoriteAddNew_triggered() { ConnectDialogEdit *cde = new ConnectDialogEdit(this); if (cde->exec() == QDialog::Accepted) { ServerItem *si = new ServerItem(cde->qsName, cde->qsHostname, cde->usPort, cde->qsUsername, cde->qsPassword); qlItems << si; qtwServers->siFavorite->addServerItem(si); qtwServers->setCurrentItem(si); startDns(si); } delete cde; } void ConnectDialog::on_qaFavoriteEdit_triggered() { ServerItem *si = static_cast<ServerItem *>(qtwServers->currentItem()); if (! si || (si->itType != ServerItem::FavoriteType)) return; QString host; if (! si->qsBonjourHost.isEmpty()) host = QLatin1Char('@') + si->qsBonjourHost; else host = si->qsHostname; ConnectDialogEdit *cde = new ConnectDialogEdit(this, si->qsName, host, si->qsUsername, si->usPort, si->qsPassword); if (cde->exec() == QDialog::Accepted) { si->qsName = cde->qsName; si->qsUsername = cde->qsUsername; si->qsPassword = cde->qsPassword; if ((cde->qsHostname != host) || (cde->usPort != si->usPort)) { stopDns(si); si->qlAddresses.clear(); si->reset(); si->usPort = cde->usPort; if (cde->qsHostname.startsWith(QLatin1Char('@'))) { si->qsHostname = QString(); si->qsBonjourHost = cde->qsHostname.mid(1); si->brRecord = BonjourRecord(si->qsBonjourHost, QLatin1String("_mumble._tcp."), QLatin1String("local.")); } else { si->qsHostname = cde->qsHostname; si->qsBonjourHost = QString(); si->brRecord = BonjourRecord(); } startDns(si); } si->setDatas(); } delete cde; } void ConnectDialog::on_qaFavoriteRemove_triggered() { ServerItem *si = static_cast<ServerItem *>(qtwServers->currentItem()); if (! si || (si->itType != ServerItem::FavoriteType)) return; stopDns(si); qlItems.removeAll(si); delete si; } void ConnectDialog::on_qaFavoriteCopy_triggered() { ServerItem *si = static_cast<ServerItem *>(qtwServers->currentItem()); if (! si) return; QApplication::clipboard()->setMimeData(si->toMimeData()); } void ConnectDialog::on_qaFavoritePaste_triggered() { ServerItem *si = ServerItem::fromMimeData(QApplication::clipboard()->mimeData()); if (! si) return; qlItems << si; qtwServers->siFavorite->addServerItem(si); qtwServers->setCurrentItem(si); startDns(si); } void ConnectDialog::on_qaUrl_triggered() { auto *si = static_cast< const ServerItem * >(qtwServers->currentItem()); if (!si || si->qsUrl.isEmpty()) { return; } const QStringList allowedSchemes = { QLatin1String("http"), QLatin1String("https") }; const auto url = QUrl(si->qsUrl); if (allowedSchemes.contains(url.scheme())) { QDesktopServices::openUrl(url); } else { // Inform user that the requested URL has been blocked QMessageBox msgBox; msgBox.setText(QObject::tr("<b>Blocked URL scheme \"%1\"</b>").arg(url.scheme())); msgBox.setInformativeText(QObject::tr("The URL uses a scheme that has been blocked for security reasons.")); msgBox.setDetailedText(QObject::tr("Blocked URL: \"%1\"").arg(url.toString())); msgBox.setIcon(QMessageBox::Warning); msgBox.exec(); } } void ConnectDialog::onFiltersTriggered(QAction *act) { if (act == qaShowAll) g.s.ssFilter = Settings::ShowAll; else if (act == qaShowReachable) g.s.ssFilter = Settings::ShowReachable; else if (act == qaShowPopulated) g.s.ssFilter = Settings::ShowPopulated; foreach(ServerItem *si, qlItems) si->hideCheck(); } void ConnectDialog::on_qtwServers_customContextMenuRequested(const QPoint &mpos) { ServerItem *si = static_cast<ServerItem *>(qtwServers->itemAt(mpos)); qmPopup->clear(); if (si != NULL && si->bParent) { si = NULL; } if (si != NULL) { if (!g.s.disableConnectDialogEditing) { if (si->itType == ServerItem::FavoriteType) { qmPopup->addAction(qaFavoriteEdit); qmPopup->addAction(qaFavoriteRemove); } else { qmPopup->addAction(qaFavoriteAdd); } } if (!si->qsUrl.isEmpty()) { qmPopup->addAction(qaUrl); } } if (! qmPopup->isEmpty()) { qmPopup->addSeparator(); } qmPopup->addMenu(qmFilters); qmPopup->popup(qtwServers->viewport()->mapToGlobal(mpos), NULL); } void ConnectDialog::on_qtwServers_itemDoubleClicked(QTreeWidgetItem *item, int) { qtwServers->setCurrentItem(item); accept(); } void ConnectDialog::on_qtwServers_currentItemChanged(QTreeWidgetItem *item, QTreeWidgetItem *) { ServerItem *si = static_cast<ServerItem *>(item); if (si->siParent == qtwServers->siFavorite) { qpbEdit->setEnabled(true); } else { qpbEdit->setEnabled(false); } bool bOk = !si->qlAddresses.isEmpty(); if (!bAllowHostLookup) { bOk = true; } qdbbButtonBox->button(QDialogButtonBox::Ok)->setEnabled(bOk); bLastFound = true; } void ConnectDialog::on_qtwServers_itemExpanded(QTreeWidgetItem *item) { if (qtwServers->siPublic != NULL && item == qtwServers->siPublic) { initList(); fillList(); } ServerItem *p = static_cast<ServerItem *>(item); foreach(ServerItem *si, p->qlChildren) startDns(si); } void ConnectDialog::initList() { if (bPublicInit || (qlPublicServers.count() > 0)) return; bPublicInit = true; QUrl url; url.setPath(QLatin1String("/v1/list")); #if QT_VERSION >= 0x050000 QUrlQuery query; query.addQueryItem(QLatin1String("version"), QLatin1String(MUMTEXT(MUMBLE_VERSION_STRING))); url.setQuery(query); #else url.addQueryItem(QLatin1String("version"), QLatin1String(MUMTEXT(MUMBLE_VERSION_STRING))); #endif WebFetch::fetch(QLatin1String("publist"), url, this, SLOT(fetched(QByteArray,QUrl,QMap<QString,QString>))); } #ifdef USE_BONJOUR void ConnectDialog::onResolved(BonjourRecord record, QString host, int port) { qlBonjourActive.removeAll(record); foreach(ServerItem *si, qlItems) { if (si->brRecord == record) { unsigned short usport = static_cast<unsigned short>(port); if ((host != si->qsHostname) || (usport != si->usPort)) { stopDns(si); si->usPort = static_cast<unsigned short>(port); si->qsHostname = host; startDns(si); } } } } void ConnectDialog::onUpdateLanList(const QList<BonjourRecord> &list) { QSet<ServerItem *> items; QSet<ServerItem *> old = qtwServers->siLAN->qlChildren.toSet(); foreach(const BonjourRecord &record, list) { bool found = false; foreach(ServerItem *si, old) { if (si->brRecord == record) { items.insert(si); found = true; break; } } if (! found) { ServerItem *si = new ServerItem(record); qlItems << si; g.bc->bsrResolver->resolveBonjourRecord(record); startDns(si); qtwServers->siLAN->addServerItem(si); } } QSet<ServerItem *> remove = old.subtract(items); foreach(ServerItem *si, remove) { stopDns(si); qlItems.removeAll(si); delete si; } } void ConnectDialog::onLanBrowseError(DNSServiceErrorType err) { qWarning()<<"Bonjour reported browser error "<< err; } void ConnectDialog::onLanResolveError(BonjourRecord br, DNSServiceErrorType err) { qlBonjourActive.removeAll(br); qWarning()<<"Bonjour reported resolver error "<< err; } #endif void ConnectDialog::fillList() { QList<QTreeWidgetItem *> ql; QList<QTreeWidgetItem *> qlNew; foreach(const PublicInfo &pi, qlPublicServers) { bool found = false; foreach(ServerItem *si, qlItems) { if ((pi.qsIp == si->qsHostname) && (pi.usPort == si->usPort)) { si->qsCountry = pi.qsCountry; si->qsCountryCode = pi.qsCountryCode; si->qsContinentCode = pi.qsContinentCode; si->qsUrl = pi.quUrl.toString(); si->bCA = pi.bCA; si->setDatas(); if (si->itType == ServerItem::PublicType) found = true; } } if (! found) ql << new ServerItem(pi); } while (! ql.isEmpty()) { ServerItem *si = static_cast<ServerItem *>(ql.takeAt(qrand() % ql.count())); qlNew << si; qlItems << si; } foreach(QTreeWidgetItem *qtwi, qlNew) { ServerItem *si = static_cast<ServerItem *>(qtwi); ServerItem *p = qtwServers->getParent(si->qsContinentCode, si->qsCountryCode, si->qsCountry, qsUserContinentCode, qsUserCountryCode); p->addServerItem(si); if (p->isExpanded() && p->parent()->isExpanded()) startDns(si); } } void ConnectDialog::timeTick() { if (! bLastFound && ! g.s.qsLastServer.isEmpty()) { QList<QTreeWidgetItem *> items = qtwServers->findItems(g.s.qsLastServer, Qt::MatchExactly | Qt::MatchRecursive); if (!items.isEmpty()) { bLastFound = true; qtwServers->setCurrentItem(items.at(0)); if (g.s.bAutoConnect && bAutoConnect) { siAutoConnect = static_cast<ServerItem *>(items.at(0)); if (! siAutoConnect->qlAddresses.isEmpty()) { accept(); return; } else if (!bAllowHostLookup) { accept(); return; } } } } if (bAllowHostLookup) { // Start DNS Lookup of first unknown hostname foreach(const UnresolvedServerAddress &unresolved, qlDNSLookup) { if (qsDNSActive.contains(unresolved)) { continue; } qlDNSLookup.removeAll(unresolved); qlDNSLookup.append(unresolved); qsDNSActive.insert(unresolved); ServerResolver *sr = new ServerResolver(); QObject::connect(sr, SIGNAL(resolved()), this, SLOT(lookedUp())); sr->resolve(unresolved.hostname, unresolved.port); break; } } ServerItem *current = static_cast<ServerItem *>(qtwServers->currentItem()); ServerItem *hover = static_cast<ServerItem *>(qtwServers->itemAt(qtwServers->viewport()->mapFromGlobal(QCursor::pos()))); ServerItem *si = NULL; if (tCurrent.elapsed() >= 1000000ULL) si = current; if (! si && (tHover.elapsed() >= 1000000ULL)) si = hover; if (si) { QString hostname = si->qsHostname.toLower(); unsigned short port = si->usPort; UnresolvedServerAddress unresolved(hostname, port); if (si->qlAddresses.isEmpty()) { if (! hostname.isEmpty()) { qlDNSLookup.removeAll(unresolved); qlDNSLookup.prepend(unresolved); } si = NULL; } } if (!si) { if (qlItems.isEmpty()) return; bool expanded; do { ++iPingIndex; if (iPingIndex >= qlItems.count()) { if (tRestart.isElapsed(1000000ULL)) iPingIndex = 0; else return; } si = qlItems.at(iPingIndex); ServerItem *p = si->siParent; expanded = true; while (p && expanded) { expanded = expanded && p->isExpanded(); p = p->siParent; } } while (si->qlAddresses.isEmpty() || ! expanded); } if (si == current) tCurrent.restart(); if (si == hover) tHover.restart(); foreach(const ServerAddress &addr, si->qlAddresses) { sendPing(addr.host.toAddress(), addr.port); } } void ConnectDialog::startDns(ServerItem *si) { if (!bAllowHostLookup) { return; } QString hostname = si->qsHostname.toLower(); unsigned short port = si->usPort; UnresolvedServerAddress unresolved(hostname, port); if (si->qlAddresses.isEmpty()) { // Determine if qsHostname is an IP address // or a hostname. If it is an IP address, we // can treat it as resolved as-is. QHostAddress qha(si->qsHostname); bool hostnameIsIPAddress = !qha.isNull(); if (hostnameIsIPAddress) { si->qlAddresses.append(ServerAddress(HostAddress(qha), port)); } else { si->qlAddresses = qhDNSCache.value(unresolved); } } if (qtwServers->currentItem() == si) qdbbButtonBox->button(QDialogButtonBox::Ok)->setEnabled(! si->qlAddresses.isEmpty()); if (! si->qlAddresses.isEmpty()) { foreach(const ServerAddress &addr, si->qlAddresses) { qhPings[addr].insert(si); } return; } #ifdef USE_BONJOUR if (bAllowBonjour && si->qsHostname.isEmpty() && ! si->brRecord.serviceName.isEmpty()) { if (! qlBonjourActive.contains(si->brRecord)) { g.bc->bsrResolver->resolveBonjourRecord(si->brRecord); qlBonjourActive.append(si->brRecord); } return; } #endif if (! qhDNSWait.contains(unresolved)) { if (si->itType == ServerItem::PublicType) qlDNSLookup.append(unresolved); else qlDNSLookup.prepend(unresolved); } qhDNSWait[unresolved].insert(si); } void ConnectDialog::stopDns(ServerItem *si) { if (!bAllowHostLookup) { return; } foreach(const ServerAddress &addr, si->qlAddresses) { if (qhPings.contains(addr)) { qhPings[addr].remove(si); if (qhPings[addr].isEmpty()) { qhPings.remove(addr); qhPingRand.remove(addr); } } } QString hostname = si->qsHostname.toLower(); unsigned short port = si->usPort; UnresolvedServerAddress unresolved(hostname, port); if (qhDNSWait.contains(unresolved)) { qhDNSWait[unresolved].remove(si); if (qhDNSWait[unresolved].isEmpty()) { qhDNSWait.remove(unresolved); qlDNSLookup.removeAll(unresolved); } } } void ConnectDialog::lookedUp() { ServerResolver *sr = qobject_cast<ServerResolver *>(QObject::sender()); sr->deleteLater(); QString hostname = sr->hostname().toLower(); unsigned short port = sr->port(); UnresolvedServerAddress unresolved(hostname, port); qsDNSActive.remove(unresolved); // An error occurred, or no records were found. if (sr->records().size() == 0) { return; } QSet<ServerAddress> qs; foreach (ServerResolverRecord record, sr->records()) { foreach(const HostAddress &ha, record.addresses()) { qs.insert(ServerAddress(ha, record.port())); } } QSet<ServerItem *> waiting = qhDNSWait[unresolved]; foreach(ServerItem *si, waiting) { foreach (const ServerAddress &addr, qs) { qhPings[addr].insert(si); } si->qlAddresses = qs.toList(); } qlDNSLookup.removeAll(unresolved); qhDNSCache.insert(unresolved, qs.toList()); qhDNSWait.remove(unresolved); foreach(ServerItem *si, waiting) { if (si == qtwServers->currentItem()) { on_qtwServers_currentItemChanged(si, si); if (si == siAutoConnect) accept(); } } if (bAllowPing) { foreach(const ServerAddress &addr, qs) { sendPing(addr.host.toAddress(), addr.port); } } } void ConnectDialog::sendPing(const QHostAddress &host, unsigned short port) { char blob[16]; ServerAddress addr(HostAddress(host), port); quint64 uiRand; if (qhPingRand.contains(addr)) { uiRand = qhPingRand.value(addr); } else { uiRand = (static_cast<quint64>(qrand()) << 32) | static_cast<quint64>(qrand()); qhPingRand.insert(addr, uiRand); } memset(blob, 0, sizeof(blob)); * reinterpret_cast<quint64 *>(blob+8) = tPing.elapsed() ^ uiRand; if (bIPv4 && host.protocol() == QAbstractSocket::IPv4Protocol) qusSocket4->writeDatagram(blob+4, 12, host, port); else if (bIPv6 && host.protocol() == QAbstractSocket::IPv6Protocol) qusSocket6->writeDatagram(blob+4, 12, host, port); else return; const QSet<ServerItem *> &qs = qhPings.value(addr); foreach(ServerItem *si, qs) ++ si->uiSent; } void ConnectDialog::udpReply() { QUdpSocket *sock = qobject_cast<QUdpSocket *>(sender()); while (sock->hasPendingDatagrams()) { char blob[64]; QHostAddress host; unsigned short port; qint64 len = sock->readDatagram(blob+4, 24, &host, &port); if (len == 24) { if (host.scopeId() == QLatin1String("0")) host.setScopeId(QLatin1String("")); ServerAddress address(HostAddress(host), port); if (qhPings.contains(address)) { quint32 *ping = reinterpret_cast<quint32 *>(blob+4); quint64 *ts = reinterpret_cast<quint64 *>(blob+8); quint64 elapsed = tPing.elapsed() - (*ts ^ qhPingRand.value(address)); foreach(ServerItem *si, qhPings.value(address)) { si->uiVersion = qFromBigEndian(ping[0]); quint32 users = qFromBigEndian(ping[3]); quint32 maxusers = qFromBigEndian(ping[4]); si->uiBandwidth = qFromBigEndian(ping[5]); if (! si->uiPingSort) si->uiPingSort = qmPingCache.value(UnresolvedServerAddress(si->qsHostname, si->usPort)); si->setDatas(static_cast<double>(elapsed), users, maxusers); si->hideCheck(); } } } } } void ConnectDialog::fetched(QByteArray xmlData, QUrl, QMap<QString, QString> headers) { if (xmlData.isNull()) { QMessageBox::warning(this, QLatin1String("Mumble"), tr("Failed to fetch server list"), QMessageBox::Ok); return; } QDomDocument doc; doc.setContent(xmlData); qlPublicServers.clear(); qsUserCountry = headers.value(QLatin1String("Geo-Country")); qsUserCountryCode = headers.value(QLatin1String("Geo-Country-Code")).toLower(); qsUserContinentCode = headers.value(QLatin1String("Geo-Continent-Code")).toLower(); QDomElement root=doc.documentElement(); QDomNode n = root.firstChild(); while (!n.isNull()) { QDomElement e = n.toElement(); if (!e.isNull()) { if (e.tagName() == QLatin1String("server")) { PublicInfo pi; pi.qsName = e.attribute(QLatin1String("name")); pi.quUrl = e.attribute(QLatin1String("url")); pi.qsIp = e.attribute(QLatin1String("ip")); pi.usPort = e.attribute(QLatin1String("port")).toUShort(); pi.qsCountry = e.attribute(QLatin1String("country"), tr("Unknown")); pi.qsCountryCode = e.attribute(QLatin1String("country_code")).toLower(); pi.qsContinentCode = e.attribute(QLatin1String("continent_code")).toLower(); pi.bCA = e.attribute(QLatin1String("ca")).toInt() ? true : false; qlPublicServers << pi; } } n = n.nextSibling(); } tPublicServers.restart(); fillList(); }
./CrossVul/dataset_final_sorted/CWE-59/cpp/good_1993_0
crossvul-cpp_data_bad_1993_0
// Copyright 2005-2019 The Mumble Developers. All rights reserved. // Use of this source code is governed by a BSD-style license // that can be found in the LICENSE file at the root of the // Mumble source tree or at <https://www.mumble.info/LICENSE>. #include "mumble_pch.hpp" #include "ConnectDialog.h" #ifdef USE_BONJOUR #include "BonjourClient.h" #include "BonjourServiceBrowser.h" #include "BonjourServiceResolver.h" #endif #include "Channel.h" #include "Database.h" #include "ServerHandler.h" #include "WebFetch.h" #include "ServerResolver.h" // We define a global macro called 'g'. This can lead to issues when included code uses 'g' as a type or parameter name (like protobuf 3.7 does). As such, for now, we have to make this our last include. #include "Global.h" QMap<QString, QIcon> ServerItem::qmIcons; QList<PublicInfo> ConnectDialog::qlPublicServers; QString ConnectDialog::qsUserCountry, ConnectDialog::qsUserCountryCode, ConnectDialog::qsUserContinentCode; Timer ConnectDialog::tPublicServers; PingStats::PingStats() { init(); } PingStats::~PingStats() { delete asQuantile; } void PingStats::init() { boost::array<double, 3> probs = {{0.75, 0.80, 0.95 }}; asQuantile = new asQuantileType(boost::accumulators::tag::extended_p_square::probabilities = probs); dPing = 0.0; uiPing = 0; uiPingSort = 0; uiUsers = 0; uiMaxUsers = 0; uiBandwidth = 0; uiSent = 0; uiRecv = 0; uiVersion = 0; } void PingStats::reset() { delete asQuantile; init(); } ServerViewDelegate::ServerViewDelegate(QObject *p) : QStyledItemDelegate(p) { } ServerViewDelegate::~ServerViewDelegate() { } void ServerViewDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { // Allow a ServerItem's BackgroundRole to override the current theme's default color. QVariant bg = index.data(Qt::BackgroundRole); if (bg.isValid()) { painter->fillRect(option.rect, bg.value<QBrush>()); } QStyledItemDelegate::paint(painter, option, index); } ServerView::ServerView(QWidget *p) : QTreeWidget(p) { siFavorite = new ServerItem(tr("Favorite"), ServerItem::FavoriteType); addTopLevelItem(siFavorite); siFavorite->setExpanded(true); siFavorite->setHidden(true); #ifdef USE_BONJOUR siLAN = new ServerItem(tr("LAN"), ServerItem::LANType); addTopLevelItem(siLAN); siLAN->setExpanded(true); siLAN->setHidden(true); #else siLAN = NULL; #endif if (!g.s.disablePublicList) { siPublic = new ServerItem(tr("Public Internet"), ServerItem::PublicType); siPublic->setChildIndicatorPolicy(QTreeWidgetItem::ShowIndicator); addTopLevelItem(siPublic); siPublic->setExpanded(false); // The continent code is empty when the server's IP address is not in the GeoIP database qmContinentNames.insert(QLatin1String(""), tr("Unknown")); qmContinentNames.insert(QLatin1String("af"), tr("Africa")); qmContinentNames.insert(QLatin1String("as"), tr("Asia")); qmContinentNames.insert(QLatin1String("na"), tr("North America")); qmContinentNames.insert(QLatin1String("sa"), tr("South America")); qmContinentNames.insert(QLatin1String("eu"), tr("Europe")); qmContinentNames.insert(QLatin1String("oc"), tr("Oceania")); } else { qWarning()<< "Public list disabled"; siPublic = NULL; } } ServerView::~ServerView() { delete siFavorite; delete siLAN; delete siPublic; } QMimeData *ServerView::mimeData(const QList<QTreeWidgetItem *> mimeitems) const { if (mimeitems.isEmpty()) return NULL; ServerItem *si = static_cast<ServerItem *>(mimeitems.first()); return si->toMimeData(); } QStringList ServerView::mimeTypes() const { QStringList qsl; qsl << QStringList(QLatin1String("text/uri-list")); qsl << QStringList(QLatin1String("text/plain")); return qsl; } Qt::DropActions ServerView::supportedDropActions() const { return Qt::CopyAction | Qt::LinkAction; } /* Extract and append (2), (3) etc to the end of a servers name if it is cloned. */ void ServerView::fixupName(ServerItem *si) { QString name = si->qsName; int tag = 1; QRegExp tmatch(QLatin1String("(.+)\\((\\d+)\\)")); tmatch.setMinimal(true); if (tmatch.exactMatch(name)) { name = tmatch.capturedTexts().at(1).trimmed(); tag = tmatch.capturedTexts().at(2).toInt(); } bool found; QString cmpname; do { found = false; if (tag > 1) cmpname = name + QString::fromLatin1(" (%1)").arg(tag); else cmpname = name; foreach(ServerItem *f, siFavorite->qlChildren) if (f->qsName == cmpname) found = true; ++tag; } while (found); si->qsName = cmpname; } bool ServerView::dropMimeData(QTreeWidgetItem *, int, const QMimeData *mime, Qt::DropAction) { ServerItem *si = ServerItem::fromMimeData(mime); if (! si) return false; fixupName(si); qobject_cast<ConnectDialog *>(parent())->qlItems << si; siFavorite->addServerItem(si); qobject_cast<ConnectDialog *>(parent())->startDns(si); setCurrentItem(si); return true; } ServerItem *ServerView::getParent(const QString &continentcode, const QString &countrycode, const QString &countryname, const QString &usercontinent, const QString &usercountry) { ServerItem *continent = qmContinent.value(continentcode); if (!continent) { QString name = qmContinentNames.value(continentcode); if (name.isEmpty()) name = continentcode; continent = new ServerItem(name, ServerItem::PublicType, continentcode); qmContinent.insert(continentcode, continent); siPublic->addServerItem(continent); if (!continentcode.isEmpty()) { if (continentcode == usercontinent) { continent->setExpanded(true); scrollToItem(continent, QAbstractItemView::PositionAtTop); } } else { continent->setChildIndicatorPolicy(QTreeWidgetItem::ShowIndicator); } } // If the continent code is empty, we put the server directly into the "Unknown" continent if (continentcode.isEmpty()) { return continent; } ServerItem *country = qmCountry.value(countrycode); if (!country) { country = new ServerItem(countryname, ServerItem::PublicType, continentcode, countrycode); qmCountry.insert(countrycode, country); country->setChildIndicatorPolicy(QTreeWidgetItem::ShowIndicator); continent->addServerItem(country); if (!countrycode.isEmpty() && countrycode == usercountry) { country->setExpanded(true); scrollToItem(country, QAbstractItemView::PositionAtTop); } } return country; } void ServerItem::init() { // Without this, columncount is wrong. setData(0, Qt::DisplayRole, QVariant()); setData(1, Qt::DisplayRole, QVariant()); setData(2, Qt::DisplayRole, QVariant()); emitDataChanged(); } ServerItem::ServerItem(const FavoriteServer &fs) : QTreeWidgetItem(QTreeWidgetItem::UserType) { siParent = NULL; bParent = false; itType = FavoriteType; qsName = fs.qsName; usPort = fs.usPort; qsUsername = fs.qsUsername; qsPassword = fs.qsPassword; qsUrl = fs.qsUrl; bCA = false; if (fs.qsHostname.startsWith(QLatin1Char('@'))) { qsBonjourHost = fs.qsHostname.mid(1); brRecord = BonjourRecord(qsBonjourHost, QLatin1String("_mumble._tcp."), QLatin1String("local.")); } else { qsHostname = fs.qsHostname; } init(); } ServerItem::ServerItem(const PublicInfo &pi) : QTreeWidgetItem(QTreeWidgetItem::UserType) { siParent = NULL; bParent = false; itType = PublicType; qsName = pi.qsName; qsHostname = pi.qsIp; usPort = pi.usPort; qsUrl = pi.quUrl.toString(); qsCountry = pi.qsCountry; qsCountryCode = pi.qsCountryCode; qsContinentCode = pi.qsContinentCode; bCA = pi.bCA; init(); } ServerItem::ServerItem(const QString &name, const QString &host, unsigned short port, const QString &username, const QString &password) : QTreeWidgetItem(QTreeWidgetItem::UserType) { siParent = NULL; bParent = false; itType = FavoriteType; qsName = name; usPort = port; qsUsername = username; qsPassword = password; bCA = false; if (host.startsWith(QLatin1Char('@'))) { qsBonjourHost = host.mid(1); brRecord = BonjourRecord(qsBonjourHost, QLatin1String("_mumble._tcp."), QLatin1String("local.")); } else { qsHostname = host; } init(); } ServerItem::ServerItem(const BonjourRecord &br) : QTreeWidgetItem(QTreeWidgetItem::UserType) { siParent = NULL; bParent = false; itType = LANType; qsName = br.serviceName; qsBonjourHost = qsName; brRecord = br; usPort = 0; bCA = false; init(); } ServerItem::ServerItem(const QString &name, ItemType itype, const QString &continent, const QString &country) { siParent = NULL; bParent = true; qsName = name; itType = itype; if (itType == PublicType) { qsCountryCode = country; qsContinentCode = continent; } setFlags(flags() & ~Qt::ItemIsDragEnabled); bCA = false; init(); } ServerItem::ServerItem(const ServerItem *si) { siParent = NULL; bParent = false; itType = FavoriteType; qsName = si->qsName; qsHostname = si->qsHostname; usPort = si->usPort; qsUsername = si->qsUsername; qsPassword = si->qsPassword; qsCountry = si->qsCountry; qsCountryCode = si->qsCountryCode; qsContinentCode = si->qsContinentCode; qsUrl = si->qsUrl; qsBonjourHost = si->qsBonjourHost; brRecord = si->brRecord; qlAddresses = si->qlAddresses; bCA = si->bCA; uiVersion = si->uiVersion; uiPing = si->uiPing; uiPingSort = si->uiPing; uiUsers = si->uiUsers; uiMaxUsers = si->uiMaxUsers; uiBandwidth = si->uiBandwidth; uiSent = si->uiSent; dPing = si->dPing; *asQuantile = * si->asQuantile; } ServerItem::~ServerItem() { if (siParent) { siParent->qlChildren.removeAll(this); if (siParent->bParent && siParent->qlChildren.isEmpty()) siParent->setHidden(true); } // This is just for cleanup when exiting the dialog, it won't stop pending DNS for the children. foreach(ServerItem *si, qlChildren) delete si; } ServerItem *ServerItem::fromMimeData(const QMimeData *mime, bool default_name, QWidget *p, bool convertHttpUrls) { if (mime->hasFormat(QLatin1String("OriginatedInMumble"))) return NULL; QUrl url; if (mime->hasUrls() && ! mime->urls().isEmpty()) url = mime->urls().at(0); else if (mime->hasText()) url = QUrl::fromEncoded(mime->text().toUtf8()); QString qsFile = url.toLocalFile(); if (! qsFile.isEmpty()) { QFile f(qsFile); // Make sure we don't accidently read something big the user // happened to have in his clipboard. We only want to look // at small link files. if (f.open(QIODevice::ReadOnly) && f.size() < 10240) { QByteArray qba = f.readAll(); f.close(); url = QUrl::fromEncoded(qba, QUrl::StrictMode); if (! url.isValid()) { // Windows internet shortcut files (.url) are an ini with an URL value QSettings qs(qsFile, QSettings::IniFormat); url = QUrl::fromEncoded(qs.value(QLatin1String("InternetShortcut/URL")).toByteArray(), QUrl::StrictMode); } } } if (default_name) { #if QT_VERSION >= 0x050000 QUrlQuery query(url); if (! query.hasQueryItem(QLatin1String("title"))) { query.addQueryItem(QLatin1String("title"), url.host()); } #else if (! url.hasQueryItem(QLatin1String("title"))) { url.addQueryItem(QLatin1String("title"), url.host()); } #endif } if (! url.isValid()) { return NULL; } // An URL from text without a scheme will have the hostname text // in the QUrl scheme and no hostname. We do not want to use that. if (url.host().isEmpty()) { return NULL; } // Some communication programs automatically create http links from domains. // When a user sends another user a domain to connect to, and http is added wrongly, // we do our best to remove it again. if (convertHttpUrls && ( url.scheme() == QLatin1String("http") || url.scheme() == QLatin1String("https"))) { url.setScheme(QLatin1String("mumble")); } return fromUrl(url, p); } ServerItem *ServerItem::fromUrl(QUrl url, QWidget *p) { if (! url.isValid() || (url.scheme() != QLatin1String("mumble"))) { return NULL; } #if QT_VERSION >= 0x050000 QUrlQuery query(url); #endif if (url.userName().isEmpty()) { if (g.s.qsUsername.isEmpty()) { bool ok; QString defUserName = QInputDialog::getText(p, ConnectDialog::tr("Adding host %1").arg(url.host()), ConnectDialog::tr("Enter username"), QLineEdit::Normal, g.s.qsUsername, &ok).trimmed(); if (! ok) return NULL; if (defUserName.isEmpty()) return NULL; g.s.qsUsername = defUserName; } url.setUserName(g.s.qsUsername); } #if QT_VERSION >= 0x050000 ServerItem *si = new ServerItem(query.queryItemValue(QLatin1String("title")), url.host(), static_cast<unsigned short>(url.port(DEFAULT_MUMBLE_PORT)), url.userName(), url.password()); if (query.hasQueryItem(QLatin1String("url"))) si->qsUrl = query.queryItemValue(QLatin1String("url")); #else ServerItem *si = new ServerItem(url.queryItemValue(QLatin1String("title")), url.host(), static_cast<unsigned short>(url.port(DEFAULT_MUMBLE_PORT)), url.userName(), url.password()); if (url.hasQueryItem(QLatin1String("url"))) si->qsUrl = url.queryItemValue(QLatin1String("url")); #endif return si; } QVariant ServerItem::data(int column, int role) const { if (bParent) { if (column == 0) { switch (role) { case Qt::DisplayRole: return qsName; case Qt::DecorationRole: if (itType == FavoriteType) return loadIcon(QLatin1String("skin:emblems/emblem-favorite.svg")); else if (itType == LANType) return loadIcon(QLatin1String("skin:places/network-workgroup.svg")); else if (! qsCountryCode.isEmpty()) { QString flag = QString::fromLatin1(":/flags/%1.svg").arg(qsCountryCode); if (!QFileInfo(flag).exists()) { flag = QLatin1String("skin:categories/applications-internet.svg"); } return loadIcon(flag); } else return loadIcon(QLatin1String("skin:categories/applications-internet.svg")); } } } else { if (role == Qt::DisplayRole) { switch (column) { case 0: return qsName; case 1: return (dPing > 0.0) ? QString::number(uiPing) : QVariant(); case 2: return uiUsers ? QString::fromLatin1("%1/%2 ").arg(uiUsers).arg(uiMaxUsers) : QVariant(); } } else if (role == Qt::ToolTipRole) { QStringList qsl; foreach(const ServerAddress &addr, qlAddresses) { qsl << Qt::escape(addr.host.toString() + QLatin1String(":") + QString::number(static_cast<unsigned long>(addr.port))); } double ploss = 100.0; if (uiSent > 0) ploss = (uiSent - qMin(uiRecv, uiSent)) * 100. / uiSent; QString qs; qs += QLatin1String("<table>") + QString::fromLatin1("<tr><th align=left>%1</th><td>%2</td></tr>").arg(ConnectDialog::tr("Servername"), Qt::escape(qsName)) + QString::fromLatin1("<tr><th align=left>%1</th><td>%2</td></tr>").arg(ConnectDialog::tr("Hostname"), Qt::escape(qsHostname)); if (! qsBonjourHost.isEmpty()) qs += QString::fromLatin1("<tr><th align=left>%1</th><td>%2</td></tr>").arg(ConnectDialog::tr("Bonjour name"), Qt::escape(qsBonjourHost)); qs += QString::fromLatin1("<tr><th align=left>%1</th><td>%2</td></tr>").arg(ConnectDialog::tr("Port")).arg(usPort) + QString::fromLatin1("<tr><th align=left>%1</th><td>%2</td></tr>").arg(ConnectDialog::tr("Addresses"), qsl.join(QLatin1String(", "))); if (! qsUrl.isEmpty()) qs += QString::fromLatin1("<tr><th align=left>%1</th><td>%2</td></tr>").arg(ConnectDialog::tr("Website"), Qt::escape(qsUrl)); if (uiSent > 0) { qs += QString::fromLatin1("<tr><th align=left>%1</th><td>%2</td></tr>").arg(ConnectDialog::tr("Packet loss"), QString::fromLatin1("%1% (%2/%3)").arg(ploss, 0, 'f', 1).arg(uiRecv).arg(uiSent)); if (uiRecv > 0) { qs += QString::fromLatin1("<tr><th align=left>%1</th><td>%2</td></tr>").arg(ConnectDialog::tr("Ping (80%)"), ConnectDialog::tr("%1 ms"). arg(boost::accumulators::extended_p_square(* asQuantile)[1] / 1000., 0, 'f', 2)) + QString::fromLatin1("<tr><th align=left>%1</th><td>%2</td></tr>").arg(ConnectDialog::tr("Ping (95%)"), ConnectDialog::tr("%1 ms"). arg(boost::accumulators::extended_p_square(* asQuantile)[2] / 1000., 0, 'f', 2)) + QString::fromLatin1("<tr><th align=left>%1</th><td>%2</td></tr>").arg(ConnectDialog::tr("Bandwidth"), ConnectDialog::tr("%1 kbit/s").arg(uiBandwidth / 1000)) + QString::fromLatin1("<tr><th align=left>%1</th><td>%2</td></tr>").arg(ConnectDialog::tr("Users"), QString::fromLatin1("%1/%2").arg(uiUsers).arg(uiMaxUsers)) + QString::fromLatin1("<tr><th align=left>%1</th><td>%2</td></tr>").arg(ConnectDialog::tr("Version")).arg(MumbleVersion::toString(uiVersion)); } } qs += QLatin1String("</table>"); return qs; } else if (role == Qt::BackgroundRole) { if (bCA) { QColor qc(Qt::green); qc.setAlpha(32); return qc; } } } return QTreeWidgetItem::data(column, role); } void ServerItem::addServerItem(ServerItem *childitem) { Q_ASSERT(childitem->siParent == NULL); childitem->siParent = this; qlChildren.append(childitem); childitem->hideCheck(); if (bParent && (itType != PublicType) && isHidden()) setHidden(false); } // If all child items are hidden, there is no child indicator, regardless of policy, so we have to add/remove instead. void ServerItem::hideCheck() { bool hide = false; bool ishidden = (parent() == NULL); if (! bParent && (itType == PublicType)) { if (g.s.ssFilter == Settings::ShowReachable) hide = (dPing == 0.0); else if (g.s.ssFilter == Settings::ShowPopulated) hide = (uiUsers == 0); } if (hide != ishidden) { if (hide) siParent->removeChild(this); else siParent->addChild(this); } } void ServerItem::setDatas(double elapsed, quint32 users, quint32 maxusers) { if (elapsed == 0.0) { emitDataChanged(); return; } (*asQuantile)(static_cast<double>(elapsed)); dPing = boost::accumulators::extended_p_square(*asQuantile)[0]; if (dPing == 0.0) dPing = elapsed; quint32 ping = static_cast<quint32>(lround(dPing / 1000.)); uiRecv = static_cast<quint32>(boost::accumulators::count(* asQuantile)); bool changed = (ping != uiPing) || (users != uiUsers) || (maxusers != uiMaxUsers); uiUsers = users; uiMaxUsers = maxusers; uiPing = ping; double grace = qMax(5000., 50. * uiPingSort); double diff = fabs(1000. * uiPingSort - dPing); if ((uiPingSort == 0) || ((uiSent >= 10) && (diff >= grace))) uiPingSort = ping; if (changed) emitDataChanged(); } FavoriteServer ServerItem::toFavoriteServer() const { FavoriteServer fs; fs.qsName = qsName; if (! qsBonjourHost.isEmpty()) fs.qsHostname = QLatin1Char('@') + qsBonjourHost; else fs.qsHostname = qsHostname; fs.usPort = usPort; fs.qsUsername = qsUsername; fs.qsPassword = qsPassword; fs.qsUrl = qsUrl; return fs; } /** * This function turns a ServerItem object into a QMimeData object holding a URL to the server. */ QMimeData *ServerItem::toMimeData() const { QMimeData *mime = ServerItem::toMimeData(qsName, qsHostname, usPort); if (itType == FavoriteType) mime->setData(QLatin1String("OriginatedInMumble"), QByteArray()); return mime; } /** * This function creates a QMimeData object containing a URL to the server at host and port. name is passed in the * query string as "title", which is used for adding a server to favorites. channel may be omitted, but if specified it * should be in the format of "/path/to/channel". */ QMimeData *ServerItem::toMimeData(const QString &name, const QString &host, unsigned short port, const QString &channel) { QUrl url; url.setScheme(QLatin1String("mumble")); url.setHost(host); if (port != DEFAULT_MUMBLE_PORT) url.setPort(port); url.setPath(channel); #if QT_VERSION >= 0x050000 QUrlQuery query; query.addQueryItem(QLatin1String("title"), name); query.addQueryItem(QLatin1String("version"), QLatin1String("1.2.0")); url.setQuery(query); #else url.addQueryItem(QLatin1String("title"), name); url.addQueryItem(QLatin1String("version"), QLatin1String("1.2.0")); #endif QString qs = QLatin1String(url.toEncoded()); QMimeData *mime = new QMimeData; #ifdef Q_OS_WIN QString contents = QString::fromLatin1("[InternetShortcut]\r\nURL=%1\r\n").arg(qs); QString urlname = QString::fromLatin1("%1.url").arg(name); FILEGROUPDESCRIPTORA fgda; ZeroMemory(&fgda, sizeof(fgda)); fgda.cItems = 1; fgda.fgd[0].dwFlags = FD_LINKUI | FD_FILESIZE; fgda.fgd[0].nFileSizeLow=contents.length(); strcpy_s(fgda.fgd[0].cFileName, MAX_PATH, urlname.toLocal8Bit().constData()); mime->setData(QLatin1String("FileGroupDescriptor"), QByteArray(reinterpret_cast<const char *>(&fgda), sizeof(fgda))); FILEGROUPDESCRIPTORW fgdw; ZeroMemory(&fgdw, sizeof(fgdw)); fgdw.cItems = 1; fgdw.fgd[0].dwFlags = FD_LINKUI | FD_FILESIZE; fgdw.fgd[0].nFileSizeLow=contents.length(); wcscpy_s(fgdw.fgd[0].cFileName, MAX_PATH, urlname.toStdWString().c_str()); mime->setData(QLatin1String("FileGroupDescriptorW"), QByteArray(reinterpret_cast<const char *>(&fgdw), sizeof(fgdw))); mime->setData(QString::fromWCharArray(CFSTR_FILECONTENTS), contents.toLocal8Bit()); DWORD context[4]; context[0] = 0; context[1] = 1; context[2] = 0; context[3] = 0; mime->setData(QLatin1String("DragContext"), QByteArray(reinterpret_cast<const char *>(&context[0]), sizeof(context))); DWORD dropaction; dropaction = DROPEFFECT_LINK; mime->setData(QString::fromWCharArray(CFSTR_PREFERREDDROPEFFECT), QByteArray(reinterpret_cast<const char *>(&dropaction), sizeof(dropaction))); #endif QList<QUrl> urls; urls << url; mime->setUrls(urls); mime->setText(qs); mime->setHtml(QString::fromLatin1("<a href=\"%1\">%2</a>").arg(qs).arg(Qt::escape(name))); return mime; } bool ServerItem::operator <(const QTreeWidgetItem &o) const { const ServerItem &other = static_cast<const ServerItem &>(o); const QTreeWidget *w = treeWidget(); const int column = w ? w->sortColumn() : 0; if (itType != other.itType) { const bool inverse = w ? (w->header()->sortIndicatorOrder() == Qt::DescendingOrder) : false; bool less; if (itType == FavoriteType) less = true; else if ((itType == LANType) && (other.itType == PublicType)) less = true; else less = false; return less ^ inverse; } if (bParent) { const bool inverse = w ? (w->header()->sortIndicatorOrder() == Qt::DescendingOrder) : false; return (qsName < other.qsName) ^ inverse; } if (column == 0) { QString a = qsName.toLower(); QString b = other.qsName.toLower(); QRegExp re(QLatin1String("[^0-9a-z]")); a.remove(re); b.remove(re); return a < b; } else if (column == 1) { quint32 a = uiPingSort ? uiPingSort : UINT_MAX; quint32 b = other.uiPingSort ? other.uiPingSort : UINT_MAX; return a < b; } else if (column == 2) { return uiUsers < other.uiUsers; } return false; } QIcon ServerItem::loadIcon(const QString &name) { if (! qmIcons.contains(name)) qmIcons.insert(name, QIcon(name)); return qmIcons.value(name); } ConnectDialogEdit::ConnectDialogEdit(QWidget *p, const QString &name, const QString &host, const QString &user, unsigned short port, const QString &password) : QDialog(p) { setupUi(this); init(); bCustomLabel = ! name.simplified().isEmpty(); qleName->setText(name); qleServer->setText(host); qleUsername->setText(user); qlePort->setText(QString::number(port)); qlePassword->setText(password); validate(); } ConnectDialogEdit::ConnectDialogEdit(QWidget *parent) : QDialog(parent) { setupUi(this); setWindowTitle(tr("Add Server")); init(); if (!updateFromClipboard()) { // If connected to a server assume the user wants to add it if (g.sh && g.sh->isRunning()) { QString host, name, user, pw; unsigned short port = DEFAULT_MUMBLE_PORT; g.sh->getConnectionInfo(host, port, user, pw); Channel *c = Channel::get(0); if (c && c->qsName != QLatin1String("Root")) { name = c->qsName; } showNotice(tr("You are currently connected to a server.\nDo you want to fill the dialog with the connection data of this server?\nHost: %1 Port: %2").arg(host).arg(port)); m_si = new ServerItem(name, host, port, user, pw); } } qleUsername->setText(g.s.qsUsername); } void ConnectDialogEdit::init() { m_si = NULL; usPort = 0; bOk = true; bCustomLabel = false; qwInlineNotice->hide(); qlePort->setValidator(new QIntValidator(1, 65535, qlePort)); qlePort->setText(QString::number(DEFAULT_MUMBLE_PORT)); qlePassword->setEchoMode(QLineEdit::Password); connect(qleName, SIGNAL(textChanged(const QString &)), this, SLOT(validate())); connect(qleServer, SIGNAL(textChanged(const QString &)), this, SLOT(validate())); connect(qlePort, SIGNAL(textChanged(const QString &)), this, SLOT(validate())); connect(qleUsername, SIGNAL(textChanged(const QString &)), this, SLOT(validate())); connect(qlePassword, SIGNAL(textChanged(const QString &)), this, SLOT(validate())); validate(); } ConnectDialogEdit::~ConnectDialogEdit() { delete m_si; } void ConnectDialogEdit::showNotice(const QString &text) { QLabel *label = qwInlineNotice->findChild<QLabel *>(QLatin1String("qlPasteNotice")); Q_ASSERT(label); label->setText(text); qwInlineNotice->show(); adjustSize(); } bool ConnectDialogEdit::updateFromClipboard() { delete m_si; m_si = ServerItem::fromMimeData(QApplication::clipboard()->mimeData(), false, NULL, true); bool hasServerData = m_si != NULL; if (hasServerData) { showNotice(tr("You have an URL in your clipboard.\nDo you want to fill the dialog with this data?\nHost: %1 Port: %2").arg(m_si->qsHostname).arg(m_si->usPort)); return true; } else { qwInlineNotice->hide(); adjustSize(); return false; } } void ConnectDialogEdit::on_qbFill_clicked() { Q_ASSERT(m_si); qwInlineNotice->hide(); adjustSize(); qleName->setText(m_si->qsName); qleServer->setText(m_si->qsHostname); qleUsername->setText(m_si->qsUsername); qlePort->setText(QString::number(m_si->usPort)); qlePassword->setText(m_si->qsPassword); delete m_si; m_si = NULL; } void ConnectDialogEdit::on_qbDiscard_clicked() { qwInlineNotice->hide(); adjustSize(); } void ConnectDialogEdit::on_qleName_textEdited(const QString& name) { if (bCustomLabel) { // If empty, then reset to automatic label. // NOTE(nik@jnstw.us): You may be tempted to set qleName to qleServer, but that results in the odd // UI behavior that clearing the field doesn't clear it; it'll immediately equal qleServer. Instead, // leave it empty and let it update the next time qleServer updates. Code in accept will default it // to qleServer if it isn't updated beforehand. if (name.simplified().isEmpty()) { bCustomLabel = false; } } else { // If manually edited, set to Custom bCustomLabel = true; } } void ConnectDialogEdit::on_qleServer_textEdited(const QString& server) { // If using automatic label, update it if (!bCustomLabel) { qleName->setText(server); } } void ConnectDialogEdit::validate() { qsName = qleName->text().simplified(); qsHostname = qleServer->text().simplified(); usPort = qlePort->text().toUShort(); qsUsername = qleUsername->text().simplified(); qsPassword = qlePassword->text(); // For bonjour hosts disable the port field as it's auto-detected qlePort->setDisabled(!qsHostname.isEmpty() && qsHostname.startsWith(QLatin1Char('@'))); // For SuperUser show password edit if (qsUsername.toLower() == QLatin1String("superuser")) { qliPassword->setVisible(true); qlePassword->setVisible(true); qcbShowPassword->setVisible(true); adjustSize(); } else if (qsPassword.isEmpty()) { qliPassword->setVisible(false); qlePassword->setVisible(false); qcbShowPassword->setVisible(false); adjustSize(); } bOk = ! qsHostname.isEmpty() && ! qsUsername.isEmpty() && usPort; qdbbButtonBox->button(QDialogButtonBox::Ok)->setEnabled(bOk); } void ConnectDialogEdit::accept() { validate(); if (bOk) { QString server = qleServer->text().simplified(); // If the user accidentally added a schema or path part, drop it now. // We can't do so during editing as that is quite jarring. const int schemaPos = server.indexOf(QLatin1String("://")); if (schemaPos != -1) { server.remove(0, schemaPos + 3); } const int pathPos = server.indexOf(QLatin1Char('/')); if (pathPos != -1) { server.resize(pathPos); } qleServer->setText(server); if (qleName->text().simplified().isEmpty() || !bCustomLabel) { qleName->setText(server); } QDialog::accept(); } } void ConnectDialogEdit::on_qcbShowPassword_toggled(bool checked) { qlePassword->setEchoMode(checked ? QLineEdit::Normal : QLineEdit::Password); } ConnectDialog::ConnectDialog(QWidget *p, bool autoconnect) : QDialog(p), bAutoConnect(autoconnect) { setupUi(this); #ifdef Q_OS_MAC setWindowModality(Qt::WindowModal); #endif bPublicInit = false; siAutoConnect = NULL; bAllowPing = g.s.ptProxyType == Settings::NoProxy; bAllowHostLookup = g.s.ptProxyType == Settings::NoProxy; bAllowBonjour = g.s.ptProxyType == Settings::NoProxy; bAllowFilters = g.s.ptProxyType == Settings::NoProxy; if (tPublicServers.elapsed() >= 60 * 24 * 1000000ULL) { qlPublicServers.clear(); } qdbbButtonBox->button(QDialogButtonBox::Ok)->setEnabled(false); qdbbButtonBox->button(QDialogButtonBox::Ok)->setText(tr("&Connect")); QPushButton *qpbAdd = new QPushButton(tr("&Add New..."), this); qpbAdd->setDefault(false); qpbAdd->setAutoDefault(false); connect(qpbAdd, SIGNAL(clicked()), qaFavoriteAddNew, SIGNAL(triggered())); qdbbButtonBox->addButton(qpbAdd, QDialogButtonBox::ActionRole); qpbEdit = new QPushButton(tr("&Edit..."), this); qpbEdit->setEnabled(false); qpbEdit->setDefault(false); qpbEdit->setAutoDefault(false); connect(qpbEdit, SIGNAL(clicked()), qaFavoriteEdit, SIGNAL(triggered())); qdbbButtonBox->addButton(qpbEdit, QDialogButtonBox::ActionRole); qpbAdd->setHidden(g.s.disableConnectDialogEditing); qpbEdit->setHidden(g.s.disableConnectDialogEditing); qtwServers->setItemDelegate(new ServerViewDelegate()); // Hide ping and user count if we are not allowed to ping. if (!bAllowPing) { qtwServers->setColumnCount(1); } qtwServers->sortItems(1, Qt::AscendingOrder); #if QT_VERSION >= 0x050000 qtwServers->header()->setSectionResizeMode(0, QHeaderView::Stretch); if (qtwServers->columnCount() >= 2) { qtwServers->header()->setSectionResizeMode(1, QHeaderView::ResizeToContents); } if (qtwServers->columnCount() >= 3) { qtwServers->header()->setSectionResizeMode(2, QHeaderView::ResizeToContents); } #else qtwServers->header()->setResizeMode(0, QHeaderView::Stretch); if (qtwServers->columnCount() >= 2) { qtwServers->header()->setResizeMode(1, QHeaderView::ResizeToContents); } if (qtwServers->columnCount() >= 3) { qtwServers->header()->setResizeMode(2, QHeaderView::ResizeToContents); } #endif connect(qtwServers->header(), SIGNAL(sortIndicatorChanged(int, Qt::SortOrder)), this, SLOT(OnSortChanged(int, Qt::SortOrder))); qaShowAll->setChecked(false); qaShowReachable->setChecked(false); qaShowPopulated->setChecked(false); if (bAllowFilters) { switch (g.s.ssFilter) { case Settings::ShowPopulated: qaShowPopulated->setChecked(true); break; case Settings::ShowReachable: qaShowReachable->setChecked(true); break; default: qaShowAll->setChecked(true); break; } } else { qaShowAll->setChecked(true); } qagFilters = new QActionGroup(this); qagFilters->addAction(qaShowAll); qagFilters->addAction(qaShowReachable); qagFilters->addAction(qaShowPopulated); connect(qagFilters, SIGNAL(triggered(QAction *)), this, SLOT(onFiltersTriggered(QAction *))); qmPopup = new QMenu(this); qmFilters = new QMenu(tr("&Filters"), this); qmFilters->addAction(qaShowAll); qmFilters->addAction(qaShowReachable); qmFilters->addAction(qaShowPopulated); if (!bAllowFilters) { qmFilters->setEnabled(false); } QList<QTreeWidgetItem *> ql; QList<FavoriteServer> favorites = g.db->getFavorites(); foreach(const FavoriteServer &fs, favorites) { ServerItem *si = new ServerItem(fs); qlItems << si; startDns(si); qtwServers->siFavorite->addServerItem(si); } #ifdef USE_BONJOUR // Make sure the we got the objects we need, then wire them up if (bAllowBonjour && g.bc->bsbBrowser && g.bc->bsrResolver) { connect(g.bc->bsbBrowser, SIGNAL(error(DNSServiceErrorType)), this, SLOT(onLanBrowseError(DNSServiceErrorType))); connect(g.bc->bsbBrowser, SIGNAL(currentBonjourRecordsChanged(const QList<BonjourRecord> &)), this, SLOT(onUpdateLanList(const QList<BonjourRecord> &))); connect(g.bc->bsrResolver, SIGNAL(error(BonjourRecord, DNSServiceErrorType)), this, SLOT(onLanResolveError(BonjourRecord, DNSServiceErrorType))); connect(g.bc->bsrResolver, SIGNAL(bonjourRecordResolved(BonjourRecord, QString, int)), this, SLOT(onResolved(BonjourRecord, QString, int))); onUpdateLanList(g.bc->bsbBrowser->currentRecords()); } #endif qtPingTick = new QTimer(this); connect(qtPingTick, SIGNAL(timeout()), this, SLOT(timeTick())); qusSocket4 = new QUdpSocket(this); qusSocket6 = new QUdpSocket(this); bIPv4 = qusSocket4->bind(QHostAddress(QHostAddress::Any), 0); bIPv6 = qusSocket6->bind(QHostAddress(QHostAddress::AnyIPv6), 0); connect(qusSocket4, SIGNAL(readyRead()), this, SLOT(udpReply())); connect(qusSocket6, SIGNAL(readyRead()), this, SLOT(udpReply())); if (qtwServers->siFavorite->isHidden() && (!qtwServers->siLAN || qtwServers->siLAN->isHidden()) && qtwServers->siPublic != NULL) { qtwServers->siPublic->setExpanded(true); } iPingIndex = -1; qtPingTick->start(50); new QShortcut(QKeySequence(QKeySequence::Copy), this, SLOT(on_qaFavoriteCopy_triggered())); new QShortcut(QKeySequence(QKeySequence::Paste), this, SLOT(on_qaFavoritePaste_triggered())); qtwServers->setCurrentItem(NULL); bLastFound = false; qmPingCache = g.db->getPingCache(); if (! g.s.qbaConnectDialogGeometry.isEmpty()) restoreGeometry(g.s.qbaConnectDialogGeometry); if (! g.s.qbaConnectDialogHeader.isEmpty()) qtwServers->header()->restoreState(g.s.qbaConnectDialogHeader); } ConnectDialog::~ConnectDialog() { ServerItem::qmIcons.clear(); QList<FavoriteServer> ql; qmPingCache.clear(); foreach(ServerItem *si, qlItems) { if (si->uiPing) qmPingCache.insert(UnresolvedServerAddress(si->qsHostname, si->usPort), si->uiPing); if (si->itType != ServerItem::FavoriteType) continue; ql << si->toFavoriteServer(); } g.db->setFavorites(ql); g.db->setPingCache(qmPingCache); g.s.qbaConnectDialogHeader = qtwServers->header()->saveState(); g.s.qbaConnectDialogGeometry = saveGeometry(); } void ConnectDialog::accept() { ServerItem *si = static_cast<ServerItem *>(qtwServers->currentItem()); if (! si || (bAllowHostLookup && si->qlAddresses.isEmpty()) || si->qsHostname.isEmpty()) { qWarning() << "Invalid server"; return; } qsPassword = si->qsPassword; qsServer = si->qsHostname; usPort = si->usPort; if (si->qsUsername.isEmpty()) { bool ok; QString defUserName = QInputDialog::getText(this, tr("Connecting to %1").arg(si->qsName), tr("Enter username"), QLineEdit::Normal, g.s.qsUsername, &ok).trimmed(); if (! ok) return; g.s.qsUsername = si->qsUsername = defUserName; } qsUsername = si->qsUsername; g.s.qsLastServer = si->qsName; QDialog::accept(); } void ConnectDialog::OnSortChanged(int logicalIndex, Qt::SortOrder) { if (logicalIndex != 2) { return; } foreach(ServerItem *si, qlItems) { if (si->uiPing && (si->uiPing != si->uiPingSort)) { si->uiPingSort = si->uiPing; si->setDatas(); } } } void ConnectDialog::on_qaFavoriteAdd_triggered() { ServerItem *si = static_cast<ServerItem *>(qtwServers->currentItem()); if (! si || (si->itType == ServerItem::FavoriteType)) return; si = new ServerItem(si); qtwServers->fixupName(si); qlItems << si; qtwServers->siFavorite->addServerItem(si); qtwServers->setCurrentItem(si); startDns(si); } void ConnectDialog::on_qaFavoriteAddNew_triggered() { ConnectDialogEdit *cde = new ConnectDialogEdit(this); if (cde->exec() == QDialog::Accepted) { ServerItem *si = new ServerItem(cde->qsName, cde->qsHostname, cde->usPort, cde->qsUsername, cde->qsPassword); qlItems << si; qtwServers->siFavorite->addServerItem(si); qtwServers->setCurrentItem(si); startDns(si); } delete cde; } void ConnectDialog::on_qaFavoriteEdit_triggered() { ServerItem *si = static_cast<ServerItem *>(qtwServers->currentItem()); if (! si || (si->itType != ServerItem::FavoriteType)) return; QString host; if (! si->qsBonjourHost.isEmpty()) host = QLatin1Char('@') + si->qsBonjourHost; else host = si->qsHostname; ConnectDialogEdit *cde = new ConnectDialogEdit(this, si->qsName, host, si->qsUsername, si->usPort, si->qsPassword); if (cde->exec() == QDialog::Accepted) { si->qsName = cde->qsName; si->qsUsername = cde->qsUsername; si->qsPassword = cde->qsPassword; if ((cde->qsHostname != host) || (cde->usPort != si->usPort)) { stopDns(si); si->qlAddresses.clear(); si->reset(); si->usPort = cde->usPort; if (cde->qsHostname.startsWith(QLatin1Char('@'))) { si->qsHostname = QString(); si->qsBonjourHost = cde->qsHostname.mid(1); si->brRecord = BonjourRecord(si->qsBonjourHost, QLatin1String("_mumble._tcp."), QLatin1String("local.")); } else { si->qsHostname = cde->qsHostname; si->qsBonjourHost = QString(); si->brRecord = BonjourRecord(); } startDns(si); } si->setDatas(); } delete cde; } void ConnectDialog::on_qaFavoriteRemove_triggered() { ServerItem *si = static_cast<ServerItem *>(qtwServers->currentItem()); if (! si || (si->itType != ServerItem::FavoriteType)) return; stopDns(si); qlItems.removeAll(si); delete si; } void ConnectDialog::on_qaFavoriteCopy_triggered() { ServerItem *si = static_cast<ServerItem *>(qtwServers->currentItem()); if (! si) return; QApplication::clipboard()->setMimeData(si->toMimeData()); } void ConnectDialog::on_qaFavoritePaste_triggered() { ServerItem *si = ServerItem::fromMimeData(QApplication::clipboard()->mimeData()); if (! si) return; qlItems << si; qtwServers->siFavorite->addServerItem(si); qtwServers->setCurrentItem(si); startDns(si); } void ConnectDialog::on_qaUrl_triggered() { ServerItem *si = static_cast<ServerItem *>(qtwServers->currentItem()); if (! si || si->qsUrl.isEmpty()) return; QDesktopServices::openUrl(QUrl(si->qsUrl)); } void ConnectDialog::onFiltersTriggered(QAction *act) { if (act == qaShowAll) g.s.ssFilter = Settings::ShowAll; else if (act == qaShowReachable) g.s.ssFilter = Settings::ShowReachable; else if (act == qaShowPopulated) g.s.ssFilter = Settings::ShowPopulated; foreach(ServerItem *si, qlItems) si->hideCheck(); } void ConnectDialog::on_qtwServers_customContextMenuRequested(const QPoint &mpos) { ServerItem *si = static_cast<ServerItem *>(qtwServers->itemAt(mpos)); qmPopup->clear(); if (si != NULL && si->bParent) { si = NULL; } if (si != NULL) { if (!g.s.disableConnectDialogEditing) { if (si->itType == ServerItem::FavoriteType) { qmPopup->addAction(qaFavoriteEdit); qmPopup->addAction(qaFavoriteRemove); } else { qmPopup->addAction(qaFavoriteAdd); } } if (!si->qsUrl.isEmpty()) { qmPopup->addAction(qaUrl); } } if (! qmPopup->isEmpty()) { qmPopup->addSeparator(); } qmPopup->addMenu(qmFilters); qmPopup->popup(qtwServers->viewport()->mapToGlobal(mpos), NULL); } void ConnectDialog::on_qtwServers_itemDoubleClicked(QTreeWidgetItem *item, int) { qtwServers->setCurrentItem(item); accept(); } void ConnectDialog::on_qtwServers_currentItemChanged(QTreeWidgetItem *item, QTreeWidgetItem *) { ServerItem *si = static_cast<ServerItem *>(item); if (si->siParent == qtwServers->siFavorite) { qpbEdit->setEnabled(true); } else { qpbEdit->setEnabled(false); } bool bOk = !si->qlAddresses.isEmpty(); if (!bAllowHostLookup) { bOk = true; } qdbbButtonBox->button(QDialogButtonBox::Ok)->setEnabled(bOk); bLastFound = true; } void ConnectDialog::on_qtwServers_itemExpanded(QTreeWidgetItem *item) { if (qtwServers->siPublic != NULL && item == qtwServers->siPublic) { initList(); fillList(); } ServerItem *p = static_cast<ServerItem *>(item); foreach(ServerItem *si, p->qlChildren) startDns(si); } void ConnectDialog::initList() { if (bPublicInit || (qlPublicServers.count() > 0)) return; bPublicInit = true; QUrl url; url.setPath(QLatin1String("/v1/list")); #if QT_VERSION >= 0x050000 QUrlQuery query; query.addQueryItem(QLatin1String("version"), QLatin1String(MUMTEXT(MUMBLE_VERSION_STRING))); url.setQuery(query); #else url.addQueryItem(QLatin1String("version"), QLatin1String(MUMTEXT(MUMBLE_VERSION_STRING))); #endif WebFetch::fetch(QLatin1String("publist"), url, this, SLOT(fetched(QByteArray,QUrl,QMap<QString,QString>))); } #ifdef USE_BONJOUR void ConnectDialog::onResolved(BonjourRecord record, QString host, int port) { qlBonjourActive.removeAll(record); foreach(ServerItem *si, qlItems) { if (si->brRecord == record) { unsigned short usport = static_cast<unsigned short>(port); if ((host != si->qsHostname) || (usport != si->usPort)) { stopDns(si); si->usPort = static_cast<unsigned short>(port); si->qsHostname = host; startDns(si); } } } } void ConnectDialog::onUpdateLanList(const QList<BonjourRecord> &list) { QSet<ServerItem *> items; QSet<ServerItem *> old = qtwServers->siLAN->qlChildren.toSet(); foreach(const BonjourRecord &record, list) { bool found = false; foreach(ServerItem *si, old) { if (si->brRecord == record) { items.insert(si); found = true; break; } } if (! found) { ServerItem *si = new ServerItem(record); qlItems << si; g.bc->bsrResolver->resolveBonjourRecord(record); startDns(si); qtwServers->siLAN->addServerItem(si); } } QSet<ServerItem *> remove = old.subtract(items); foreach(ServerItem *si, remove) { stopDns(si); qlItems.removeAll(si); delete si; } } void ConnectDialog::onLanBrowseError(DNSServiceErrorType err) { qWarning()<<"Bonjour reported browser error "<< err; } void ConnectDialog::onLanResolveError(BonjourRecord br, DNSServiceErrorType err) { qlBonjourActive.removeAll(br); qWarning()<<"Bonjour reported resolver error "<< err; } #endif void ConnectDialog::fillList() { QList<QTreeWidgetItem *> ql; QList<QTreeWidgetItem *> qlNew; foreach(const PublicInfo &pi, qlPublicServers) { bool found = false; foreach(ServerItem *si, qlItems) { if ((pi.qsIp == si->qsHostname) && (pi.usPort == si->usPort)) { si->qsCountry = pi.qsCountry; si->qsCountryCode = pi.qsCountryCode; si->qsContinentCode = pi.qsContinentCode; si->qsUrl = pi.quUrl.toString(); si->bCA = pi.bCA; si->setDatas(); if (si->itType == ServerItem::PublicType) found = true; } } if (! found) ql << new ServerItem(pi); } while (! ql.isEmpty()) { ServerItem *si = static_cast<ServerItem *>(ql.takeAt(qrand() % ql.count())); qlNew << si; qlItems << si; } foreach(QTreeWidgetItem *qtwi, qlNew) { ServerItem *si = static_cast<ServerItem *>(qtwi); ServerItem *p = qtwServers->getParent(si->qsContinentCode, si->qsCountryCode, si->qsCountry, qsUserContinentCode, qsUserCountryCode); p->addServerItem(si); if (p->isExpanded() && p->parent()->isExpanded()) startDns(si); } } void ConnectDialog::timeTick() { if (! bLastFound && ! g.s.qsLastServer.isEmpty()) { QList<QTreeWidgetItem *> items = qtwServers->findItems(g.s.qsLastServer, Qt::MatchExactly | Qt::MatchRecursive); if (!items.isEmpty()) { bLastFound = true; qtwServers->setCurrentItem(items.at(0)); if (g.s.bAutoConnect && bAutoConnect) { siAutoConnect = static_cast<ServerItem *>(items.at(0)); if (! siAutoConnect->qlAddresses.isEmpty()) { accept(); return; } else if (!bAllowHostLookup) { accept(); return; } } } } if (bAllowHostLookup) { // Start DNS Lookup of first unknown hostname foreach(const UnresolvedServerAddress &unresolved, qlDNSLookup) { if (qsDNSActive.contains(unresolved)) { continue; } qlDNSLookup.removeAll(unresolved); qlDNSLookup.append(unresolved); qsDNSActive.insert(unresolved); ServerResolver *sr = new ServerResolver(); QObject::connect(sr, SIGNAL(resolved()), this, SLOT(lookedUp())); sr->resolve(unresolved.hostname, unresolved.port); break; } } ServerItem *current = static_cast<ServerItem *>(qtwServers->currentItem()); ServerItem *hover = static_cast<ServerItem *>(qtwServers->itemAt(qtwServers->viewport()->mapFromGlobal(QCursor::pos()))); ServerItem *si = NULL; if (tCurrent.elapsed() >= 1000000ULL) si = current; if (! si && (tHover.elapsed() >= 1000000ULL)) si = hover; if (si) { QString hostname = si->qsHostname.toLower(); unsigned short port = si->usPort; UnresolvedServerAddress unresolved(hostname, port); if (si->qlAddresses.isEmpty()) { if (! hostname.isEmpty()) { qlDNSLookup.removeAll(unresolved); qlDNSLookup.prepend(unresolved); } si = NULL; } } if (!si) { if (qlItems.isEmpty()) return; bool expanded; do { ++iPingIndex; if (iPingIndex >= qlItems.count()) { if (tRestart.isElapsed(1000000ULL)) iPingIndex = 0; else return; } si = qlItems.at(iPingIndex); ServerItem *p = si->siParent; expanded = true; while (p && expanded) { expanded = expanded && p->isExpanded(); p = p->siParent; } } while (si->qlAddresses.isEmpty() || ! expanded); } if (si == current) tCurrent.restart(); if (si == hover) tHover.restart(); foreach(const ServerAddress &addr, si->qlAddresses) { sendPing(addr.host.toAddress(), addr.port); } } void ConnectDialog::startDns(ServerItem *si) { if (!bAllowHostLookup) { return; } QString hostname = si->qsHostname.toLower(); unsigned short port = si->usPort; UnresolvedServerAddress unresolved(hostname, port); if (si->qlAddresses.isEmpty()) { // Determine if qsHostname is an IP address // or a hostname. If it is an IP address, we // can treat it as resolved as-is. QHostAddress qha(si->qsHostname); bool hostnameIsIPAddress = !qha.isNull(); if (hostnameIsIPAddress) { si->qlAddresses.append(ServerAddress(HostAddress(qha), port)); } else { si->qlAddresses = qhDNSCache.value(unresolved); } } if (qtwServers->currentItem() == si) qdbbButtonBox->button(QDialogButtonBox::Ok)->setEnabled(! si->qlAddresses.isEmpty()); if (! si->qlAddresses.isEmpty()) { foreach(const ServerAddress &addr, si->qlAddresses) { qhPings[addr].insert(si); } return; } #ifdef USE_BONJOUR if (bAllowBonjour && si->qsHostname.isEmpty() && ! si->brRecord.serviceName.isEmpty()) { if (! qlBonjourActive.contains(si->brRecord)) { g.bc->bsrResolver->resolveBonjourRecord(si->brRecord); qlBonjourActive.append(si->brRecord); } return; } #endif if (! qhDNSWait.contains(unresolved)) { if (si->itType == ServerItem::PublicType) qlDNSLookup.append(unresolved); else qlDNSLookup.prepend(unresolved); } qhDNSWait[unresolved].insert(si); } void ConnectDialog::stopDns(ServerItem *si) { if (!bAllowHostLookup) { return; } foreach(const ServerAddress &addr, si->qlAddresses) { if (qhPings.contains(addr)) { qhPings[addr].remove(si); if (qhPings[addr].isEmpty()) { qhPings.remove(addr); qhPingRand.remove(addr); } } } QString hostname = si->qsHostname.toLower(); unsigned short port = si->usPort; UnresolvedServerAddress unresolved(hostname, port); if (qhDNSWait.contains(unresolved)) { qhDNSWait[unresolved].remove(si); if (qhDNSWait[unresolved].isEmpty()) { qhDNSWait.remove(unresolved); qlDNSLookup.removeAll(unresolved); } } } void ConnectDialog::lookedUp() { ServerResolver *sr = qobject_cast<ServerResolver *>(QObject::sender()); sr->deleteLater(); QString hostname = sr->hostname().toLower(); unsigned short port = sr->port(); UnresolvedServerAddress unresolved(hostname, port); qsDNSActive.remove(unresolved); // An error occurred, or no records were found. if (sr->records().size() == 0) { return; } QSet<ServerAddress> qs; foreach (ServerResolverRecord record, sr->records()) { foreach(const HostAddress &ha, record.addresses()) { qs.insert(ServerAddress(ha, record.port())); } } QSet<ServerItem *> waiting = qhDNSWait[unresolved]; foreach(ServerItem *si, waiting) { foreach (const ServerAddress &addr, qs) { qhPings[addr].insert(si); } si->qlAddresses = qs.toList(); } qlDNSLookup.removeAll(unresolved); qhDNSCache.insert(unresolved, qs.toList()); qhDNSWait.remove(unresolved); foreach(ServerItem *si, waiting) { if (si == qtwServers->currentItem()) { on_qtwServers_currentItemChanged(si, si); if (si == siAutoConnect) accept(); } } if (bAllowPing) { foreach(const ServerAddress &addr, qs) { sendPing(addr.host.toAddress(), addr.port); } } } void ConnectDialog::sendPing(const QHostAddress &host, unsigned short port) { char blob[16]; ServerAddress addr(HostAddress(host), port); quint64 uiRand; if (qhPingRand.contains(addr)) { uiRand = qhPingRand.value(addr); } else { uiRand = (static_cast<quint64>(qrand()) << 32) | static_cast<quint64>(qrand()); qhPingRand.insert(addr, uiRand); } memset(blob, 0, sizeof(blob)); * reinterpret_cast<quint64 *>(blob+8) = tPing.elapsed() ^ uiRand; if (bIPv4 && host.protocol() == QAbstractSocket::IPv4Protocol) qusSocket4->writeDatagram(blob+4, 12, host, port); else if (bIPv6 && host.protocol() == QAbstractSocket::IPv6Protocol) qusSocket6->writeDatagram(blob+4, 12, host, port); else return; const QSet<ServerItem *> &qs = qhPings.value(addr); foreach(ServerItem *si, qs) ++ si->uiSent; } void ConnectDialog::udpReply() { QUdpSocket *sock = qobject_cast<QUdpSocket *>(sender()); while (sock->hasPendingDatagrams()) { char blob[64]; QHostAddress host; unsigned short port; qint64 len = sock->readDatagram(blob+4, 24, &host, &port); if (len == 24) { if (host.scopeId() == QLatin1String("0")) host.setScopeId(QLatin1String("")); ServerAddress address(HostAddress(host), port); if (qhPings.contains(address)) { quint32 *ping = reinterpret_cast<quint32 *>(blob+4); quint64 *ts = reinterpret_cast<quint64 *>(blob+8); quint64 elapsed = tPing.elapsed() - (*ts ^ qhPingRand.value(address)); foreach(ServerItem *si, qhPings.value(address)) { si->uiVersion = qFromBigEndian(ping[0]); quint32 users = qFromBigEndian(ping[3]); quint32 maxusers = qFromBigEndian(ping[4]); si->uiBandwidth = qFromBigEndian(ping[5]); if (! si->uiPingSort) si->uiPingSort = qmPingCache.value(UnresolvedServerAddress(si->qsHostname, si->usPort)); si->setDatas(static_cast<double>(elapsed), users, maxusers); si->hideCheck(); } } } } } void ConnectDialog::fetched(QByteArray xmlData, QUrl, QMap<QString, QString> headers) { if (xmlData.isNull()) { QMessageBox::warning(this, QLatin1String("Mumble"), tr("Failed to fetch server list"), QMessageBox::Ok); return; } QDomDocument doc; doc.setContent(xmlData); qlPublicServers.clear(); qsUserCountry = headers.value(QLatin1String("Geo-Country")); qsUserCountryCode = headers.value(QLatin1String("Geo-Country-Code")).toLower(); qsUserContinentCode = headers.value(QLatin1String("Geo-Continent-Code")).toLower(); QDomElement root=doc.documentElement(); QDomNode n = root.firstChild(); while (!n.isNull()) { QDomElement e = n.toElement(); if (!e.isNull()) { if (e.tagName() == QLatin1String("server")) { PublicInfo pi; pi.qsName = e.attribute(QLatin1String("name")); pi.quUrl = e.attribute(QLatin1String("url")); pi.qsIp = e.attribute(QLatin1String("ip")); pi.usPort = e.attribute(QLatin1String("port")).toUShort(); pi.qsCountry = e.attribute(QLatin1String("country"), tr("Unknown")); pi.qsCountryCode = e.attribute(QLatin1String("country_code")).toLower(); pi.qsContinentCode = e.attribute(QLatin1String("continent_code")).toLower(); pi.bCA = e.attribute(QLatin1String("ca")).toInt() ? true : false; qlPublicServers << pi; } } n = n.nextSibling(); } tPublicServers.restart(); fillList(); }
./CrossVul/dataset_final_sorted/CWE-59/cpp/bad_1993_0
crossvul-cpp_data_good_915_3
/* * Copyright (C) 2017 ~ 2017 Deepin Technology Co., Ltd. * * Author: zccrs <zccrs@live.com> * * Maintainer: zccrs <zhangjide@deepin.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "bootdoctor.h" #include "helper.h" #include "ddevicediskinfo.h" #include "ddevicepartinfo.h" QString BootDoctor::m_lastErrorString; bool BootDoctor::fix(const QString &partDevice) { m_lastErrorString.clear(); DDevicePartInfo part_info(partDevice); const QString part_old_uuid = part_info.uuid(); if (Helper::processExec("lsblk -s -d -n -o UUID") == 0) { if (Helper::lastProcessStandardOutput().contains(part_old_uuid.toLatin1())) { // reset uuid if (Helper::resetPartUUID(part_info)) { QThread::sleep(1); part_info.refresh(); qDebug() << part_old_uuid << part_info.uuid(); } else { dCWarning("Failed to reset uuid"); } } } bool device_is_mounted = Helper::isMounted(partDevice); const QString &mount_root = Helper::temporaryMountDevice(partDevice, QFileInfo(partDevice).fileName()); if (mount_root.isEmpty()) { m_lastErrorString = QObject::tr("Failed to mount partition \"%1\"").arg(partDevice); goto failed; } { const QString tmp_dir = "/var/cache/deepin-clone"; if (!QDir::current().mkpath(tmp_dir)) { dCError("mkpath \"%s\" failed", qPrintable(tmp_dir)); goto failed; } const QString &repo_path = tmp_dir + "/repo.iso"; if (!QFile::exists(repo_path) && !QFile::copy(QString(":/repo_%1.iso").arg(HOST_ARCH), repo_path)) { dCError("copy file failed, new name: %s", qPrintable(repo_path)); goto failed; } bool ok = false; const QString &repo_mount_point = mount_root + "/deepin-clone"; QFile file_boot_fix(mount_root + "/boot_fix.sh"); do { if (!QDir(mount_root).exists("deepin-clone") && !QDir(mount_root).mkdir("deepin-clone")) { dCError("Create \"deepin-clone\" dir failed(\"%s\")", qPrintable(mount_root)); break; } if (!Helper::mountDevice(repo_path, repo_mount_point, true)) { m_lastErrorString = QObject::tr("Failed to mount partition \"%1\"").arg(repo_path); break; } if (file_boot_fix.exists()) { file_boot_fix.remove(); } if (!QFile::copy(QString(":/scripts/boot_fix_%1.sh").arg( #if defined(HOST_ARCH_x86_64) || defined(HOST_ARCH_i386) || defined(HOST_ARCH_i686) "x86" #elif defined(HOST_ARCH_mips64) || defined(HOST_ARCH_mips32) "mips" #elif defined(HOST_ARCH_sw_64) "sw_64" #elif defined(HOST_ARCH_aarch64) "aarch64" #else #pragma message "Machine: " HOST_ARCH "unknow" #endif ), file_boot_fix.fileName())) { dCError("copy file failed, new name: %s", qPrintable(file_boot_fix.fileName())); break; } if (!file_boot_fix.setPermissions(file_boot_fix.permissions() | QFile::ExeUser)) { dCError("Set \"%s\" permissions failed", qPrintable(file_boot_fix.fileName())); break; } if (Helper::processExec(QString("mount --bind -v --bind /dev %1/dev").arg(mount_root)) != 0) { dCError("Failed to bind /dev"); break; } if (Helper::processExec(QString("mount --bind -v --bind /dev/pts %1/dev/pts").arg(mount_root)) != 0) { dCError("Failed to bind /dev/pts"); break; } if (Helper::processExec(QString("mount --bind -v --bind /proc %1/proc").arg(mount_root)) != 0) { dCError("Failed to bind /proc"); break; } if (Helper::processExec(QString("mount --bind -v --bind /sys %1/sys").arg(mount_root)) != 0) { dCError("Failed to bind /sys"); break; } ok = true; } while (0); QProcess process; if (ok) { const QString &parent_device = Helper::parentDevice(partDevice); bool is_efi = false; if (!parent_device.isEmpty()) { DDeviceDiskInfo info(parent_device); dCDebug("Disk partition table type: %d", info.ptType()); if (info.ptType() == DDeviceDiskInfo::GPT) { for (const DPartInfo &part : info.childrenPartList()) { if (part.guidType() == DPartInfo::EFI_SP_None) { const QString &efi_path = mount_root + "/boot/efi"; QDir::current().mkpath(efi_path); if (Helper::processExec(QString("mount %1 %2").arg(part.filePath()).arg(efi_path)) != 0) { dCError("Failed to mount EFI partition"); m_lastErrorString = QObject::tr("Failed to mount partition \"%1\"").arg(part.filePath()); ok = false; break; } is_efi = true; break; } } if (!is_efi && m_lastErrorString.isEmpty()) { m_lastErrorString = QObject::tr("EFI partition not found"); ok = false; } } else if (info.ptType() == DDeviceDiskInfo::Unknow) { m_lastErrorString = QObject::tr("Unknown partition style"); ok = false; } } if (ok) { process.setProcessChannelMode(QProcess::MergedChannels); process.start(QString("chroot %1 ./boot_fix.sh %2 %3 /deepin-clone") .arg(mount_root) .arg(parent_device) .arg(is_efi ? "true" : "false")); while (process.waitForReadyRead()) { const QByteArray &data = process.readAll().simplified().constData(); dCDebug(data.constData()); } process.waitForFinished(-1); switch (process.exitCode()) { case 1: m_lastErrorString = QObject::tr("Boot for install system failed"); break; case 2: m_lastErrorString = QObject::tr("Boot for update system failed"); break; default: break; } } } // clear Helper::processExec("umount " + repo_mount_point); QDir(mount_root).rmdir("deepin-clone"); file_boot_fix.remove(); Helper::processExec("umount " + mount_root + "/dev/pts"); Helper::processExec("umount " + mount_root + "/dev"); Helper::processExec("umount " + mount_root + "/proc"); Helper::processExec("umount " + mount_root + "/sys"); Helper::processExec("umount " + mount_root + "/boot/efi"); if (ok && process.exitCode() == 0) { if (part_old_uuid != part_info.uuid()) { dCDebug("Reset the uuid from \"%s\" to \"%s\"", qPrintable(part_old_uuid), qPrintable(part_info.uuid())); // update /etc/fstab QFile file(mount_root + "/etc/fstab"); if (file.exists() && file.open(QIODevice::ReadWrite)) { QByteArray data = file.readAll(); if (file.seek(0)) { file.write(data.replace(part_old_uuid.toLatin1(), part_info.uuid().toLatin1())); } file.close(); } else { dCWarning("Failed to update /etc/fstab, error: %s", qPrintable(file.errorString())); } file.setFileName(mount_root + "/etc/crypttab"); if (file.exists() && file.open(QIODevice::ReadWrite)) { QByteArray data = file.readAll(); if (file.seek(0)) { file.write(data.replace(part_old_uuid.toLatin1(), part_info.uuid().toLatin1())); } file.close(); } else { dCWarning("Failed to update /etc/crypttab, error: %s", qPrintable(file.errorString())); } } if (!device_is_mounted) Helper::umountDevice(partDevice); return true; } } failed: if (!device_is_mounted) Helper::umountDevice(partDevice); if (m_lastErrorString.isEmpty()) m_lastErrorString = QObject::tr("Boot for repair system failed"); dCDebug("Restore partition uuid"); if (!Helper::resetPartUUID(part_info, part_old_uuid.toLatin1())) { dCWarning("Failed to restore partition uuid, part: %s, uuid: %s", qPrintable(partDevice), qPrintable(part_old_uuid)); } return false; } QString BootDoctor::errorString() { return m_lastErrorString; }
./CrossVul/dataset_final_sorted/CWE-59/cpp/good_915_3
crossvul-cpp_data_bad_915_0
/* * Copyright (C) 2017 ~ 2017 Deepin Technology Co., Ltd. * * Author: zccrs <zccrs@live.com> * * Maintainer: zccrs <zhangjide@deepin.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #define private public #include <private/qiodevice_p.h> #undef private #include "ddevicediskinfo.h" #include "ddiskinfo_p.h" #include "helper.h" #include "ddevicepartinfo.h" #include "dpartinfo_p.h" #include <QJsonObject> #include <QJsonArray> #include <QJsonDocument> #include <QProcess> #include <QBuffer> static QString getPTName(const QString &device) { Helper::processExec(QStringLiteral("/sbin/blkid -p -s PTTYPE -d -i %1").arg(device)); const QByteArray &data = Helper::lastProcessStandardOutput(); if (data.isEmpty()) return QString(); const QByteArrayList &list = data.split('='); if (list.count() != 3) return QString(); return list.last().simplified(); } class DDeviceDiskInfoPrivate : public DDiskInfoPrivate { public: DDeviceDiskInfoPrivate(DDeviceDiskInfo *qq); ~DDeviceDiskInfoPrivate(); void init(const QJsonObject &obj); QString filePath() const Q_DECL_OVERRIDE; void refresh() Q_DECL_OVERRIDE; bool hasScope(DDiskInfo::DataScope scope, DDiskInfo::ScopeMode mode, int index = 0) const Q_DECL_OVERRIDE; bool openDataStream(int index) Q_DECL_OVERRIDE; void closeDataStream() Q_DECL_OVERRIDE; // Unfulfilled qint64 readableDataSize(DDiskInfo::DataScope scope) const Q_DECL_OVERRIDE; qint64 totalReadableDataSize() const Q_DECL_OVERRIDE; qint64 maxReadableDataSize() const Q_DECL_OVERRIDE; qint64 totalWritableDataSize() const Q_DECL_OVERRIDE; qint64 read(char *data, qint64 maxSize) Q_DECL_OVERRIDE; qint64 write(const char *data, qint64 maxSize) Q_DECL_OVERRIDE; bool atEnd() const Q_DECL_OVERRIDE; QString errorString() const Q_DECL_OVERRIDE; bool isClosing() const; QProcess *process = NULL; QBuffer buffer; bool closing = false; }; DDeviceDiskInfoPrivate::DDeviceDiskInfoPrivate(DDeviceDiskInfo *qq) : DDiskInfoPrivate(qq) { } DDeviceDiskInfoPrivate::~DDeviceDiskInfoPrivate() { closeDataStream(); if (process) process->deleteLater(); } void DDeviceDiskInfoPrivate::init(const QJsonObject &obj) { model = obj.value("model").toString(); name = obj.value("name").toString(); kname = obj.value("kname").toString(); size = obj.value("size").toString().toLongLong(); typeName = obj.value("type").toString(); readonly = obj.value("ro").toString() == "1" || typeName == "rom"; removeable = obj.value("rm").toString() == "1"; transport = obj.value("tran").toString(); serial = obj.value("serial").toString(); if (obj.value("pkname").isNull()) type = DDiskInfo::Disk; else type = DDiskInfo::Part; const QJsonArray &list = obj.value("children").toArray(); QStringList children_uuids; for (const QJsonValue &part : list) { const QJsonObject &obj = part.toObject(); const QString &uuid = obj.value("partuuid").toString(); if (!uuid.isEmpty() && children_uuids.contains(uuid)) continue; DDevicePartInfo info; info.init(obj); if (!info.partUUID().isEmpty() && children_uuids.contains(info.partUUID())) continue; info.d->transport = transport; children << info; children_uuids << info.partUUID(); } qSort(children.begin(), children.end(), [] (const DPartInfo &info1, const DPartInfo &info2) { return info1.sizeStart() < info2.sizeStart(); }); if (type == DDiskInfo::Disk) ptTypeName = getPTName(name); else ptTypeName = getPTName(obj.value("pkname").toString()); if (ptTypeName == "dos") { ptType = DDiskInfo::MBR; } else if (ptTypeName == "gpt") { ptType = DDiskInfo::GPT; } else { ptType = DDiskInfo::Unknow; havePartitionTable = false; } if (type == DDiskInfo::Part) havePartitionTable = false; if ((!havePartitionTable && children.isEmpty()) || type == DDiskInfo::Part) { DDevicePartInfo info; info.init(obj); info.d->transport = transport; info.d->index = 0; children << info; } } QString DDeviceDiskInfoPrivate::filePath() const { return name; } void DDeviceDiskInfoPrivate::refresh() { children.clear(); const QJsonArray &block_devices = Helper::getBlockDevices(name); if (!block_devices.isEmpty()) init(block_devices.first().toObject()); } bool DDeviceDiskInfoPrivate::hasScope(DDiskInfo::DataScope scope, DDiskInfo::ScopeMode mode, int index) const { if (mode == DDiskInfo::Read) { if (scope == DDiskInfo::Headgear) { return havePartitionTable && (children.isEmpty() || children.first().sizeStart() >= 1048576); } else if (scope == DDiskInfo::JsonInfo) { return true; } if (scope == DDiskInfo::PartitionTable) return havePartitionTable; } else if (readonly || scope == DDiskInfo::JsonInfo) { return false; } if (scope == DDiskInfo::Partition) { if (index == 0 && mode == DDiskInfo::Write) return true; const DPartInfo &info = q->getPartByNumber(index); if (!info) { dCDebug("Can not find parition by number(device: \"%s\"): %d", qPrintable(q->filePath()), index); return false; } if (info.isExtended() || (mode == DDiskInfo::Read && info.type() == DPartInfo::Unknow && info.fileSystemType() == DPartInfo::Invalid && info.guidType() == DPartInfo::InvalidGUID)) { dCDebug("Skip the \"%s\" partition, type: %s", qPrintable(info.filePath()), qPrintable(info.typeDescription(info.type()))); return false; } return mode != DDiskInfo::Write || !info.isReadonly(); } return (scope == DDiskInfo::Headgear || scope == DDiskInfo::PartitionTable) ? type == DDiskInfo::Disk : true; } bool DDeviceDiskInfoPrivate::openDataStream(int index) { if (process) { process->deleteLater(); } process = new QProcess(); QObject::connect(process, static_cast<void (QProcess::*)(int, QProcess::ExitStatus)>(&QProcess::finished), process, [this] (int code, QProcess::ExitStatus status) { if (isClosing()) return; if (status == QProcess::CrashExit) { setErrorString(QObject::tr("process \"%1 %2\" crashed").arg(process->program()).arg(process->arguments().join(" "))); } else if (code != 0) { setErrorString(QObject::tr("Failed to perform process \"%1 %2\", error: %3").arg(process->program()).arg(process->arguments().join(" ")).arg(QString::fromUtf8(process->readAllStandardError()))); } }); switch (currentScope) { case DDiskInfo::Headgear: { if (type != DDiskInfo::Disk) { setErrorString(QObject::tr("\"%1\" is not a disk device").arg(filePath())); return false; } if (currentMode == DDiskInfo::Read) { process->start(QStringLiteral("dd if=%1 bs=512 count=2048 status=none").arg(filePath()), QIODevice::ReadOnly); } else { process->start(QStringLiteral("dd of=%1 bs=512 status=none conv=fsync").arg(filePath())); } break; } case DDiskInfo::PartitionTable: { if (type != DDiskInfo::Disk) { setErrorString(QObject::tr("\"%1\" is not a disk device").arg(filePath())); return false; } if (currentMode == DDiskInfo::Read) process->start(QStringLiteral("sfdisk -d %1").arg(filePath()), QIODevice::ReadOnly); else process->start(QStringLiteral("sfdisk %1 --no-reread").arg(filePath())); break; } case DDiskInfo::Partition: { const DPartInfo &part = (index == 0 && currentMode == DDiskInfo::Write) ? DDevicePartInfo(filePath()) : q->getPartByNumber(index); if (!part) { dCDebug("Part is null(index: %d)", index); return false; } dCDebug("Try open device: %s, mode: %s", qPrintable(part.filePath()), currentMode == DDiskInfo::Read ? "Read" : "Write"); if (Helper::isMounted(part.filePath())) { if (Helper::umountDevice(part.filePath())) { part.d->mountPoint.clear(); } else { setErrorString(QObject::tr("\"%1\" is busy").arg(part.filePath())); return false; } } if (currentMode == DDiskInfo::Read) { const QString &executer = Helper::getPartcloneExecuter(part); process->start(QStringLiteral("%1 -s %2 -o - -c -z %3 -L /tmp/partclone.log").arg(executer).arg(part.filePath()).arg(Global::bufferSize), QIODevice::ReadOnly); } else { process->start(QStringLiteral("partclone.restore -s - -o %2 -z %3 -L /tmp/partclone.log").arg(part.filePath()).arg(Global::bufferSize)); } break; } case DDiskInfo::JsonInfo: { process->deleteLater(); process = 0; buffer.setData(q->toJson()); break; } default: return false; } if (process) { if (!process->waitForStarted()) { setErrorString(QObject::tr("Failed to start \"%1 %2\", error: %3").arg(process->program()).arg(process->arguments().join(" ")).arg(process->errorString())); return false; } dCDebug("The \"%s %s\" command start finished", qPrintable(process->program()), qPrintable(process->arguments().join(" "))); } bool ok = process ? process->isOpen() : buffer.open(QIODevice::ReadOnly); if (!ok) { setErrorString(QObject::tr("Failed to open process, error: %1").arg(process ? process->errorString(): buffer.errorString())); } return ok; } void DDeviceDiskInfoPrivate::closeDataStream() { closing = true; if (process) { if (process->state() != QProcess::NotRunning) { if (currentMode == DDiskInfo::Read) { process->closeReadChannel(QProcess::StandardOutput); process->terminate(); } else { process->closeWriteChannel(); } while (process->state() != QProcess::NotRunning) { QThread::currentThread()->sleep(1); if (!QFile::exists(QString("/proc/%2").arg(process->pid()))) { process->waitForFinished(-1); if (process->error() == QProcess::Timedout) process->QIODevice::d_func()->errorString.clear(); break; } } } dCDebug("Process exit code: %d(%s %s)", process->exitCode(), qPrintable(process->program()), qPrintable(process->arguments().join(' '))); } if (currentMode == DDiskInfo::Write && currentScope == DDiskInfo::PartitionTable) { Helper::umountDevice(filePath()); if (Helper::refreshSystemPartList(filePath())) { refresh(); } else { dCWarning("Refresh the devcie %s failed", qPrintable(filePath())); } } if (currentScope == DDiskInfo::JsonInfo) buffer.close(); closing = false; } qint64 DDeviceDiskInfoPrivate::readableDataSize(DDiskInfo::DataScope scope) const { Q_UNUSED(scope) return -1; } qint64 DDeviceDiskInfoPrivate::totalReadableDataSize() const { qint64 size = 0; if (hasScope(DDiskInfo::PartitionTable, DDiskInfo::Read)) { if (hasScope(DDiskInfo::Headgear, DDiskInfo::Read)) { size += 1048576; } else if (!children.isEmpty()) { size += children.first().sizeStart(); } if (ptType == DDiskInfo::MBR) { size += 512; } else if (ptType == DDiskInfo::GPT) { size += 17408; size += 16896; } } for (const DPartInfo &part : children) { if (!part.isExtended()) size += part.usedSize(); } return size; } qint64 DDeviceDiskInfoPrivate::maxReadableDataSize() const { if (children.isEmpty()) { return totalReadableDataSize(); } if (type == DDiskInfo::Disk) return children.last().sizeEnd() + 1; return children.first().totalSize(); } qint64 DDeviceDiskInfoPrivate::totalWritableDataSize() const { return size; } qint64 DDeviceDiskInfoPrivate::read(char *data, qint64 maxSize) { if (!process) { return buffer.read(data, maxSize); } process->waitForReadyRead(-1); if (process->bytesAvailable() > Global::bufferSize) { dCWarning("The \"%s %s\" process bytes available: %s", qPrintable(process->program()), qPrintable(process->arguments().join(" ")), qPrintable(Helper::sizeDisplay(process->bytesAvailable()))); } return process->read(data, maxSize); } qint64 DDeviceDiskInfoPrivate::write(const char *data, qint64 maxSize) { if (!process) return -1; if (process->state() != QProcess::Running) return -1; qint64 size = process->write(data, maxSize); QElapsedTimer timer; timer.start(); int timeout = 5000; while (process->state() == QProcess::Running && process->bytesToWrite() > 0) { process->waitForBytesWritten(); if (timer.elapsed() > timeout) { timeout += 5000; dCWarning("Wait for bytes written timeout, elapsed: %lld, bytes to write: %lld", timer.elapsed(), process->bytesToWrite()); } } return size; } bool DDeviceDiskInfoPrivate::atEnd() const { if (!process) { return buffer.atEnd(); } process->waitForReadyRead(-1); return process->atEnd(); } QString DDeviceDiskInfoPrivate::errorString() const { if (error.isEmpty()) { if (process) { if (process->error() == QProcess::UnknownError) return QString(); return QString("%1 %2: %3").arg(process->program()).arg(process->arguments().join(' ')).arg(process->errorString()); } if (!buffer.QIODevice::d_func()->errorString.isEmpty()) return buffer.errorString(); } return error; } bool DDeviceDiskInfoPrivate::isClosing() const { return closing; } DDeviceDiskInfo::DDeviceDiskInfo() { } DDeviceDiskInfo::DDeviceDiskInfo(const QString &filePath) { const QJsonArray &block_devices = Helper::getBlockDevices(filePath); if (!block_devices.isEmpty()) { const QJsonObject &obj = block_devices.first().toObject(); d = new DDeviceDiskInfoPrivate(this); d_func()->init(obj); if (d->type == Part) { const QJsonArray &parent = Helper::getBlockDevices(obj.value("pkname").toString()); if (!parent.isEmpty()) { const QJsonObject &parent_obj = parent.first().toObject(); d->transport = parent_obj.value("tran").toString(); d->model = parent_obj.value("model").toString(); d->serial = parent_obj.value("serial").toString(); } if (!d->children.isEmpty()) d->children.first().d->transport = d->transport; } } } QList<DDeviceDiskInfo> DDeviceDiskInfo::localeDiskList() { const QJsonArray &block_devices = Helper::getBlockDevices(); QList<DDeviceDiskInfo> list; for (const QJsonValue &value : block_devices) { const QJsonObject &obj = value.toObject(); if (Global::disableLoopDevice && obj.value("type").toString() == "loop") continue; DDeviceDiskInfo info; info.d = new DDeviceDiskInfoPrivate(&info); info.d_func()->init(obj); list << info; } return list; }
./CrossVul/dataset_final_sorted/CWE-59/cpp/bad_915_0
crossvul-cpp_data_good_436_3
/* * Soft: Keepalived is a failover program for the LVS project * <www.linuxvirtualserver.org>. It monitor & manipulate * a loadbalanced server pool using multi-layer checks. * * Part: DBus server thread for VRRP * * Author: Alexandre Cassen, <acassen@linux-vs.org> * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. * * Copyright (C) 2016-2017 Alexandre Cassen, <acassen@gmail.com> */ /* See https://git.gnome.org/browse/glib/tree/gio/tests/fdbus-example-server.c * and https://developer.gnome.org/gio/stable/GDBusConnection.html#gdbus-server * for examples of coding. * * Create a general /org/keepalived/Vrrp1/Vrrp DBus * object and a /org/keepalived/Vrrp1/Instance/#interface#/#group# object for * each VRRP instance. * Interface org.keepalived.Vrrp1.Vrrp implements methods PrintData, * PrintStats and signal VrrpStopped. * Interface com.keepalived.Vrrp1.Instance implements method SendGarp * (sends a single Gratuitous ARP from the given Instance), * signal VrrpStatusChange, and properties Name and State (retrievable * through calls to org.freedesktop.DBus.Properties.Get) * * Interface files need to be installed in /usr/share/dbus-1/interfaces/ * A policy file, which determines who has access to the service, is * installed in /etc/dbus-1/system.d/. Sources for the policy and interface * files are in keepalived/dbus. * * To test the DBus service run a command like: dbus-send --system --dest=org.keepalived.Vrrp1 --print-reply object interface.method type:argument * e.g. * dbus-send --system --dest=org.keepalived.Vrrp1 --print-reply /org/keepalived/Vrrp1/Vrrp org.keepalived.Vrrp1.Vrrp.PrintData * or * dbus-send --system --dest=org.keepalived.Vrrp1 --print-reply /org/keepalived/Vrrp1/Instance/eth0/1/IPv4 org.freedesktop.DBus.Properties.Get string:'org.keepalived.Vrrp1.Instance' string:'State' * * To monitor signals, run: * dbus-monitor --system type='signal' * * d-feet is a useful program for interfacing with DBus */ #include "config.h" #include <errno.h> #include <pthread.h> #include <semaphore.h> #include <gio/gio.h> #include <ctype.h> #include <fcntl.h> #include <sys/types.h> #include <stdlib.h> #include <stdint.h> #include "vrrp_dbus.h" #include "vrrp_data.h" #include "vrrp_print.h" #include "global_data.h" #include "main.h" #include "logger.h" #include "utils.h" #ifdef THREAD_DUMP #include "scheduler.h" #endif typedef enum dbus_action { DBUS_ACTION_NONE, DBUS_PRINT_DATA, DBUS_PRINT_STATS, DBUS_RELOAD, #ifdef _WITH_DBUS_CREATE_INSTANCE_ DBUS_CREATE_INSTANCE, DBUS_DESTROY_INSTANCE, #endif DBUS_SEND_GARP, DBUS_GET_NAME, DBUS_GET_STATUS, } dbus_action_t; typedef enum dbus_error { DBUS_SUCCESS, DBUS_INTERFACE_NOT_FOUND, DBUS_OBJECT_ALREADY_EXISTS, DBUS_INTERFACE_TOO_LONG, DBUS_INSTANCE_NOT_FOUND, } dbus_error_t; typedef struct dbus_queue_ent { dbus_action_t action; dbus_error_t reply; char *ifname; uint8_t vrid; uint8_t family; GVariant *args; } dbus_queue_ent_t; /* Global file variables */ static GDBusNodeInfo *vrrp_introspection_data = NULL; static GDBusNodeInfo *vrrp_instance_introspection_data = NULL; static GDBusConnection *global_connection; static GHashTable *objects; static GMainLoop *loop; /* Data passing between main vrrp thread and dbus thread */ dbus_queue_ent_t *ent_ptr; static int dbus_in_pipe[2], dbus_out_pipe[2]; static sem_t thread_end; /* The only characters that are valid in a dbus path are A-Z, a-z, 0-9, _ */ static char * set_valid_path(char *valid_path, const char *path) { const char *str_in; char *str_out; for (str_in = path, str_out = valid_path; *str_in; str_in++, str_out++) { if (!isalnum(*str_in)) *str_out = '_'; else *str_out = *str_in; } *str_out = '\0'; return valid_path; } static bool valid_path_cmp(const char *path, const char *valid_path) { for ( ; *path && *valid_path; path++, valid_path++) { if (!isalnum(*path)) { if (*valid_path != '_') return true; } else if (*path != *valid_path) return true; } return *path != *valid_path; } static const char * family_str(int family) { if (family == AF_INET) return "IPv4"; if (family == AF_INET6) return "IPv6"; return "None"; } static const char * state_str(int state) { switch (state) { case VRRP_STATE_INIT: return "Init"; case VRRP_STATE_BACK: return "Backup"; case VRRP_STATE_MAST: return "Master"; case VRRP_STATE_FAULT: return "Fault"; } return "Unknown"; } static vrrp_t * get_vrrp_instance(const char *ifname, int vrid, int family) { element e; vrrp_t *vrrp; if (LIST_ISEMPTY(vrrp_data->vrrp)) return NULL; for (e = LIST_HEAD(vrrp_data->vrrp); e; ELEMENT_NEXT(e)) { vrrp = ELEMENT_DATA(e); if (vrrp->vrid == vrid && vrrp->family == family && !valid_path_cmp(IF_BASE_IFP(vrrp->ifp)->ifname, ifname)) return vrrp; } return NULL; } static gboolean unregister_object(gpointer key, gpointer value, __attribute__((unused)) gpointer user_data) { if (g_hash_table_remove(objects, key)) return g_dbus_connection_unregister_object(global_connection, GPOINTER_TO_UINT(value)); return false; } static gchar * dbus_object_create_path_vrrp(void) { return g_strconcat(DBUS_VRRP_OBJECT_ROOT, #if HAVE_DECL_CLONE_NEWNET global_data->network_namespace ? "/" : "", global_data->network_namespace ? global_data->network_namespace : "", #endif global_data->instance_name ? "/" : "", global_data->instance_name ? global_data->instance_name : "", "/Vrrp", NULL); } static gchar * dbus_object_create_path_instance(const gchar *interface, int vrid, sa_family_t family) { gchar *object_path; char standardized_name[sizeof ((vrrp_t*)NULL)->ifp->ifname]; gchar *vrid_str = g_strdup_printf("%d", vrid); set_valid_path(standardized_name, interface); object_path = g_strconcat(DBUS_VRRP_OBJECT_ROOT, #if HAVE_DECL_CLONE_NEWNET global_data->network_namespace ? "/" : "", global_data->network_namespace ? global_data->network_namespace : "", #endif global_data->instance_name ? "/" : "", global_data->instance_name ? global_data->instance_name : "", "/Instance/", standardized_name, "/", vrid_str, "/", family_str(family), NULL); g_free(vrid_str); return object_path; } static dbus_queue_ent_t * process_method_call(dbus_queue_ent_t *ent) { ssize_t ret; if (!ent) return NULL; /* Tell the main thread that a queue entry is waiting. Any data works */ ent_ptr = ent; if (write(dbus_in_pipe[1], ent, 1) != 1) log_message(LOG_INFO, "Write from DBus thread to main thread failed"); /* Wait for a response */ while ((ret = read(dbus_out_pipe[0], ent, 1)) == -1 && errno == EINTR) { log_message(LOG_INFO, "dbus_out_pipe read returned EINTR"); } if (ret == -1) log_message(LOG_INFO, "DBus response read error - errno = %d", errno); #ifdef DBUS_DEBUG if (ent->reply != DBUS_SUCCESS) { char *iname; if (ent->reply == DBUS_INTERFACE_NOT_FOUND) log_message(LOG_INFO, "Unable to find DBus requested instance %s/%d/%s", ent->ifname, ent->vrid, family_str(ent->family)); else if (ent->reply == DBUS_OBJECT_ALREADY_EXISTS) log_message(LOG_INFO, "Unable to create DBus requested object with instance %s/%d/%s", ent->ifname, ent->vrid, family_str(ent->family)); else if (ent->reply == DBUS_INSTANCE_NOT_FOUND) { g_variant_get(ent->args, "(s)", &iname); log_message(LOG_INFO, "Unable to find DBus requested instance %s", iname); } else log_message(LOG_INFO, "Unknown DBus reply %d", ent->reply); } #endif return ent; } static void get_interface_ids(const gchar *object_path, gchar *interface, uint8_t *vrid, uint8_t *family) { int path_length = DBUS_VRRP_INSTANCE_PATH_DEFAULT_LENGTH; gchar **dirs; char *endptr; #if HAVE_DECL_CLONE_NEWNET if(global_data->network_namespace) path_length++; #endif if(global_data->instance_name) path_length++; /* object_path will have interface, vrid and family as * the third to last, second to last and last levels */ dirs = g_strsplit(object_path, "/", path_length); strcpy(interface, dirs[path_length-3]); *vrid = (uint8_t)strtoul(dirs[path_length-2], &endptr, 10); if (*endptr) log_message(LOG_INFO, "Dbus unexpected characters '%s' at end of number '%s'", endptr, dirs[path_length-2]); *family = !g_strcmp0(dirs[path_length-1], "IPv4") ? AF_INET : !g_strcmp0(dirs[path_length-1], "IPv6") ? AF_INET6 : AF_UNSPEC; /* We are finished with all the object_path strings now */ g_strfreev(dirs); } /* handles reply to org.freedesktop.DBus.Properties.Get method on any object*/ static GVariant * handle_get_property(__attribute__((unused)) GDBusConnection *connection, __attribute__((unused)) const gchar *sender, const gchar *object_path, const gchar *interface_name, const gchar *property_name, GError **error, __attribute__((unused)) gpointer user_data) { GVariant *ret = NULL; dbus_queue_ent_t ent; char ifname_str[sizeof ((vrrp_t*)NULL)->ifp->ifname]; int action; if (g_strcmp0(interface_name, DBUS_VRRP_INSTANCE_INTERFACE)) { log_message(LOG_INFO, "Interface %s has not been implemented yet", interface_name); return NULL; } if (!g_strcmp0(property_name, "Name")) action = DBUS_GET_NAME; else if (!g_strcmp0(property_name, "State")) action = DBUS_GET_STATUS; else { log_message(LOG_INFO, "Property %s does not exist", property_name); return NULL; } get_interface_ids(object_path, ifname_str, &ent.vrid, &ent.family); ent.action = action; ent.ifname = ifname_str; ent.args = NULL; process_method_call(&ent); if (ent.reply == DBUS_SUCCESS) ret = ent.args; else g_set_error(error, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS, "Instance '%s/%d/%s' not found", ifname_str, ent.vrid, family_str(ent.family)); return ret; } /* handles method_calls on any object */ static void handle_method_call(__attribute__((unused)) GDBusConnection *connection, __attribute__((unused)) const gchar *sender, const gchar *object_path, const gchar *interface_name, const gchar *method_name, #ifndef _WITH_DBUS_CREATE_INSTANCE_ __attribute__((unused)) #endif GVariant *parameters, GDBusMethodInvocation *invocation, __attribute__((unused)) gpointer user_data) { #ifdef _WITH_DBUS_CREATE_INSTANCE_ char *iname; char *ifname; size_t len; unsigned family; #endif dbus_queue_ent_t ent; char ifname_str[sizeof ((vrrp_t*)NULL)->ifp->ifname]; if (!g_strcmp0(interface_name, DBUS_VRRP_INTERFACE)) { if (!g_strcmp0(method_name, "PrintData")) { ent.action = DBUS_PRINT_DATA; process_method_call(&ent); g_dbus_method_invocation_return_value(invocation, NULL); } else if (g_strcmp0(method_name, "PrintStats") == 0) { ent.action = DBUS_PRINT_STATS; process_method_call(&ent); g_dbus_method_invocation_return_value(invocation, NULL); } else if (g_strcmp0(method_name, "ReloadConfig") == 0) { g_dbus_method_invocation_return_value(invocation, NULL); kill(getppid(), SIGHUP); } #ifdef _WITH_DBUS_CREATE_INSTANCE_ else if (g_strcmp0(method_name, "CreateInstance") == 0) { g_variant_get(parameters, "(ssuu)", &iname, &ifname, &ent.vrid, &family); len = strlen(ifname); if (len == 0 || len >= IFNAMSIZ) { log_message(LOG_INFO, "Interface name '%s' too long for CreateInstance", ifname); g_dbus_method_invocation_return_error(invocation, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS, "Interface name empty or too long"); return; } ent.action = DBUS_CREATE_INSTANCE; ent.ifname = ifname; ent.family = family == 4 ? AF_INET : family == 6 ? AF_INET6 : AF_UNSPEC; ent.args = g_variant_new("(s)", iname); process_method_call(&ent); g_variant_unref(ent.args); g_dbus_method_invocation_return_value(invocation, NULL); } else if (g_strcmp0(method_name, "DestroyInstance") == 0) { // TODO - this should be on the instance ent.action = DBUS_DESTROY_INSTANCE; ent.args = parameters; process_method_call(&ent); if (ent.reply == DBUS_INSTANCE_NOT_FOUND) { g_variant_get(parameters, "(s)", &iname); g_dbus_method_invocation_return_error(invocation, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS, "Instance '%s' not found", iname); } else g_dbus_method_invocation_return_value(invocation, NULL); } #endif else { log_message(LOG_INFO, "Method %s has not been implemented yet", method_name); g_dbus_method_invocation_return_error(invocation, G_DBUS_ERROR, G_DBUS_ERROR_MATCH_RULE_NOT_FOUND, "Method not implemented"); } return; } if (!g_strcmp0(interface_name, DBUS_VRRP_INSTANCE_INTERFACE)) { if (!g_strcmp0(method_name, "SendGarp")) { get_interface_ids(object_path, ifname_str, &ent.vrid, &ent.family); ent.action = DBUS_SEND_GARP; ent.ifname = ifname_str; process_method_call(&ent); if (ent.reply == DBUS_INTERFACE_NOT_FOUND) g_dbus_method_invocation_return_error(invocation, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS, "Instance '%s/%d/%s' not found", ifname_str, ent.vrid, family_str(ent.family)); else g_dbus_method_invocation_return_value(invocation, NULL); } else { log_message(LOG_INFO, "Method %s has not been implemented yet", method_name); g_dbus_method_invocation_return_error(invocation, G_DBUS_ERROR, G_DBUS_ERROR_MATCH_RULE_NOT_FOUND, "Method not implemented"); } return; } log_message(LOG_INFO, "Interface %s has not been implemented yet", interface_name); g_dbus_method_invocation_return_error(invocation, G_DBUS_ERROR, G_DBUS_ERROR_MATCH_RULE_NOT_FOUND, "Interface not implemented"); } static const GDBusInterfaceVTable interface_vtable = { handle_method_call, handle_get_property, NULL, /* handle_set_property is null because we have no writeable property */ {} }; static int dbus_create_object_params(char *instance_name, const char *interface_name, int vrid, sa_family_t family, bool log_success) { gchar *object_path; GError *local_error = NULL; if (g_hash_table_lookup(objects, instance_name)) { log_message(LOG_INFO, "An object for instance %s already exists", instance_name); return DBUS_OBJECT_ALREADY_EXISTS; } object_path = dbus_object_create_path_instance(interface_name, vrid, family); guint instance = g_dbus_connection_register_object(global_connection, object_path, vrrp_instance_introspection_data->interfaces[0], &interface_vtable, NULL, NULL, &local_error); if (local_error != NULL) { log_message(LOG_INFO, "Registering DBus object on %s failed: %s", object_path, local_error->message); g_clear_error(&local_error); } if (instance) { g_hash_table_insert(objects, instance_name, GUINT_TO_POINTER(instance)); if (log_success) log_message(LOG_INFO, "Added DBus object for instance %s on path %s", instance_name, object_path); } g_free(object_path); return DBUS_SUCCESS; } static void dbus_create_object(vrrp_t *vrrp) { dbus_create_object_params(vrrp->iname, IF_NAME(IF_BASE_IFP(vrrp->ifp)), vrrp->vrid, vrrp->family, false); } static bool dbus_emit_signal(GDBusConnection *connection, const gchar *object_path, const gchar *interface_name, const gchar *signal_name, GVariant *parameters) { GError *local_error = NULL; g_dbus_connection_emit_signal(connection, NULL, object_path, interface_name, signal_name, parameters, &local_error); if (local_error != NULL) { log_message(LOG_INFO, "Emitting DBus signal %s.%s on %s failed: %s", interface_name, signal_name, object_path, local_error->message); g_clear_error(&local_error); return false; } return true; } /* first function to be run when trying to own bus, * exports objects to the bus */ static void on_bus_acquired(GDBusConnection *connection, const gchar *name, __attribute__((unused)) gpointer user_data) { global_connection = connection; gchar *path; element e; GError *local_error = NULL; log_message(LOG_INFO, "Acquired DBus bus %s", name); /* register VRRP object */ path = dbus_object_create_path_vrrp(); guint vrrp = g_dbus_connection_register_object(connection, path, vrrp_introspection_data->interfaces[0], &interface_vtable, NULL, NULL, &local_error); g_hash_table_insert(objects, "__Vrrp__", GUINT_TO_POINTER(vrrp)); g_free(path); if (local_error != NULL) { log_message(LOG_INFO, "Registering VRRP object on %s failed: %s", path, local_error->message); g_clear_error(&local_error); } /* for each available VRRP instance, register an object */ if (LIST_ISEMPTY(vrrp_data->vrrp)) return; for (e = LIST_HEAD(vrrp_data->vrrp); e; ELEMENT_NEXT(e)) { vrrp_t * vrrp = ELEMENT_DATA(e); dbus_create_object(vrrp); } /* Send a signal to say we have started */ path = dbus_object_create_path_vrrp(); dbus_emit_signal(global_connection, path, DBUS_VRRP_INTERFACE, "VrrpStarted", NULL); g_free(path); /* Notify DBus of the state of our instances */ for (e = LIST_HEAD(vrrp_data->vrrp); e; ELEMENT_NEXT(e)) { vrrp_t * vrrp = ELEMENT_DATA(e); dbus_send_state_signal(vrrp); } } /* run if bus name is acquired successfully */ static void on_name_acquired(__attribute__((unused)) GDBusConnection *connection, const gchar *name, __attribute__((unused)) gpointer user_data) { log_message(LOG_INFO, "Acquired the name %s on the session bus", name); } /* run if bus name or connection are lost */ static void on_name_lost(GDBusConnection *connection, const gchar *name, __attribute__((unused)) gpointer user_data) { log_message(LOG_INFO, "Lost the name %s on the session bus", name); global_connection = connection; g_hash_table_foreach_remove(objects, unregister_object, NULL); objects = NULL; global_connection = NULL; } static gchar* read_file(gchar* filepath) { FILE * f; size_t length; gchar *ret = NULL; f = fopen(filepath, "r"); if (f) { fseek(f, 0, SEEK_END); length = (size_t)ftell(f); fseek(f, 0, SEEK_SET); /* We can't use MALLOC since it isn't thread safe */ ret = MALLOC(length + 1); if (ret) { if (fread(ret, length, 1, f) != 1) { log_message(LOG_INFO, "Failed to read all of %s", filepath); } ret[length] = '\0'; } else log_message(LOG_INFO, "Unable to read Dbus file %s", filepath); fclose(f); } return ret; } static void * dbus_main(__attribute__ ((unused)) void *unused) { gchar *introspection_xml; guint owner_id; const char *service_name; objects = g_hash_table_new(g_str_hash, g_str_equal); /* DBus service org.keepalived.Vrrp1 exposes two interfaces, Vrrp and Instance. * Vrrp is implemented by a single VRRP object for general purposes, such as printing * data or signaling that the VRRP process has been stopped. * Instance is implemented by an Instance object for every VRRP Instance in vrrp_data. * It exposes instance specific methods and properties. */ #ifdef DBUS_NEED_G_TYPE_INIT g_type_init(); #endif GError *error = NULL; /* read service interface data from xml files */ introspection_xml = read_file(DBUS_VRRP_INTERFACE_FILE_PATH); if (!introspection_xml) return NULL; vrrp_introspection_data = g_dbus_node_info_new_for_xml(introspection_xml, &error); FREE(introspection_xml); if (error != NULL) { log_message(LOG_INFO, "Parsing DBus interface %s from file %s failed: %s", DBUS_VRRP_INTERFACE, DBUS_VRRP_INTERFACE_FILE_PATH, error->message); g_clear_error(&error); return NULL; } introspection_xml = read_file(DBUS_VRRP_INSTANCE_INTERFACE_FILE_PATH); if (!introspection_xml) return NULL; vrrp_instance_introspection_data = g_dbus_node_info_new_for_xml(introspection_xml, &error); FREE(introspection_xml); if (error != NULL) { log_message(LOG_INFO, "Parsing DBus interface %s from file %s failed: %s", DBUS_VRRP_INSTANCE_INTERFACE, DBUS_VRRP_INSTANCE_INTERFACE_FILE_PATH, error->message); g_clear_error(&error); return NULL; } service_name = global_data->dbus_service_name ? global_data->dbus_service_name : DBUS_SERVICE_NAME; owner_id = g_bus_own_name(G_BUS_TYPE_SYSTEM, service_name, G_BUS_NAME_OWNER_FLAGS_NONE, on_bus_acquired, on_name_acquired, on_name_lost, NULL, /* user_data */ NULL); /* user_data_free_func */ loop = g_main_loop_new(NULL, FALSE); g_main_loop_run(loop); /* cleanup after loop terminates */ g_main_loop_unref(loop); g_bus_unown_name(owner_id); global_connection = NULL; sem_post(&thread_end); pthread_exit(0); } /* The following functions are run in the context of the main vrrp thread */ /* send signal VrrpStatusChange * containing the new state of vrrp */ void dbus_send_state_signal(vrrp_t *vrrp) { gchar *object_path; GVariant *args; /* the interface will go through the initial state changes before * the main loop can be started and global_connection initialised */ if (global_connection == NULL) return; object_path = dbus_object_create_path_instance(IF_NAME(IF_BASE_IFP(vrrp->ifp)), vrrp->vrid, vrrp->family); args = g_variant_new("(u)", vrrp->state); dbus_emit_signal(global_connection, object_path, DBUS_VRRP_INSTANCE_INTERFACE, "VrrpStatusChange", args); g_free(object_path); } /* send signal VrrpRestarted */ static void dbus_send_reload_signal(void) { gchar *path; if (global_connection == NULL) return; path = dbus_object_create_path_vrrp(); dbus_emit_signal(global_connection, path, DBUS_VRRP_INTERFACE, "VrrpReloaded", NULL); g_free(path); } static gboolean dbus_unregister_object(char *str) { gboolean ret = false; gpointer value = g_hash_table_lookup(objects, str); if (value) { ret = unregister_object(str, value, NULL); log_message(LOG_INFO, "Deleted DBus object for instance %s", str); } #ifdef DBUS_DEBUG else log_message(LOG_INFO, "DBus object not found for instance %s", str); #endif return ret; } void dbus_remove_object(vrrp_t *vrrp) { dbus_unregister_object(vrrp->iname); } static int handle_dbus_msg(__attribute__((unused)) thread_t *thread) { dbus_queue_ent_t *ent; char recv_buf; vrrp_t *vrrp; #ifdef _WITH_DBUS_CREATE_INSTANCE_ gchar *name; #endif if (read(dbus_in_pipe[0], &recv_buf, 1) != 1) log_message(LOG_INFO, "Read from DBus thread to vrrp thread failed"); if ((ent = ent_ptr) != NULL) { ent->reply = DBUS_SUCCESS; if (ent->action == DBUS_PRINT_DATA) { log_message(LOG_INFO, "Printing VRRP data on DBus request"); vrrp_print_data(); } else if (ent->action == DBUS_PRINT_STATS) { log_message(LOG_INFO, "Printing VRRP stats on DBus request"); vrrp_print_stats(); } #ifdef _WITH_DBUS_CREATE_INSTANCE_ else if (ent->action == DBUS_CREATE_INSTANCE) { g_variant_get(ent->args, "(s)", &name); ent->reply = dbus_create_object_params(name, ent->ifname, ent->vrid, ent->family, true); } else if (ent->action == DBUS_DESTROY_INSTANCE) { g_variant_get(ent->args, "(s)", &name); if (!dbus_unregister_object(name)) ent->reply = DBUS_INSTANCE_NOT_FOUND; } #endif else if (ent->action == DBUS_SEND_GARP) { ent->reply = DBUS_INTERFACE_NOT_FOUND; vrrp = get_vrrp_instance(ent->ifname, ent->vrid, ent->family); if (vrrp) { log_message(LOG_INFO, "Sending garps on %s on DBus request", vrrp->iname); vrrp_send_link_update(vrrp, 1); ent->reply = DBUS_SUCCESS; } } else if (ent->action == DBUS_GET_NAME || ent->action == DBUS_GET_STATUS) { /* we look for the vrrp instance object that corresponds to our interface and group */ ent->reply = DBUS_INTERFACE_NOT_FOUND; vrrp = get_vrrp_instance(ent->ifname, ent->vrid, ent->family); if (vrrp) { /* the property_name argument is the property we want to Get */ if (ent->action == DBUS_GET_NAME) ent->args = g_variant_new("(s)", vrrp->iname); else if (ent->action == DBUS_GET_STATUS) ent->args = g_variant_new("(us)", vrrp->state, state_str(vrrp->state)); else ent->args = NULL; /* How did we get here? */ ent->reply = DBUS_SUCCESS; } } if (write(dbus_out_pipe[1], ent, 1) != 1) log_message(LOG_INFO, "Write from main thread to DBus thread failed"); } thread_add_read(master, handle_dbus_msg, NULL, dbus_in_pipe[0], TIMER_NEVER); return 0; } void dbus_reload(list o, list n) { element e1, e2, e3; vrrp_t *vrrp_n, *vrrp_o, *vrrp_n3; if (!LIST_ISEMPTY(n)) { for (e1 = LIST_HEAD(n); e1; ELEMENT_NEXT(e1)) { char *n_name; bool match_found; vrrp_n = ELEMENT_DATA(e1); if (LIST_ISEMPTY(o)) { dbus_create_object(vrrp_n); continue; } n_name = IF_BASE_IFP(vrrp_n->ifp)->ifname; /* Try an find an instance with same vrid/family/interface that existed before and now */ for (e2 = LIST_HEAD(o), match_found = false; e2 && !match_found; ELEMENT_NEXT(e2)) { vrrp_o = ELEMENT_DATA(e2); if (vrrp_n->vrid == vrrp_o->vrid && vrrp_n->family == vrrp_o->family && !strcmp(n_name, IF_BASE_IFP(vrrp_o->ifp)->ifname)) { /* If the old instance exists in the new config, * then the dbus object will exist */ if (!strcmp(vrrp_n->iname, vrrp_o->iname)) { match_found = true; break; } /* Check if the old instance name we found still exists * (but has a different vrid/family/interface) */ for (e3 = LIST_HEAD(n); e3; ELEMENT_NEXT(e3)) { vrrp_n3 = ELEMENT_DATA(e3); if (!strcmp(vrrp_o->iname, vrrp_n3->iname)) { match_found = true; break; } } } } if (match_found) continue; dbus_create_object(vrrp_n); } } /* Signal we have reloaded */ dbus_send_reload_signal(); /* We need to reinstate the read thread */ thread_add_read(master, handle_dbus_msg, NULL, dbus_in_pipe[0], TIMER_NEVER); } bool dbus_start(void) { pthread_t dbus_thread; sigset_t sigset, cursigset; if (open_pipe(dbus_in_pipe)) { log_message(LOG_INFO, "Unable to create inbound dbus pipe - disabling DBus"); return false; } if (open_pipe(dbus_out_pipe)) { log_message(LOG_INFO, "Unable to create outbound dbus pipe - disabling DBus"); close(dbus_in_pipe[0]); close(dbus_in_pipe[1]); return false; } /* We don't want the main thread to block when using the pipes, * but the other side of the pipes should block. */ fcntl(dbus_in_pipe[1], F_SETFL, fcntl(dbus_in_pipe[1], F_GETFL) & ~O_NONBLOCK); fcntl(dbus_out_pipe[0], F_SETFL, fcntl(dbus_out_pipe[0], F_GETFL) & ~O_NONBLOCK); thread_add_read(master, handle_dbus_msg, NULL, dbus_in_pipe[0], TIMER_NEVER); /* Initialise the thread termination semaphore */ sem_init(&thread_end, 0, 0); /* Block signals (all) we don't want the new thread to process */ sigfillset(&sigset); pthread_sigmask(SIG_SETMASK, &sigset, &cursigset); /* Now create the dbus thread */ pthread_create(&dbus_thread, NULL, &dbus_main, NULL); /* Reenable our signals */ pthread_sigmask(SIG_SETMASK, &cursigset, NULL); return true; } void dbus_stop(void) { struct timespec thread_end_wait; int ret; gchar *path; if (global_connection != NULL) { path = dbus_object_create_path_vrrp(); dbus_emit_signal(global_connection, path, DBUS_VRRP_INTERFACE, "VrrpStopped", NULL); g_free(path); } g_main_loop_quit(loop); g_dbus_node_info_unref(vrrp_introspection_data); g_dbus_node_info_unref(vrrp_instance_introspection_data); clock_gettime(CLOCK_REALTIME, &thread_end_wait); thread_end_wait.tv_sec += 1; while ((ret = sem_timedwait(&thread_end, &thread_end_wait)) == -1 && errno == EINTR) ; if (ret == -1 ) { if (errno == ETIMEDOUT) log_message(LOG_INFO, "DBus thread termination timed out"); else log_message(LOG_INFO, "sem_timewait error %d", errno); } else { log_message(LOG_INFO, "Released DBus"); sem_destroy(&thread_end); } } #ifdef THREAD_DUMP void register_vrrp_dbus_addresses(void) { register_thread_address("handle_dbus_msg", handle_dbus_msg); } #endif
./CrossVul/dataset_final_sorted/CWE-59/c/good_436_3
crossvul-cpp_data_good_436_0
/* * Soft: Keepalived is a failover program for the LVS project * <www.linuxvirtualserver.org>. It monitor & manipulate * a loadbalanced server pool using multi-layer checks. * * Part: Main program structure. * * Author: Alexandre Cassen, <acassen@linux-vs.org> * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. * * Copyright (C) 2001-2017 Alexandre Cassen, <acassen@gmail.com> */ #include "config.h" #include <stdlib.h> #include <sys/utsname.h> #include <sys/resource.h> #include <stdbool.h> #ifdef HAVE_SIGNALFD #include <sys/signalfd.h> #endif #include <errno.h> #include <signal.h> #include <fcntl.h> #include <sys/wait.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <getopt.h> #include <linux/version.h> #include <ctype.h> #include "main.h" #include "global_data.h" #include "daemon.h" #include "config.h" #include "git-commit.h" #include "utils.h" #include "signals.h" #include "pidfile.h" #include "bitops.h" #include "logger.h" #include "parser.h" #include "notify.h" #include "utils.h" #ifdef _WITH_LVS_ #include "check_parser.h" #include "check_daemon.h" #endif #ifdef _WITH_VRRP_ #include "vrrp_daemon.h" #include "vrrp_parser.h" #include "vrrp_if.h" #ifdef _WITH_JSON_ #include "vrrp_json.h" #endif #endif #ifdef _WITH_BFD_ #include "bfd_daemon.h" #include "bfd_parser.h" #endif #include "global_parser.h" #if HAVE_DECL_CLONE_NEWNET #include "namespaces.h" #endif #include "scheduler.h" #include "keepalived_netlink.h" #include "git-commit.h" #if defined THREAD_DUMP || defined _EPOLL_DEBUG_ || defined _EPOLL_THREAD_DUMP_ #include "scheduler.h" #endif #include "process.h" #ifdef _TIMER_CHECK_ #include "timer.h" #endif #ifdef _SMTP_ALERT_DEBUG_ #include "smtp.h" #endif #if defined _REGEX_DEBUG_ || defined _WITH_REGEX_TIMERS_ #include "check_http.h" #endif #ifdef _TSM_DEBUG_ #include "vrrp_scheduler.h" #endif /* musl libc doesn't define the following */ #ifndef W_EXITCODE #define W_EXITCODE(ret, sig) ((ret) << 8 | (sig)) #endif #ifndef WCOREFLAG #define WCOREFLAG ((int32_t)WCOREDUMP(0xffffffff)) #endif #define VERSION_STRING PACKAGE_NAME " v" PACKAGE_VERSION " (" GIT_DATE ")" #define COPYRIGHT_STRING "Copyright(C) 2001-" GIT_YEAR " Alexandre Cassen, <acassen@gmail.com>" #define CHILD_WAIT_SECS 5 /* global var */ const char *version_string = VERSION_STRING; /* keepalived version */ char *conf_file = KEEPALIVED_CONFIG_FILE; /* Configuration file */ int log_facility = LOG_DAEMON; /* Optional logging facilities */ bool reload; /* Set during a reload */ char *main_pidfile; /* overrule default pidfile */ static bool free_main_pidfile; #ifdef _WITH_LVS_ pid_t checkers_child; /* Healthcheckers child process ID */ char *checkers_pidfile; /* overrule default pidfile */ static bool free_checkers_pidfile; #endif #ifdef _WITH_VRRP_ pid_t vrrp_child; /* VRRP child process ID */ char *vrrp_pidfile; /* overrule default pidfile */ static bool free_vrrp_pidfile; #endif #ifdef _WITH_BFD_ pid_t bfd_child; /* BFD child process ID */ char *bfd_pidfile; /* overrule default pidfile */ static bool free_bfd_pidfile; #endif unsigned long daemon_mode; /* VRRP/CHECK/BFD subsystem selection */ #ifdef _WITH_SNMP_ bool snmp; /* Enable SNMP support */ const char *snmp_socket; /* Socket to use for SNMP agent */ #endif static char *syslog_ident; /* syslog ident if not default */ bool use_pid_dir; /* Put pid files in /var/run/keepalived or @localstatedir@/run/keepalived */ unsigned os_major; /* Kernel version */ unsigned os_minor; unsigned os_release; char *hostname; /* Initial part of hostname */ #if HAVE_DECL_CLONE_NEWNET static char *override_namespace; /* If namespace specified on command line */ #endif unsigned child_wait_time = CHILD_WAIT_SECS; /* Time to wait for children to exit */ /* Log facility table */ static struct { int facility; } LOG_FACILITY[] = { {LOG_LOCAL0}, {LOG_LOCAL1}, {LOG_LOCAL2}, {LOG_LOCAL3}, {LOG_LOCAL4}, {LOG_LOCAL5}, {LOG_LOCAL6}, {LOG_LOCAL7} }; #define LOG_FACILITY_MAX ((sizeof(LOG_FACILITY) / sizeof(LOG_FACILITY[0])) - 1) /* umask settings */ bool umask_cmdline; static mode_t umask_val = S_IXUSR | S_IWGRP | S_IXGRP | S_IWOTH | S_IXOTH; /* Control producing core dumps */ static bool set_core_dump_pattern = false; static bool create_core_dump = false; static const char *core_dump_pattern = "core"; static char *orig_core_dump_pattern = NULL; /* debug flags */ #if defined _TIMER_CHECK_ || defined _SMTP_ALERT_DEBUG_ || defined _EPOLL_DEBUG_ || defined _EPOLL_THREAD_DUMP_ || defined _REGEX_DEBUG_ || defined _WITH_REGEX_TIMERS_ || defined _TSM_DEBUG_ || defined _VRRP_FD_DEBUG_ || defined _NETLINK_TIMERS_ #define WITH_DEBUG_OPTIONS 1 #endif #ifdef _TIMER_CHECK_ static char timer_debug; #endif #ifdef _SMTP_ALERT_DEBUG_ static char smtp_debug; #endif #ifdef _EPOLL_DEBUG_ static char epoll_debug; #endif #ifdef _EPOLL_THREAD_DUMP_ static char epoll_thread_debug; #endif #ifdef _REGEX_DEBUG_ static char regex_debug; #endif #ifdef _WITH_REGEX_TIMERS_ static char regex_timers; #endif #ifdef _TSM_DEBUG_ static char tsm_debug; #endif #ifdef _VRRP_FD_DEBUG_ static char vrrp_fd_debug; #endif #ifdef _NETLINK_TIMERS_ static char netlink_timer_debug; #endif void free_parent_mallocs_startup(bool am_child) { if (am_child) { #if HAVE_DECL_CLONE_NEWNET free_dirname(); #endif #ifndef _MEM_CHECK_LOG_ FREE_PTR(syslog_ident); #else free(syslog_ident); #endif syslog_ident = NULL; FREE_PTR(orig_core_dump_pattern); } if (free_main_pidfile) { FREE_PTR(main_pidfile); free_main_pidfile = false; } } void free_parent_mallocs_exit(void) { #ifdef _WITH_VRRP_ if (free_vrrp_pidfile) FREE_PTR(vrrp_pidfile); #endif #ifdef _WITH_LVS_ if (free_checkers_pidfile) FREE_PTR(checkers_pidfile); #endif #ifdef _WITH_BFD_ if (free_bfd_pidfile) FREE_PTR(bfd_pidfile); #endif FREE_PTR(config_id); } char * make_syslog_ident(const char* name) { size_t ident_len = strlen(name) + 1; char *ident; #if HAVE_DECL_CLONE_NEWNET if (global_data->network_namespace) ident_len += strlen(global_data->network_namespace) + 1; #endif if (global_data->instance_name) ident_len += strlen(global_data->instance_name) + 1; /* If we are writing MALLOC/FREE info to the log, we have * trouble FREEing the syslog_ident */ #ifndef _MEM_CHECK_LOG_ ident = MALLOC(ident_len); #else ident = malloc(ident_len); #endif if (!ident) return NULL; strcpy(ident, name); #if HAVE_DECL_CLONE_NEWNET if (global_data->network_namespace) { strcat(ident, "_"); strcat(ident, global_data->network_namespace); } #endif if (global_data->instance_name) { strcat(ident, "_"); strcat(ident, global_data->instance_name); } return ident; } static char * make_pidfile_name(const char* start, const char* instance, const char* extn) { size_t len; char *name; len = strlen(start) + 1; if (instance) len += strlen(instance) + 1; if (extn) len += strlen(extn); name = MALLOC(len); if (!name) { log_message(LOG_INFO, "Unable to make pidfile name for %s", start); return NULL; } strcpy(name, start); if (instance) { strcat(name, "_"); strcat(name, instance); } if (extn) strcat(name, extn); return name; } #ifdef _WITH_VRRP_ bool running_vrrp(void) { return (__test_bit(DAEMON_VRRP, &daemon_mode) && (global_data->have_vrrp_config || __test_bit(RUN_ALL_CHILDREN, &daemon_mode))); } #endif #ifdef _WITH_LVS_ bool running_checker(void) { return (__test_bit(DAEMON_CHECKERS, &daemon_mode) && (global_data->have_checker_config || __test_bit(RUN_ALL_CHILDREN, &daemon_mode))); } #endif #ifdef _WITH_BFD_ bool running_bfd(void) { return (__test_bit(DAEMON_BFD, &daemon_mode) && (global_data->have_bfd_config || __test_bit(RUN_ALL_CHILDREN, &daemon_mode))); } #endif static char const * find_keepalived_child_name(pid_t pid) { #ifdef _WITH_LVS_ if (pid == checkers_child) return PROG_CHECK; #endif #ifdef _WITH_VRRP_ if (pid == vrrp_child) return PROG_VRRP; #endif #ifdef _WITH_BFD_ if (pid == bfd_child) return PROG_BFD; #endif return NULL; } static vector_t * global_init_keywords(void) { /* global definitions mapping */ init_global_keywords(true); #ifdef _WITH_VRRP_ init_vrrp_keywords(false); #endif #ifdef _WITH_LVS_ init_check_keywords(false); #endif #ifdef _WITH_BFD_ init_bfd_keywords(false); #endif return keywords; } static void read_config_file(void) { init_data(conf_file, global_init_keywords); } /* Daemon stop sequence */ void stop_keepalived(void) { #ifndef _DEBUG_ /* Just cleanup memory & exit */ thread_destroy_master(master); #ifdef _WITH_VRRP_ if (__test_bit(DAEMON_VRRP, &daemon_mode)) pidfile_rm(vrrp_pidfile); #endif #ifdef _WITH_LVS_ if (__test_bit(DAEMON_CHECKERS, &daemon_mode)) pidfile_rm(checkers_pidfile); #endif #ifdef _WITH_BFD_ if (__test_bit(DAEMON_BFD, &daemon_mode)) pidfile_rm(bfd_pidfile); #endif pidfile_rm(main_pidfile); #endif } /* Daemon init sequence */ static int start_keepalived(void) { bool have_child = false; #ifdef _WITH_BFD_ /* must be opened before vrrp and bfd start */ open_bfd_pipes(); #endif #ifdef _WITH_LVS_ /* start healthchecker child */ if (running_checker()) { start_check_child(); have_child = true; } #endif #ifdef _WITH_VRRP_ /* start vrrp child */ if (running_vrrp()) { start_vrrp_child(); have_child = true; } #endif #ifdef _WITH_BFD_ /* start bfd child */ if (running_bfd()) { start_bfd_child(); have_child = true; } #endif return have_child; } static void validate_config(void) { #ifdef _WITH_VRRP_ kernel_netlink_read_interfaces(); #endif #ifdef _WITH_LVS_ /* validate healthchecker config */ #ifndef _DEBUG_ prog_type = PROG_TYPE_CHECKER; #endif check_validate_config(); #endif #ifdef _WITH_VRRP_ /* validate vrrp config */ #ifndef _DEBUG_ prog_type = PROG_TYPE_VRRP; #endif vrrp_validate_config(); #endif #ifdef _WITH_BFD_ /* validate bfd config */ #ifndef _DEBUG_ prog_type = PROG_TYPE_BFD; #endif bfd_validate_config(); #endif } static void config_test_exit(void) { config_err_t config_err = get_config_status(); switch (config_err) { case CONFIG_OK: exit(KEEPALIVED_EXIT_OK); case CONFIG_FILE_NOT_FOUND: case CONFIG_BAD_IF: case CONFIG_FATAL: exit(KEEPALIVED_EXIT_CONFIG); case CONFIG_SECURITY_ERROR: exit(KEEPALIVED_EXIT_CONFIG_TEST_SECURITY); default: exit(KEEPALIVED_EXIT_CONFIG_TEST); } } #ifndef _DEBUG_ static bool reload_config(void) { bool unsupported_change = false; log_message(LOG_INFO, "Reloading ..."); /* Make sure there isn't an attempt to change the network namespace or instance name */ old_global_data = global_data; global_data = NULL; global_data = alloc_global_data(); read_config_file(); init_global_data(global_data, old_global_data); #if HAVE_DECL_CLONE_NEWNET if (!!old_global_data->network_namespace != !!global_data->network_namespace || (global_data->network_namespace && strcmp(old_global_data->network_namespace, global_data->network_namespace))) { log_message(LOG_INFO, "Cannot change network namespace at a reload - please restart %s", PACKAGE); unsupported_change = true; } FREE_PTR(global_data->network_namespace); global_data->network_namespace = old_global_data->network_namespace; old_global_data->network_namespace = NULL; #endif if (!!old_global_data->instance_name != !!global_data->instance_name || (global_data->instance_name && strcmp(old_global_data->instance_name, global_data->instance_name))) { log_message(LOG_INFO, "Cannot change instance name at a reload - please restart %s", PACKAGE); unsupported_change = true; } FREE_PTR(global_data->instance_name); global_data->instance_name = old_global_data->instance_name; old_global_data->instance_name = NULL; if (unsupported_change) { /* We cannot reload the configuration, so continue with the old config */ free_global_data (global_data); global_data = old_global_data; } else free_global_data (old_global_data); return !unsupported_change; } /* SIGHUP/USR1/USR2 handler */ static void propagate_signal(__attribute__((unused)) void *v, int sig) { if (sig == SIGHUP) { if (!reload_config()) return; } /* Signal child processes */ #ifdef _WITH_VRRP_ if (vrrp_child > 0) kill(vrrp_child, sig); else if (sig == SIGHUP && running_vrrp()) start_vrrp_child(); #endif #ifdef _WITH_LVS_ if (sig == SIGHUP) { if (checkers_child > 0) kill(checkers_child, sig); else if (running_checker()) start_check_child(); } #endif #ifdef _WITH_BFD_ if (sig == SIGHUP) { if (bfd_child > 0) kill(bfd_child, sig); else if (running_bfd()) start_bfd_child(); } #endif } /* Terminate handler */ static void sigend(__attribute__((unused)) void *v, __attribute__((unused)) int sig) { int status; int ret; int wait_count = 0; struct timeval start_time, now; #ifdef HAVE_SIGNALFD struct timeval timeout = { .tv_sec = child_wait_time, .tv_usec = 0 }; int signal_fd = master->signal_fd; fd_set read_set; struct signalfd_siginfo siginfo; sigset_t sigmask; #else sigset_t old_set, child_wait; struct timespec timeout = { .tv_sec = child_wait_time, .tv_nsec = 0 }; #endif /* register the terminate thread */ thread_add_terminate_event(master); log_message(LOG_INFO, "Stopping"); #ifdef HAVE_SIGNALFD /* We only want to receive SIGCHLD now */ sigemptyset(&sigmask); sigaddset(&sigmask, SIGCHLD); signalfd(signal_fd, &sigmask, 0); FD_ZERO(&read_set); #else sigmask_func(0, NULL, &old_set); if (!sigismember(&old_set, SIGCHLD)) { sigemptyset(&child_wait); sigaddset(&child_wait, SIGCHLD); sigmask_func(SIG_BLOCK, &child_wait, NULL); } #endif #ifdef _WITH_VRRP_ if (vrrp_child > 0) { if (kill(vrrp_child, SIGTERM)) { /* ESRCH means no such process */ if (errno == ESRCH) vrrp_child = 0; } else wait_count++; } #endif #ifdef _WITH_LVS_ if (checkers_child > 0) { if (kill(checkers_child, SIGTERM)) { if (errno == ESRCH) checkers_child = 0; } else wait_count++; } #endif #ifdef _WITH_BFD_ if (bfd_child > 0) { if (kill(bfd_child, SIGTERM)) { if (errno == ESRCH) bfd_child = 0; } else wait_count++; } #endif gettimeofday(&start_time, NULL); while (wait_count) { #ifdef HAVE_SIGNALFD FD_SET(signal_fd, &read_set); ret = select(signal_fd + 1, &read_set, NULL, NULL, &timeout); if (ret == 0) break; if (ret == -1) { if (errno == EINTR) continue; log_message(LOG_INFO, "Terminating select returned errno %d", errno); break; } if (!FD_ISSET(signal_fd, &read_set)) { log_message(LOG_INFO, "Terminating select did not return select_fd"); continue; } if (read(signal_fd, &siginfo, sizeof(siginfo)) != sizeof(siginfo)) { log_message(LOG_INFO, "Terminating signal read did not read entire siginfo"); break; } status = siginfo.ssi_code == CLD_EXITED ? W_EXITCODE(siginfo.ssi_status, 0) : siginfo.ssi_code == CLD_KILLED ? W_EXITCODE(0, siginfo.ssi_status) : WCOREFLAG; #ifdef _WITH_VRRP_ if (vrrp_child > 0 && vrrp_child == (pid_t)siginfo.ssi_pid) { report_child_status(status, vrrp_child, PROG_VRRP); vrrp_child = 0; wait_count--; } #endif #ifdef _WITH_LVS_ if (checkers_child > 0 && checkers_child == (pid_t)siginfo.ssi_pid) { report_child_status(status, checkers_child, PROG_CHECK); checkers_child = 0; wait_count--; } #endif #ifdef _WITH_BFD_ if (bfd_child > 0 && bfd_child == (pid_t)siginfo.ssi_pid) { report_child_status(status, bfd_child, PROG_BFD); bfd_child = 0; wait_count--; } #endif #else ret = sigtimedwait(&child_wait, NULL, &timeout); if (ret == -1) { if (errno == EINTR) continue; if (errno == EAGAIN) break; } #ifdef _WITH_VRRP_ if (vrrp_child > 0 && vrrp_child == waitpid(vrrp_child, &status, WNOHANG)) { report_child_status(status, vrrp_child, PROG_VRRP); vrrp_child = 0; wait_count--; } #endif #ifdef _WITH_LVS_ if (checkers_child > 0 && checkers_child == waitpid(checkers_child, &status, WNOHANG)) { report_child_status(status, checkers_child, PROG_CHECK); checkers_child = 0; wait_count--; } #endif #ifdef _WITH_BFD_ if (bfd_child > 0 && bfd_child == waitpid(bfd_child, &status, WNOHANG)) { report_child_status(status, bfd_child, PROG_BFD); bfd_child = 0; wait_count--; } #endif #endif if (wait_count) { gettimeofday(&now, NULL); timeout.tv_sec = child_wait_time - (now.tv_sec - start_time.tv_sec); #ifdef HAVE_SIGNALFD timeout.tv_usec = (start_time.tv_usec - now.tv_usec); if (timeout.tv_usec < 0) { timeout.tv_usec += 1000000L; timeout.tv_sec--; } #else timeout.tv_nsec = (start_time.tv_usec - now.tv_usec) * 1000; if (timeout.tv_nsec < 0) { timeout.tv_nsec += 1000000000L; timeout.tv_sec--; } #endif if (timeout.tv_sec < 0) break; } } /* A child may not have terminated, so force its termination */ #ifdef _WITH_VRRP_ if (vrrp_child) { log_message(LOG_INFO, "vrrp process failed to die - forcing termination"); kill(vrrp_child, SIGKILL); } #endif #ifdef _WITH_LVS_ if (checkers_child) { log_message(LOG_INFO, "checker process failed to die - forcing termination"); kill(checkers_child, SIGKILL); } #endif #ifdef _WITH_BFD_ if (bfd_child) { log_message(LOG_INFO, "bfd process failed to die - forcing termination"); kill(bfd_child, SIGKILL); } #endif #ifndef HAVE_SIGNALFD if (!sigismember(&old_set, SIGCHLD)) sigmask_func(SIG_UNBLOCK, &child_wait, NULL); #endif } #endif /* Initialize signal handler */ static void signal_init(void) { #ifndef _DEBUG_ signal_set(SIGHUP, propagate_signal, NULL); signal_set(SIGUSR1, propagate_signal, NULL); signal_set(SIGUSR2, propagate_signal, NULL); #ifdef _WITH_JSON_ signal_set(SIGJSON, propagate_signal, NULL); #endif signal_set(SIGINT, sigend, NULL); signal_set(SIGTERM, sigend, NULL); #endif signal_ignore(SIGPIPE); } /* To create a core file when abrt is running (a RedHat distribution), * and keepalived isn't installed from an RPM package, edit the file * “/etc/abrt/abrt.conf”, and change the value of the field * “ProcessUnpackaged” to “yes”. * * Alternatively, use the -M command line option. */ static void update_core_dump_pattern(const char *pattern_str) { int fd; bool initialising = (orig_core_dump_pattern == NULL); /* CORENAME_MAX_SIZE in kernel source include/linux/binfmts.h defines * the maximum string length, * see core_pattern[CORENAME_MAX_SIZE] in * fs/coredump.c. Currently (Linux 4.10) defines it to be 128, but the * definition is not exposed to user-space. */ #define CORENAME_MAX_SIZE 128 if (initialising) orig_core_dump_pattern = MALLOC(CORENAME_MAX_SIZE); fd = open ("/proc/sys/kernel/core_pattern", O_RDWR); if (fd == -1 || (initialising && read(fd, orig_core_dump_pattern, CORENAME_MAX_SIZE - 1) == -1) || write(fd, pattern_str, strlen(pattern_str)) == -1) { log_message(LOG_INFO, "Unable to read/write core_pattern"); if (fd != -1) close(fd); FREE(orig_core_dump_pattern); return; } close(fd); if (!initialising) FREE_PTR(orig_core_dump_pattern); } static void core_dump_init(void) { struct rlimit orig_rlim, rlim; if (set_core_dump_pattern) { /* If we set the core_pattern here, we will attempt to restore it when we * exit. This will be fine if it is a child of ours that core dumps, * but if we ourself core dump, then the core_pattern will not be restored */ update_core_dump_pattern(core_dump_pattern); } if (create_core_dump) { rlim.rlim_cur = RLIM_INFINITY; rlim.rlim_max = RLIM_INFINITY; if (getrlimit(RLIMIT_CORE, &orig_rlim) == -1) log_message(LOG_INFO, "Failed to get core file size"); else if (setrlimit(RLIMIT_CORE, &rlim) == -1) log_message(LOG_INFO, "Failed to set core file size"); else set_child_rlimit(RLIMIT_CORE, &orig_rlim); } } static mode_t set_umask(const char *optarg) { long umask_long; mode_t umask_val; char *endptr; umask_long = strtoll(optarg, &endptr, 0); if (*endptr || umask_long < 0 || umask_long & ~0777L) { fprintf(stderr, "Invalid --umask option %s", optarg); return 0; } umask_val = umask_long & 0777; umask(umask_val); umask_cmdline = true; return umask_val; } void initialise_debug_options(void) { #if defined WITH_DEBUG_OPTIONS && !defined _DEBUG_ char mask = 0; if (prog_type == PROG_TYPE_PARENT) mask = 1 << PROG_TYPE_PARENT; #if _WITH_BFD_ else if (prog_type == PROG_TYPE_BFD) mask = 1 << PROG_TYPE_BFD; #endif #if _WITH_LVS_ else if (prog_type == PROG_TYPE_CHECKER) mask = 1 << PROG_TYPE_CHECKER; #endif #if _WITH_VRRP_ else if (prog_type == PROG_TYPE_VRRP) mask = 1 << PROG_TYPE_VRRP; #endif #ifdef _TIMER_CHECK_ do_timer_check = !!(timer_debug & mask); #endif #ifdef _SMTP_ALERT_DEBUG_ do_smtp_alert_debug = !!(smtp_debug & mask); #endif #ifdef _EPOLL_DEBUG_ do_epoll_debug = !!(epoll_debug & mask); #endif #ifdef _EPOLL_THREAD_DUMP_ do_epoll_thread_dump = !!(epoll_thread_debug & mask); #endif #ifdef _REGEX_DEBUG_ do_regex_debug = !!(regex_debug & mask); #endif #ifdef _WITH_REGEX_TIMERS_ do_regex_timers = !!(regex_timers & mask); #endif #ifdef _TSM_DEBUG_ do_tsm_debug = !!(tsm_debug & mask); #endif #ifdef _VRRP_FD_DEBUG_ do_vrrp_fd_debug = !!(vrrp_fd_debug & mask); #endif #ifdef _NETLINK_TIMERS_ do_netlink_timers = !!(netlink_timer_debug & mask); #endif #endif } #ifdef WITH_DEBUG_OPTIONS static void set_debug_options(const char *options) { char all_processes, processes; char opt; const char *opt_p = options; #ifdef _DEBUG_ all_processes = 1; #else all_processes = (1 << PROG_TYPE_PARENT); #if _WITH_BFD_ all_processes |= (1 << PROG_TYPE_BFD); #endif #if _WITH_LVS_ all_processes |= (1 << PROG_TYPE_CHECKER); #endif #if _WITH_VRRP_ all_processes |= (1 << PROG_TYPE_VRRP); #endif #endif if (!options) { #ifdef _TIMER_CHECK_ timer_debug = all_processes; #endif #ifdef _SMTP_ALERT_DEBUG_ smtp_debug = all_processes; #endif #ifdef _EPOLL_DEBUG_ epoll_debug = all_processes; #endif #ifdef _EPOLL_THREAD_DUMP_ epoll_thread_debug = all_processes; #endif #ifdef _REGEX_DEBUG_ regex_debug = all_processes; #endif #ifdef _WITH_REGEX_TIMERS_ regex_timers = all_processes; #endif #ifdef _TSM_DEBUG_ tsm_debug = all_processes; #endif #ifdef _VRRP_FD_DEBUG_ vrrp_fd_debug = all_processes; #endif #ifdef _NETLINK_TIMERS_ netlink_timer_debug = all_processes; #endif return; } opt_p = options; do { if (!isupper(*opt_p)) { fprintf(stderr, "Unknown debug option'%c' in '%s'\n", *opt_p, options); return; } opt = *opt_p++; #ifdef _DEBUG_ processes = all_processes; #else if (!*opt_p || isupper(*opt_p)) processes = all_processes; else { processes = 0; while (*opt_p && !isupper(*opt_p)) { switch (*opt_p) { case 'p': processes |= (1 << PROG_TYPE_PARENT); break; #if _WITH_BFD_ case 'b': processes |= (1 << PROG_TYPE_BFD); break; #endif #if _WITH_LVS_ case 'c': processes |= (1 << PROG_TYPE_CHECKER); break; #endif #if _WITH_VRRP_ case 'v': processes |= (1 << PROG_TYPE_VRRP); break; #endif default: fprintf(stderr, "Unknown debug process '%c' in '%s'\n", *opt_p, options); return; } opt_p++; } } #endif switch (opt) { #ifdef _TIMER_CHECK_ case 'T': timer_debug = processes; break; #endif #ifdef _SMTP_ALERT_DEBUG_ case 'M': smtp_debug = processes; break; #endif #ifdef _EPOLL_DEBUG_ case 'E': epoll_debug = processes; break; #endif #ifdef _EPOLL_THREAD_DUMP_ case 'D': epoll_thread_debug = processes; break; #endif #ifdef _REGEX_DEBUG_ case 'R': regex_debug = processes; break; #endif #ifdef _WITH_REGEX_TIMERS_ case 'X': regex_timers = processes; break; #endif #ifdef _TSM_DEBUG_ case 'S': tsm_debug = processes; break; #endif #ifdef _VRRP_FD_DEBUG_ case 'F': vrrp_fd_debug = processes; break; #endif #ifdef _NETLINK_TIMERS_ case 'N': netlink_timer_debug = processes; break; #endif default: fprintf(stderr, "Unknown debug type '%c' in '%s'\n", opt, options); return; } } while (opt_p && *opt_p); } #endif /* Usage function */ static void usage(const char *prog) { fprintf(stderr, "Usage: %s [OPTION...]\n", prog); fprintf(stderr, " -f, --use-file=FILE Use the specified configuration file\n"); #if defined _WITH_VRRP_ && defined _WITH_LVS_ fprintf(stderr, " -P, --vrrp Only run with VRRP subsystem\n"); fprintf(stderr, " -C, --check Only run with Health-checker subsystem\n"); #endif #ifdef _WITH_BFD_ fprintf(stderr, " -B, --no_bfd Don't run BFD subsystem\n"); #endif fprintf(stderr, " --all Force all child processes to run, even if have no configuration\n"); fprintf(stderr, " -l, --log-console Log messages to local console\n"); fprintf(stderr, " -D, --log-detail Detailed log messages\n"); fprintf(stderr, " -S, --log-facility=[0-7] Set syslog facility to LOG_LOCAL[0-7]\n"); fprintf(stderr, " -g, --log-file=FILE Also log to FILE (default /tmp/keepalived.log)\n"); fprintf(stderr, " --flush-log-file Flush log file on write\n"); fprintf(stderr, " -G, --no-syslog Don't log via syslog\n"); fprintf(stderr, " -u, --umask=MASK umask for file creation (in numeric form)\n"); #ifdef _WITH_VRRP_ fprintf(stderr, " -X, --release-vips Drop VIP on transition from signal.\n"); fprintf(stderr, " -V, --dont-release-vrrp Don't remove VRRP VIPs and VROUTEs on daemon stop\n"); #endif #ifdef _WITH_LVS_ fprintf(stderr, " -I, --dont-release-ipvs Don't remove IPVS topology on daemon stop\n"); #endif fprintf(stderr, " -R, --dont-respawn Don't respawn child processes\n"); fprintf(stderr, " -n, --dont-fork Don't fork the daemon process\n"); fprintf(stderr, " -d, --dump-conf Dump the configuration data\n"); fprintf(stderr, " -p, --pid=FILE Use specified pidfile for parent process\n"); #ifdef _WITH_VRRP_ fprintf(stderr, " -r, --vrrp_pid=FILE Use specified pidfile for VRRP child process\n"); #endif #ifdef _WITH_LVS_ fprintf(stderr, " -c, --checkers_pid=FILE Use specified pidfile for checkers child process\n"); fprintf(stderr, " -a, --address-monitoring Report all address additions/deletions notified via netlink\n"); #endif #ifdef _WITH_BFD_ fprintf(stderr, " -b, --bfd_pid=FILE Use specified pidfile for BFD child process\n"); #endif #ifdef _WITH_SNMP_ fprintf(stderr, " -x, --snmp Enable SNMP subsystem\n"); fprintf(stderr, " -A, --snmp-agent-socket=FILE Use the specified socket for master agent\n"); #endif #if HAVE_DECL_CLONE_NEWNET fprintf(stderr, " -s, --namespace=NAME Run in network namespace NAME (overrides config)\n"); #endif fprintf(stderr, " -m, --core-dump Produce core dump if terminate abnormally\n"); fprintf(stderr, " -M, --core-dump-pattern=PATN Also set /proc/sys/kernel/core_pattern to PATN (default 'core')\n"); #ifdef _MEM_CHECK_LOG_ fprintf(stderr, " -L, --mem-check-log Log malloc/frees to syslog\n"); #endif fprintf(stderr, " -i, --config-id id Skip any configuration lines beginning '@' that don't match id\n" " or any lines beginning @^ that do match.\n" " The config-id defaults to the node name if option not used\n"); fprintf(stderr, " --signum=SIGFUNC Return signal number for STOP, RELOAD, DATA, STATS" #ifdef _WITH_JSON_ ", JSON" #endif "\n"); fprintf(stderr, " -t, --config-test[=LOG_FILE] Check the configuration for obvious errors, output to\n" " stderr by default\n"); #ifdef _WITH_PERF_ fprintf(stderr, " --perf[=PERF_TYPE] Collect perf data, PERF_TYPE=all, run(default) or end\n"); #endif #ifdef WITH_DEBUG_OPTIONS fprintf(stderr, " --debug[=...] Enable debug options. p, b, c, v specify parent, bfd, checker and vrrp processes\n"); #ifdef _TIMER_CHECK_ fprintf(stderr, " T - timer debug\n"); #endif #ifdef _SMTP_ALERT_DEBUG_ fprintf(stderr, " M - email alert debug\n"); #endif #ifdef _EPOLL_DEBUG_ fprintf(stderr, " E - epoll debug\n"); #endif #ifdef _EPOLL_THREAD_DUMP_ fprintf(stderr, " D - epoll thread dump debug\n"); #endif #ifdef _VRRP_FD_DEBUG fprintf(stderr, " F - vrrp fd dump debug\n"); #endif #ifdef _REGEX_DEBUG_ fprintf(stderr, " R - regex debug\n"); #endif #ifdef _WITH_REGEX_TIMERS_ fprintf(stderr, " X - regex timers\n"); #endif #ifdef _TSM_DEBUG_ fprintf(stderr, " S - TSM debug\n"); #endif #ifdef _NETLINK_TIMERS_ fprintf(stderr, " N - netlink timer debug\n"); #endif fprintf(stderr, " Example --debug=TpMEvcp\n"); #endif fprintf(stderr, " -v, --version Display the version number\n"); fprintf(stderr, " -h, --help Display this help message\n"); } /* Command line parser */ static bool parse_cmdline(int argc, char **argv) { int c; bool reopen_log = false; int signum; struct utsname uname_buf; int longindex; int curind; bool bad_option = false; unsigned facility; mode_t new_umask_val; struct option long_options[] = { {"use-file", required_argument, NULL, 'f'}, #if defined _WITH_VRRP_ && defined _WITH_LVS_ {"vrrp", no_argument, NULL, 'P'}, {"check", no_argument, NULL, 'C'}, #endif #ifdef _WITH_BFD_ {"no_bfd", no_argument, NULL, 'B'}, #endif {"all", no_argument, NULL, 3 }, {"log-console", no_argument, NULL, 'l'}, {"log-detail", no_argument, NULL, 'D'}, {"log-facility", required_argument, NULL, 'S'}, {"log-file", optional_argument, NULL, 'g'}, {"flush-log-file", no_argument, NULL, 2 }, {"no-syslog", no_argument, NULL, 'G'}, {"umask", required_argument, NULL, 'u'}, #ifdef _WITH_VRRP_ {"release-vips", no_argument, NULL, 'X'}, {"dont-release-vrrp", no_argument, NULL, 'V'}, #endif #ifdef _WITH_LVS_ {"dont-release-ipvs", no_argument, NULL, 'I'}, #endif {"dont-respawn", no_argument, NULL, 'R'}, {"dont-fork", no_argument, NULL, 'n'}, {"dump-conf", no_argument, NULL, 'd'}, {"pid", required_argument, NULL, 'p'}, #ifdef _WITH_VRRP_ {"vrrp_pid", required_argument, NULL, 'r'}, #endif #ifdef _WITH_LVS_ {"checkers_pid", required_argument, NULL, 'c'}, {"address-monitoring", no_argument, NULL, 'a'}, #endif #ifdef _WITH_BFD_ {"bfd_pid", required_argument, NULL, 'b'}, #endif #ifdef _WITH_SNMP_ {"snmp", no_argument, NULL, 'x'}, {"snmp-agent-socket", required_argument, NULL, 'A'}, #endif {"core-dump", no_argument, NULL, 'm'}, {"core-dump-pattern", optional_argument, NULL, 'M'}, #ifdef _MEM_CHECK_LOG_ {"mem-check-log", no_argument, NULL, 'L'}, #endif #if HAVE_DECL_CLONE_NEWNET {"namespace", required_argument, NULL, 's'}, #endif {"config-id", required_argument, NULL, 'i'}, {"signum", required_argument, NULL, 4 }, {"config-test", optional_argument, NULL, 't'}, #ifdef _WITH_PERF_ {"perf", optional_argument, NULL, 5 }, #endif #ifdef WITH_DEBUG_OPTIONS {"debug", optional_argument, NULL, 6 }, #endif {"version", no_argument, NULL, 'v'}, {"help", no_argument, NULL, 'h'}, {NULL, 0, NULL, 0 } }; /* Unfortunately, if a short option is used, getopt_long() doesn't change the value * of longindex, so we need to ensure that before calling getopt_long(), longindex * is set to a known invalid value */ curind = optind; while (longindex = -1, (c = getopt_long(argc, argv, ":vhlndu:DRS:f:p:i:mM::g::Gt::" #if defined _WITH_VRRP_ && defined _WITH_LVS_ "PC" #endif #ifdef _WITH_VRRP_ "r:VX" #endif #ifdef _WITH_LVS_ "ac:I" #endif #ifdef _WITH_BFD_ "Bb:" #endif #ifdef _WITH_SNMP_ "xA:" #endif #ifdef _MEM_CHECK_LOG_ "L" #endif #if HAVE_DECL_CLONE_NEWNET "s:" #endif , long_options, &longindex)) != -1) { /* Check for an empty option argument. For example --use-file= returns * a 0 length option, which we don't want */ if (longindex >= 0 && long_options[longindex].has_arg == required_argument && optarg && !optarg[0]) { c = ':'; optarg = NULL; } switch (c) { case 'v': fprintf(stderr, "%s", version_string); #ifdef GIT_COMMIT fprintf(stderr, ", git commit %s", GIT_COMMIT); #endif fprintf(stderr, "\n\n%s\n\n", COPYRIGHT_STRING); fprintf(stderr, "Built with kernel headers for Linux %d.%d.%d\n", (LINUX_VERSION_CODE >> 16) & 0xff, (LINUX_VERSION_CODE >> 8) & 0xff, (LINUX_VERSION_CODE ) & 0xff); uname(&uname_buf); fprintf(stderr, "Running on %s %s %s\n\n", uname_buf.sysname, uname_buf.release, uname_buf.version); fprintf(stderr, "configure options: %s\n\n", KEEPALIVED_CONFIGURE_OPTIONS); fprintf(stderr, "Config options: %s\n\n", CONFIGURATION_OPTIONS); fprintf(stderr, "System options: %s\n", SYSTEM_OPTIONS); exit(0); break; case 'h': usage(argv[0]); exit(0); break; case 'l': __set_bit(LOG_CONSOLE_BIT, &debug); reopen_log = true; break; case 'n': __set_bit(DONT_FORK_BIT, &debug); break; case 'd': __set_bit(DUMP_CONF_BIT, &debug); break; #ifdef _WITH_VRRP_ case 'V': __set_bit(DONT_RELEASE_VRRP_BIT, &debug); break; #endif #ifdef _WITH_LVS_ case 'I': __set_bit(DONT_RELEASE_IPVS_BIT, &debug); break; #endif case 'D': if (__test_bit(LOG_DETAIL_BIT, &debug)) __set_bit(LOG_EXTRA_DETAIL_BIT, &debug); else __set_bit(LOG_DETAIL_BIT, &debug); break; case 'R': __set_bit(DONT_RESPAWN_BIT, &debug); break; #ifdef _WITH_VRRP_ case 'X': __set_bit(RELEASE_VIPS_BIT, &debug); break; #endif case 'S': if (!read_unsigned(optarg, &facility, 0, LOG_FACILITY_MAX, false)) fprintf(stderr, "Invalid log facility '%s'\n", optarg); else { log_facility = LOG_FACILITY[facility].facility; reopen_log = true; } break; case 'g': if (optarg && optarg[0]) log_file_name = optarg; else log_file_name = "/tmp/keepalived.log"; open_log_file(log_file_name, NULL, NULL, NULL); break; case 'G': __set_bit(NO_SYSLOG_BIT, &debug); reopen_log = true; break; case 'u': new_umask_val = set_umask(optarg); if (umask_cmdline) umask_val = new_umask_val; break; case 't': __set_bit(CONFIG_TEST_BIT, &debug); __set_bit(DONT_RESPAWN_BIT, &debug); __set_bit(DONT_FORK_BIT, &debug); __set_bit(NO_SYSLOG_BIT, &debug); if (optarg && optarg[0]) { int fd = open(optarg, O_WRONLY | O_APPEND | O_CREAT | O_NOFOLLOW, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); if (fd == -1) { fprintf(stderr, "Unable to open config-test log file %s\n", optarg); exit(EXIT_FAILURE); } dup2(fd, STDERR_FILENO); close(fd); } break; case 'f': conf_file = optarg; break; case 2: /* --flush-log-file */ set_flush_log_file(); break; #if defined _WITH_VRRP_ && defined _WITH_LVS_ case 'P': __clear_bit(DAEMON_CHECKERS, &daemon_mode); break; case 'C': __clear_bit(DAEMON_VRRP, &daemon_mode); break; #endif #ifdef _WITH_BFD_ case 'B': __clear_bit(DAEMON_BFD, &daemon_mode); break; #endif case 'p': main_pidfile = optarg; break; #ifdef _WITH_LVS_ case 'c': checkers_pidfile = optarg; break; case 'a': __set_bit(LOG_ADDRESS_CHANGES, &debug); break; #endif #ifdef _WITH_VRRP_ case 'r': vrrp_pidfile = optarg; break; #endif #ifdef _WITH_BFD_ case 'b': bfd_pidfile = optarg; break; #endif #ifdef _WITH_SNMP_ case 'x': snmp = 1; break; case 'A': snmp_socket = optarg; break; #endif case 'M': set_core_dump_pattern = true; if (optarg && optarg[0]) core_dump_pattern = optarg; /* ... falls through ... */ case 'm': create_core_dump = true; break; #ifdef _MEM_CHECK_LOG_ case 'L': __set_bit(MEM_CHECK_LOG_BIT, &debug); break; #endif #if HAVE_DECL_CLONE_NEWNET case 's': override_namespace = MALLOC(strlen(optarg) + 1); strcpy(override_namespace, optarg); break; #endif case 'i': FREE_PTR(config_id); config_id = MALLOC(strlen(optarg) + 1); strcpy(config_id, optarg); break; case 4: /* --signum */ signum = get_signum(optarg); if (signum == -1) { fprintf(stderr, "Unknown sigfunc %s\n", optarg); exit(1); } printf("%d\n", signum); exit(0); break; case 3: /* --all */ __set_bit(RUN_ALL_CHILDREN, &daemon_mode); #ifdef _WITH_VRRP_ __set_bit(DAEMON_VRRP, &daemon_mode); #endif #ifdef _WITH_LVS_ __set_bit(DAEMON_CHECKERS, &daemon_mode); #endif #ifdef _WITH_BFD_ __set_bit(DAEMON_BFD, &daemon_mode); #endif break; #ifdef _WITH_PERF_ case 5: if (optarg && optarg[0]) { if (!strcmp(optarg, "run")) perf_run = PERF_RUN; else if (!strcmp(optarg, "all")) perf_run = PERF_ALL; else if (!strcmp(optarg, "end")) perf_run = PERF_END; else log_message(LOG_INFO, "Unknown perf start point %s", optarg); } else perf_run = PERF_RUN; break; #endif #ifdef WITH_DEBUG_OPTIONS case 6: set_debug_options(optarg && optarg[0] ? optarg : NULL); break; #endif case '?': if (optopt && argv[curind][1] != '-') fprintf(stderr, "Unknown option -%c\n", optopt); else fprintf(stderr, "Unknown option %s\n", argv[curind]); bad_option = true; break; case ':': if (optopt && argv[curind][1] != '-') fprintf(stderr, "Missing parameter for option -%c\n", optopt); else fprintf(stderr, "Missing parameter for option --%s\n", long_options[longindex].name); bad_option = true; break; default: exit(1); break; } curind = optind; } if (optind < argc) { printf("Unexpected argument(s): "); while (optind < argc) printf("%s ", argv[optind++]); printf("\n"); } if (bad_option) exit(1); return reopen_log; } #ifdef THREAD_DUMP static void register_parent_thread_addresses(void) { register_scheduler_addresses(); register_signal_thread_addresses(); #ifdef _WITH_LVS_ register_check_parent_addresses(); #endif #ifdef _WITH_VRRP_ register_vrrp_parent_addresses(); #endif #ifdef _WITH_BFD_ register_bfd_parent_addresses(); #endif #ifndef _DEBUG_ register_signal_handler_address("propagate_signal", propagate_signal); register_signal_handler_address("sigend", sigend); #endif register_signal_handler_address("thread_child_handler", thread_child_handler); } #endif /* Entry point */ int keepalived_main(int argc, char **argv) { bool report_stopped = true; struct utsname uname_buf; char *end; /* Ensure time_now is set. We then don't have to check anywhere * else if it is set. */ set_time_now(); /* Save command line options in case need to log them later */ save_cmd_line_options(argc, argv); /* Init debugging level */ debug = 0; /* We are the parent process */ #ifndef _DEBUG_ prog_type = PROG_TYPE_PARENT; #endif /* Initialise daemon_mode */ #ifdef _WITH_VRRP_ __set_bit(DAEMON_VRRP, &daemon_mode); #endif #ifdef _WITH_LVS_ __set_bit(DAEMON_CHECKERS, &daemon_mode); #endif #ifdef _WITH_BFD_ __set_bit(DAEMON_BFD, &daemon_mode); #endif /* Set default file creation mask */ umask(022); /* Open log with default settings so we can log initially */ openlog(PACKAGE_NAME, LOG_PID, log_facility); #ifdef _MEM_CHECK_ mem_log_init(PACKAGE_NAME, "Parent process"); #endif /* Some functionality depends on kernel version, so get the version here */ if (uname(&uname_buf)) log_message(LOG_INFO, "Unable to get uname() information - error %d", errno); else { os_major = (unsigned)strtoul(uname_buf.release, &end, 10); if (*end != '.') os_major = 0; else { os_minor = (unsigned)strtoul(end + 1, &end, 10); if (*end != '.') os_major = 0; else { if (!isdigit(end[1])) os_major = 0; else os_release = (unsigned)strtoul(end + 1, &end, 10); } } if (!os_major) log_message(LOG_INFO, "Unable to parse kernel version %s", uname_buf.release); /* config_id defaults to hostname */ if (!config_id) { end = strchrnul(uname_buf.nodename, '.'); config_id = MALLOC((size_t)(end - uname_buf.nodename) + 1); strncpy(config_id, uname_buf.nodename, (size_t)(end - uname_buf.nodename)); config_id[end - uname_buf.nodename] = '\0'; } } /* * Parse command line and set debug level. * bits 0..7 reserved by main.c */ if (parse_cmdline(argc, argv)) { closelog(); if (!__test_bit(NO_SYSLOG_BIT, &debug)) openlog(PACKAGE_NAME, LOG_PID | ((__test_bit(LOG_CONSOLE_BIT, &debug)) ? LOG_CONS : 0) , log_facility); } if (__test_bit(LOG_CONSOLE_BIT, &debug)) enable_console_log(); #ifdef GIT_COMMIT log_message(LOG_INFO, "Starting %s, git commit %s", version_string, GIT_COMMIT); #else log_message(LOG_INFO, "Starting %s", version_string); #endif /* Handle any core file requirements */ core_dump_init(); if (os_major) { if (KERNEL_VERSION(os_major, os_minor, os_release) < LINUX_VERSION_CODE) { /* keepalived was build for a later kernel version */ log_message(LOG_INFO, "WARNING - keepalived was build for newer Linux %d.%d.%d, running on %s %s %s", (LINUX_VERSION_CODE >> 16) & 0xff, (LINUX_VERSION_CODE >> 8) & 0xff, (LINUX_VERSION_CODE ) & 0xff, uname_buf.sysname, uname_buf.release, uname_buf.version); } else { /* keepalived was build for a later kernel version */ log_message(LOG_INFO, "Running on %s %s %s (built for Linux %d.%d.%d)", uname_buf.sysname, uname_buf.release, uname_buf.version, (LINUX_VERSION_CODE >> 16) & 0xff, (LINUX_VERSION_CODE >> 8) & 0xff, (LINUX_VERSION_CODE ) & 0xff); } } #ifndef _DEBUG_ log_command_line(0); #endif /* Check we can read the configuration file(s). NOTE: the working directory will be / if we forked, but will be the current working directory when keepalived was run if we haven't forked. This means that if any config file names are not absolute file names, the behaviour will be different depending on whether we forked or not. */ if (!check_conf_file(conf_file)) { if (__test_bit(CONFIG_TEST_BIT, &debug)) config_test_exit(); goto end; } global_data = alloc_global_data(); global_data->umask = umask_val; read_config_file(); init_global_data(global_data, NULL); #if HAVE_DECL_CLONE_NEWNET if (override_namespace) { if (global_data->network_namespace) { log_message(LOG_INFO, "Overriding config net_namespace '%s' with command line namespace '%s'", global_data->network_namespace, override_namespace); FREE(global_data->network_namespace); } global_data->network_namespace = override_namespace; override_namespace = NULL; } #endif if (!__test_bit(CONFIG_TEST_BIT, &debug) && (global_data->instance_name #if HAVE_DECL_CLONE_NEWNET || global_data->network_namespace #endif )) { if ((syslog_ident = make_syslog_ident(PACKAGE_NAME))) { log_message(LOG_INFO, "Changing syslog ident to %s", syslog_ident); closelog(); openlog(syslog_ident, LOG_PID | ((__test_bit(LOG_CONSOLE_BIT, &debug)) ? LOG_CONS : 0), log_facility); } else log_message(LOG_INFO, "Unable to change syslog ident"); use_pid_dir = true; open_log_file(log_file_name, NULL, #if HAVE_DECL_CLONE_NEWNET global_data->network_namespace, #else NULL, #endif global_data->instance_name); } /* Initialise pointer to child finding function */ set_child_finder_name(find_keepalived_child_name); if (!__test_bit(CONFIG_TEST_BIT, &debug)) { if (use_pid_dir) { /* Create the directory for pid files */ create_pid_dir(); } } #if HAVE_DECL_CLONE_NEWNET if (global_data->network_namespace) { if (global_data->network_namespace && !set_namespaces(global_data->network_namespace)) { log_message(LOG_ERR, "Unable to set network namespace %s - exiting", global_data->network_namespace); goto end; } } #endif if (!__test_bit(CONFIG_TEST_BIT, &debug)) { if (global_data->instance_name) { if (!main_pidfile && (main_pidfile = make_pidfile_name(KEEPALIVED_PID_DIR KEEPALIVED_PID_FILE, global_data->instance_name, PID_EXTENSION))) free_main_pidfile = true; #ifdef _WITH_LVS_ if (!checkers_pidfile && (checkers_pidfile = make_pidfile_name(KEEPALIVED_PID_DIR CHECKERS_PID_FILE, global_data->instance_name, PID_EXTENSION))) free_checkers_pidfile = true; #endif #ifdef _WITH_VRRP_ if (!vrrp_pidfile && (vrrp_pidfile = make_pidfile_name(KEEPALIVED_PID_DIR VRRP_PID_FILE, global_data->instance_name, PID_EXTENSION))) free_vrrp_pidfile = true; #endif #ifdef _WITH_BFD_ if (!bfd_pidfile && (bfd_pidfile = make_pidfile_name(KEEPALIVED_PID_DIR VRRP_PID_FILE, global_data->instance_name, PID_EXTENSION))) free_bfd_pidfile = true; #endif } if (use_pid_dir) { if (!main_pidfile) main_pidfile = KEEPALIVED_PID_DIR KEEPALIVED_PID_FILE PID_EXTENSION; #ifdef _WITH_LVS_ if (!checkers_pidfile) checkers_pidfile = KEEPALIVED_PID_DIR CHECKERS_PID_FILE PID_EXTENSION; #endif #ifdef _WITH_VRRP_ if (!vrrp_pidfile) vrrp_pidfile = KEEPALIVED_PID_DIR VRRP_PID_FILE PID_EXTENSION; #endif #ifdef _WITH_BFD_ if (!bfd_pidfile) bfd_pidfile = KEEPALIVED_PID_DIR BFD_PID_FILE PID_EXTENSION; #endif } else { if (!main_pidfile) main_pidfile = PID_DIR KEEPALIVED_PID_FILE PID_EXTENSION; #ifdef _WITH_LVS_ if (!checkers_pidfile) checkers_pidfile = PID_DIR CHECKERS_PID_FILE PID_EXTENSION; #endif #ifdef _WITH_VRRP_ if (!vrrp_pidfile) vrrp_pidfile = PID_DIR VRRP_PID_FILE PID_EXTENSION; #endif #ifdef _WITH_BFD_ if (!bfd_pidfile) bfd_pidfile = PID_DIR BFD_PID_FILE PID_EXTENSION; #endif } /* Check if keepalived is already running */ if (keepalived_running(daemon_mode)) { log_message(LOG_INFO, "daemon is already running"); report_stopped = false; goto end; } } /* daemonize process */ if (!__test_bit(DONT_FORK_BIT, &debug) && xdaemon(false, false, true) > 0) { closelog(); FREE_PTR(config_id); FREE_PTR(orig_core_dump_pattern); close_std_fd(); exit(0); } #ifdef _MEM_CHECK_ enable_mem_log_termination(); #endif if (__test_bit(CONFIG_TEST_BIT, &debug)) { validate_config(); config_test_exit(); } /* write the father's pidfile */ if (!pidfile_write(main_pidfile, getpid())) goto end; /* Create the master thread */ master = thread_make_master(); /* Signal handling initialization */ signal_init(); /* Init daemon */ if (!start_keepalived()) log_message(LOG_INFO, "Warning - keepalived has no configuration to run"); initialise_debug_options(); #ifdef THREAD_DUMP register_parent_thread_addresses(); #endif /* Launch the scheduling I/O multiplexer */ launch_thread_scheduler(master); /* Finish daemon process */ stop_keepalived(); #ifdef THREAD_DUMP deregister_thread_addresses(); #endif /* * Reached when terminate signal catched. * finally return from system */ end: if (report_stopped) { #ifdef GIT_COMMIT log_message(LOG_INFO, "Stopped %s, git commit %s", version_string, GIT_COMMIT); #else log_message(LOG_INFO, "Stopped %s", version_string); #endif } #if HAVE_DECL_CLONE_NEWNET if (global_data && global_data->network_namespace) clear_namespaces(); #endif if (use_pid_dir) remove_pid_dir(); /* Restore original core_pattern if necessary */ if (orig_core_dump_pattern) update_core_dump_pattern(orig_core_dump_pattern); free_parent_mallocs_startup(false); free_parent_mallocs_exit(); free_global_data(global_data); closelog(); #ifndef _MEM_CHECK_LOG_ FREE_PTR(syslog_ident); #else if (syslog_ident) free(syslog_ident); #endif close_std_fd(); exit(KEEPALIVED_EXIT_OK); }
./CrossVul/dataset_final_sorted/CWE-59/c/good_436_0
crossvul-cpp_data_good_5487_2
/***************************************************************************** * * LOGGING.C - Log file functions for use with Nagios * * * License: * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * *****************************************************************************/ #include "../include/config.h" #include "../include/common.h" #include "../include/statusdata.h" #include "../include/macros.h" #include "../include/nagios.h" #include "../include/broker.h" #include <fcntl.h> static FILE *debug_file_fp; static FILE *log_fp; /******************************************************************/ /************************ LOGGING FUNCTIONS ***********************/ /******************************************************************/ /* write something to the console */ static void write_to_console(char *buffer) { /* should we print to the console? */ if(daemon_mode == FALSE) printf("%s\n", buffer); } /* write something to the log file, syslog, and possibly the console */ static void write_to_logs_and_console(char *buffer, unsigned long data_type, int display) { register int len = 0; register int x = 0; /* strip unnecessary newlines */ len = strlen(buffer); for(x = len - 1; x >= 0; x--) { if(buffer[x] == '\n') buffer[x] = '\x0'; else break; } /* write messages to the logs */ write_to_all_logs(buffer, data_type); /* write message to the console */ if(display == TRUE) { /* don't display warnings if we're just testing scheduling */ if(test_scheduling == TRUE && data_type == NSLOG_VERIFICATION_WARNING) return; write_to_console(buffer); } } /* The main logging function */ void logit(int data_type, int display, const char *fmt, ...) { va_list ap; char *buffer = NULL; va_start(ap, fmt); if(vasprintf(&buffer, fmt, ap) > 0) { write_to_logs_and_console(buffer, data_type, display); free(buffer); } va_end(ap); } /* write something to the log file and syslog facility */ int write_to_all_logs(char *buffer, unsigned long data_type) { /* write to syslog */ write_to_syslog(buffer, data_type); /* write to main log */ write_to_log(buffer, data_type, NULL); return OK; } /* write something to the log file and syslog facility */ static void write_to_all_logs_with_timestamp(char *buffer, unsigned long data_type, time_t *timestamp) { /* write to syslog */ write_to_syslog(buffer, data_type); /* write to main log */ write_to_log(buffer, data_type, timestamp); } static FILE *open_log_file(void) { int fh; struct stat st; if(log_fp) /* keep it open unless we rotate */ return log_fp; if ((fh = open(log_file, O_RDWR|O_APPEND|O_CREAT|O_NOFOLLOW, S_IRUSR|S_IWUSR)) == -1) { if (daemon_mode == FALSE) printf("Warning: Cannot open log file '%s' for writing\n", log_file); return NULL; } log_fp = fdopen(fh, "a+"); if(log_fp == NULL) { if (daemon_mode == FALSE) printf("Warning: Cannot open log file '%s' for writing\n", log_file); return NULL; } if ((fstat(fh, &st)) == -1) { log_fp = NULL; close(fh); if (daemon_mode == FALSE) printf("Warning: Cannot fstat log file '%s'\n", log_file); return NULL; } if (st.st_nlink != 1 || (st.st_mode & S_IFMT) != S_IFREG) { log_fp = NULL; close(fh); if (daemon_mode == FALSE) printf("Warning: log file '%s' has an invalid mode\n", log_file); return NULL; } (void)fcntl(fileno(log_fp), F_SETFD, FD_CLOEXEC); return log_fp; } int fix_log_file_owner(uid_t uid, gid_t gid) { int r1 = 0, r2 = 0; if (!(log_fp = open_log_file())) return -1; r1 = fchown(fileno(log_fp), uid, gid); if (open_debug_log() != OK) return -1; if (debug_file_fp) r2 = fchown(fileno(debug_file_fp), uid, gid); /* return 0 if both are 0 and otherwise < 0 */ return r1 < r2 ? r1 : r2; } int close_log_file(void) { if(!log_fp) return 0; fflush(log_fp); fclose(log_fp); log_fp = NULL; return 0; } /* write something to the nagios log file */ int write_to_log(char *buffer, unsigned long data_type, time_t *timestamp) { FILE *fp; time_t log_time = 0L; if(buffer == NULL) return ERROR; /* don't log anything if we're not actually running... */ if(verify_config || test_scheduling == TRUE) return OK; /* make sure we can log this type of entry */ if(!(data_type & logging_options)) return OK; fp = open_log_file(); if (fp == NULL) return ERROR; /* what timestamp should we use? */ if(timestamp == NULL) time(&log_time); else log_time = *timestamp; /* strip any newlines from the end of the buffer */ strip(buffer); /* write the buffer to the log file */ fprintf(fp, "[%llu] %s\n", (unsigned long long)log_time, buffer); fflush(fp); #ifdef USE_EVENT_BROKER /* send data to the event broker */ broker_log_data(NEBTYPE_LOG_DATA, NEBFLAG_NONE, NEBATTR_NONE, buffer, data_type, log_time, NULL); #endif return OK; } /* write something to the syslog facility */ int write_to_syslog(char *buffer, unsigned long data_type) { if(buffer == NULL) return ERROR; /* don't log anything if we're not actually running... */ if(verify_config || test_scheduling == TRUE) return OK; /* bail out if we shouldn't write to syslog */ if(use_syslog == FALSE) return OK; /* make sure we should log this type of entry */ if(!(data_type & syslog_options)) return OK; /* write the buffer to the syslog facility */ syslog(LOG_USER | LOG_INFO, "%s", buffer); return OK; } /* write a service problem/recovery to the nagios log file */ int log_service_event(service *svc) { char *temp_buffer = NULL; unsigned long log_options = 0L; host *temp_host = NULL; /* don't log soft errors if the user doesn't want to */ if(svc->state_type == SOFT_STATE && !log_service_retries) return OK; /* get the log options */ if(svc->current_state == STATE_UNKNOWN) log_options = NSLOG_SERVICE_UNKNOWN; else if(svc->current_state == STATE_WARNING) log_options = NSLOG_SERVICE_WARNING; else if(svc->current_state == STATE_CRITICAL) log_options = NSLOG_SERVICE_CRITICAL; else log_options = NSLOG_SERVICE_OK; /* find the associated host */ if((temp_host = svc->host_ptr) == NULL) return ERROR; asprintf(&temp_buffer, "SERVICE ALERT: %s;%s;%s;%s;%d;%s\n", svc->host_name, svc->description, service_state_name(svc->current_state), state_type_name(svc->state_type), svc->current_attempt, (svc->plugin_output == NULL) ? "" : svc->plugin_output); write_to_all_logs(temp_buffer, log_options); free(temp_buffer); return OK; } /* write a host problem/recovery to the log file */ int log_host_event(host *hst) { char *temp_buffer = NULL; unsigned long log_options = 0L; /* get the log options */ if(hst->current_state == HOST_DOWN) log_options = NSLOG_HOST_DOWN; else if(hst->current_state == HOST_UNREACHABLE) log_options = NSLOG_HOST_UNREACHABLE; else log_options = NSLOG_HOST_UP; asprintf(&temp_buffer, "HOST ALERT: %s;%s;%s;%d;%s\n", hst->name, host_state_name(hst->current_state), state_type_name(hst->state_type), hst->current_attempt, (hst->plugin_output == NULL) ? "" : hst->plugin_output); write_to_all_logs(temp_buffer, log_options); my_free(temp_buffer); return OK; } /* logs host states */ int log_host_states(int type, time_t *timestamp) { char *temp_buffer = NULL; host *temp_host = NULL;; /* bail if we shouldn't be logging initial states */ if(type == INITIAL_STATES && log_initial_states == FALSE) return OK; for(temp_host = host_list; temp_host != NULL; temp_host = temp_host->next) { asprintf(&temp_buffer, "%s HOST STATE: %s;%s;%s;%d;%s\n", (type == INITIAL_STATES) ? "INITIAL" : "CURRENT", temp_host->name, host_state_name(temp_host->current_state), state_type_name(temp_host->state_type), temp_host->current_attempt, (temp_host->plugin_output == NULL) ? "" : temp_host->plugin_output); write_to_all_logs_with_timestamp(temp_buffer, NSLOG_INFO_MESSAGE, timestamp); my_free(temp_buffer); } return OK; } /* logs service states */ int log_service_states(int type, time_t *timestamp) { char *temp_buffer = NULL; service *temp_service = NULL; host *temp_host = NULL;; /* bail if we shouldn't be logging initial states */ if(type == INITIAL_STATES && log_initial_states == FALSE) return OK; for(temp_service = service_list; temp_service != NULL; temp_service = temp_service->next) { /* find the associated host */ if((temp_host = temp_service->host_ptr) == NULL) continue; asprintf(&temp_buffer, "%s SERVICE STATE: %s;%s;%s;%s;%d;%s\n", (type == INITIAL_STATES) ? "INITIAL" : "CURRENT", temp_service->host_name, temp_service->description, service_state_name(temp_service->current_state), state_type_name(temp_service->state_type), temp_service->current_attempt, temp_service->plugin_output); write_to_all_logs_with_timestamp(temp_buffer, NSLOG_INFO_MESSAGE, timestamp); my_free(temp_buffer); } return OK; } /* rotates the main log file */ int rotate_log_file(time_t rotation_time) { char *temp_buffer = NULL; char method_string[16] = ""; char *log_archive = NULL; struct tm *t, tm_s; int rename_result = 0; int stat_result = -1; struct stat log_file_stat; struct stat archive_stat; int archive_stat_result; if(log_rotation_method == LOG_ROTATION_NONE) { return OK; } else if(log_rotation_method == LOG_ROTATION_HOURLY) strcpy(method_string, "HOURLY"); else if(log_rotation_method == LOG_ROTATION_DAILY) strcpy(method_string, "DAILY"); else if(log_rotation_method == LOG_ROTATION_WEEKLY) strcpy(method_string, "WEEKLY"); else if(log_rotation_method == LOG_ROTATION_MONTHLY) strcpy(method_string, "MONTHLY"); else return ERROR; /* update the last log rotation time and status log */ last_log_rotation = time(NULL); update_program_status(FALSE); t = localtime_r(&rotation_time, &tm_s); stat_result = stat(log_file, &log_file_stat); close_log_file(); /* get the archived filename to use */ asprintf(&log_archive, "%s%snagios-%02d-%02d-%d-%02d.log", log_archive_path, (log_archive_path[strlen(log_archive_path) - 1] == '/') ? "" : "/", t->tm_mon + 1, t->tm_mday, t->tm_year + 1900, t->tm_hour); /* HACK: If the archive exists, don't overwrite it. This is a hack because the real problem is that some log rotations are executed early and as a result the next log rotatation is scheduled for the same time as the one that ran early */ archive_stat_result = stat(log_archive, &archive_stat); if((0 == archive_stat_result) || ((-1 == archive_stat_result) && (ENOENT != errno))) { return OK; } /* rotate the log file */ rename_result = my_rename(log_file, log_archive); log_fp = open_log_file(); if (log_fp == NULL) return ERROR; if(rename_result) { my_free(log_archive); return ERROR; } /* record the log rotation after it has been done... */ asprintf(&temp_buffer, "LOG ROTATION: %s\n", method_string); write_to_all_logs_with_timestamp(temp_buffer, NSLOG_PROCESS_INFO, &rotation_time); my_free(temp_buffer); /* record log file version format */ write_log_file_info(&rotation_time); if(stat_result == 0) { chmod(log_file, log_file_stat.st_mode); chown(log_file, log_file_stat.st_uid, log_file_stat.st_gid); } /* log current host and service state if activated */ if(log_current_states==TRUE) { log_host_states(CURRENT_STATES, &rotation_time); log_service_states(CURRENT_STATES, &rotation_time); } /* free memory */ my_free(log_archive); return OK; } /* record log file version/info */ int write_log_file_info(time_t *timestamp) { char *temp_buffer = NULL; /* write log version */ asprintf(&temp_buffer, "LOG VERSION: %s\n", LOG_VERSION_2); write_to_all_logs_with_timestamp(temp_buffer, NSLOG_PROCESS_INFO, timestamp); my_free(temp_buffer); return OK; } /* opens the debug log for writing */ int open_debug_log(void) { int fh; struct stat st; /* don't do anything if we're not actually running... */ if(verify_config || test_scheduling == TRUE) return OK; /* don't do anything if we're not debugging */ if(debug_level == DEBUGL_NONE) return OK; if ((fh = open(debug_file, O_RDWR|O_APPEND|O_CREAT|O_NOFOLLOW, S_IRUSR|S_IWUSR)) == -1) return ERROR; if((debug_file_fp = fdopen(fh, "a+")) == NULL) return ERROR; if ((fstat(fh, &st)) == -1) { debug_file_fp = NULL; close(fh); return ERROR; } if (st.st_nlink != 1 || (st.st_mode & S_IFMT) != S_IFREG) { debug_file_fp = NULL; close(fh); return ERROR; } (void)fcntl(fh, F_SETFD, FD_CLOEXEC); return OK; } /* closes the debug log */ int close_debug_log(void) { if(debug_file_fp != NULL) fclose(debug_file_fp); debug_file_fp = NULL; return OK; } /* write to the debug log */ int log_debug_info(int level, int verbosity, const char *fmt, ...) { va_list ap; char *tmppath = NULL; struct timeval current_time; if(!(debug_level == DEBUGL_ALL || (level & debug_level))) return OK; if(verbosity > debug_verbosity) return OK; if(debug_file_fp == NULL) return ERROR; /* write the timestamp */ gettimeofday(&current_time, NULL); fprintf(debug_file_fp, "[%lu.%06lu] [%03d.%d] [pid=%lu] ", current_time.tv_sec, current_time.tv_usec, level, verbosity, (unsigned long)getpid()); /* write the data */ va_start(ap, fmt); vfprintf(debug_file_fp, fmt, ap); va_end(ap); /* flush, so we don't have problems tailing or when fork()ing */ fflush(debug_file_fp); /* if file has grown beyond max, rotate it */ if((unsigned long)ftell(debug_file_fp) > max_debug_file_size && max_debug_file_size > 0L) { /* close the file */ close_debug_log(); /* rotate the log file */ asprintf(&tmppath, "%s.old", debug_file); if(tmppath) { /* unlink the old debug file */ unlink(tmppath); /* rotate the debug file */ my_rename(debug_file, tmppath); /* free memory */ my_free(tmppath); } /* open a new file */ open_debug_log(); } return OK; }
./CrossVul/dataset_final_sorted/CWE-59/c/good_5487_2
crossvul-cpp_data_good_436_11
/* * Soft: Keepalived is a failover program for the LVS project * <www.linuxvirtualserver.org>. It monitor & manipulate * a loadbalanced server pool using multi-layer checks. * * Part: Configuration file parser/reader. Place into the dynamic * data structure representation the conf file representing * the loadbalanced server pool. * * Author: Alexandre Cassen, <acassen@linux-vs.org> * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. * * Copyright (C) 2001-2017 Alexandre Cassen, <acassen@gmail.com> */ #include "config.h" #include <glob.h> #include <unistd.h> #include <libgen.h> #include <errno.h> #include <sys/stat.h> #include <sys/types.h> #include <fcntl.h> #include <stdlib.h> #include <ctype.h> #include <stdbool.h> #include <linux/version.h> #include <pwd.h> #include <string.h> #include <stdio.h> #include <stdarg.h> #include <math.h> #include <inttypes.h> #include "parser.h" #include "memory.h" #include "logger.h" #include "rttables.h" #include "scheduler.h" #include "notify.h" #include "list.h" #include "bitops.h" #include "utils.h" /* #define PARSER_DEBUG */ #define DUMP_KEYWORDS 0 #define DEF_LINE_END "\n" #define BOB "{" #define EOB "}" #define WHITE_SPACE_STR " \t\f\n\r\v" typedef struct _defs { char *name; size_t name_len; char *value; size_t value_len; bool multiline; char *(*fn)(void); } def_t; /* global vars */ vector_t *keywords; char *config_id; const char *WHITE_SPACE = WHITE_SPACE_STR; /* local vars */ static vector_t *current_keywords; static FILE *current_stream; static const char *current_file_name; static size_t current_file_line_no; static int sublevel = 0; static int skip_sublevel = 0; static list multiline_stack; static char *buf_extern; static config_err_t config_err = CONFIG_OK; /* Highest level of config error for --config-test */ /* Parameter definitions */ static list defs; /* Forward declarations for recursion */ static bool read_line(char *, size_t); void report_config_error(config_err_t err, const char *format, ...) { va_list args; char *format_buf = NULL; /* current_file_name will be set if there is more than one config file, in which * case we need to specify the file name. */ if (current_file_name) { /* "(file_name:line_no) format" + '\0' */ format_buf = MALLOC(1 + strlen(current_file_name) + 1 + 10 + 1 + 1 + strlen(format) + 1); sprintf(format_buf, "(%s:%zd) %s", current_file_name, current_file_line_no, format); } else if (current_file_line_no) { /* Set while reading from config files */ /* "(Line line_no) format" + '\0' */ format_buf = MALLOC(1 + 5 + 10 + 1 + 1 + strlen(format) + 1); sprintf(format_buf, "(%s %zd) %s", "Line", current_file_line_no, format); } va_start(args, format); if (__test_bit(CONFIG_TEST_BIT, &debug)) { vfprintf(stderr, format_buf ? format_buf : format, args); fputc('\n', stderr); if (config_err == CONFIG_OK || config_err < err) config_err = err; } else vlog_message(LOG_INFO, format_buf ? format_buf : format, args); va_end(args); if (format_buf) FREE(format_buf); } config_err_t get_config_status(void) { return config_err; } static char * null_strvec(const vector_t *strvec, size_t index) { if (index - 1 < vector_size(strvec) && index > 0 && vector_slot(strvec, index - 1)) report_config_error(CONFIG_MISSING_PARAMETER, "*** Configuration line starting `%s` is missing a parameter after keyword `%s` at word position %zu", vector_slot(strvec, 0) ? (char *)vector_slot(strvec, 0) : "***MISSING ***", (char *)vector_slot(strvec, index - 1), index + 1); else report_config_error(CONFIG_MISSING_PARAMETER, "*** Configuration line starting `%s` is missing a parameter at word position %zu", vector_slot(strvec, 0) ? (char *)vector_slot(strvec, 0) : "***MISSING ***", index + 1); exit(KEEPALIVED_EXIT_CONFIG); return NULL; } static bool read_int_func(const char *number, int base, int *res, int min_val, int max_val, __attribute__((unused)) bool ignore_error) { long val; char *endptr; char *warn = ""; #ifndef _STRICT_CONFIG_ if (ignore_error && !__test_bit(CONFIG_TEST_BIT, &debug)) warn = "WARNING - "; #endif errno = 0; val = strtol(number, &endptr, base); *res = (int)val; if (*endptr) report_config_error(CONFIG_INVALID_NUMBER, "%sinvalid number '%s'", warn, number); else if (errno == ERANGE || val < INT_MIN || val > INT_MAX) report_config_error(CONFIG_INVALID_NUMBER, "%snumber '%s' outside integer range", warn, number); else if (val < min_val || val > max_val) report_config_error(CONFIG_INVALID_NUMBER, "number '%s' outside range [%d, %d]", number, min_val, max_val); else return true; #ifdef _STRICT_CONFIG_ return false; #else return ignore_error && val >= min_val && val <= max_val && !__test_bit(CONFIG_TEST_BIT, &debug); #endif } static bool read_unsigned_func(const char *number, int base, unsigned *res, unsigned min_val, unsigned max_val, __attribute__((unused)) bool ignore_error) { unsigned long val; char *endptr; char *warn = ""; size_t offset; #ifndef _STRICT_CONFIG_ if (ignore_error && !__test_bit(CONFIG_TEST_BIT, &debug)) warn = "WARNING - "; #endif /* In case the string starts with spaces (even in the configuration this * can be achieved by enclosing the number in quotes - e.g. weight " -100") * skip any leading whitespace */ offset = strspn(number, WHITE_SPACE); errno = 0; val = strtoul(number + offset, &endptr, base); *res = (unsigned)val; if (number[offset] == '-') report_config_error(CONFIG_INVALID_NUMBER, "%snegative number '%s'", warn, number); else if (*endptr) report_config_error(CONFIG_INVALID_NUMBER, "%sinvalid number '%s'", warn, number); else if (errno == ERANGE || val > UINT_MAX) report_config_error(CONFIG_INVALID_NUMBER, "%snumber '%s' outside unsigned integer range", warn, number); else if (val < min_val || val > max_val) report_config_error(CONFIG_INVALID_NUMBER, "number '%s' outside range [%u, %u]", number, min_val, max_val); else return true; #ifdef _STRICT_CONFIG_ return false; #else return ignore_error && val >= min_val && val <= max_val && !__test_bit(CONFIG_TEST_BIT, &debug); #endif } static bool read_unsigned64_func(const char *number, int base, uint64_t *res, uint64_t min_val, uint64_t max_val, __attribute__((unused)) bool ignore_error) { unsigned long long val; char *endptr; char *warn = ""; size_t offset; #ifndef _STRICT_CONFIG_ if (ignore_error && !__test_bit(CONFIG_TEST_BIT, &debug)) warn = "WARNING - "; #endif /* In case the string starts with spaces (even in the configuration this * can be achieved by enclosing the number in quotes - e.g. weight " -100") * skip any leading whitespace */ offset = strspn(number, WHITE_SPACE); errno = 0; val = strtoull(number + offset, &endptr, base); *res = (unsigned)val; if (number[offset] == '-') report_config_error(CONFIG_INVALID_NUMBER, "%snegative number '%s'", warn, number); else if (*endptr) report_config_error(CONFIG_INVALID_NUMBER, "%sinvalid number '%s'", warn, number); else if (errno == ERANGE) report_config_error(CONFIG_INVALID_NUMBER, "%snumber '%s' outside unsigned 64 bit range", warn, number); else if (val < min_val || val > max_val) report_config_error(CONFIG_INVALID_NUMBER, "number '%s' outside range [%" PRIu64 ", %" PRIu64 "]", number, min_val, max_val); else return true; #ifdef _STRICT_CONFIG_ return false; #else return ignore_error && val >= min_val && val <= max_val && !__test_bit(CONFIG_TEST_BIT, &debug); #endif } static bool read_double_func(const char *number, double *res, double min_val, double max_val, __attribute__((unused)) bool ignore_error) { double val; char *endptr; char *warn = ""; #ifndef _STRICT_CONFIG_ if (ignore_error && !__test_bit(CONFIG_TEST_BIT, &debug)) warn = "WARNING - "; #endif errno = 0; val = strtod(number, &endptr); *res = val; if (*endptr) report_config_error(CONFIG_INVALID_NUMBER, "%sinvalid number '%s'", warn, number); else if (errno == ERANGE) report_config_error(CONFIG_INVALID_NUMBER, "%snumber '%s' out of range", warn, number); else if (val == -HUGE_VAL || val == HUGE_VAL) /* +/- Inf */ report_config_error(CONFIG_INVALID_NUMBER, "infinite number '%s'", number); else if (!(val <= 0 || val >= 0)) /* NaN */ report_config_error(CONFIG_INVALID_NUMBER, "not a number '%s'", number); else if (val < min_val || val > max_val) report_config_error(CONFIG_INVALID_NUMBER, "number '%s' outside range [%g, %g]", number, min_val, max_val); else return true; #ifdef _STRICT_CONFIG_ return false; #else return ignore_error && val >= min_val && val <= max_val && !__test_bit(CONFIG_TEST_BIT, &debug); #endif } bool read_int(const char *str, int *res, int min_val, int max_val, bool ignore_error) { return read_int_func(str, 10, res, min_val, max_val, ignore_error); } bool read_unsigned(const char *str, unsigned *res, unsigned min_val, unsigned max_val, bool ignore_error) { return read_unsigned_func(str, 10, res, min_val, max_val, ignore_error); } bool read_unsigned64(const char *str, uint64_t *res, uint64_t min_val, uint64_t max_val, bool ignore_error) { return read_unsigned64_func(str, 10, res, min_val, max_val, ignore_error); } bool read_double(const char *str, double *res, double min_val, double max_val, bool ignore_error) { return read_double_func(str, res, min_val, max_val, ignore_error); } bool read_int_strvec(const vector_t *strvec, size_t index, int *res, int min_val, int max_val, bool ignore_error) { return read_int_func(strvec_slot(strvec, index), 10, res, min_val, max_val, ignore_error); } bool read_unsigned_strvec(const vector_t *strvec, size_t index, unsigned *res, unsigned min_val, unsigned max_val, bool ignore_error) { return read_unsigned_func(strvec_slot(strvec, index), 10, res, min_val, max_val, ignore_error); } bool read_unsigned64_strvec(const vector_t *strvec, size_t index, uint64_t *res, uint64_t min_val, uint64_t max_val, bool ignore_error) { return read_unsigned64_func(strvec_slot(strvec, index), 10, res, min_val, max_val, ignore_error); } bool read_double_strvec(const vector_t *strvec, size_t index, double *res, double min_val, double max_val, bool ignore_error) { return read_double_func(strvec_slot(strvec, index), res, min_val, max_val, ignore_error); } bool read_unsigned_base_strvec(const vector_t *strvec, size_t index, int base, unsigned *res, unsigned min_val, unsigned max_val, bool ignore_error) { return read_unsigned_func(strvec_slot(strvec, index), base, res, min_val, max_val, ignore_error); } static void keyword_alloc(vector_t *keywords_vec, const char *string, void (*handler) (vector_t *), bool active) { keyword_t *keyword; vector_alloc_slot(keywords_vec); keyword = (keyword_t *) MALLOC(sizeof(keyword_t)); keyword->string = string; keyword->handler = handler; keyword->active = active; vector_set_slot(keywords_vec, keyword); } static void keyword_alloc_sub(vector_t *keywords_vec, const char *string, void (*handler) (vector_t *)) { int i = 0; keyword_t *keyword; /* fetch last keyword */ keyword = vector_slot(keywords_vec, vector_size(keywords_vec) - 1); /* Don't install subordinate keywords if configuration block inactive */ if (!keyword->active) return; /* position to last sub level */ for (i = 0; i < sublevel; i++) keyword = vector_slot(keyword->sub, vector_size(keyword->sub) - 1); /* First sub level allocation */ if (!keyword->sub) keyword->sub = vector_alloc(); /* add new sub keyword */ keyword_alloc(keyword->sub, string, handler, true); } /* Exported helpers */ void install_sublevel(void) { sublevel++; } void install_sublevel_end(void) { sublevel--; } void install_keyword_root(const char *string, void (*handler) (vector_t *), bool active) { /* If the root keyword is inactive, the handler will still be called, * but with a NULL strvec */ keyword_alloc(keywords, string, handler, active); } void install_root_end_handler(void (*handler) (void)) { keyword_t *keyword; /* fetch last keyword */ keyword = vector_slot(keywords, vector_size(keywords) - 1); if (!keyword->active) return; keyword->sub_close_handler = handler; } void install_keyword(const char *string, void (*handler) (vector_t *)) { keyword_alloc_sub(keywords, string, handler); } void install_sublevel_end_handler(void (*handler) (void)) { int i = 0; keyword_t *keyword; /* fetch last keyword */ keyword = vector_slot(keywords, vector_size(keywords) - 1); if (!keyword->active) return; /* position to last sub level */ for (i = 0; i < sublevel; i++) keyword = vector_slot(keyword->sub, vector_size(keyword->sub) - 1); keyword->sub_close_handler = handler; } #if DUMP_KEYWORDS static void dump_keywords(vector_t *keydump, int level, FILE *fp) { unsigned int i; keyword_t *keyword_vec; char file_name[22]; if (!level) { snprintf(file_name, sizeof(file_name), "/tmp/keywords.%d", getpid()); fp = fopen_safe(file_name, "w"); if (!fp) return; } for (i = 0; i < vector_size(keydump); i++) { keyword_vec = vector_slot(keydump, i); fprintf(fp, "%*sKeyword : %s (%s)\n", level * 2, "", keyword_vec->string, keyword_vec->active ? "active": "disabled"); if (keyword_vec->sub) dump_keywords(keyword_vec->sub, level + 1, fp); } if (!level) fclose(fp); } #endif static void free_keywords(vector_t *keywords_vec) { keyword_t *keyword_vec; unsigned int i; for (i = 0; i < vector_size(keywords_vec); i++) { keyword_vec = vector_slot(keywords_vec, i); if (keyword_vec->sub) free_keywords(keyword_vec->sub); FREE(keyword_vec); } vector_free(keywords_vec); } /* Functions used for standard definitions */ static char * get_cwd(void) { char *dir = MALLOC(PATH_MAX); /* Since keepalived doesn't do a chroot(), we don't need to be concerned * about (unreachable) - see getcwd(3) man page. */ return getcwd(dir, PATH_MAX); } static char * get_instance(void) { char *conf_id = MALLOC(strlen(config_id) + 1); strcpy(conf_id, config_id); return conf_id; } vector_t * alloc_strvec_quoted_escaped(char *src) { char *token; vector_t *strvec; char cur_quote = 0; char *ofs_op; char *op_buf; char *ofs, *ofs1; char op_char; if (!src) { if (!buf_extern) return NULL; src = buf_extern; } /* Create a vector and alloc each command piece */ strvec = vector_alloc(); op_buf = MALLOC(MAXBUF); ofs = src; while (*ofs) { /* Find the next 'word' */ ofs += strspn(ofs, WHITE_SPACE); if (!*ofs) break; ofs_op = op_buf; while (*ofs) { ofs1 = strpbrk(ofs, cur_quote == '"' ? "\"\\" : cur_quote == '\'' ? "'\\" : WHITE_SPACE_STR "'\"\\"); if (!ofs1) { size_t len; if (cur_quote) { report_config_error(CONFIG_UNMATCHED_QUOTE, "String '%s': missing terminating %c", src, cur_quote); goto err_exit; } strcpy(ofs_op, ofs); len = strlen(ofs); ofs += len; ofs_op += len; break; } /* Save the wanted text */ strncpy(ofs_op, ofs, ofs1 - ofs); ofs_op += ofs1 - ofs; ofs = ofs1; if (*ofs == '\\') { /* It is a '\' */ ofs++; if (!*ofs) { log_message(LOG_INFO, "Missing escape char at end: '%s'", src); goto err_exit; } if (*ofs == 'x' && isxdigit(ofs[1])) { op_char = 0; ofs++; while (isxdigit(*ofs)) { op_char <<= 4; op_char |= isdigit(*ofs) ? *ofs - '0' : (10 + *ofs - (isupper(*ofs) ? 'A' : 'a')); ofs++; } } else if (*ofs == 'c' && ofs[1]) { op_char = *++ofs & 0x1f; /* Convert to control character */ ofs++; } else if (*ofs >= '0' && *ofs <= '7') { op_char = *ofs++ - '0'; if (*ofs >= '0' && *ofs <= '7') { op_char <<= 3; op_char += *ofs++ - '0'; } if (*ofs >= '0' && *ofs <= '7') { op_char <<= 3; op_char += *ofs++ - '0'; } } else { switch (*ofs) { case 'a': op_char = '\a'; break; case 'b': op_char = '\b'; break; case 'E': op_char = 0x1b; break; case 'f': op_char = '\f'; break; case 'n': op_char = '\n'; break; case 'r': op_char = '\r'; break; case 't': op_char = '\t'; break; case 'v': op_char = '\v'; break; default: /* \"' */ op_char = *ofs; break; } ofs++; } *ofs_op++ = op_char; continue; } if (cur_quote) { /* It's the close quote */ ofs++; cur_quote = 0; continue; } if (*ofs == '"' || *ofs == '\'') { cur_quote = *ofs++; continue; } break; } token = MALLOC(ofs_op - op_buf + 1); memcpy(token, op_buf, ofs_op - op_buf); token[ofs_op - op_buf] = '\0'; /* Alloc & set the slot */ vector_alloc_slot(strvec); vector_set_slot(strvec, token); } FREE(op_buf); if (!vector_size(strvec)) { free_strvec(strvec); return NULL; } return strvec; err_exit: free_strvec(strvec); FREE(op_buf); return NULL; } vector_t * alloc_strvec_r(char *string) { char *cp, *start, *token; size_t str_len; vector_t *strvec; if (!string) return NULL; /* Create a vector and alloc each command piece */ strvec = vector_alloc(); cp = string; while (true) { cp += strspn(cp, WHITE_SPACE); if (!*cp) break; start = cp; /* Save a quoted string without the ""s as a single string */ if (*start == '"') { start++; if (!(cp = strchr(start, '"'))) { report_config_error(CONFIG_UNMATCHED_QUOTE, "Unmatched quote: '%s'", string); break; } str_len = (size_t)(cp - start); cp++; } else { cp += strcspn(start, WHITE_SPACE_STR "\""); str_len = (size_t)(cp - start); } token = MALLOC(str_len + 1); memcpy(token, start, str_len); token[str_len] = '\0'; /* Alloc & set the slot */ vector_alloc_slot(strvec); vector_set_slot(strvec, token); } if (!vector_size(strvec)) { free_strvec(strvec); return NULL; } return strvec; } typedef struct _seq { char *var; int next; int last; int step; char *text; } seq_t; static list seq_list; /* List of seq_t */ #ifdef PARSER_DEBUG static void dump_seqs(void) { seq_t *seq; element e; LIST_FOREACH(seq_list, seq, e) log_message(LOG_INFO, "SEQ: %s => %d -> %d step %d: '%s'", seq->var, seq->next, seq->last, seq->step, seq->text); log_message(LOG_INFO, "%s", ""); } #endif static void free_seq(void *s) { seq_t *seq = s; FREE(seq->var); FREE(seq->text); FREE(seq); } static bool add_seq(char *buf) { char *p = buf + 4; /* Skip ~SEQ */ long one, two, three; long start, step, end; seq_t *seq_ent; char *var; char *var_end; p += strspn(p, " \t"); if (*p++ != '(') return false; p += strspn(p, " \t"); var = p; p += strcspn(p, " \t,)"); var_end = p; p += strspn(p, " \t"); if (!*p || *p == ')' || p == var) { report_config_error(CONFIG_GENERAL_ERROR, "Invalid ~SEQ definition '%s'", buf); return false; } p++; do { // Handle missing number one = strtol(p, &p, 0); p += strspn(p, " \t"); if (*p == ')') { end = one; step = (end < 1) ? -1 : 1; start = (end < 0) ? -1 : 1; break; } if (*p != ',') { report_config_error(CONFIG_GENERAL_ERROR, "Invalid ~SEQ definition '%s'", buf); return false; } two = strtol(p + 1, &p, 0); p += strspn(p, " \t"); if (*p == ')') { start = one; end = two; step = start <= end ? 1 : -1; break; } if (*p != ',') { report_config_error(CONFIG_GENERAL_ERROR, "Invalid ~SEQ definition '%s'", buf); return false; } three = strtol(p + 1, &p, 0); p += strspn(p, " \t"); if (*p != ')') { report_config_error(CONFIG_GENERAL_ERROR, "Invalid ~SEQ definition '%s'", buf); return false; } start = one; step = two; end = three; if (!step || (start < end && step < 0) || (start > end && step > 0)) { report_config_error(CONFIG_GENERAL_ERROR, "Invalid ~SEQ values '%s'", buf); return false; } } while (false); p += strspn(p + 1, " \t") + 1; PMALLOC(seq_ent); seq_ent->var = MALLOC(var_end - var + 1); strncpy(seq_ent->var, var, var_end - var); seq_ent->next = start; seq_ent->step = step; seq_ent->last = end; seq_ent->text = MALLOC(strlen(p) + 1); strcpy(seq_ent->text, p); if (!seq_list) seq_list = alloc_list(free_seq, NULL); list_add(seq_list, seq_ent); return true; } #ifdef PARSER_DEBUG static void dump_definitions(void) { def_t *def; element e; LIST_FOREACH(defs, def, e) log_message(LOG_INFO, "Defn %s = '%s'", def->name, def->value); log_message(LOG_INFO, "%s", ""); } #endif /* recursive configuration stream handler */ static int kw_level; static int block_depth; static bool process_stream(vector_t *keywords_vec, int need_bob) { unsigned int i; keyword_t *keyword_vec; char *str; char *buf; vector_t *strvec; vector_t *prev_keywords = current_keywords; current_keywords = keywords_vec; int bob_needed = 0; bool ret_err = false; bool ret; buf = MALLOC(MAXBUF); while (read_line(buf, MAXBUF)) { strvec = alloc_strvec(buf); if (!strvec) continue; str = vector_slot(strvec, 0); if (skip_sublevel == -1) { /* There wasn't a '{' on the keyword line */ if (!strcmp(str, BOB)) { /* We've got the opening '{' now */ skip_sublevel = 1; need_bob = 0; free_strvec(strvec); continue; } /* The skipped keyword doesn't have a {} block, so we no longer want to skip */ skip_sublevel = 0; } if (skip_sublevel) { for (i = 0; i < vector_size(strvec); i++) { str = vector_slot(strvec,i); if (!strcmp(str,BOB)) skip_sublevel++; else if (!strcmp(str,EOB)) { if (--skip_sublevel == 0) break; } } /* If we have reached the outer level of the block and we have * nested keyword level, then we need to return to restore the * next level up of keywords. */ if (!strcmp(str, EOB) && skip_sublevel == 0 && kw_level > 0) { ret_err = true; free_strvec(strvec); break; } free_strvec(strvec); continue; } if (need_bob) { need_bob = 0; if (!strcmp(str, BOB) && kw_level > 0) { free_strvec(strvec); continue; } else report_config_error(CONFIG_MISSING_BOB, "Missing '%s' at beginning of configuration block", BOB); } else if (!strcmp(str, BOB)) { report_config_error(CONFIG_UNEXPECTED_BOB, "Unexpected '%s' - ignoring", BOB); free_strvec(strvec); continue; } if (!strcmp(str, EOB) && kw_level > 0) { free_strvec(strvec); break; } if (!strncmp(str, "~SEQ", 4)) { if (!add_seq(buf)) report_config_error(CONFIG_GENERAL_ERROR, "Invalid ~SEQ specification '%s'", buf); free_strvec(strvec); #ifdef PARSER_DEBUG dump_definitions(); dump_seqs(); #endif continue; } for (i = 0; i < vector_size(keywords_vec); i++) { keyword_vec = vector_slot(keywords_vec, i); if (!strcmp(keyword_vec->string, str)) { if (!keyword_vec->active) { if (!strcmp(vector_slot(strvec, vector_size(strvec)-1), BOB)) skip_sublevel = 1; else skip_sublevel = -1; /* Sometimes a process wants to know if another process * has any of a type of configuration. For example, there * is no point starting the VRRP process of there are no * vrrp instances, and so the parent process would be * interested in that. */ if (keyword_vec->handler) (*keyword_vec->handler)(NULL); } /* There is an inconsistency here. 'static_ipaddress' for example * does not have sub levels, but needs a '{' */ if (keyword_vec->sub) { /* Remove a trailing '{' */ char *bob = vector_slot(strvec, vector_size(strvec)-1) ; if (!strcmp(bob, BOB)) { vector_unset(strvec, vector_size(strvec)-1); FREE(bob); bob_needed = 0; } else bob_needed = 1; } if (keyword_vec->active && keyword_vec->handler) { buf_extern = buf; /* In case the raw line wants to be accessed */ (*keyword_vec->handler) (strvec); } if (keyword_vec->sub) { kw_level++; ret = process_stream(keyword_vec->sub, bob_needed); kw_level--; /* We mustn't run any close handler if the block was skipped */ if (!ret && keyword_vec->active && keyword_vec->sub_close_handler) (*keyword_vec->sub_close_handler) (); } break; } } if (i >= vector_size(keywords_vec)) report_config_error(CONFIG_UNKNOWN_KEYWORD, "Unknown keyword '%s'", str); free_strvec(strvec); } current_keywords = prev_keywords; FREE(buf); return ret_err; } static bool read_conf_file(const char *conf_file) { FILE *stream; glob_t globbuf; size_t i; int res; struct stat stb; unsigned num_matches = 0; globbuf.gl_offs = 0; res = glob(conf_file, GLOB_MARK #if HAVE_DECL_GLOB_BRACE | GLOB_BRACE #endif , NULL, &globbuf); if (res) { if (res == GLOB_NOMATCH) log_message(LOG_INFO, "No config files matched '%s'.", conf_file); else log_message(LOG_INFO, "Error reading config file(s): glob(\"%s\") returned %d, skipping.", conf_file, res); return true; } for (i = 0; i < globbuf.gl_pathc; i++) { if (globbuf.gl_pathv[i][strlen(globbuf.gl_pathv[i])-1] == '/') { /* This is a directory - so skip */ continue; } log_message(LOG_INFO, "Opening file '%s'.", globbuf.gl_pathv[i]); stream = fopen(globbuf.gl_pathv[i], "r"); if (!stream) { log_message(LOG_INFO, "Configuration file '%s' open problem (%s) - skipping" , globbuf.gl_pathv[i], strerror(errno)); continue; } /* Make sure what we have opened is a regular file, and not for example a directory or executable */ if (fstat(fileno(stream), &stb) || !S_ISREG(stb.st_mode) || (stb.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))) { log_message(LOG_INFO, "Configuration file '%s' is not a regular non-executable file - skipping", globbuf.gl_pathv[i]); fclose(stream); continue; } num_matches++; current_stream = stream; /* We only want to report the file name if there is more than one file used */ if (current_file_name || globbuf.gl_pathc > 1) current_file_name = globbuf.gl_pathv[i]; current_file_line_no = 0; int curdir_fd = -1; if (strchr(globbuf.gl_pathv[i], '/')) { /* If the filename contains a directory element, change to that directory. The man page open(2) states that fchdir() didn't support O_PATH until Linux 3.5, even though testing on Linux 3.1 shows it appears to work. To be safe, don't use it until Linux 3.5. */ curdir_fd = open(".", O_RDONLY | O_DIRECTORY #if HAVE_DECL_O_PATH && LINUX_VERSION_CODE >= KERNEL_VERSION(3,5,0) | O_PATH #endif ); char *confpath = strdup(globbuf.gl_pathv[i]); dirname(confpath); if (chdir(confpath) < 0) log_message(LOG_INFO, "chdir(%s) error (%s)", confpath, strerror(errno)); free(confpath); } process_stream(current_keywords, 0); fclose(stream); free_list(&seq_list); /* If we changed directory, restore the previous directory */ if (curdir_fd != -1) { if ((res = fchdir(curdir_fd))) log_message(LOG_INFO, "Failed to restore previous directory after include"); close(curdir_fd); if (res) return true; } } globfree(&globbuf); if (!num_matches) log_message(LOG_INFO, "No config files matched '%s'.", conf_file); return false; } bool check_conf_file(const char *conf_file) { glob_t globbuf; size_t i; bool ret = true; int res; struct stat stb; unsigned num_matches = 0; globbuf.gl_offs = 0; res = glob(conf_file, GLOB_MARK #if HAVE_DECL_GLOB_BRACE | GLOB_BRACE #endif , NULL, &globbuf); if (res) { report_config_error(CONFIG_FILE_NOT_FOUND, "Unable to find configuration file %s (glob returned %d)", conf_file, res); return false; } for (i = 0; i < globbuf.gl_pathc; i++) { if (globbuf.gl_pathv[i][strlen(globbuf.gl_pathv[i])-1] == '/') { /* This is a directory - so skip */ continue; } if (access(globbuf.gl_pathv[i], R_OK)) { log_message(LOG_INFO, "Unable to read configuration file %s", globbuf.gl_pathv[i]); ret = false; break; } /* Make sure that the file is a regular file, and not for example a directory or executable */ if (stat(globbuf.gl_pathv[i], &stb) || !S_ISREG(stb.st_mode) || (stb.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))) { log_message(LOG_INFO, "Configuration file '%s' is not a regular non-executable file", globbuf.gl_pathv[i]); ret = false; break; } num_matches++; } if (ret) { if (num_matches > 1) report_config_error(CONFIG_MULTIPLE_FILES, "WARNING, more than one file matches configuration file %s, using %s", conf_file, globbuf.gl_pathv[0]); else if (num_matches == 0) { report_config_error(CONFIG_FILE_NOT_FOUND, "Unable to find configuration file %s", conf_file); ret = false; } } globfree(&globbuf); return ret; } static bool check_include(char *buf) { vector_t *strvec; bool ret = false; FILE *prev_stream; const char *prev_file_name; size_t prev_file_line_no; /* Simple check first for include */ if (!strstr(buf, "include")) return false; strvec = alloc_strvec(buf); if (!strvec) return false; if(!strcmp("include", vector_slot(strvec, 0)) && vector_size(strvec) == 2) { prev_stream = current_stream; prev_file_name = current_file_name; prev_file_line_no = current_file_line_no; read_conf_file(vector_slot(strvec, 1)); current_stream = prev_stream; current_file_name = prev_file_name; current_file_line_no = prev_file_line_no; ret = true; } free_strvec(strvec); return ret; } static def_t * find_definition(const char *name, size_t len, bool definition) { element e; def_t *def; const char *p; bool using_braces = false; bool allow_multiline; if (LIST_ISEMPTY(defs)) return NULL; if (!definition && *name == BOB[0]) { using_braces = true; name++; } if (!isalpha(*name) && *name != '_') return NULL; if (!len) { for (len = 1, p = name + 1; *p != '\0' && (isalnum(*p) || *p == '_'); len++, p++); /* Check we have a suitable end character */ if (using_braces && *p != EOB[0]) return NULL; if (!using_braces && !definition && *p != ' ' && *p != '\t' && *p != '\0') return NULL; } if (definition || (!using_braces && name[len] == '\0') || (using_braces && name[len+1] == '\0')) allow_multiline = true; else allow_multiline = false; for (e = LIST_HEAD(defs); e; ELEMENT_NEXT(e)) { def = ELEMENT_DATA(e); if (def->name_len == len && (allow_multiline || !def->multiline) && !strncmp(def->name, name, len)) return def; } return NULL; } static bool replace_param(char *buf, size_t max_len, char **multiline_ptr_ptr) { char *cur_pos = buf; size_t len_used = strlen(buf); def_t *def; char *s, *d, *e; ssize_t i; size_t extra_braces; size_t replacing_len; char *next_ptr = NULL; bool found_defn = false; char *multiline_ptr = *multiline_ptr_ptr; while ((cur_pos = strchr(cur_pos, '$')) && cur_pos[1] != '\0') { if ((def = find_definition(cur_pos + 1, 0, false))) { found_defn = true; extra_braces = cur_pos[1] == BOB[0] ? 2 : 0; next_ptr = multiline_ptr; /* We are in a multiline expansion, and now have another * one, so save the previous state on the multiline stack */ if (def->multiline && multiline_ptr) { if (!LIST_EXISTS(multiline_stack)) multiline_stack = alloc_list(NULL, NULL); list_add(multiline_stack, multiline_ptr); } if (def->fn) { /* This is a standard definition that uses a function for the replacement text */ if (def->value) FREE(def->value); def->value = (*def->fn)(); def->value_len = strlen(def->value); } /* Ensure there is enough room to replace $PARAM or ${PARAM} with value */ if (def->multiline) { replacing_len = strcspn(def->value, DEF_LINE_END); next_ptr = def->value + replacing_len + 1; multiline_ptr = next_ptr; } else replacing_len = def->value_len; if (len_used + replacing_len - (def->name_len + 1 + extra_braces) >= max_len) { log_message(LOG_INFO, "Parameter substitution on line '%s' would exceed maximum line length", buf); return NULL; } if (def->name_len + 1 + extra_braces != replacing_len) { /* We need to move the existing text */ if (def->name_len + 1 + extra_braces < replacing_len) { /* We are lengthening the buf text */ s = cur_pos + strlen(cur_pos); d = s - (def->name_len + 1 + extra_braces) + replacing_len; e = cur_pos; i = -1; } else { /* We are shortening the buf text */ s = cur_pos + (def->name_len + 1 + extra_braces) - replacing_len; d = cur_pos; e = cur_pos + strlen(cur_pos); i = 1; } do { *d = *s; if (s == e) break; d += i; s += i; } while (true); len_used = len_used + replacing_len - (def->name_len + 1 + extra_braces); } /* Now copy the replacement text */ strncpy(cur_pos, def->value, replacing_len); if (def->value[strspn(def->value, " \t")] == '~') break; } else cur_pos++; } /* If we did a replacement, update the multiline_ptr */ if (found_defn) *multiline_ptr_ptr = next_ptr; return found_defn; } static void free_definition(void *d) { def_t *def = d; FREE(def->name); FREE_PTR(def->value); FREE(def); } static def_t* set_definition(const char *name, const char *value) { def_t *def; size_t name_len = strlen(name); if ((def = find_definition(name, name_len, false))) { FREE(def->value); def->fn = NULL; /* Allow a standard definition to be overridden */ } else { def = MALLOC(sizeof(*def)); def->name_len = name_len; def->name = MALLOC(name_len + 1); strcpy(def->name, name); if (!LIST_EXISTS(defs)) defs = alloc_list(free_definition, NULL); list_add(defs, def); } def->value_len = strlen(value); def->value = MALLOC(def->value_len + 1); strcpy(def->value, value); #ifdef PARSER_DEBUG log_message(LOG_INFO, "Definition %s now '%s'", def->name, def->value); #endif return def; } /* A definition is of the form $NAME=TEXT */ static def_t* check_definition(const char *buf) { const char *p; def_t* def; size_t def_name_len; char *str; if (buf[0] != '$') return false; if (!isalpha(buf[1]) && buf[1] != '_') return NULL; for (p = buf + 2; *p; p++) { if (*p == '=') break; if (!isalnum(*p) && !isdigit(*p) && *p != '_') return NULL; } def_name_len = (size_t)(p - &buf[1]); p += strspn(p, " \t"); if (*p != '=') return NULL; if ((def = find_definition(&buf[1], def_name_len, true))) { FREE(def->value); def->fn = NULL; /* Allow a standard definition to be overridden */ } else { def = MALLOC(sizeof(*def)); def->name_len = def_name_len; str = MALLOC(def->name_len + 1); strncpy(str, &buf[1], def->name_len); str[def->name_len] = '\0'; def->name = str; if (!LIST_EXISTS(defs)) defs = alloc_list(free_definition, NULL); list_add(defs, def); } /* Skip leading whitespace */ p += strspn(p + 1, " \t") + 1; def->value_len = strlen(p); if (p[def->value_len - 1] == '\\') { /* Remove trailing whitespace */ while (def->value_len >= 2 && isblank(p[def->value_len - 2])) def->value_len--; if (def->value_len < 2) { /* If the string has nothing except spaces and terminating '\' * point to the string terminator. */ p += def->value_len; def->value_len = 0; } def->multiline = true; } else def->multiline = false; str = MALLOC(def->value_len + 1); strcpy(str, p); def->value = str; /* If it a multiline definition, we need to mark the end of the first line * by overwriting the '\' with the line end marker. */ if (def->value_len >= 2 && def->multiline) def->value[def->value_len - 1] = DEF_LINE_END[0]; return def; } static void add_std_definition(const char *name, const char *value, char *(*fn)(void)) { def_t* def; def = MALLOC(sizeof(*def)); def->name_len = strlen(name); def->name = MALLOC(def->name_len + 1); strcpy(def->name, name); if (value) { def->value_len = strlen(value); def->value = MALLOC(def->value_len + 1); strcpy(def->value, value); } def->fn = fn; if (!LIST_EXISTS(defs)) defs = alloc_list(free_definition, NULL); list_add(defs, def); } static void set_std_definitions(void) { add_std_definition("_PWD", NULL, get_cwd); add_std_definition("_INSTANCE", NULL, get_instance); } static void free_parser_data(void) { if (LIST_EXISTS(defs)) free_list(&defs); if (LIST_EXISTS(multiline_stack)) free_list(&multiline_stack); } /* decomment() removes comments, the escaping of comment start characters, * and leading and trailing whitespace, including whitespace before a * terminating \ character */ static void decomment(char *str) { bool quote = false; bool cont = false; char *skip = NULL; char *p = str + strspn(str, " \t"); /* Remove leading whitespace */ if (p != str) memmove(str, p, strlen(p) + 1); p = str; while ((p = strpbrk(p, "!#\"\\"))) { if (*p == '"') { if (!skip) quote = !quote; p++; continue; } if (*p == '\\') { if (p[1]) { /* Don't modify quoted strings */ if (!quote && (p[1] == '#' || p[1] == '!')) { memmove(p, p + 1, strlen(p + 1) + 1); p++; } else p += 2; continue; } *p = '\0'; cont = true; break; } if (!quote && !skip && (*p == '!' || *p == '#')) skip = p; p++; } if (quote) report_config_error(CONFIG_GENERAL_ERROR, "Unterminated quote '%s'", str); if (skip) *skip = '\0'; /* Remove trailing whitespace */ p = str + strlen(str) - 1; while (p >= str && isblank(*p)) *p-- = '\0'; if (cont) { *++p = '\\'; *++p = '\0'; } } static bool read_line(char *buf, size_t size) { size_t len ; bool eof = false; size_t config_id_len; char *buf_start; bool rev_cmp; size_t ofs; bool recheck; static def_t *def = NULL; static char *next_ptr = NULL; bool multiline_param_def = false; char *end; static char *line_residue = NULL; size_t skip; char *p; config_id_len = config_id ? strlen(config_id) : 0; do { if (line_residue) { strcpy(buf, line_residue); FREE(line_residue); line_residue = NULL; } else if (next_ptr) { /* We are expanding a multiline parameter, so copy next line */ end = strchr(next_ptr, DEF_LINE_END[0]); if (!end) { strcpy(buf, next_ptr); if (!LIST_ISEMPTY(multiline_stack)) { next_ptr = LIST_TAIL_DATA(multiline_stack); list_remove(multiline_stack, multiline_stack->tail); } else next_ptr = NULL; } else { strncpy(buf, next_ptr, (size_t)(end - next_ptr)); buf[end - next_ptr] = '\0'; next_ptr = end + 1; } } else if (!LIST_ISEMPTY(seq_list)) { seq_t *seq = LIST_TAIL_DATA(seq_list); char val[12]; snprintf(val, sizeof(val), "%d", seq->next); #ifdef PARSER_DEBUG log_message(LOG_INFO, "Processing seq %d of %s for '%s'", seq->next, seq->var, seq->text); #endif set_definition(seq->var, val); strcpy(buf, seq->text); seq->next += seq->step; if ((seq->step > 0 && seq->next > seq->last) || (seq->step < 0 && seq->next < seq->last)) { #ifdef PARSER_DEBUG log_message(LOG_INFO, "Removing seq %s for '%s'", seq->var, seq->text); #endif list_remove(seq_list, seq_list->tail); } } else { retry: if (!fgets(buf, (int)size, current_stream)) { eof = true; buf[0] = '\0'; break; } /* Check if we have read the end of a line */ len = strlen(buf); if (buf[0] && buf[len-1] == '\n') current_file_line_no++; /* Remove end of line chars */ while (len && (buf[len-1] == '\n' || buf[len-1] == '\r')) len--; /* Skip blank lines */ if (!len) goto retry; buf[len] = '\0'; decomment(buf); } len = strlen(buf); /* Handle multi-line definitions */ if (multiline_param_def) { /* Remove trailing whitespace */ if (len && buf[len-1] == '\\') { len--; while (len >= 1 && isblank(buf[len - 1])) len--; buf[len++] = DEF_LINE_END[0]; } else { multiline_param_def = false; if (!def->value_len) def->multiline = false; } /* Don't add blank lines */ if (len >= 2 || (len && !multiline_param_def)) { /* Add the line to the definition */ def->value = REALLOC(def->value, def->value_len + len + 1); strncpy(def->value + def->value_len, buf, len); def->value_len += len; def->value[def->value_len] = '\0'; } buf[0] = '\0'; continue; } if (len == 0) continue; recheck = false; do { if (buf[0] == '@') { /* If the line starts '@', check the following word matches the system id. @^ reverses the sense of the match */ if (buf[1] == '^') { rev_cmp = true; ofs = 2; } else { rev_cmp = false; ofs = 1; } /* We need something after the system_id */ if (!(buf_start = strpbrk(buf + ofs, " \t"))) { buf[0] = '\0'; break; } /* Check if config_id matches/doesn't match as appropriate */ if ((!config_id || (size_t)(buf_start - (buf + ofs)) != config_id_len || strncmp(buf + ofs, config_id, config_id_len)) != rev_cmp) { buf[0] = '\0'; break; } /* Remove the @config_id from start of line */ buf_start += strspn(buf_start, " \t"); len -= (buf_start - buf); memmove(buf, buf_start, len + 1); } if (buf[0] == '$' && (def = check_definition(buf))) { /* check_definition() saves the definition */ if (def->multiline) multiline_param_def = true; buf[0] = '\0'; break; } if (buf[0] == '~') break; if (!LIST_ISEMPTY(defs) && (p = strchr(buf, '$'))) { if (!replace_param(buf, size, &next_ptr)) { /* If nothing has changed, we don't need to do any more processing */ break; } if (buf[0] == '@') recheck = true; if (strchr(buf, '$')) recheck = true; } } while (recheck); } while (buf[0] == '\0' || check_include(buf)); /* Search for BOB[0] or EOB[0] not in "" */ if (buf[0]) { p = buf; if (p[0] != BOB[0] && p[0] != EOB[0]) { while ((p = strpbrk(p, BOB EOB "\""))) { if (*p != '"') break; /* Skip over anything in ""s */ if (!(p = strchr(p + 1, '"'))) break; p++; } } if (p && (p[0] == BOB[0] || p[0] == EOB[0])) { if (p == buf) skip = strspn(p + 1, " \t") + 1; else skip = 0; if (p[skip]) { /* Skip trailing whitespace */ len = strlen(p + skip); while (len && (p[skip+len-1] == ' ' || p[skip+len-1] == '\t')) len--; line_residue = MALLOC(len + 1); p[skip+len] = '\0'; strcpy(line_residue, p + skip); p[skip] = '\0'; } } /* Skip trailing whitespace */ len = strlen(buf); while (len && (buf[len-1] == ' ' || buf[len-1] == '\t')) len--; buf[len] = '\0'; /* Check that we haven't got too many '}'s */ if (!strcmp(buf, BOB)) block_depth++; else if (!strcmp(buf, EOB)) { if (--block_depth < 0) { report_config_error(CONFIG_UNEXPECTED_EOB, "Extra '}' found"); block_depth = 0; } } } #ifdef PARSER_DEBUG log_message(LOG_INFO, "read_line(%d): '%s'", block_depth, buf); #endif return !eof; } void alloc_value_block(void (*alloc_func) (vector_t *), const char *block_type) { char *buf; char *str = NULL; vector_t *vec = NULL; bool first_line = true; buf = (char *) MALLOC(MAXBUF); while (read_line(buf, MAXBUF)) { if (!(vec = alloc_strvec(buf))) continue; if (first_line) { first_line = false; if (!strcmp(vector_slot(vec, 0), BOB)) { free_strvec(vec); continue; } log_message(LOG_INFO, "'%s' missing from beginning of block %s", BOB, block_type); } str = vector_slot(vec, 0); if (!strcmp(str, EOB)) { free_strvec(vec); break; } if (vector_size(vec)) (*alloc_func) (vec); free_strvec(vec); } FREE(buf); } static vector_t *read_value_block_vec; static void read_value_block_line(vector_t *strvec) { size_t word; char *str; char *dup; if (!read_value_block_vec) read_value_block_vec = vector_alloc(); vector_foreach_slot(strvec, str, word) { dup = (char *) MALLOC(strlen(str) + 1); strcpy(dup, str); vector_alloc_slot(read_value_block_vec); vector_set_slot(read_value_block_vec, dup); } } vector_t * read_value_block(vector_t *strvec) { vector_t *ret_vec; alloc_value_block(read_value_block_line, vector_slot(strvec,0)); ret_vec = read_value_block_vec; read_value_block_vec = NULL; return ret_vec; } void * set_value(vector_t *strvec) { char *str; size_t size; char *alloc; if (vector_size(strvec) < 2) return NULL; str = vector_slot(strvec, 1); size = strlen(str); alloc = (char *) MALLOC(size + 1); if (!alloc) return NULL; memcpy(alloc, str, size); return alloc; } bool read_timer(vector_t *strvec, size_t index, unsigned long *res, unsigned long min_time, unsigned long max_time, __attribute__((unused)) bool ignore_error) { unsigned long timer; char *endptr; char *warn = ""; #ifndef _STRICT_CONFIG_ if (ignore_error && !__test_bit(CONFIG_TEST_BIT, &debug)) warn = "WARNING - "; #endif if (!max_time) max_time = TIMER_MAX; errno = 0; timer = strtoul(vector_slot(strvec, index), &endptr, 10); *res = (timer > TIMER_MAX ? TIMER_MAX : timer) * TIMER_HZ; if (FMT_STR_VSLOT(strvec, index)[0] == '-') report_config_error(CONFIG_INVALID_NUMBER, "%snegative number '%s'", warn, FMT_STR_VSLOT(strvec, index)); else if (*endptr) report_config_error(CONFIG_INVALID_NUMBER, "%sinvalid number '%s'", warn, FMT_STR_VSLOT(strvec, index)); else if (errno == ERANGE || timer > TIMER_MAX) report_config_error(CONFIG_INVALID_NUMBER, "%snumber '%s' outside timer range", warn, FMT_STR_VSLOT(strvec, index)); else if (timer < min_time || timer > max_time) report_config_error(CONFIG_INVALID_NUMBER, "number '%s' outside range [%ld, %ld]", FMT_STR_VSLOT(strvec, index), min_time, max_time ? max_time : TIMER_MAX); else return true; #ifdef _STRICT_CONFIG_ return false; #else return ignore_error && timer >= min_time && timer <= max_time && !__test_bit(CONFIG_TEST_BIT, &debug); #endif } /* Checks for on/true/yes or off/false/no */ int check_true_false(char *str) { if (!strcmp(str, "true") || !strcmp(str, "on") || !strcmp(str, "yes")) return true; if (!strcmp(str, "false") || !strcmp(str, "off") || !strcmp(str, "no")) return false; return -1; /* error */ } void skip_block(bool need_block_start) { /* Don't process the rest of the configuration block */ if (need_block_start) skip_sublevel = -1; else skip_sublevel = 1; } /* Data initialization */ void init_data(const char *conf_file, vector_t * (*init_keywords) (void)) { /* Init Keywords structure */ keywords = vector_alloc(); (*init_keywords) (); /* Add out standard definitions */ set_std_definitions(); #if DUMP_KEYWORDS /* Dump configuration */ dump_keywords(keywords, 0, NULL); #endif /* Stream handling */ current_keywords = keywords; current_file_name = NULL; current_file_line_no = 0; /* A parent process may have left these set */ block_depth = 0; kw_level = 0; register_null_strvec_handler(null_strvec); read_conf_file(conf_file); unregister_null_strvec_handler(); /* Report if there are missing '}'s. If there are missing '{'s it will already have been reported */ if (block_depth > 0) report_config_error(CONFIG_MISSING_EOB, "There are %d missing '%s's or extra '%s's", block_depth, EOB, BOB); /* We have finished reading the configuration files, so any configuration * errors report from now mustn't include a reference to the config file name */ current_file_line_no = 0; /* Close the password database if it was opened */ endpwent(); free_keywords(keywords); free_parser_data(); #ifdef _WITH_VRRP_ clear_rt_names(); #endif notify_resource_release(); }
./CrossVul/dataset_final_sorted/CWE-59/c/good_436_11
crossvul-cpp_data_good_436_4
/* * Soft: Vrrpd is an implementation of VRRPv2 as specified in rfc2338. * VRRP is a protocol which elect a master server on a LAN. If the * master fails, a backup server takes over. * The original implementation has been made by jerome etienne. * * Part: Output running VRRP state information in JSON format * * Author: Damien Clabaut, <Damien.Clabaut@corp.ovh.com> * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. * * Copyright (C) 2017 Damien Clabaut, <Damien.Clabaut@corp.ovh.com> * Copyright (C) 2017-2017 Alexandre Cassen, <acassen@gmail.com> */ #include "config.h" #include "vrrp_json.h" #include <errno.h> #include <stdio.h> #include <json.h> #include "vrrp.h" #include "vrrp_track.h" #include "list.h" #include "vrrp_data.h" #include "vrrp_iproute.h" #include "vrrp_iprule.h" #include "logger.h" #include "timer.h" #include "utils.h" static inline double timeval_to_double(const timeval_t *t) { /* The casts are necessary to avoid conversion warnings */ return (double)t->tv_sec + (double)t->tv_usec / TIMER_HZ_FLOAT; } void vrrp_print_json(void) { FILE *file; element e; struct json_object *array; if (LIST_ISEMPTY(vrrp_data->vrrp)) return; file = fopen_safe("/tmp/keepalived.json", "w"); if (!file) { log_message(LOG_INFO, "Can't open /tmp/keepalived.json (%d: %s)", errno, strerror(errno)); return; } array = json_object_new_array(); for (e = LIST_HEAD(vrrp_data->vrrp); e; ELEMENT_NEXT(e)) { struct json_object *instance_json, *json_stats, *json_data, *vips, *evips, *track_ifp, *track_script; #ifdef _HAVE_FIB_ROUTING_ struct json_object *vroutes, *vrules; #endif element f; vrrp_t *vrrp = ELEMENT_DATA(e); instance_json = json_object_new_object(); json_stats = json_object_new_object(); json_data = json_object_new_object(); vips = json_object_new_array(); evips = json_object_new_array(); track_ifp = json_object_new_array(); track_script = json_object_new_array(); #ifdef _HAVE_FIB_ROUTING_ vroutes = json_object_new_array(); vrules = json_object_new_array(); #endif // Dump data to json json_object_object_add(json_data, "iname", json_object_new_string(vrrp->iname)); json_object_object_add(json_data, "dont_track_primary", json_object_new_int(vrrp->dont_track_primary)); json_object_object_add(json_data, "skip_check_adv_addr", json_object_new_int(vrrp->skip_check_adv_addr)); json_object_object_add(json_data, "strict_mode", json_object_new_int((int)vrrp->strict_mode)); #ifdef _HAVE_VRRP_VMAC_ json_object_object_add(json_data, "vmac_ifname", json_object_new_string(vrrp->vmac_ifname)); #endif // Tracked interfaces are stored in a list if (!LIST_ISEMPTY(vrrp->track_ifp)) { for (f = LIST_HEAD(vrrp->track_ifp); f; ELEMENT_NEXT(f)) { interface_t *ifp = ELEMENT_DATA(f); json_object_array_add(track_ifp, json_object_new_string(ifp->ifname)); } } json_object_object_add(json_data, "track_ifp", track_ifp); // Tracked scripts also if (!LIST_ISEMPTY(vrrp->track_script)) { for (f = LIST_HEAD(vrrp->track_script); f; ELEMENT_NEXT(f)) { tracked_sc_t *tsc = ELEMENT_DATA(f); vrrp_script_t *vscript = tsc->scr; json_object_array_add(track_script, json_object_new_string(cmd_str(&vscript->script))); } } json_object_object_add(json_data, "track_script", track_script); json_object_object_add(json_data, "ifp_ifname", json_object_new_string(vrrp->ifp->ifname)); json_object_object_add(json_data, "master_priority", json_object_new_int(vrrp->master_priority)); json_object_object_add(json_data, "last_transition", json_object_new_double(timeval_to_double(&vrrp->last_transition))); json_object_object_add(json_data, "garp_delay", json_object_new_double(vrrp->garp_delay / TIMER_HZ_FLOAT)); json_object_object_add(json_data, "garp_refresh", json_object_new_int((int)vrrp->garp_refresh.tv_sec)); json_object_object_add(json_data, "garp_rep", json_object_new_int((int)vrrp->garp_rep)); json_object_object_add(json_data, "garp_refresh_rep", json_object_new_int((int)vrrp->garp_refresh_rep)); json_object_object_add(json_data, "garp_lower_prio_delay", json_object_new_int((int)(vrrp->garp_lower_prio_delay / TIMER_HZ))); json_object_object_add(json_data, "garp_lower_prio_rep", json_object_new_int((int)vrrp->garp_lower_prio_rep)); json_object_object_add(json_data, "lower_prio_no_advert", json_object_new_int((int)vrrp->lower_prio_no_advert)); json_object_object_add(json_data, "higher_prio_send_advert", json_object_new_int((int)vrrp->higher_prio_send_advert)); json_object_object_add(json_data, "vrid", json_object_new_int(vrrp->vrid)); json_object_object_add(json_data, "base_priority", json_object_new_int(vrrp->base_priority)); json_object_object_add(json_data, "effective_priority", json_object_new_int(vrrp->effective_priority)); json_object_object_add(json_data, "vipset", json_object_new_boolean(vrrp->vipset)); //Virtual IPs are stored in a list if (!LIST_ISEMPTY(vrrp->vip)) { for (f = LIST_HEAD(vrrp->vip); f; ELEMENT_NEXT(f)) { ip_address_t *vip = ELEMENT_DATA(f); char ipaddr[INET6_ADDRSTRLEN]; inet_ntop(vrrp->family, &(vip->u.sin.sin_addr.s_addr), ipaddr, INET6_ADDRSTRLEN); json_object_array_add(vips, json_object_new_string(ipaddr)); } } json_object_object_add(json_data, "vips", vips); //External VIPs are also stored in a list if (!LIST_ISEMPTY(vrrp->evip)) { for (f = LIST_HEAD(vrrp->evip); f; ELEMENT_NEXT(f)) { ip_address_t *evip = ELEMENT_DATA(f); char ipaddr[INET6_ADDRSTRLEN]; inet_ntop(vrrp->family, &(evip->u.sin.sin_addr.s_addr), ipaddr, INET6_ADDRSTRLEN); json_object_array_add(evips, json_object_new_string(ipaddr)); } } json_object_object_add(json_data, "evips", evips); json_object_object_add(json_data, "promote_secondaries", json_object_new_boolean(vrrp->promote_secondaries)); #ifdef _HAVE_FIB_ROUTING_ // Dump vroutes if (!LIST_ISEMPTY(vrrp->vroutes)) { for (f = LIST_HEAD(vrrp->vroutes); f; ELEMENT_NEXT(f)) { ip_route_t *route = ELEMENT_DATA(f); char *buf = MALLOC(ROUTE_BUF_SIZE); format_iproute(route, buf, ROUTE_BUF_SIZE); json_object_array_add(vroutes, json_object_new_string(buf)); } } json_object_object_add(json_data, "vroutes", vroutes); // Dump vrules if (!LIST_ISEMPTY(vrrp->vrules)) { for (f = LIST_HEAD(vrrp->vrules); f; ELEMENT_NEXT(f)) { ip_rule_t *rule = ELEMENT_DATA(f); char *buf = MALLOC(RULE_BUF_SIZE); format_iprule(rule, buf, RULE_BUF_SIZE); json_object_array_add(vrules, json_object_new_string(buf)); } } json_object_object_add(json_data, "vrules", vrules); #endif json_object_object_add(json_data, "adver_int", json_object_new_double(vrrp->adver_int / TIMER_HZ_FLOAT)); json_object_object_add(json_data, "master_adver_int", json_object_new_double(vrrp->master_adver_int / TIMER_HZ_FLOAT)); json_object_object_add(json_data, "accept", json_object_new_int((int)vrrp->accept)); json_object_object_add(json_data, "nopreempt", json_object_new_boolean(vrrp->nopreempt)); json_object_object_add(json_data, "preempt_delay", json_object_new_int((int)(vrrp->preempt_delay / TIMER_HZ))); json_object_object_add(json_data, "state", json_object_new_int(vrrp->state)); json_object_object_add(json_data, "wantstate", json_object_new_int(vrrp->wantstate)); json_object_object_add(json_data, "version", json_object_new_int(vrrp->version)); if (vrrp->script_backup) json_object_object_add(json_data, "script_backup", json_object_new_string(cmd_str(vrrp->script_backup))); if (vrrp->script_master) json_object_object_add(json_data, "script_master", json_object_new_string(cmd_str(vrrp->script_master))); if (vrrp->script_fault) json_object_object_add(json_data, "script_fault", json_object_new_string(cmd_str(vrrp->script_fault))); if (vrrp->script_stop) json_object_object_add(json_data, "script_stop", json_object_new_string(cmd_str(vrrp->script_stop))); if (vrrp->script) json_object_object_add(json_data, "script", json_object_new_string(cmd_str(vrrp->script))); if (vrrp->script_master_rx_lower_pri) json_object_object_add(json_data, "script_master_rx_lower_pri", json_object_new_string(cmd_str(vrrp->script_master_rx_lower_pri))); json_object_object_add(json_data, "smtp_alert", json_object_new_boolean(vrrp->smtp_alert)); #ifdef _WITH_VRRP_AUTH_ if (vrrp->auth_type) { json_object_object_add(json_data, "auth_type", json_object_new_int(vrrp->auth_type)); if (vrrp->auth_type != VRRP_AUTH_AH) { char auth_data[sizeof(vrrp->auth_data) + 1]; memcpy(auth_data, vrrp->auth_data, sizeof(vrrp->auth_data)); auth_data[sizeof(vrrp->auth_data)] = '\0'; json_object_object_add(json_data, "auth_data", json_object_new_string(auth_data)); } } else json_object_object_add(json_data, "auth_type", json_object_new_int(0)); #endif // Dump stats to json json_object_object_add(json_stats, "advert_rcvd", json_object_new_int64((int64_t)vrrp->stats->advert_rcvd)); json_object_object_add(json_stats, "advert_sent", json_object_new_int64(vrrp->stats->advert_sent)); json_object_object_add(json_stats, "become_master", json_object_new_int64(vrrp->stats->become_master)); json_object_object_add(json_stats, "release_master", json_object_new_int64(vrrp->stats->release_master)); json_object_object_add(json_stats, "packet_len_err", json_object_new_int64((int64_t)vrrp->stats->packet_len_err)); json_object_object_add(json_stats, "advert_interval_err", json_object_new_int64((int64_t)vrrp->stats->advert_interval_err)); json_object_object_add(json_stats, "ip_ttl_err", json_object_new_int64((int64_t)vrrp->stats->ip_ttl_err)); json_object_object_add(json_stats, "invalid_type_rcvd", json_object_new_int64((int64_t)vrrp->stats->invalid_type_rcvd)); json_object_object_add(json_stats, "addr_list_err", json_object_new_int64((int64_t)vrrp->stats->addr_list_err)); json_object_object_add(json_stats, "invalid_authtype", json_object_new_int64(vrrp->stats->invalid_authtype)); #ifdef _WITH_VRRP_AUTH_ json_object_object_add(json_stats, "authtype_mismatch", json_object_new_int64(vrrp->stats->authtype_mismatch)); json_object_object_add(json_stats, "auth_failure", json_object_new_int64(vrrp->stats->auth_failure)); #endif json_object_object_add(json_stats, "pri_zero_rcvd", json_object_new_int64((int64_t)vrrp->stats->pri_zero_rcvd)); json_object_object_add(json_stats, "pri_zero_sent", json_object_new_int64((int64_t)vrrp->stats->pri_zero_sent)); // Add both json_data and json_stats to main instance_json json_object_object_add(instance_json, "data", json_data); json_object_object_add(instance_json, "stats", json_stats); // Add instance_json to main array json_object_array_add(array, instance_json); } fprintf(file, "%s", json_object_to_json_string(array)); fclose(file); }
./CrossVul/dataset_final_sorted/CWE-59/c/good_436_4
crossvul-cpp_data_good_1592_0
/* abrt-hook-ccpp.cpp - the hook for C/C++ crashing program Copyright (C) 2009 Zdenek Prikryl (zprikryl@redhat.com) Copyright (C) 2009 RedHat inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <sys/utsname.h> #include "libabrt.h" #define DUMP_SUID_UNSAFE 1 #define DUMP_SUID_SAFE 2 /* I want to use -Werror, but gcc-4.4 throws a curveball: * "warning: ignoring return value of 'ftruncate', declared with attribute warn_unused_result" * and (void) cast is not enough to shut it up! Oh God... */ #define IGNORE_RESULT(func_call) do { if (func_call) /* nothing */; } while (0) static char* malloc_readlink(const char *linkname) { char buf[PATH_MAX + 1]; int len; len = readlink(linkname, buf, sizeof(buf)-1); if (len >= 0) { buf[len] = '\0'; return xstrdup(buf); } return NULL; } /* Custom version of copyfd_xyz, * one which is able to write into two descriptors at once. */ #define CONFIG_FEATURE_COPYBUF_KB 4 static off_t copyfd_sparse(int src_fd, int dst_fd1, int dst_fd2, off_t size2) { off_t total = 0; int last_was_seek = 0; #if CONFIG_FEATURE_COPYBUF_KB <= 4 char buffer[CONFIG_FEATURE_COPYBUF_KB * 1024]; enum { buffer_size = sizeof(buffer) }; #else char *buffer; int buffer_size; /* We want page-aligned buffer, just in case kernel is clever * and can do page-aligned io more efficiently */ buffer = mmap(NULL, CONFIG_FEATURE_COPYBUF_KB * 1024, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, /* ignored: */ -1, 0); buffer_size = CONFIG_FEATURE_COPYBUF_KB * 1024; if (buffer == MAP_FAILED) { buffer = alloca(4 * 1024); buffer_size = 4 * 1024; } #endif while (1) { ssize_t rd = safe_read(src_fd, buffer, buffer_size); if (!rd) { /* eof */ if (last_was_seek) { if (lseek(dst_fd1, -1, SEEK_CUR) < 0 || safe_write(dst_fd1, "", 1) != 1 || (dst_fd2 >= 0 && (lseek(dst_fd2, -1, SEEK_CUR) < 0 || safe_write(dst_fd2, "", 1) != 1 ) ) ) { perror_msg("Write error"); total = -1; goto out; } } /* all done */ goto out; } if (rd < 0) { perror_msg("Read error"); total = -1; goto out; } /* checking sparseness */ ssize_t cnt = rd; while (--cnt >= 0) { if (buffer[cnt] != 0) { /* not sparse */ errno = 0; ssize_t wr1 = full_write(dst_fd1, buffer, rd); ssize_t wr2 = (dst_fd2 >= 0 ? full_write(dst_fd2, buffer, rd) : rd); if (wr1 < rd || wr2 < rd) { perror_msg("Write error"); total = -1; goto out; } last_was_seek = 0; goto adv; } } /* sparse */ xlseek(dst_fd1, rd, SEEK_CUR); if (dst_fd2 >= 0) xlseek(dst_fd2, rd, SEEK_CUR); last_was_seek = 1; adv: total += rd; size2 -= rd; if (size2 < 0) dst_fd2 = -1; //TODO: truncate to 0 or even delete the second file //(currently we delete the file later) } out: #if CONFIG_FEATURE_COPYBUF_KB > 4 if (buffer_size != 4 * 1024) munmap(buffer, buffer_size); #endif return total; } /* Global data */ static char *user_pwd; static char *proc_pid_status; static struct dump_dir *dd; static int user_core_fd = -1; /* * %s - signal number * %c - ulimit -c value * %p - pid * %u - uid * %g - gid * %t - UNIX time of dump * %e - executable filename * %h - hostname * %% - output one "%" */ /* Hook must be installed with exactly the same sequence of %c specifiers. * Last one, %h, may be omitted (we can find it out). */ static const char percent_specifiers[] = "%scpugteh"; static char *core_basename = (char*) "core"; /* * Used for error messages only. * It is either the same as core_basename if it is absolute, * or $PWD/core_basename. */ static char *full_core_basename; static char* get_executable(pid_t pid, int *fd_p) { char buf[sizeof("/proc/%lu/exe") + sizeof(long)*3]; sprintf(buf, "/proc/%lu/exe", (long)pid); if (fd_p) *fd_p = open(buf, O_RDONLY); /* might fail and return -1, it's ok */ char *executable = malloc_readlink(buf); if (!executable) return NULL; /* find and cut off " (deleted)" from the path */ char *deleted = executable + strlen(executable) - strlen(" (deleted)"); if (deleted > executable && strcmp(deleted, " (deleted)") == 0) { *deleted = '\0'; log("File '%s' seems to be deleted", executable); } /* find and cut off prelink suffixes from the path */ char *prelink = executable + strlen(executable) - strlen(".#prelink#.XXXXXX"); if (prelink > executable && strncmp(prelink, ".#prelink#.", strlen(".#prelink#.")) == 0) { log("File '%s' seems to be a prelink temporary file", executable); *prelink = '\0'; } return executable; } static char* get_cwd(pid_t pid) { char buf[sizeof("/proc/%lu/cwd") + sizeof(long)*3]; sprintf(buf, "/proc/%lu/cwd", (long)pid); return malloc_readlink(buf); } static char* get_rootdir(pid_t pid) { char buf[sizeof("/proc/%lu/root") + sizeof(long)*3]; sprintf(buf, "/proc/%lu/root", (long)pid); return malloc_readlink(buf); } static int get_fsuid(void) { int real, euid, saved; /* if we fail to parse the uid, then make it root only readable to be safe */ int fs_uid = 0; char *line = proc_pid_status; /* never NULL */ for (;;) { if (strncmp(line, "Uid", 3) == 0) { int n = sscanf(line, "Uid:\t%d\t%d\t%d\t%d\n", &real, &euid, &saved, &fs_uid); if (n != 4) { perror_msg_and_die("Can't parse Uid: line"); } break; } line = strchr(line, '\n'); if (!line) break; line++; } return fs_uid; } static int dump_suid_policy() { /* - values are: 0 - don't dump suided programs - in this case the hook is not called by kernel 1 - create coredump readable by fs_uid 2 - create coredump readable by root only */ int c; int suid_dump_policy = 0; const char *filename = "/proc/sys/fs/suid_dumpable"; FILE *f = fopen(filename, "r"); if (!f) { log("Can't open %s", filename); return suid_dump_policy; } c = fgetc(f); fclose(f); if (c != EOF) suid_dump_policy = c - '0'; //log("suid dump policy is: %i", suid_dump_policy); return suid_dump_policy; } static int open_user_core(uid_t uid, uid_t fsuid, pid_t pid, char **percent_values) { errno = 0; if (user_pwd == NULL || chdir(user_pwd) != 0 ) { perror_msg("Can't cd to '%s'", user_pwd); return -1; } struct passwd* pw = getpwuid(uid); gid_t gid = pw ? pw->pw_gid : uid; //log("setting uid: %i gid: %i", uid, gid); xsetegid(gid); xseteuid(fsuid); if (strcmp(core_basename, "core") == 0) { /* Mimic "core.PID" if requested */ char buf[] = "0\n"; int fd = open("/proc/sys/kernel/core_uses_pid", O_RDONLY); if (fd >= 0) { IGNORE_RESULT(read(fd, buf, sizeof(buf))); close(fd); } if (strcmp(buf, "1\n") == 0) { core_basename = xasprintf("%s.%lu", core_basename, (long)pid); } } else { /* Expand old core pattern, put expanded name in core_basename */ core_basename = xstrdup(core_basename); unsigned idx = 0; while (1) { char c = core_basename[idx]; if (!c) break; idx++; if (c != '%') continue; /* We just copied %, look at following char and expand %c */ c = core_basename[idx]; unsigned specifier_num = strchrnul(percent_specifiers, c) - percent_specifiers; if (percent_specifiers[specifier_num] != '\0') /* valid %c (might be %% too) */ { const char *val = "%"; if (specifier_num > 0) /* not %% */ val = percent_values[specifier_num - 1]; //log("c:'%c'", c); //log("val:'%s'", val); /* Replace %c at core_basename[idx] by its value */ idx--; char *old = core_basename; core_basename = xasprintf("%.*s%s%s", idx, core_basename, val, core_basename + idx + 2); //log("pos:'%*s|'", idx, ""); //log("new:'%s'", core_basename); //log("old:'%s'", old); free(old); idx += strlen(val); } /* else: invalid %c, % is already copied verbatim, * next loop iteration will copy c */ } } full_core_basename = core_basename; if (core_basename[0] != '/') core_basename = concat_path_file(user_pwd, core_basename); /* Open (create) compat core file. * man core: * There are various circumstances in which a core dump file * is not produced: * * [skipped obvious ones] * The process does not have permission to write the core file. * ...if a file with the same name exists and is not writable * or is not a regular file (e.g., it is a directory or a symbolic link). * * A file with the same name already exists, but there is more * than one hard link to that file. * * The file system where the core dump file would be created is full; * or has run out of inodes; or is mounted read-only; * or the user has reached their quota for the file system. * * The RLIMIT_CORE or RLIMIT_FSIZE resource limits for the process * are set to zero. * [we check RLIMIT_CORE, but how can we check RLIMIT_FSIZE?] * * The binary being executed by the process does not have * read permission enabled. [how we can check it here?] * * The process is executing a set-user-ID (set-group-ID) program * that is owned by a user (group) other than the real * user (group) ID of the process. [TODO?] * (However, see the description of the prctl(2) PR_SET_DUMPABLE operation, * and the description of the /proc/sys/fs/suid_dumpable file in proc(5).) */ struct stat sb; errno = 0; /* Do not O_TRUNC: if later checks fail, we do not want to have file already modified here */ int user_core_fd = open(core_basename, O_WRONLY | O_CREAT | O_NOFOLLOW, 0600); /* kernel makes 0600 too */ xsetegid(0); xseteuid(0); if (user_core_fd < 0 || fstat(user_core_fd, &sb) != 0 || !S_ISREG(sb.st_mode) || sb.st_nlink != 1 /* kernel internal dumper checks this too: if (inode->i_uid != current->fsuid) <fail>, need to mimic? */ ) { if (user_core_fd < 0) perror_msg("Can't open '%s'", full_core_basename); else perror_msg("'%s' is not a regular file with link count 1", full_core_basename); return -1; } if (ftruncate(user_core_fd, 0) != 0) { /* perror first, otherwise unlink may trash errno */ perror_msg("Can't truncate '%s' to size 0", full_core_basename); unlink(core_basename); return -1; } return user_core_fd; } static bool dump_fd_info(const char *dest_filename, char *source_filename, int source_base_ofs, uid_t uid, gid_t gid) { FILE *fp = fopen(dest_filename, "w"); if (!fp) return false; unsigned fd = 0; while (fd <= 99999) /* paranoia check */ { sprintf(source_filename + source_base_ofs, "fd/%u", fd); char *name = malloc_readlink(source_filename); if (!name) break; fprintf(fp, "%u:%s\n", fd, name); free(name); sprintf(source_filename + source_base_ofs, "fdinfo/%u", fd); fd++; FILE *in = fopen(source_filename, "r"); if (!in) continue; char buf[128]; while (fgets(buf, sizeof(buf)-1, in)) { /* in case the line is not terminated, terminate it */ char *eol = strchrnul(buf, '\n'); eol[0] = '\n'; eol[1] = '\0'; fputs(buf, fp); } fclose(in); } const int dest_fd = fileno(fp); if (fchown(dest_fd, uid, gid) < 0) { perror_msg("Can't change '%s' ownership to %lu:%lu", dest_filename, (long)uid, (long)gid); fclose(fp); unlink(dest_filename); return false; } fclose(fp); return true; } /* Like xopen, but on error, unlocks and deletes dd and user core */ static int create_or_die(const char *filename) { int fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, DEFAULT_DUMP_DIR_MODE); if (fd >= 0) { IGNORE_RESULT(fchown(fd, dd->dd_uid, dd->dd_gid)); return fd; } int sv_errno = errno; if (dd) dd_delete(dd); if (user_core_fd >= 0) { xchdir(user_pwd); unlink(core_basename); } errno = sv_errno; perror_msg_and_die("Can't open '%s'", filename); } int main(int argc, char** argv) { /* Kernel starts us with all fd's closed. * But it's dangerous: * fprintf(stderr) can dump messages into random fds, etc. * Ensure that if any of fd 0,1,2 is closed, we open it to /dev/null. */ int fd = xopen("/dev/null", O_RDWR); while (fd < 2) fd = xdup(fd); if (fd > 2) close(fd); if (argc < 8) { /* percent specifier: %s %c %p %u %g %t %e %h */ /* argv: [0] [1] [2] [3] [4] [5] [6] [7] [8]*/ error_msg_and_die("Usage: %s SIGNO CORE_SIZE_LIMIT PID UID GID TIME BINARY_NAME [HOSTNAME]", argv[0]); } /* Not needed on 2.6.30. * At least 2.6.18 has a bug where * argv[1] = "SIGNO CORE_SIZE_LIMIT PID ..." * argv[2] = "CORE_SIZE_LIMIT PID ..." * and so on. Fixing it: */ if (strchr(argv[1], ' ')) { int i; for (i = 1; argv[i]; i++) { strchrnul(argv[i], ' ')[0] = '\0'; } } logmode = LOGMODE_JOURNAL; /* Parse abrt.conf */ load_abrt_conf(); /* ... and plugins/CCpp.conf */ bool setting_MakeCompatCore; bool setting_SaveBinaryImage; { map_string_t *settings = new_map_string(); load_abrt_plugin_conf_file("CCpp.conf", settings); const char *value; value = get_map_string_item_or_NULL(settings, "MakeCompatCore"); setting_MakeCompatCore = value && string_to_bool(value); value = get_map_string_item_or_NULL(settings, "SaveBinaryImage"); setting_SaveBinaryImage = value && string_to_bool(value); value = get_map_string_item_or_NULL(settings, "VerboseLog"); if (value) g_verbose = xatoi_positive(value); free_map_string(settings); } errno = 0; const char* signal_str = argv[1]; int signal_no = xatoi_positive(signal_str); off_t ulimit_c = strtoull(argv[2], NULL, 10); if (ulimit_c < 0) /* unlimited? */ { /* set to max possible >0 value */ ulimit_c = ~((off_t)1 << (sizeof(off_t)*8-1)); } const char *pid_str = argv[3]; pid_t pid = xatoi_positive(argv[3]); uid_t uid = xatoi_positive(argv[4]); if (errno || pid <= 0) { perror_msg_and_die("PID '%s' or limit '%s' is bogus", argv[3], argv[2]); } { char *s = xmalloc_fopen_fgetline_fclose(VAR_RUN"/abrt/saved_core_pattern"); /* If we have a saved pattern and it's not a "|PROG ARGS" thing... */ if (s && s[0] != '|') core_basename = s; else free(s); } struct utsname uts; if (!argv[8]) /* no HOSTNAME? */ { uname(&uts); argv[8] = uts.nodename; } char path[PATH_MAX]; int src_fd_binary = -1; char *executable = get_executable(pid, setting_SaveBinaryImage ? &src_fd_binary : NULL); if (executable && strstr(executable, "/abrt-hook-ccpp")) { error_msg_and_die("PID %lu is '%s', not dumping it to avoid recursion", (long)pid, executable); } user_pwd = get_cwd(pid); /* may be NULL on error */ log_notice("user_pwd:'%s'", user_pwd); sprintf(path, "/proc/%lu/status", (long)pid); proc_pid_status = xmalloc_xopen_read_close(path, /*maxsz:*/ NULL); uid_t fsuid = uid; uid_t tmp_fsuid = get_fsuid(); int suid_policy = dump_suid_policy(); if (tmp_fsuid != uid) { /* use root for suided apps unless it's explicitly set to UNSAFE */ fsuid = 0; if (suid_policy == DUMP_SUID_UNSAFE) { fsuid = tmp_fsuid; } } /* Open a fd to compat coredump, if requested and is possible */ if (setting_MakeCompatCore && ulimit_c != 0) /* note: checks "user_pwd == NULL" inside; updates core_basename */ user_core_fd = open_user_core(uid, fsuid, pid, &argv[1]); if (executable == NULL) { /* readlink on /proc/$PID/exe failed, don't create abrt dump dir */ error_msg("Can't read /proc/%lu/exe link", (long)pid); goto create_user_core; } const char *signame = NULL; switch (signal_no) { case SIGILL : signame = "ILL" ; break; case SIGFPE : signame = "FPE" ; break; case SIGSEGV: signame = "SEGV"; break; case SIGBUS : signame = "BUS" ; break; //Bus error (bad memory access) case SIGABRT: signame = "ABRT"; break; //usually when abort() was called // We have real-world reports from users who see buggy programs // dying with SIGTRAP, uncommented it too: case SIGTRAP: signame = "TRAP"; break; //Trace/breakpoint trap // These usually aren't caused by bugs: //case SIGQUIT: signame = "QUIT"; break; //Quit from keyboard //case SIGSYS : signame = "SYS" ; break; //Bad argument to routine (SVr4) //case SIGXCPU: signame = "XCPU"; break; //CPU time limit exceeded (4.2BSD) //case SIGXFSZ: signame = "XFSZ"; break; //File size limit exceeded (4.2BSD) default: goto create_user_core; // not a signal we care about } if (!daemon_is_ok()) { /* not an error, exit with exit code 0 */ log("abrtd is not running. If it crashed, " "/proc/sys/kernel/core_pattern contains a stale value, " "consider resetting it to 'core'" ); goto create_user_core; } if (g_settings_nMaxCrashReportsSize > 0) { /* If free space is less than 1/4 of MaxCrashReportsSize... */ if (low_free_space(g_settings_nMaxCrashReportsSize, g_settings_dump_location)) goto create_user_core; } /* Check /var/tmp/abrt/last-ccpp marker, do not dump repeated crashes * if they happen too often. Else, write new marker value. */ snprintf(path, sizeof(path), "%s/last-ccpp", g_settings_dump_location); if (check_recent_crash_file(path, executable)) { /* It is a repeating crash */ goto create_user_core; } const char *last_slash = strrchr(executable, '/'); if (last_slash && strncmp(++last_slash, "abrt", 4) == 0) { /* If abrtd/abrt-foo crashes, we don't want to create a _directory_, * since that can make new copy of abrtd to process it, * and maybe crash again... * Unlike dirs, mere files are ignored by abrtd. */ snprintf(path, sizeof(path), "%s/%s-coredump", g_settings_dump_location, last_slash); int abrt_core_fd = xopen3(path, O_WRONLY | O_CREAT | O_TRUNC, 0600); off_t core_size = copyfd_eof(STDIN_FILENO, abrt_core_fd, COPYFD_SPARSE); if (core_size < 0 || fsync(abrt_core_fd) != 0) { unlink(path); /* copyfd_eof logs the error including errno string, * but it does not log file name */ error_msg_and_die("Error saving '%s'", path); } log("Saved core dump of pid %lu (%s) to %s (%llu bytes)", (long)pid, executable, path, (long long)core_size); return 0; } unsigned path_len = snprintf(path, sizeof(path), "%s/ccpp-%s-%lu.new", g_settings_dump_location, iso_date_string(NULL), (long)pid); if (path_len >= (sizeof(path) - sizeof("/"FILENAME_COREDUMP))) { goto create_user_core; } /* use fsuid instead of uid, so we don't expose any sensitive * information of suided app in /var/tmp/abrt */ dd = dd_create(path, fsuid, DEFAULT_DUMP_DIR_MODE); if (dd) { char *rootdir = get_rootdir(pid); dd_create_basic_files(dd, fsuid, (rootdir && strcmp(rootdir, "/") != 0) ? rootdir : NULL); char source_filename[sizeof("/proc/%lu/somewhat_long_name") + sizeof(long)*3]; int source_base_ofs = sprintf(source_filename, "/proc/%lu/smaps", (long)pid); source_base_ofs -= strlen("smaps"); char *dest_filename = concat_path_file(dd->dd_dirname, "also_somewhat_longish_name"); char *dest_base = strrchr(dest_filename, '/') + 1; // Disabled for now: /proc/PID/smaps tends to be BIG, // and not much more informative than /proc/PID/maps: //copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL); strcpy(source_filename + source_base_ofs, "maps"); strcpy(dest_base, FILENAME_MAPS); copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL); strcpy(source_filename + source_base_ofs, "limits"); strcpy(dest_base, FILENAME_LIMITS); copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL); strcpy(source_filename + source_base_ofs, "cgroup"); strcpy(dest_base, FILENAME_CGROUP); copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL); strcpy(dest_base, FILENAME_OPEN_FDS); dump_fd_info(dest_filename, source_filename, source_base_ofs, dd->dd_uid, dd->dd_gid); free(dest_filename); dd_save_text(dd, FILENAME_ANALYZER, "CCpp"); dd_save_text(dd, FILENAME_TYPE, "CCpp"); dd_save_text(dd, FILENAME_EXECUTABLE, executable); dd_save_text(dd, FILENAME_PID, pid_str); dd_save_text(dd, FILENAME_PROC_PID_STATUS, proc_pid_status); if (user_pwd) dd_save_text(dd, FILENAME_PWD, user_pwd); if (rootdir) { if (strcmp(rootdir, "/") != 0) dd_save_text(dd, FILENAME_ROOTDIR, rootdir); } char *reason = xasprintf("%s killed by SIG%s", last_slash, signame ? signame : signal_str); dd_save_text(dd, FILENAME_REASON, reason); free(reason); char *cmdline = get_cmdline(pid); dd_save_text(dd, FILENAME_CMDLINE, cmdline ? : ""); free(cmdline); char *environ = get_environ(pid); dd_save_text(dd, FILENAME_ENVIRON, environ ? : ""); free(environ); char *fips_enabled = xmalloc_fopen_fgetline_fclose("/proc/sys/crypto/fips_enabled"); if (fips_enabled) { if (strcmp(fips_enabled, "0") != 0) dd_save_text(dd, "fips_enabled", fips_enabled); free(fips_enabled); } dd_save_text(dd, FILENAME_ABRT_VERSION, VERSION); if (src_fd_binary > 0) { strcpy(path + path_len, "/"FILENAME_BINARY); int dst_fd = create_or_die(path); off_t sz = copyfd_eof(src_fd_binary, dst_fd, COPYFD_SPARSE); if (fsync(dst_fd) != 0 || close(dst_fd) != 0 || sz < 0) { dd_delete(dd); error_msg_and_die("Error saving '%s'", path); } close(src_fd_binary); } strcpy(path + path_len, "/"FILENAME_COREDUMP); int abrt_core_fd = create_or_die(path); /* We write both coredumps at once. * We can't write user coredump first, since it might be truncated * and thus can't be copied and used as abrt coredump; * and if we write abrt coredump first and then copy it as user one, * then we have a race when process exits but coredump does not exist yet: * $ echo -e '#include<signal.h>\nmain(){raise(SIGSEGV);}' | gcc -o test -x c - * $ rm -f core*; ulimit -c unlimited; ./test; ls -l core* * 21631 Segmentation fault (core dumped) ./test * ls: cannot access core*: No such file or directory <=== BAD */ off_t core_size = copyfd_sparse(STDIN_FILENO, abrt_core_fd, user_core_fd, ulimit_c); if (fsync(abrt_core_fd) != 0 || close(abrt_core_fd) != 0 || core_size < 0) { unlink(path); dd_delete(dd); if (user_core_fd >= 0) { xchdir(user_pwd); unlink(core_basename); } /* copyfd_sparse logs the error including errno string, * but it does not log file name */ error_msg_and_die("Error writing '%s'", path); } if (user_core_fd >= 0 /* error writing user coredump? */ && (fsync(user_core_fd) != 0 || close(user_core_fd) != 0 /* user coredump is too big? */ || (ulimit_c == 0 /* paranoia */ || core_size > ulimit_c) ) ) { /* nuke it (silently) */ xchdir(user_pwd); unlink(core_basename); } /* Save JVM crash log if it exists. (JVM's coredump per se * is nearly useless for JVM developers) */ { char *java_log = xasprintf("/tmp/jvm-%lu/hs_error.log", (long)pid); int src_fd = open(java_log, O_RDONLY); free(java_log); /* If we couldn't open the error log in /tmp directory we can try to * read the log from the current directory. It may produce AVC, it * may produce some error log but all these are expected. */ if (src_fd < 0) { java_log = xasprintf("%s/hs_err_pid%lu.log", user_pwd, (long)pid); src_fd = open(java_log, O_RDONLY); free(java_log); } if (src_fd >= 0) { strcpy(path + path_len, "/hs_err.log"); int dst_fd = create_or_die(path); off_t sz = copyfd_eof(src_fd, dst_fd, COPYFD_SPARSE); if (close(dst_fd) != 0 || sz < 0) { dd_delete(dd); error_msg_and_die("Error saving '%s'", path); } close(src_fd); } } /* We close dumpdir before we start catering for crash storm case. * Otherwise, delete_dump_dir's from other concurrent * CCpp's won't be able to delete our dump (their delete_dump_dir * will wait for us), and we won't be able to delete their dumps. * Classic deadlock. */ dd_close(dd); path[path_len] = '\0'; /* path now contains only directory name */ char *newpath = xstrndup(path, path_len - (sizeof(".new")-1)); if (rename(path, newpath) == 0) strcpy(path, newpath); free(newpath); log("Saved core dump of pid %lu (%s) to %s (%llu bytes)", (long)pid, executable, path, (long long)core_size); notify_new_path(path); /* rhbz#539551: "abrt going crazy when crashing process is respawned" */ if (g_settings_nMaxCrashReportsSize > 0) { /* x1.25 and round up to 64m: go a bit up, so that usual in-daemon trimming * kicks in first, and we don't "fight" with it: */ unsigned maxsize = g_settings_nMaxCrashReportsSize + g_settings_nMaxCrashReportsSize / 4; maxsize |= 63; trim_problem_dirs(g_settings_dump_location, maxsize * (double)(1024*1024), path); } free(rootdir); return 0; } /* We didn't create abrt dump, but may need to create compat coredump */ create_user_core: if (user_core_fd >= 0) { off_t core_size = copyfd_size(STDIN_FILENO, user_core_fd, ulimit_c, COPYFD_SPARSE); if (fsync(user_core_fd) != 0 || close(user_core_fd) != 0 || core_size < 0) { /* perror first, otherwise unlink may trash errno */ perror_msg("Error writing '%s'", full_core_basename); xchdir(user_pwd); unlink(core_basename); return 1; } if (ulimit_c == 0 || core_size > ulimit_c) { xchdir(user_pwd); unlink(core_basename); return 1; } log("Saved core dump of pid %lu to %s (%llu bytes)", (long)pid, full_core_basename, (long long)core_size); } return 0; }
./CrossVul/dataset_final_sorted/CWE-59/c/good_1592_0
crossvul-cpp_data_bad_3273_0
/** \ingroup payload * \file lib/fsm.c * File state machine to handle a payload from a package. */ #include "system.h" #include <utime.h> #include <errno.h> #if WITH_CAP #include <sys/capability.h> #endif #include <rpm/rpmte.h> #include <rpm/rpmts.h> #include <rpm/rpmlog.h> #include "rpmio/rpmio_internal.h" /* fdInit/FiniDigest */ #include "lib/fsm.h" #include "lib/rpmte_internal.h" /* XXX rpmfs */ #include "lib/rpmplugins.h" /* rpm plugins hooks */ #include "lib/rpmug.h" #include "debug.h" #define _FSM_DEBUG 0 int _fsm_debug = _FSM_DEBUG; /* XXX Failure to remove is not (yet) cause for failure. */ static int strict_erasures = 0; #define SUFFIX_RPMORIG ".rpmorig" #define SUFFIX_RPMSAVE ".rpmsave" #define SUFFIX_RPMNEW ".rpmnew" /* Default directory and file permissions if not mapped */ #define _dirPerms 0755 #define _filePerms 0644 /* * XXX Forward declarations for previously exported functions to avoid moving * things around needlessly */ static const char * fileActionString(rpmFileAction a); /** \ingroup payload * Build path to file from file info, optionally ornamented with suffix. * @param fi file info iterator * @param suffix suffix to use (NULL disables) * @retval path to file (malloced) */ static char * fsmFsPath(rpmfi fi, const char * suffix) { return rstrscat(NULL, rpmfiDN(fi), rpmfiBN(fi), suffix ? suffix : "", NULL); } /** \ingroup payload * Directory name iterator. */ typedef struct dnli_s { rpmfiles fi; char * active; int reverse; int isave; int i; } * DNLI_t; /** \ingroup payload * Destroy directory name iterator. * @param dnli directory name iterator * @retval NULL always */ static DNLI_t dnlFreeIterator(DNLI_t dnli) { if (dnli) { if (dnli->active) free(dnli->active); free(dnli); } return NULL; } /** \ingroup payload * Create directory name iterator. * @param fi file info set * @param fs file state set * @param reverse traverse directory names in reverse order? * @return directory name iterator */ static DNLI_t dnlInitIterator(rpmfiles fi, rpmfs fs, int reverse) { DNLI_t dnli; int i, j; int dc; if (fi == NULL) return NULL; dc = rpmfilesDC(fi); dnli = xcalloc(1, sizeof(*dnli)); dnli->fi = fi; dnli->reverse = reverse; dnli->i = (reverse ? dc : 0); if (dc) { dnli->active = xcalloc(dc, sizeof(*dnli->active)); int fc = rpmfilesFC(fi); /* Identify parent directories not skipped. */ for (i = 0; i < fc; i++) if (!XFA_SKIPPING(rpmfsGetAction(fs, i))) dnli->active[rpmfilesDI(fi, i)] = 1; /* Exclude parent directories that are explicitly included. */ for (i = 0; i < fc; i++) { int dil; size_t dnlen, bnlen; if (!S_ISDIR(rpmfilesFMode(fi, i))) continue; dil = rpmfilesDI(fi, i); dnlen = strlen(rpmfilesDN(fi, dil)); bnlen = strlen(rpmfilesBN(fi, i)); for (j = 0; j < dc; j++) { const char * dnl; size_t jlen; if (!dnli->active[j] || j == dil) continue; dnl = rpmfilesDN(fi, j); jlen = strlen(dnl); if (jlen != (dnlen+bnlen+1)) continue; if (!rstreqn(dnl, rpmfilesDN(fi, dil), dnlen)) continue; if (!rstreqn(dnl+dnlen, rpmfilesBN(fi, i), bnlen)) continue; if (dnl[dnlen+bnlen] != '/' || dnl[dnlen+bnlen+1] != '\0') continue; /* This directory is included in the package. */ dnli->active[j] = 0; break; } } /* Print only once per package. */ if (!reverse) { j = 0; for (i = 0; i < dc; i++) { if (!dnli->active[i]) continue; if (j == 0) { j = 1; rpmlog(RPMLOG_DEBUG, "========== Directories not explicitly included in package:\n"); } rpmlog(RPMLOG_DEBUG, "%10d %s\n", i, rpmfilesDN(fi, i)); } if (j) rpmlog(RPMLOG_DEBUG, "==========\n"); } } return dnli; } /** \ingroup payload * Return next directory name (from file info). * @param dnli directory name iterator * @return next directory name */ static const char * dnlNextIterator(DNLI_t dnli) { const char * dn = NULL; if (dnli) { rpmfiles fi = dnli->fi; int dc = rpmfilesDC(fi); int i = -1; if (dnli->active) do { i = (!dnli->reverse ? dnli->i++ : --dnli->i); } while (i >= 0 && i < dc && !dnli->active[i]); if (i >= 0 && i < dc) dn = rpmfilesDN(fi, i); else i = -1; dnli->isave = i; } return dn; } static int fsmSetFCaps(const char *path, const char *captxt) { int rc = 0; #if WITH_CAP if (captxt && *captxt != '\0') { cap_t fcaps = cap_from_text(captxt); if (fcaps == NULL || cap_set_file(path, fcaps) != 0) { rc = RPMERR_SETCAP_FAILED; } cap_free(fcaps); } #endif return rc; } /** \ingroup payload * Create file from payload stream. * @return 0 on success */ static int expandRegular(rpmfi fi, const char *dest, rpmpsm psm, int nodigest, int nocontent) { FD_t wfd = NULL; int rc = 0; /* Create the file with 0200 permissions (write by owner). */ { mode_t old_umask = umask(0577); wfd = Fopen(dest, "w.ufdio"); umask(old_umask); } if (Ferror(wfd)) { rc = RPMERR_OPEN_FAILED; goto exit; } if (!nocontent) rc = rpmfiArchiveReadToFilePsm(fi, wfd, nodigest, psm); exit: if (wfd) { int myerrno = errno; Fclose(wfd); errno = myerrno; } return rc; } static int fsmMkfile(rpmfi fi, const char *dest, rpmfiles files, rpmpsm psm, int nodigest, int *setmeta, int * firsthardlink) { int rc = 0; int numHardlinks = rpmfiFNlink(fi); if (numHardlinks > 1) { /* Create first hardlinked file empty */ if (*firsthardlink < 0) { *firsthardlink = rpmfiFX(fi); rc = expandRegular(fi, dest, psm, nodigest, 1); } else { /* Create hard links for others */ char *fn = rpmfilesFN(files, *firsthardlink); rc = link(fn, dest); if (rc < 0) { rc = RPMERR_LINK_FAILED; } free(fn); } } /* Write normal files or fill the last hardlinked (already existing) file with content */ if (numHardlinks<=1) { if (!rc) rc = expandRegular(fi, dest, psm, nodigest, 0); } else if (rpmfiArchiveHasContent(fi)) { if (!rc) rc = expandRegular(fi, dest, psm, nodigest, 0); *firsthardlink = -1; } else { *setmeta = 0; } return rc; } static int fsmReadLink(const char *path, char *buf, size_t bufsize, size_t *linklen) { ssize_t llen = readlink(path, buf, bufsize - 1); int rc = RPMERR_READLINK_FAILED; if (_fsm_debug) { rpmlog(RPMLOG_DEBUG, " %8s (%s, buf, %d) %s\n", __func__, path, (int)(bufsize -1), (llen < 0 ? strerror(errno) : "")); } if (llen >= 0) { buf[llen] = '\0'; rc = 0; *linklen = llen; } return rc; } static int fsmStat(const char *path, int dolstat, struct stat *sb) { int rc; if (dolstat){ rc = lstat(path, sb); } else { rc = stat(path, sb); } if (_fsm_debug && rc && errno != ENOENT) rpmlog(RPMLOG_DEBUG, " %8s (%s, ost) %s\n", __func__, path, (rc < 0 ? strerror(errno) : "")); if (rc < 0) { rc = (errno == ENOENT ? RPMERR_ENOENT : RPMERR_LSTAT_FAILED); /* Ensure consistent struct content on failure */ memset(sb, 0, sizeof(*sb)); } return rc; } static int fsmRmdir(const char *path) { int rc = rmdir(path); if (_fsm_debug) rpmlog(RPMLOG_DEBUG, " %8s (%s) %s\n", __func__, path, (rc < 0 ? strerror(errno) : "")); if (rc < 0) switch (errno) { case ENOENT: rc = RPMERR_ENOENT; break; case ENOTEMPTY: rc = RPMERR_ENOTEMPTY; break; default: rc = RPMERR_RMDIR_FAILED; break; } return rc; } static int fsmMkdir(const char *path, mode_t mode) { int rc = mkdir(path, (mode & 07777)); if (_fsm_debug) rpmlog(RPMLOG_DEBUG, " %8s (%s, 0%04o) %s\n", __func__, path, (unsigned)(mode & 07777), (rc < 0 ? strerror(errno) : "")); if (rc < 0) rc = RPMERR_MKDIR_FAILED; return rc; } static int fsmMkfifo(const char *path, mode_t mode) { int rc = mkfifo(path, (mode & 07777)); if (_fsm_debug) { rpmlog(RPMLOG_DEBUG, " %8s (%s, 0%04o) %s\n", __func__, path, (unsigned)(mode & 07777), (rc < 0 ? strerror(errno) : "")); } if (rc < 0) rc = RPMERR_MKFIFO_FAILED; return rc; } static int fsmMknod(const char *path, mode_t mode, dev_t dev) { /* FIX: check S_IFIFO or dev != 0 */ int rc = mknod(path, (mode & ~07777), dev); if (_fsm_debug) { rpmlog(RPMLOG_DEBUG, " %8s (%s, 0%o, 0x%x) %s\n", __func__, path, (unsigned)(mode & ~07777), (unsigned)dev, (rc < 0 ? strerror(errno) : "")); } if (rc < 0) rc = RPMERR_MKNOD_FAILED; return rc; } /** * Create (if necessary) directories not explicitly included in package. * @param files file data * @param fs file states * @param plugins rpm plugins handle * @return 0 on success */ static int fsmMkdirs(rpmfiles files, rpmfs fs, rpmPlugins plugins) { DNLI_t dnli = dnlInitIterator(files, fs, 0); struct stat sb; const char *dpath; int dc = rpmfilesDC(files); int rc = 0; int i; int ldnlen = 0; int ldnalloc = 0; char * ldn = NULL; short * dnlx = NULL; dnlx = (dc ? xcalloc(dc, sizeof(*dnlx)) : NULL); if (dnlx != NULL) while ((dpath = dnlNextIterator(dnli)) != NULL) { size_t dnlen = strlen(dpath); char * te, dn[dnlen+1]; dc = dnli->isave; if (dc < 0) continue; dnlx[dc] = dnlen; if (dnlen <= 1) continue; if (dnlen <= ldnlen && rstreq(dpath, ldn)) continue; /* Copy as we need to modify the string */ (void) stpcpy(dn, dpath); /* Assume '/' directory exists, "mkdir -p" for others if non-existent */ for (i = 1, te = dn + 1; *te != '\0'; te++, i++) { if (*te != '/') continue; *te = '\0'; /* Already validated? */ if (i < ldnlen && (ldn[i] == '/' || ldn[i] == '\0') && rstreqn(dn, ldn, i)) { *te = '/'; /* Move pre-existing path marker forward. */ dnlx[dc] = (te - dn); continue; } /* Validate next component of path. */ rc = fsmStat(dn, 1, &sb); /* lstat */ *te = '/'; /* Directory already exists? */ if (rc == 0 && S_ISDIR(sb.st_mode)) { /* Move pre-existing path marker forward. */ dnlx[dc] = (te - dn); } else if (rc == RPMERR_ENOENT) { *te = '\0'; mode_t mode = S_IFDIR | (_dirPerms & 07777); rpmFsmOp op = (FA_CREATE|FAF_UNOWNED); /* Run fsm file pre hook for all plugins */ rc = rpmpluginsCallFsmFilePre(plugins, NULL, dn, mode, op); if (!rc) rc = fsmMkdir(dn, mode); if (!rc) { rc = rpmpluginsCallFsmFilePrepare(plugins, NULL, dn, dn, mode, op); } /* Run fsm file post hook for all plugins */ rpmpluginsCallFsmFilePost(plugins, NULL, dn, mode, op, rc); if (!rc) { rpmlog(RPMLOG_DEBUG, "%s directory created with perms %04o\n", dn, (unsigned)(mode & 07777)); } *te = '/'; } if (rc) break; } if (rc) break; /* Save last validated path. */ if (ldnalloc < (dnlen + 1)) { ldnalloc = dnlen + 100; ldn = xrealloc(ldn, ldnalloc); } if (ldn != NULL) { /* XXX can't happen */ strcpy(ldn, dn); ldnlen = dnlen; } } free(dnlx); free(ldn); dnlFreeIterator(dnli); return rc; } static void removeSBITS(const char *path) { struct stat stb; if (lstat(path, &stb) == 0 && S_ISREG(stb.st_mode)) { if ((stb.st_mode & 06000) != 0) { (void) chmod(path, stb.st_mode & 0777); } #if WITH_CAP if (stb.st_mode & (S_IXUSR|S_IXGRP|S_IXOTH)) { (void) cap_set_file(path, NULL); } #endif } } static void fsmDebug(const char *fpath, rpmFileAction action, const struct stat *st) { rpmlog(RPMLOG_DEBUG, "%-10s %06o%3d (%4d,%4d)%6d %s\n", fileActionString(action), (int)st->st_mode, (int)st->st_nlink, (int)st->st_uid, (int)st->st_gid, (int)st->st_size, (fpath ? fpath : "")); } static int fsmSymlink(const char *opath, const char *path) { int rc = symlink(opath, path); if (_fsm_debug) { rpmlog(RPMLOG_DEBUG, " %8s (%s, %s) %s\n", __func__, opath, path, (rc < 0 ? strerror(errno) : "")); } if (rc < 0) rc = RPMERR_SYMLINK_FAILED; return rc; } static int fsmUnlink(const char *path) { int rc = 0; removeSBITS(path); rc = unlink(path); if (_fsm_debug) rpmlog(RPMLOG_DEBUG, " %8s (%s) %s\n", __func__, path, (rc < 0 ? strerror(errno) : "")); if (rc < 0) rc = (errno == ENOENT ? RPMERR_ENOENT : RPMERR_UNLINK_FAILED); return rc; } static int fsmRename(const char *opath, const char *path) { removeSBITS(path); int rc = rename(opath, path); #if defined(ETXTBSY) && defined(__HPUX__) /* XXX HP-UX (and other os'es) don't permit rename to busy files. */ if (rc && errno == ETXTBSY) { char *rmpath = NULL; rstrscat(&rmpath, path, "-RPMDELETE", NULL); rc = rename(path, rmpath); if (!rc) rc = rename(opath, path); free(rmpath); } #endif if (_fsm_debug) rpmlog(RPMLOG_DEBUG, " %8s (%s, %s) %s\n", __func__, opath, path, (rc < 0 ? strerror(errno) : "")); if (rc < 0) rc = (errno == EISDIR ? RPMERR_EXIST_AS_DIR : RPMERR_RENAME_FAILED); return rc; } static int fsmRemove(const char *path, mode_t mode) { return S_ISDIR(mode) ? fsmRmdir(path) : fsmUnlink(path); } static int fsmChown(const char *path, mode_t mode, uid_t uid, gid_t gid) { int rc = S_ISLNK(mode) ? lchown(path, uid, gid) : chown(path, uid, gid); if (rc < 0) { struct stat st; if (lstat(path, &st) == 0 && st.st_uid == uid && st.st_gid == gid) rc = 0; } if (_fsm_debug) rpmlog(RPMLOG_DEBUG, " %8s (%s, %d, %d) %s\n", __func__, path, (int)uid, (int)gid, (rc < 0 ? strerror(errno) : "")); if (rc < 0) rc = RPMERR_CHOWN_FAILED; return rc; } static int fsmChmod(const char *path, mode_t mode) { int rc = chmod(path, (mode & 07777)); if (rc < 0) { struct stat st; if (lstat(path, &st) == 0 && (st.st_mode & 07777) == (mode & 07777)) rc = 0; } if (_fsm_debug) rpmlog(RPMLOG_DEBUG, " %8s (%s, 0%04o) %s\n", __func__, path, (unsigned)(mode & 07777), (rc < 0 ? strerror(errno) : "")); if (rc < 0) rc = RPMERR_CHMOD_FAILED; return rc; } static int fsmUtime(const char *path, mode_t mode, time_t mtime) { int rc = 0; struct timeval stamps[2] = { { .tv_sec = mtime, .tv_usec = 0 }, { .tv_sec = mtime, .tv_usec = 0 }, }; #if HAVE_LUTIMES rc = lutimes(path, stamps); #else if (!S_ISLNK(mode)) rc = utimes(path, stamps); #endif if (_fsm_debug) rpmlog(RPMLOG_DEBUG, " %8s (%s, 0x%x) %s\n", __func__, path, (unsigned)mtime, (rc < 0 ? strerror(errno) : "")); if (rc < 0) rc = RPMERR_UTIME_FAILED; /* ...but utime error is not critical for directories */ if (rc && S_ISDIR(mode)) rc = 0; return rc; } static int fsmVerify(const char *path, rpmfi fi) { int rc; int saveerrno = errno; struct stat dsb; mode_t mode = rpmfiFMode(fi); rc = fsmStat(path, 1, &dsb); if (rc) return rc; if (S_ISREG(mode)) { /* HP-UX (and other os'es) don't permit unlink on busy files. */ char *rmpath = rstrscat(NULL, path, "-RPMDELETE", NULL); rc = fsmRename(path, rmpath); /* XXX shouldn't we take unlink return code here? */ if (!rc) (void) fsmUnlink(rmpath); else rc = RPMERR_UNLINK_FAILED; free(rmpath); return (rc ? rc : RPMERR_ENOENT); /* XXX HACK */ } else if (S_ISDIR(mode)) { if (S_ISDIR(dsb.st_mode)) return 0; if (S_ISLNK(dsb.st_mode)) { rc = fsmStat(path, 0, &dsb); if (rc == RPMERR_ENOENT) rc = 0; if (rc) return rc; errno = saveerrno; if (S_ISDIR(dsb.st_mode)) return 0; } } else if (S_ISLNK(mode)) { if (S_ISLNK(dsb.st_mode)) { char buf[8 * BUFSIZ]; size_t len; rc = fsmReadLink(path, buf, 8 * BUFSIZ, &len); errno = saveerrno; if (rc) return rc; if (rstreq(rpmfiFLink(fi), buf)) return 0; } } else if (S_ISFIFO(mode)) { if (S_ISFIFO(dsb.st_mode)) return 0; } else if (S_ISCHR(mode) || S_ISBLK(mode)) { if ((S_ISCHR(dsb.st_mode) || S_ISBLK(dsb.st_mode)) && (dsb.st_rdev == rpmfiFRdev(fi))) return 0; } else if (S_ISSOCK(mode)) { if (S_ISSOCK(dsb.st_mode)) return 0; } /* XXX shouldn't do this with commit/undo. */ rc = fsmUnlink(path); if (rc == 0) rc = RPMERR_ENOENT; return (rc ? rc : RPMERR_ENOENT); /* XXX HACK */ } #define IS_DEV_LOG(_x) \ ((_x) != NULL && strlen(_x) >= (sizeof("/dev/log")-1) && \ rstreqn((_x), "/dev/log", sizeof("/dev/log")-1) && \ ((_x)[sizeof("/dev/log")-1] == '\0' || \ (_x)[sizeof("/dev/log")-1] == ';')) /* Rename pre-existing modified or unmanaged file. */ static int fsmBackup(rpmfi fi, rpmFileAction action) { int rc = 0; const char *suffix = NULL; if (!(rpmfiFFlags(fi) & RPMFILE_GHOST)) { switch (action) { case FA_SAVE: suffix = SUFFIX_RPMSAVE; break; case FA_BACKUP: suffix = SUFFIX_RPMORIG; break; default: break; } } if (suffix) { char * opath = fsmFsPath(fi, NULL); char * path = fsmFsPath(fi, suffix); rc = fsmRename(opath, path); if (!rc) { rpmlog(RPMLOG_WARNING, _("%s saved as %s\n"), opath, path); } free(path); free(opath); } return rc; } static int fsmSetmeta(const char *path, rpmfi fi, rpmPlugins plugins, rpmFileAction action, const struct stat * st, int nofcaps) { int rc = 0; const char *dest = rpmfiFN(fi); if (!rc && !getuid()) { rc = fsmChown(path, st->st_mode, st->st_uid, st->st_gid); } if (!rc && !S_ISLNK(st->st_mode)) { rc = fsmChmod(path, st->st_mode); } /* Set file capabilities (if enabled) */ if (!rc && !nofcaps && S_ISREG(st->st_mode) && !getuid()) { rc = fsmSetFCaps(path, rpmfiFCaps(fi)); } if (!rc) { rc = fsmUtime(path, st->st_mode, rpmfiFMtime(fi)); } if (!rc) { rc = rpmpluginsCallFsmFilePrepare(plugins, fi, path, dest, st->st_mode, action); } return rc; } static int fsmCommit(char **path, rpmfi fi, rpmFileAction action, const char *suffix) { int rc = 0; /* XXX Special case /dev/log, which shouldn't be packaged anyways */ if (!(S_ISSOCK(rpmfiFMode(fi)) && IS_DEV_LOG(*path))) { const char *nsuffix = (action == FA_ALTNAME) ? SUFFIX_RPMNEW : NULL; char *dest = *path; /* Construct final destination path (nsuffix is usually NULL) */ if (suffix) dest = fsmFsPath(fi, nsuffix); /* Rename temporary to final file name if needed. */ if (dest != *path) { rc = fsmRename(*path, dest); if (!rc && nsuffix) { char * opath = fsmFsPath(fi, NULL); rpmlog(RPMLOG_WARNING, _("%s created as %s\n"), opath, dest); free(opath); } free(*path); *path = dest; } } return rc; } /** * Return formatted string representation of file disposition. * @param a file disposition * @return formatted string */ static const char * fileActionString(rpmFileAction a) { switch (a) { case FA_UNKNOWN: return "unknown"; case FA_CREATE: return "create"; case FA_BACKUP: return "backup"; case FA_SAVE: return "save"; case FA_SKIP: return "skip"; case FA_ALTNAME: return "altname"; case FA_ERASE: return "erase"; case FA_SKIPNSTATE: return "skipnstate"; case FA_SKIPNETSHARED: return "skipnetshared"; case FA_SKIPCOLOR: return "skipcolor"; case FA_TOUCH: return "touch"; default: return "???"; } } /* Remember any non-regular file state for recording in the rpmdb */ static void setFileState(rpmfs fs, int i) { switch (rpmfsGetAction(fs, i)) { case FA_SKIPNSTATE: rpmfsSetState(fs, i, RPMFILE_STATE_NOTINSTALLED); break; case FA_SKIPNETSHARED: rpmfsSetState(fs, i, RPMFILE_STATE_NETSHARED); break; case FA_SKIPCOLOR: rpmfsSetState(fs, i, RPMFILE_STATE_WRONGCOLOR); break; case FA_TOUCH: rpmfsSetState(fs, i, RPMFILE_STATE_NORMAL); break; default: break; } } int rpmPackageFilesInstall(rpmts ts, rpmte te, rpmfiles files, rpmpsm psm, char ** failedFile) { FD_t payload = rpmtePayload(te); rpmfi fi = rpmfiNewArchiveReader(payload, files, RPMFI_ITER_READ_ARCHIVE); rpmfs fs = rpmteGetFileStates(te); rpmPlugins plugins = rpmtsPlugins(ts); struct stat sb; int saveerrno = errno; int rc = 0; int nodigest = (rpmtsFlags(ts) & RPMTRANS_FLAG_NOFILEDIGEST) ? 1 : 0; int nofcaps = (rpmtsFlags(ts) & RPMTRANS_FLAG_NOCAPS) ? 1 : 0; int firsthardlink = -1; int skip; rpmFileAction action; char *tid = NULL; const char *suffix; char *fpath = NULL; if (fi == NULL) { rc = RPMERR_BAD_MAGIC; goto exit; } /* transaction id used for temporary path suffix while installing */ rasprintf(&tid, ";%08x", (unsigned)rpmtsGetTid(ts)); /* Detect and create directories not explicitly in package. */ rc = fsmMkdirs(files, fs, plugins); while (!rc) { /* Read next payload header. */ rc = rpmfiNext(fi); if (rc < 0) { if (rc == RPMERR_ITER_END) rc = 0; break; } action = rpmfsGetAction(fs, rpmfiFX(fi)); skip = XFA_SKIPPING(action); suffix = S_ISDIR(rpmfiFMode(fi)) ? NULL : tid; if (action != FA_TOUCH) { fpath = fsmFsPath(fi, suffix); } else { fpath = fsmFsPath(fi, ""); } /* Remap file perms, owner, and group. */ rc = rpmfiStat(fi, 1, &sb); fsmDebug(fpath, action, &sb); /* Exit on error. */ if (rc) break; /* Run fsm file pre hook for all plugins */ rc = rpmpluginsCallFsmFilePre(plugins, fi, fpath, sb.st_mode, action); if (rc) { skip = 1; } else { setFileState(fs, rpmfiFX(fi)); } if (!skip) { int setmeta = 1; /* Directories replacing something need early backup */ if (!suffix) { rc = fsmBackup(fi, action); } /* Assume file does't exist when tmp suffix is in use */ if (!suffix) { rc = fsmVerify(fpath, fi); } else { rc = (action == FA_TOUCH) ? 0 : RPMERR_ENOENT; } if (S_ISREG(sb.st_mode)) { if (rc == RPMERR_ENOENT) { rc = fsmMkfile(fi, fpath, files, psm, nodigest, &setmeta, &firsthardlink); } } else if (S_ISDIR(sb.st_mode)) { if (rc == RPMERR_ENOENT) { mode_t mode = sb.st_mode; mode &= ~07777; mode |= 00700; rc = fsmMkdir(fpath, mode); } } else if (S_ISLNK(sb.st_mode)) { if (rc == RPMERR_ENOENT) { rc = fsmSymlink(rpmfiFLink(fi), fpath); } } else if (S_ISFIFO(sb.st_mode)) { /* This mimics cpio S_ISSOCK() behavior but probably isn't right */ if (rc == RPMERR_ENOENT) { rc = fsmMkfifo(fpath, 0000); } } else if (S_ISCHR(sb.st_mode) || S_ISBLK(sb.st_mode) || S_ISSOCK(sb.st_mode)) { if (rc == RPMERR_ENOENT) { rc = fsmMknod(fpath, sb.st_mode, sb.st_rdev); } } else { /* XXX Special case /dev/log, which shouldn't be packaged anyways */ if (!IS_DEV_LOG(fpath)) rc = RPMERR_UNKNOWN_FILETYPE; } /* Set permissions, timestamps etc for non-hardlink entries */ if (!rc && setmeta) { rc = fsmSetmeta(fpath, fi, plugins, action, &sb, nofcaps); } } else if (firsthardlink >= 0 && rpmfiArchiveHasContent(fi)) { /* we skip the hard linked file containing the content */ /* write the content to the first used instead */ char *fn = rpmfilesFN(files, firsthardlink); rc = expandRegular(fi, fn, psm, nodigest, 0); firsthardlink = -1; free(fn); } if (rc) { if (!skip) { /* XXX only erase if temp fn w suffix is in use */ if (suffix && (action != FA_TOUCH)) { (void) fsmRemove(fpath, sb.st_mode); } errno = saveerrno; } } else { /* Notify on success. */ rpmpsmNotify(psm, RPMCALLBACK_INST_PROGRESS, rpmfiArchiveTell(fi)); if (!skip) { /* Backup file if needed. Directories are handled earlier */ if (suffix) rc = fsmBackup(fi, action); if (!rc) rc = fsmCommit(&fpath, fi, action, suffix); } } if (rc) *failedFile = xstrdup(fpath); /* Run fsm file post hook for all plugins */ rpmpluginsCallFsmFilePost(plugins, fi, fpath, sb.st_mode, action, rc); fpath = _free(fpath); } rpmswAdd(rpmtsOp(ts, RPMTS_OP_UNCOMPRESS), fdOp(payload, FDSTAT_READ)); rpmswAdd(rpmtsOp(ts, RPMTS_OP_DIGEST), fdOp(payload, FDSTAT_DIGEST)); exit: /* No need to bother with close errors on read */ rpmfiArchiveClose(fi); rpmfiFree(fi); Fclose(payload); free(tid); free(fpath); return rc; } int rpmPackageFilesRemove(rpmts ts, rpmte te, rpmfiles files, rpmpsm psm, char ** failedFile) { rpmfi fi = rpmfilesIter(files, RPMFI_ITER_BACK); rpmfs fs = rpmteGetFileStates(te); rpmPlugins plugins = rpmtsPlugins(ts); struct stat sb; int rc = 0; char *fpath = NULL; while (!rc && rpmfiNext(fi) >= 0) { rpmFileAction action = rpmfsGetAction(fs, rpmfiFX(fi)); fpath = fsmFsPath(fi, NULL); rc = fsmStat(fpath, 1, &sb); fsmDebug(fpath, action, &sb); /* Run fsm file pre hook for all plugins */ rc = rpmpluginsCallFsmFilePre(plugins, fi, fpath, sb.st_mode, action); if (!XFA_SKIPPING(action)) rc = fsmBackup(fi, action); /* Remove erased files. */ if (action == FA_ERASE) { int missingok = (rpmfiFFlags(fi) & (RPMFILE_MISSINGOK | RPMFILE_GHOST)); rc = fsmRemove(fpath, sb.st_mode); /* * Missing %ghost or %missingok entries are not errors. * XXX: Are non-existent files ever an actual error here? Afterall * that's exactly what we're trying to accomplish here, * and complaining about job already done seems like kinderkarten * level "But it was MY turn!" whining... */ if (rc == RPMERR_ENOENT && missingok) { rc = 0; } /* * Dont whine on non-empty directories for now. We might be able * to track at least some of the expected failures though, * such as when we knowingly left config file backups etc behind. */ if (rc == RPMERR_ENOTEMPTY) { rc = 0; } if (rc) { int lvl = strict_erasures ? RPMLOG_ERR : RPMLOG_WARNING; rpmlog(lvl, _("%s %s: remove failed: %s\n"), S_ISDIR(sb.st_mode) ? _("directory") : _("file"), fpath, strerror(errno)); } } /* Run fsm file post hook for all plugins */ rpmpluginsCallFsmFilePost(plugins, fi, fpath, sb.st_mode, action, rc); /* XXX Failure to remove is not (yet) cause for failure. */ if (!strict_erasures) rc = 0; if (rc) *failedFile = xstrdup(fpath); if (rc == 0) { /* Notify on success. */ /* On erase we're iterating backwards, fixup for progress */ rpm_loff_t amount = rpmfiFC(fi) - rpmfiFX(fi); rpmpsmNotify(psm, RPMCALLBACK_UNINST_PROGRESS, amount); } fpath = _free(fpath); } free(fpath); rpmfiFree(fi); return rc; }
./CrossVul/dataset_final_sorted/CWE-59/c/bad_3273_0
crossvul-cpp_data_good_1506_3
/* Copyright (C) 2009 RedHat inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <sys/statvfs.h> #include "internal_libabrt.h" int low_free_space(unsigned setting_MaxCrashReportsSize, const char *dump_location) { struct statvfs vfs; if (statvfs(dump_location, &vfs) != 0) { perror_msg("statvfs('%s')", dump_location); return 0; } /* Check that at least MaxCrashReportsSize/4 MBs are free */ /* fs_free_mb_x4 ~= vfs.f_bfree * vfs.f_bsize * 4, expressed in MBytes. * Need to neither overflow nor round f_bfree down too much. */ unsigned long fs_free_mb_x4 = ((unsigned long long)vfs.f_bfree / (1024/4)) * vfs.f_bsize / 1024; if (fs_free_mb_x4 < setting_MaxCrashReportsSize) { error_msg("Only %luMiB is available on %s", fs_free_mb_x4 / 4, dump_location); return 1; } return 0; } /* rhbz#539551: "abrt going crazy when crashing process is respawned". * Check total size of problem dirs, if it overflows, * delete oldest/biggest dirs. */ void trim_problem_dirs(const char *dirname, double cap_size, const char *exclude_path) { const char *excluded_basename = NULL; if (exclude_path) { unsigned len_dirname = strlen(dirname); /* Trim trailing '/'s, but dont trim name "/" to "" */ while (len_dirname > 1 && dirname[len_dirname-1] == '/') len_dirname--; if (strncmp(dirname, exclude_path, len_dirname) == 0 && exclude_path[len_dirname] == '/' ) { /* exclude_path is "dirname/something" */ excluded_basename = exclude_path + len_dirname + 1; } } log_debug("excluded_basename:'%s'", excluded_basename); int count = 20; while (--count >= 0) { /* We exclude our own dir from candidates for deletion (3rd param): */ char *worst_basename = NULL; double cur_size = get_dirsize_find_largest_dir(dirname, &worst_basename, excluded_basename); if (cur_size <= cap_size || !worst_basename) { log_info("cur_size:%.0f cap_size:%.0f, no (more) trimming", cur_size, cap_size); free(worst_basename); break; } log("%s is %.0f bytes (more than %.0fMiB), deleting '%s'", dirname, cur_size, cap_size / (1024*1024), worst_basename); char *d = concat_path_file(dirname, worst_basename); free(worst_basename); delete_dump_dir(d); free(d); } } /** * * @param[out] status See `man 2 wait` for status information. * @return Malloc'ed string */ static char* exec_vp(char **args, int redirect_stderr, int exec_timeout_sec, int *status) { /* Nuke everything which may make setlocale() switch to non-POSIX locale: * we need to avoid having gdb output in some obscure language. */ static const char *const env_vec[] = { "LANG", "LC_ALL", "LC_COLLATE", "LC_CTYPE", "LC_MESSAGES", "LC_MONETARY", "LC_NUMERIC", "LC_TIME", /* Workaround for * http://sourceware.org/bugzilla/show_bug.cgi?id=9622 * (gdb emitting ESC sequences even with -batch) */ "TERM", NULL }; int flags = EXECFLG_INPUT_NUL | EXECFLG_OUTPUT | EXECFLG_SETSID | EXECFLG_QUIET; if (redirect_stderr) flags |= EXECFLG_ERR2OUT; VERB1 flags &= ~EXECFLG_QUIET; int pipeout[2]; pid_t child = fork_execv_on_steroids(flags, args, pipeout, (char**)env_vec, /*dir:*/ NULL, /*uid(unused):*/ 0); /* We use this function to run gdb and unstrip. Bugs in gdb or corrupted * coredumps were observed to cause gdb to enter infinite loop. * Therefore we have a (largish) timeout, after which we kill the child. */ ndelay_on(pipeout[0]); int t = time(NULL); /* int is enough, no need to use time_t */ int endtime = t + exec_timeout_sec; struct strbuf *buf_out = strbuf_new(); while (1) { int timeout = endtime - t; if (timeout < 0) { kill(child, SIGKILL); strbuf_append_strf(buf_out, "\n" "Timeout exceeded: %u seconds, killing %s.\n" "Looks like gdb hung while generating backtrace.\n" "This may be a bug in gdb. Consider submitting a bug report to gdb developers.\n" "Please attach coredump from this crash to the bug report if you do.\n", exec_timeout_sec, args[0] ); break; } /* We don't check poll result - checking read result is enough */ struct pollfd pfd; pfd.fd = pipeout[0]; pfd.events = POLLIN; poll(&pfd, 1, timeout * 1000); char buff[1024]; int r = read(pipeout[0], buff, sizeof(buff) - 1); if (r <= 0) { /* I did see EAGAIN happening here */ if (r < 0 && errno == EAGAIN) goto next; break; } buff[r] = '\0'; strbuf_append_str(buf_out, buff); next: t = time(NULL); } close(pipeout[0]); /* Prevent having zombie child process, and maybe collect status * (note that status == NULL is ok too) */ safe_waitpid(child, status, 0); return strbuf_free_nobuf(buf_out); } char *run_unstrip_n(const char *dump_dir_name, unsigned timeout_sec) { int flags = EXECFLG_INPUT_NUL | EXECFLG_OUTPUT | EXECFLG_SETSID | EXECFLG_QUIET; VERB1 flags &= ~EXECFLG_QUIET; int pipeout[2]; char* args[4]; args[0] = (char*)"eu-unstrip"; args[1] = xasprintf("--core=%s/"FILENAME_COREDUMP, dump_dir_name); args[2] = (char*)"-n"; args[3] = NULL; pid_t child = fork_execv_on_steroids(flags, args, pipeout, /*env_vec:*/ NULL, /*dir:*/ NULL, /*uid(unused):*/ 0); free(args[1]); /* Bugs in unstrip or corrupted coredumps can cause it to enter infinite loop. * Therefore we have a (largish) timeout, after which we kill the child. */ ndelay_on(pipeout[0]); int t = time(NULL); /* int is enough, no need to use time_t */ int endtime = t + timeout_sec; struct strbuf *buf_out = strbuf_new(); while (1) { int timeout = endtime - t; if (timeout < 0) { kill(child, SIGKILL); strbuf_free(buf_out); buf_out = NULL; break; } /* We don't check poll result - checking read result is enough */ struct pollfd pfd; pfd.fd = pipeout[0]; pfd.events = POLLIN; poll(&pfd, 1, timeout * 1000); char buff[1024]; int r = read(pipeout[0], buff, sizeof(buff) - 1); if (r <= 0) { /* I did see EAGAIN happening here */ if (r < 0 && errno == EAGAIN) goto next; break; } buff[r] = '\0'; strbuf_append_str(buf_out, buff); next: t = time(NULL); } close(pipeout[0]); /* Prevent having zombie child process */ int status; safe_waitpid(child, &status, 0); if (status != 0 || buf_out == NULL) { /* unstrip didnt exit with exit code 0, or we timed out */ strbuf_free(buf_out); return NULL; } return strbuf_free_nobuf(buf_out); } char *get_backtrace(const char *dump_dir_name, unsigned timeout_sec, const char *debuginfo_dirs) { INITIALIZE_LIBABRT(); struct dump_dir *dd = dd_opendir(dump_dir_name, /*flags:*/ 0); if (!dd) return NULL; char *executable = dd_load_text(dd, FILENAME_EXECUTABLE); dd_close(dd); /* Let user know what's going on */ log(_("Generating backtrace")); unsigned i = 0; char *args[25]; args[i++] = (char*)"gdb"; args[i++] = (char*)"-batch"; struct strbuf *set_debug_file_directory = strbuf_new(); unsigned auto_load_base_index = 0; if(debuginfo_dirs == NULL) { // set non-existent debug file directory to prevent resolving // function names - we need offsets for core backtrace. strbuf_append_str(set_debug_file_directory, "set debug-file-directory /"); } else { strbuf_append_str(set_debug_file_directory, "set debug-file-directory /usr/lib/debug"); struct strbuf *debug_directories = strbuf_new(); const char *p = debuginfo_dirs; while (1) { while (*p == ':') p++; if (*p == '\0') break; const char *colon_or_nul = strchrnul(p, ':'); strbuf_append_strf(debug_directories, "%s%.*s/usr/lib/debug", (debug_directories->len == 0 ? "" : ":"), (int)(colon_or_nul - p), p); p = colon_or_nul; } strbuf_append_strf(set_debug_file_directory, ":%s", debug_directories->buf); args[i++] = (char*)"-iex"; auto_load_base_index = i; args[i++] = xasprintf("add-auto-load-safe-path %s", debug_directories->buf); args[i++] = (char*)"-iex"; args[i++] = xasprintf("add-auto-load-scripts-directory %s", debug_directories->buf); strbuf_free(debug_directories); } args[i++] = (char*)"-ex"; const unsigned debug_dir_cmd_index = i++; args[debug_dir_cmd_index] = strbuf_free_nobuf(set_debug_file_directory); /* "file BINARY_FILE" is needed, without it gdb cannot properly * unwind the stack. Currently the unwind information is located * in .eh_frame which is stored only in binary, not in coredump * or debuginfo. * * Fedora GDB does not strictly need it, it will find the binary * by its build-id. But for binaries either without build-id * (= built on non-Fedora GCC) or which do not have * their debuginfo rpm installed gdb would not find BINARY_FILE * so it is still makes sense to supply "file BINARY_FILE". * * Unfortunately, "file BINARY_FILE" doesn't work well if BINARY_FILE * was deleted (as often happens during system updates): * gdb uses specified BINARY_FILE * even if it is completely unrelated to the coredump. * See https://bugzilla.redhat.com/show_bug.cgi?id=525721 * * TODO: check mtimes on COREFILE and BINARY_FILE and not supply * BINARY_FILE if it is newer (to at least avoid gdb complaining). */ args[i++] = (char*)"-ex"; const unsigned file_cmd_index = i++; args[file_cmd_index] = xasprintf("file %s", executable); free(executable); args[i++] = (char*)"-ex"; const unsigned core_cmd_index = i++; args[core_cmd_index] = xasprintf("core-file %s/"FILENAME_COREDUMP, dump_dir_name); args[i++] = (char*)"-ex"; const unsigned bt_cmd_index = i++; /*args[9] = ... see below */ args[i++] = (char*)"-ex"; args[i++] = (char*)"info sharedlib"; /* glibc's abort() stores its message in __abort_msg variable */ args[i++] = (char*)"-ex"; args[i++] = (char*)"print (char*)__abort_msg"; args[i++] = (char*)"-ex"; args[i++] = (char*)"print (char*)__glib_assert_msg"; args[i++] = (char*)"-ex"; args[i++] = (char*)"info all-registers"; args[i++] = (char*)"-ex"; const unsigned dis_cmd_index = i++; args[dis_cmd_index] = (char*)"disassemble"; args[i++] = NULL; /* Get the backtrace, but try to cap its size */ /* Limit bt depth. With no limit, gdb sometimes OOMs the machine */ unsigned bt_depth = 1024; const char *thread_apply_all = "thread apply all"; const char *full = " full"; char *bt = NULL; while (1) { args[bt_cmd_index] = xasprintf("%s backtrace %u%s", thread_apply_all, bt_depth, full); bt = exec_vp(args, /*redirect_stderr:*/ 1, timeout_sec, NULL); free(args[bt_cmd_index]); if ((bt && strnlen(bt, 256*1024) < 256*1024) || bt_depth <= 32) { break; } bt_depth /= 2; if (bt) log("Backtrace is too big (%u bytes), reducing depth to %u", (unsigned)strlen(bt), bt_depth); else /* (NB: in fact, current impl. of exec_vp() never returns NULL) */ log("Failed to generate backtrace, reducing depth to %u", bt_depth); free(bt); /* Replace -ex disassemble (which disasms entire function $pc points to) * to a version which analyzes limited, small patch of code around $pc. * (Users reported a case where bare "disassemble" attempted to process * entire .bss). * TODO: what if "$pc-N" underflows? in my test, this happens: * Dump of assembler code from 0xfffffffffffffff0 to 0x30: * End of assembler dump. * (IOW: "empty" dump) */ args[dis_cmd_index] = (char*)"disassemble $pc-20, $pc+64"; if (bt_depth <= 64 && thread_apply_all[0] != '\0') { /* This program likely has gazillion threads, dont try to bt them all */ bt_depth = 128; thread_apply_all = ""; } if (bt_depth <= 64 && full[0] != '\0') { /* Looks like there are gigantic local structures or arrays, disable "full" bt */ bt_depth = 128; full = ""; } } if (auto_load_base_index > 0) { free(args[auto_load_base_index]); free(args[auto_load_base_index + 2]); } free(args[debug_dir_cmd_index]); free(args[file_cmd_index]); free(args[core_cmd_index]); return bt; } char* problem_data_save(problem_data_t *pd) { load_abrt_conf(); struct dump_dir *dd = NULL; if (g_settings_privatereports) dd = create_dump_dir_from_problem_data_ext(pd, g_settings_dump_location, 0); else dd = create_dump_dir_from_problem_data(pd, g_settings_dump_location); char *problem_id = NULL; if (dd) { problem_id = xstrdup(dd->dd_dirname); dd_close(dd); } log_info("problem id: '%s'", problem_id); return problem_id; } bool dir_is_in_dump_location(const char *dir_name) { unsigned len = strlen(g_settings_dump_location); /* The path must start with "g_settings_dump_location" */ if (strncmp(dir_name, g_settings_dump_location, len) != 0) { log_debug("Bad parent directory: '%s' not in '%s'", g_settings_dump_location, dir_name); return false; } /* and must be a sub-directory of the g_settings_dump_location dir */ const char *base_name = dir_name + len; while (*base_name && *base_name == '/') ++base_name; if (*(base_name - 1) != '/' || !str_is_correct_filename(base_name)) { log_debug("Invalid dump directory name: '%s'", base_name); return false; } /* and we are sure it is a directory */ struct stat sb; if (lstat(dir_name, &sb) < 0) { VERB2 perror_msg("stat('%s')", dir_name); return errno== ENOENT; } return S_ISDIR(sb.st_mode); } bool dir_has_correct_permissions(const char *dir_name) { if (g_settings_privatereports) { struct stat statbuf; if (lstat(dir_name, &statbuf) != 0 || !S_ISDIR(statbuf.st_mode)) { error_msg("Path '%s' isn't directory", dir_name); return false; } /* Get ABRT's group gid */ struct group *gr = getgrnam("abrt"); if (!gr) { error_msg("Group 'abrt' does not exist"); return false; } if (statbuf.st_uid != 0 || !(statbuf.st_gid == 0 || statbuf.st_gid == gr->gr_gid) || statbuf.st_mode & 07) return false; } return true; } bool allowed_new_user_problem_entry(uid_t uid, const char *name, const char *value) { /* Allow root to create everything */ if (uid == 0) return true; /* Permit non-root users to create everything except: analyzer and type */ if (strcmp(name, FILENAME_ANALYZER) != 0 && strcmp(name, FILENAME_TYPE) != 0 /* compatibility value used in abrt-server */ && strcmp(name, "basename") != 0) return true; /* Permit non-root users to create all types except: C/C++, Koops, vmcore and xorg */ if (strcmp(value, "CCpp") != 0 && strcmp(value, "Kerneloops") != 0 && strcmp(value, "vmcore") != 0 && strcmp(value, "xorg") != 0) return true; error_msg("Only root is permitted to create element '%s' containing '%s'", name, value); return false; }
./CrossVul/dataset_final_sorted/CWE-59/c/good_1506_3
crossvul-cpp_data_bad_1590_0
/* abrt-hook-ccpp.cpp - the hook for C/C++ crashing program Copyright (C) 2009 Zdenek Prikryl (zprikryl@redhat.com) Copyright (C) 2009 RedHat inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <sys/utsname.h> #include "libabrt.h" #define DUMP_SUID_UNSAFE 1 #define DUMP_SUID_SAFE 2 /* I want to use -Werror, but gcc-4.4 throws a curveball: * "warning: ignoring return value of 'ftruncate', declared with attribute warn_unused_result" * and (void) cast is not enough to shut it up! Oh God... */ #define IGNORE_RESULT(func_call) do { if (func_call) /* nothing */; } while (0) static char* malloc_readlink(const char *linkname) { char buf[PATH_MAX + 1]; int len; len = readlink(linkname, buf, sizeof(buf)-1); if (len >= 0) { buf[len] = '\0'; return xstrdup(buf); } return NULL; } /* Custom version of copyfd_xyz, * one which is able to write into two descriptors at once. */ #define CONFIG_FEATURE_COPYBUF_KB 4 static off_t copyfd_sparse(int src_fd, int dst_fd1, int dst_fd2, off_t size2) { off_t total = 0; int last_was_seek = 0; #if CONFIG_FEATURE_COPYBUF_KB <= 4 char buffer[CONFIG_FEATURE_COPYBUF_KB * 1024]; enum { buffer_size = sizeof(buffer) }; #else char *buffer; int buffer_size; /* We want page-aligned buffer, just in case kernel is clever * and can do page-aligned io more efficiently */ buffer = mmap(NULL, CONFIG_FEATURE_COPYBUF_KB * 1024, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, /* ignored: */ -1, 0); buffer_size = CONFIG_FEATURE_COPYBUF_KB * 1024; if (buffer == MAP_FAILED) { buffer = alloca(4 * 1024); buffer_size = 4 * 1024; } #endif while (1) { ssize_t rd = safe_read(src_fd, buffer, buffer_size); if (!rd) { /* eof */ if (last_was_seek) { if (lseek(dst_fd1, -1, SEEK_CUR) < 0 || safe_write(dst_fd1, "", 1) != 1 || (dst_fd2 >= 0 && (lseek(dst_fd2, -1, SEEK_CUR) < 0 || safe_write(dst_fd2, "", 1) != 1 ) ) ) { perror_msg("Write error"); total = -1; goto out; } } /* all done */ goto out; } if (rd < 0) { perror_msg("Read error"); total = -1; goto out; } /* checking sparseness */ ssize_t cnt = rd; while (--cnt >= 0) { if (buffer[cnt] != 0) { /* not sparse */ errno = 0; ssize_t wr1 = full_write(dst_fd1, buffer, rd); ssize_t wr2 = (dst_fd2 >= 0 ? full_write(dst_fd2, buffer, rd) : rd); if (wr1 < rd || wr2 < rd) { perror_msg("Write error"); total = -1; goto out; } last_was_seek = 0; goto adv; } } /* sparse */ xlseek(dst_fd1, rd, SEEK_CUR); if (dst_fd2 >= 0) xlseek(dst_fd2, rd, SEEK_CUR); last_was_seek = 1; adv: total += rd; size2 -= rd; if (size2 < 0) dst_fd2 = -1; //TODO: truncate to 0 or even delete the second file //(currently we delete the file later) } out: #if CONFIG_FEATURE_COPYBUF_KB > 4 if (buffer_size != 4 * 1024) munmap(buffer, buffer_size); #endif return total; } /* Global data */ static char *user_pwd; static char *proc_pid_status; static struct dump_dir *dd; static int user_core_fd = -1; /* * %s - signal number * %c - ulimit -c value * %p - pid * %u - uid * %g - gid * %t - UNIX time of dump * %e - executable filename * %h - hostname * %% - output one "%" */ /* Hook must be installed with exactly the same sequence of %c specifiers. * Last one, %h, may be omitted (we can find it out). */ static const char percent_specifiers[] = "%scpugteh"; static char *core_basename = (char*) "core"; /* * Used for error messages only. * It is either the same as core_basename if it is absolute, * or $PWD/core_basename. */ static char *full_core_basename; static char* get_executable(pid_t pid, int *fd_p) { char buf[sizeof("/proc/%lu/exe") + sizeof(long)*3]; sprintf(buf, "/proc/%lu/exe", (long)pid); if (fd_p) *fd_p = open(buf, O_RDONLY); /* might fail and return -1, it's ok */ char *executable = malloc_readlink(buf); if (!executable) return NULL; /* find and cut off " (deleted)" from the path */ char *deleted = executable + strlen(executable) - strlen(" (deleted)"); if (deleted > executable && strcmp(deleted, " (deleted)") == 0) { *deleted = '\0'; log("File '%s' seems to be deleted", executable); } /* find and cut off prelink suffixes from the path */ char *prelink = executable + strlen(executable) - strlen(".#prelink#.XXXXXX"); if (prelink > executable && strncmp(prelink, ".#prelink#.", strlen(".#prelink#.")) == 0) { log("File '%s' seems to be a prelink temporary file", executable); *prelink = '\0'; } return executable; } static char* get_cwd(pid_t pid) { char buf[sizeof("/proc/%lu/cwd") + sizeof(long)*3]; sprintf(buf, "/proc/%lu/cwd", (long)pid); return malloc_readlink(buf); } static char* get_rootdir(pid_t pid) { char buf[sizeof("/proc/%lu/root") + sizeof(long)*3]; sprintf(buf, "/proc/%lu/root", (long)pid); return malloc_readlink(buf); } static int get_fsuid(void) { int real, euid, saved; /* if we fail to parse the uid, then make it root only readable to be safe */ int fs_uid = 0; char *line = proc_pid_status; /* never NULL */ for (;;) { if (strncmp(line, "Uid", 3) == 0) { int n = sscanf(line, "Uid:\t%d\t%d\t%d\t%d\n", &real, &euid, &saved, &fs_uid); if (n != 4) { perror_msg_and_die("Can't parse Uid: line"); } break; } line = strchr(line, '\n'); if (!line) break; line++; } return fs_uid; } static int dump_suid_policy() { /* - values are: 0 - don't dump suided programs - in this case the hook is not called by kernel 1 - create coredump readable by fs_uid 2 - create coredump readable by root only */ int c; int suid_dump_policy = 0; const char *filename = "/proc/sys/fs/suid_dumpable"; FILE *f = fopen(filename, "r"); if (!f) { log("Can't open %s", filename); return suid_dump_policy; } c = fgetc(f); fclose(f); if (c != EOF) suid_dump_policy = c - '0'; //log("suid dump policy is: %i", suid_dump_policy); return suid_dump_policy; } static int open_user_core(uid_t uid, uid_t fsuid, pid_t pid, char **percent_values) { errno = 0; if (user_pwd == NULL || chdir(user_pwd) != 0 ) { perror_msg("Can't cd to '%s'", user_pwd); return -1; } struct passwd* pw = getpwuid(uid); gid_t gid = pw ? pw->pw_gid : uid; //log("setting uid: %i gid: %i", uid, gid); xsetegid(gid); xseteuid(fsuid); if (strcmp(core_basename, "core") == 0) { /* Mimic "core.PID" if requested */ char buf[] = "0\n"; int fd = open("/proc/sys/kernel/core_uses_pid", O_RDONLY); if (fd >= 0) { IGNORE_RESULT(read(fd, buf, sizeof(buf))); close(fd); } if (strcmp(buf, "1\n") == 0) { core_basename = xasprintf("%s.%lu", core_basename, (long)pid); } } else { /* Expand old core pattern, put expanded name in core_basename */ core_basename = xstrdup(core_basename); unsigned idx = 0; while (1) { char c = core_basename[idx]; if (!c) break; idx++; if (c != '%') continue; /* We just copied %, look at following char and expand %c */ c = core_basename[idx]; unsigned specifier_num = strchrnul(percent_specifiers, c) - percent_specifiers; if (percent_specifiers[specifier_num] != '\0') /* valid %c (might be %% too) */ { const char *val = "%"; if (specifier_num > 0) /* not %% */ val = percent_values[specifier_num - 1]; //log("c:'%c'", c); //log("val:'%s'", val); /* Replace %c at core_basename[idx] by its value */ idx--; char *old = core_basename; core_basename = xasprintf("%.*s%s%s", idx, core_basename, val, core_basename + idx + 2); //log("pos:'%*s|'", idx, ""); //log("new:'%s'", core_basename); //log("old:'%s'", old); free(old); idx += strlen(val); } /* else: invalid %c, % is already copied verbatim, * next loop iteration will copy c */ } } full_core_basename = core_basename; if (core_basename[0] != '/') core_basename = concat_path_file(user_pwd, core_basename); /* Open (create) compat core file. * man core: * There are various circumstances in which a core dump file * is not produced: * * [skipped obvious ones] * The process does not have permission to write the core file. * ...if a file with the same name exists and is not writable * or is not a regular file (e.g., it is a directory or a symbolic link). * * A file with the same name already exists, but there is more * than one hard link to that file. * * The file system where the core dump file would be created is full; * or has run out of inodes; or is mounted read-only; * or the user has reached their quota for the file system. * * The RLIMIT_CORE or RLIMIT_FSIZE resource limits for the process * are set to zero. * [we check RLIMIT_CORE, but how can we check RLIMIT_FSIZE?] * * The binary being executed by the process does not have * read permission enabled. [how we can check it here?] * * The process is executing a set-user-ID (set-group-ID) program * that is owned by a user (group) other than the real * user (group) ID of the process. [TODO?] * (However, see the description of the prctl(2) PR_SET_DUMPABLE operation, * and the description of the /proc/sys/fs/suid_dumpable file in proc(5).) */ struct stat sb; errno = 0; /* Do not O_TRUNC: if later checks fail, we do not want to have file already modified here */ int user_core_fd = open(core_basename, O_WRONLY | O_CREAT | O_NOFOLLOW, 0600); /* kernel makes 0600 too */ xsetegid(0); xseteuid(0); if (user_core_fd < 0 || fstat(user_core_fd, &sb) != 0 || !S_ISREG(sb.st_mode) || sb.st_nlink != 1 /* kernel internal dumper checks this too: if (inode->i_uid != current->fsuid) <fail>, need to mimic? */ ) { if (user_core_fd < 0) perror_msg("Can't open '%s'", full_core_basename); else perror_msg("'%s' is not a regular file with link count 1", full_core_basename); return -1; } if (ftruncate(user_core_fd, 0) != 0) { /* perror first, otherwise unlink may trash errno */ perror_msg("Can't truncate '%s' to size 0", full_core_basename); unlink(core_basename); return -1; } return user_core_fd; } static bool dump_fd_info(const char *dest_filename, char *source_filename, int source_base_ofs, uid_t uid, gid_t gid) { FILE *fp = fopen(dest_filename, "w"); if (!fp) return false; unsigned fd = 0; while (fd <= 99999) /* paranoia check */ { sprintf(source_filename + source_base_ofs, "fd/%u", fd); char *name = malloc_readlink(source_filename); if (!name) break; fprintf(fp, "%u:%s\n", fd, name); free(name); sprintf(source_filename + source_base_ofs, "fdinfo/%u", fd); fd++; FILE *in = fopen(source_filename, "r"); if (!in) continue; char buf[128]; while (fgets(buf, sizeof(buf)-1, in)) { /* in case the line is not terminated, terminate it */ char *eol = strchrnul(buf, '\n'); eol[0] = '\n'; eol[1] = '\0'; fputs(buf, fp); } fclose(in); } const int dest_fd = fileno(fp); if (fchown(dest_fd, uid, gid) < 0) { perror_msg("Can't change '%s' ownership to %lu:%lu", dest_filename, (long)uid, (long)gid); fclose(fp); unlink(dest_filename); return false; } fclose(fp); return true; } /* Like xopen, but on error, unlocks and deletes dd and user core */ static int create_or_die(const char *filename) { int fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, DEFAULT_DUMP_DIR_MODE); if (fd >= 0) { IGNORE_RESULT(fchown(fd, dd->dd_uid, dd->dd_gid)); return fd; } int sv_errno = errno; if (dd) dd_delete(dd); if (user_core_fd >= 0) { xchdir(user_pwd); unlink(core_basename); } errno = sv_errno; perror_msg_and_die("Can't open '%s'", filename); } int main(int argc, char** argv) { /* Kernel starts us with all fd's closed. * But it's dangerous: * fprintf(stderr) can dump messages into random fds, etc. * Ensure that if any of fd 0,1,2 is closed, we open it to /dev/null. */ int fd = xopen("/dev/null", O_RDWR); while (fd < 2) fd = xdup(fd); if (fd > 2) close(fd); if (argc < 8) { /* percent specifier: %s %c %p %u %g %t %e %h */ /* argv: [0] [1] [2] [3] [4] [5] [6] [7] [8]*/ error_msg_and_die("Usage: %s SIGNO CORE_SIZE_LIMIT PID UID GID TIME BINARY_NAME [HOSTNAME]", argv[0]); } /* Not needed on 2.6.30. * At least 2.6.18 has a bug where * argv[1] = "SIGNO CORE_SIZE_LIMIT PID ..." * argv[2] = "CORE_SIZE_LIMIT PID ..." * and so on. Fixing it: */ if (strchr(argv[1], ' ')) { int i; for (i = 1; argv[i]; i++) { strchrnul(argv[i], ' ')[0] = '\0'; } } logmode = LOGMODE_JOURNAL; /* Parse abrt.conf */ load_abrt_conf(); /* ... and plugins/CCpp.conf */ bool setting_MakeCompatCore; bool setting_SaveBinaryImage; { map_string_t *settings = new_map_string(); load_abrt_plugin_conf_file("CCpp.conf", settings); const char *value; value = get_map_string_item_or_NULL(settings, "MakeCompatCore"); setting_MakeCompatCore = value && string_to_bool(value); value = get_map_string_item_or_NULL(settings, "SaveBinaryImage"); setting_SaveBinaryImage = value && string_to_bool(value); value = get_map_string_item_or_NULL(settings, "VerboseLog"); if (value) g_verbose = xatoi_positive(value); free_map_string(settings); } errno = 0; const char* signal_str = argv[1]; int signal_no = xatoi_positive(signal_str); off_t ulimit_c = strtoull(argv[2], NULL, 10); if (ulimit_c < 0) /* unlimited? */ { /* set to max possible >0 value */ ulimit_c = ~((off_t)1 << (sizeof(off_t)*8-1)); } const char *pid_str = argv[3]; pid_t pid = xatoi_positive(argv[3]); uid_t uid = xatoi_positive(argv[4]); if (errno || pid <= 0) { perror_msg_and_die("PID '%s' or limit '%s' is bogus", argv[3], argv[2]); } { char *s = xmalloc_fopen_fgetline_fclose(VAR_RUN"/abrt/saved_core_pattern"); /* If we have a saved pattern and it's not a "|PROG ARGS" thing... */ if (s && s[0] != '|') core_basename = s; else free(s); } struct utsname uts; if (!argv[8]) /* no HOSTNAME? */ { uname(&uts); argv[8] = uts.nodename; } char path[PATH_MAX]; int src_fd_binary = -1; char *executable = get_executable(pid, setting_SaveBinaryImage ? &src_fd_binary : NULL); if (executable && strstr(executable, "/abrt-hook-ccpp")) { error_msg_and_die("PID %lu is '%s', not dumping it to avoid recursion", (long)pid, executable); } user_pwd = get_cwd(pid); /* may be NULL on error */ log_notice("user_pwd:'%s'", user_pwd); sprintf(path, "/proc/%lu/status", (long)pid); proc_pid_status = xmalloc_xopen_read_close(path, /*maxsz:*/ NULL); uid_t fsuid = uid; uid_t tmp_fsuid = get_fsuid(); int suid_policy = dump_suid_policy(); if (tmp_fsuid != uid) { /* use root for suided apps unless it's explicitly set to UNSAFE */ fsuid = 0; if (suid_policy == DUMP_SUID_UNSAFE) { fsuid = tmp_fsuid; } } /* Open a fd to compat coredump, if requested and is possible */ if (setting_MakeCompatCore && ulimit_c != 0) /* note: checks "user_pwd == NULL" inside; updates core_basename */ user_core_fd = open_user_core(uid, fsuid, pid, &argv[1]); if (executable == NULL) { /* readlink on /proc/$PID/exe failed, don't create abrt dump dir */ error_msg("Can't read /proc/%lu/exe link", (long)pid); goto create_user_core; } const char *signame = NULL; switch (signal_no) { case SIGILL : signame = "ILL" ; break; case SIGFPE : signame = "FPE" ; break; case SIGSEGV: signame = "SEGV"; break; case SIGBUS : signame = "BUS" ; break; //Bus error (bad memory access) case SIGABRT: signame = "ABRT"; break; //usually when abort() was called // We have real-world reports from users who see buggy programs // dying with SIGTRAP, uncommented it too: case SIGTRAP: signame = "TRAP"; break; //Trace/breakpoint trap // These usually aren't caused by bugs: //case SIGQUIT: signame = "QUIT"; break; //Quit from keyboard //case SIGSYS : signame = "SYS" ; break; //Bad argument to routine (SVr4) //case SIGXCPU: signame = "XCPU"; break; //CPU time limit exceeded (4.2BSD) //case SIGXFSZ: signame = "XFSZ"; break; //File size limit exceeded (4.2BSD) default: goto create_user_core; // not a signal we care about } if (!daemon_is_ok()) { /* not an error, exit with exit code 0 */ log("abrtd is not running. If it crashed, " "/proc/sys/kernel/core_pattern contains a stale value, " "consider resetting it to 'core'" ); goto create_user_core; } if (g_settings_nMaxCrashReportsSize > 0) { /* If free space is less than 1/4 of MaxCrashReportsSize... */ if (low_free_space(g_settings_nMaxCrashReportsSize, g_settings_dump_location)) goto create_user_core; } /* Check /var/tmp/abrt/last-ccpp marker, do not dump repeated crashes * if they happen too often. Else, write new marker value. */ snprintf(path, sizeof(path), "%s/last-ccpp", g_settings_dump_location); if (check_recent_crash_file(path, executable)) { /* It is a repeating crash */ goto create_user_core; } const char *last_slash = strrchr(executable, '/'); if (last_slash && strncmp(++last_slash, "abrt", 4) == 0) { /* If abrtd/abrt-foo crashes, we don't want to create a _directory_, * since that can make new copy of abrtd to process it, * and maybe crash again... * Unlike dirs, mere files are ignored by abrtd. */ snprintf(path, sizeof(path), "%s/%s-coredump", g_settings_dump_location, last_slash); int abrt_core_fd = xopen3(path, O_WRONLY | O_CREAT | O_TRUNC, 0600); off_t core_size = copyfd_eof(STDIN_FILENO, abrt_core_fd, COPYFD_SPARSE); if (core_size < 0 || fsync(abrt_core_fd) != 0) { unlink(path); /* copyfd_eof logs the error including errno string, * but it does not log file name */ error_msg_and_die("Error saving '%s'", path); } log("Saved core dump of pid %lu (%s) to %s (%llu bytes)", (long)pid, executable, path, (long long)core_size); return 0; } unsigned path_len = snprintf(path, sizeof(path), "%s/ccpp-%s-%lu.new", g_settings_dump_location, iso_date_string(NULL), (long)pid); if (path_len >= (sizeof(path) - sizeof("/"FILENAME_COREDUMP))) { goto create_user_core; } /* use fsuid instead of uid, so we don't expose any sensitive * information of suided app in /var/tmp/abrt */ dd = dd_create(path, fsuid, DEFAULT_DUMP_DIR_MODE); if (dd) { char *rootdir = get_rootdir(pid); dd_create_basic_files(dd, fsuid, (rootdir && strcmp(rootdir, "/") != 0) ? rootdir : NULL); char source_filename[sizeof("/proc/%lu/somewhat_long_name") + sizeof(long)*3]; int source_base_ofs = sprintf(source_filename, "/proc/%lu/smaps", (long)pid); source_base_ofs -= strlen("smaps"); char *dest_filename = concat_path_file(dd->dd_dirname, "also_somewhat_longish_name"); char *dest_base = strrchr(dest_filename, '/') + 1; // Disabled for now: /proc/PID/smaps tends to be BIG, // and not much more informative than /proc/PID/maps: //copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL); strcpy(source_filename + source_base_ofs, "maps"); strcpy(dest_base, FILENAME_MAPS); copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL); strcpy(source_filename + source_base_ofs, "limits"); strcpy(dest_base, FILENAME_LIMITS); copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL); strcpy(source_filename + source_base_ofs, "cgroup"); strcpy(dest_base, FILENAME_CGROUP); copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL); strcpy(dest_base, FILENAME_OPEN_FDS); dump_fd_info(dest_filename, source_filename, source_base_ofs, dd->dd_uid, dd->dd_gid); free(dest_filename); dd_save_text(dd, FILENAME_ANALYZER, "CCpp"); dd_save_text(dd, FILENAME_TYPE, "CCpp"); dd_save_text(dd, FILENAME_EXECUTABLE, executable); dd_save_text(dd, FILENAME_PID, pid_str); dd_save_text(dd, FILENAME_PROC_PID_STATUS, proc_pid_status); if (user_pwd) dd_save_text(dd, FILENAME_PWD, user_pwd); if (rootdir) { if (strcmp(rootdir, "/") != 0) dd_save_text(dd, FILENAME_ROOTDIR, rootdir); } char *reason = xasprintf("%s killed by SIG%s", last_slash, signame ? signame : signal_str); dd_save_text(dd, FILENAME_REASON, reason); free(reason); char *cmdline = get_cmdline(pid); dd_save_text(dd, FILENAME_CMDLINE, cmdline ? : ""); free(cmdline); char *environ = get_environ(pid); dd_save_text(dd, FILENAME_ENVIRON, environ ? : ""); free(environ); char *fips_enabled = xmalloc_fopen_fgetline_fclose("/proc/sys/crypto/fips_enabled"); if (fips_enabled) { if (strcmp(fips_enabled, "0") != 0) dd_save_text(dd, "fips_enabled", fips_enabled); free(fips_enabled); } dd_save_text(dd, FILENAME_ABRT_VERSION, VERSION); if (src_fd_binary > 0) { strcpy(path + path_len, "/"FILENAME_BINARY); int dst_fd = create_or_die(path); off_t sz = copyfd_eof(src_fd_binary, dst_fd, COPYFD_SPARSE); if (fsync(dst_fd) != 0 || close(dst_fd) != 0 || sz < 0) { dd_delete(dd); error_msg_and_die("Error saving '%s'", path); } close(src_fd_binary); } strcpy(path + path_len, "/"FILENAME_COREDUMP); int abrt_core_fd = create_or_die(path); /* We write both coredumps at once. * We can't write user coredump first, since it might be truncated * and thus can't be copied and used as abrt coredump; * and if we write abrt coredump first and then copy it as user one, * then we have a race when process exits but coredump does not exist yet: * $ echo -e '#include<signal.h>\nmain(){raise(SIGSEGV);}' | gcc -o test -x c - * $ rm -f core*; ulimit -c unlimited; ./test; ls -l core* * 21631 Segmentation fault (core dumped) ./test * ls: cannot access core*: No such file or directory <=== BAD */ off_t core_size = copyfd_sparse(STDIN_FILENO, abrt_core_fd, user_core_fd, ulimit_c); if (fsync(abrt_core_fd) != 0 || close(abrt_core_fd) != 0 || core_size < 0) { unlink(path); dd_delete(dd); if (user_core_fd >= 0) { xchdir(user_pwd); unlink(core_basename); } /* copyfd_sparse logs the error including errno string, * but it does not log file name */ error_msg_and_die("Error writing '%s'", path); } if (user_core_fd >= 0 /* error writing user coredump? */ && (fsync(user_core_fd) != 0 || close(user_core_fd) != 0 /* user coredump is too big? */ || (ulimit_c == 0 /* paranoia */ || core_size > ulimit_c) ) ) { /* nuke it (silently) */ xchdir(user_pwd); unlink(core_basename); } /* Save JVM crash log if it exists. (JVM's coredump per se * is nearly useless for JVM developers) */ { char *java_log = xasprintf("/tmp/jvm-%lu/hs_error.log", (long)pid); int src_fd = open(java_log, O_RDONLY); free(java_log); /* If we couldn't open the error log in /tmp directory we can try to * read the log from the current directory. It may produce AVC, it * may produce some error log but all these are expected. */ if (src_fd < 0) { java_log = xasprintf("%s/hs_err_pid%lu.log", user_pwd, (long)pid); src_fd = open(java_log, O_RDONLY); free(java_log); } if (src_fd >= 0) { strcpy(path + path_len, "/hs_err.log"); int dst_fd = create_or_die(path); off_t sz = copyfd_eof(src_fd, dst_fd, COPYFD_SPARSE); if (close(dst_fd) != 0 || sz < 0) { dd_delete(dd); error_msg_and_die("Error saving '%s'", path); } close(src_fd); } } /* We close dumpdir before we start catering for crash storm case. * Otherwise, delete_dump_dir's from other concurrent * CCpp's won't be able to delete our dump (their delete_dump_dir * will wait for us), and we won't be able to delete their dumps. * Classic deadlock. */ dd_close(dd); path[path_len] = '\0'; /* path now contains only directory name */ char *newpath = xstrndup(path, path_len - (sizeof(".new")-1)); if (rename(path, newpath) == 0) strcpy(path, newpath); free(newpath); log("Saved core dump of pid %lu (%s) to %s (%llu bytes)", (long)pid, executable, path, (long long)core_size); notify_new_path(path); /* rhbz#539551: "abrt going crazy when crashing process is respawned" */ if (g_settings_nMaxCrashReportsSize > 0) { /* x1.25 and round up to 64m: go a bit up, so that usual in-daemon trimming * kicks in first, and we don't "fight" with it: */ unsigned maxsize = g_settings_nMaxCrashReportsSize + g_settings_nMaxCrashReportsSize / 4; maxsize |= 63; trim_problem_dirs(g_settings_dump_location, maxsize * (double)(1024*1024), path); } free(rootdir); return 0; } /* We didn't create abrt dump, but may need to create compat coredump */ create_user_core: if (user_core_fd >= 0) { off_t core_size = copyfd_size(STDIN_FILENO, user_core_fd, ulimit_c, COPYFD_SPARSE); if (fsync(user_core_fd) != 0 || close(user_core_fd) != 0 || core_size < 0) { /* perror first, otherwise unlink may trash errno */ perror_msg("Error writing '%s'", full_core_basename); xchdir(user_pwd); unlink(core_basename); return 1; } if (ulimit_c == 0 || core_size > ulimit_c) { xchdir(user_pwd); unlink(core_basename); return 1; } log("Saved core dump of pid %lu to %s (%llu bytes)", (long)pid, full_core_basename, (long long)core_size); } return 0; }
./CrossVul/dataset_final_sorted/CWE-59/c/bad_1590_0
crossvul-cpp_data_good_825_0
/* * Copyright (C) 2015 Canonical Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "mount-support.h" #include <errno.h> #include <fcntl.h> #include <libgen.h> #include <limits.h> #include <mntent.h> #include <sched.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/mount.h> #include <sys/stat.h> #include <sys/syscall.h> #include <sys/types.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #include "../libsnap-confine-private/apparmor-support.h" #include "../libsnap-confine-private/classic.h" #include "../libsnap-confine-private/cleanup-funcs.h" #include "../libsnap-confine-private/mount-opt.h" #include "../libsnap-confine-private/mountinfo.h" #include "../libsnap-confine-private/snap.h" #include "../libsnap-confine-private/string-utils.h" #include "../libsnap-confine-private/tool.h" #include "../libsnap-confine-private/utils.h" #include "mount-support-nvidia.h" #define MAX_BUF 1000 /*! * The void directory. * * Snap confine moves to that directory in case it cannot retain the current * working directory across the pivot_root call. **/ #define SC_VOID_DIR "/var/lib/snapd/void" // TODO: simplify this, after all it is just a tmpfs // TODO: fold this into bootstrap static void setup_private_mount(const char *snap_name) { char tmpdir[MAX_BUF] = { 0 }; // Create a 0700 base directory, this is the base dir that is // protected from other users. // // Under that basedir, we put a 1777 /tmp dir that is then bind // mounted for the applications to use sc_must_snprintf(tmpdir, sizeof(tmpdir), "/tmp/snap.%s_XXXXXX", snap_name); if (mkdtemp(tmpdir) == NULL) { die("cannot create temporary directory essential for private /tmp"); } // now we create a 1777 /tmp inside our private dir mode_t old_mask = umask(0); char *d = sc_strdup(tmpdir); sc_must_snprintf(tmpdir, sizeof(tmpdir), "%s/tmp", d); free(d); if (mkdir(tmpdir, 01777) != 0) { die("cannot create temporary directory for private /tmp"); } umask(old_mask); // chdir to '/' since the mount won't apply to the current directory char *pwd = get_current_dir_name(); if (pwd == NULL) die("cannot get current working directory"); if (chdir("/") != 0) die("cannot change directory to '/'"); // MS_BIND is there from linux 2.4 sc_do_mount(tmpdir, "/tmp", NULL, MS_BIND, NULL); // MS_PRIVATE needs linux > 2.6.11 sc_do_mount("none", "/tmp", NULL, MS_PRIVATE, NULL); // do the chown after the bind mount to avoid potential shenanigans if (chown("/tmp/", 0, 0) < 0) { die("cannot change ownership of /tmp"); } // chdir to original directory if (chdir(pwd) != 0) die("cannot change current working directory to the original directory"); free(pwd); } // TODO: fold this into bootstrap static void setup_private_pts(void) { // See https://www.kernel.org/doc/Documentation/filesystems/devpts.txt // // Ubuntu by default uses devpts 'single-instance' mode where // /dev/pts/ptmx is mounted with ptmxmode=0000. We don't want to change // the startup scripts though, so we follow the instructions in point // '4' of 'User-space changes' in the above doc. In other words, after // unshare(CLONE_NEWNS), we mount devpts with -o // newinstance,ptmxmode=0666 and then bind mount /dev/pts/ptmx onto // /dev/ptmx struct stat st; // Make sure /dev/pts/ptmx exists, otherwise we are in legacy mode // which doesn't provide the isolation we require. if (stat("/dev/pts/ptmx", &st) != 0) { die("cannot stat /dev/pts/ptmx"); } // Make sure /dev/ptmx exists so we can bind mount over it if (stat("/dev/ptmx", &st) != 0) { die("cannot stat /dev/ptmx"); } // Since multi-instance, use ptmxmode=0666. The other options are // copied from /etc/default/devpts sc_do_mount("devpts", "/dev/pts", "devpts", MS_MGC_VAL, "newinstance,ptmxmode=0666,mode=0620,gid=5"); sc_do_mount("/dev/pts/ptmx", "/dev/ptmx", "none", MS_BIND, 0); } struct sc_mount { const char *path; bool is_bidirectional; // Alternate path defines the rbind mount "alternative" of path. // It exists so that we can make /media on systems that use /run/media. const char *altpath; // Optional mount points are not processed unless the source and // destination both exist. bool is_optional; }; struct sc_mount_config { const char *rootfs_dir; // The struct is terminated with an entry with NULL path. const struct sc_mount *mounts; sc_distro distro; bool normal_mode; const char *base_snap_name; }; /** * Bootstrap mount namespace. * * This is a chunk of tricky code that lets us have full control over the * layout and direction of propagation of mount events. The documentation below * assumes knowledge of the 'sharedsubtree.txt' document from the kernel source * tree. * * As a reminder two definitions are quoted below: * * A 'propagation event' is defined as event generated on a vfsmount * that leads to mount or unmount actions in other vfsmounts. * * A 'peer group' is defined as a group of vfsmounts that propagate * events to each other. * * (end of quote). * * The main idea is to setup a mount namespace that has a root filesystem with * vfsmounts and peer groups that, depending on the location, either isolate * or share with the rest of the system. * * The vast majority of the filesystem is shared in one direction. Events from * the outside (from the main mount namespace) propagate inside (to namespaces * of particular snaps) so things like new snap revisions, mounted drives, etc, * just show up as expected but even if a snap is exploited or malicious in * nature it cannot affect anything in another namespace where it might cause * security or stability issues. * * Selected directories (today just /media) can be shared in both directions. * This allows snaps with sufficient privileges to either create, through the * mount system call, additional mount points that are visible by the rest of * the system (both the main mount namespace and namespaces of individual * snaps) or remove them, through the unmount system call. **/ static void sc_bootstrap_mount_namespace(const struct sc_mount_config *config) { char scratch_dir[] = "/tmp/snap.rootfs_XXXXXX"; char src[PATH_MAX] = { 0 }; char dst[PATH_MAX] = { 0 }; if (mkdtemp(scratch_dir) == NULL) { die("cannot create temporary directory for the root file system"); } // NOTE: at this stage we just called unshare(CLONE_NEWNS). We are in a new // mount namespace and have a private list of mounts. debug("scratch directory for constructing namespace: %s", scratch_dir); // Make the root filesystem recursively shared. This way propagation events // will be shared with main mount namespace. sc_do_mount("none", "/", NULL, MS_REC | MS_SHARED, NULL); // Bind mount the temporary scratch directory for root filesystem over // itself so that it is a mount point. This is done so that it can become // unbindable as explained below. sc_do_mount(scratch_dir, scratch_dir, NULL, MS_BIND, NULL); // Make the scratch directory unbindable. // // This is necessary as otherwise a mount loop can occur and the kernel // would crash. The term unbindable simply states that it cannot be bind // mounted anywhere. When we construct recursive bind mounts below this // guarantees that this directory will not be replicated anywhere. sc_do_mount("none", scratch_dir, NULL, MS_UNBINDABLE, NULL); // Recursively bind mount desired root filesystem directory over the // scratch directory. This puts the initial content into the scratch space // and serves as a foundation for all subsequent operations below. // // The mount is recursive because it can either be applied to the root // filesystem of a core system (aka all-snap) or the core snap on a classic // system. In the former case we need recursive bind mounts to accurately // replicate the state of the root filesystem into the scratch directory. sc_do_mount(config->rootfs_dir, scratch_dir, NULL, MS_REC | MS_BIND, NULL); // Make the scratch directory recursively private. Nothing done there will // be shared with any peer group, This effectively detaches us from the // original namespace and coupled with pivot_root below serves as the // foundation of the mount sandbox. sc_do_mount("none", scratch_dir, NULL, MS_REC | MS_SLAVE, NULL); // Bind mount certain directories from the host filesystem to the scratch // directory. By default mount events will propagate in both into and out // of the peer group. This way the running application can alter any global // state visible on the host and in other snaps. This can be restricted by // disabling the "is_bidirectional" flag as can be seen below. for (const struct sc_mount * mnt = config->mounts; mnt->path != NULL; mnt++) { if (mnt->is_bidirectional && mkdir(mnt->path, 0755) < 0 && errno != EEXIST) { die("cannot create %s", mnt->path); } sc_must_snprintf(dst, sizeof dst, "%s/%s", scratch_dir, mnt->path); if (mnt->is_optional) { bool ok = sc_do_optional_mount(mnt->path, dst, NULL, MS_REC | MS_BIND, NULL); if (!ok) { // If we cannot mount it, just continue. continue; } } else { sc_do_mount(mnt->path, dst, NULL, MS_REC | MS_BIND, NULL); } if (!mnt->is_bidirectional) { // Mount events will only propagate inwards to the namespace. This // way the running application cannot alter any global state apart // from that of its own snap. sc_do_mount("none", dst, NULL, MS_REC | MS_SLAVE, NULL); } if (mnt->altpath == NULL) { continue; } // An alternate path of mnt->path is provided at another location. // It should behave exactly the same as the original. sc_must_snprintf(dst, sizeof dst, "%s/%s", scratch_dir, mnt->altpath); struct stat stat_buf; if (lstat(dst, &stat_buf) < 0) { die("cannot lstat %s", dst); } if ((stat_buf.st_mode & S_IFMT) == S_IFLNK) { die("cannot bind mount alternate path over a symlink: %s", dst); } sc_do_mount(mnt->path, dst, NULL, MS_REC | MS_BIND, NULL); if (!mnt->is_bidirectional) { sc_do_mount("none", dst, NULL, MS_REC | MS_SLAVE, NULL); } } if (config->normal_mode) { // Since we mounted /etc from the host filesystem to the scratch directory, // we may need to put certain directories from the desired root filesystem // (e.g. the core snap) back. This way the behavior of running snaps is not // affected by the alternatives directory from the host, if one exists. // // Fixes the following bugs: // - https://bugs.launchpad.net/snap-confine/+bug/1580018 // - https://bugzilla.opensuse.org/show_bug.cgi?id=1028568 const char *dirs_from_core[] = { "/etc/alternatives", "/etc/ssl", "/etc/nsswitch.conf", NULL }; for (const char **dirs = dirs_from_core; *dirs != NULL; dirs++) { const char *dir = *dirs; struct stat buf; if (access(dir, F_OK) == 0) { sc_must_snprintf(src, sizeof src, "%s%s", config->rootfs_dir, dir); sc_must_snprintf(dst, sizeof dst, "%s%s", scratch_dir, dir); if (lstat(src, &buf) == 0 && lstat(dst, &buf) == 0) { sc_do_mount(src, dst, NULL, MS_BIND, NULL); sc_do_mount("none", dst, NULL, MS_SLAVE, NULL); } } } } // The "core" base snap is special as it contains snapd and friends. // Other base snaps do not, so whenever a base snap other than core is // in use we need extra provisions for setting up internal tooling to // be available. // // However on a core18 (and similar) system the core snap is not // a special base anymore and we should map our own tooling in. if (config->distro == SC_DISTRO_CORE_OTHER || !sc_streq(config->base_snap_name, "core")) { // when bases are used we need to bind-mount the libexecdir // (that contains snap-exec) into /usr/lib/snapd of the // base snap so that snap-exec is available for the snaps // (base snaps do not ship snapd) // dst is always /usr/lib/snapd as this is where snapd // assumes to find snap-exec sc_must_snprintf(dst, sizeof dst, "%s/usr/lib/snapd", scratch_dir); // bind mount the current $ROOT/usr/lib/snapd path, // where $ROOT is either "/" or the "/snap/{core,snapd}/current" // that we are re-execing from char *src = NULL; char self[PATH_MAX + 1] = { 0 }; if (readlink("/proc/self/exe", self, sizeof(self) - 1) < 0) { die("cannot read /proc/self/exe"); } // this cannot happen except when the kernel is buggy if (strstr(self, "/snap-confine") == NULL) { die("cannot use result from readlink: %s", self); } src = dirname(self); // dirname(path) might return '.' depending on path. // /proc/self/exe should always point // to an absolute path, but let's guarantee that. if (src[0] != '/') { die("cannot use the result of dirname(): %s", src); } sc_do_mount(src, dst, NULL, MS_BIND | MS_RDONLY, NULL); sc_do_mount("none", dst, NULL, MS_SLAVE, NULL); } // Bind mount the directory where all snaps are mounted. The location of // the this directory on the host filesystem may not match the location in // the desired root filesystem. In the "core" and "ubuntu-core" snaps the // directory is always /snap. On the host it is a build-time configuration // option stored in SNAP_MOUNT_DIR. sc_must_snprintf(dst, sizeof dst, "%s/snap", scratch_dir); sc_do_mount(SNAP_MOUNT_DIR, dst, NULL, MS_BIND | MS_REC | MS_SLAVE, NULL); sc_do_mount("none", dst, NULL, MS_REC | MS_SLAVE, NULL); // Create the hostfs directory if one is missing. This directory is a part // of packaging now so perhaps this code can be removed later. if (access(SC_HOSTFS_DIR, F_OK) != 0) { debug("creating missing hostfs directory"); if (mkdir(SC_HOSTFS_DIR, 0755) != 0) { die("cannot perform operation: mkdir %s", SC_HOSTFS_DIR); } } // Ensure that hostfs isgroup owned by root. We may have (now or earlier) // created the directory as the user who first ran a snap on a given // system and the group identity of that user is visilbe on disk. // This was LP:#1665004 struct stat sb; if (stat(SC_HOSTFS_DIR, &sb) < 0) { die("cannot stat %s", SC_HOSTFS_DIR); } if (sb.st_uid != 0 || sb.st_gid != 0) { if (chown(SC_HOSTFS_DIR, 0, 0) < 0) { die("cannot change user/group owner of %s to root", SC_HOSTFS_DIR); } } // Make the upcoming "put_old" directory for pivot_root private so that // mount events don't propagate to any peer group. In practice pivot root // has a number of undocumented requirements and one of them is that the // "put_old" directory (the second argument) cannot be shared in any way. sc_must_snprintf(dst, sizeof dst, "%s/%s", scratch_dir, SC_HOSTFS_DIR); sc_do_mount(dst, dst, NULL, MS_BIND, NULL); sc_do_mount("none", dst, NULL, MS_PRIVATE, NULL); // On classic mount the nvidia driver. Ideally this would be done in an // uniform way after pivot_root but this is good enough and requires less // code changes the nvidia code assumes it has access to the existing // pre-pivot filesystem. if (config->distro == SC_DISTRO_CLASSIC) { sc_mount_nvidia_driver(scratch_dir); } // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX // pivot_root // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX // Use pivot_root to "chroot" into the scratch directory. // // Q: Why are we using something as esoteric as pivot_root(2)? // A: Because this makes apparmor handling easy. Using a normal chroot // makes all apparmor rules conditional. We are either running on an // all-snap system where this would-be chroot didn't happen and all the // rules see / as the root file system _OR_ we are running on top of a // classic distribution and this chroot has now moved all paths to // /tmp/snap.rootfs_*. // // Because we are using unshare(2) with CLONE_NEWNS we can essentially use // pivot_root just like chroot but this makes apparmor unaware of the old // root so everything works okay. // // HINT: If you are debugging this and are trying to see why pivot_root // happens to return EINVAL with any changes you may be making, please // consider applying // misc/0001-Add-printk-based-debugging-to-pivot_root.patch to your tree // kernel. debug("performing operation: pivot_root %s %s", scratch_dir, dst); if (syscall(SYS_pivot_root, scratch_dir, dst) < 0) { die("cannot perform operation: pivot_root %s %s", scratch_dir, dst); } // Unmount the self-bind mount over the scratch directory created earlier // in the original root filesystem (which is now mounted on SC_HOSTFS_DIR). // This way we can remove the temporary directory we created and "clean up" // after ourselves nicely. sc_must_snprintf(dst, sizeof dst, "%s/%s", SC_HOSTFS_DIR, scratch_dir); sc_do_umount(dst, 0); // Remove the scratch directory. Note that we are using the path that is // based on the old root filesystem as after pivot_root we cannot guarantee // what is present at the same location normally. (It is probably an empty // /tmp directory that is populated in another place). debug("performing operation: rmdir %s", dst); if (rmdir(scratch_dir) < 0) { die("cannot perform operation: rmdir %s", dst); }; // Make the old root filesystem recursively slave. This way operations // performed in this mount namespace will not propagate to the peer group. // This is another essential part of the confinement system. sc_do_mount("none", SC_HOSTFS_DIR, NULL, MS_REC | MS_SLAVE, NULL); // Detach the redundant hostfs version of sysfs since it shows up in the // mount table and software inspecting the mount table may become confused // (eg, docker and LP:# 162601). sc_must_snprintf(src, sizeof src, "%s/sys", SC_HOSTFS_DIR); sc_do_umount(src, UMOUNT_NOFOLLOW | MNT_DETACH); // Detach the redundant hostfs version of /dev since it shows up in the // mount table and software inspecting the mount table may become confused. sc_must_snprintf(src, sizeof src, "%s/dev", SC_HOSTFS_DIR); sc_do_umount(src, UMOUNT_NOFOLLOW | MNT_DETACH); // Detach the redundant hostfs version of /proc since it shows up in the // mount table and software inspecting the mount table may become confused. sc_must_snprintf(src, sizeof src, "%s/proc", SC_HOSTFS_DIR); sc_do_umount(src, UMOUNT_NOFOLLOW | MNT_DETACH); } /** * @path: a pathname where / replaced with '\0'. * @offsetp: pointer to int showing which path segment was last seen. * Updated on return to reflect the next segment. * @fulllen: full original path length. * Returns a pointer to the next path segment, or NULL if done. */ static char * __attribute__ ((used)) get_nextpath(char *path, size_t * offsetp, size_t fulllen) { size_t offset = *offsetp; if (offset >= fulllen) return NULL; while (offset < fulllen && path[offset] != '\0') offset++; while (offset < fulllen && path[offset] == '\0') offset++; *offsetp = offset; return (offset < fulllen) ? &path[offset] : NULL; } /** * Check that @subdir is a subdir of @dir. **/ static bool __attribute__ ((used)) is_subdir(const char *subdir, const char *dir) { size_t dirlen = strlen(dir); size_t subdirlen = strlen(subdir); // @dir has to be at least as long as @subdir if (subdirlen < dirlen) return false; // @dir has to be a prefix of @subdir if (strncmp(subdir, dir, dirlen) != 0) return false; // @dir can look like "path/" (that is, end with the directory separator). // When that is the case then given the test above we can be sure @subdir // is a real subdirectory. if (dirlen > 0 && dir[dirlen - 1] == '/') return true; // @subdir can look like "path/stuff" and when the directory separator // is exactly at the spot where @dir ends (that is, it was not caught // by the test above) then @subdir is a real subdirectory. if (subdir[dirlen] == '/' && dirlen > 0) return true; // If both @dir and @subdir have identical length then given that the // prefix check above @subdir is a real subdirectory. if (subdirlen == dirlen) return true; return false; } void sc_populate_mount_ns(struct sc_apparmor *apparmor, int snap_update_ns_fd, const char *base_snap_name, const char *snap_name) { // Get the current working directory before we start fiddling with // mounts and possibly pivot_root. At the end of the whole process, we // will try to re-locate to the same directory (if possible). char *vanilla_cwd SC_CLEANUP(sc_cleanup_string) = NULL; vanilla_cwd = get_current_dir_name(); if (vanilla_cwd == NULL) { die("cannot get the current working directory"); } // Classify the current distribution, as claimed by /etc/os-release. sc_distro distro = sc_classify_distro(); // Check which mode we should run in, normal or legacy. if (sc_should_use_normal_mode(distro, base_snap_name)) { // In normal mode we use the base snap as / and set up several bind mounts. const struct sc_mount mounts[] = { {"/dev"}, // because it contains devices on host OS {"/etc"}, // because that's where /etc/resolv.conf lives, perhaps a bad idea {"/home"}, // to support /home/*/snap and home interface {"/root"}, // because that is $HOME for services {"/proc"}, // fundamental filesystem {"/sys"}, // fundamental filesystem {"/tmp"}, // to get writable tmp {"/var/snap"}, // to get access to global snap data {"/var/lib/snapd"}, // to get access to snapd state and seccomp profiles {"/var/tmp"}, // to get access to the other temporary directory {"/run"}, // to get /run with sockets and what not {"/lib/modules",.is_optional = true}, // access to the modules of the running kernel {"/usr/src"}, // FIXME: move to SecurityMounts in system-trace interface {"/var/log"}, // FIXME: move to SecurityMounts in log-observe interface #ifdef MERGED_USR {"/run/media", true, "/media"}, // access to the users removable devices #else {"/media", true}, // access to the users removable devices #endif // MERGED_USR {"/run/netns", true}, // access to the 'ip netns' network namespaces // The /mnt directory is optional in base snaps to ensure backwards // compatibility with the first version of base snaps that was // released. {"/mnt",.is_optional = true}, // to support the removable-media interface {"/var/lib/extrausers",.is_optional = true}, // access to UID/GID of extrausers (if available) {}, }; char rootfs_dir[PATH_MAX] = { 0 }; sc_must_snprintf(rootfs_dir, sizeof rootfs_dir, "%s/%s/current/", SNAP_MOUNT_DIR, base_snap_name); if (access(rootfs_dir, F_OK) != 0) { if (sc_streq(base_snap_name, "core")) { // As a special fallback, allow the // base snap to degrade from "core" to // "ubuntu-core". This is needed for // the migration tests. base_snap_name = "ubuntu-core"; sc_must_snprintf(rootfs_dir, sizeof rootfs_dir, "%s/%s/current/", SNAP_MOUNT_DIR, base_snap_name); if (access(rootfs_dir, F_OK) != 0) { die("cannot locate the core or legacy core snap (current symlink missing?)"); } } // If after the special case handling above we are // still not ok, die if (access(rootfs_dir, F_OK) != 0) die("cannot locate the base snap: %s", base_snap_name); } struct sc_mount_config normal_config = { .rootfs_dir = rootfs_dir, .mounts = mounts, .distro = distro, .normal_mode = true, .base_snap_name = base_snap_name, }; sc_bootstrap_mount_namespace(&normal_config); } else { // In legacy mode we don't pivot and instead just arrange bi- // directional mount propagation for two directories. const struct sc_mount mounts[] = { {"/media", true}, {"/run/netns", true}, {}, }; struct sc_mount_config legacy_config = { .rootfs_dir = "/", .mounts = mounts, .distro = distro, .normal_mode = false, .base_snap_name = base_snap_name, }; sc_bootstrap_mount_namespace(&legacy_config); } // set up private mounts // TODO: rename this and fold it into bootstrap setup_private_mount(snap_name); // set up private /dev/pts // TODO: fold this into bootstrap setup_private_pts(); // setup the security backend bind mounts sc_call_snap_update_ns(snap_update_ns_fd, snap_name, apparmor); // Try to re-locate back to vanilla working directory. This can fail // because that directory is no longer present. if (chdir(vanilla_cwd) != 0) { debug("cannot remain in %s, moving to the void directory", vanilla_cwd); if (chdir(SC_VOID_DIR) != 0) { die("cannot change directory to %s", SC_VOID_DIR); } debug("successfully moved to %s", SC_VOID_DIR); } } static bool is_mounted_with_shared_option(const char *dir) __attribute__ ((nonnull(1))); static bool is_mounted_with_shared_option(const char *dir) { struct sc_mountinfo *sm SC_CLEANUP(sc_cleanup_mountinfo) = NULL; sm = sc_parse_mountinfo(NULL); if (sm == NULL) { die("cannot parse /proc/self/mountinfo"); } struct sc_mountinfo_entry *entry = sc_first_mountinfo_entry(sm); while (entry != NULL) { const char *mount_dir = entry->mount_dir; if (sc_streq(mount_dir, dir)) { const char *optional_fields = entry->optional_fields; if (strstr(optional_fields, "shared:") != NULL) { return true; } } entry = sc_next_mountinfo_entry(entry); } return false; } void sc_ensure_shared_snap_mount(void) { if (!is_mounted_with_shared_option("/") && !is_mounted_with_shared_option(SNAP_MOUNT_DIR)) { // TODO: We could be more aggressive and refuse to function but since // we have no data on actual environments that happen to limp along in // this configuration let's not do that yet. This code should be // removed once we have a measurement and feedback mechanism that lets // us decide based on measurable data. sc_do_mount(SNAP_MOUNT_DIR, SNAP_MOUNT_DIR, "none", MS_BIND | MS_REC, 0); sc_do_mount("none", SNAP_MOUNT_DIR, NULL, MS_SHARED | MS_REC, NULL); } } static void sc_make_slave_mount_ns(void) { if (unshare(CLONE_NEWNS) < 0) { die("can not unshare mount namespace"); } // In our new mount namespace, recursively change all mounts // to slave mode, so we see changes from the parent namespace // but don't propagate our own changes. sc_do_mount("none", "/", NULL, MS_REC | MS_SLAVE, NULL); } void sc_setup_user_mounts(struct sc_apparmor *apparmor, int snap_update_ns_fd, const char *snap_name) { debug("%s: %s", __FUNCTION__, snap_name); char profile_path[PATH_MAX]; struct stat st; sc_must_snprintf(profile_path, sizeof(profile_path), "/var/lib/snapd/mount/snap.%s.user-fstab", snap_name); if (stat(profile_path, &st) != 0) { // It is ok for the user fstab to not exist. return; } sc_make_slave_mount_ns(); sc_call_snap_update_ns_as_user(snap_update_ns_fd, snap_name, apparmor); }
./CrossVul/dataset_final_sorted/CWE-59/c/good_825_0
crossvul-cpp_data_bad_2241_0
/* * linux/fs/namei.c * * Copyright (C) 1991, 1992 Linus Torvalds */ /* * Some corrections by tytso. */ /* [Feb 1997 T. Schoebel-Theuer] Complete rewrite of the pathname * lookup logic. */ /* [Feb-Apr 2000, AV] Rewrite to the new namespace architecture. */ #include <linux/init.h> #include <linux/export.h> #include <linux/kernel.h> #include <linux/slab.h> #include <linux/fs.h> #include <linux/namei.h> #include <linux/pagemap.h> #include <linux/fsnotify.h> #include <linux/personality.h> #include <linux/security.h> #include <linux/ima.h> #include <linux/syscalls.h> #include <linux/mount.h> #include <linux/audit.h> #include <linux/capability.h> #include <linux/file.h> #include <linux/fcntl.h> #include <linux/device_cgroup.h> #include <linux/fs_struct.h> #include <linux/posix_acl.h> #include <asm/uaccess.h> #include "internal.h" #include "mount.h" /* [Feb-1997 T. Schoebel-Theuer] * Fundamental changes in the pathname lookup mechanisms (namei) * were necessary because of omirr. The reason is that omirr needs * to know the _real_ pathname, not the user-supplied one, in case * of symlinks (and also when transname replacements occur). * * The new code replaces the old recursive symlink resolution with * an iterative one (in case of non-nested symlink chains). It does * this with calls to <fs>_follow_link(). * As a side effect, dir_namei(), _namei() and follow_link() are now * replaced with a single function lookup_dentry() that can handle all * the special cases of the former code. * * With the new dcache, the pathname is stored at each inode, at least as * long as the refcount of the inode is positive. As a side effect, the * size of the dcache depends on the inode cache and thus is dynamic. * * [29-Apr-1998 C. Scott Ananian] Updated above description of symlink * resolution to correspond with current state of the code. * * Note that the symlink resolution is not *completely* iterative. * There is still a significant amount of tail- and mid- recursion in * the algorithm. Also, note that <fs>_readlink() is not used in * lookup_dentry(): lookup_dentry() on the result of <fs>_readlink() * may return different results than <fs>_follow_link(). Many virtual * filesystems (including /proc) exhibit this behavior. */ /* [24-Feb-97 T. Schoebel-Theuer] Side effects caused by new implementation: * New symlink semantics: when open() is called with flags O_CREAT | O_EXCL * and the name already exists in form of a symlink, try to create the new * name indicated by the symlink. The old code always complained that the * name already exists, due to not following the symlink even if its target * is nonexistent. The new semantics affects also mknod() and link() when * the name is a symlink pointing to a non-existent name. * * I don't know which semantics is the right one, since I have no access * to standards. But I found by trial that HP-UX 9.0 has the full "new" * semantics implemented, while SunOS 4.1.1 and Solaris (SunOS 5.4) have the * "old" one. Personally, I think the new semantics is much more logical. * Note that "ln old new" where "new" is a symlink pointing to a non-existing * file does succeed in both HP-UX and SunOs, but not in Solaris * and in the old Linux semantics. */ /* [16-Dec-97 Kevin Buhr] For security reasons, we change some symlink * semantics. See the comments in "open_namei" and "do_link" below. * * [10-Sep-98 Alan Modra] Another symlink change. */ /* [Feb-Apr 2000 AV] Complete rewrite. Rules for symlinks: * inside the path - always follow. * in the last component in creation/removal/renaming - never follow. * if LOOKUP_FOLLOW passed - follow. * if the pathname has trailing slashes - follow. * otherwise - don't follow. * (applied in that order). * * [Jun 2000 AV] Inconsistent behaviour of open() in case if flags==O_CREAT * restored for 2.4. This is the last surviving part of old 4.2BSD bug. * During the 2.4 we need to fix the userland stuff depending on it - * hopefully we will be able to get rid of that wart in 2.5. So far only * XEmacs seems to be relying on it... */ /* * [Sep 2001 AV] Single-semaphore locking scheme (kudos to David Holland) * implemented. Let's see if raised priority of ->s_vfs_rename_mutex gives * any extra contention... */ /* In order to reduce some races, while at the same time doing additional * checking and hopefully speeding things up, we copy filenames to the * kernel data space before using them.. * * POSIX.1 2.4: an empty pathname is invalid (ENOENT). * PATH_MAX includes the nul terminator --RR. */ void final_putname(struct filename *name) { if (name->separate) { __putname(name->name); kfree(name); } else { __putname(name); } } #define EMBEDDED_NAME_MAX (PATH_MAX - sizeof(struct filename)) static struct filename * getname_flags(const char __user *filename, int flags, int *empty) { struct filename *result, *err; int len; long max; char *kname; result = audit_reusename(filename); if (result) return result; result = __getname(); if (unlikely(!result)) return ERR_PTR(-ENOMEM); /* * First, try to embed the struct filename inside the names_cache * allocation */ kname = (char *)result + sizeof(*result); result->name = kname; result->separate = false; max = EMBEDDED_NAME_MAX; recopy: len = strncpy_from_user(kname, filename, max); if (unlikely(len < 0)) { err = ERR_PTR(len); goto error; } /* * Uh-oh. We have a name that's approaching PATH_MAX. Allocate a * separate struct filename so we can dedicate the entire * names_cache allocation for the pathname, and re-do the copy from * userland. */ if (len == EMBEDDED_NAME_MAX && max == EMBEDDED_NAME_MAX) { kname = (char *)result; result = kzalloc(sizeof(*result), GFP_KERNEL); if (!result) { err = ERR_PTR(-ENOMEM); result = (struct filename *)kname; goto error; } result->name = kname; result->separate = true; max = PATH_MAX; goto recopy; } /* The empty path is special. */ if (unlikely(!len)) { if (empty) *empty = 1; err = ERR_PTR(-ENOENT); if (!(flags & LOOKUP_EMPTY)) goto error; } err = ERR_PTR(-ENAMETOOLONG); if (unlikely(len >= PATH_MAX)) goto error; result->uptr = filename; result->aname = NULL; audit_getname(result); return result; error: final_putname(result); return err; } struct filename * getname(const char __user * filename) { return getname_flags(filename, 0, NULL); } /* * The "getname_kernel()" interface doesn't do pathnames longer * than EMBEDDED_NAME_MAX. Deal with it - you're a kernel user. */ struct filename * getname_kernel(const char * filename) { struct filename *result; char *kname; int len; len = strlen(filename); if (len >= EMBEDDED_NAME_MAX) return ERR_PTR(-ENAMETOOLONG); result = __getname(); if (unlikely(!result)) return ERR_PTR(-ENOMEM); kname = (char *)result + sizeof(*result); result->name = kname; result->uptr = NULL; result->aname = NULL; result->separate = false; strlcpy(kname, filename, EMBEDDED_NAME_MAX); return result; } #ifdef CONFIG_AUDITSYSCALL void putname(struct filename *name) { if (unlikely(!audit_dummy_context())) return audit_putname(name); final_putname(name); } #endif static int check_acl(struct inode *inode, int mask) { #ifdef CONFIG_FS_POSIX_ACL struct posix_acl *acl; if (mask & MAY_NOT_BLOCK) { acl = get_cached_acl_rcu(inode, ACL_TYPE_ACCESS); if (!acl) return -EAGAIN; /* no ->get_acl() calls in RCU mode... */ if (acl == ACL_NOT_CACHED) return -ECHILD; return posix_acl_permission(inode, acl, mask & ~MAY_NOT_BLOCK); } acl = get_acl(inode, ACL_TYPE_ACCESS); if (IS_ERR(acl)) return PTR_ERR(acl); if (acl) { int error = posix_acl_permission(inode, acl, mask); posix_acl_release(acl); return error; } #endif return -EAGAIN; } /* * This does the basic permission checking */ static int acl_permission_check(struct inode *inode, int mask) { unsigned int mode = inode->i_mode; if (likely(uid_eq(current_fsuid(), inode->i_uid))) mode >>= 6; else { if (IS_POSIXACL(inode) && (mode & S_IRWXG)) { int error = check_acl(inode, mask); if (error != -EAGAIN) return error; } if (in_group_p(inode->i_gid)) mode >>= 3; } /* * If the DACs are ok we don't need any capability check. */ if ((mask & ~mode & (MAY_READ | MAY_WRITE | MAY_EXEC)) == 0) return 0; return -EACCES; } /** * generic_permission - check for access rights on a Posix-like filesystem * @inode: inode to check access rights for * @mask: right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC, ...) * * Used to check for read/write/execute permissions on a file. * We use "fsuid" for this, letting us set arbitrary permissions * for filesystem access without changing the "normal" uids which * are used for other things. * * generic_permission is rcu-walk aware. It returns -ECHILD in case an rcu-walk * request cannot be satisfied (eg. requires blocking or too much complexity). * It would then be called again in ref-walk mode. */ int generic_permission(struct inode *inode, int mask) { int ret; /* * Do the basic permission checks. */ ret = acl_permission_check(inode, mask); if (ret != -EACCES) return ret; if (S_ISDIR(inode->i_mode)) { /* DACs are overridable for directories */ if (capable_wrt_inode_uidgid(inode, CAP_DAC_OVERRIDE)) return 0; if (!(mask & MAY_WRITE)) if (capable_wrt_inode_uidgid(inode, CAP_DAC_READ_SEARCH)) return 0; return -EACCES; } /* * Read/write DACs are always overridable. * Executable DACs are overridable when there is * at least one exec bit set. */ if (!(mask & MAY_EXEC) || (inode->i_mode & S_IXUGO)) if (capable_wrt_inode_uidgid(inode, CAP_DAC_OVERRIDE)) return 0; /* * Searching includes executable on directories, else just read. */ mask &= MAY_READ | MAY_WRITE | MAY_EXEC; if (mask == MAY_READ) if (capable_wrt_inode_uidgid(inode, CAP_DAC_READ_SEARCH)) return 0; return -EACCES; } EXPORT_SYMBOL(generic_permission); /* * We _really_ want to just do "generic_permission()" without * even looking at the inode->i_op values. So we keep a cache * flag in inode->i_opflags, that says "this has not special * permission function, use the fast case". */ static inline int do_inode_permission(struct inode *inode, int mask) { if (unlikely(!(inode->i_opflags & IOP_FASTPERM))) { if (likely(inode->i_op->permission)) return inode->i_op->permission(inode, mask); /* This gets set once for the inode lifetime */ spin_lock(&inode->i_lock); inode->i_opflags |= IOP_FASTPERM; spin_unlock(&inode->i_lock); } return generic_permission(inode, mask); } /** * __inode_permission - Check for access rights to a given inode * @inode: Inode to check permission on * @mask: Right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC) * * Check for read/write/execute permissions on an inode. * * When checking for MAY_APPEND, MAY_WRITE must also be set in @mask. * * This does not check for a read-only file system. You probably want * inode_permission(). */ int __inode_permission(struct inode *inode, int mask) { int retval; if (unlikely(mask & MAY_WRITE)) { /* * Nobody gets write access to an immutable file. */ if (IS_IMMUTABLE(inode)) return -EACCES; } retval = do_inode_permission(inode, mask); if (retval) return retval; retval = devcgroup_inode_permission(inode, mask); if (retval) return retval; return security_inode_permission(inode, mask); } /** * sb_permission - Check superblock-level permissions * @sb: Superblock of inode to check permission on * @inode: Inode to check permission on * @mask: Right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC) * * Separate out file-system wide checks from inode-specific permission checks. */ static int sb_permission(struct super_block *sb, struct inode *inode, int mask) { if (unlikely(mask & MAY_WRITE)) { umode_t mode = inode->i_mode; /* Nobody gets write access to a read-only fs. */ if ((sb->s_flags & MS_RDONLY) && (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) return -EROFS; } return 0; } /** * inode_permission - Check for access rights to a given inode * @inode: Inode to check permission on * @mask: Right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC) * * Check for read/write/execute permissions on an inode. We use fs[ug]id for * this, letting us set arbitrary permissions for filesystem access without * changing the "normal" UIDs which are used for other things. * * When checking for MAY_APPEND, MAY_WRITE must also be set in @mask. */ int inode_permission(struct inode *inode, int mask) { int retval; retval = sb_permission(inode->i_sb, inode, mask); if (retval) return retval; return __inode_permission(inode, mask); } EXPORT_SYMBOL(inode_permission); /** * path_get - get a reference to a path * @path: path to get the reference to * * Given a path increment the reference count to the dentry and the vfsmount. */ void path_get(const struct path *path) { mntget(path->mnt); dget(path->dentry); } EXPORT_SYMBOL(path_get); /** * path_put - put a reference to a path * @path: path to put the reference to * * Given a path decrement the reference count to the dentry and the vfsmount. */ void path_put(const struct path *path) { dput(path->dentry); mntput(path->mnt); } EXPORT_SYMBOL(path_put); /* * Path walking has 2 modes, rcu-walk and ref-walk (see * Documentation/filesystems/path-lookup.txt). In situations when we can't * continue in RCU mode, we attempt to drop out of rcu-walk mode and grab * normal reference counts on dentries and vfsmounts to transition to rcu-walk * mode. Refcounts are grabbed at the last known good point before rcu-walk * got stuck, so ref-walk may continue from there. If this is not successful * (eg. a seqcount has changed), then failure is returned and it's up to caller * to restart the path walk from the beginning in ref-walk mode. */ /** * unlazy_walk - try to switch to ref-walk mode. * @nd: nameidata pathwalk data * @dentry: child of nd->path.dentry or NULL * Returns: 0 on success, -ECHILD on failure * * unlazy_walk attempts to legitimize the current nd->path, nd->root and dentry * for ref-walk mode. @dentry must be a path found by a do_lookup call on * @nd or NULL. Must be called from rcu-walk context. */ static int unlazy_walk(struct nameidata *nd, struct dentry *dentry) { struct fs_struct *fs = current->fs; struct dentry *parent = nd->path.dentry; BUG_ON(!(nd->flags & LOOKUP_RCU)); /* * After legitimizing the bastards, terminate_walk() * will do the right thing for non-RCU mode, and all our * subsequent exit cases should rcu_read_unlock() * before returning. Do vfsmount first; if dentry * can't be legitimized, just set nd->path.dentry to NULL * and rely on dput(NULL) being a no-op. */ if (!legitimize_mnt(nd->path.mnt, nd->m_seq)) return -ECHILD; nd->flags &= ~LOOKUP_RCU; if (!lockref_get_not_dead(&parent->d_lockref)) { nd->path.dentry = NULL; goto out; } /* * For a negative lookup, the lookup sequence point is the parents * sequence point, and it only needs to revalidate the parent dentry. * * For a positive lookup, we need to move both the parent and the * dentry from the RCU domain to be properly refcounted. And the * sequence number in the dentry validates *both* dentry counters, * since we checked the sequence number of the parent after we got * the child sequence number. So we know the parent must still * be valid if the child sequence number is still valid. */ if (!dentry) { if (read_seqcount_retry(&parent->d_seq, nd->seq)) goto out; BUG_ON(nd->inode != parent->d_inode); } else { if (!lockref_get_not_dead(&dentry->d_lockref)) goto out; if (read_seqcount_retry(&dentry->d_seq, nd->seq)) goto drop_dentry; } /* * Sequence counts matched. Now make sure that the root is * still valid and get it if required. */ if (nd->root.mnt && !(nd->flags & LOOKUP_ROOT)) { spin_lock(&fs->lock); if (nd->root.mnt != fs->root.mnt || nd->root.dentry != fs->root.dentry) goto unlock_and_drop_dentry; path_get(&nd->root); spin_unlock(&fs->lock); } rcu_read_unlock(); return 0; unlock_and_drop_dentry: spin_unlock(&fs->lock); drop_dentry: rcu_read_unlock(); dput(dentry); goto drop_root_mnt; out: rcu_read_unlock(); drop_root_mnt: if (!(nd->flags & LOOKUP_ROOT)) nd->root.mnt = NULL; return -ECHILD; } static inline int d_revalidate(struct dentry *dentry, unsigned int flags) { return dentry->d_op->d_revalidate(dentry, flags); } /** * complete_walk - successful completion of path walk * @nd: pointer nameidata * * If we had been in RCU mode, drop out of it and legitimize nd->path. * Revalidate the final result, unless we'd already done that during * the path walk or the filesystem doesn't ask for it. Return 0 on * success, -error on failure. In case of failure caller does not * need to drop nd->path. */ static int complete_walk(struct nameidata *nd) { struct dentry *dentry = nd->path.dentry; int status; if (nd->flags & LOOKUP_RCU) { nd->flags &= ~LOOKUP_RCU; if (!(nd->flags & LOOKUP_ROOT)) nd->root.mnt = NULL; if (!legitimize_mnt(nd->path.mnt, nd->m_seq)) { rcu_read_unlock(); return -ECHILD; } if (unlikely(!lockref_get_not_dead(&dentry->d_lockref))) { rcu_read_unlock(); mntput(nd->path.mnt); return -ECHILD; } if (read_seqcount_retry(&dentry->d_seq, nd->seq)) { rcu_read_unlock(); dput(dentry); mntput(nd->path.mnt); return -ECHILD; } rcu_read_unlock(); } if (likely(!(nd->flags & LOOKUP_JUMPED))) return 0; if (likely(!(dentry->d_flags & DCACHE_OP_WEAK_REVALIDATE))) return 0; status = dentry->d_op->d_weak_revalidate(dentry, nd->flags); if (status > 0) return 0; if (!status) status = -ESTALE; path_put(&nd->path); return status; } static __always_inline void set_root(struct nameidata *nd) { if (!nd->root.mnt) get_fs_root(current->fs, &nd->root); } static int link_path_walk(const char *, struct nameidata *); static __always_inline void set_root_rcu(struct nameidata *nd) { if (!nd->root.mnt) { struct fs_struct *fs = current->fs; unsigned seq; do { seq = read_seqcount_begin(&fs->seq); nd->root = fs->root; nd->seq = __read_seqcount_begin(&nd->root.dentry->d_seq); } while (read_seqcount_retry(&fs->seq, seq)); } } static void path_put_conditional(struct path *path, struct nameidata *nd) { dput(path->dentry); if (path->mnt != nd->path.mnt) mntput(path->mnt); } static inline void path_to_nameidata(const struct path *path, struct nameidata *nd) { if (!(nd->flags & LOOKUP_RCU)) { dput(nd->path.dentry); if (nd->path.mnt != path->mnt) mntput(nd->path.mnt); } nd->path.mnt = path->mnt; nd->path.dentry = path->dentry; } /* * Helper to directly jump to a known parsed path from ->follow_link, * caller must have taken a reference to path beforehand. */ void nd_jump_link(struct nameidata *nd, struct path *path) { path_put(&nd->path); nd->path = *path; nd->inode = nd->path.dentry->d_inode; nd->flags |= LOOKUP_JUMPED; } static inline void put_link(struct nameidata *nd, struct path *link, void *cookie) { struct inode *inode = link->dentry->d_inode; if (inode->i_op->put_link) inode->i_op->put_link(link->dentry, nd, cookie); path_put(link); } int sysctl_protected_symlinks __read_mostly = 0; int sysctl_protected_hardlinks __read_mostly = 0; /** * may_follow_link - Check symlink following for unsafe situations * @link: The path of the symlink * @nd: nameidata pathwalk data * * In the case of the sysctl_protected_symlinks sysctl being enabled, * CAP_DAC_OVERRIDE needs to be specifically ignored if the symlink is * in a sticky world-writable directory. This is to protect privileged * processes from failing races against path names that may change out * from under them by way of other users creating malicious symlinks. * It will permit symlinks to be followed only when outside a sticky * world-writable directory, or when the uid of the symlink and follower * match, or when the directory owner matches the symlink's owner. * * Returns 0 if following the symlink is allowed, -ve on error. */ static inline int may_follow_link(struct path *link, struct nameidata *nd) { const struct inode *inode; const struct inode *parent; if (!sysctl_protected_symlinks) return 0; /* Allowed if owner and follower match. */ inode = link->dentry->d_inode; if (uid_eq(current_cred()->fsuid, inode->i_uid)) return 0; /* Allowed if parent directory not sticky and world-writable. */ parent = nd->path.dentry->d_inode; if ((parent->i_mode & (S_ISVTX|S_IWOTH)) != (S_ISVTX|S_IWOTH)) return 0; /* Allowed if parent directory and link owner match. */ if (uid_eq(parent->i_uid, inode->i_uid)) return 0; audit_log_link_denied("follow_link", link); path_put_conditional(link, nd); path_put(&nd->path); return -EACCES; } /** * safe_hardlink_source - Check for safe hardlink conditions * @inode: the source inode to hardlink from * * Return false if at least one of the following conditions: * - inode is not a regular file * - inode is setuid * - inode is setgid and group-exec * - access failure for read and write * * Otherwise returns true. */ static bool safe_hardlink_source(struct inode *inode) { umode_t mode = inode->i_mode; /* Special files should not get pinned to the filesystem. */ if (!S_ISREG(mode)) return false; /* Setuid files should not get pinned to the filesystem. */ if (mode & S_ISUID) return false; /* Executable setgid files should not get pinned to the filesystem. */ if ((mode & (S_ISGID | S_IXGRP)) == (S_ISGID | S_IXGRP)) return false; /* Hardlinking to unreadable or unwritable sources is dangerous. */ if (inode_permission(inode, MAY_READ | MAY_WRITE)) return false; return true; } /** * may_linkat - Check permissions for creating a hardlink * @link: the source to hardlink from * * Block hardlink when all of: * - sysctl_protected_hardlinks enabled * - fsuid does not match inode * - hardlink source is unsafe (see safe_hardlink_source() above) * - not CAP_FOWNER * * Returns 0 if successful, -ve on error. */ static int may_linkat(struct path *link) { const struct cred *cred; struct inode *inode; if (!sysctl_protected_hardlinks) return 0; cred = current_cred(); inode = link->dentry->d_inode; /* Source inode owner (or CAP_FOWNER) can hardlink all they like, * otherwise, it must be a safe source. */ if (uid_eq(cred->fsuid, inode->i_uid) || safe_hardlink_source(inode) || capable(CAP_FOWNER)) return 0; audit_log_link_denied("linkat", link); return -EPERM; } static __always_inline int follow_link(struct path *link, struct nameidata *nd, void **p) { struct dentry *dentry = link->dentry; int error; char *s; BUG_ON(nd->flags & LOOKUP_RCU); if (link->mnt == nd->path.mnt) mntget(link->mnt); error = -ELOOP; if (unlikely(current->total_link_count >= 40)) goto out_put_nd_path; cond_resched(); current->total_link_count++; touch_atime(link); nd_set_link(nd, NULL); error = security_inode_follow_link(link->dentry, nd); if (error) goto out_put_nd_path; nd->last_type = LAST_BIND; *p = dentry->d_inode->i_op->follow_link(dentry, nd); error = PTR_ERR(*p); if (IS_ERR(*p)) goto out_put_nd_path; error = 0; s = nd_get_link(nd); if (s) { if (unlikely(IS_ERR(s))) { path_put(&nd->path); put_link(nd, link, *p); return PTR_ERR(s); } if (*s == '/') { set_root(nd); path_put(&nd->path); nd->path = nd->root; path_get(&nd->root); nd->flags |= LOOKUP_JUMPED; } nd->inode = nd->path.dentry->d_inode; error = link_path_walk(s, nd); if (unlikely(error)) put_link(nd, link, *p); } return error; out_put_nd_path: *p = NULL; path_put(&nd->path); path_put(link); return error; } static int follow_up_rcu(struct path *path) { struct mount *mnt = real_mount(path->mnt); struct mount *parent; struct dentry *mountpoint; parent = mnt->mnt_parent; if (&parent->mnt == path->mnt) return 0; mountpoint = mnt->mnt_mountpoint; path->dentry = mountpoint; path->mnt = &parent->mnt; return 1; } /* * follow_up - Find the mountpoint of path's vfsmount * * Given a path, find the mountpoint of its source file system. * Replace @path with the path of the mountpoint in the parent mount. * Up is towards /. * * Return 1 if we went up a level and 0 if we were already at the * root. */ int follow_up(struct path *path) { struct mount *mnt = real_mount(path->mnt); struct mount *parent; struct dentry *mountpoint; read_seqlock_excl(&mount_lock); parent = mnt->mnt_parent; if (parent == mnt) { read_sequnlock_excl(&mount_lock); return 0; } mntget(&parent->mnt); mountpoint = dget(mnt->mnt_mountpoint); read_sequnlock_excl(&mount_lock); dput(path->dentry); path->dentry = mountpoint; mntput(path->mnt); path->mnt = &parent->mnt; return 1; } EXPORT_SYMBOL(follow_up); /* * Perform an automount * - return -EISDIR to tell follow_managed() to stop and return the path we * were called with. */ static int follow_automount(struct path *path, unsigned flags, bool *need_mntput) { struct vfsmount *mnt; int err; if (!path->dentry->d_op || !path->dentry->d_op->d_automount) return -EREMOTE; /* We don't want to mount if someone's just doing a stat - * unless they're stat'ing a directory and appended a '/' to * the name. * * We do, however, want to mount if someone wants to open or * create a file of any type under the mountpoint, wants to * traverse through the mountpoint or wants to open the * mounted directory. Also, autofs may mark negative dentries * as being automount points. These will need the attentions * of the daemon to instantiate them before they can be used. */ if (!(flags & (LOOKUP_PARENT | LOOKUP_DIRECTORY | LOOKUP_OPEN | LOOKUP_CREATE | LOOKUP_AUTOMOUNT)) && path->dentry->d_inode) return -EISDIR; current->total_link_count++; if (current->total_link_count >= 40) return -ELOOP; mnt = path->dentry->d_op->d_automount(path); if (IS_ERR(mnt)) { /* * The filesystem is allowed to return -EISDIR here to indicate * it doesn't want to automount. For instance, autofs would do * this so that its userspace daemon can mount on this dentry. * * However, we can only permit this if it's a terminal point in * the path being looked up; if it wasn't then the remainder of * the path is inaccessible and we should say so. */ if (PTR_ERR(mnt) == -EISDIR && (flags & LOOKUP_PARENT)) return -EREMOTE; return PTR_ERR(mnt); } if (!mnt) /* mount collision */ return 0; if (!*need_mntput) { /* lock_mount() may release path->mnt on error */ mntget(path->mnt); *need_mntput = true; } err = finish_automount(mnt, path); switch (err) { case -EBUSY: /* Someone else made a mount here whilst we were busy */ return 0; case 0: path_put(path); path->mnt = mnt; path->dentry = dget(mnt->mnt_root); return 0; default: return err; } } /* * Handle a dentry that is managed in some way. * - Flagged for transit management (autofs) * - Flagged as mountpoint * - Flagged as automount point * * This may only be called in refwalk mode. * * Serialization is taken care of in namespace.c */ static int follow_managed(struct path *path, unsigned flags) { struct vfsmount *mnt = path->mnt; /* held by caller, must be left alone */ unsigned managed; bool need_mntput = false; int ret = 0; /* Given that we're not holding a lock here, we retain the value in a * local variable for each dentry as we look at it so that we don't see * the components of that value change under us */ while (managed = ACCESS_ONCE(path->dentry->d_flags), managed &= DCACHE_MANAGED_DENTRY, unlikely(managed != 0)) { /* Allow the filesystem to manage the transit without i_mutex * being held. */ if (managed & DCACHE_MANAGE_TRANSIT) { BUG_ON(!path->dentry->d_op); BUG_ON(!path->dentry->d_op->d_manage); ret = path->dentry->d_op->d_manage(path->dentry, false); if (ret < 0) break; } /* Transit to a mounted filesystem. */ if (managed & DCACHE_MOUNTED) { struct vfsmount *mounted = lookup_mnt(path); if (mounted) { dput(path->dentry); if (need_mntput) mntput(path->mnt); path->mnt = mounted; path->dentry = dget(mounted->mnt_root); need_mntput = true; continue; } /* Something is mounted on this dentry in another * namespace and/or whatever was mounted there in this * namespace got unmounted before lookup_mnt() could * get it */ } /* Handle an automount point */ if (managed & DCACHE_NEED_AUTOMOUNT) { ret = follow_automount(path, flags, &need_mntput); if (ret < 0) break; continue; } /* We didn't change the current path point */ break; } if (need_mntput && path->mnt == mnt) mntput(path->mnt); if (ret == -EISDIR) ret = 0; return ret < 0 ? ret : need_mntput; } int follow_down_one(struct path *path) { struct vfsmount *mounted; mounted = lookup_mnt(path); if (mounted) { dput(path->dentry); mntput(path->mnt); path->mnt = mounted; path->dentry = dget(mounted->mnt_root); return 1; } return 0; } EXPORT_SYMBOL(follow_down_one); static inline bool managed_dentry_might_block(struct dentry *dentry) { return (dentry->d_flags & DCACHE_MANAGE_TRANSIT && dentry->d_op->d_manage(dentry, true) < 0); } /* * Try to skip to top of mountpoint pile in rcuwalk mode. Fail if * we meet a managed dentry that would need blocking. */ static bool __follow_mount_rcu(struct nameidata *nd, struct path *path, struct inode **inode) { for (;;) { struct mount *mounted; /* * Don't forget we might have a non-mountpoint managed dentry * that wants to block transit. */ if (unlikely(managed_dentry_might_block(path->dentry))) return false; if (!d_mountpoint(path->dentry)) return true; mounted = __lookup_mnt(path->mnt, path->dentry); if (!mounted) break; path->mnt = &mounted->mnt; path->dentry = mounted->mnt.mnt_root; nd->flags |= LOOKUP_JUMPED; nd->seq = read_seqcount_begin(&path->dentry->d_seq); /* * Update the inode too. We don't need to re-check the * dentry sequence number here after this d_inode read, * because a mount-point is always pinned. */ *inode = path->dentry->d_inode; } return read_seqretry(&mount_lock, nd->m_seq); } static int follow_dotdot_rcu(struct nameidata *nd) { set_root_rcu(nd); while (1) { if (nd->path.dentry == nd->root.dentry && nd->path.mnt == nd->root.mnt) { break; } if (nd->path.dentry != nd->path.mnt->mnt_root) { struct dentry *old = nd->path.dentry; struct dentry *parent = old->d_parent; unsigned seq; seq = read_seqcount_begin(&parent->d_seq); if (read_seqcount_retry(&old->d_seq, nd->seq)) goto failed; nd->path.dentry = parent; nd->seq = seq; break; } if (!follow_up_rcu(&nd->path)) break; nd->seq = read_seqcount_begin(&nd->path.dentry->d_seq); } while (d_mountpoint(nd->path.dentry)) { struct mount *mounted; mounted = __lookup_mnt(nd->path.mnt, nd->path.dentry); if (!mounted) break; nd->path.mnt = &mounted->mnt; nd->path.dentry = mounted->mnt.mnt_root; nd->seq = read_seqcount_begin(&nd->path.dentry->d_seq); if (!read_seqretry(&mount_lock, nd->m_seq)) goto failed; } nd->inode = nd->path.dentry->d_inode; return 0; failed: nd->flags &= ~LOOKUP_RCU; if (!(nd->flags & LOOKUP_ROOT)) nd->root.mnt = NULL; rcu_read_unlock(); return -ECHILD; } /* * Follow down to the covering mount currently visible to userspace. At each * point, the filesystem owning that dentry may be queried as to whether the * caller is permitted to proceed or not. */ int follow_down(struct path *path) { unsigned managed; int ret; while (managed = ACCESS_ONCE(path->dentry->d_flags), unlikely(managed & DCACHE_MANAGED_DENTRY)) { /* Allow the filesystem to manage the transit without i_mutex * being held. * * We indicate to the filesystem if someone is trying to mount * something here. This gives autofs the chance to deny anyone * other than its daemon the right to mount on its * superstructure. * * The filesystem may sleep at this point. */ if (managed & DCACHE_MANAGE_TRANSIT) { BUG_ON(!path->dentry->d_op); BUG_ON(!path->dentry->d_op->d_manage); ret = path->dentry->d_op->d_manage( path->dentry, false); if (ret < 0) return ret == -EISDIR ? 0 : ret; } /* Transit to a mounted filesystem. */ if (managed & DCACHE_MOUNTED) { struct vfsmount *mounted = lookup_mnt(path); if (!mounted) break; dput(path->dentry); mntput(path->mnt); path->mnt = mounted; path->dentry = dget(mounted->mnt_root); continue; } /* Don't handle automount points here */ break; } return 0; } EXPORT_SYMBOL(follow_down); /* * Skip to top of mountpoint pile in refwalk mode for follow_dotdot() */ static void follow_mount(struct path *path) { while (d_mountpoint(path->dentry)) { struct vfsmount *mounted = lookup_mnt(path); if (!mounted) break; dput(path->dentry); mntput(path->mnt); path->mnt = mounted; path->dentry = dget(mounted->mnt_root); } } static void follow_dotdot(struct nameidata *nd) { set_root(nd); while(1) { struct dentry *old = nd->path.dentry; if (nd->path.dentry == nd->root.dentry && nd->path.mnt == nd->root.mnt) { break; } if (nd->path.dentry != nd->path.mnt->mnt_root) { /* rare case of legitimate dget_parent()... */ nd->path.dentry = dget_parent(nd->path.dentry); dput(old); break; } if (!follow_up(&nd->path)) break; } follow_mount(&nd->path); nd->inode = nd->path.dentry->d_inode; } /* * This looks up the name in dcache, possibly revalidates the old dentry and * allocates a new one if not found or not valid. In the need_lookup argument * returns whether i_op->lookup is necessary. * * dir->d_inode->i_mutex must be held */ static struct dentry *lookup_dcache(struct qstr *name, struct dentry *dir, unsigned int flags, bool *need_lookup) { struct dentry *dentry; int error; *need_lookup = false; dentry = d_lookup(dir, name); if (dentry) { if (dentry->d_flags & DCACHE_OP_REVALIDATE) { error = d_revalidate(dentry, flags); if (unlikely(error <= 0)) { if (error < 0) { dput(dentry); return ERR_PTR(error); } else if (!d_invalidate(dentry)) { dput(dentry); dentry = NULL; } } } } if (!dentry) { dentry = d_alloc(dir, name); if (unlikely(!dentry)) return ERR_PTR(-ENOMEM); *need_lookup = true; } return dentry; } /* * Call i_op->lookup on the dentry. The dentry must be negative and * unhashed. * * dir->d_inode->i_mutex must be held */ static struct dentry *lookup_real(struct inode *dir, struct dentry *dentry, unsigned int flags) { struct dentry *old; /* Don't create child dentry for a dead directory. */ if (unlikely(IS_DEADDIR(dir))) { dput(dentry); return ERR_PTR(-ENOENT); } old = dir->i_op->lookup(dir, dentry, flags); if (unlikely(old)) { dput(dentry); dentry = old; } return dentry; } static struct dentry *__lookup_hash(struct qstr *name, struct dentry *base, unsigned int flags) { bool need_lookup; struct dentry *dentry; dentry = lookup_dcache(name, base, flags, &need_lookup); if (!need_lookup) return dentry; return lookup_real(base->d_inode, dentry, flags); } /* * It's more convoluted than I'd like it to be, but... it's still fairly * small and for now I'd prefer to have fast path as straight as possible. * It _is_ time-critical. */ static int lookup_fast(struct nameidata *nd, struct path *path, struct inode **inode) { struct vfsmount *mnt = nd->path.mnt; struct dentry *dentry, *parent = nd->path.dentry; int need_reval = 1; int status = 1; int err; /* * Rename seqlock is not required here because in the off chance * of a false negative due to a concurrent rename, we're going to * do the non-racy lookup, below. */ if (nd->flags & LOOKUP_RCU) { unsigned seq; dentry = __d_lookup_rcu(parent, &nd->last, &seq); if (!dentry) goto unlazy; /* * This sequence count validates that the inode matches * the dentry name information from lookup. */ *inode = dentry->d_inode; if (read_seqcount_retry(&dentry->d_seq, seq)) return -ECHILD; /* * This sequence count validates that the parent had no * changes while we did the lookup of the dentry above. * * The memory barrier in read_seqcount_begin of child is * enough, we can use __read_seqcount_retry here. */ if (__read_seqcount_retry(&parent->d_seq, nd->seq)) return -ECHILD; nd->seq = seq; if (unlikely(dentry->d_flags & DCACHE_OP_REVALIDATE)) { status = d_revalidate(dentry, nd->flags); if (unlikely(status <= 0)) { if (status != -ECHILD) need_reval = 0; goto unlazy; } } path->mnt = mnt; path->dentry = dentry; if (unlikely(!__follow_mount_rcu(nd, path, inode))) goto unlazy; if (unlikely(path->dentry->d_flags & DCACHE_NEED_AUTOMOUNT)) goto unlazy; return 0; unlazy: if (unlazy_walk(nd, dentry)) return -ECHILD; } else { dentry = __d_lookup(parent, &nd->last); } if (unlikely(!dentry)) goto need_lookup; if (unlikely(dentry->d_flags & DCACHE_OP_REVALIDATE) && need_reval) status = d_revalidate(dentry, nd->flags); if (unlikely(status <= 0)) { if (status < 0) { dput(dentry); return status; } if (!d_invalidate(dentry)) { dput(dentry); goto need_lookup; } } path->mnt = mnt; path->dentry = dentry; err = follow_managed(path, nd->flags); if (unlikely(err < 0)) { path_put_conditional(path, nd); return err; } if (err) nd->flags |= LOOKUP_JUMPED; *inode = path->dentry->d_inode; return 0; need_lookup: return 1; } /* Fast lookup failed, do it the slow way */ static int lookup_slow(struct nameidata *nd, struct path *path) { struct dentry *dentry, *parent; int err; parent = nd->path.dentry; BUG_ON(nd->inode != parent->d_inode); mutex_lock(&parent->d_inode->i_mutex); dentry = __lookup_hash(&nd->last, parent, nd->flags); mutex_unlock(&parent->d_inode->i_mutex); if (IS_ERR(dentry)) return PTR_ERR(dentry); path->mnt = nd->path.mnt; path->dentry = dentry; err = follow_managed(path, nd->flags); if (unlikely(err < 0)) { path_put_conditional(path, nd); return err; } if (err) nd->flags |= LOOKUP_JUMPED; return 0; } static inline int may_lookup(struct nameidata *nd) { if (nd->flags & LOOKUP_RCU) { int err = inode_permission(nd->inode, MAY_EXEC|MAY_NOT_BLOCK); if (err != -ECHILD) return err; if (unlazy_walk(nd, NULL)) return -ECHILD; } return inode_permission(nd->inode, MAY_EXEC); } static inline int handle_dots(struct nameidata *nd, int type) { if (type == LAST_DOTDOT) { if (nd->flags & LOOKUP_RCU) { if (follow_dotdot_rcu(nd)) return -ECHILD; } else follow_dotdot(nd); } return 0; } static void terminate_walk(struct nameidata *nd) { if (!(nd->flags & LOOKUP_RCU)) { path_put(&nd->path); } else { nd->flags &= ~LOOKUP_RCU; if (!(nd->flags & LOOKUP_ROOT)) nd->root.mnt = NULL; rcu_read_unlock(); } } /* * Do we need to follow links? We _really_ want to be able * to do this check without having to look at inode->i_op, * so we keep a cache of "no, this doesn't need follow_link" * for the common case. */ static inline int should_follow_link(struct dentry *dentry, int follow) { return unlikely(d_is_symlink(dentry)) ? follow : 0; } static inline int walk_component(struct nameidata *nd, struct path *path, int follow) { struct inode *inode; int err; /* * "." and ".." are special - ".." especially so because it has * to be able to know about the current root directory and * parent relationships. */ if (unlikely(nd->last_type != LAST_NORM)) return handle_dots(nd, nd->last_type); err = lookup_fast(nd, path, &inode); if (unlikely(err)) { if (err < 0) goto out_err; err = lookup_slow(nd, path); if (err < 0) goto out_err; inode = path->dentry->d_inode; } err = -ENOENT; if (!inode || d_is_negative(path->dentry)) goto out_path_put; if (should_follow_link(path->dentry, follow)) { if (nd->flags & LOOKUP_RCU) { if (unlikely(unlazy_walk(nd, path->dentry))) { err = -ECHILD; goto out_err; } } BUG_ON(inode != path->dentry->d_inode); return 1; } path_to_nameidata(path, nd); nd->inode = inode; return 0; out_path_put: path_to_nameidata(path, nd); out_err: terminate_walk(nd); return err; } /* * This limits recursive symlink follows to 8, while * limiting consecutive symlinks to 40. * * Without that kind of total limit, nasty chains of consecutive * symlinks can cause almost arbitrarily long lookups. */ static inline int nested_symlink(struct path *path, struct nameidata *nd) { int res; if (unlikely(current->link_count >= MAX_NESTED_LINKS)) { path_put_conditional(path, nd); path_put(&nd->path); return -ELOOP; } BUG_ON(nd->depth >= MAX_NESTED_LINKS); nd->depth++; current->link_count++; do { struct path link = *path; void *cookie; res = follow_link(&link, nd, &cookie); if (res) break; res = walk_component(nd, path, LOOKUP_FOLLOW); put_link(nd, &link, cookie); } while (res > 0); current->link_count--; nd->depth--; return res; } /* * We can do the critical dentry name comparison and hashing * operations one word at a time, but we are limited to: * * - Architectures with fast unaligned word accesses. We could * do a "get_unaligned()" if this helps and is sufficiently * fast. * * - non-CONFIG_DEBUG_PAGEALLOC configurations (so that we * do not trap on the (extremely unlikely) case of a page * crossing operation. * * - Furthermore, we need an efficient 64-bit compile for the * 64-bit case in order to generate the "number of bytes in * the final mask". Again, that could be replaced with a * efficient population count instruction or similar. */ #ifdef CONFIG_DCACHE_WORD_ACCESS #include <asm/word-at-a-time.h> #ifdef CONFIG_64BIT static inline unsigned int fold_hash(unsigned long hash) { hash += hash >> (8*sizeof(int)); return hash; } #else /* 32-bit case */ #define fold_hash(x) (x) #endif unsigned int full_name_hash(const unsigned char *name, unsigned int len) { unsigned long a, mask; unsigned long hash = 0; for (;;) { a = load_unaligned_zeropad(name); if (len < sizeof(unsigned long)) break; hash += a; hash *= 9; name += sizeof(unsigned long); len -= sizeof(unsigned long); if (!len) goto done; } mask = bytemask_from_count(len); hash += mask & a; done: return fold_hash(hash); } EXPORT_SYMBOL(full_name_hash); /* * Calculate the length and hash of the path component, and * return the length of the component; */ static inline unsigned long hash_name(const char *name, unsigned int *hashp) { unsigned long a, b, adata, bdata, mask, hash, len; const struct word_at_a_time constants = WORD_AT_A_TIME_CONSTANTS; hash = a = 0; len = -sizeof(unsigned long); do { hash = (hash + a) * 9; len += sizeof(unsigned long); a = load_unaligned_zeropad(name+len); b = a ^ REPEAT_BYTE('/'); } while (!(has_zero(a, &adata, &constants) | has_zero(b, &bdata, &constants))); adata = prep_zero_mask(a, adata, &constants); bdata = prep_zero_mask(b, bdata, &constants); mask = create_zero_mask(adata | bdata); hash += a & zero_bytemask(mask); *hashp = fold_hash(hash); return len + find_zero(mask); } #else unsigned int full_name_hash(const unsigned char *name, unsigned int len) { unsigned long hash = init_name_hash(); while (len--) hash = partial_name_hash(*name++, hash); return end_name_hash(hash); } EXPORT_SYMBOL(full_name_hash); /* * We know there's a real path component here of at least * one character. */ static inline unsigned long hash_name(const char *name, unsigned int *hashp) { unsigned long hash = init_name_hash(); unsigned long len = 0, c; c = (unsigned char)*name; do { len++; hash = partial_name_hash(c, hash); c = (unsigned char)name[len]; } while (c && c != '/'); *hashp = end_name_hash(hash); return len; } #endif /* * Name resolution. * This is the basic name resolution function, turning a pathname into * the final dentry. We expect 'base' to be positive and a directory. * * Returns 0 and nd will have valid dentry and mnt on success. * Returns error and drops reference to input namei data on failure. */ static int link_path_walk(const char *name, struct nameidata *nd) { struct path next; int err; while (*name=='/') name++; if (!*name) return 0; /* At this point we know we have a real path component. */ for(;;) { struct qstr this; long len; int type; err = may_lookup(nd); if (err) break; len = hash_name(name, &this.hash); this.name = name; this.len = len; type = LAST_NORM; if (name[0] == '.') switch (len) { case 2: if (name[1] == '.') { type = LAST_DOTDOT; nd->flags |= LOOKUP_JUMPED; } break; case 1: type = LAST_DOT; } if (likely(type == LAST_NORM)) { struct dentry *parent = nd->path.dentry; nd->flags &= ~LOOKUP_JUMPED; if (unlikely(parent->d_flags & DCACHE_OP_HASH)) { err = parent->d_op->d_hash(parent, &this); if (err < 0) break; } } nd->last = this; nd->last_type = type; if (!name[len]) return 0; /* * If it wasn't NUL, we know it was '/'. Skip that * slash, and continue until no more slashes. */ do { len++; } while (unlikely(name[len] == '/')); if (!name[len]) return 0; name += len; err = walk_component(nd, &next, LOOKUP_FOLLOW); if (err < 0) return err; if (err) { err = nested_symlink(&next, nd); if (err) return err; } if (!d_can_lookup(nd->path.dentry)) { err = -ENOTDIR; break; } } terminate_walk(nd); return err; } static int path_init(int dfd, const char *name, unsigned int flags, struct nameidata *nd, struct file **fp) { int retval = 0; nd->last_type = LAST_ROOT; /* if there are only slashes... */ nd->flags = flags | LOOKUP_JUMPED; nd->depth = 0; if (flags & LOOKUP_ROOT) { struct dentry *root = nd->root.dentry; struct inode *inode = root->d_inode; if (*name) { if (!d_can_lookup(root)) return -ENOTDIR; retval = inode_permission(inode, MAY_EXEC); if (retval) return retval; } nd->path = nd->root; nd->inode = inode; if (flags & LOOKUP_RCU) { rcu_read_lock(); nd->seq = __read_seqcount_begin(&nd->path.dentry->d_seq); nd->m_seq = read_seqbegin(&mount_lock); } else { path_get(&nd->path); } return 0; } nd->root.mnt = NULL; nd->m_seq = read_seqbegin(&mount_lock); if (*name=='/') { if (flags & LOOKUP_RCU) { rcu_read_lock(); set_root_rcu(nd); } else { set_root(nd); path_get(&nd->root); } nd->path = nd->root; } else if (dfd == AT_FDCWD) { if (flags & LOOKUP_RCU) { struct fs_struct *fs = current->fs; unsigned seq; rcu_read_lock(); do { seq = read_seqcount_begin(&fs->seq); nd->path = fs->pwd; nd->seq = __read_seqcount_begin(&nd->path.dentry->d_seq); } while (read_seqcount_retry(&fs->seq, seq)); } else { get_fs_pwd(current->fs, &nd->path); } } else { /* Caller must check execute permissions on the starting path component */ struct fd f = fdget_raw(dfd); struct dentry *dentry; if (!f.file) return -EBADF; dentry = f.file->f_path.dentry; if (*name) { if (!d_can_lookup(dentry)) { fdput(f); return -ENOTDIR; } } nd->path = f.file->f_path; if (flags & LOOKUP_RCU) { if (f.flags & FDPUT_FPUT) *fp = f.file; nd->seq = __read_seqcount_begin(&nd->path.dentry->d_seq); rcu_read_lock(); } else { path_get(&nd->path); fdput(f); } } nd->inode = nd->path.dentry->d_inode; return 0; } static inline int lookup_last(struct nameidata *nd, struct path *path) { if (nd->last_type == LAST_NORM && nd->last.name[nd->last.len]) nd->flags |= LOOKUP_FOLLOW | LOOKUP_DIRECTORY; nd->flags &= ~LOOKUP_PARENT; return walk_component(nd, path, nd->flags & LOOKUP_FOLLOW); } /* Returns 0 and nd will be valid on success; Retuns error, otherwise. */ static int path_lookupat(int dfd, const char *name, unsigned int flags, struct nameidata *nd) { struct file *base = NULL; struct path path; int err; /* * Path walking is largely split up into 2 different synchronisation * schemes, rcu-walk and ref-walk (explained in * Documentation/filesystems/path-lookup.txt). These share much of the * path walk code, but some things particularly setup, cleanup, and * following mounts are sufficiently divergent that functions are * duplicated. Typically there is a function foo(), and its RCU * analogue, foo_rcu(). * * -ECHILD is the error number of choice (just to avoid clashes) that * is returned if some aspect of an rcu-walk fails. Such an error must * be handled by restarting a traditional ref-walk (which will always * be able to complete). */ err = path_init(dfd, name, flags | LOOKUP_PARENT, nd, &base); if (unlikely(err)) return err; current->total_link_count = 0; err = link_path_walk(name, nd); if (!err && !(flags & LOOKUP_PARENT)) { err = lookup_last(nd, &path); while (err > 0) { void *cookie; struct path link = path; err = may_follow_link(&link, nd); if (unlikely(err)) break; nd->flags |= LOOKUP_PARENT; err = follow_link(&link, nd, &cookie); if (err) break; err = lookup_last(nd, &path); put_link(nd, &link, cookie); } } if (!err) err = complete_walk(nd); if (!err && nd->flags & LOOKUP_DIRECTORY) { if (!d_can_lookup(nd->path.dentry)) { path_put(&nd->path); err = -ENOTDIR; } } if (base) fput(base); if (nd->root.mnt && !(nd->flags & LOOKUP_ROOT)) { path_put(&nd->root); nd->root.mnt = NULL; } return err; } static int filename_lookup(int dfd, struct filename *name, unsigned int flags, struct nameidata *nd) { int retval = path_lookupat(dfd, name->name, flags | LOOKUP_RCU, nd); if (unlikely(retval == -ECHILD)) retval = path_lookupat(dfd, name->name, flags, nd); if (unlikely(retval == -ESTALE)) retval = path_lookupat(dfd, name->name, flags | LOOKUP_REVAL, nd); if (likely(!retval)) audit_inode(name, nd->path.dentry, flags & LOOKUP_PARENT); return retval; } static int do_path_lookup(int dfd, const char *name, unsigned int flags, struct nameidata *nd) { struct filename filename = { .name = name }; return filename_lookup(dfd, &filename, flags, nd); } /* does lookup, returns the object with parent locked */ struct dentry *kern_path_locked(const char *name, struct path *path) { struct nameidata nd; struct dentry *d; int err = do_path_lookup(AT_FDCWD, name, LOOKUP_PARENT, &nd); if (err) return ERR_PTR(err); if (nd.last_type != LAST_NORM) { path_put(&nd.path); return ERR_PTR(-EINVAL); } mutex_lock_nested(&nd.path.dentry->d_inode->i_mutex, I_MUTEX_PARENT); d = __lookup_hash(&nd.last, nd.path.dentry, 0); if (IS_ERR(d)) { mutex_unlock(&nd.path.dentry->d_inode->i_mutex); path_put(&nd.path); return d; } *path = nd.path; return d; } int kern_path(const char *name, unsigned int flags, struct path *path) { struct nameidata nd; int res = do_path_lookup(AT_FDCWD, name, flags, &nd); if (!res) *path = nd.path; return res; } EXPORT_SYMBOL(kern_path); /** * vfs_path_lookup - lookup a file path relative to a dentry-vfsmount pair * @dentry: pointer to dentry of the base directory * @mnt: pointer to vfs mount of the base directory * @name: pointer to file name * @flags: lookup flags * @path: pointer to struct path to fill */ int vfs_path_lookup(struct dentry *dentry, struct vfsmount *mnt, const char *name, unsigned int flags, struct path *path) { struct nameidata nd; int err; nd.root.dentry = dentry; nd.root.mnt = mnt; BUG_ON(flags & LOOKUP_PARENT); /* the first argument of do_path_lookup() is ignored with LOOKUP_ROOT */ err = do_path_lookup(AT_FDCWD, name, flags | LOOKUP_ROOT, &nd); if (!err) *path = nd.path; return err; } EXPORT_SYMBOL(vfs_path_lookup); /* * Restricted form of lookup. Doesn't follow links, single-component only, * needs parent already locked. Doesn't follow mounts. * SMP-safe. */ static struct dentry *lookup_hash(struct nameidata *nd) { return __lookup_hash(&nd->last, nd->path.dentry, nd->flags); } /** * lookup_one_len - filesystem helper to lookup single pathname component * @name: pathname component to lookup * @base: base directory to lookup from * @len: maximum length @len should be interpreted to * * Note that this routine is purely a helper for filesystem usage and should * not be called by generic code. Also note that by using this function the * nameidata argument is passed to the filesystem methods and a filesystem * using this helper needs to be prepared for that. */ struct dentry *lookup_one_len(const char *name, struct dentry *base, int len) { struct qstr this; unsigned int c; int err; WARN_ON_ONCE(!mutex_is_locked(&base->d_inode->i_mutex)); this.name = name; this.len = len; this.hash = full_name_hash(name, len); if (!len) return ERR_PTR(-EACCES); if (unlikely(name[0] == '.')) { if (len < 2 || (len == 2 && name[1] == '.')) return ERR_PTR(-EACCES); } while (len--) { c = *(const unsigned char *)name++; if (c == '/' || c == '\0') return ERR_PTR(-EACCES); } /* * See if the low-level filesystem might want * to use its own hash.. */ if (base->d_flags & DCACHE_OP_HASH) { int err = base->d_op->d_hash(base, &this); if (err < 0) return ERR_PTR(err); } err = inode_permission(base->d_inode, MAY_EXEC); if (err) return ERR_PTR(err); return __lookup_hash(&this, base, 0); } EXPORT_SYMBOL(lookup_one_len); int user_path_at_empty(int dfd, const char __user *name, unsigned flags, struct path *path, int *empty) { struct nameidata nd; struct filename *tmp = getname_flags(name, flags, empty); int err = PTR_ERR(tmp); if (!IS_ERR(tmp)) { BUG_ON(flags & LOOKUP_PARENT); err = filename_lookup(dfd, tmp, flags, &nd); putname(tmp); if (!err) *path = nd.path; } return err; } int user_path_at(int dfd, const char __user *name, unsigned flags, struct path *path) { return user_path_at_empty(dfd, name, flags, path, NULL); } EXPORT_SYMBOL(user_path_at); /* * NB: most callers don't do anything directly with the reference to the * to struct filename, but the nd->last pointer points into the name string * allocated by getname. So we must hold the reference to it until all * path-walking is complete. */ static struct filename * user_path_parent(int dfd, const char __user *path, struct nameidata *nd, unsigned int flags) { struct filename *s = getname(path); int error; /* only LOOKUP_REVAL is allowed in extra flags */ flags &= LOOKUP_REVAL; if (IS_ERR(s)) return s; error = filename_lookup(dfd, s, flags | LOOKUP_PARENT, nd); if (error) { putname(s); return ERR_PTR(error); } return s; } /** * mountpoint_last - look up last component for umount * @nd: pathwalk nameidata - currently pointing at parent directory of "last" * @path: pointer to container for result * * This is a special lookup_last function just for umount. In this case, we * need to resolve the path without doing any revalidation. * * The nameidata should be the result of doing a LOOKUP_PARENT pathwalk. Since * mountpoints are always pinned in the dcache, their ancestors are too. Thus, * in almost all cases, this lookup will be served out of the dcache. The only * cases where it won't are if nd->last refers to a symlink or the path is * bogus and it doesn't exist. * * Returns: * -error: if there was an error during lookup. This includes -ENOENT if the * lookup found a negative dentry. The nd->path reference will also be * put in this case. * * 0: if we successfully resolved nd->path and found it to not to be a * symlink that needs to be followed. "path" will also be populated. * The nd->path reference will also be put. * * 1: if we successfully resolved nd->last and found it to be a symlink * that needs to be followed. "path" will be populated with the path * to the link, and nd->path will *not* be put. */ static int mountpoint_last(struct nameidata *nd, struct path *path) { int error = 0; struct dentry *dentry; struct dentry *dir = nd->path.dentry; /* If we're in rcuwalk, drop out of it to handle last component */ if (nd->flags & LOOKUP_RCU) { if (unlazy_walk(nd, NULL)) { error = -ECHILD; goto out; } } nd->flags &= ~LOOKUP_PARENT; if (unlikely(nd->last_type != LAST_NORM)) { error = handle_dots(nd, nd->last_type); if (error) goto out; dentry = dget(nd->path.dentry); goto done; } mutex_lock(&dir->d_inode->i_mutex); dentry = d_lookup(dir, &nd->last); if (!dentry) { /* * No cached dentry. Mounted dentries are pinned in the cache, * so that means that this dentry is probably a symlink or the * path doesn't actually point to a mounted dentry. */ dentry = d_alloc(dir, &nd->last); if (!dentry) { error = -ENOMEM; mutex_unlock(&dir->d_inode->i_mutex); goto out; } dentry = lookup_real(dir->d_inode, dentry, nd->flags); error = PTR_ERR(dentry); if (IS_ERR(dentry)) { mutex_unlock(&dir->d_inode->i_mutex); goto out; } } mutex_unlock(&dir->d_inode->i_mutex); done: if (!dentry->d_inode || d_is_negative(dentry)) { error = -ENOENT; dput(dentry); goto out; } path->dentry = dentry; path->mnt = mntget(nd->path.mnt); if (should_follow_link(dentry, nd->flags & LOOKUP_FOLLOW)) return 1; follow_mount(path); error = 0; out: terminate_walk(nd); return error; } /** * path_mountpoint - look up a path to be umounted * @dfd: directory file descriptor to start walk from * @name: full pathname to walk * @path: pointer to container for result * @flags: lookup flags * * Look up the given name, but don't attempt to revalidate the last component. * Returns 0 and "path" will be valid on success; Returns error otherwise. */ static int path_mountpoint(int dfd, const char *name, struct path *path, unsigned int flags) { struct file *base = NULL; struct nameidata nd; int err; err = path_init(dfd, name, flags | LOOKUP_PARENT, &nd, &base); if (unlikely(err)) return err; current->total_link_count = 0; err = link_path_walk(name, &nd); if (err) goto out; err = mountpoint_last(&nd, path); while (err > 0) { void *cookie; struct path link = *path; err = may_follow_link(&link, &nd); if (unlikely(err)) break; nd.flags |= LOOKUP_PARENT; err = follow_link(&link, &nd, &cookie); if (err) break; err = mountpoint_last(&nd, path); put_link(&nd, &link, cookie); } out: if (base) fput(base); if (nd.root.mnt && !(nd.flags & LOOKUP_ROOT)) path_put(&nd.root); return err; } static int filename_mountpoint(int dfd, struct filename *s, struct path *path, unsigned int flags) { int error = path_mountpoint(dfd, s->name, path, flags | LOOKUP_RCU); if (unlikely(error == -ECHILD)) error = path_mountpoint(dfd, s->name, path, flags); if (unlikely(error == -ESTALE)) error = path_mountpoint(dfd, s->name, path, flags | LOOKUP_REVAL); if (likely(!error)) audit_inode(s, path->dentry, 0); return error; } /** * user_path_mountpoint_at - lookup a path from userland in order to umount it * @dfd: directory file descriptor * @name: pathname from userland * @flags: lookup flags * @path: pointer to container to hold result * * A umount is a special case for path walking. We're not actually interested * in the inode in this situation, and ESTALE errors can be a problem. We * simply want track down the dentry and vfsmount attached at the mountpoint * and avoid revalidating the last component. * * Returns 0 and populates "path" on success. */ int user_path_mountpoint_at(int dfd, const char __user *name, unsigned int flags, struct path *path) { struct filename *s = getname(name); int error; if (IS_ERR(s)) return PTR_ERR(s); error = filename_mountpoint(dfd, s, path, flags); putname(s); return error; } int kern_path_mountpoint(int dfd, const char *name, struct path *path, unsigned int flags) { struct filename s = {.name = name}; return filename_mountpoint(dfd, &s, path, flags); } EXPORT_SYMBOL(kern_path_mountpoint); /* * It's inline, so penalty for filesystems that don't use sticky bit is * minimal. */ static inline int check_sticky(struct inode *dir, struct inode *inode) { kuid_t fsuid = current_fsuid(); if (!(dir->i_mode & S_ISVTX)) return 0; if (uid_eq(inode->i_uid, fsuid)) return 0; if (uid_eq(dir->i_uid, fsuid)) return 0; return !capable_wrt_inode_uidgid(inode, CAP_FOWNER); } /* * Check whether we can remove a link victim from directory dir, check * whether the type of victim is right. * 1. We can't do it if dir is read-only (done in permission()) * 2. We should have write and exec permissions on dir * 3. We can't remove anything from append-only dir * 4. We can't do anything with immutable dir (done in permission()) * 5. If the sticky bit on dir is set we should either * a. be owner of dir, or * b. be owner of victim, or * c. have CAP_FOWNER capability * 6. If the victim is append-only or immutable we can't do antyhing with * links pointing to it. * 7. If we were asked to remove a directory and victim isn't one - ENOTDIR. * 8. If we were asked to remove a non-directory and victim isn't one - EISDIR. * 9. We can't remove a root or mountpoint. * 10. We don't allow removal of NFS sillyrenamed files; it's handled by * nfs_async_unlink(). */ static int may_delete(struct inode *dir, struct dentry *victim, bool isdir) { struct inode *inode = victim->d_inode; int error; if (d_is_negative(victim)) return -ENOENT; BUG_ON(!inode); BUG_ON(victim->d_parent->d_inode != dir); audit_inode_child(dir, victim, AUDIT_TYPE_CHILD_DELETE); error = inode_permission(dir, MAY_WRITE | MAY_EXEC); if (error) return error; if (IS_APPEND(dir)) return -EPERM; if (check_sticky(dir, inode) || IS_APPEND(inode) || IS_IMMUTABLE(inode) || IS_SWAPFILE(inode)) return -EPERM; if (isdir) { if (!d_is_dir(victim)) return -ENOTDIR; if (IS_ROOT(victim)) return -EBUSY; } else if (d_is_dir(victim)) return -EISDIR; if (IS_DEADDIR(dir)) return -ENOENT; if (victim->d_flags & DCACHE_NFSFS_RENAMED) return -EBUSY; return 0; } /* Check whether we can create an object with dentry child in directory * dir. * 1. We can't do it if child already exists (open has special treatment for * this case, but since we are inlined it's OK) * 2. We can't do it if dir is read-only (done in permission()) * 3. We should have write and exec permissions on dir * 4. We can't do it if dir is immutable (done in permission()) */ static inline int may_create(struct inode *dir, struct dentry *child) { audit_inode_child(dir, child, AUDIT_TYPE_CHILD_CREATE); if (child->d_inode) return -EEXIST; if (IS_DEADDIR(dir)) return -ENOENT; return inode_permission(dir, MAY_WRITE | MAY_EXEC); } /* * p1 and p2 should be directories on the same fs. */ struct dentry *lock_rename(struct dentry *p1, struct dentry *p2) { struct dentry *p; if (p1 == p2) { mutex_lock_nested(&p1->d_inode->i_mutex, I_MUTEX_PARENT); return NULL; } mutex_lock(&p1->d_inode->i_sb->s_vfs_rename_mutex); p = d_ancestor(p2, p1); if (p) { mutex_lock_nested(&p2->d_inode->i_mutex, I_MUTEX_PARENT); mutex_lock_nested(&p1->d_inode->i_mutex, I_MUTEX_CHILD); return p; } p = d_ancestor(p1, p2); if (p) { mutex_lock_nested(&p1->d_inode->i_mutex, I_MUTEX_PARENT); mutex_lock_nested(&p2->d_inode->i_mutex, I_MUTEX_CHILD); return p; } mutex_lock_nested(&p1->d_inode->i_mutex, I_MUTEX_PARENT); mutex_lock_nested(&p2->d_inode->i_mutex, I_MUTEX_CHILD); return NULL; } EXPORT_SYMBOL(lock_rename); void unlock_rename(struct dentry *p1, struct dentry *p2) { mutex_unlock(&p1->d_inode->i_mutex); if (p1 != p2) { mutex_unlock(&p2->d_inode->i_mutex); mutex_unlock(&p1->d_inode->i_sb->s_vfs_rename_mutex); } } EXPORT_SYMBOL(unlock_rename); int vfs_create(struct inode *dir, struct dentry *dentry, umode_t mode, bool want_excl) { int error = may_create(dir, dentry); if (error) return error; if (!dir->i_op->create) return -EACCES; /* shouldn't it be ENOSYS? */ mode &= S_IALLUGO; mode |= S_IFREG; error = security_inode_create(dir, dentry, mode); if (error) return error; error = dir->i_op->create(dir, dentry, mode, want_excl); if (!error) fsnotify_create(dir, dentry); return error; } EXPORT_SYMBOL(vfs_create); static int may_open(struct path *path, int acc_mode, int flag) { struct dentry *dentry = path->dentry; struct inode *inode = dentry->d_inode; int error; /* O_PATH? */ if (!acc_mode) return 0; if (!inode) return -ENOENT; switch (inode->i_mode & S_IFMT) { case S_IFLNK: return -ELOOP; case S_IFDIR: if (acc_mode & MAY_WRITE) return -EISDIR; break; case S_IFBLK: case S_IFCHR: if (path->mnt->mnt_flags & MNT_NODEV) return -EACCES; /*FALLTHRU*/ case S_IFIFO: case S_IFSOCK: flag &= ~O_TRUNC; break; } error = inode_permission(inode, acc_mode); if (error) return error; /* * An append-only file must be opened in append mode for writing. */ if (IS_APPEND(inode)) { if ((flag & O_ACCMODE) != O_RDONLY && !(flag & O_APPEND)) return -EPERM; if (flag & O_TRUNC) return -EPERM; } /* O_NOATIME can only be set by the owner or superuser */ if (flag & O_NOATIME && !inode_owner_or_capable(inode)) return -EPERM; return 0; } static int handle_truncate(struct file *filp) { struct path *path = &filp->f_path; struct inode *inode = path->dentry->d_inode; int error = get_write_access(inode); if (error) return error; /* * Refuse to truncate files with mandatory locks held on them. */ error = locks_verify_locked(filp); if (!error) error = security_path_truncate(path); if (!error) { error = do_truncate(path->dentry, 0, ATTR_MTIME|ATTR_CTIME|ATTR_OPEN, filp); } put_write_access(inode); return error; } static inline int open_to_namei_flags(int flag) { if ((flag & O_ACCMODE) == 3) flag--; return flag; } static int may_o_create(struct path *dir, struct dentry *dentry, umode_t mode) { int error = security_path_mknod(dir, dentry, mode, 0); if (error) return error; error = inode_permission(dir->dentry->d_inode, MAY_WRITE | MAY_EXEC); if (error) return error; return security_inode_create(dir->dentry->d_inode, dentry, mode); } /* * Attempt to atomically look up, create and open a file from a negative * dentry. * * Returns 0 if successful. The file will have been created and attached to * @file by the filesystem calling finish_open(). * * Returns 1 if the file was looked up only or didn't need creating. The * caller will need to perform the open themselves. @path will have been * updated to point to the new dentry. This may be negative. * * Returns an error code otherwise. */ static int atomic_open(struct nameidata *nd, struct dentry *dentry, struct path *path, struct file *file, const struct open_flags *op, bool got_write, bool need_lookup, int *opened) { struct inode *dir = nd->path.dentry->d_inode; unsigned open_flag = open_to_namei_flags(op->open_flag); umode_t mode; int error; int acc_mode; int create_error = 0; struct dentry *const DENTRY_NOT_SET = (void *) -1UL; bool excl; BUG_ON(dentry->d_inode); /* Don't create child dentry for a dead directory. */ if (unlikely(IS_DEADDIR(dir))) { error = -ENOENT; goto out; } mode = op->mode; if ((open_flag & O_CREAT) && !IS_POSIXACL(dir)) mode &= ~current_umask(); excl = (open_flag & (O_EXCL | O_CREAT)) == (O_EXCL | O_CREAT); if (excl) open_flag &= ~O_TRUNC; /* * Checking write permission is tricky, bacuse we don't know if we are * going to actually need it: O_CREAT opens should work as long as the * file exists. But checking existence breaks atomicity. The trick is * to check access and if not granted clear O_CREAT from the flags. * * Another problem is returing the "right" error value (e.g. for an * O_EXCL open we want to return EEXIST not EROFS). */ if (((open_flag & (O_CREAT | O_TRUNC)) || (open_flag & O_ACCMODE) != O_RDONLY) && unlikely(!got_write)) { if (!(open_flag & O_CREAT)) { /* * No O_CREATE -> atomicity not a requirement -> fall * back to lookup + open */ goto no_open; } else if (open_flag & (O_EXCL | O_TRUNC)) { /* Fall back and fail with the right error */ create_error = -EROFS; goto no_open; } else { /* No side effects, safe to clear O_CREAT */ create_error = -EROFS; open_flag &= ~O_CREAT; } } if (open_flag & O_CREAT) { error = may_o_create(&nd->path, dentry, mode); if (error) { create_error = error; if (open_flag & O_EXCL) goto no_open; open_flag &= ~O_CREAT; } } if (nd->flags & LOOKUP_DIRECTORY) open_flag |= O_DIRECTORY; file->f_path.dentry = DENTRY_NOT_SET; file->f_path.mnt = nd->path.mnt; error = dir->i_op->atomic_open(dir, dentry, file, open_flag, mode, opened); if (error < 0) { if (create_error && error == -ENOENT) error = create_error; goto out; } if (error) { /* returned 1, that is */ if (WARN_ON(file->f_path.dentry == DENTRY_NOT_SET)) { error = -EIO; goto out; } if (file->f_path.dentry) { dput(dentry); dentry = file->f_path.dentry; } if (*opened & FILE_CREATED) fsnotify_create(dir, dentry); if (!dentry->d_inode) { WARN_ON(*opened & FILE_CREATED); if (create_error) { error = create_error; goto out; } } else { if (excl && !(*opened & FILE_CREATED)) { error = -EEXIST; goto out; } } goto looked_up; } /* * We didn't have the inode before the open, so check open permission * here. */ acc_mode = op->acc_mode; if (*opened & FILE_CREATED) { WARN_ON(!(open_flag & O_CREAT)); fsnotify_create(dir, dentry); acc_mode = MAY_OPEN; } error = may_open(&file->f_path, acc_mode, open_flag); if (error) fput(file); out: dput(dentry); return error; no_open: if (need_lookup) { dentry = lookup_real(dir, dentry, nd->flags); if (IS_ERR(dentry)) return PTR_ERR(dentry); if (create_error) { int open_flag = op->open_flag; error = create_error; if ((open_flag & O_EXCL)) { if (!dentry->d_inode) goto out; } else if (!dentry->d_inode) { goto out; } else if ((open_flag & O_TRUNC) && S_ISREG(dentry->d_inode->i_mode)) { goto out; } /* will fail later, go on to get the right error */ } } looked_up: path->dentry = dentry; path->mnt = nd->path.mnt; return 1; } /* * Look up and maybe create and open the last component. * * Must be called with i_mutex held on parent. * * Returns 0 if the file was successfully atomically created (if necessary) and * opened. In this case the file will be returned attached to @file. * * Returns 1 if the file was not completely opened at this time, though lookups * and creations will have been performed and the dentry returned in @path will * be positive upon return if O_CREAT was specified. If O_CREAT wasn't * specified then a negative dentry may be returned. * * An error code is returned otherwise. * * FILE_CREATE will be set in @*opened if the dentry was created and will be * cleared otherwise prior to returning. */ static int lookup_open(struct nameidata *nd, struct path *path, struct file *file, const struct open_flags *op, bool got_write, int *opened) { struct dentry *dir = nd->path.dentry; struct inode *dir_inode = dir->d_inode; struct dentry *dentry; int error; bool need_lookup; *opened &= ~FILE_CREATED; dentry = lookup_dcache(&nd->last, dir, nd->flags, &need_lookup); if (IS_ERR(dentry)) return PTR_ERR(dentry); /* Cached positive dentry: will open in f_op->open */ if (!need_lookup && dentry->d_inode) goto out_no_open; if ((nd->flags & LOOKUP_OPEN) && dir_inode->i_op->atomic_open) { return atomic_open(nd, dentry, path, file, op, got_write, need_lookup, opened); } if (need_lookup) { BUG_ON(dentry->d_inode); dentry = lookup_real(dir_inode, dentry, nd->flags); if (IS_ERR(dentry)) return PTR_ERR(dentry); } /* Negative dentry, just create the file */ if (!dentry->d_inode && (op->open_flag & O_CREAT)) { umode_t mode = op->mode; if (!IS_POSIXACL(dir->d_inode)) mode &= ~current_umask(); /* * This write is needed to ensure that a * rw->ro transition does not occur between * the time when the file is created and when * a permanent write count is taken through * the 'struct file' in finish_open(). */ if (!got_write) { error = -EROFS; goto out_dput; } *opened |= FILE_CREATED; error = security_path_mknod(&nd->path, dentry, mode, 0); if (error) goto out_dput; error = vfs_create(dir->d_inode, dentry, mode, nd->flags & LOOKUP_EXCL); if (error) goto out_dput; } out_no_open: path->dentry = dentry; path->mnt = nd->path.mnt; return 1; out_dput: dput(dentry); return error; } /* * Handle the last step of open() */ static int do_last(struct nameidata *nd, struct path *path, struct file *file, const struct open_flags *op, int *opened, struct filename *name) { struct dentry *dir = nd->path.dentry; int open_flag = op->open_flag; bool will_truncate = (open_flag & O_TRUNC) != 0; bool got_write = false; int acc_mode = op->acc_mode; struct inode *inode; bool symlink_ok = false; struct path save_parent = { .dentry = NULL, .mnt = NULL }; bool retried = false; int error; nd->flags &= ~LOOKUP_PARENT; nd->flags |= op->intent; if (nd->last_type != LAST_NORM) { error = handle_dots(nd, nd->last_type); if (error) return error; goto finish_open; } if (!(open_flag & O_CREAT)) { if (nd->last.name[nd->last.len]) nd->flags |= LOOKUP_FOLLOW | LOOKUP_DIRECTORY; if (open_flag & O_PATH && !(nd->flags & LOOKUP_FOLLOW)) symlink_ok = true; /* we _can_ be in RCU mode here */ error = lookup_fast(nd, path, &inode); if (likely(!error)) goto finish_lookup; if (error < 0) goto out; BUG_ON(nd->inode != dir->d_inode); } else { /* create side of things */ /* * This will *only* deal with leaving RCU mode - LOOKUP_JUMPED * has been cleared when we got to the last component we are * about to look up */ error = complete_walk(nd); if (error) return error; audit_inode(name, dir, LOOKUP_PARENT); error = -EISDIR; /* trailing slashes? */ if (nd->last.name[nd->last.len]) goto out; } retry_lookup: if (op->open_flag & (O_CREAT | O_TRUNC | O_WRONLY | O_RDWR)) { error = mnt_want_write(nd->path.mnt); if (!error) got_write = true; /* * do _not_ fail yet - we might not need that or fail with * a different error; let lookup_open() decide; we'll be * dropping this one anyway. */ } mutex_lock(&dir->d_inode->i_mutex); error = lookup_open(nd, path, file, op, got_write, opened); mutex_unlock(&dir->d_inode->i_mutex); if (error <= 0) { if (error) goto out; if ((*opened & FILE_CREATED) || !S_ISREG(file_inode(file)->i_mode)) will_truncate = false; audit_inode(name, file->f_path.dentry, 0); goto opened; } if (*opened & FILE_CREATED) { /* Don't check for write permission, don't truncate */ open_flag &= ~O_TRUNC; will_truncate = false; acc_mode = MAY_OPEN; path_to_nameidata(path, nd); goto finish_open_created; } /* * create/update audit record if it already exists. */ if (d_is_positive(path->dentry)) audit_inode(name, path->dentry, 0); /* * If atomic_open() acquired write access it is dropped now due to * possible mount and symlink following (this might be optimized away if * necessary...) */ if (got_write) { mnt_drop_write(nd->path.mnt); got_write = false; } error = -EEXIST; if ((open_flag & (O_EXCL | O_CREAT)) == (O_EXCL | O_CREAT)) goto exit_dput; error = follow_managed(path, nd->flags); if (error < 0) goto exit_dput; if (error) nd->flags |= LOOKUP_JUMPED; BUG_ON(nd->flags & LOOKUP_RCU); inode = path->dentry->d_inode; finish_lookup: /* we _can_ be in RCU mode here */ error = -ENOENT; if (!inode || d_is_negative(path->dentry)) { path_to_nameidata(path, nd); goto out; } if (should_follow_link(path->dentry, !symlink_ok)) { if (nd->flags & LOOKUP_RCU) { if (unlikely(unlazy_walk(nd, path->dentry))) { error = -ECHILD; goto out; } } BUG_ON(inode != path->dentry->d_inode); return 1; } if ((nd->flags & LOOKUP_RCU) || nd->path.mnt != path->mnt) { path_to_nameidata(path, nd); } else { save_parent.dentry = nd->path.dentry; save_parent.mnt = mntget(path->mnt); nd->path.dentry = path->dentry; } nd->inode = inode; /* Why this, you ask? _Now_ we might have grown LOOKUP_JUMPED... */ finish_open: error = complete_walk(nd); if (error) { path_put(&save_parent); return error; } audit_inode(name, nd->path.dentry, 0); error = -EISDIR; if ((open_flag & O_CREAT) && d_is_dir(nd->path.dentry)) goto out; error = -ENOTDIR; if ((nd->flags & LOOKUP_DIRECTORY) && !d_can_lookup(nd->path.dentry)) goto out; if (!S_ISREG(nd->inode->i_mode)) will_truncate = false; if (will_truncate) { error = mnt_want_write(nd->path.mnt); if (error) goto out; got_write = true; } finish_open_created: error = may_open(&nd->path, acc_mode, open_flag); if (error) goto out; file->f_path.mnt = nd->path.mnt; error = finish_open(file, nd->path.dentry, NULL, opened); if (error) { if (error == -EOPENSTALE) goto stale_open; goto out; } opened: error = open_check_o_direct(file); if (error) goto exit_fput; error = ima_file_check(file, op->acc_mode); if (error) goto exit_fput; if (will_truncate) { error = handle_truncate(file); if (error) goto exit_fput; } out: if (got_write) mnt_drop_write(nd->path.mnt); path_put(&save_parent); terminate_walk(nd); return error; exit_dput: path_put_conditional(path, nd); goto out; exit_fput: fput(file); goto out; stale_open: /* If no saved parent or already retried then can't retry */ if (!save_parent.dentry || retried) goto out; BUG_ON(save_parent.dentry != dir); path_put(&nd->path); nd->path = save_parent; nd->inode = dir->d_inode; save_parent.mnt = NULL; save_parent.dentry = NULL; if (got_write) { mnt_drop_write(nd->path.mnt); got_write = false; } retried = true; goto retry_lookup; } static int do_tmpfile(int dfd, struct filename *pathname, struct nameidata *nd, int flags, const struct open_flags *op, struct file *file, int *opened) { static const struct qstr name = QSTR_INIT("/", 1); struct dentry *dentry, *child; struct inode *dir; int error = path_lookupat(dfd, pathname->name, flags | LOOKUP_DIRECTORY, nd); if (unlikely(error)) return error; error = mnt_want_write(nd->path.mnt); if (unlikely(error)) goto out; /* we want directory to be writable */ error = inode_permission(nd->inode, MAY_WRITE | MAY_EXEC); if (error) goto out2; dentry = nd->path.dentry; dir = dentry->d_inode; if (!dir->i_op->tmpfile) { error = -EOPNOTSUPP; goto out2; } child = d_alloc(dentry, &name); if (unlikely(!child)) { error = -ENOMEM; goto out2; } nd->flags &= ~LOOKUP_DIRECTORY; nd->flags |= op->intent; dput(nd->path.dentry); nd->path.dentry = child; error = dir->i_op->tmpfile(dir, nd->path.dentry, op->mode); if (error) goto out2; audit_inode(pathname, nd->path.dentry, 0); error = may_open(&nd->path, op->acc_mode, op->open_flag); if (error) goto out2; file->f_path.mnt = nd->path.mnt; error = finish_open(file, nd->path.dentry, NULL, opened); if (error) goto out2; error = open_check_o_direct(file); if (error) { fput(file); } else if (!(op->open_flag & O_EXCL)) { struct inode *inode = file_inode(file); spin_lock(&inode->i_lock); inode->i_state |= I_LINKABLE; spin_unlock(&inode->i_lock); } out2: mnt_drop_write(nd->path.mnt); out: path_put(&nd->path); return error; } 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; } struct file *do_filp_open(int dfd, struct filename *pathname, const struct open_flags *op) { struct nameidata nd; int flags = op->lookup_flags; struct file *filp; filp = path_openat(dfd, pathname, &nd, op, flags | LOOKUP_RCU); if (unlikely(filp == ERR_PTR(-ECHILD))) filp = path_openat(dfd, pathname, &nd, op, flags); if (unlikely(filp == ERR_PTR(-ESTALE))) filp = path_openat(dfd, pathname, &nd, op, flags | LOOKUP_REVAL); return filp; } struct file *do_file_open_root(struct dentry *dentry, struct vfsmount *mnt, const char *name, const struct open_flags *op) { struct nameidata nd; struct file *file; struct filename filename = { .name = name }; int flags = op->lookup_flags | LOOKUP_ROOT; nd.root.mnt = mnt; nd.root.dentry = dentry; if (d_is_symlink(dentry) && op->intent & LOOKUP_OPEN) return ERR_PTR(-ELOOP); file = path_openat(-1, &filename, &nd, op, flags | LOOKUP_RCU); if (unlikely(file == ERR_PTR(-ECHILD))) file = path_openat(-1, &filename, &nd, op, flags); if (unlikely(file == ERR_PTR(-ESTALE))) file = path_openat(-1, &filename, &nd, op, flags | LOOKUP_REVAL); return file; } struct dentry *kern_path_create(int dfd, const char *pathname, struct path *path, unsigned int lookup_flags) { struct dentry *dentry = ERR_PTR(-EEXIST); struct nameidata nd; int err2; int error; bool is_dir = (lookup_flags & LOOKUP_DIRECTORY); /* * Note that only LOOKUP_REVAL and LOOKUP_DIRECTORY matter here. Any * other flags passed in are ignored! */ lookup_flags &= LOOKUP_REVAL; error = do_path_lookup(dfd, pathname, LOOKUP_PARENT|lookup_flags, &nd); if (error) return ERR_PTR(error); /* * Yucky last component or no last component at all? * (foo/., foo/.., /////) */ if (nd.last_type != LAST_NORM) goto out; nd.flags &= ~LOOKUP_PARENT; nd.flags |= LOOKUP_CREATE | LOOKUP_EXCL; /* don't fail immediately if it's r/o, at least try to report other errors */ err2 = mnt_want_write(nd.path.mnt); /* * Do the final lookup. */ mutex_lock_nested(&nd.path.dentry->d_inode->i_mutex, I_MUTEX_PARENT); dentry = lookup_hash(&nd); if (IS_ERR(dentry)) goto unlock; error = -EEXIST; if (d_is_positive(dentry)) goto fail; /* * Special case - lookup gave negative, but... we had foo/bar/ * From the vfs_mknod() POV we just have a negative dentry - * all is fine. Let's be bastards - you had / on the end, you've * been asking for (non-existent) directory. -ENOENT for you. */ if (unlikely(!is_dir && nd.last.name[nd.last.len])) { error = -ENOENT; goto fail; } if (unlikely(err2)) { error = err2; goto fail; } *path = nd.path; return dentry; fail: dput(dentry); dentry = ERR_PTR(error); unlock: mutex_unlock(&nd.path.dentry->d_inode->i_mutex); if (!err2) mnt_drop_write(nd.path.mnt); out: path_put(&nd.path); return dentry; } EXPORT_SYMBOL(kern_path_create); void done_path_create(struct path *path, struct dentry *dentry) { dput(dentry); mutex_unlock(&path->dentry->d_inode->i_mutex); mnt_drop_write(path->mnt); path_put(path); } EXPORT_SYMBOL(done_path_create); struct dentry *user_path_create(int dfd, const char __user *pathname, struct path *path, unsigned int lookup_flags) { struct filename *tmp = getname(pathname); struct dentry *res; if (IS_ERR(tmp)) return ERR_CAST(tmp); res = kern_path_create(dfd, tmp->name, path, lookup_flags); putname(tmp); return res; } EXPORT_SYMBOL(user_path_create); int vfs_mknod(struct inode *dir, struct dentry *dentry, umode_t mode, dev_t dev) { int error = may_create(dir, dentry); if (error) return error; if ((S_ISCHR(mode) || S_ISBLK(mode)) && !capable(CAP_MKNOD)) return -EPERM; if (!dir->i_op->mknod) return -EPERM; error = devcgroup_inode_mknod(mode, dev); if (error) return error; error = security_inode_mknod(dir, dentry, mode, dev); if (error) return error; error = dir->i_op->mknod(dir, dentry, mode, dev); if (!error) fsnotify_create(dir, dentry); return error; } EXPORT_SYMBOL(vfs_mknod); static int may_mknod(umode_t mode) { switch (mode & S_IFMT) { case S_IFREG: case S_IFCHR: case S_IFBLK: case S_IFIFO: case S_IFSOCK: case 0: /* zero mode translates to S_IFREG */ return 0; case S_IFDIR: return -EPERM; default: return -EINVAL; } } SYSCALL_DEFINE4(mknodat, int, dfd, const char __user *, filename, umode_t, mode, unsigned, dev) { struct dentry *dentry; struct path path; int error; unsigned int lookup_flags = 0; error = may_mknod(mode); if (error) return error; retry: dentry = user_path_create(dfd, filename, &path, lookup_flags); if (IS_ERR(dentry)) return PTR_ERR(dentry); if (!IS_POSIXACL(path.dentry->d_inode)) mode &= ~current_umask(); error = security_path_mknod(&path, dentry, mode, dev); if (error) goto out; switch (mode & S_IFMT) { case 0: case S_IFREG: error = vfs_create(path.dentry->d_inode,dentry,mode,true); break; case S_IFCHR: case S_IFBLK: error = vfs_mknod(path.dentry->d_inode,dentry,mode, new_decode_dev(dev)); break; case S_IFIFO: case S_IFSOCK: error = vfs_mknod(path.dentry->d_inode,dentry,mode,0); break; } out: done_path_create(&path, dentry); if (retry_estale(error, lookup_flags)) { lookup_flags |= LOOKUP_REVAL; goto retry; } return error; } SYSCALL_DEFINE3(mknod, const char __user *, filename, umode_t, mode, unsigned, dev) { return sys_mknodat(AT_FDCWD, filename, mode, dev); } int vfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode) { int error = may_create(dir, dentry); unsigned max_links = dir->i_sb->s_max_links; if (error) return error; if (!dir->i_op->mkdir) return -EPERM; mode &= (S_IRWXUGO|S_ISVTX); error = security_inode_mkdir(dir, dentry, mode); if (error) return error; if (max_links && dir->i_nlink >= max_links) return -EMLINK; error = dir->i_op->mkdir(dir, dentry, mode); if (!error) fsnotify_mkdir(dir, dentry); return error; } EXPORT_SYMBOL(vfs_mkdir); SYSCALL_DEFINE3(mkdirat, int, dfd, const char __user *, pathname, umode_t, mode) { struct dentry *dentry; struct path path; int error; unsigned int lookup_flags = LOOKUP_DIRECTORY; retry: dentry = user_path_create(dfd, pathname, &path, lookup_flags); if (IS_ERR(dentry)) return PTR_ERR(dentry); if (!IS_POSIXACL(path.dentry->d_inode)) mode &= ~current_umask(); error = security_path_mkdir(&path, dentry, mode); if (!error) error = vfs_mkdir(path.dentry->d_inode, dentry, mode); done_path_create(&path, dentry); if (retry_estale(error, lookup_flags)) { lookup_flags |= LOOKUP_REVAL; goto retry; } return error; } SYSCALL_DEFINE2(mkdir, const char __user *, pathname, umode_t, mode) { return sys_mkdirat(AT_FDCWD, pathname, mode); } /* * The dentry_unhash() helper will try to drop the dentry early: we * should have a usage count of 1 if we're the only user of this * dentry, and if that is true (possibly after pruning the dcache), * then we drop the dentry now. * * A low-level filesystem can, if it choses, legally * do a * * if (!d_unhashed(dentry)) * return -EBUSY; * * if it cannot handle the case of removing a directory * that is still in use by something else.. */ void dentry_unhash(struct dentry *dentry) { shrink_dcache_parent(dentry); spin_lock(&dentry->d_lock); if (dentry->d_lockref.count == 1) __d_drop(dentry); spin_unlock(&dentry->d_lock); } EXPORT_SYMBOL(dentry_unhash); int vfs_rmdir(struct inode *dir, struct dentry *dentry) { int error = may_delete(dir, dentry, 1); if (error) return error; if (!dir->i_op->rmdir) return -EPERM; dget(dentry); mutex_lock(&dentry->d_inode->i_mutex); error = -EBUSY; if (d_mountpoint(dentry)) goto out; error = security_inode_rmdir(dir, dentry); if (error) goto out; shrink_dcache_parent(dentry); error = dir->i_op->rmdir(dir, dentry); if (error) goto out; dentry->d_inode->i_flags |= S_DEAD; dont_mount(dentry); out: mutex_unlock(&dentry->d_inode->i_mutex); dput(dentry); if (!error) d_delete(dentry); return error; } EXPORT_SYMBOL(vfs_rmdir); static long do_rmdir(int dfd, const char __user *pathname) { int error = 0; struct filename *name; struct dentry *dentry; struct nameidata nd; unsigned int lookup_flags = 0; retry: name = user_path_parent(dfd, pathname, &nd, lookup_flags); if (IS_ERR(name)) return PTR_ERR(name); switch(nd.last_type) { case LAST_DOTDOT: error = -ENOTEMPTY; goto exit1; case LAST_DOT: error = -EINVAL; goto exit1; case LAST_ROOT: error = -EBUSY; goto exit1; } nd.flags &= ~LOOKUP_PARENT; error = mnt_want_write(nd.path.mnt); if (error) goto exit1; mutex_lock_nested(&nd.path.dentry->d_inode->i_mutex, I_MUTEX_PARENT); dentry = lookup_hash(&nd); error = PTR_ERR(dentry); if (IS_ERR(dentry)) goto exit2; if (!dentry->d_inode) { error = -ENOENT; goto exit3; } error = security_path_rmdir(&nd.path, dentry); if (error) goto exit3; error = vfs_rmdir(nd.path.dentry->d_inode, dentry); exit3: dput(dentry); exit2: mutex_unlock(&nd.path.dentry->d_inode->i_mutex); mnt_drop_write(nd.path.mnt); exit1: path_put(&nd.path); putname(name); if (retry_estale(error, lookup_flags)) { lookup_flags |= LOOKUP_REVAL; goto retry; } return error; } SYSCALL_DEFINE1(rmdir, const char __user *, pathname) { return do_rmdir(AT_FDCWD, pathname); } /** * vfs_unlink - unlink a filesystem object * @dir: parent directory * @dentry: victim * @delegated_inode: returns victim inode, if the inode is delegated. * * The caller must hold dir->i_mutex. * * If vfs_unlink discovers a delegation, it will return -EWOULDBLOCK and * return a reference to the inode in delegated_inode. The caller * should then break the delegation on that inode and retry. Because * breaking a delegation may take a long time, the caller should drop * dir->i_mutex before doing so. * * Alternatively, a caller may pass NULL for delegated_inode. This may * be appropriate for callers that expect the underlying filesystem not * to be NFS exported. */ int vfs_unlink(struct inode *dir, struct dentry *dentry, struct inode **delegated_inode) { struct inode *target = dentry->d_inode; int error = may_delete(dir, dentry, 0); if (error) return error; if (!dir->i_op->unlink) return -EPERM; mutex_lock(&target->i_mutex); if (d_mountpoint(dentry)) error = -EBUSY; else { error = security_inode_unlink(dir, dentry); if (!error) { error = try_break_deleg(target, delegated_inode); if (error) goto out; error = dir->i_op->unlink(dir, dentry); if (!error) dont_mount(dentry); } } out: mutex_unlock(&target->i_mutex); /* We don't d_delete() NFS sillyrenamed files--they still exist. */ if (!error && !(dentry->d_flags & DCACHE_NFSFS_RENAMED)) { fsnotify_link_count(target); d_delete(dentry); } return error; } EXPORT_SYMBOL(vfs_unlink); /* * Make sure that the actual truncation of the file will occur outside its * directory's i_mutex. Truncate can take a long time if there is a lot of * writeout happening, and we don't want to prevent access to the directory * while waiting on the I/O. */ static long do_unlinkat(int dfd, const char __user *pathname) { int error; struct filename *name; struct dentry *dentry; struct nameidata nd; struct inode *inode = NULL; struct inode *delegated_inode = NULL; unsigned int lookup_flags = 0; retry: name = user_path_parent(dfd, pathname, &nd, lookup_flags); if (IS_ERR(name)) return PTR_ERR(name); error = -EISDIR; if (nd.last_type != LAST_NORM) goto exit1; nd.flags &= ~LOOKUP_PARENT; error = mnt_want_write(nd.path.mnt); if (error) goto exit1; retry_deleg: mutex_lock_nested(&nd.path.dentry->d_inode->i_mutex, I_MUTEX_PARENT); dentry = lookup_hash(&nd); error = PTR_ERR(dentry); if (!IS_ERR(dentry)) { /* Why not before? Because we want correct error value */ if (nd.last.name[nd.last.len]) goto slashes; inode = dentry->d_inode; if (d_is_negative(dentry)) goto slashes; ihold(inode); error = security_path_unlink(&nd.path, dentry); if (error) goto exit2; error = vfs_unlink(nd.path.dentry->d_inode, dentry, &delegated_inode); exit2: dput(dentry); } mutex_unlock(&nd.path.dentry->d_inode->i_mutex); if (inode) iput(inode); /* truncate the inode here */ inode = NULL; if (delegated_inode) { error = break_deleg_wait(&delegated_inode); if (!error) goto retry_deleg; } mnt_drop_write(nd.path.mnt); exit1: path_put(&nd.path); putname(name); if (retry_estale(error, lookup_flags)) { lookup_flags |= LOOKUP_REVAL; inode = NULL; goto retry; } return error; slashes: if (d_is_negative(dentry)) error = -ENOENT; else if (d_is_dir(dentry)) error = -EISDIR; else error = -ENOTDIR; goto exit2; } SYSCALL_DEFINE3(unlinkat, int, dfd, const char __user *, pathname, int, flag) { if ((flag & ~AT_REMOVEDIR) != 0) return -EINVAL; if (flag & AT_REMOVEDIR) return do_rmdir(dfd, pathname); return do_unlinkat(dfd, pathname); } SYSCALL_DEFINE1(unlink, const char __user *, pathname) { return do_unlinkat(AT_FDCWD, pathname); } int vfs_symlink(struct inode *dir, struct dentry *dentry, const char *oldname) { int error = may_create(dir, dentry); if (error) return error; if (!dir->i_op->symlink) return -EPERM; error = security_inode_symlink(dir, dentry, oldname); if (error) return error; error = dir->i_op->symlink(dir, dentry, oldname); if (!error) fsnotify_create(dir, dentry); return error; } EXPORT_SYMBOL(vfs_symlink); SYSCALL_DEFINE3(symlinkat, const char __user *, oldname, int, newdfd, const char __user *, newname) { int error; struct filename *from; struct dentry *dentry; struct path path; unsigned int lookup_flags = 0; from = getname(oldname); if (IS_ERR(from)) return PTR_ERR(from); retry: dentry = user_path_create(newdfd, newname, &path, lookup_flags); error = PTR_ERR(dentry); if (IS_ERR(dentry)) goto out_putname; error = security_path_symlink(&path, dentry, from->name); if (!error) error = vfs_symlink(path.dentry->d_inode, dentry, from->name); done_path_create(&path, dentry); if (retry_estale(error, lookup_flags)) { lookup_flags |= LOOKUP_REVAL; goto retry; } out_putname: putname(from); return error; } SYSCALL_DEFINE2(symlink, const char __user *, oldname, const char __user *, newname) { return sys_symlinkat(oldname, AT_FDCWD, newname); } /** * vfs_link - create a new link * @old_dentry: object to be linked * @dir: new parent * @new_dentry: where to create the new link * @delegated_inode: returns inode needing a delegation break * * The caller must hold dir->i_mutex * * If vfs_link discovers a delegation on the to-be-linked file in need * of breaking, it will return -EWOULDBLOCK and return a reference to the * inode in delegated_inode. The caller should then break the delegation * and retry. Because breaking a delegation may take a long time, the * caller should drop the i_mutex before doing so. * * Alternatively, a caller may pass NULL for delegated_inode. This may * be appropriate for callers that expect the underlying filesystem not * to be NFS exported. */ int vfs_link(struct dentry *old_dentry, struct inode *dir, struct dentry *new_dentry, struct inode **delegated_inode) { struct inode *inode = old_dentry->d_inode; unsigned max_links = dir->i_sb->s_max_links; int error; if (!inode) return -ENOENT; error = may_create(dir, new_dentry); if (error) return error; if (dir->i_sb != inode->i_sb) return -EXDEV; /* * A link to an append-only or immutable file cannot be created. */ if (IS_APPEND(inode) || IS_IMMUTABLE(inode)) return -EPERM; if (!dir->i_op->link) return -EPERM; if (S_ISDIR(inode->i_mode)) return -EPERM; error = security_inode_link(old_dentry, dir, new_dentry); if (error) return error; mutex_lock(&inode->i_mutex); /* Make sure we don't allow creating hardlink to an unlinked file */ if (inode->i_nlink == 0 && !(inode->i_state & I_LINKABLE)) error = -ENOENT; else if (max_links && inode->i_nlink >= max_links) error = -EMLINK; else { error = try_break_deleg(inode, delegated_inode); if (!error) error = dir->i_op->link(old_dentry, dir, new_dentry); } if (!error && (inode->i_state & I_LINKABLE)) { spin_lock(&inode->i_lock); inode->i_state &= ~I_LINKABLE; spin_unlock(&inode->i_lock); } mutex_unlock(&inode->i_mutex); if (!error) fsnotify_link(dir, inode, new_dentry); return error; } EXPORT_SYMBOL(vfs_link); /* * Hardlinks are often used in delicate situations. We avoid * security-related surprises by not following symlinks on the * newname. --KAB * * We don't follow them on the oldname either to be compatible * with linux 2.0, and to avoid hard-linking to directories * and other special files. --ADM */ SYSCALL_DEFINE5(linkat, int, olddfd, const char __user *, oldname, int, newdfd, const char __user *, newname, int, flags) { struct dentry *new_dentry; struct path old_path, new_path; struct inode *delegated_inode = NULL; int how = 0; int error; if ((flags & ~(AT_SYMLINK_FOLLOW | AT_EMPTY_PATH)) != 0) return -EINVAL; /* * To use null names we require CAP_DAC_READ_SEARCH * This ensures that not everyone will be able to create * handlink using the passed filedescriptor. */ if (flags & AT_EMPTY_PATH) { if (!capable(CAP_DAC_READ_SEARCH)) return -ENOENT; how = LOOKUP_EMPTY; } if (flags & AT_SYMLINK_FOLLOW) how |= LOOKUP_FOLLOW; retry: error = user_path_at(olddfd, oldname, how, &old_path); if (error) return error; new_dentry = user_path_create(newdfd, newname, &new_path, (how & LOOKUP_REVAL)); error = PTR_ERR(new_dentry); if (IS_ERR(new_dentry)) goto out; error = -EXDEV; if (old_path.mnt != new_path.mnt) goto out_dput; error = may_linkat(&old_path); if (unlikely(error)) goto out_dput; error = security_path_link(old_path.dentry, &new_path, new_dentry); if (error) goto out_dput; error = vfs_link(old_path.dentry, new_path.dentry->d_inode, new_dentry, &delegated_inode); out_dput: done_path_create(&new_path, new_dentry); if (delegated_inode) { error = break_deleg_wait(&delegated_inode); if (!error) { path_put(&old_path); goto retry; } } if (retry_estale(error, how)) { path_put(&old_path); how |= LOOKUP_REVAL; goto retry; } out: path_put(&old_path); return error; } SYSCALL_DEFINE2(link, const char __user *, oldname, const char __user *, newname) { return sys_linkat(AT_FDCWD, oldname, AT_FDCWD, newname, 0); } /** * vfs_rename - rename a filesystem object * @old_dir: parent of source * @old_dentry: source * @new_dir: parent of destination * @new_dentry: destination * @delegated_inode: returns an inode needing a delegation break * @flags: rename flags * * The caller must hold multiple mutexes--see lock_rename()). * * If vfs_rename discovers a delegation in need of breaking at either * the source or destination, it will return -EWOULDBLOCK and return a * reference to the inode in delegated_inode. The caller should then * break the delegation and retry. Because breaking a delegation may * take a long time, the caller should drop all locks before doing * so. * * Alternatively, a caller may pass NULL for delegated_inode. This may * be appropriate for callers that expect the underlying filesystem not * to be NFS exported. * * The worst of all namespace operations - renaming directory. "Perverted" * doesn't even start to describe it. Somebody in UCB had a heck of a trip... * Problems: * a) we can get into loop creation. Check is done in is_subdir(). * b) race potential - two innocent renames can create a loop together. * That's where 4.4 screws up. Current fix: serialization on * sb->s_vfs_rename_mutex. We might be more accurate, but that's another * story. * c) we have to lock _four_ objects - parents and victim (if it exists), * and source (if it is not a directory). * And that - after we got ->i_mutex on parents (until then we don't know * whether the target exists). Solution: try to be smart with locking * order for inodes. We rely on the fact that tree topology may change * only under ->s_vfs_rename_mutex _and_ that parent of the object we * move will be locked. Thus we can rank directories by the tree * (ancestors first) and rank all non-directories after them. * That works since everybody except rename does "lock parent, lookup, * lock child" and rename is under ->s_vfs_rename_mutex. * HOWEVER, it relies on the assumption that any object with ->lookup() * has no more than 1 dentry. If "hybrid" objects will ever appear, * we'd better make sure that there's no link(2) for them. * d) conversion from fhandle to dentry may come in the wrong moment - when * we are removing the target. Solution: we will have to grab ->i_mutex * in the fhandle_to_dentry code. [FIXME - current nfsfh.c relies on * ->i_mutex on parents, which works but leads to some truly excessive * locking]. */ int vfs_rename(struct inode *old_dir, struct dentry *old_dentry, struct inode *new_dir, struct dentry *new_dentry, struct inode **delegated_inode, unsigned int flags) { int error; bool is_dir = d_is_dir(old_dentry); const unsigned char *old_name; struct inode *source = old_dentry->d_inode; struct inode *target = new_dentry->d_inode; bool new_is_dir = false; unsigned max_links = new_dir->i_sb->s_max_links; if (source == target) return 0; error = may_delete(old_dir, old_dentry, is_dir); if (error) return error; if (!target) { error = may_create(new_dir, new_dentry); } else { new_is_dir = d_is_dir(new_dentry); if (!(flags & RENAME_EXCHANGE)) error = may_delete(new_dir, new_dentry, is_dir); else error = may_delete(new_dir, new_dentry, new_is_dir); } if (error) return error; if (!old_dir->i_op->rename) return -EPERM; if (flags && !old_dir->i_op->rename2) return -EINVAL; /* * If we are going to change the parent - check write permissions, * we'll need to flip '..'. */ if (new_dir != old_dir) { if (is_dir) { error = inode_permission(source, MAY_WRITE); if (error) return error; } if ((flags & RENAME_EXCHANGE) && new_is_dir) { error = inode_permission(target, MAY_WRITE); if (error) return error; } } error = security_inode_rename(old_dir, old_dentry, new_dir, new_dentry, flags); if (error) return error; old_name = fsnotify_oldname_init(old_dentry->d_name.name); dget(new_dentry); if (!is_dir || (flags & RENAME_EXCHANGE)) lock_two_nondirectories(source, target); else if (target) mutex_lock(&target->i_mutex); error = -EBUSY; if (d_mountpoint(old_dentry) || d_mountpoint(new_dentry)) goto out; if (max_links && new_dir != old_dir) { error = -EMLINK; if (is_dir && !new_is_dir && new_dir->i_nlink >= max_links) goto out; if ((flags & RENAME_EXCHANGE) && !is_dir && new_is_dir && old_dir->i_nlink >= max_links) goto out; } if (is_dir && !(flags & RENAME_EXCHANGE) && target) shrink_dcache_parent(new_dentry); if (!is_dir) { error = try_break_deleg(source, delegated_inode); if (error) goto out; } if (target && !new_is_dir) { error = try_break_deleg(target, delegated_inode); if (error) goto out; } if (!flags) { error = old_dir->i_op->rename(old_dir, old_dentry, new_dir, new_dentry); } else { error = old_dir->i_op->rename2(old_dir, old_dentry, new_dir, new_dentry, flags); } if (error) goto out; if (!(flags & RENAME_EXCHANGE) && target) { if (is_dir) target->i_flags |= S_DEAD; dont_mount(new_dentry); } if (!(old_dir->i_sb->s_type->fs_flags & FS_RENAME_DOES_D_MOVE)) { if (!(flags & RENAME_EXCHANGE)) d_move(old_dentry, new_dentry); else d_exchange(old_dentry, new_dentry); } out: if (!is_dir || (flags & RENAME_EXCHANGE)) unlock_two_nondirectories(source, target); else if (target) mutex_unlock(&target->i_mutex); dput(new_dentry); if (!error) { fsnotify_move(old_dir, new_dir, old_name, is_dir, !(flags & RENAME_EXCHANGE) ? target : NULL, old_dentry); if (flags & RENAME_EXCHANGE) { fsnotify_move(new_dir, old_dir, old_dentry->d_name.name, new_is_dir, NULL, new_dentry); } } fsnotify_oldname_free(old_name); return error; } EXPORT_SYMBOL(vfs_rename); SYSCALL_DEFINE5(renameat2, int, olddfd, const char __user *, oldname, int, newdfd, const char __user *, newname, unsigned int, flags) { struct dentry *old_dir, *new_dir; struct dentry *old_dentry, *new_dentry; struct dentry *trap; struct nameidata oldnd, newnd; struct inode *delegated_inode = NULL; struct filename *from; struct filename *to; unsigned int lookup_flags = 0; bool should_retry = false; int error; if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE)) return -EINVAL; if ((flags & RENAME_NOREPLACE) && (flags & RENAME_EXCHANGE)) return -EINVAL; retry: from = user_path_parent(olddfd, oldname, &oldnd, lookup_flags); if (IS_ERR(from)) { error = PTR_ERR(from); goto exit; } to = user_path_parent(newdfd, newname, &newnd, lookup_flags); if (IS_ERR(to)) { error = PTR_ERR(to); goto exit1; } error = -EXDEV; if (oldnd.path.mnt != newnd.path.mnt) goto exit2; old_dir = oldnd.path.dentry; error = -EBUSY; if (oldnd.last_type != LAST_NORM) goto exit2; new_dir = newnd.path.dentry; if (flags & RENAME_NOREPLACE) error = -EEXIST; if (newnd.last_type != LAST_NORM) goto exit2; error = mnt_want_write(oldnd.path.mnt); if (error) goto exit2; oldnd.flags &= ~LOOKUP_PARENT; newnd.flags &= ~LOOKUP_PARENT; if (!(flags & RENAME_EXCHANGE)) newnd.flags |= LOOKUP_RENAME_TARGET; retry_deleg: trap = lock_rename(new_dir, old_dir); old_dentry = lookup_hash(&oldnd); error = PTR_ERR(old_dentry); if (IS_ERR(old_dentry)) goto exit3; /* source must exist */ error = -ENOENT; if (d_is_negative(old_dentry)) goto exit4; new_dentry = lookup_hash(&newnd); error = PTR_ERR(new_dentry); if (IS_ERR(new_dentry)) goto exit4; error = -EEXIST; if ((flags & RENAME_NOREPLACE) && d_is_positive(new_dentry)) goto exit5; if (flags & RENAME_EXCHANGE) { error = -ENOENT; if (d_is_negative(new_dentry)) goto exit5; if (!d_is_dir(new_dentry)) { error = -ENOTDIR; if (newnd.last.name[newnd.last.len]) goto exit5; } } /* unless the source is a directory trailing slashes give -ENOTDIR */ if (!d_is_dir(old_dentry)) { error = -ENOTDIR; if (oldnd.last.name[oldnd.last.len]) goto exit5; if (!(flags & RENAME_EXCHANGE) && newnd.last.name[newnd.last.len]) goto exit5; } /* source should not be ancestor of target */ error = -EINVAL; if (old_dentry == trap) goto exit5; /* target should not be an ancestor of source */ if (!(flags & RENAME_EXCHANGE)) error = -ENOTEMPTY; if (new_dentry == trap) goto exit5; error = security_path_rename(&oldnd.path, old_dentry, &newnd.path, new_dentry, flags); if (error) goto exit5; error = vfs_rename(old_dir->d_inode, old_dentry, new_dir->d_inode, new_dentry, &delegated_inode, flags); exit5: dput(new_dentry); exit4: dput(old_dentry); exit3: unlock_rename(new_dir, old_dir); if (delegated_inode) { error = break_deleg_wait(&delegated_inode); if (!error) goto retry_deleg; } mnt_drop_write(oldnd.path.mnt); exit2: if (retry_estale(error, lookup_flags)) should_retry = true; path_put(&newnd.path); putname(to); exit1: path_put(&oldnd.path); putname(from); if (should_retry) { should_retry = false; lookup_flags |= LOOKUP_REVAL; goto retry; } exit: return error; } SYSCALL_DEFINE4(renameat, int, olddfd, const char __user *, oldname, int, newdfd, const char __user *, newname) { return sys_renameat2(olddfd, oldname, newdfd, newname, 0); } SYSCALL_DEFINE2(rename, const char __user *, oldname, const char __user *, newname) { return sys_renameat2(AT_FDCWD, oldname, AT_FDCWD, newname, 0); } int readlink_copy(char __user *buffer, int buflen, const char *link) { int len = PTR_ERR(link); if (IS_ERR(link)) goto out; len = strlen(link); if (len > (unsigned) buflen) len = buflen; if (copy_to_user(buffer, link, len)) len = -EFAULT; out: return len; } EXPORT_SYMBOL(readlink_copy); /* * A helper for ->readlink(). This should be used *ONLY* for symlinks that * have ->follow_link() touching nd only in nd_set_link(). Using (or not * using) it for any given inode is up to filesystem. */ int generic_readlink(struct dentry *dentry, char __user *buffer, int buflen) { struct nameidata nd; void *cookie; int res; nd.depth = 0; cookie = dentry->d_inode->i_op->follow_link(dentry, &nd); if (IS_ERR(cookie)) return PTR_ERR(cookie); res = readlink_copy(buffer, buflen, nd_get_link(&nd)); if (dentry->d_inode->i_op->put_link) dentry->d_inode->i_op->put_link(dentry, &nd, cookie); return res; } EXPORT_SYMBOL(generic_readlink); /* get the link contents into pagecache */ static char *page_getlink(struct dentry * dentry, struct page **ppage) { char *kaddr; struct page *page; struct address_space *mapping = dentry->d_inode->i_mapping; page = read_mapping_page(mapping, 0, NULL); if (IS_ERR(page)) return (char*)page; *ppage = page; kaddr = kmap(page); nd_terminate_link(kaddr, dentry->d_inode->i_size, PAGE_SIZE - 1); return kaddr; } int page_readlink(struct dentry *dentry, char __user *buffer, int buflen) { struct page *page = NULL; int res = readlink_copy(buffer, buflen, page_getlink(dentry, &page)); if (page) { kunmap(page); page_cache_release(page); } return res; } EXPORT_SYMBOL(page_readlink); void *page_follow_link_light(struct dentry *dentry, struct nameidata *nd) { struct page *page = NULL; nd_set_link(nd, page_getlink(dentry, &page)); return page; } EXPORT_SYMBOL(page_follow_link_light); void page_put_link(struct dentry *dentry, struct nameidata *nd, void *cookie) { struct page *page = cookie; if (page) { kunmap(page); page_cache_release(page); } } EXPORT_SYMBOL(page_put_link); /* * The nofs argument instructs pagecache_write_begin to pass AOP_FLAG_NOFS */ int __page_symlink(struct inode *inode, const char *symname, int len, int nofs) { struct address_space *mapping = inode->i_mapping; struct page *page; void *fsdata; int err; char *kaddr; unsigned int flags = AOP_FLAG_UNINTERRUPTIBLE; if (nofs) flags |= AOP_FLAG_NOFS; retry: err = pagecache_write_begin(NULL, mapping, 0, len-1, flags, &page, &fsdata); if (err) goto fail; kaddr = kmap_atomic(page); memcpy(kaddr, symname, len-1); kunmap_atomic(kaddr); err = pagecache_write_end(NULL, mapping, 0, len-1, len-1, page, fsdata); if (err < 0) goto fail; if (err < len-1) goto retry; mark_inode_dirty(inode); return 0; fail: return err; } EXPORT_SYMBOL(__page_symlink); int page_symlink(struct inode *inode, const char *symname, int len) { return __page_symlink(inode, symname, len, !(mapping_gfp_mask(inode->i_mapping) & __GFP_FS)); } EXPORT_SYMBOL(page_symlink); const struct inode_operations page_symlink_inode_operations = { .readlink = generic_readlink, .follow_link = page_follow_link_light, .put_link = page_put_link, }; EXPORT_SYMBOL(page_symlink_inode_operations);
./CrossVul/dataset_final_sorted/CWE-59/c/bad_2241_0
crossvul-cpp_data_bad_436_6
/* * Soft: Vrrpd is an implementation of VRRPv2 as specified in rfc2338. * VRRP is a protocol which elect a master server on a LAN. If the * master fails, a backup server takes over. * The original implementation has been made by jerome etienne. * * Part: Print running VRRP state information * * Author: John Southworth, <john.southworth@vyatta.com> * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. * * Copyright (C) 2012 John Southworth, <john.southworth@vyatta.com> * Copyright (C) 2015-2017 Alexandre Cassen, <acassen@gmail.com> */ #include "config.h" #include <errno.h> #include <inttypes.h> #include "logger.h" #include "vrrp.h" #include "vrrp_data.h" #include "vrrp_print.h" static const char *dump_file = "/tmp/keepalived.data"; static const char *stats_file = "/tmp/keepalived.stats"; void vrrp_print_data(void) { FILE *file = fopen (dump_file, "w"); if (!file) { log_message(LOG_INFO, "Can't open %s (%d: %s)", dump_file, errno, strerror(errno)); return; } dump_data_vrrp(file); fclose(file); } void vrrp_print_stats(void) { FILE *file; file = fopen (stats_file, "w"); if (!file) { log_message(LOG_INFO, "Can't open %s (%d: %s)", stats_file, errno, strerror(errno)); return; } list l = vrrp_data->vrrp; element e; vrrp_t *vrrp; for (e = LIST_HEAD(l); e; ELEMENT_NEXT(e)) { vrrp = ELEMENT_DATA(e); fprintf(file, "VRRP Instance: %s\n", vrrp->iname); fprintf(file, " Advertisements:\n"); fprintf(file, " Received: %" PRIu64 "\n", vrrp->stats->advert_rcvd); fprintf(file, " Sent: %d\n", vrrp->stats->advert_sent); fprintf(file, " Became master: %d\n", vrrp->stats->become_master); fprintf(file, " Released master: %d\n", vrrp->stats->release_master); fprintf(file, " Packet Errors:\n"); fprintf(file, " Length: %" PRIu64 "\n", vrrp->stats->packet_len_err); fprintf(file, " TTL: %" PRIu64 "\n", vrrp->stats->ip_ttl_err); fprintf(file, " Invalid Type: %" PRIu64 "\n", vrrp->stats->invalid_type_rcvd); fprintf(file, " Advertisement Interval: %" PRIu64 "\n", vrrp->stats->advert_interval_err); fprintf(file, " Address List: %" PRIu64 "\n", vrrp->stats->addr_list_err); fprintf(file, " Authentication Errors:\n"); fprintf(file, " Invalid Type: %d\n", vrrp->stats->invalid_authtype); #ifdef _WITH_VRRP_AUTH_ fprintf(file, " Type Mismatch: %d\n", vrrp->stats->authtype_mismatch); fprintf(file, " Failure: %d\n", vrrp->stats->auth_failure); #endif fprintf(file, " Priority Zero:\n"); fprintf(file, " Received: %" PRIu64 "\n", vrrp->stats->pri_zero_rcvd); fprintf(file, " Sent: %" PRIu64 "\n", vrrp->stats->pri_zero_sent); } fclose(file); }
./CrossVul/dataset_final_sorted/CWE-59/c/bad_436_6
crossvul-cpp_data_good_3576_1
/* * internal.c: internal data structures and helpers * * Copyright (C) 2007-2011 David Lutterkort * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: David Lutterkort <dlutter@redhat.com> */ #include <config.h> #include <ctype.h> #include <stdio.h> #include <stdarg.h> #include <locale.h> #include "internal.h" #include "memory.h" #include "fa.h" #ifndef MIN # define MIN(a, b) ((a) < (b) ? (a) : (b)) #endif /* Cap file reads somwhat arbitrarily at 32 MB */ #define MAX_READ_LEN (32*1024*1024) int pathjoin(char **path, int nseg, ...) { va_list ap; va_start(ap, nseg); for (int i=0; i < nseg; i++) { const char *seg = va_arg(ap, const char *); if (seg == NULL) seg = "()"; int len = strlen(seg) + 1; if (*path != NULL) { len += strlen(*path) + 1; if (REALLOC_N(*path, len) == -1) { FREE(*path); return -1; } if (strlen(*path) == 0 || (*path)[strlen(*path)-1] != SEP) strcat(*path, "/"); if (seg[0] == SEP) seg += 1; strcat(*path, seg); } else { if ((*path = malloc(len)) == NULL) return -1; strcpy(*path, seg); } } va_end(ap); return 0; } /* Like gnulib's fread_file, but read no more than the specified maximum number of bytes. If the length of the input is <= max_len, and upon error while reading that data, it works just like fread_file. Taken verbatim from libvirt's util.c */ static char * fread_file_lim (FILE *stream, size_t max_len, size_t *length) { char *buf = NULL; size_t alloc = 0; size_t size = 0; int save_errno; for (;;) { size_t count; size_t requested; if (size + BUFSIZ + 1 > alloc) { char *new_buf; alloc += alloc / 2; if (alloc < size + BUFSIZ + 1) alloc = size + BUFSIZ + 1; new_buf = realloc (buf, alloc); if (!new_buf) { save_errno = errno; break; } buf = new_buf; } /* Ensure that (size + requested <= max_len); */ requested = MIN (size < max_len ? max_len - size : 0, alloc - size - 1); count = fread (buf + size, 1, requested, stream); size += count; if (count != requested || requested == 0) { save_errno = errno; if (ferror (stream)) break; buf[size] = '\0'; *length = size; return buf; } } free (buf); errno = save_errno; return NULL; } char* xfread_file(FILE *fp) { char *result; size_t len; if (!fp) return NULL; result = fread_file_lim(fp, MAX_READ_LEN, &len); if (result != NULL && len <= MAX_READ_LEN && (int) len == len) return result; free(result); return NULL; } char* xread_file(const char *path) { FILE *fp; char *result; fp = fopen(path, "r"); result = xfread_file(fp); fclose (fp); return result; } /* * Escape/unescape of string literals */ static const char *const escape_chars = "\a\b\t\n\v\f\r"; static const char *const escape_names = "abtnvfr"; char *unescape(const char *s, int len, const char *extra) { size_t size; const char *n; char *result, *t; int i; if (len < 0 || len > strlen(s)) len = strlen(s); size = 0; for (i=0; i < len; i++, size++) { if (s[i] == '\\' && strchr(escape_names, s[i+1])) { i += 1; } else if (s[i] == '\\' && extra && strchr(extra, s[i+1])) { i += 1; } } if (ALLOC_N(result, size + 1) < 0) return NULL; for (i = 0, t = result; i < len; i++, size++) { if (s[i] == '\\' && (n = strchr(escape_names, s[i+1])) != NULL) { *t++ = escape_chars[n - escape_names]; i += 1; } else if (s[i] == '\\' && extra && strchr(extra, s[i+1]) != NULL) { *t++ = s[i+1]; i += 1; } else { *t++ = s[i]; } } return result; } char *escape(const char *text, int cnt, const char *extra) { int len = 0; char *esc = NULL, *e; if (cnt < 0 || cnt > strlen(text)) cnt = strlen(text); for (int i=0; i < cnt; i++) { if (text[i] && (strchr(escape_chars, text[i]) != NULL)) len += 2; /* Escaped as '\x' */ else if (text[i] && extra && (strchr(extra, text[i]) != NULL)) len += 2; /* Escaped as '\x' */ else if (! isprint(text[i])) len += 4; /* Escaped as '\ooo' */ else len += 1; } if (ALLOC_N(esc, len+1) < 0) return NULL; e = esc; for (int i=0; i < cnt; i++) { char *p; if (text[i] && ((p = strchr(escape_chars, text[i])) != NULL)) { *e++ = '\\'; *e++ = escape_names[p - escape_chars]; } else if (text[i] && extra && (strchr(extra, text[i]) != NULL)) { *e++ = '\\'; *e++ = text[i]; } else if (! isprint(text[i])) { sprintf(e, "\\%03o", (unsigned char) text[i]); e += 4; } else { *e++ = text[i]; } } return esc; } int print_chars(FILE *out, const char *text, int cnt) { int total = 0; char *esc; if (text == NULL) { fprintf(out, "nil"); return 3; } if (cnt < 0) cnt = strlen(text); esc = escape(text, cnt, NULL); total = strlen(esc); if (out != NULL) fprintf(out, "%s", esc); free(esc); return total; } char *format_pos(const char *text, int pos) { static const int window = 28; char *buf = NULL, *left = NULL, *right = NULL; int before = pos; int llen, rlen; int r; if (before > window) before = window; left = escape(text + pos - before, before, NULL); if (left == NULL) goto done; right = escape(text + pos, window, NULL); if (right == NULL) goto done; llen = strlen(left); rlen = strlen(right); if (llen < window && rlen < window) { r = asprintf(&buf, "%*s%s|=|%s%-*s\n", window - llen, "<", left, right, window - rlen, ">"); } else if (strlen(left) < window) { r = asprintf(&buf, "%*s%s|=|%s>\n", window - llen, "<", left, right); } else if (strlen(right) < window) { r = asprintf(&buf, "<%s|=|%s%-*s\n", left, right, window - rlen, ">"); } else { r = asprintf(&buf, "<%s|=|%s>\n", left, right); } if (r < 0) { buf = NULL; } done: free(left); free(right); return buf; } void print_pos(FILE *out, const char *text, int pos) { char *format = format_pos(text, pos); if (format != NULL) { fputs(format, out); FREE(format); } } int __aug_init_memstream(struct memstream *ms) { MEMZERO(ms, 1); #if HAVE_OPEN_MEMSTREAM ms->stream = open_memstream(&(ms->buf), &(ms->size)); return ms->stream == NULL ? -1 : 0; #else ms->stream = tmpfile(); if (ms->stream == NULL) { return -1; } return 0; #endif } int __aug_close_memstream(struct memstream *ms) { #if !HAVE_OPEN_MEMSTREAM rewind(ms->stream); ms->buf = fread_file_lim(ms->stream, MAX_READ_LEN, &(ms->size)); #endif if (fclose(ms->stream) == EOF) { FREE(ms->buf); ms->size = 0; return -1; } return 0; } char *path_expand(struct tree *tree, const char *ppath) { struct tree *siblings = tree->parent->children; char *path; const char *label; int cnt = 0, ind = 0, r; list_for_each(t, siblings) { if (streqv(t->label, tree->label)) { cnt += 1; if (t == tree) ind = cnt; } } if (ppath == NULL) ppath = ""; if (tree == NULL) label = "(no_tree)"; else if (tree->label == NULL) label = "(none)"; else label = tree->label; if (cnt > 1) { r = asprintf(&path, "%s/%s[%d]", ppath, label, ind); } else { r = asprintf(&path, "%s/%s", ppath, label); } if (r == -1) return NULL; return path; } char *path_of_tree(struct tree *tree) { int depth, i; struct tree *t, **anc; char *path = NULL; for (t = tree, depth = 1; ! ROOT_P(t); depth++, t = t->parent); if (ALLOC_N(anc, depth) < 0) return NULL; for (t = tree, i = depth - 1; i >= 0; i--, t = t->parent) anc[i] = t; for (i = 0; i < depth; i++) { char *p = path_expand(anc[i], path); free(path); path = p; } FREE(anc); return path; } /* User-facing path cleaning */ static char *cleanstr(char *path, const char sep) { if (path == NULL || strlen(path) == 0) return path; char *e = path + strlen(path) - 1; while (e >= path && (*e == sep || isspace(*e))) *e-- = '\0'; return path; } char *cleanpath(char *path) { if (path == NULL || strlen(path) == 0) return path; if (STREQ(path, "/")) return path; return cleanstr(path, SEP); } const char *xstrerror(int errnum, char *buf, size_t len) { #ifdef HAVE_STRERROR_R # ifdef __USE_GNU /* Annoying linux specific API contract */ return strerror_r(errnum, buf, len); # else strerror_r(errnum, buf, len); return buf; # endif #else int n = snprintf(buf, len, "errno=%d", errnum); return (0 < n && n < len ? buf : "internal error: buffer too small in xstrerror"); #endif } int xasprintf(char **strp, const char *format, ...) { va_list args; int result; va_start (args, format); result = vasprintf (strp, format, args); va_end (args); if (result < 0) *strp = NULL; return result; } /* From libvirt's src/xen/block_stats.c */ int xstrtoint64(char const *s, int base, int64_t *result) { long long int lli; char *p; errno = 0; lli = strtoll(s, &p, base); if (errno || !(*p == 0 || *p == '\n') || p == s || (int64_t) lli != lli) return -1; *result = lli; return 0; } void calc_line_ofs(const char *text, size_t pos, size_t *line, size_t *ofs) { *line = 1; *ofs = 0; for (const char *t = text; t < text + pos; t++) { *ofs += 1; if (*t == '\n') { *ofs = 0; *line += 1; } } } #if HAVE_USELOCALE int regexp_c_locale(ATTRIBUTE_UNUSED char **u, ATTRIBUTE_UNUSED size_t *len) { /* On systems with uselocale, we are ok, since we make sure that we * switch to the "C" locale any time we enter through the public API */ return 0; } #else int regexp_c_locale(char **u, size_t *len) { /* Without uselocale, we need to expand character ranges */ int r; char *s = *u; size_t s_len, u_len; if (len == NULL) { len = &u_len; s_len = strlen(s); } else { s_len = *len; } r = fa_expand_char_ranges(s, s_len, u, len); if (r != 0) { *u = s; *len = s_len; } if (r < 0) return -1; /* Syntax errors will be caught when the result is compiled */ if (r > 0) return 0; free(s); return 1; } #endif #if ENABLE_DEBUG bool debugging(const char *category) { const char *debug = getenv("AUGEAS_DEBUG"); const char *s; if (debug == NULL) return false; for (s = debug; s != NULL; ) { if (STREQLEN(s, category, strlen(category))) return true; s = strchr(s, ':'); if (s != NULL) s+=1; } return false; } FILE *debug_fopen(const char *format, ...) { va_list ap; FILE *result = NULL; const char *dir; char *name = NULL, *path = NULL; int r; dir = getenv("AUGEAS_DEBUG_DIR"); if (dir == NULL) goto error; va_start(ap, format); r = vasprintf(&name, format, ap); va_end(ap); if (r < 0) goto error; r = xasprintf(&path, "%s/%s", dir, name); if (r < 0) goto error; result = fopen(path, "w"); error: free(name); free(path); return result; } #endif /* * Local variables: * indent-tabs-mode: nil * c-indent-level: 4 * c-basic-offset: 4 * tab-width: 4 * End: */
./CrossVul/dataset_final_sorted/CWE-59/c/good_3576_1
crossvul-cpp_data_good_3272_0
/** \ingroup payload * \file lib/fsm.c * File state machine to handle a payload from a package. */ #include "system.h" #include <utime.h> #include <errno.h> #if WITH_CAP #include <sys/capability.h> #endif #include <rpm/rpmte.h> #include <rpm/rpmts.h> #include <rpm/rpmlog.h> #include <rpm/rpmmacro.h> #include "rpmio/rpmio_internal.h" /* fdInit/FiniDigest */ #include "lib/fsm.h" #include "lib/rpmte_internal.h" /* XXX rpmfs */ #include "lib/rpmplugins.h" /* rpm plugins hooks */ #include "lib/rpmug.h" #include "debug.h" #define _FSM_DEBUG 0 int _fsm_debug = _FSM_DEBUG; /* XXX Failure to remove is not (yet) cause for failure. */ static int strict_erasures = 0; #define SUFFIX_RPMORIG ".rpmorig" #define SUFFIX_RPMSAVE ".rpmsave" #define SUFFIX_RPMNEW ".rpmnew" /* Default directory and file permissions if not mapped */ #define _dirPerms 0755 #define _filePerms 0644 /* * XXX Forward declarations for previously exported functions to avoid moving * things around needlessly */ static const char * fileActionString(rpmFileAction a); /** \ingroup payload * Build path to file from file info, optionally ornamented with suffix. * @param fi file info iterator * @param suffix suffix to use (NULL disables) * @retval path to file (malloced) */ static char * fsmFsPath(rpmfi fi, const char * suffix) { return rstrscat(NULL, rpmfiDN(fi), rpmfiBN(fi), suffix ? suffix : "", NULL); } /** \ingroup payload * Directory name iterator. */ typedef struct dnli_s { rpmfiles fi; char * active; int reverse; int isave; int i; } * DNLI_t; /** \ingroup payload * Destroy directory name iterator. * @param dnli directory name iterator * @retval NULL always */ static DNLI_t dnlFreeIterator(DNLI_t dnli) { if (dnli) { if (dnli->active) free(dnli->active); free(dnli); } return NULL; } /** \ingroup payload * Create directory name iterator. * @param fi file info set * @param fs file state set * @param reverse traverse directory names in reverse order? * @return directory name iterator */ static DNLI_t dnlInitIterator(rpmfiles fi, rpmfs fs, int reverse) { DNLI_t dnli; int i, j; int dc; if (fi == NULL) return NULL; dc = rpmfilesDC(fi); dnli = xcalloc(1, sizeof(*dnli)); dnli->fi = fi; dnli->reverse = reverse; dnli->i = (reverse ? dc : 0); if (dc) { dnli->active = xcalloc(dc, sizeof(*dnli->active)); int fc = rpmfilesFC(fi); /* Identify parent directories not skipped. */ for (i = 0; i < fc; i++) if (!XFA_SKIPPING(rpmfsGetAction(fs, i))) dnli->active[rpmfilesDI(fi, i)] = 1; /* Exclude parent directories that are explicitly included. */ for (i = 0; i < fc; i++) { int dil; size_t dnlen, bnlen; if (!S_ISDIR(rpmfilesFMode(fi, i))) continue; dil = rpmfilesDI(fi, i); dnlen = strlen(rpmfilesDN(fi, dil)); bnlen = strlen(rpmfilesBN(fi, i)); for (j = 0; j < dc; j++) { const char * dnl; size_t jlen; if (!dnli->active[j] || j == dil) continue; dnl = rpmfilesDN(fi, j); jlen = strlen(dnl); if (jlen != (dnlen+bnlen+1)) continue; if (!rstreqn(dnl, rpmfilesDN(fi, dil), dnlen)) continue; if (!rstreqn(dnl+dnlen, rpmfilesBN(fi, i), bnlen)) continue; if (dnl[dnlen+bnlen] != '/' || dnl[dnlen+bnlen+1] != '\0') continue; /* This directory is included in the package. */ dnli->active[j] = 0; break; } } /* Print only once per package. */ if (!reverse) { j = 0; for (i = 0; i < dc; i++) { if (!dnli->active[i]) continue; if (j == 0) { j = 1; rpmlog(RPMLOG_DEBUG, "========== Directories not explicitly included in package:\n"); } rpmlog(RPMLOG_DEBUG, "%10d %s\n", i, rpmfilesDN(fi, i)); } if (j) rpmlog(RPMLOG_DEBUG, "==========\n"); } } return dnli; } /** \ingroup payload * Return next directory name (from file info). * @param dnli directory name iterator * @return next directory name */ static const char * dnlNextIterator(DNLI_t dnli) { const char * dn = NULL; if (dnli) { rpmfiles fi = dnli->fi; int dc = rpmfilesDC(fi); int i = -1; if (dnli->active) do { i = (!dnli->reverse ? dnli->i++ : --dnli->i); } while (i >= 0 && i < dc && !dnli->active[i]); if (i >= 0 && i < dc) dn = rpmfilesDN(fi, i); else i = -1; dnli->isave = i; } return dn; } static int fsmSetFCaps(const char *path, const char *captxt) { int rc = 0; #if WITH_CAP if (captxt && *captxt != '\0') { cap_t fcaps = cap_from_text(captxt); if (fcaps == NULL || cap_set_file(path, fcaps) != 0) { rc = RPMERR_SETCAP_FAILED; } cap_free(fcaps); } #endif return rc; } /* Check dest is the same, empty and regular file with writeonly permissions */ static int linkSane(FD_t wfd, const char *dest) { struct stat sb, lsb; return (fstat(Fileno(wfd), &sb) == 0 && sb.st_size == 0 && (sb.st_mode & ~S_IFMT) == S_IWUSR && lstat(dest, &lsb) == 0 && S_ISREG(lsb.st_mode) && sb.st_dev == lsb.st_dev && sb.st_ino == lsb.st_ino); } /** \ingroup payload * Create file from payload stream. * @return 0 on success */ static int expandRegular(rpmfi fi, const char *dest, rpmpsm psm, int exclusive, int nodigest, int nocontent) { FD_t wfd = NULL; int rc = 0; /* Create the file with 0200 permissions (write by owner). */ { mode_t old_umask = umask(0577); wfd = Fopen(dest, exclusive ? "wx.ufdio" : "a.ufdio"); umask(old_umask); /* If reopening, make sure the file is what we expect */ if (!exclusive && wfd != NULL && !linkSane(wfd, dest)) { rc = RPMERR_OPEN_FAILED; goto exit; } } if (Ferror(wfd)) { rc = RPMERR_OPEN_FAILED; goto exit; } if (!nocontent) rc = rpmfiArchiveReadToFilePsm(fi, wfd, nodigest, psm); exit: if (wfd) { int myerrno = errno; static int oneshot = 0; static int flush_io = 0; if (!oneshot) { flush_io = rpmExpandNumeric("%{?_flush_io}"); oneshot = 1; } if (flush_io) { int fdno = Fileno(wfd); fsync(fdno); } Fclose(wfd); errno = myerrno; } return rc; } static int fsmMkfile(rpmfi fi, const char *dest, rpmfiles files, rpmpsm psm, int nodigest, int *setmeta, int * firsthardlink) { int rc = 0; int numHardlinks = rpmfiFNlink(fi); if (numHardlinks > 1) { /* Create first hardlinked file empty */ if (*firsthardlink < 0) { *firsthardlink = rpmfiFX(fi); rc = expandRegular(fi, dest, psm, 1, nodigest, 1); } else { /* Create hard links for others */ char *fn = rpmfilesFN(files, *firsthardlink); rc = link(fn, dest); if (rc < 0) { rc = RPMERR_LINK_FAILED; } free(fn); } } /* Write normal files or fill the last hardlinked (already existing) file with content */ if (numHardlinks<=1) { if (!rc) rc = expandRegular(fi, dest, psm, 1, nodigest, 0); } else if (rpmfiArchiveHasContent(fi)) { if (!rc) rc = expandRegular(fi, dest, psm, 0, nodigest, 0); *firsthardlink = -1; } else { *setmeta = 0; } return rc; } static int fsmReadLink(const char *path, char *buf, size_t bufsize, size_t *linklen) { ssize_t llen = readlink(path, buf, bufsize - 1); int rc = RPMERR_READLINK_FAILED; if (_fsm_debug) { rpmlog(RPMLOG_DEBUG, " %8s (%s, buf, %d) %s\n", __func__, path, (int)(bufsize -1), (llen < 0 ? strerror(errno) : "")); } if (llen >= 0) { buf[llen] = '\0'; rc = 0; *linklen = llen; } return rc; } static int fsmStat(const char *path, int dolstat, struct stat *sb) { int rc; if (dolstat){ rc = lstat(path, sb); } else { rc = stat(path, sb); } if (_fsm_debug && rc && errno != ENOENT) rpmlog(RPMLOG_DEBUG, " %8s (%s, ost) %s\n", __func__, path, (rc < 0 ? strerror(errno) : "")); if (rc < 0) { rc = (errno == ENOENT ? RPMERR_ENOENT : RPMERR_LSTAT_FAILED); /* Ensure consistent struct content on failure */ memset(sb, 0, sizeof(*sb)); } return rc; } static int fsmRmdir(const char *path) { int rc = rmdir(path); if (_fsm_debug) rpmlog(RPMLOG_DEBUG, " %8s (%s) %s\n", __func__, path, (rc < 0 ? strerror(errno) : "")); if (rc < 0) switch (errno) { case ENOENT: rc = RPMERR_ENOENT; break; case ENOTEMPTY: rc = RPMERR_ENOTEMPTY; break; default: rc = RPMERR_RMDIR_FAILED; break; } return rc; } static int fsmMkdir(const char *path, mode_t mode) { int rc = mkdir(path, (mode & 07777)); if (_fsm_debug) rpmlog(RPMLOG_DEBUG, " %8s (%s, 0%04o) %s\n", __func__, path, (unsigned)(mode & 07777), (rc < 0 ? strerror(errno) : "")); if (rc < 0) rc = RPMERR_MKDIR_FAILED; return rc; } static int fsmMkfifo(const char *path, mode_t mode) { int rc = mkfifo(path, (mode & 07777)); if (_fsm_debug) { rpmlog(RPMLOG_DEBUG, " %8s (%s, 0%04o) %s\n", __func__, path, (unsigned)(mode & 07777), (rc < 0 ? strerror(errno) : "")); } if (rc < 0) rc = RPMERR_MKFIFO_FAILED; return rc; } static int fsmMknod(const char *path, mode_t mode, dev_t dev) { /* FIX: check S_IFIFO or dev != 0 */ int rc = mknod(path, (mode & ~07777), dev); if (_fsm_debug) { rpmlog(RPMLOG_DEBUG, " %8s (%s, 0%o, 0x%x) %s\n", __func__, path, (unsigned)(mode & ~07777), (unsigned)dev, (rc < 0 ? strerror(errno) : "")); } if (rc < 0) rc = RPMERR_MKNOD_FAILED; return rc; } /** * Create (if necessary) directories not explicitly included in package. * @param files file data * @param fs file states * @param plugins rpm plugins handle * @return 0 on success */ static int fsmMkdirs(rpmfiles files, rpmfs fs, rpmPlugins plugins) { DNLI_t dnli = dnlInitIterator(files, fs, 0); struct stat sb; const char *dpath; int dc = rpmfilesDC(files); int rc = 0; int i; int ldnlen = 0; int ldnalloc = 0; char * ldn = NULL; short * dnlx = NULL; dnlx = (dc ? xcalloc(dc, sizeof(*dnlx)) : NULL); if (dnlx != NULL) while ((dpath = dnlNextIterator(dnli)) != NULL) { size_t dnlen = strlen(dpath); char * te, dn[dnlen+1]; dc = dnli->isave; if (dc < 0) continue; dnlx[dc] = dnlen; if (dnlen <= 1) continue; if (dnlen <= ldnlen && rstreq(dpath, ldn)) continue; /* Copy as we need to modify the string */ (void) stpcpy(dn, dpath); /* Assume '/' directory exists, "mkdir -p" for others if non-existent */ for (i = 1, te = dn + 1; *te != '\0'; te++, i++) { if (*te != '/') continue; *te = '\0'; /* Already validated? */ if (i < ldnlen && (ldn[i] == '/' || ldn[i] == '\0') && rstreqn(dn, ldn, i)) { *te = '/'; /* Move pre-existing path marker forward. */ dnlx[dc] = (te - dn); continue; } /* Validate next component of path. */ rc = fsmStat(dn, 1, &sb); /* lstat */ *te = '/'; /* Directory already exists? */ if (rc == 0 && S_ISDIR(sb.st_mode)) { /* Move pre-existing path marker forward. */ dnlx[dc] = (te - dn); } else if (rc == RPMERR_ENOENT) { *te = '\0'; mode_t mode = S_IFDIR | (_dirPerms & 07777); rpmFsmOp op = (FA_CREATE|FAF_UNOWNED); /* Run fsm file pre hook for all plugins */ rc = rpmpluginsCallFsmFilePre(plugins, NULL, dn, mode, op); if (!rc) rc = fsmMkdir(dn, mode); if (!rc) { rc = rpmpluginsCallFsmFilePrepare(plugins, NULL, dn, dn, mode, op); } /* Run fsm file post hook for all plugins */ rpmpluginsCallFsmFilePost(plugins, NULL, dn, mode, op, rc); if (!rc) { rpmlog(RPMLOG_DEBUG, "%s directory created with perms %04o\n", dn, (unsigned)(mode & 07777)); } *te = '/'; } if (rc) break; } if (rc) break; /* Save last validated path. */ if (ldnalloc < (dnlen + 1)) { ldnalloc = dnlen + 100; ldn = xrealloc(ldn, ldnalloc); } if (ldn != NULL) { /* XXX can't happen */ strcpy(ldn, dn); ldnlen = dnlen; } } free(dnlx); free(ldn); dnlFreeIterator(dnli); return rc; } static void removeSBITS(const char *path) { struct stat stb; if (lstat(path, &stb) == 0 && S_ISREG(stb.st_mode)) { if ((stb.st_mode & 06000) != 0) { (void) chmod(path, stb.st_mode & 0777); } #if WITH_CAP if (stb.st_mode & (S_IXUSR|S_IXGRP|S_IXOTH)) { (void) cap_set_file(path, NULL); } #endif } } static void fsmDebug(const char *fpath, rpmFileAction action, const struct stat *st) { rpmlog(RPMLOG_DEBUG, "%-10s %06o%3d (%4d,%4d)%6d %s\n", fileActionString(action), (int)st->st_mode, (int)st->st_nlink, (int)st->st_uid, (int)st->st_gid, (int)st->st_size, (fpath ? fpath : "")); } static int fsmSymlink(const char *opath, const char *path) { int rc = symlink(opath, path); if (_fsm_debug) { rpmlog(RPMLOG_DEBUG, " %8s (%s, %s) %s\n", __func__, opath, path, (rc < 0 ? strerror(errno) : "")); } if (rc < 0) rc = RPMERR_SYMLINK_FAILED; return rc; } static int fsmUnlink(const char *path) { int rc = 0; removeSBITS(path); rc = unlink(path); if (_fsm_debug) rpmlog(RPMLOG_DEBUG, " %8s (%s) %s\n", __func__, path, (rc < 0 ? strerror(errno) : "")); if (rc < 0) rc = (errno == ENOENT ? RPMERR_ENOENT : RPMERR_UNLINK_FAILED); return rc; } static int fsmRename(const char *opath, const char *path) { removeSBITS(path); int rc = rename(opath, path); #if defined(ETXTBSY) && defined(__HPUX__) /* XXX HP-UX (and other os'es) don't permit rename to busy files. */ if (rc && errno == ETXTBSY) { char *rmpath = NULL; rstrscat(&rmpath, path, "-RPMDELETE", NULL); rc = rename(path, rmpath); if (!rc) rc = rename(opath, path); free(rmpath); } #endif if (_fsm_debug) rpmlog(RPMLOG_DEBUG, " %8s (%s, %s) %s\n", __func__, opath, path, (rc < 0 ? strerror(errno) : "")); if (rc < 0) rc = (errno == EISDIR ? RPMERR_EXIST_AS_DIR : RPMERR_RENAME_FAILED); return rc; } static int fsmRemove(const char *path, mode_t mode) { return S_ISDIR(mode) ? fsmRmdir(path) : fsmUnlink(path); } static int fsmChown(const char *path, mode_t mode, uid_t uid, gid_t gid) { int rc = S_ISLNK(mode) ? lchown(path, uid, gid) : chown(path, uid, gid); if (rc < 0) { struct stat st; if (lstat(path, &st) == 0 && st.st_uid == uid && st.st_gid == gid) rc = 0; } if (_fsm_debug) rpmlog(RPMLOG_DEBUG, " %8s (%s, %d, %d) %s\n", __func__, path, (int)uid, (int)gid, (rc < 0 ? strerror(errno) : "")); if (rc < 0) rc = RPMERR_CHOWN_FAILED; return rc; } static int fsmChmod(const char *path, mode_t mode) { int rc = chmod(path, (mode & 07777)); if (rc < 0) { struct stat st; if (lstat(path, &st) == 0 && (st.st_mode & 07777) == (mode & 07777)) rc = 0; } if (_fsm_debug) rpmlog(RPMLOG_DEBUG, " %8s (%s, 0%04o) %s\n", __func__, path, (unsigned)(mode & 07777), (rc < 0 ? strerror(errno) : "")); if (rc < 0) rc = RPMERR_CHMOD_FAILED; return rc; } static int fsmUtime(const char *path, mode_t mode, time_t mtime) { int rc = 0; struct timeval stamps[2] = { { .tv_sec = mtime, .tv_usec = 0 }, { .tv_sec = mtime, .tv_usec = 0 }, }; #if HAVE_LUTIMES rc = lutimes(path, stamps); #else if (!S_ISLNK(mode)) rc = utimes(path, stamps); #endif if (_fsm_debug) rpmlog(RPMLOG_DEBUG, " %8s (%s, 0x%x) %s\n", __func__, path, (unsigned)mtime, (rc < 0 ? strerror(errno) : "")); if (rc < 0) rc = RPMERR_UTIME_FAILED; /* ...but utime error is not critical for directories */ if (rc && S_ISDIR(mode)) rc = 0; return rc; } static int fsmVerify(const char *path, rpmfi fi, const struct stat *fsb) { int rc; int saveerrno = errno; struct stat dsb; mode_t mode = rpmfiFMode(fi); rc = fsmStat(path, 1, &dsb); if (rc) return rc; if (S_ISREG(mode)) { /* HP-UX (and other os'es) don't permit unlink on busy files. */ char *rmpath = rstrscat(NULL, path, "-RPMDELETE", NULL); rc = fsmRename(path, rmpath); /* XXX shouldn't we take unlink return code here? */ if (!rc) (void) fsmUnlink(rmpath); else rc = RPMERR_UNLINK_FAILED; free(rmpath); return (rc ? rc : RPMERR_ENOENT); /* XXX HACK */ } else if (S_ISDIR(mode)) { if (S_ISDIR(dsb.st_mode)) return 0; if (S_ISLNK(dsb.st_mode)) { uid_t luid = dsb.st_uid; rc = fsmStat(path, 0, &dsb); if (rc == RPMERR_ENOENT) rc = 0; if (rc) return rc; errno = saveerrno; /* Only permit directory symlinks by target owner and root */ if (S_ISDIR(dsb.st_mode) && (luid == 0 || luid == fsb->st_uid)) return 0; } } else if (S_ISLNK(mode)) { if (S_ISLNK(dsb.st_mode)) { char buf[8 * BUFSIZ]; size_t len; rc = fsmReadLink(path, buf, 8 * BUFSIZ, &len); errno = saveerrno; if (rc) return rc; if (rstreq(rpmfiFLink(fi), buf)) return 0; } } else if (S_ISFIFO(mode)) { if (S_ISFIFO(dsb.st_mode)) return 0; } else if (S_ISCHR(mode) || S_ISBLK(mode)) { if ((S_ISCHR(dsb.st_mode) || S_ISBLK(dsb.st_mode)) && (dsb.st_rdev == rpmfiFRdev(fi))) return 0; } else if (S_ISSOCK(mode)) { if (S_ISSOCK(dsb.st_mode)) return 0; } /* XXX shouldn't do this with commit/undo. */ rc = fsmUnlink(path); if (rc == 0) rc = RPMERR_ENOENT; return (rc ? rc : RPMERR_ENOENT); /* XXX HACK */ } #define IS_DEV_LOG(_x) \ ((_x) != NULL && strlen(_x) >= (sizeof("/dev/log")-1) && \ rstreqn((_x), "/dev/log", sizeof("/dev/log")-1) && \ ((_x)[sizeof("/dev/log")-1] == '\0' || \ (_x)[sizeof("/dev/log")-1] == ';')) /* Rename pre-existing modified or unmanaged file. */ static int fsmBackup(rpmfi fi, rpmFileAction action) { int rc = 0; const char *suffix = NULL; if (!(rpmfiFFlags(fi) & RPMFILE_GHOST)) { switch (action) { case FA_SAVE: suffix = SUFFIX_RPMSAVE; break; case FA_BACKUP: suffix = SUFFIX_RPMORIG; break; default: break; } } if (suffix) { char * opath = fsmFsPath(fi, NULL); char * path = fsmFsPath(fi, suffix); rc = fsmRename(opath, path); if (!rc) { rpmlog(RPMLOG_WARNING, _("%s saved as %s\n"), opath, path); } free(path); free(opath); } return rc; } static int fsmSetmeta(const char *path, rpmfi fi, rpmPlugins plugins, rpmFileAction action, const struct stat * st, int nofcaps) { int rc = 0; const char *dest = rpmfiFN(fi); if (!rc && !getuid()) { rc = fsmChown(path, st->st_mode, st->st_uid, st->st_gid); } if (!rc && !S_ISLNK(st->st_mode)) { rc = fsmChmod(path, st->st_mode); } /* Set file capabilities (if enabled) */ if (!rc && !nofcaps && S_ISREG(st->st_mode) && !getuid()) { rc = fsmSetFCaps(path, rpmfiFCaps(fi)); } if (!rc) { rc = fsmUtime(path, st->st_mode, rpmfiFMtime(fi)); } if (!rc) { rc = rpmpluginsCallFsmFilePrepare(plugins, fi, path, dest, st->st_mode, action); } return rc; } static int fsmCommit(char **path, rpmfi fi, rpmFileAction action, const char *suffix) { int rc = 0; /* XXX Special case /dev/log, which shouldn't be packaged anyways */ if (!(S_ISSOCK(rpmfiFMode(fi)) && IS_DEV_LOG(*path))) { const char *nsuffix = (action == FA_ALTNAME) ? SUFFIX_RPMNEW : NULL; char *dest = *path; /* Construct final destination path (nsuffix is usually NULL) */ if (suffix) dest = fsmFsPath(fi, nsuffix); /* Rename temporary to final file name if needed. */ if (dest != *path) { rc = fsmRename(*path, dest); if (!rc && nsuffix) { char * opath = fsmFsPath(fi, NULL); rpmlog(RPMLOG_WARNING, _("%s created as %s\n"), opath, dest); free(opath); } free(*path); *path = dest; } } return rc; } /** * Return formatted string representation of file disposition. * @param a file disposition * @return formatted string */ static const char * fileActionString(rpmFileAction a) { switch (a) { case FA_UNKNOWN: return "unknown"; case FA_CREATE: return "create"; case FA_BACKUP: return "backup"; case FA_SAVE: return "save"; case FA_SKIP: return "skip"; case FA_ALTNAME: return "altname"; case FA_ERASE: return "erase"; case FA_SKIPNSTATE: return "skipnstate"; case FA_SKIPNETSHARED: return "skipnetshared"; case FA_SKIPCOLOR: return "skipcolor"; case FA_TOUCH: return "touch"; default: return "???"; } } /* Remember any non-regular file state for recording in the rpmdb */ static void setFileState(rpmfs fs, int i) { switch (rpmfsGetAction(fs, i)) { case FA_SKIPNSTATE: rpmfsSetState(fs, i, RPMFILE_STATE_NOTINSTALLED); break; case FA_SKIPNETSHARED: rpmfsSetState(fs, i, RPMFILE_STATE_NETSHARED); break; case FA_SKIPCOLOR: rpmfsSetState(fs, i, RPMFILE_STATE_WRONGCOLOR); break; case FA_TOUCH: rpmfsSetState(fs, i, RPMFILE_STATE_NORMAL); break; default: break; } } int rpmPackageFilesInstall(rpmts ts, rpmte te, rpmfiles files, rpmpsm psm, char ** failedFile) { FD_t payload = rpmtePayload(te); rpmfi fi = rpmfiNewArchiveReader(payload, files, RPMFI_ITER_READ_ARCHIVE); rpmfs fs = rpmteGetFileStates(te); rpmPlugins plugins = rpmtsPlugins(ts); struct stat sb; int saveerrno = errno; int rc = 0; int nodigest = (rpmtsFlags(ts) & RPMTRANS_FLAG_NOFILEDIGEST) ? 1 : 0; int nofcaps = (rpmtsFlags(ts) & RPMTRANS_FLAG_NOCAPS) ? 1 : 0; int firsthardlink = -1; int skip; rpmFileAction action; char *tid = NULL; const char *suffix; char *fpath = NULL; if (fi == NULL) { rc = RPMERR_BAD_MAGIC; goto exit; } /* transaction id used for temporary path suffix while installing */ rasprintf(&tid, ";%08x", (unsigned)rpmtsGetTid(ts)); /* Detect and create directories not explicitly in package. */ rc = fsmMkdirs(files, fs, plugins); while (!rc) { /* Read next payload header. */ rc = rpmfiNext(fi); if (rc < 0) { if (rc == RPMERR_ITER_END) rc = 0; break; } action = rpmfsGetAction(fs, rpmfiFX(fi)); skip = XFA_SKIPPING(action); suffix = S_ISDIR(rpmfiFMode(fi)) ? NULL : tid; if (action != FA_TOUCH) { fpath = fsmFsPath(fi, suffix); } else { fpath = fsmFsPath(fi, ""); } /* Remap file perms, owner, and group. */ rc = rpmfiStat(fi, 1, &sb); fsmDebug(fpath, action, &sb); /* Exit on error. */ if (rc) break; /* Run fsm file pre hook for all plugins */ rc = rpmpluginsCallFsmFilePre(plugins, fi, fpath, sb.st_mode, action); if (rc) { skip = 1; } else { setFileState(fs, rpmfiFX(fi)); } if (!skip) { int setmeta = 1; /* Directories replacing something need early backup */ if (!suffix) { rc = fsmBackup(fi, action); } /* Assume file does't exist when tmp suffix is in use */ if (!suffix) { rc = fsmVerify(fpath, fi, &sb); } else { rc = (action == FA_TOUCH) ? 0 : RPMERR_ENOENT; } if (S_ISREG(sb.st_mode)) { if (rc == RPMERR_ENOENT) { rc = fsmMkfile(fi, fpath, files, psm, nodigest, &setmeta, &firsthardlink); } } else if (S_ISDIR(sb.st_mode)) { if (rc == RPMERR_ENOENT) { mode_t mode = sb.st_mode; mode &= ~07777; mode |= 00700; rc = fsmMkdir(fpath, mode); } } else if (S_ISLNK(sb.st_mode)) { if (rc == RPMERR_ENOENT) { rc = fsmSymlink(rpmfiFLink(fi), fpath); } } else if (S_ISFIFO(sb.st_mode)) { /* This mimics cpio S_ISSOCK() behavior but probably isn't right */ if (rc == RPMERR_ENOENT) { rc = fsmMkfifo(fpath, 0000); } } else if (S_ISCHR(sb.st_mode) || S_ISBLK(sb.st_mode) || S_ISSOCK(sb.st_mode)) { if (rc == RPMERR_ENOENT) { rc = fsmMknod(fpath, sb.st_mode, sb.st_rdev); } } else { /* XXX Special case /dev/log, which shouldn't be packaged anyways */ if (!IS_DEV_LOG(fpath)) rc = RPMERR_UNKNOWN_FILETYPE; } /* Set permissions, timestamps etc for non-hardlink entries */ if (!rc && setmeta) { rc = fsmSetmeta(fpath, fi, plugins, action, &sb, nofcaps); } } else if (firsthardlink >= 0 && rpmfiArchiveHasContent(fi)) { /* we skip the hard linked file containing the content */ /* write the content to the first used instead */ char *fn = rpmfilesFN(files, firsthardlink); rc = expandRegular(fi, fn, psm, 0, nodigest, 0); firsthardlink = -1; free(fn); } if (rc) { if (!skip) { /* XXX only erase if temp fn w suffix is in use */ if (suffix && (action != FA_TOUCH)) { (void) fsmRemove(fpath, sb.st_mode); } errno = saveerrno; } } else { /* Notify on success. */ rpmpsmNotify(psm, RPMCALLBACK_INST_PROGRESS, rpmfiArchiveTell(fi)); if (!skip) { /* Backup file if needed. Directories are handled earlier */ if (suffix) rc = fsmBackup(fi, action); if (!rc) rc = fsmCommit(&fpath, fi, action, suffix); } } if (rc) *failedFile = xstrdup(fpath); /* Run fsm file post hook for all plugins */ rpmpluginsCallFsmFilePost(plugins, fi, fpath, sb.st_mode, action, rc); fpath = _free(fpath); } rpmswAdd(rpmtsOp(ts, RPMTS_OP_UNCOMPRESS), fdOp(payload, FDSTAT_READ)); rpmswAdd(rpmtsOp(ts, RPMTS_OP_DIGEST), fdOp(payload, FDSTAT_DIGEST)); exit: /* No need to bother with close errors on read */ rpmfiArchiveClose(fi); rpmfiFree(fi); Fclose(payload); free(tid); free(fpath); return rc; } int rpmPackageFilesRemove(rpmts ts, rpmte te, rpmfiles files, rpmpsm psm, char ** failedFile) { rpmfi fi = rpmfilesIter(files, RPMFI_ITER_BACK); rpmfs fs = rpmteGetFileStates(te); rpmPlugins plugins = rpmtsPlugins(ts); struct stat sb; int rc = 0; char *fpath = NULL; while (!rc && rpmfiNext(fi) >= 0) { rpmFileAction action = rpmfsGetAction(fs, rpmfiFX(fi)); fpath = fsmFsPath(fi, NULL); rc = fsmStat(fpath, 1, &sb); fsmDebug(fpath, action, &sb); /* Run fsm file pre hook for all plugins */ rc = rpmpluginsCallFsmFilePre(plugins, fi, fpath, sb.st_mode, action); if (!XFA_SKIPPING(action)) rc = fsmBackup(fi, action); /* Remove erased files. */ if (action == FA_ERASE) { int missingok = (rpmfiFFlags(fi) & (RPMFILE_MISSINGOK | RPMFILE_GHOST)); rc = fsmRemove(fpath, sb.st_mode); /* * Missing %ghost or %missingok entries are not errors. * XXX: Are non-existent files ever an actual error here? Afterall * that's exactly what we're trying to accomplish here, * and complaining about job already done seems like kinderkarten * level "But it was MY turn!" whining... */ if (rc == RPMERR_ENOENT && missingok) { rc = 0; } /* * Dont whine on non-empty directories for now. We might be able * to track at least some of the expected failures though, * such as when we knowingly left config file backups etc behind. */ if (rc == RPMERR_ENOTEMPTY) { rc = 0; } if (rc) { int lvl = strict_erasures ? RPMLOG_ERR : RPMLOG_WARNING; rpmlog(lvl, _("%s %s: remove failed: %s\n"), S_ISDIR(sb.st_mode) ? _("directory") : _("file"), fpath, strerror(errno)); } } /* Run fsm file post hook for all plugins */ rpmpluginsCallFsmFilePost(plugins, fi, fpath, sb.st_mode, action, rc); /* XXX Failure to remove is not (yet) cause for failure. */ if (!strict_erasures) rc = 0; if (rc) *failedFile = xstrdup(fpath); if (rc == 0) { /* Notify on success. */ /* On erase we're iterating backwards, fixup for progress */ rpm_loff_t amount = rpmfiFC(fi) - rpmfiFX(fi); rpmpsmNotify(psm, RPMCALLBACK_UNINST_PROGRESS, amount); } fpath = _free(fpath); } free(fpath); rpmfiFree(fi); return rc; }
./CrossVul/dataset_final_sorted/CWE-59/c/good_3272_0
crossvul-cpp_data_good_4226_4
/* * parse.c * */ /* Portions of this file are subject to the following copyrights. See * the Net-SNMP's COPYING file for more details and other copyrights * that may apply: */ /****************************************************************** Copyright 1989, 1991, 1992 by Carnegie Mellon University All Rights Reserved Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation, and that the name of CMU not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. CMU DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL CMU BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ******************************************************************/ /* * Copyright � 2003 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms specified in the COPYING file * distributed with the Net-SNMP package. */ #include <net-snmp/net-snmp-config.h> #include <net-snmp/net-snmp-features.h> #ifndef NETSNMP_DISABLE_MIB_LOADING #if HAVE_LIMITS_H #include <limits.h> #endif #include <stdio.h> #if HAVE_STDLIB_H #include <stdlib.h> #endif #if HAVE_STRING_H #include <string.h> #else #include <strings.h> #endif #include <ctype.h> #include <sys/types.h> #if HAVE_SYS_STAT_H #include <sys/stat.h> #endif /* * Wow. This is ugly. -- Wes */ #if HAVE_DIRENT_H # include <dirent.h> # define NAMLEN(dirent) strlen((dirent)->d_name) #else # define dirent direct # define NAMLEN(dirent) (dirent)->d_namlen # if HAVE_SYS_NDIR_H # include <sys/ndir.h> # endif # if HAVE_SYS_DIR_H # include <sys/dir.h> # endif # if HAVE_NDIR_H # include <ndir.h> # endif #endif #if TIME_WITH_SYS_TIME # include <sys/time.h> # include <time.h> #else # if HAVE_SYS_TIME_H # include <sys/time.h> # else # include <time.h> # endif #endif #if HAVE_NETINET_IN_H #include <netinet/in.h> #endif #if defined(HAVE_REGEX_H) && defined(HAVE_REGCOMP) #include <regex.h> #endif #if HAVE_UNISTD_H #include <unistd.h> #endif #if HAVE_DMALLOC_H #include <dmalloc.h> #endif #include <errno.h> #include <net-snmp/types.h> #include <net-snmp/output_api.h> #include <net-snmp/config_api.h> #include <net-snmp/utilities.h> #include <net-snmp/library/parse.h> #include <net-snmp/library/mib.h> #include <net-snmp/library/snmp_api.h> #include <net-snmp/library/tools.h> netsnmp_feature_child_of(find_module, mib_api) netsnmp_feature_child_of(get_tc_description, mib_api) /* * A linked list of nodes. */ struct node { struct node *next; char *label; /* This node's (unique) textual name */ u_long subid; /* This node's integer subidentifier */ int modid; /* The module containing this node */ char *parent; /* The parent's textual name */ int tc_index; /* index into tclist (-1 if NA) */ int type; /* The type of object this represents */ int access; int status; struct enum_list *enums; /* (optional) list of enumerated integers */ struct range_list *ranges; struct index_list *indexes; char *augments; struct varbind_list *varbinds; char *hint; char *units; char *description; /* description (a quoted string) */ char *reference; /* references (a quoted string) */ char *defaultValue; char *filename; int lineno; }; /* * This is one element of an object identifier with either an integer * subidentifier, or a textual string label, or both. * The subid is -1 if not present, and label is NULL if not present. */ struct subid_s { int subid; int modid; char *label; }; #define MAXTC 16384 struct tc { /* textual conventions */ int type; int modid; char *descriptor; char *hint; struct enum_list *enums; struct range_list *ranges; char *description; } tclist[MAXTC]; int mibLine = 0; const char *File = "(none)"; static int anonymous = 0; struct objgroup { char *name; int line; struct objgroup *next; } *objgroups = NULL, *objects = NULL, *notifs = NULL; #define SYNTAX_MASK 0x80 /* * types of tokens * Tokens wiht the SYNTAX_MASK bit set are syntax tokens */ #define CONTINUE -1 #define ENDOFFILE 0 #define LABEL 1 #define SUBTREE 2 #define SYNTAX 3 #define OBJID (4 | SYNTAX_MASK) #define OCTETSTR (5 | SYNTAX_MASK) #define INTEGER (6 | SYNTAX_MASK) #define NETADDR (7 | SYNTAX_MASK) #define IPADDR (8 | SYNTAX_MASK) #define COUNTER (9 | SYNTAX_MASK) #define GAUGE (10 | SYNTAX_MASK) #define TIMETICKS (11 | SYNTAX_MASK) #define KW_OPAQUE (12 | SYNTAX_MASK) #define NUL (13 | SYNTAX_MASK) #define SEQUENCE 14 #define OF 15 /* SEQUENCE OF */ #define OBJTYPE 16 #define ACCESS 17 #define READONLY 18 #define READWRITE 19 #define WRITEONLY 20 #ifdef NOACCESS #undef NOACCESS /* agent 'NOACCESS' token */ #endif #define NOACCESS 21 #define STATUS 22 #define MANDATORY 23 #define KW_OPTIONAL 24 #define OBSOLETE 25 /* * #define RECOMMENDED 26 */ #define PUNCT 27 #define EQUALS 28 #define NUMBER 29 #define LEFTBRACKET 30 #define RIGHTBRACKET 31 #define LEFTPAREN 32 #define RIGHTPAREN 33 #define COMMA 34 #define DESCRIPTION 35 #define QUOTESTRING 36 #define INDEX 37 #define DEFVAL 38 #define DEPRECATED 39 #define SIZE 40 #define BITSTRING (41 | SYNTAX_MASK) #define NSAPADDRESS (42 | SYNTAX_MASK) #define COUNTER64 (43 | SYNTAX_MASK) #define OBJGROUP 44 #define NOTIFTYPE 45 #define AUGMENTS 46 #define COMPLIANCE 47 #define READCREATE 48 #define UNITS 49 #define REFERENCE 50 #define NUM_ENTRIES 51 #define MODULEIDENTITY 52 #define LASTUPDATED 53 #define ORGANIZATION 54 #define CONTACTINFO 55 #define UINTEGER32 (56 | SYNTAX_MASK) #define CURRENT 57 #define DEFINITIONS 58 #define END 59 #define SEMI 60 #define TRAPTYPE 61 #define ENTERPRISE 62 /* * #define DISPLAYSTR (63 | SYNTAX_MASK) */ #define BEGIN 64 #define IMPORTS 65 #define EXPORTS 66 #define ACCNOTIFY 67 #define BAR 68 #define RANGE 69 #define CONVENTION 70 #define DISPLAYHINT 71 #define FROM 72 #define AGENTCAP 73 #define MACRO 74 #define IMPLIED 75 #define SUPPORTS 76 #define INCLUDES 77 #define VARIATION 78 #define REVISION 79 #define NOTIMPL 80 #define OBJECTS 81 #define NOTIFICATIONS 82 #define MODULE 83 #define MINACCESS 84 #define PRODREL 85 #define WRSYNTAX 86 #define CREATEREQ 87 #define NOTIFGROUP 88 #define MANDATORYGROUPS 89 #define GROUP 90 #define OBJECT 91 #define IDENTIFIER 92 #define CHOICE 93 #define LEFTSQBRACK 95 #define RIGHTSQBRACK 96 #define IMPLICIT 97 #define APPSYNTAX (98 | SYNTAX_MASK) #define OBJSYNTAX (99 | SYNTAX_MASK) #define SIMPLESYNTAX (100 | SYNTAX_MASK) #define OBJNAME (101 | SYNTAX_MASK) #define NOTIFNAME (102 | SYNTAX_MASK) #define VARIABLES 103 #define UNSIGNED32 (104 | SYNTAX_MASK) #define INTEGER32 (105 | SYNTAX_MASK) #define OBJIDENTITY 106 /* * Beware of reaching SYNTAX_MASK (0x80) */ struct tok { const char *name; /* token name */ int len; /* length not counting nul */ int token; /* value */ int hash; /* hash of name */ struct tok *next; /* pointer to next in hash table */ }; static struct tok tokens[] = { {"obsolete", sizeof("obsolete") - 1, OBSOLETE} , {"Opaque", sizeof("Opaque") - 1, KW_OPAQUE} , {"optional", sizeof("optional") - 1, KW_OPTIONAL} , {"LAST-UPDATED", sizeof("LAST-UPDATED") - 1, LASTUPDATED} , {"ORGANIZATION", sizeof("ORGANIZATION") - 1, ORGANIZATION} , {"CONTACT-INFO", sizeof("CONTACT-INFO") - 1, CONTACTINFO} , {"MODULE-IDENTITY", sizeof("MODULE-IDENTITY") - 1, MODULEIDENTITY} , {"MODULE-COMPLIANCE", sizeof("MODULE-COMPLIANCE") - 1, COMPLIANCE} , {"DEFINITIONS", sizeof("DEFINITIONS") - 1, DEFINITIONS} , {"END", sizeof("END") - 1, END} , {"AUGMENTS", sizeof("AUGMENTS") - 1, AUGMENTS} , {"not-accessible", sizeof("not-accessible") - 1, NOACCESS} , {"write-only", sizeof("write-only") - 1, WRITEONLY} , {"NsapAddress", sizeof("NsapAddress") - 1, NSAPADDRESS} , {"UNITS", sizeof("Units") - 1, UNITS} , {"REFERENCE", sizeof("REFERENCE") - 1, REFERENCE} , {"NUM-ENTRIES", sizeof("NUM-ENTRIES") - 1, NUM_ENTRIES} , {"BITSTRING", sizeof("BITSTRING") - 1, BITSTRING} , {"BIT", sizeof("BIT") - 1, CONTINUE} , {"BITS", sizeof("BITS") - 1, BITSTRING} , {"Counter64", sizeof("Counter64") - 1, COUNTER64} , {"TimeTicks", sizeof("TimeTicks") - 1, TIMETICKS} , {"NOTIFICATION-TYPE", sizeof("NOTIFICATION-TYPE") - 1, NOTIFTYPE} , {"OBJECT-GROUP", sizeof("OBJECT-GROUP") - 1, OBJGROUP} , {"OBJECT-IDENTITY", sizeof("OBJECT-IDENTITY") - 1, OBJIDENTITY} , {"IDENTIFIER", sizeof("IDENTIFIER") - 1, IDENTIFIER} , {"OBJECT", sizeof("OBJECT") - 1, OBJECT} , {"NetworkAddress", sizeof("NetworkAddress") - 1, NETADDR} , {"Gauge", sizeof("Gauge") - 1, GAUGE} , {"Gauge32", sizeof("Gauge32") - 1, GAUGE} , {"Unsigned32", sizeof("Unsigned32") - 1, UNSIGNED32} , {"read-write", sizeof("read-write") - 1, READWRITE} , {"read-create", sizeof("read-create") - 1, READCREATE} , {"OCTETSTRING", sizeof("OCTETSTRING") - 1, OCTETSTR} , {"OCTET", sizeof("OCTET") - 1, CONTINUE} , {"OF", sizeof("OF") - 1, OF} , {"SEQUENCE", sizeof("SEQUENCE") - 1, SEQUENCE} , {"NULL", sizeof("NULL") - 1, NUL} , {"IpAddress", sizeof("IpAddress") - 1, IPADDR} , {"UInteger32", sizeof("UInteger32") - 1, UINTEGER32} , {"INTEGER", sizeof("INTEGER") - 1, INTEGER} , {"Integer32", sizeof("Integer32") - 1, INTEGER32} , {"Counter", sizeof("Counter") - 1, COUNTER} , {"Counter32", sizeof("Counter32") - 1, COUNTER} , {"read-only", sizeof("read-only") - 1, READONLY} , {"DESCRIPTION", sizeof("DESCRIPTION") - 1, DESCRIPTION} , {"INDEX", sizeof("INDEX") - 1, INDEX} , {"DEFVAL", sizeof("DEFVAL") - 1, DEFVAL} , {"deprecated", sizeof("deprecated") - 1, DEPRECATED} , {"SIZE", sizeof("SIZE") - 1, SIZE} , {"MAX-ACCESS", sizeof("MAX-ACCESS") - 1, ACCESS} , {"ACCESS", sizeof("ACCESS") - 1, ACCESS} , {"mandatory", sizeof("mandatory") - 1, MANDATORY} , {"current", sizeof("current") - 1, CURRENT} , {"STATUS", sizeof("STATUS") - 1, STATUS} , {"SYNTAX", sizeof("SYNTAX") - 1, SYNTAX} , {"OBJECT-TYPE", sizeof("OBJECT-TYPE") - 1, OBJTYPE} , {"TRAP-TYPE", sizeof("TRAP-TYPE") - 1, TRAPTYPE} , {"ENTERPRISE", sizeof("ENTERPRISE") - 1, ENTERPRISE} , {"BEGIN", sizeof("BEGIN") - 1, BEGIN} , {"IMPORTS", sizeof("IMPORTS") - 1, IMPORTS} , {"EXPORTS", sizeof("EXPORTS") - 1, EXPORTS} , {"accessible-for-notify", sizeof("accessible-for-notify") - 1, ACCNOTIFY} , {"TEXTUAL-CONVENTION", sizeof("TEXTUAL-CONVENTION") - 1, CONVENTION} , {"NOTIFICATION-GROUP", sizeof("NOTIFICATION-GROUP") - 1, NOTIFGROUP} , {"DISPLAY-HINT", sizeof("DISPLAY-HINT") - 1, DISPLAYHINT} , {"FROM", sizeof("FROM") - 1, FROM} , {"AGENT-CAPABILITIES", sizeof("AGENT-CAPABILITIES") - 1, AGENTCAP} , {"MACRO", sizeof("MACRO") - 1, MACRO} , {"IMPLIED", sizeof("IMPLIED") - 1, IMPLIED} , {"SUPPORTS", sizeof("SUPPORTS") - 1, SUPPORTS} , {"INCLUDES", sizeof("INCLUDES") - 1, INCLUDES} , {"VARIATION", sizeof("VARIATION") - 1, VARIATION} , {"REVISION", sizeof("REVISION") - 1, REVISION} , {"not-implemented", sizeof("not-implemented") - 1, NOTIMPL} , {"OBJECTS", sizeof("OBJECTS") - 1, OBJECTS} , {"NOTIFICATIONS", sizeof("NOTIFICATIONS") - 1, NOTIFICATIONS} , {"MODULE", sizeof("MODULE") - 1, MODULE} , {"MIN-ACCESS", sizeof("MIN-ACCESS") - 1, MINACCESS} , {"PRODUCT-RELEASE", sizeof("PRODUCT-RELEASE") - 1, PRODREL} , {"WRITE-SYNTAX", sizeof("WRITE-SYNTAX") - 1, WRSYNTAX} , {"CREATION-REQUIRES", sizeof("CREATION-REQUIRES") - 1, CREATEREQ} , {"MANDATORY-GROUPS", sizeof("MANDATORY-GROUPS") - 1, MANDATORYGROUPS} , {"GROUP", sizeof("GROUP") - 1, GROUP} , {"CHOICE", sizeof("CHOICE") - 1, CHOICE} , {"IMPLICIT", sizeof("IMPLICIT") - 1, IMPLICIT} , {"ObjectSyntax", sizeof("ObjectSyntax") - 1, OBJSYNTAX} , {"SimpleSyntax", sizeof("SimpleSyntax") - 1, SIMPLESYNTAX} , {"ApplicationSyntax", sizeof("ApplicationSyntax") - 1, APPSYNTAX} , {"ObjectName", sizeof("ObjectName") - 1, OBJNAME} , {"NotificationName", sizeof("NotificationName") - 1, NOTIFNAME} , {"VARIABLES", sizeof("VARIABLES") - 1, VARIABLES} , {NULL} }; static struct module_compatability *module_map_head; static struct module_compatability module_map[] = { {"RFC1065-SMI", "RFC1155-SMI", NULL, 0}, {"RFC1066-MIB", "RFC1156-MIB", NULL, 0}, /* * 'mib' -> 'mib-2' */ {"RFC1156-MIB", "RFC1158-MIB", NULL, 0}, /* * 'snmpEnableAuthTraps' -> 'snmpEnableAuthenTraps' */ {"RFC1158-MIB", "RFC1213-MIB", NULL, 0}, /* * 'nullOID' -> 'zeroDotZero' */ {"RFC1155-SMI", "SNMPv2-SMI", NULL, 0}, {"RFC1213-MIB", "SNMPv2-SMI", "mib-2", 0}, {"RFC1213-MIB", "SNMPv2-MIB", "sys", 3}, {"RFC1213-MIB", "IF-MIB", "if", 2}, {"RFC1213-MIB", "IP-MIB", "ip", 2}, {"RFC1213-MIB", "IP-MIB", "icmp", 4}, {"RFC1213-MIB", "TCP-MIB", "tcp", 3}, {"RFC1213-MIB", "UDP-MIB", "udp", 3}, {"RFC1213-MIB", "SNMPv2-SMI", "transmission", 0}, {"RFC1213-MIB", "SNMPv2-MIB", "snmp", 4}, {"RFC1231-MIB", "TOKENRING-MIB", NULL, 0}, {"RFC1271-MIB", "RMON-MIB", NULL, 0}, {"RFC1286-MIB", "SOURCE-ROUTING-MIB", "dot1dSr", 7}, {"RFC1286-MIB", "BRIDGE-MIB", NULL, 0}, {"RFC1315-MIB", "FRAME-RELAY-DTE-MIB", NULL, 0}, {"RFC1316-MIB", "CHARACTER-MIB", NULL, 0}, {"RFC1406-MIB", "DS1-MIB", NULL, 0}, {"RFC-1213", "RFC1213-MIB", NULL, 0}, }; #define MODULE_NOT_FOUND 0 #define MODULE_LOADED_OK 1 #define MODULE_ALREADY_LOADED 2 /* * #define MODULE_LOAD_FAILED 3 */ #define MODULE_LOAD_FAILED MODULE_NOT_FOUND #define MODULE_SYNTAX_ERROR 4 int gMibError = 0,gLoop = 0; static char *gpMibErrorString; char gMibNames[STRINGMAX]; #define HASHSIZE 32 #define BUCKET(x) (x & (HASHSIZE-1)) #define NHASHSIZE 128 #define NBUCKET(x) (x & (NHASHSIZE-1)) static struct tok *buckets[HASHSIZE]; static struct node *nbuckets[NHASHSIZE]; static struct tree *tbuckets[NHASHSIZE]; static struct module *module_head = NULL; static struct node *orphan_nodes = NULL; NETSNMP_IMPORT struct tree *tree_head; struct tree *tree_head = NULL; #define NUMBER_OF_ROOT_NODES 3 static struct module_import root_imports[NUMBER_OF_ROOT_NODES]; static int current_module = 0; static int max_module = 0; static int first_err_module = 1; static char *last_err_module = NULL; /* no repeats on "Cannot find module..." */ static void tree_from_node(struct tree *tp, struct node *np); static void do_subtree(struct tree *, struct node **); static void do_linkup(struct module *, struct node *); static void dump_module_list(void); static int get_token(FILE *, char *, int); static int parseQuoteString(FILE *, char *, int); static int tossObjectIdentifier(FILE *); static int name_hash(const char *); static void init_node_hash(struct node *); static void print_error(const char *, const char *, int); static void free_tree(struct tree *); static void free_partial_tree(struct tree *, int); static void free_node(struct node *); static void build_translation_table(void); static void init_tree_roots(void); static void merge_anon_children(struct tree *, struct tree *); static void unlink_tbucket(struct tree *); static void unlink_tree(struct tree *); static int getoid(FILE *, struct subid_s *, int); static struct node *parse_objectid(FILE *, char *); static int get_tc(const char *, int, int *, struct enum_list **, struct range_list **, char **); static int get_tc_index(const char *, int); static struct enum_list *parse_enumlist(FILE *, struct enum_list **); static struct range_list *parse_ranges(FILE * fp, struct range_list **); static struct node *parse_asntype(FILE *, char *, int *, char *); static struct node *parse_objecttype(FILE *, char *); static struct node *parse_objectgroup(FILE *, char *, int, struct objgroup **); static struct node *parse_notificationDefinition(FILE *, char *); static struct node *parse_trapDefinition(FILE *, char *); static struct node *parse_compliance(FILE *, char *); static struct node *parse_capabilities(FILE *, char *); static struct node *parse_moduleIdentity(FILE *, char *); static struct node *parse_macro(FILE *, char *); static void parse_imports(FILE *); static struct node *parse(FILE *, struct node *); static int read_module_internal(const char *); static int read_module_replacements(const char *); static int read_import_replacements(const char *, struct module_import *); static struct node *merge_parse_objectid(struct node *, FILE *, char *); static struct index_list *getIndexes(FILE * fp, struct index_list **); static struct varbind_list *getVarbinds(FILE * fp, struct varbind_list **); static void free_indexes(struct index_list **); static void free_varbinds(struct varbind_list **); static void free_ranges(struct range_list **); static void free_enums(struct enum_list **); static struct range_list *copy_ranges(struct range_list *); static struct enum_list *copy_enums(struct enum_list *); static u_int compute_match(const char *search_base, const char *key); void snmp_mib_toggle_options_usage(const char *lead, FILE * outf) { fprintf(outf, "%su: %sallow the use of underlines in MIB symbols\n", lead, ((netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_PARSE_LABEL)) ? "dis" : "")); fprintf(outf, "%sc: %sallow the use of \"--\" to terminate comments\n", lead, ((netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_COMMENT_TERM)) ? "" : "dis")); fprintf(outf, "%sd: %ssave the DESCRIPTIONs of the MIB objects\n", lead, ((netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_SAVE_MIB_DESCRS)) ? "do not " : "")); fprintf(outf, "%se: disable errors when MIB symbols conflict\n", lead); fprintf(outf, "%sw: enable warnings when MIB symbols conflict\n", lead); fprintf(outf, "%sW: enable detailed warnings when MIB symbols conflict\n", lead); fprintf(outf, "%sR: replace MIB symbols from latest module\n", lead); } char * snmp_mib_toggle_options(char *options) { if (options) { while (*options) { switch (*options) { case 'u': netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_PARSE_LABEL, !netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_PARSE_LABEL)); break; case 'c': netsnmp_ds_toggle_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_COMMENT_TERM); break; case 'e': netsnmp_ds_toggle_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_ERRORS); break; case 'w': netsnmp_ds_set_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_WARNINGS, 1); break; case 'W': netsnmp_ds_set_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_WARNINGS, 2); break; case 'd': netsnmp_ds_toggle_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_SAVE_MIB_DESCRS); break; case 'R': netsnmp_ds_toggle_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_REPLACE); break; default: /* * return at the unknown option */ return options; } options++; } } return NULL; } static int name_hash(const char *name) { int hash = 0; const char *cp; if (!name) return 0; for (cp = name; *cp; cp++) hash += tolower((unsigned char)(*cp)); return (hash); } void netsnmp_init_mib_internals(void) { register struct tok *tp; register int b, i; int max_modc; if (tree_head) return; /* * Set up hash list of pre-defined tokens */ memset(buckets, 0, sizeof(buckets)); for (tp = tokens; tp->name; tp++) { tp->hash = name_hash(tp->name); b = BUCKET(tp->hash); if (buckets[b]) tp->next = buckets[b]; /* BUG ??? */ buckets[b] = tp; } /* * Initialise other internal structures */ max_modc = sizeof(module_map) / sizeof(module_map[0]) - 1; for (i = 0; i < max_modc; ++i) module_map[i].next = &(module_map[i + 1]); module_map[max_modc].next = NULL; module_map_head = module_map; memset(nbuckets, 0, sizeof(nbuckets)); memset(tbuckets, 0, sizeof(tbuckets)); memset(tclist, 0, MAXTC * sizeof(struct tc)); build_translation_table(); init_tree_roots(); /* Set up initial roots */ /* * Relies on 'add_mibdir' having set up the modules */ } #ifndef NETSNMP_NO_LEGACY_DEFINITIONS void init_mib_internals(void) { netsnmp_init_mib_internals(); } #endif static void init_node_hash(struct node *nodes) { struct node *np, *nextp; int hash; memset(nbuckets, 0, sizeof(nbuckets)); for (np = nodes; np;) { nextp = np->next; hash = NBUCKET(name_hash(np->parent)); np->next = nbuckets[hash]; nbuckets[hash] = np; np = nextp; } } static int erroneousMibs = 0; netsnmp_feature_child_of(parse_get_error_count, netsnmp_unused) #ifndef NETSNMP_FEATURE_REMOVE_PARSE_GET_ERROR_COUNT int get_mib_parse_error_count(void) { return erroneousMibs; } #endif /* NETSNMP_FEATURE_REMOVE_PARSE_GET_ERROR_COUNT */ static void print_error(const char *str, const char *token, int type) { erroneousMibs++; if (!netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_ERRORS)) return; DEBUGMSGTL(("parse-mibs", "\n")); if (type == ENDOFFILE) snmp_log(LOG_ERR, "%s (EOF): At line %d in %s\n", str, mibLine, File); else if (token && *token) snmp_log(LOG_ERR, "%s (%s): At line %d in %s\n", str, token, mibLine, File); else snmp_log(LOG_ERR, "%s: At line %d in %s\n", str, mibLine, File); } static void print_module_not_found(const char *cp) { if (first_err_module) { snmp_log(LOG_ERR, "MIB search path: %s\n", netsnmp_get_mib_directory()); first_err_module = 0; } if (!last_err_module || strcmp(cp, last_err_module)) print_error("Cannot find module", cp, CONTINUE); if (last_err_module) free(last_err_module); last_err_module = strdup(cp); } static struct node * alloc_node(int modid) { struct node *np; np = (struct node *) calloc(1, sizeof(struct node)); if (np) { np->tc_index = -1; np->modid = modid; np->filename = strdup(File); np->lineno = mibLine; } return np; } static void unlink_tbucket(struct tree *tp) { int hash = NBUCKET(name_hash(tp->label)); struct tree *otp = NULL, *ntp = tbuckets[hash]; while (ntp && ntp != tp) { otp = ntp; ntp = ntp->next; } if (!ntp) snmp_log(LOG_EMERG, "Can't find %s in tbuckets\n", tp->label); else if (otp) otp->next = ntp->next; else tbuckets[hash] = tp->next; } static void unlink_tree(struct tree *tp) { struct tree *otp = NULL, *ntp = tp->parent; if (!ntp) { /* this tree has no parent */ DEBUGMSGTL(("unlink_tree", "Tree node %s has no parent\n", tp->label)); } else { ntp = ntp->child_list; while (ntp && ntp != tp) { otp = ntp; ntp = ntp->next_peer; } if (!ntp) snmp_log(LOG_EMERG, "Can't find %s in %s's children\n", tp->label, tp->parent->label); else if (otp) otp->next_peer = ntp->next_peer; else tp->parent->child_list = tp->next_peer; } if (tree_head == tp) tree_head = tp->next_peer; } static void free_partial_tree(struct tree *tp, int keep_label) { if (!tp) return; /* * remove the data from this tree node */ free_enums(&tp->enums); free_ranges(&tp->ranges); free_indexes(&tp->indexes); free_varbinds(&tp->varbinds); if (!keep_label) SNMP_FREE(tp->label); SNMP_FREE(tp->hint); SNMP_FREE(tp->units); SNMP_FREE(tp->description); SNMP_FREE(tp->reference); SNMP_FREE(tp->augments); SNMP_FREE(tp->defaultValue); } /* * free a tree node. Note: the node must already have been unlinked * from the tree when calling this routine */ static void free_tree(struct tree *Tree) { if (!Tree) return; unlink_tbucket(Tree); free_partial_tree(Tree, FALSE); if (Tree->module_list != &Tree->modid) free(Tree->module_list); free(Tree); } static void free_node(struct node *np) { if (!np) return; free_enums(&np->enums); free_ranges(&np->ranges); free_indexes(&np->indexes); free_varbinds(&np->varbinds); if (np->label) free(np->label); if (np->hint) free(np->hint); if (np->units) free(np->units); if (np->description) free(np->description); if (np->reference) free(np->reference); if (np->defaultValue) free(np->defaultValue); if (np->parent) free(np->parent); if (np->augments) free(np->augments); if (np->filename) free(np->filename); free((char *) np); } static void print_range_value(FILE * fp, int type, struct range_list * rp) { switch (type) { case TYPE_INTEGER: case TYPE_INTEGER32: if (rp->low == rp->high) fprintf(fp, "%d", rp->low); else fprintf(fp, "%d..%d", rp->low, rp->high); break; case TYPE_UNSIGNED32: case TYPE_OCTETSTR: case TYPE_GAUGE: case TYPE_UINTEGER: if (rp->low == rp->high) fprintf(fp, "%u", (unsigned)rp->low); else fprintf(fp, "%u..%u", (unsigned)rp->low, (unsigned)rp->high); break; default: /* No other range types allowed */ break; } } #ifdef TEST static void print_nodes(FILE * fp, struct node *root) { struct enum_list *ep; struct index_list *ip; struct varbind_list *vp; struct node *np; for (np = root; np; np = np->next) { fprintf(fp, "%s ::= { %s %ld } (%d)\n", np->label, np->parent, np->subid, np->type); if (np->tc_index >= 0) fprintf(fp, " TC = %s\n", tclist[np->tc_index].descriptor); if (np->enums) { fprintf(fp, " Enums: \n"); for (ep = np->enums; ep; ep = ep->next) { fprintf(fp, " %s(%d)\n", ep->label, ep->value); } } if (np->ranges) { struct range_list *rp; fprintf(fp, " Ranges: "); for (rp = np->ranges; rp; rp = rp->next) { fprintf(fp, "\n "); print_range_value(fp, np->type, rp); } fprintf(fp, "\n"); } if (np->indexes) { fprintf(fp, " Indexes: \n"); for (ip = np->indexes; ip; ip = ip->next) { fprintf(fp, " %s\n", ip->ilabel); } } if (np->augments) fprintf(fp, " Augments: %s\n", np->augments); if (np->varbinds) { fprintf(fp, " Varbinds: \n"); for (vp = np->varbinds; vp; vp = vp->next) { fprintf(fp, " %s\n", vp->vblabel); } } if (np->hint) fprintf(fp, " Hint: %s\n", np->hint); if (np->units) fprintf(fp, " Units: %s\n", np->units); if (np->defaultValue) fprintf(fp, " DefaultValue: %s\n", np->defaultValue); } } #endif void print_subtree(FILE * f, struct tree *tree, int count) { struct tree *tp; int i; char modbuf[256]; for (i = 0; i < count; i++) fprintf(f, " "); fprintf(f, "Children of %s(%ld):\n", tree->label, tree->subid); count++; for (tp = tree->child_list; tp; tp = tp->next_peer) { for (i = 0; i < count; i++) fprintf(f, " "); fprintf(f, "%s:%s(%ld) type=%d", module_name(tp->module_list[0], modbuf), tp->label, tp->subid, tp->type); if (tp->tc_index != -1) fprintf(f, " tc=%d", tp->tc_index); if (tp->hint) fprintf(f, " hint=%s", tp->hint); if (tp->units) fprintf(f, " units=%s", tp->units); if (tp->number_modules > 1) { fprintf(f, " modules:"); for (i = 1; i < tp->number_modules; i++) fprintf(f, " %s", module_name(tp->module_list[i], modbuf)); } fprintf(f, "\n"); } for (tp = tree->child_list; tp; tp = tp->next_peer) { if (tp->child_list) print_subtree(f, tp, count); } } void print_ascii_dump_tree(FILE * f, struct tree *tree, int count) { struct tree *tp; count++; for (tp = tree->child_list; tp; tp = tp->next_peer) { fprintf(f, "%s OBJECT IDENTIFIER ::= { %s %ld }\n", tp->label, tree->label, tp->subid); } for (tp = tree->child_list; tp; tp = tp->next_peer) { if (tp->child_list) print_ascii_dump_tree(f, tp, count); } } static int translation_table[256]; static void build_translation_table(void) { int count; for (count = 0; count < 256; count++) { switch (count) { case OBJID: translation_table[count] = TYPE_OBJID; break; case OCTETSTR: translation_table[count] = TYPE_OCTETSTR; break; case INTEGER: translation_table[count] = TYPE_INTEGER; break; case NETADDR: translation_table[count] = TYPE_NETADDR; break; case IPADDR: translation_table[count] = TYPE_IPADDR; break; case COUNTER: translation_table[count] = TYPE_COUNTER; break; case GAUGE: translation_table[count] = TYPE_GAUGE; break; case TIMETICKS: translation_table[count] = TYPE_TIMETICKS; break; case KW_OPAQUE: translation_table[count] = TYPE_OPAQUE; break; case NUL: translation_table[count] = TYPE_NULL; break; case COUNTER64: translation_table[count] = TYPE_COUNTER64; break; case BITSTRING: translation_table[count] = TYPE_BITSTRING; break; case NSAPADDRESS: translation_table[count] = TYPE_NSAPADDRESS; break; case INTEGER32: translation_table[count] = TYPE_INTEGER32; break; case UINTEGER32: translation_table[count] = TYPE_UINTEGER; break; case UNSIGNED32: translation_table[count] = TYPE_UNSIGNED32; break; case TRAPTYPE: translation_table[count] = TYPE_TRAPTYPE; break; case NOTIFTYPE: translation_table[count] = TYPE_NOTIFTYPE; break; case NOTIFGROUP: translation_table[count] = TYPE_NOTIFGROUP; break; case OBJGROUP: translation_table[count] = TYPE_OBJGROUP; break; case MODULEIDENTITY: translation_table[count] = TYPE_MODID; break; case OBJIDENTITY: translation_table[count] = TYPE_OBJIDENTITY; break; case AGENTCAP: translation_table[count] = TYPE_AGENTCAP; break; case COMPLIANCE: translation_table[count] = TYPE_MODCOMP; break; default: translation_table[count] = TYPE_OTHER; break; } } } static void init_tree_roots(void) { struct tree *tp, *lasttp; int base_modid; int hash; base_modid = which_module("SNMPv2-SMI"); if (base_modid == -1) base_modid = which_module("RFC1155-SMI"); if (base_modid == -1) base_modid = which_module("RFC1213-MIB"); /* * build root node */ tp = (struct tree *) calloc(1, sizeof(struct tree)); if (tp == NULL) return; tp->label = strdup("joint-iso-ccitt"); tp->modid = base_modid; tp->number_modules = 1; tp->module_list = &(tp->modid); tp->subid = 2; tp->tc_index = -1; set_function(tp); /* from mib.c */ hash = NBUCKET(name_hash(tp->label)); tp->next = tbuckets[hash]; tbuckets[hash] = tp; lasttp = tp; root_imports[0].label = strdup(tp->label); root_imports[0].modid = base_modid; /* * build root node */ tp = (struct tree *) calloc(1, sizeof(struct tree)); if (tp == NULL) return; tp->next_peer = lasttp; tp->label = strdup("ccitt"); tp->modid = base_modid; tp->number_modules = 1; tp->module_list = &(tp->modid); tp->subid = 0; tp->tc_index = -1; set_function(tp); /* from mib.c */ hash = NBUCKET(name_hash(tp->label)); tp->next = tbuckets[hash]; tbuckets[hash] = tp; lasttp = tp; root_imports[1].label = strdup(tp->label); root_imports[1].modid = base_modid; /* * build root node */ tp = (struct tree *) calloc(1, sizeof(struct tree)); if (tp == NULL) return; tp->next_peer = lasttp; tp->label = strdup("iso"); tp->modid = base_modid; tp->number_modules = 1; tp->module_list = &(tp->modid); tp->subid = 1; tp->tc_index = -1; set_function(tp); /* from mib.c */ hash = NBUCKET(name_hash(tp->label)); tp->next = tbuckets[hash]; tbuckets[hash] = tp; lasttp = tp; root_imports[2].label = strdup(tp->label); root_imports[2].modid = base_modid; tree_head = tp; } #ifdef STRICT_MIB_PARSEING #define label_compare strcasecmp #else #define label_compare strcmp #endif struct tree * find_tree_node(const char *name, int modid) { struct tree *tp, *headtp; int count, *int_p; if (!name || !*name) return (NULL); headtp = tbuckets[NBUCKET(name_hash(name))]; for (tp = headtp; tp; tp = tp->next) { if (tp->label && !label_compare(tp->label, name)) { if (modid == -1) /* Any module */ return (tp); for (int_p = tp->module_list, count = 0; count < tp->number_modules; ++count, ++int_p) if (*int_p == modid) return (tp); } } return (NULL); } /* * computes a value which represents how close name1 is to name2. * * high scores mean a worse match. * * (yes, the algorithm sucks!) */ #define MAX_BAD 0xffffff static u_int compute_match(const char *search_base, const char *key) { #if defined(HAVE_REGEX_H) && defined(HAVE_REGCOMP) int rc; regex_t parsetree; regmatch_t pmatch; rc = regcomp(&parsetree, key, REG_ICASE | REG_EXTENDED); if (rc == 0) rc = regexec(&parsetree, search_base, 1, &pmatch, 0); regfree(&parsetree); if (rc == 0) { /* * found */ return pmatch.rm_so; } #else /* use our own wildcard matcher */ /* * first find the longest matching substring (ick) */ char *first = NULL, *result = NULL, *entry; const char *position; char *newkey = strdup(key); char *st; entry = strtok_r(newkey, "*", &st); position = search_base; while (entry) { result = strcasestr(position, entry); if (result == NULL) { free(newkey); return MAX_BAD; } if (first == NULL) first = result; position = result + strlen(entry); entry = strtok_r(NULL, "*", &st); } free(newkey); if (result) return (first - search_base); #endif /* * not found */ return MAX_BAD; } /* * Find the tree node that best matches the pattern string. * Use the "reported" flag such that only one match * is attempted for every node. * * Warning! This function may recurse. * * Caller _must_ invoke clear_tree_flags before first call * to this function. This function may be called multiple times * to ensure that the entire tree is traversed. */ struct tree * find_best_tree_node(const char *pattrn, struct tree *tree_top, u_int * match) { struct tree *tp, *best_so_far = NULL, *retptr; u_int old_match = MAX_BAD, new_match = MAX_BAD; if (!pattrn || !*pattrn) return (NULL); if (!tree_top) tree_top = get_tree_head(); for (tp = tree_top; tp; tp = tp->next_peer) { if (!tp->reported && tp->label) new_match = compute_match(tp->label, pattrn); tp->reported = 1; if (new_match < old_match) { best_so_far = tp; old_match = new_match; } if (new_match == 0) break; /* this is the best result we can get */ if (tp->child_list) { retptr = find_best_tree_node(pattrn, tp->child_list, &new_match); if (new_match < old_match) { best_so_far = retptr; old_match = new_match; } if (new_match == 0) break; /* this is the best result we can get */ } } if (match) *match = old_match; return (best_so_far); } static void merge_anon_children(struct tree *tp1, struct tree *tp2) /* * NB: tp1 is the 'anonymous' node */ { struct tree *child1, *child2, *previous; for (child1 = tp1->child_list; child1;) { for (child2 = tp2->child_list, previous = NULL; child2; previous = child2, child2 = child2->next_peer) { if (child1->subid == child2->subid) { /* * Found 'matching' children, * so merge them */ if (!strncmp(child1->label, ANON, ANON_LEN)) { merge_anon_children(child1, child2); child1->child_list = NULL; previous = child1; /* Finished with 'child1' */ child1 = child1->next_peer; free_tree(previous); goto next; } else if (!strncmp(child2->label, ANON, ANON_LEN)) { merge_anon_children(child2, child1); if (previous) previous->next_peer = child2->next_peer; else tp2->child_list = child2->next_peer; free_tree(child2); previous = child1; /* Move 'child1' to 'tp2' */ child1 = child1->next_peer; previous->next_peer = tp2->child_list; tp2->child_list = previous; for (previous = tp2->child_list; previous; previous = previous->next_peer) previous->parent = tp2; goto next; } else if (!label_compare(child1->label, child2->label)) { if (netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_WARNINGS)) { snmp_log(LOG_WARNING, "Warning: %s.%ld is both %s and %s (%s)\n", tp2->label, child1->subid, child1->label, child2->label, File); } continue; } else { /* * Two copies of the same node. * 'child2' adopts the children of 'child1' */ if (child2->child_list) { for (previous = child2->child_list; previous->next_peer; previous = previous->next_peer); /* Find the end of the list */ previous->next_peer = child1->child_list; } else child2->child_list = child1->child_list; for (previous = child1->child_list; previous; previous = previous->next_peer) previous->parent = child2; child1->child_list = NULL; previous = child1; /* Finished with 'child1' */ child1 = child1->next_peer; free_tree(previous); goto next; } } } /* * If no match, move 'child1' to 'tp2' child_list */ if (child1) { previous = child1; child1 = child1->next_peer; previous->parent = tp2; previous->next_peer = tp2->child_list; tp2->child_list = previous; } next:; } } /* * Find all the children of root in the list of nodes. Link them into the * tree and out of the nodes list. */ static void do_subtree(struct tree *root, struct node **nodes) { struct tree *tp, *anon_tp = NULL; struct tree *xroot = root; struct node *np, **headp; struct node *oldnp = NULL, *child_list = NULL, *childp = NULL; int hash; int *int_p; while (xroot->next_peer && xroot->next_peer->subid == root->subid) { #if 0 printf("xroot: %s.%s => %s\n", xroot->parent->label, xroot->label, xroot->next_peer->label); #endif xroot = xroot->next_peer; } tp = root; headp = &nbuckets[NBUCKET(name_hash(tp->label))]; /* * Search each of the nodes for one whose parent is root, and * move each into a separate list. */ for (np = *headp; np; np = np->next) { if (!label_compare(tp->label, np->parent)) { /* * take this node out of the node list */ if (oldnp == NULL) { *headp = np->next; /* fix root of node list */ } else { oldnp->next = np->next; /* link around this node */ } if (child_list) childp->next = np; else child_list = np; childp = np; } else { oldnp = np; } } if (childp) childp->next = NULL; /* * Take each element in the child list and place it into the tree. */ for (np = child_list; np; np = np->next) { struct tree *otp = NULL; struct tree *xxroot = xroot; anon_tp = NULL; tp = xroot->child_list; if (np->subid == -1) { /* * name ::= { parent } */ np->subid = xroot->subid; tp = xroot; xxroot = xroot->parent; } while (tp) { if (tp->subid == np->subid) break; else { otp = tp; tp = tp->next_peer; } } if (tp) { if (!label_compare(tp->label, np->label)) { /* * Update list of modules */ int_p = malloc((tp->number_modules + 1) * sizeof(int)); if (int_p == NULL) return; memcpy(int_p, tp->module_list, tp->number_modules * sizeof(int)); int_p[tp->number_modules] = np->modid; if (tp->module_list != &tp->modid) free(tp->module_list); ++tp->number_modules; tp->module_list = int_p; if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_REPLACE)) { /* * Replace from node */ tree_from_node(tp, np); } /* * Handle children */ do_subtree(tp, nodes); continue; } if (!strncmp(np->label, ANON, ANON_LEN) || !strncmp(tp->label, ANON, ANON_LEN)) { anon_tp = tp; /* Need to merge these two trees later */ } else if (netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_WARNINGS)) { snmp_log(LOG_WARNING, "Warning: %s.%ld is both %s and %s (%s)\n", root->label, np->subid, tp->label, np->label, File); } } tp = (struct tree *) calloc(1, sizeof(struct tree)); if (tp == NULL) return; tp->parent = xxroot; tp->modid = np->modid; tp->number_modules = 1; tp->module_list = &(tp->modid); tree_from_node(tp, np); tp->next_peer = otp ? otp->next_peer : xxroot->child_list; if (otp) otp->next_peer = tp; else xxroot->child_list = tp; hash = NBUCKET(name_hash(tp->label)); tp->next = tbuckets[hash]; tbuckets[hash] = tp; do_subtree(tp, nodes); if (anon_tp) { if (!strncmp(tp->label, ANON, ANON_LEN)) { /* * The new node is anonymous, * so merge it with the existing one. */ merge_anon_children(tp, anon_tp); /* * unlink and destroy tp */ unlink_tree(tp); free_tree(tp); } else if (!strncmp(anon_tp->label, ANON, ANON_LEN)) { struct tree *ntp; /* * The old node was anonymous, * so merge it with the existing one, * and fill in the full information. */ merge_anon_children(anon_tp, tp); /* * unlink anon_tp from the hash */ unlink_tbucket(anon_tp); /* * get rid of old contents of anon_tp */ free_partial_tree(anon_tp, FALSE); /* * put in the current information */ anon_tp->label = tp->label; anon_tp->child_list = tp->child_list; anon_tp->modid = tp->modid; anon_tp->tc_index = tp->tc_index; anon_tp->type = tp->type; anon_tp->enums = tp->enums; anon_tp->indexes = tp->indexes; anon_tp->augments = tp->augments; anon_tp->varbinds = tp->varbinds; anon_tp->ranges = tp->ranges; anon_tp->hint = tp->hint; anon_tp->units = tp->units; anon_tp->description = tp->description; anon_tp->reference = tp->reference; anon_tp->defaultValue = tp->defaultValue; anon_tp->parent = tp->parent; set_function(anon_tp); /* * update parent pointer in moved children */ ntp = anon_tp->child_list; while (ntp) { ntp->parent = anon_tp; ntp = ntp->next_peer; } /* * hash in anon_tp in its new place */ hash = NBUCKET(name_hash(anon_tp->label)); anon_tp->next = tbuckets[hash]; tbuckets[hash] = anon_tp; /* * unlink and destroy tp */ unlink_tbucket(tp); unlink_tree(tp); free(tp); } else { /* * Uh? One of these two should have been anonymous! */ if (netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_WARNINGS)) { snmp_log(LOG_WARNING, "Warning: expected anonymous node (either %s or %s) in %s\n", tp->label, anon_tp->label, File); } } anon_tp = NULL; } } /* * free all nodes that were copied into tree */ oldnp = NULL; for (np = child_list; np; np = np->next) { if (oldnp) free_node(oldnp); oldnp = np; } if (oldnp) free_node(oldnp); } static void do_linkup(struct module *mp, struct node *np) { struct module_import *mip; struct node *onp, *oldp, *newp; struct tree *tp; int i, more; /* * All modules implicitly import * the roots of the tree */ if (snmp_get_do_debugging() > 1) dump_module_list(); DEBUGMSGTL(("parse-mibs", "Processing IMPORTS for module %d %s\n", mp->modid, mp->name)); if (mp->no_imports == 0) { mp->no_imports = NUMBER_OF_ROOT_NODES; mp->imports = root_imports; } /* * Build the tree */ init_node_hash(np); for (i = 0, mip = mp->imports; i < mp->no_imports; ++i, ++mip) { char modbuf[256]; DEBUGMSGTL(("parse-mibs", " Processing import: %s\n", mip->label)); if (get_tc_index(mip->label, mip->modid) != -1) continue; tp = find_tree_node(mip->label, mip->modid); if (!tp) { if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_ERRORS)) snmp_log(LOG_WARNING, "Did not find '%s' in module %s (%s)\n", mip->label, module_name(mip->modid, modbuf), File); continue; } do_subtree(tp, &np); } /* * If any nodes left over, * check that they're not the result of a "fully qualified" * name, and then add them to the list of orphans */ if (!np) return; for (tp = tree_head; tp; tp = tp->next_peer) do_subtree(tp, &np); if (!np) return; /* * quietly move all internal references to the orphan list */ oldp = orphan_nodes; do { for (i = 0; i < NHASHSIZE; i++) for (onp = nbuckets[i]; onp; onp = onp->next) { struct node *op = NULL; int hash = NBUCKET(name_hash(onp->label)); np = nbuckets[hash]; while (np) { if (label_compare(onp->label, np->parent)) { op = np; np = np->next; } else { if (op) op->next = np->next; else nbuckets[hash] = np->next; DEBUGMSGTL(("parse-mibs", "Moving %s to orphanage", np->label)); np->next = orphan_nodes; orphan_nodes = np; op = NULL; np = nbuckets[hash]; } } } newp = orphan_nodes; more = 0; for (onp = orphan_nodes; onp != oldp; onp = onp->next) { struct node *op = NULL; int hash = NBUCKET(name_hash(onp->label)); np = nbuckets[hash]; while (np) { if (label_compare(onp->label, np->parent)) { op = np; np = np->next; } else { if (op) op->next = np->next; else nbuckets[hash] = np->next; np->next = orphan_nodes; orphan_nodes = np; op = NULL; np = nbuckets[hash]; more = 1; } } } oldp = newp; } while (more); /* * complain about left over nodes */ for (np = orphan_nodes; np && np->next; np = np->next); /* find the end of the orphan list */ for (i = 0; i < NHASHSIZE; i++) if (nbuckets[i]) { if (orphan_nodes) onp = np->next = nbuckets[i]; else onp = orphan_nodes = nbuckets[i]; nbuckets[i] = NULL; while (onp) { snmp_log(LOG_WARNING, "Unlinked OID in %s: %s ::= { %s %ld }\n", (mp->name ? mp->name : "<no module>"), (onp->label ? onp->label : "<no label>"), (onp->parent ? onp->parent : "<no parent>"), onp->subid); snmp_log(LOG_WARNING, "Undefined identifier: %s near line %d of %s\n", (onp->parent ? onp->parent : "<no parent>"), onp->lineno, onp->filename); np = onp; onp = onp->next; } } return; } /* * Takes a list of the form: * { iso org(3) dod(6) 1 } * and creates several nodes, one for each parent-child pair. * Returns 0 on error. */ static int getoid(FILE * fp, struct subid_s *id, /* an array of subids */ int length) { /* the length of the array */ register int count; int type; char token[MAXTOKEN]; if ((type = get_token(fp, token, MAXTOKEN)) != LEFTBRACKET) { print_error("Expected \"{\"", token, type); return 0; } type = get_token(fp, token, MAXTOKEN); for (count = 0; count < length; count++, id++) { id->label = NULL; id->modid = current_module; id->subid = -1; if (type == RIGHTBRACKET) return count; if (type == LABEL) { /* * this entry has a label */ id->label = strdup(token); type = get_token(fp, token, MAXTOKEN); if (type == LEFTPAREN) { type = get_token(fp, token, MAXTOKEN); if (type == NUMBER) { id->subid = strtoul(token, NULL, 10); if ((type = get_token(fp, token, MAXTOKEN)) != RIGHTPAREN) { print_error("Expected a closing parenthesis", token, type); return 0; } } else { print_error("Expected a number", token, type); return 0; } } else { continue; } } else if (type == NUMBER) { /* * this entry has just an integer sub-identifier */ id->subid = strtoul(token, NULL, 10); } else { print_error("Expected label or number", token, type); return 0; } type = get_token(fp, token, MAXTOKEN); } print_error("Too long OID", token, type); return 0; } /* * Parse a sequence of object subidentifiers for the given name. * The "label OBJECT IDENTIFIER ::=" portion has already been parsed. * * The majority of cases take this form : * label OBJECT IDENTIFIER ::= { parent 2 } * where a parent label and a child subidentifier number are specified. * * Variations on the theme include cases where a number appears with * the parent, or intermediate subidentifiers are specified by label, * by number, or both. * * Here are some representative samples : * internet OBJECT IDENTIFIER ::= { iso org(3) dod(6) 1 } * mgmt OBJECT IDENTIFIER ::= { internet 2 } * rptrInfoHealth OBJECT IDENTIFIER ::= { snmpDot3RptrMgt 0 4 } * * Here is a very rare form : * iso OBJECT IDENTIFIER ::= { 1 } * * Returns NULL on error. When this happens, memory may be leaked. */ static struct node * parse_objectid(FILE * fp, char *name) { register int count; register struct subid_s *op, *nop; int length; struct subid_s loid[32]; struct node *np, *root = NULL, *oldnp = NULL; struct tree *tp; if ((length = getoid(fp, loid, 32)) == 0) { print_error("Bad object identifier", NULL, CONTINUE); return NULL; } /* * Handle numeric-only object identifiers, * by labelling the first sub-identifier */ op = loid; if (!op->label) { if (length == 1) { print_error("Attempt to define a root oid", name, OBJECT); return NULL; } for (tp = tree_head; tp; tp = tp->next_peer) if ((int) tp->subid == op->subid) { op->label = strdup(tp->label); break; } } /* * Handle "label OBJECT-IDENTIFIER ::= { subid }" */ if (length == 1) { op = loid; np = alloc_node(op->modid); if (np == NULL) return (NULL); np->subid = op->subid; np->label = strdup(name); np->parent = op->label; return np; } /* * For each parent-child subid pair in the subid array, * create a node and link it into the node list. */ for (count = 0, op = loid, nop = loid + 1; count < (length - 1); count++, op++, nop++) { /* * every node must have parent's name and child's name or number */ /* * XX the next statement is always true -- does it matter ?? */ if (op->label && (nop->label || (nop->subid != -1))) { np = alloc_node(nop->modid); if (np == NULL) goto err; if (root == NULL) root = np; np->parent = strdup(op->label); if (count == (length - 2)) { /* * The name for this node is the label for this entry */ np->label = strdup(name); if (np->label == NULL) goto err; } else { if (!nop->label) { nop->label = (char *) malloc(20 + ANON_LEN); if (nop->label == NULL) goto err; sprintf(nop->label, "%s%d", ANON, anonymous++); } np->label = strdup(nop->label); } if (nop->subid != -1) np->subid = nop->subid; else print_error("Warning: This entry is pretty silly", np->label, CONTINUE); /* * set up next entry */ if (oldnp) oldnp->next = np; oldnp = np; } /* end if(op->label... */ } out: /* * free the loid array */ for (count = 0, op = loid; count < length; count++, op++) { if (op->label) free(op->label); } return root; err: for (; root; root = np) { np = root->next; free_node(root); } goto out; } static int get_tc(const char *descriptor, int modid, int *tc_index, struct enum_list **ep, struct range_list **rp, char **hint) { int i; struct tc *tcp; i = get_tc_index(descriptor, modid); if (tc_index) *tc_index = i; if (i != -1) { tcp = &tclist[i]; if (ep) { free_enums(ep); *ep = copy_enums(tcp->enums); } if (rp) { free_ranges(rp); *rp = copy_ranges(tcp->ranges); } if (hint) { if (*hint) free(*hint); *hint = (tcp->hint ? strdup(tcp->hint) : NULL); } return tcp->type; } return LABEL; } /* * return index into tclist of given TC descriptor * return -1 if not found */ static int get_tc_index(const char *descriptor, int modid) { int i; struct tc *tcp; struct module *mp; struct module_import *mip; /* * Check that the descriptor isn't imported * by searching the import list */ for (mp = module_head; mp; mp = mp->next) if (mp->modid == modid) break; if (mp) for (i = 0, mip = mp->imports; i < mp->no_imports; ++i, ++mip) { if (!label_compare(mip->label, descriptor)) { /* * Found it - so amend the module ID */ modid = mip->modid; break; } } for (i = 0, tcp = tclist; i < MAXTC; i++, tcp++) { if (tcp->type == 0) break; if (!label_compare(descriptor, tcp->descriptor) && ((modid == tcp->modid) || (modid == -1))) { return i; } } return -1; } /* * translate integer tc_index to string identifier from tclist * * * * Returns pointer to string in table (should not be modified) or NULL */ const char * get_tc_descriptor(int tc_index) { if (tc_index < 0 || tc_index >= MAXTC) return NULL; return (tclist[tc_index].descriptor); } #ifndef NETSNMP_FEATURE_REMOVE_GET_TC_DESCRIPTION /* used in the perl module */ const char * get_tc_description(int tc_index) { if (tc_index < 0 || tc_index >= MAXTC) return NULL; return (tclist[tc_index].description); } #endif /* NETSNMP_FEATURE_REMOVE_GET_TC_DESCRIPTION */ /* * Parses an enumeration list of the form: * { label(value) label(value) ... } * The initial { has already been parsed. * Returns NULL on error. */ static struct enum_list * parse_enumlist(FILE * fp, struct enum_list **retp) { register int type; char token[MAXTOKEN]; struct enum_list *ep = NULL, **epp = &ep; free_enums(retp); while ((type = get_token(fp, token, MAXTOKEN)) != ENDOFFILE) { if (type == RIGHTBRACKET) break; /* some enums use "deprecated" to indicate a no longer value label */ /* (EG: IP-MIB's IpAddressStatusTC) */ if (type == LABEL || type == DEPRECATED) { /* * this is an enumerated label */ *epp = (struct enum_list *) calloc(1, sizeof(struct enum_list)); if (*epp == NULL) return (NULL); /* * a reasonable approximation for the length */ (*epp)->label = strdup(token); type = get_token(fp, token, MAXTOKEN); if (type != LEFTPAREN) { print_error("Expected \"(\"", token, type); return NULL; } type = get_token(fp, token, MAXTOKEN); if (type != NUMBER) { print_error("Expected integer", token, type); return NULL; } (*epp)->value = strtol(token, NULL, 10); type = get_token(fp, token, MAXTOKEN); if (type != RIGHTPAREN) { print_error("Expected \")\"", token, type); return NULL; } epp = &(*epp)->next; } } if (type == ENDOFFILE) { print_error("Expected \"}\"", token, type); return NULL; } *retp = ep; return ep; } static struct range_list * parse_ranges(FILE * fp, struct range_list **retp) { int low, high; char nexttoken[MAXTOKEN]; int nexttype; struct range_list *rp = NULL, **rpp = &rp; int size = 0, taken = 1; free_ranges(retp); nexttype = get_token(fp, nexttoken, MAXTOKEN); if (nexttype == SIZE) { size = 1; taken = 0; nexttype = get_token(fp, nexttoken, MAXTOKEN); if (nexttype != LEFTPAREN) print_error("Expected \"(\" after SIZE", nexttoken, nexttype); } do { if (!taken) nexttype = get_token(fp, nexttoken, MAXTOKEN); else taken = 0; high = low = strtoul(nexttoken, NULL, 10); nexttype = get_token(fp, nexttoken, MAXTOKEN); if (nexttype == RANGE) { nexttype = get_token(fp, nexttoken, MAXTOKEN); errno = 0; high = strtoul(nexttoken, NULL, 10); if ( errno == ERANGE ) { if (netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_WARNINGS)) snmp_log(LOG_WARNING, "Warning: Upper bound not handled correctly (%s != %d): At line %d in %s\n", nexttoken, high, mibLine, File); } nexttype = get_token(fp, nexttoken, MAXTOKEN); } *rpp = (struct range_list *) calloc(1, sizeof(struct range_list)); if (*rpp == NULL) break; (*rpp)->low = low; (*rpp)->high = high; rpp = &(*rpp)->next; } while (nexttype == BAR); if (size) { if (nexttype != RIGHTPAREN) print_error("Expected \")\" after SIZE", nexttoken, nexttype); nexttype = get_token(fp, nexttoken, nexttype); } if (nexttype != RIGHTPAREN) print_error("Expected \")\"", nexttoken, nexttype); *retp = rp; return rp; } /* * Parses an asn type. Structures are ignored by this parser. * Returns NULL on error. */ static struct node * parse_asntype(FILE * fp, char *name, int *ntype, char *ntoken) { int type, i; char token[MAXTOKEN]; char quoted_string_buffer[MAXQUOTESTR]; char *hint = NULL; char *descr = NULL; struct tc *tcp; int level; type = get_token(fp, token, MAXTOKEN); if (type == SEQUENCE || type == CHOICE) { level = 0; while ((type = get_token(fp, token, MAXTOKEN)) != ENDOFFILE) { if (type == LEFTBRACKET) { level++; } else if (type == RIGHTBRACKET && --level == 0) { *ntype = get_token(fp, ntoken, MAXTOKEN); return NULL; } } print_error("Expected \"}\"", token, type); return NULL; } else if (type == LEFTBRACKET) { struct node *np; int ch_next = '{'; ungetc(ch_next, fp); np = parse_objectid(fp, name); if (np != NULL) { *ntype = get_token(fp, ntoken, MAXTOKEN); return np; } return NULL; } else if (type == LEFTSQBRACK) { int size = 0; do { type = get_token(fp, token, MAXTOKEN); } while (type != ENDOFFILE && type != RIGHTSQBRACK); if (type != RIGHTSQBRACK) { print_error("Expected \"]\"", token, type); return NULL; } type = get_token(fp, token, MAXTOKEN); if (type == IMPLICIT) type = get_token(fp, token, MAXTOKEN); *ntype = get_token(fp, ntoken, MAXTOKEN); if (*ntype == LEFTPAREN) { switch (type) { case OCTETSTR: *ntype = get_token(fp, ntoken, MAXTOKEN); if (*ntype != SIZE) { print_error("Expected SIZE", ntoken, *ntype); return NULL; } size = 1; *ntype = get_token(fp, ntoken, MAXTOKEN); if (*ntype != LEFTPAREN) { print_error("Expected \"(\" after SIZE", ntoken, *ntype); return NULL; } /* FALL THROUGH */ case INTEGER: *ntype = get_token(fp, ntoken, MAXTOKEN); do { if (*ntype != NUMBER) print_error("Expected NUMBER", ntoken, *ntype); *ntype = get_token(fp, ntoken, MAXTOKEN); if (*ntype == RANGE) { *ntype = get_token(fp, ntoken, MAXTOKEN); if (*ntype != NUMBER) print_error("Expected NUMBER", ntoken, *ntype); *ntype = get_token(fp, ntoken, MAXTOKEN); } } while (*ntype == BAR); if (*ntype != RIGHTPAREN) { print_error("Expected \")\"", ntoken, *ntype); return NULL; } *ntype = get_token(fp, ntoken, MAXTOKEN); if (size) { if (*ntype != RIGHTPAREN) { print_error("Expected \")\" to terminate SIZE", ntoken, *ntype); return NULL; } *ntype = get_token(fp, ntoken, MAXTOKEN); } } } return NULL; } else { if (type == CONVENTION) { while (type != SYNTAX && type != ENDOFFILE) { if (type == DISPLAYHINT) { type = get_token(fp, token, MAXTOKEN); if (type != QUOTESTRING) { print_error("DISPLAY-HINT must be string", token, type); } else { free(hint); hint = strdup(token); } } else if (type == DESCRIPTION && netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_SAVE_MIB_DESCRS)) { type = get_token(fp, quoted_string_buffer, MAXQUOTESTR); if (type != QUOTESTRING) { print_error("DESCRIPTION must be string", token, type); } else { free(descr); descr = strdup(quoted_string_buffer); } } else type = get_token(fp, quoted_string_buffer, MAXQUOTESTR); } type = get_token(fp, token, MAXTOKEN); if (type == OBJECT) { type = get_token(fp, token, MAXTOKEN); if (type != IDENTIFIER) { print_error("Expected IDENTIFIER", token, type); goto err; } type = OBJID; } } else if (type == OBJECT) { type = get_token(fp, token, MAXTOKEN); if (type != IDENTIFIER) { print_error("Expected IDENTIFIER", token, type); goto err; } type = OBJID; } if (type == LABEL) { type = get_tc(token, current_module, NULL, NULL, NULL, NULL); } /* * textual convention */ for (i = 0; i < MAXTC; i++) { if (tclist[i].type == 0) break; } if (i == MAXTC) { print_error("Too many textual conventions", token, type); goto err; } if (!(type & SYNTAX_MASK)) { print_error("Textual convention doesn't map to real type", token, type); goto err; } tcp = &tclist[i]; tcp->modid = current_module; tcp->descriptor = strdup(name); tcp->hint = hint; tcp->description = descr; tcp->type = type; *ntype = get_token(fp, ntoken, MAXTOKEN); if (*ntype == LEFTPAREN) { tcp->ranges = parse_ranges(fp, &tcp->ranges); *ntype = get_token(fp, ntoken, MAXTOKEN); } else if (*ntype == LEFTBRACKET) { /* * if there is an enumeration list, parse it */ tcp->enums = parse_enumlist(fp, &tcp->enums); *ntype = get_token(fp, ntoken, MAXTOKEN); } return NULL; } err: SNMP_FREE(descr); SNMP_FREE(hint); return NULL; } /* * Parses an OBJECT TYPE macro. * Returns 0 on error. */ static struct node * parse_objecttype(FILE * fp, char *name) { register int type; char token[MAXTOKEN]; char nexttoken[MAXTOKEN]; char quoted_string_buffer[MAXQUOTESTR]; int nexttype, tctype; register struct node *np; type = get_token(fp, token, MAXTOKEN); if (type != SYNTAX) { print_error("Bad format for OBJECT-TYPE", token, type); return NULL; } np = alloc_node(current_module); if (np == NULL) return (NULL); type = get_token(fp, token, MAXTOKEN); if (type == OBJECT) { type = get_token(fp, token, MAXTOKEN); if (type != IDENTIFIER) { print_error("Expected IDENTIFIER", token, type); free_node(np); return NULL; } type = OBJID; } if (type == LABEL) { int tmp_index; tctype = get_tc(token, current_module, &tmp_index, &np->enums, &np->ranges, &np->hint); if (tctype == LABEL && netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_WARNINGS) > 1) { print_error("Warning: No known translation for type", token, type); } type = tctype; np->tc_index = tmp_index; /* store TC for later reference */ } np->type = type; nexttype = get_token(fp, nexttoken, MAXTOKEN); switch (type) { case SEQUENCE: if (nexttype == OF) { nexttype = get_token(fp, nexttoken, MAXTOKEN); nexttype = get_token(fp, nexttoken, MAXTOKEN); } break; case INTEGER: case INTEGER32: case UINTEGER32: case UNSIGNED32: case COUNTER: case GAUGE: case BITSTRING: case LABEL: if (nexttype == LEFTBRACKET) { /* * if there is an enumeration list, parse it */ np->enums = parse_enumlist(fp, &np->enums); nexttype = get_token(fp, nexttoken, MAXTOKEN); } else if (nexttype == LEFTPAREN) { /* * if there is a range list, parse it */ np->ranges = parse_ranges(fp, &np->ranges); nexttype = get_token(fp, nexttoken, MAXTOKEN); } break; case OCTETSTR: case KW_OPAQUE: /* * parse any SIZE specification */ if (nexttype == LEFTPAREN) { nexttype = get_token(fp, nexttoken, MAXTOKEN); if (nexttype == SIZE) { nexttype = get_token(fp, nexttoken, MAXTOKEN); if (nexttype == LEFTPAREN) { np->ranges = parse_ranges(fp, &np->ranges); nexttype = get_token(fp, nexttoken, MAXTOKEN); /* ) */ if (nexttype == RIGHTPAREN) { nexttype = get_token(fp, nexttoken, MAXTOKEN); break; } } } print_error("Bad SIZE syntax", token, type); free_node(np); return NULL; } break; case OBJID: case NETADDR: case IPADDR: case TIMETICKS: case NUL: case NSAPADDRESS: case COUNTER64: break; default: print_error("Bad syntax", token, type); free_node(np); return NULL; } if (nexttype == UNITS) { type = get_token(fp, quoted_string_buffer, MAXQUOTESTR); if (type != QUOTESTRING) { print_error("Bad UNITS", quoted_string_buffer, type); free_node(np); return NULL; } np->units = strdup(quoted_string_buffer); nexttype = get_token(fp, nexttoken, MAXTOKEN); } if (nexttype != ACCESS) { print_error("Should be ACCESS", nexttoken, nexttype); free_node(np); return NULL; } type = get_token(fp, token, MAXTOKEN); if (type != READONLY && type != READWRITE && type != WRITEONLY && type != NOACCESS && type != READCREATE && type != ACCNOTIFY) { print_error("Bad ACCESS type", token, type); free_node(np); return NULL; } np->access = type; type = get_token(fp, token, MAXTOKEN); if (type != STATUS) { print_error("Should be STATUS", token, type); free_node(np); return NULL; } type = get_token(fp, token, MAXTOKEN); if (type != MANDATORY && type != CURRENT && type != KW_OPTIONAL && type != OBSOLETE && type != DEPRECATED) { print_error("Bad STATUS", token, type); free_node(np); return NULL; } np->status = type; /* * Optional parts of the OBJECT-TYPE macro */ type = get_token(fp, token, MAXTOKEN); while (type != EQUALS && type != ENDOFFILE) { switch (type) { case DESCRIPTION: type = get_token(fp, quoted_string_buffer, MAXQUOTESTR); if (type != QUOTESTRING) { print_error("Bad DESCRIPTION", quoted_string_buffer, type); free_node(np); return NULL; } if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_SAVE_MIB_DESCRS)) { np->description = strdup(quoted_string_buffer); } break; case REFERENCE: type = get_token(fp, quoted_string_buffer, MAXQUOTESTR); if (type != QUOTESTRING) { print_error("Bad REFERENCE", quoted_string_buffer, type); free_node(np); return NULL; } np->reference = strdup(quoted_string_buffer); break; case INDEX: if (np->augments) { print_error("Cannot have both INDEX and AUGMENTS", token, type); free_node(np); return NULL; } np->indexes = getIndexes(fp, &np->indexes); if (np->indexes == NULL) { print_error("Bad INDEX list", token, type); free_node(np); return NULL; } break; case AUGMENTS: if (np->indexes) { print_error("Cannot have both INDEX and AUGMENTS", token, type); free_node(np); return NULL; } np->indexes = getIndexes(fp, &np->indexes); if (np->indexes == NULL) { print_error("Bad AUGMENTS list", token, type); free_node(np); return NULL; } np->augments = strdup(np->indexes->ilabel); free_indexes(&np->indexes); break; case DEFVAL: /* * Mark's defVal section */ type = get_token(fp, quoted_string_buffer, MAXTOKEN); if (type != LEFTBRACKET) { print_error("Bad DEFAULTVALUE", quoted_string_buffer, type); free_node(np); return NULL; } { int level = 1; char defbuf[512]; defbuf[0] = 0; while (1) { type = get_token(fp, quoted_string_buffer, MAXTOKEN); if ((type == RIGHTBRACKET && --level == 0) || type == ENDOFFILE) break; else if (type == LEFTBRACKET) level++; if (type == QUOTESTRING) strlcat(defbuf, "\\\"", sizeof(defbuf)); strlcat(defbuf, quoted_string_buffer, sizeof(defbuf)); if (type == QUOTESTRING) strlcat(defbuf, "\\\"", sizeof(defbuf)); strlcat(defbuf, " ", sizeof(defbuf)); } if (type != RIGHTBRACKET) { print_error("Bad DEFAULTVALUE", quoted_string_buffer, type); free_node(np); return NULL; } defbuf[strlen(defbuf) - 1] = 0; np->defaultValue = strdup(defbuf); } break; case NUM_ENTRIES: if (tossObjectIdentifier(fp) != OBJID) { print_error("Bad Object Identifier", token, type); free_node(np); return NULL; } break; default: print_error("Bad format of optional clauses", token, type); free_node(np); return NULL; } type = get_token(fp, token, MAXTOKEN); } if (type != EQUALS) { print_error("Bad format", token, type); free_node(np); return NULL; } return merge_parse_objectid(np, fp, name); } /* * Parses an OBJECT GROUP macro. * Returns 0 on error. * * Also parses object-identity, since they are similar (ignore STATUS). * - WJH 10/96 */ static struct node * parse_objectgroup(FILE * fp, char *name, int what, struct objgroup **ol) { int type; char token[MAXTOKEN]; char quoted_string_buffer[MAXQUOTESTR]; struct node *np; np = alloc_node(current_module); if (np == NULL) return (NULL); type = get_token(fp, token, MAXTOKEN); if (type == what) { type = get_token(fp, token, MAXTOKEN); if (type != LEFTBRACKET) { print_error("Expected \"{\"", token, type); goto skip; } do { struct objgroup *o; type = get_token(fp, token, MAXTOKEN); if (type != LABEL) { print_error("Bad identifier", token, type); goto skip; } o = (struct objgroup *) malloc(sizeof(struct objgroup)); if (!o) { print_error("Resource failure", token, type); goto skip; } o->line = mibLine; o->name = strdup(token); o->next = *ol; *ol = o; type = get_token(fp, token, MAXTOKEN); } while (type == COMMA); if (type != RIGHTBRACKET) { print_error("Expected \"}\" after list", token, type); goto skip; } type = get_token(fp, token, type); } if (type != STATUS) { print_error("Expected STATUS", token, type); goto skip; } type = get_token(fp, token, MAXTOKEN); if (type != CURRENT && type != DEPRECATED && type != OBSOLETE) { print_error("Bad STATUS value", token, type); goto skip; } type = get_token(fp, token, MAXTOKEN); if (type != DESCRIPTION) { print_error("Expected DESCRIPTION", token, type); goto skip; } type = get_token(fp, quoted_string_buffer, MAXQUOTESTR); if (type != QUOTESTRING) { print_error("Bad DESCRIPTION", quoted_string_buffer, type); free_node(np); return NULL; } if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_SAVE_MIB_DESCRS)) { np->description = strdup(quoted_string_buffer); } type = get_token(fp, token, MAXTOKEN); if (type == REFERENCE) { type = get_token(fp, quoted_string_buffer, MAXQUOTESTR); if (type != QUOTESTRING) { print_error("Bad REFERENCE", quoted_string_buffer, type); free_node(np); return NULL; } np->reference = strdup(quoted_string_buffer); type = get_token(fp, token, MAXTOKEN); } if (type != EQUALS) print_error("Expected \"::=\"", token, type); skip: while (type != EQUALS && type != ENDOFFILE) type = get_token(fp, token, MAXTOKEN); return merge_parse_objectid(np, fp, name); } /* * Parses a NOTIFICATION-TYPE macro. * Returns 0 on error. */ static struct node * parse_notificationDefinition(FILE * fp, char *name) { register int type; char token[MAXTOKEN]; char quoted_string_buffer[MAXQUOTESTR]; register struct node *np; np = alloc_node(current_module); if (np == NULL) return (NULL); type = get_token(fp, token, MAXTOKEN); while (type != EQUALS && type != ENDOFFILE) { switch (type) { case DESCRIPTION: type = get_token(fp, quoted_string_buffer, MAXQUOTESTR); if (type != QUOTESTRING) { print_error("Bad DESCRIPTION", quoted_string_buffer, type); free_node(np); return NULL; } if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_SAVE_MIB_DESCRS)) { np->description = strdup(quoted_string_buffer); } break; case REFERENCE: type = get_token(fp, quoted_string_buffer, MAXQUOTESTR); if (type != QUOTESTRING) { print_error("Bad REFERENCE", quoted_string_buffer, type); free_node(np); return NULL; } np->reference = strdup(quoted_string_buffer); break; case OBJECTS: np->varbinds = getVarbinds(fp, &np->varbinds); if (!np->varbinds) { print_error("Bad OBJECTS list", token, type); free_node(np); return NULL; } break; default: /* * NOTHING */ break; } type = get_token(fp, token, MAXTOKEN); } return merge_parse_objectid(np, fp, name); } /* * Parses a TRAP-TYPE macro. * Returns 0 on error. */ static struct node * parse_trapDefinition(FILE * fp, char *name) { register int type; char token[MAXTOKEN]; char quoted_string_buffer[MAXQUOTESTR]; register struct node *np; np = alloc_node(current_module); if (np == NULL) return (NULL); type = get_token(fp, token, MAXTOKEN); while (type != EQUALS && type != ENDOFFILE) { switch (type) { case DESCRIPTION: type = get_token(fp, quoted_string_buffer, MAXQUOTESTR); if (type != QUOTESTRING) { print_error("Bad DESCRIPTION", quoted_string_buffer, type); free_node(np); return NULL; } if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_SAVE_MIB_DESCRS)) { np->description = strdup(quoted_string_buffer); } break; case REFERENCE: /* I'm not sure REFERENCEs are legal in smiv1 traps??? */ type = get_token(fp, quoted_string_buffer, MAXQUOTESTR); if (type != QUOTESTRING) { print_error("Bad REFERENCE", quoted_string_buffer, type); free_node(np); return NULL; } np->reference = strdup(quoted_string_buffer); break; case ENTERPRISE: type = get_token(fp, token, MAXTOKEN); if (type == LEFTBRACKET) { type = get_token(fp, token, MAXTOKEN); if (type != LABEL) { print_error("Bad Trap Format", token, type); free_node(np); return NULL; } np->parent = strdup(token); /* * Get right bracket */ type = get_token(fp, token, MAXTOKEN); } else if (type == LABEL) { np->parent = strdup(token); } else { free_node(np); return NULL; } break; case VARIABLES: np->varbinds = getVarbinds(fp, &np->varbinds); if (!np->varbinds) { print_error("Bad VARIABLES list", token, type); free_node(np); return NULL; } break; default: /* * NOTHING */ break; } type = get_token(fp, token, MAXTOKEN); } type = get_token(fp, token, MAXTOKEN); np->label = strdup(name); if (type != NUMBER) { print_error("Expected a Number", token, type); free_node(np); return NULL; } np->subid = strtoul(token, NULL, 10); np->next = alloc_node(current_module); if (np->next == NULL) { free_node(np); return (NULL); } /* Catch the syntax error */ if (np->parent == NULL) { free_node(np->next); free_node(np); gMibError = MODULE_SYNTAX_ERROR; return (NULL); } np->next->parent = np->parent; np->parent = (char *) malloc(strlen(np->parent) + 2); if (np->parent == NULL) { free_node(np->next); free_node(np); return (NULL); } strcpy(np->parent, np->next->parent); strcat(np->parent, "#"); np->next->label = strdup(np->parent); return np; } /* * Parses a compliance macro * Returns 0 on error. */ static int eat_syntax(FILE * fp, char *token, int maxtoken) { int type, nexttype; struct node *np = alloc_node(current_module); char nexttoken[MAXTOKEN]; if (!np) return 0; type = get_token(fp, token, maxtoken); nexttype = get_token(fp, nexttoken, MAXTOKEN); switch (type) { case INTEGER: case INTEGER32: case UINTEGER32: case UNSIGNED32: case COUNTER: case GAUGE: case BITSTRING: case LABEL: if (nexttype == LEFTBRACKET) { /* * if there is an enumeration list, parse it */ np->enums = parse_enumlist(fp, &np->enums); nexttype = get_token(fp, nexttoken, MAXTOKEN); } else if (nexttype == LEFTPAREN) { /* * if there is a range list, parse it */ np->ranges = parse_ranges(fp, &np->ranges); nexttype = get_token(fp, nexttoken, MAXTOKEN); } break; case OCTETSTR: case KW_OPAQUE: /* * parse any SIZE specification */ if (nexttype == LEFTPAREN) { nexttype = get_token(fp, nexttoken, MAXTOKEN); if (nexttype == SIZE) { nexttype = get_token(fp, nexttoken, MAXTOKEN); if (nexttype == LEFTPAREN) { np->ranges = parse_ranges(fp, &np->ranges); nexttype = get_token(fp, nexttoken, MAXTOKEN); /* ) */ if (nexttype == RIGHTPAREN) { nexttype = get_token(fp, nexttoken, MAXTOKEN); break; } } } print_error("Bad SIZE syntax", token, type); free_node(np); return nexttype; } break; case OBJID: case NETADDR: case IPADDR: case TIMETICKS: case NUL: case NSAPADDRESS: case COUNTER64: break; default: print_error("Bad syntax", token, type); free_node(np); return nexttype; } free_node(np); return nexttype; } static int compliance_lookup(const char *name, int modid) { if (modid == -1) { struct objgroup *op = (struct objgroup *) malloc(sizeof(struct objgroup)); if (!op) return 0; op->next = objgroups; op->name = strdup(name); op->line = mibLine; objgroups = op; return 1; } else return find_tree_node(name, modid) != NULL; } static struct node * parse_compliance(FILE * fp, char *name) { int type; char token[MAXTOKEN]; char quoted_string_buffer[MAXQUOTESTR]; struct node *np; np = alloc_node(current_module); if (np == NULL) return (NULL); type = get_token(fp, token, MAXTOKEN); if (type != STATUS) { print_error("Expected STATUS", token, type); goto skip; } type = get_token(fp, token, MAXTOKEN); if (type != CURRENT && type != DEPRECATED && type != OBSOLETE) { print_error("Bad STATUS", token, type); goto skip; } type = get_token(fp, token, MAXTOKEN); if (type != DESCRIPTION) { print_error("Expected DESCRIPTION", token, type); goto skip; } type = get_token(fp, quoted_string_buffer, MAXQUOTESTR); if (type != QUOTESTRING) { print_error("Bad DESCRIPTION", quoted_string_buffer, type); goto skip; } if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_SAVE_MIB_DESCRS)) np->description = strdup(quoted_string_buffer); type = get_token(fp, token, MAXTOKEN); if (type == REFERENCE) { type = get_token(fp, quoted_string_buffer, MAXTOKEN); if (type != QUOTESTRING) { print_error("Bad REFERENCE", quoted_string_buffer, type); goto skip; } np->reference = strdup(quoted_string_buffer); type = get_token(fp, token, MAXTOKEN); } if (type != MODULE) { print_error("Expected MODULE", token, type); goto skip; } while (type == MODULE) { int modid = -1; char modname[MAXTOKEN]; type = get_token(fp, token, MAXTOKEN); if (type == LABEL && strcmp(token, module_name(current_module, modname))) { modid = read_module_internal(token); if (modid != MODULE_LOADED_OK && modid != MODULE_ALREADY_LOADED) { print_error("Unknown module", token, type); goto skip; } modid = which_module(token); type = get_token(fp, token, MAXTOKEN); } if (type == MANDATORYGROUPS) { type = get_token(fp, token, MAXTOKEN); if (type != LEFTBRACKET) { print_error("Expected \"{\"", token, type); goto skip; } do { type = get_token(fp, token, MAXTOKEN); if (type != LABEL) { print_error("Bad group name", token, type); goto skip; } if (!compliance_lookup(token, modid)) print_error("Unknown group", token, type); type = get_token(fp, token, MAXTOKEN); } while (type == COMMA); if (type != RIGHTBRACKET) { print_error("Expected \"}\"", token, type); goto skip; } type = get_token(fp, token, MAXTOKEN); } while (type == GROUP || type == OBJECT) { if (type == GROUP) { type = get_token(fp, token, MAXTOKEN); if (type != LABEL) { print_error("Bad group name", token, type); goto skip; } if (!compliance_lookup(token, modid)) print_error("Unknown group", token, type); type = get_token(fp, token, MAXTOKEN); } else { type = get_token(fp, token, MAXTOKEN); if (type != LABEL) { print_error("Bad object name", token, type); goto skip; } if (!compliance_lookup(token, modid)) print_error("Unknown group", token, type); type = get_token(fp, token, MAXTOKEN); if (type == SYNTAX) type = eat_syntax(fp, token, MAXTOKEN); if (type == WRSYNTAX) type = eat_syntax(fp, token, MAXTOKEN); if (type == MINACCESS) { type = get_token(fp, token, MAXTOKEN); if (type != NOACCESS && type != ACCNOTIFY && type != READONLY && type != WRITEONLY && type != READCREATE && type != READWRITE) { print_error("Bad MIN-ACCESS spec", token, type); goto skip; } type = get_token(fp, token, MAXTOKEN); } } if (type != DESCRIPTION) { print_error("Expected DESCRIPTION", token, type); goto skip; } type = get_token(fp, token, MAXTOKEN); if (type != QUOTESTRING) { print_error("Bad DESCRIPTION", token, type); goto skip; } type = get_token(fp, token, MAXTOKEN); } } skip: while (type != EQUALS && type != ENDOFFILE) type = get_token(fp, quoted_string_buffer, MAXQUOTESTR); return merge_parse_objectid(np, fp, name); } /* * Parses a capabilities macro * Returns 0 on error. */ static struct node * parse_capabilities(FILE * fp, char *name) { int type; char token[MAXTOKEN]; char quoted_string_buffer[MAXQUOTESTR]; struct node *np; np = alloc_node(current_module); if (np == NULL) return (NULL); type = get_token(fp, token, MAXTOKEN); if (type != PRODREL) { print_error("Expected PRODUCT-RELEASE", token, type); goto skip; } type = get_token(fp, token, MAXTOKEN); if (type != QUOTESTRING) { print_error("Expected STRING after PRODUCT-RELEASE", token, type); goto skip; } type = get_token(fp, token, MAXTOKEN); if (type != STATUS) { print_error("Expected STATUS", token, type); goto skip; } type = get_token(fp, token, MAXTOKEN); if (type != CURRENT && type != OBSOLETE) { print_error("STATUS should be current or obsolete", token, type); goto skip; } type = get_token(fp, token, MAXTOKEN); if (type != DESCRIPTION) { print_error("Expected DESCRIPTION", token, type); goto skip; } type = get_token(fp, quoted_string_buffer, MAXTOKEN); if (type != QUOTESTRING) { print_error("Bad DESCRIPTION", quoted_string_buffer, type); goto skip; } if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_SAVE_MIB_DESCRS)) { np->description = strdup(quoted_string_buffer); } type = get_token(fp, token, MAXTOKEN); if (type == REFERENCE) { type = get_token(fp, quoted_string_buffer, MAXTOKEN); if (type != QUOTESTRING) { print_error("Bad REFERENCE", quoted_string_buffer, type); goto skip; } np->reference = strdup(quoted_string_buffer); type = get_token(fp, token, type); } while (type == SUPPORTS) { int modid; struct tree *tp; type = get_token(fp, token, MAXTOKEN); if (type != LABEL) { print_error("Bad module name", token, type); goto skip; } modid = read_module_internal(token); if (modid != MODULE_LOADED_OK && modid != MODULE_ALREADY_LOADED) { print_error("Module not found", token, type); goto skip; } modid = which_module(token); type = get_token(fp, token, MAXTOKEN); if (type != INCLUDES) { print_error("Expected INCLUDES", token, type); goto skip; } type = get_token(fp, token, MAXTOKEN); if (type != LEFTBRACKET) { print_error("Expected \"{\"", token, type); goto skip; } do { type = get_token(fp, token, MAXTOKEN); if (type != LABEL) { print_error("Expected group name", token, type); goto skip; } tp = find_tree_node(token, modid); if (!tp) print_error("Group not found in module", token, type); type = get_token(fp, token, MAXTOKEN); } while (type == COMMA); if (type != RIGHTBRACKET) { print_error("Expected \"}\" after group list", token, type); goto skip; } type = get_token(fp, token, MAXTOKEN); while (type == VARIATION) { type = get_token(fp, token, MAXTOKEN); if (type != LABEL) { print_error("Bad object name", token, type); goto skip; } tp = find_tree_node(token, modid); if (!tp) print_error("Object not found in module", token, type); type = get_token(fp, token, MAXTOKEN); if (type == SYNTAX) { type = eat_syntax(fp, token, MAXTOKEN); } if (type == WRSYNTAX) { type = eat_syntax(fp, token, MAXTOKEN); } if (type == ACCESS) { type = get_token(fp, token, MAXTOKEN); if (type != ACCNOTIFY && type != READONLY && type != READWRITE && type != READCREATE && type != WRITEONLY && type != NOTIMPL) { print_error("Bad ACCESS", token, type); goto skip; } type = get_token(fp, token, MAXTOKEN); } if (type == CREATEREQ) { type = get_token(fp, token, MAXTOKEN); if (type != LEFTBRACKET) { print_error("Expected \"{\"", token, type); goto skip; } do { type = get_token(fp, token, MAXTOKEN); if (type != LABEL) { print_error("Bad object name in list", token, type); goto skip; } type = get_token(fp, token, MAXTOKEN); } while (type == COMMA); if (type != RIGHTBRACKET) { print_error("Expected \"}\" after list", token, type); goto skip; } type = get_token(fp, token, MAXTOKEN); } if (type == DEFVAL) { int level = 1; type = get_token(fp, token, MAXTOKEN); if (type != LEFTBRACKET) { print_error("Expected \"{\" after DEFVAL", token, type); goto skip; } do { type = get_token(fp, token, MAXTOKEN); if (type == LEFTBRACKET) level++; else if (type == RIGHTBRACKET) level--; } while ((type != RIGHTBRACKET || level != 0) && type != ENDOFFILE); if (type != RIGHTBRACKET) { print_error("Missing \"}\" after DEFVAL", token, type); goto skip; } type = get_token(fp, token, MAXTOKEN); } if (type != DESCRIPTION) { print_error("Expected DESCRIPTION", token, type); goto skip; } type = get_token(fp, quoted_string_buffer, MAXTOKEN); if (type != QUOTESTRING) { print_error("Bad DESCRIPTION", quoted_string_buffer, type); goto skip; } type = get_token(fp, token, MAXTOKEN); } } if (type != EQUALS) print_error("Expected \"::=\"", token, type); skip: while (type != EQUALS && type != ENDOFFILE) { type = get_token(fp, quoted_string_buffer, MAXQUOTESTR); } return merge_parse_objectid(np, fp, name); } /* * Parses a module identity macro * Returns 0 on error. */ static void check_utc(const char *utc) { int len, year, month, day, hour, minute; len = strlen(utc); if (utc[len - 1] != 'Z' && utc[len - 1] != 'z') { print_error("Timestamp should end with Z", utc, QUOTESTRING); return; } if (len == 11) { len = sscanf(utc, "%2d%2d%2d%2d%2dZ", &year, &month, &day, &hour, &minute); year += 1900; } else if (len == 13) len = sscanf(utc, "%4d%2d%2d%2d%2dZ", &year, &month, &day, &hour, &minute); else { print_error("Bad timestamp format (11 or 13 characters)", utc, QUOTESTRING); return; } if (len != 5) { print_error("Bad timestamp format", utc, QUOTESTRING); return; } if (month < 1 || month > 12) print_error("Bad month in timestamp", utc, QUOTESTRING); if (day < 1 || day > 31) print_error("Bad day in timestamp", utc, QUOTESTRING); if (hour < 0 || hour > 23) print_error("Bad hour in timestamp", utc, QUOTESTRING); if (minute < 0 || minute > 59) print_error("Bad minute in timestamp", utc, QUOTESTRING); } static struct node * parse_moduleIdentity(FILE * fp, char *name) { register int type; char token[MAXTOKEN]; char quoted_string_buffer[MAXQUOTESTR]; register struct node *np; np = alloc_node(current_module); if (np == NULL) return (NULL); type = get_token(fp, token, MAXTOKEN); if (type != LASTUPDATED) { print_error("Expected LAST-UPDATED", token, type); goto skip; } type = get_token(fp, token, MAXTOKEN); if (type != QUOTESTRING) { print_error("Need STRING for LAST-UPDATED", token, type); goto skip; } check_utc(token); type = get_token(fp, token, MAXTOKEN); if (type != ORGANIZATION) { print_error("Expected ORGANIZATION", token, type); goto skip; } type = get_token(fp, token, MAXTOKEN); if (type != QUOTESTRING) { print_error("Bad ORGANIZATION", token, type); goto skip; } type = get_token(fp, token, MAXTOKEN); if (type != CONTACTINFO) { print_error("Expected CONTACT-INFO", token, type); goto skip; } type = get_token(fp, quoted_string_buffer, MAXQUOTESTR); if (type != QUOTESTRING) { print_error("Bad CONTACT-INFO", quoted_string_buffer, type); goto skip; } type = get_token(fp, token, MAXTOKEN); if (type != DESCRIPTION) { print_error("Expected DESCRIPTION", token, type); goto skip; } type = get_token(fp, quoted_string_buffer, MAXQUOTESTR); if (type != QUOTESTRING) { print_error("Bad DESCRIPTION", quoted_string_buffer, type); goto skip; } if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_SAVE_MIB_DESCRS)) { np->description = strdup(quoted_string_buffer); } type = get_token(fp, token, MAXTOKEN); while (type == REVISION) { type = get_token(fp, token, MAXTOKEN); if (type != QUOTESTRING) { print_error("Bad REVISION", token, type); goto skip; } check_utc(token); type = get_token(fp, token, MAXTOKEN); if (type != DESCRIPTION) { print_error("Expected DESCRIPTION", token, type); goto skip; } type = get_token(fp, quoted_string_buffer, MAXQUOTESTR); if (type != QUOTESTRING) { print_error("Bad DESCRIPTION", quoted_string_buffer, type); goto skip; } type = get_token(fp, token, MAXTOKEN); } if (type != EQUALS) print_error("Expected \"::=\"", token, type); skip: while (type != EQUALS && type != ENDOFFILE) { type = get_token(fp, quoted_string_buffer, MAXQUOTESTR); } return merge_parse_objectid(np, fp, name); } /* * Parses a MACRO definition * Expect BEGIN, discard everything to end. * Returns 0 on error. */ static struct node * parse_macro(FILE * fp, char *name) { register int type; char token[MAXTOKEN]; struct node *np; int iLine = mibLine; np = alloc_node(current_module); if (np == NULL) return (NULL); type = get_token(fp, token, sizeof(token)); while (type != EQUALS && type != ENDOFFILE) { type = get_token(fp, token, sizeof(token)); } if (type != EQUALS) { if (np) free_node(np); return NULL; } while (type != BEGIN && type != ENDOFFILE) { type = get_token(fp, token, sizeof(token)); } if (type != BEGIN) { if (np) free_node(np); return NULL; } while (type != END && type != ENDOFFILE) { type = get_token(fp, token, sizeof(token)); } if (type != END) { if (np) free_node(np); return NULL; } if (netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_WARNINGS)) { snmp_log(LOG_WARNING, "%s MACRO (lines %d..%d parsed and ignored).\n", name, iLine, mibLine); } return np; } /* * Parses a module import clause * loading any modules referenced */ static void parse_imports(FILE * fp) { register int type; char token[MAXTOKEN]; char modbuf[256]; #define MAX_IMPORTS 256 struct module_import import_list[MAX_IMPORTS]; int this_module; struct module *mp; int import_count = 0; /* Total number of imported descriptors */ int i = 0, old_i; /* index of first import from each module */ type = get_token(fp, token, MAXTOKEN); /* * Parse the IMPORTS clause */ while (type != SEMI && type != ENDOFFILE) { if (type == LABEL) { if (import_count == MAX_IMPORTS) { print_error("Too many imported symbols", token, type); do { type = get_token(fp, token, MAXTOKEN); } while (type != SEMI && type != ENDOFFILE); return; } import_list[import_count++].label = strdup(token); } else if (type == FROM) { type = get_token(fp, token, MAXTOKEN); if (import_count == i) { /* All imports are handled internally */ type = get_token(fp, token, MAXTOKEN); continue; } this_module = which_module(token); for (old_i = i; i < import_count; ++i) import_list[i].modid = this_module; /* * Recursively read any pre-requisite modules */ if (read_module_internal(token) == MODULE_NOT_FOUND) { int found = 0; for (; old_i < import_count; ++old_i) { found += read_import_replacements(token, &import_list[old_i]); } if (!found) print_module_not_found(token); } } type = get_token(fp, token, MAXTOKEN); } /* Initialize modid in case the module name was missing. */ for (; i < import_count; ++i) import_list[i].modid = -1; /* * Save the import information * in the global module table */ for (mp = module_head; mp; mp = mp->next) if (mp->modid == current_module) { if (import_count == 0) return; if (mp->imports && (mp->imports != root_imports)) { /* * this can happen if all modules are in one source file. */ for (i = 0; i < mp->no_imports; ++i) { DEBUGMSGTL(("parse-mibs", "#### freeing Module %d '%s' %d\n", mp->modid, mp->imports[i].label, mp->imports[i].modid)); free((char *) mp->imports[i].label); } free((char *) mp->imports); } mp->imports = (struct module_import *) calloc(import_count, sizeof(struct module_import)); if (mp->imports == NULL) return; for (i = 0; i < import_count; ++i) { mp->imports[i].label = import_list[i].label; mp->imports[i].modid = import_list[i].modid; DEBUGMSGTL(("parse-mibs", "#### adding Module %d '%s' %d\n", mp->modid, mp->imports[i].label, mp->imports[i].modid)); } mp->no_imports = import_count; return; } /* * Shouldn't get this far */ print_module_not_found(module_name(current_module, modbuf)); return; } /* * MIB module handling routines */ static void dump_module_list(void) { struct module *mp = module_head; DEBUGMSGTL(("parse-mibs", "Module list:\n")); while (mp) { DEBUGMSGTL(("parse-mibs", " %s %d %s %d\n", mp->name, mp->modid, mp->file, mp->no_imports)); mp = mp->next; } } int which_module(const char *name) { struct module *mp; for (mp = module_head; mp; mp = mp->next) if (!label_compare(mp->name, name)) return (mp->modid); DEBUGMSGTL(("parse-mibs", "Module %s not found\n", name)); return (-1); } /* * module_name - copy module name to user buffer, return ptr to same. */ char * module_name(int modid, char *cp) { struct module *mp; for (mp = module_head; mp; mp = mp->next) if (mp->modid == modid) { strcpy(cp, mp->name); return (cp); } if (modid != -1) DEBUGMSGTL(("parse-mibs", "Module %d not found\n", modid)); sprintf(cp, "#%d", modid); return (cp); } /* * Backwards compatability * Read newer modules that replace the one specified:- * either all of them (read_module_replacements), * or those relating to a specified identifier (read_import_replacements) * plus an interface to add new replacement requirements */ netsnmp_feature_child_of(parse_add_module_replacement, netsnmp_unused) #ifndef NETSNMP_FEATURE_REMOVE_PARSE_ADD_MODULE_REPLACEMENT void add_module_replacement(const char *old_module, const char *new_module_name, const char *tag, int len) { struct module_compatability *mcp; mcp = (struct module_compatability *) calloc(1, sizeof(struct module_compatability)); if (mcp == NULL) return; mcp->old_module = strdup(old_module); mcp->new_module = strdup(new_module_name); if (tag) mcp->tag = strdup(tag); mcp->tag_len = len; mcp->next = module_map_head; module_map_head = mcp; } #endif /* NETSNMP_FEATURE_REMOVE_PARSE_ADD_MODULE_REPLACEMENT */ static int read_module_replacements(const char *name) { struct module_compatability *mcp; for (mcp = module_map_head; mcp; mcp = mcp->next) { if (!label_compare(mcp->old_module, name)) { if (netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_WARNINGS)) { snmp_log(LOG_WARNING, "Loading replacement module %s for %s (%s)\n", mcp->new_module, name, File); } (void) netsnmp_read_module(mcp->new_module); return 1; } } return 0; } static int read_import_replacements(const char *old_module_name, struct module_import *identifier) { struct module_compatability *mcp; /* * Look for matches first */ for (mcp = module_map_head; mcp; mcp = mcp->next) { if (!label_compare(mcp->old_module, old_module_name)) { if ( /* exact match */ (mcp->tag_len == 0 && (mcp->tag == NULL || !label_compare(mcp->tag, identifier->label))) || /* * prefix match */ (mcp->tag_len != 0 && !strncmp(mcp->tag, identifier->label, mcp->tag_len)) ) { if (netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_WARNINGS)) { snmp_log(LOG_WARNING, "Importing %s from replacement module %s instead of %s (%s)\n", identifier->label, mcp->new_module, old_module_name, File); } (void) netsnmp_read_module(mcp->new_module); identifier->modid = which_module(mcp->new_module); return 1; /* finished! */ } } } /* * If no exact match, load everything relevant */ return read_module_replacements(old_module_name); } /* * Read in the named module * Returns the root of the whole tree * (by analogy with 'read_mib') */ static int read_module_internal(const char *name) { struct module *mp; FILE *fp; struct node *np; netsnmp_init_mib_internals(); for (mp = module_head; mp; mp = mp->next) if (!label_compare(mp->name, name)) { const char *oldFile = File; int oldLine = mibLine; int oldModule = current_module; if (mp->no_imports != -1) { DEBUGMSGTL(("parse-mibs", "Module %s already loaded\n", name)); return MODULE_ALREADY_LOADED; } if ((fp = fopen(mp->file, "r")) == NULL) { int rval; if (errno == ENOTDIR || errno == ENOENT) rval = MODULE_NOT_FOUND; else rval = MODULE_LOAD_FAILED; snmp_log_perror(mp->file); return rval; } #ifdef HAVE_FLOCKFILE flockfile(fp); #endif mp->no_imports = 0; /* Note that we've read the file */ File = mp->file; mibLine = 1; current_module = mp->modid; /* * Parse the file */ np = parse(fp, NULL); #ifdef HAVE_FUNLOCKFILE funlockfile(fp); #endif fclose(fp); File = oldFile; mibLine = oldLine; current_module = oldModule; if ((np == NULL) && (gMibError == MODULE_SYNTAX_ERROR) ) return MODULE_SYNTAX_ERROR; return MODULE_LOADED_OK; } return MODULE_NOT_FOUND; } void adopt_orphans(void) { struct node *np, *onp; struct tree *tp; int i, adopted = 1; if (!orphan_nodes) return; init_node_hash(orphan_nodes); orphan_nodes = NULL; while (adopted) { adopted = 0; for (i = 0; i < NHASHSIZE; i++) if (nbuckets[i]) { for (np = nbuckets[i]; np != NULL; np = np->next) { tp = find_tree_node(np->parent, -1); if (tp) { do_subtree(tp, &np); adopted = 1; /* * if do_subtree adopted the entire bucket, stop */ if(NULL == nbuckets[i]) break; /* * do_subtree may modify nbuckets, and if np * was adopted, np->next probably isn't an orphan * anymore. if np is still in the bucket (do_subtree * didn't adopt it) keep on plugging. otherwise * start over, at the top of the bucket. */ for(onp = nbuckets[i]; onp; onp = onp->next) if(onp == np) break; if(NULL == onp) { /* not in the list */ np = nbuckets[i]; /* start over */ } } } } } /* * Report on outstanding orphans * and link them back into the orphan list */ for (i = 0; i < NHASHSIZE; i++) if (nbuckets[i]) { if (orphan_nodes) onp = np->next = nbuckets[i]; else onp = orphan_nodes = nbuckets[i]; nbuckets[i] = NULL; while (onp) { char modbuf[256]; snmp_log(LOG_WARNING, "Cannot adopt OID in %s: %s ::= { %s %ld }\n", module_name(onp->modid, modbuf), (onp->label ? onp->label : "<no label>"), (onp->parent ? onp->parent : "<no parent>"), onp->subid); np = onp; onp = onp->next; } } } #ifndef NETSNMP_NO_LEGACY_DEFINITIONS struct tree * read_module(const char *name) { return netsnmp_read_module(name); } #endif struct tree * netsnmp_read_module(const char *name) { int status = 0; status = read_module_internal(name); if (status == MODULE_NOT_FOUND) { if (!read_module_replacements(name)) print_module_not_found(name); } else if (status == MODULE_SYNTAX_ERROR) { gMibError = 0; gLoop = 1; strncat(gMibNames, " ", sizeof(gMibNames) - strlen(gMibNames) - 1); strncat(gMibNames, name, sizeof(gMibNames) - strlen(gMibNames) - 1); } return tree_head; } /* * Prototype definition */ void unload_module_by_ID(int modID, struct tree *tree_top); void unload_module_by_ID(int modID, struct tree *tree_top) { struct tree *tp, *next; int i; for (tp = tree_top; tp; tp = next) { /* * Essentially, this is equivalent to the code fragment: * if (tp->modID == modID) * tp->number_modules--; * but handles one tree node being part of several modules, * and possible multiple copies of the same module ID. */ int nmod = tp->number_modules; if (nmod > 0) { /* in some module */ /* * Remove all copies of this module ID */ int cnt = 0, *pi1, *pi2 = tp->module_list; for (i = 0, pi1 = pi2; i < nmod; i++, pi2++) { if (*pi2 == modID) continue; cnt++; *pi1++ = *pi2; } if (nmod != cnt) { /* in this module */ /* * if ( (nmod - cnt) > 1) * printf("Dup modid %d, %d times, '%s'\n", tp->modid, (nmod-cnt), tp->label); fflush(stdout); ?* XXDEBUG */ tp->number_modules = cnt; switch (cnt) { case 0: tp->module_list[0] = -1; /* Mark unused, */ /* FALL THROUGH */ case 1: /* save the remaining module */ if (&(tp->modid) != tp->module_list) { tp->modid = tp->module_list[0]; free(tp->module_list); tp->module_list = &(tp->modid); } break; default: break; } } /* if tree node is in this module */ } /* * if tree node is in some module */ next = tp->next_peer; /* * OK - that's dealt with *this* node. * Now let's look at the children. * (Isn't recursion wonderful!) */ if (tp->child_list) unload_module_by_ID(modID, tp->child_list); if (tp->number_modules == 0) { /* * This node isn't needed any more (except perhaps * for the sake of the children) */ if (tp->child_list == NULL) { unlink_tree(tp); free_tree(tp); } else { free_partial_tree(tp, TRUE); } } } } #ifndef NETSNMP_NO_LEGACY_DEFINITIONS int unload_module(const char *name) { return netsnmp_unload_module(name); } #endif int netsnmp_unload_module(const char *name) { struct module *mp; int modID = -1; for (mp = module_head; mp; mp = mp->next) if (!label_compare(mp->name, name)) { modID = mp->modid; break; } if (modID == -1) { DEBUGMSGTL(("unload-mib", "Module %s not found to unload\n", name)); return MODULE_NOT_FOUND; } unload_module_by_ID(modID, tree_head); mp->no_imports = -1; /* mark as unloaded */ return MODULE_LOADED_OK; /* Well, you know what I mean! */ } /* * Clear module map, tree nodes, textual convention table. */ void unload_all_mibs(void) { struct module *mp; struct module_compatability *mcp; struct tc *ptc; unsigned int i; for (mcp = module_map_head; mcp; mcp = module_map_head) { if (mcp == module_map) break; module_map_head = mcp->next; if (mcp->tag) free(NETSNMP_REMOVE_CONST(char *, mcp->tag)); free(NETSNMP_REMOVE_CONST(char *, mcp->old_module)); free(NETSNMP_REMOVE_CONST(char *, mcp->new_module)); free(mcp); } for (mp = module_head; mp; mp = module_head) { struct module_import *mi = mp->imports; if (mi) { for (i = 0; i < (unsigned int)mp->no_imports; ++i) { SNMP_FREE((mi + i)->label); } mp->no_imports = 0; if (mi == root_imports) memset(mi, 0, sizeof(*mi)); else free(mi); } unload_module_by_ID(mp->modid, tree_head); module_head = mp->next; free(mp->name); free(mp->file); free(mp); } unload_module_by_ID(-1, tree_head); /* * tree nodes are cleared */ for (i = 0, ptc = tclist; i < MAXTC; i++, ptc++) { if (ptc->type == 0) continue; free_enums(&ptc->enums); free_ranges(&ptc->ranges); free(ptc->descriptor); if (ptc->hint) free(ptc->hint); if (ptc->description) free(ptc->description); } memset(tclist, 0, MAXTC * sizeof(struct tc)); memset(buckets, 0, sizeof(buckets)); memset(nbuckets, 0, sizeof(nbuckets)); memset(tbuckets, 0, sizeof(tbuckets)); for (i = 0; i < sizeof(root_imports) / sizeof(root_imports[0]); i++) { SNMP_FREE(root_imports[i].label); } max_module = 0; current_module = 0; module_map_head = NULL; SNMP_FREE(last_err_module); } static void new_module(const char *name, const char *file) { struct module *mp; for (mp = module_head; mp; mp = mp->next) if (!label_compare(mp->name, name)) { DEBUGMSGTL(("parse-mibs", " Module %s already noted\n", name)); /* * Not the same file */ if (label_compare(mp->file, file)) { DEBUGMSGTL(("parse-mibs", " %s is now in %s\n", name, file)); if (netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_WARNINGS)) { snmp_log(LOG_WARNING, "Warning: Module %s was in %s now is %s\n", name, mp->file, file); } /* * Use the new one in preference */ free(mp->file); mp->file = strdup(file); } return; } /* * Add this module to the list */ DEBUGMSGTL(("parse-mibs", " Module %d %s is in %s\n", max_module, name, file)); mp = (struct module *) calloc(1, sizeof(struct module)); if (mp == NULL) return; mp->name = strdup(name); mp->file = strdup(file); mp->imports = NULL; mp->no_imports = -1; /* Not yet loaded */ mp->modid = max_module; ++max_module; mp->next = module_head; /* Or add to the *end* of the list? */ module_head = mp; } static void scan_objlist(struct node *root, struct module *mp, struct objgroup *list, const char *error) { int oLine = mibLine; while (list) { struct objgroup *gp = list; struct node *np; list = list->next; np = root; while (np) if (label_compare(np->label, gp->name)) np = np->next; else break; if (!np) { int i; struct module_import *mip; /* if not local, check if it was IMPORTed */ for (i = 0, mip = mp->imports; i < mp->no_imports; i++, mip++) if (strcmp(mip->label, gp->name) == 0) break; if (i == mp->no_imports) { mibLine = gp->line; print_error(error, gp->name, QUOTESTRING); } } free(gp->name); free(gp); } mibLine = oLine; } /* * Parses a mib file and returns a linked list of nodes found in the file. * Returns NULL on error. */ static struct node * parse(FILE * fp, struct node *root) { #ifdef TEST extern void xmalloc_stats(FILE *); #endif char token[MAXTOKEN]; char name[MAXTOKEN+1]; int type = LABEL; int lasttype = LABEL; #define BETWEEN_MIBS 1 #define IN_MIB 2 int state = BETWEEN_MIBS; struct node *np, *nnp; struct objgroup *oldgroups = NULL, *oldobjects = NULL, *oldnotifs = NULL; DEBUGMSGTL(("parse-file", "Parsing file: %s...\n", File)); if (last_err_module) free(last_err_module); last_err_module = NULL; np = root; if (np != NULL) { /* * now find end of chain */ while (np->next) np = np->next; } while (type != ENDOFFILE) { if (lasttype == CONTINUE) lasttype = type; else type = lasttype = get_token(fp, token, MAXTOKEN); switch (type) { case END: if (state != IN_MIB) { print_error("Error, END before start of MIB", NULL, type); gMibError = MODULE_SYNTAX_ERROR; return NULL; } else { struct module *mp; #ifdef TEST printf("\nNodes for Module %s:\n", name); print_nodes(stdout, root); #endif for (mp = module_head; mp; mp = mp->next) if (mp->modid == current_module) break; scan_objlist(root, mp, objgroups, "Undefined OBJECT-GROUP"); scan_objlist(root, mp, objects, "Undefined OBJECT"); scan_objlist(root, mp, notifs, "Undefined NOTIFICATION"); objgroups = oldgroups; objects = oldobjects; notifs = oldnotifs; do_linkup(mp, root); np = root = NULL; } state = BETWEEN_MIBS; #ifdef TEST if (netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_WARNINGS)) { /* xmalloc_stats(stderr); */ } #endif continue; case IMPORTS: parse_imports(fp); continue; case EXPORTS: while (type != SEMI && type != ENDOFFILE) type = get_token(fp, token, MAXTOKEN); continue; case LABEL: case INTEGER: case INTEGER32: case UINTEGER32: case UNSIGNED32: case COUNTER: case COUNTER64: case GAUGE: case IPADDR: case NETADDR: case NSAPADDRESS: case OBJSYNTAX: case APPSYNTAX: case SIMPLESYNTAX: case OBJNAME: case NOTIFNAME: case KW_OPAQUE: case TIMETICKS: break; case ENDOFFILE: continue; default: strlcpy(name, token, sizeof(name)); type = get_token(fp, token, MAXTOKEN); nnp = NULL; if (type == MACRO) { nnp = parse_macro(fp, name); if (nnp == NULL) { print_error("Bad parse of MACRO", NULL, type); gMibError = MODULE_SYNTAX_ERROR; /* * return NULL; */ } free_node(nnp); /* IGNORE */ nnp = NULL; } else print_error(name, "is a reserved word", lasttype); continue; /* see if we can parse the rest of the file */ } strlcpy(name, token, sizeof(name)); type = get_token(fp, token, MAXTOKEN); nnp = NULL; /* * Handle obsolete method to assign an object identifier to a * module */ if (lasttype == LABEL && type == LEFTBRACKET) { while (type != RIGHTBRACKET && type != ENDOFFILE) type = get_token(fp, token, MAXTOKEN); if (type == ENDOFFILE) { print_error("Expected \"}\"", token, type); gMibError = MODULE_SYNTAX_ERROR; return NULL; } type = get_token(fp, token, MAXTOKEN); } switch (type) { case DEFINITIONS: if (state != BETWEEN_MIBS) { print_error("Error, nested MIBS", NULL, type); gMibError = MODULE_SYNTAX_ERROR; return NULL; } state = IN_MIB; current_module = which_module(name); oldgroups = objgroups; objgroups = NULL; oldobjects = objects; objects = NULL; oldnotifs = notifs; notifs = NULL; if (current_module == -1) { new_module(name, File); current_module = which_module(name); } DEBUGMSGTL(("parse-mibs", "Parsing MIB: %d %s\n", current_module, name)); while ((type = get_token(fp, token, MAXTOKEN)) != ENDOFFILE) if (type == BEGIN) break; break; case OBJTYPE: nnp = parse_objecttype(fp, name); if (nnp == NULL) { print_error("Bad parse of OBJECT-TYPE", NULL, type); gMibError = MODULE_SYNTAX_ERROR; return NULL; } break; case OBJGROUP: nnp = parse_objectgroup(fp, name, OBJECTS, &objects); if (nnp == NULL) { print_error("Bad parse of OBJECT-GROUP", NULL, type); gMibError = MODULE_SYNTAX_ERROR; return NULL; } break; case NOTIFGROUP: nnp = parse_objectgroup(fp, name, NOTIFICATIONS, &notifs); if (nnp == NULL) { print_error("Bad parse of NOTIFICATION-GROUP", NULL, type); gMibError = MODULE_SYNTAX_ERROR; return NULL; } break; case TRAPTYPE: nnp = parse_trapDefinition(fp, name); if (nnp == NULL) { print_error("Bad parse of TRAP-TYPE", NULL, type); gMibError = MODULE_SYNTAX_ERROR; return NULL; } break; case NOTIFTYPE: nnp = parse_notificationDefinition(fp, name); if (nnp == NULL) { print_error("Bad parse of NOTIFICATION-TYPE", NULL, type); gMibError = MODULE_SYNTAX_ERROR; return NULL; } break; case COMPLIANCE: nnp = parse_compliance(fp, name); if (nnp == NULL) { print_error("Bad parse of MODULE-COMPLIANCE", NULL, type); gMibError = MODULE_SYNTAX_ERROR; return NULL; } break; case AGENTCAP: nnp = parse_capabilities(fp, name); if (nnp == NULL) { print_error("Bad parse of AGENT-CAPABILITIES", NULL, type); gMibError = MODULE_SYNTAX_ERROR; return NULL; } break; case MACRO: nnp = parse_macro(fp, name); if (nnp == NULL) { print_error("Bad parse of MACRO", NULL, type); gMibError = MODULE_SYNTAX_ERROR; /* * return NULL; */ } free_node(nnp); /* IGNORE */ nnp = NULL; break; case MODULEIDENTITY: nnp = parse_moduleIdentity(fp, name); if (nnp == NULL) { print_error("Bad parse of MODULE-IDENTITY", NULL, type); gMibError = MODULE_SYNTAX_ERROR; return NULL; } break; case OBJIDENTITY: nnp = parse_objectgroup(fp, name, OBJECTS, &objects); if (nnp == NULL) { print_error("Bad parse of OBJECT-IDENTITY", NULL, type); gMibError = MODULE_SYNTAX_ERROR; return NULL; } break; case OBJECT: type = get_token(fp, token, MAXTOKEN); if (type != IDENTIFIER) { print_error("Expected IDENTIFIER", token, type); gMibError = MODULE_SYNTAX_ERROR; return NULL; } type = get_token(fp, token, MAXTOKEN); if (type != EQUALS) { print_error("Expected \"::=\"", token, type); gMibError = MODULE_SYNTAX_ERROR; return NULL; } nnp = parse_objectid(fp, name); if (nnp == NULL) { print_error("Bad parse of OBJECT IDENTIFIER", NULL, type); gMibError = MODULE_SYNTAX_ERROR; return NULL; } break; case EQUALS: nnp = parse_asntype(fp, name, &type, token); lasttype = CONTINUE; break; case ENDOFFILE: break; default: print_error("Bad operator", token, type); gMibError = MODULE_SYNTAX_ERROR; return NULL; } if (nnp) { if (np) np->next = nnp; else np = root = nnp; while (np->next) np = np->next; if (np->type == TYPE_OTHER) np->type = type; } } DEBUGMSGTL(("parse-file", "End of file (%s)\n", File)); return root; } /* * return zero if character is not a label character. */ static int is_labelchar(int ich) { if ((isalnum(ich)) || (ich == '-')) return 1; if (ich == '_' && netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_PARSE_LABEL)) { return 1; } return 0; } /** * Read a single character from a file. Assumes that the caller has invoked * flockfile(). Uses fgetc_unlocked() instead of getc() since the former is * implemented as an inline function in glibc. See also bug 3447196 * (http://sourceforge.net/tracker/?func=detail&aid=3447196&group_id=12694&atid=112694). */ static int netsnmp_getc(FILE *stream) { #ifdef HAVE_FGETC_UNLOCKED return fgetc_unlocked(stream); #else return getc(stream); #endif } /* * Parses a token from the file. The type of the token parsed is returned, * and the text is placed in the string pointed to by token. * Warning: this method may recurse. */ static int get_token(FILE * fp, char *token, int maxtlen) { register int ch, ch_next; register char *cp = token; register int hash = 0; register struct tok *tp; int too_long = 0; enum { bdigits, xdigits, other } seenSymbols; /* * skip all white space */ do { ch = netsnmp_getc(fp); if (ch == '\n') mibLine++; } while (isspace(ch) && ch != EOF); *cp++ = ch; *cp = '\0'; switch (ch) { case EOF: return ENDOFFILE; case '"': return parseQuoteString(fp, token, maxtlen); case '\'': /* binary or hex constant */ seenSymbols = bdigits; while ((ch = netsnmp_getc(fp)) != EOF && ch != '\'') { switch (seenSymbols) { case bdigits: if (ch == '0' || ch == '1') break; seenSymbols = xdigits; /* FALL THROUGH */ case xdigits: if (isxdigit(ch)) break; seenSymbols = other; case other: break; } if (cp - token < maxtlen - 2) *cp++ = ch; } if (ch == '\'') { unsigned long val = 0; char *run = token + 1; ch = netsnmp_getc(fp); switch (ch) { case EOF: return ENDOFFILE; case 'b': case 'B': if (seenSymbols > bdigits) { *cp++ = '\''; *cp = 0; return LABEL; } while (run != cp) val = val * 2 + *run++ - '0'; break; case 'h': case 'H': if (seenSymbols > xdigits) { *cp++ = '\''; *cp = 0; return LABEL; } while (run != cp) { ch = *run++; if ('0' <= ch && ch <= '9') val = val * 16 + ch - '0'; else if ('a' <= ch && ch <= 'f') val = val * 16 + ch - 'a' + 10; else if ('A' <= ch && ch <= 'F') val = val * 16 + ch - 'A' + 10; } break; default: *cp++ = '\''; *cp = 0; return LABEL; } sprintf(token, "%ld", val); return NUMBER; } else return LABEL; case '(': return LEFTPAREN; case ')': return RIGHTPAREN; case '{': return LEFTBRACKET; case '}': return RIGHTBRACKET; case '[': return LEFTSQBRACK; case ']': return RIGHTSQBRACK; case ';': return SEMI; case ',': return COMMA; case '|': return BAR; case '.': ch_next = netsnmp_getc(fp); if (ch_next == '.') return RANGE; ungetc(ch_next, fp); return LABEL; case ':': ch_next = netsnmp_getc(fp); if (ch_next != ':') { ungetc(ch_next, fp); return LABEL; } ch_next = netsnmp_getc(fp); if (ch_next != '=') { ungetc(ch_next, fp); return LABEL; } return EQUALS; case '-': ch_next = netsnmp_getc(fp); if (ch_next == '-') { if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_COMMENT_TERM)) { /* * Treat the rest of this line as a comment. */ while ((ch_next != EOF) && (ch_next != '\n')) ch_next = netsnmp_getc(fp); } else { /* * Treat the rest of the line or until another '--' as a comment */ /* * (this is the "technically" correct way to parse comments) */ ch = ' '; ch_next = netsnmp_getc(fp); while (ch_next != EOF && ch_next != '\n' && (ch != '-' || ch_next != '-')) { ch = ch_next; ch_next = netsnmp_getc(fp); } } if (ch_next == EOF) return ENDOFFILE; if (ch_next == '\n') mibLine++; return get_token(fp, token, maxtlen); } ungetc(ch_next, fp); /* fallthrough */ default: /* * Accumulate characters until end of token is found. Then attempt to * match this token as a reserved word. If a match is found, return the * type. Else it is a label. */ if (!is_labelchar(ch)) return LABEL; hash += tolower(ch); more: while (is_labelchar(ch_next = netsnmp_getc(fp))) { hash += tolower(ch_next); if (cp - token < maxtlen - 1) *cp++ = ch_next; else too_long = 1; } ungetc(ch_next, fp); *cp = '\0'; if (too_long) print_error("Warning: token too long", token, CONTINUE); for (tp = buckets[BUCKET(hash)]; tp; tp = tp->next) { if ((tp->hash == hash) && (!label_compare(tp->name, token))) break; } if (tp) { if (tp->token != CONTINUE) return (tp->token); while (isspace((ch_next = netsnmp_getc(fp)))) if (ch_next == '\n') mibLine++; if (ch_next == EOF) return ENDOFFILE; if (isalnum(ch_next)) { *cp++ = ch_next; hash += tolower(ch_next); goto more; } } if (token[0] == '-' || isdigit((unsigned char)(token[0]))) { for (cp = token + 1; *cp; cp++) if (!isdigit((unsigned char)(*cp))) return LABEL; return NUMBER; } return LABEL; } } netsnmp_feature_child_of(parse_get_token, netsnmp_unused) #ifndef NETSNMP_FEATURE_REMOVE_PARSE_GET_TOKEN int snmp_get_token(FILE * fp, char *token, int maxtlen) { return get_token(fp, token, maxtlen); } #endif /* NETSNMP_FEATURE_REMOVE_PARSE_GET_TOKEN */ int add_mibfile(const char* tmpstr, const char* d_name) { FILE *fp; char token[MAXTOKEN], token2[MAXTOKEN]; /* * which module is this */ if ((fp = fopen(tmpstr, "r")) == NULL) { snmp_log_perror(tmpstr); return 1; } DEBUGMSGTL(("parse-mibs", "Checking file: %s...\n", tmpstr)); mibLine = 1; File = tmpstr; if (get_token(fp, token, MAXTOKEN) != LABEL) { fclose(fp); return 1; } /* * simple test for this being a MIB */ if (get_token(fp, token2, MAXTOKEN) == DEFINITIONS) { new_module(token, tmpstr); fclose(fp); return 0; } else { fclose(fp); return 1; } } static int elemcmp(const void *a, const void *b) { const char *const *s1 = a, *const *s2 = b; return strcmp(*s1, *s2); } /* * Scan a directory and return all filenames found as an array of pointers to * directory entries (@result). */ static int scan_directory(char ***result, const char *dirname) { DIR *dir, *dir2; struct dirent *file; char **filenames = NULL; int fname_len, i, filename_count = 0, array_size = 0; char *tmpstr; *result = NULL; dir = opendir(dirname); if (!dir) return -1; while ((file = readdir(dir))) { /* * Only parse file names that don't begin with a '.' * Also skip files ending in '~', or starting/ending * with '#' which are typically editor backup files. */ fname_len = strlen(file->d_name); if (fname_len > 0 && file->d_name[0] != '.' && file->d_name[0] != '#' && file->d_name[fname_len-1] != '#' && file->d_name[fname_len-1] != '~') { if (asprintf(&tmpstr, "%s/%s", dirname, file->d_name) < 0) continue; dir2 = opendir(tmpstr); if (dir2) { /* file is a directory, don't read it */ closedir(dir2); } else { if (filename_count >= array_size) { char **new_filenames; array_size = (array_size + 16) * 2; new_filenames = realloc(filenames, array_size * sizeof(filenames[0])); if (!new_filenames) { free(tmpstr); for (i = 0; i < filename_count; i++) free(filenames[i]); free(filenames); closedir(dir); return -1; } filenames = new_filenames; } filenames[filename_count++] = tmpstr; tmpstr = NULL; } free(tmpstr); } } closedir(dir); if (filenames) qsort(filenames, filename_count, sizeof(filenames[0]), elemcmp); *result = filenames; return filename_count; } /* For Win32 platforms, the directory does not maintain a last modification * date that we can compare with the modification date of the .index file. * Therefore there is no way to know whether any .index file is valid. * This is the reason for the #if !(defined(WIN32) || defined(cygwin)) * in the add_mibdir function */ int add_mibdir(const char *dirname) { const char *oldFile = File; char **filenames; int count = 0; int filename_count, i; DEBUGMSGTL(("parse-mibs", "Scanning directory %s\n", dirname)); filename_count = scan_directory(&filenames, dirname); if (filename_count >= 0) { for (i = 0; i < filename_count; i++) { if (add_mibfile(filenames[i], strrchr(filenames[i], '/')) == 0) count++; free(filenames[i]); } File = oldFile; free(filenames); return (count); } else DEBUGMSGTL(("parse-mibs","cannot open MIB directory %s\n", dirname)); return (-1); } /* * Returns the root of the whole tree * (for backwards compatability) */ struct tree * read_mib(const char *filename) { FILE *fp; char token[MAXTOKEN]; fp = fopen(filename, "r"); if (fp == NULL) { snmp_log_perror(filename); return NULL; } mibLine = 1; File = filename; DEBUGMSGTL(("parse-mibs", "Parsing file: %s...\n", filename)); if (get_token(fp, token, MAXTOKEN) != LABEL) { snmp_log(LOG_ERR, "Failed to parse MIB file %s\n", filename); fclose(fp); return NULL; } fclose(fp); new_module(token, filename); (void) netsnmp_read_module(token); return tree_head; } struct tree * read_all_mibs(void) { struct module *mp; for (mp = module_head; mp; mp = mp->next) if (mp->no_imports == -1) netsnmp_read_module(mp->name); adopt_orphans(); /* If entered the syntax error loop in "read_module()" */ if (gLoop == 1) { gLoop = 0; free(gpMibErrorString); gpMibErrorString = NULL; if (asprintf(&gpMibErrorString, "Error in parsing MIB module(s): %s !" " Unable to load corresponding MIB(s)", gMibNames) < 0) { snmp_log(LOG_CRIT, "failed to allocated memory for gpMibErrorString\n"); } } /* Caller's responsibility to free this memory */ tree_head->parseErrorString = gpMibErrorString; return tree_head; } #ifdef TEST int main(int argc, char *argv[]) { int i; struct tree *tp; netsnmp_ds_set_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_WARNINGS, 2); netsnmp_init_mib(); if (argc == 1) (void) read_all_mibs(); else for (i = 1; i < argc; i++) read_mib(argv[i]); for (tp = tree_head; tp; tp = tp->next_peer) print_subtree(stdout, tp, 0); free_tree(tree_head); return 0; } #endif /* TEST */ static int parseQuoteString(FILE * fp, char *token, int maxtlen) { register int ch; int count = 0; int too_long = 0; char *token_start = token; for (ch = netsnmp_getc(fp); ch != EOF; ch = netsnmp_getc(fp)) { if (ch == '\r') continue; if (ch == '\n') { mibLine++; } else if (ch == '"') { *token = '\0'; if (too_long && netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_WARNINGS) > 1) { /* * show short form for brevity sake */ char ch_save = *(token_start + 50); *(token_start + 50) = '\0'; print_error("Warning: string too long", token_start, QUOTESTRING); *(token_start + 50) = ch_save; } return QUOTESTRING; } /* * maximum description length check. If greater, keep parsing * but truncate the string */ if (++count < maxtlen) *token++ = ch; else too_long = 1; } return 0; } /* * struct index_list * * getIndexes(FILE *fp): * This routine parses a string like { blah blah blah } and returns a * list of the strings enclosed within it. * */ static struct index_list * getIndexes(FILE * fp, struct index_list **retp) { int type; char token[MAXTOKEN]; char nextIsImplied = 0; struct index_list *mylist = NULL; struct index_list **mypp = &mylist; free_indexes(retp); type = get_token(fp, token, MAXTOKEN); if (type != LEFTBRACKET) { return NULL; } type = get_token(fp, token, MAXTOKEN); while (type != RIGHTBRACKET && type != ENDOFFILE) { if ((type == LABEL) || (type & SYNTAX_MASK)) { *mypp = (struct index_list *) calloc(1, sizeof(struct index_list)); if (*mypp) { (*mypp)->ilabel = strdup(token); (*mypp)->isimplied = nextIsImplied; mypp = &(*mypp)->next; nextIsImplied = 0; } } else if (type == IMPLIED) { nextIsImplied = 1; } type = get_token(fp, token, MAXTOKEN); } *retp = mylist; return mylist; } static struct varbind_list * getVarbinds(FILE * fp, struct varbind_list **retp) { int type; char token[MAXTOKEN]; struct varbind_list *mylist = NULL; struct varbind_list **mypp = &mylist; free_varbinds(retp); type = get_token(fp, token, MAXTOKEN); if (type != LEFTBRACKET) { return NULL; } type = get_token(fp, token, MAXTOKEN); while (type != RIGHTBRACKET && type != ENDOFFILE) { if ((type == LABEL) || (type & SYNTAX_MASK)) { *mypp = (struct varbind_list *) calloc(1, sizeof(struct varbind_list)); if (*mypp) { (*mypp)->vblabel = strdup(token); mypp = &(*mypp)->next; } } type = get_token(fp, token, MAXTOKEN); } *retp = mylist; return mylist; } static void free_indexes(struct index_list **spp) { if (spp && *spp) { struct index_list *pp, *npp; pp = *spp; *spp = NULL; while (pp) { npp = pp->next; if (pp->ilabel) free(pp->ilabel); free(pp); pp = npp; } } } static void free_varbinds(struct varbind_list **spp) { if (spp && *spp) { struct varbind_list *pp, *npp; pp = *spp; *spp = NULL; while (pp) { npp = pp->next; if (pp->vblabel) free(pp->vblabel); free(pp); pp = npp; } } } static void free_ranges(struct range_list **spp) { if (spp && *spp) { struct range_list *pp, *npp; pp = *spp; *spp = NULL; while (pp) { npp = pp->next; free(pp); pp = npp; } } } static void free_enums(struct enum_list **spp) { if (spp && *spp) { struct enum_list *pp, *npp; pp = *spp; *spp = NULL; while (pp) { npp = pp->next; if (pp->label) free(pp->label); free(pp); pp = npp; } } } static struct enum_list * copy_enums(struct enum_list *sp) { struct enum_list *xp = NULL, **spp = &xp; while (sp) { *spp = (struct enum_list *) calloc(1, sizeof(struct enum_list)); if (!*spp) break; (*spp)->label = strdup(sp->label); (*spp)->value = sp->value; spp = &(*spp)->next; sp = sp->next; } return (xp); } static struct range_list * copy_ranges(struct range_list *sp) { struct range_list *xp = NULL, **spp = &xp; while (sp) { *spp = (struct range_list *) calloc(1, sizeof(struct range_list)); if (!*spp) break; (*spp)->low = sp->low; (*spp)->high = sp->high; spp = &(*spp)->next; sp = sp->next; } return (xp); } /* * This routine parses a string like { blah blah blah } and returns OBJID if * it is well formed, and NULL if not. */ static int tossObjectIdentifier(FILE * fp) { int type; char token[MAXTOKEN]; int bracketcount = 1; type = get_token(fp, token, MAXTOKEN); if (type != LEFTBRACKET) return 0; while ((type != RIGHTBRACKET || bracketcount > 0) && type != ENDOFFILE) { type = get_token(fp, token, MAXTOKEN); if (type == LEFTBRACKET) bracketcount++; else if (type == RIGHTBRACKET) bracketcount--; } if (type == RIGHTBRACKET) return OBJID; else return 0; } /* Find node in any MIB module Used by Perl modules */ struct tree * find_node(const char *name, struct tree *subtree) { /* Unused */ return (find_tree_node(name, -1)); } netsnmp_feature_child_of(parse_find_node2, netsnmp_unused) #ifndef NETSNMP_FEATURE_REMOVE_PARSE_FIND_NODE2 struct tree * find_node2(const char *name, const char *module) { int modid = -1; if (module) { modid = which_module(module); } if (modid == -1) { return (NULL); } return (find_tree_node(name, modid)); } #endif /* NETSNMP_FEATURE_REMOVE_PARSE_FIND_NODE2 */ #ifndef NETSNMP_FEATURE_REMOVE_FIND_MODULE /* Used in the perl module */ struct module * find_module(int mid) { struct module *mp; for (mp = module_head; mp != NULL; mp = mp->next) { if (mp->modid == mid) break; } return mp; } #endif /* NETSNMP_FEATURE_REMOVE_FIND_MODULE */ static char leave_indent[256]; static int leave_was_simple; static void print_mib_leaves(FILE * f, struct tree *tp, int width) { struct tree *ntp; char *ip = leave_indent + strlen(leave_indent) - 1; char last_ipch = *ip; *ip = '+'; if (tp->type == TYPE_OTHER || tp->type > TYPE_SIMPLE_LAST) { fprintf(f, "%s--%s(%ld)\n", leave_indent, tp->label, tp->subid); if (tp->indexes) { struct index_list *xp = tp->indexes; int first = 1, cpos = 0, len, cmax = width - strlen(leave_indent) - 12; *ip = last_ipch; fprintf(f, "%s | Index: ", leave_indent); while (xp) { if (first) first = 0; else fprintf(f, ", "); cpos += (len = strlen(xp->ilabel) + 2); if (cpos > cmax) { fprintf(f, "\n"); fprintf(f, "%s | ", leave_indent); cpos = len; } fprintf(f, "%s", xp->ilabel); xp = xp->next; } fprintf(f, "\n"); *ip = '+'; } } else { const char *acc, *typ; int size = 0; switch (tp->access) { case MIB_ACCESS_NOACCESS: acc = "----"; break; case MIB_ACCESS_READONLY: acc = "-R--"; break; case MIB_ACCESS_WRITEONLY: acc = "--W-"; break; case MIB_ACCESS_READWRITE: acc = "-RW-"; break; case MIB_ACCESS_NOTIFY: acc = "---N"; break; case MIB_ACCESS_CREATE: acc = "CR--"; break; default: acc = " "; break; } switch (tp->type) { case TYPE_OBJID: typ = "ObjID "; break; case TYPE_OCTETSTR: typ = "String "; size = 1; break; case TYPE_INTEGER: if (tp->enums) typ = "EnumVal "; else typ = "INTEGER "; break; case TYPE_NETADDR: typ = "NetAddr "; break; case TYPE_IPADDR: typ = "IpAddr "; break; case TYPE_COUNTER: typ = "Counter "; break; case TYPE_GAUGE: typ = "Gauge "; break; case TYPE_TIMETICKS: typ = "TimeTicks"; break; case TYPE_OPAQUE: typ = "Opaque "; size = 1; break; case TYPE_NULL: typ = "Null "; break; case TYPE_COUNTER64: typ = "Counter64"; break; case TYPE_BITSTRING: typ = "BitString"; break; case TYPE_NSAPADDRESS: typ = "NsapAddr "; break; case TYPE_UNSIGNED32: typ = "Unsigned "; break; case TYPE_UINTEGER: typ = "UInteger "; break; case TYPE_INTEGER32: typ = "Integer32"; break; default: typ = " "; break; } fprintf(f, "%s-- %s %s %s(%ld)\n", leave_indent, acc, typ, tp->label, tp->subid); *ip = last_ipch; if (tp->tc_index >= 0) fprintf(f, "%s Textual Convention: %s\n", leave_indent, tclist[tp->tc_index].descriptor); if (tp->enums) { struct enum_list *ep = tp->enums; int cpos = 0, cmax = width - strlen(leave_indent) - 16; fprintf(f, "%s Values: ", leave_indent); while (ep) { char buf[80]; int bufw; if (ep != tp->enums) fprintf(f, ", "); snprintf(buf, sizeof(buf), "%s(%d)", ep->label, ep->value); buf[ sizeof(buf)-1 ] = 0; cpos += (bufw = strlen(buf) + 2); if (cpos >= cmax) { fprintf(f, "\n%s ", leave_indent); cpos = bufw; } fprintf(f, "%s", buf); ep = ep->next; } fprintf(f, "\n"); } if (tp->ranges) { struct range_list *rp = tp->ranges; if (size) fprintf(f, "%s Size: ", leave_indent); else fprintf(f, "%s Range: ", leave_indent); while (rp) { if (rp != tp->ranges) fprintf(f, " | "); print_range_value(f, tp->type, rp); rp = rp->next; } fprintf(f, "\n"); } } *ip = last_ipch; strcat(leave_indent, " |"); leave_was_simple = tp->type != TYPE_OTHER; { int i, j, count = 0; struct leave { oid id; struct tree *tp; } *leaves, *lp; for (ntp = tp->child_list; ntp; ntp = ntp->next_peer) count++; if (count) { leaves = (struct leave *) calloc(count, sizeof(struct leave)); if (!leaves) return; for (ntp = tp->child_list, count = 0; ntp; ntp = ntp->next_peer) { for (i = 0, lp = leaves; i < count; i++, lp++) if (lp->id >= ntp->subid) break; for (j = count; j > i; j--) leaves[j] = leaves[j - 1]; lp->id = ntp->subid; lp->tp = ntp; count++; } for (i = 1, lp = leaves; i <= count; i++, lp++) { if (!leave_was_simple || lp->tp->type == 0) fprintf(f, "%s\n", leave_indent); if (i == count) ip[3] = ' '; print_mib_leaves(f, lp->tp, width); } free(leaves); leave_was_simple = 0; } } ip[1] = 0; } void print_mib_tree(FILE * f, struct tree *tp, int width) { leave_indent[0] = ' '; leave_indent[1] = 0; leave_was_simple = 1; print_mib_leaves(f, tp, width); } /* * Merge the parsed object identifier with the existing node. * If there is a problem with the identifier, release the existing node. */ static struct node * merge_parse_objectid(struct node *np, FILE * fp, char *name) { struct node *nnp; /* * printf("merge defval --> %s\n",np->defaultValue); */ nnp = parse_objectid(fp, name); if (nnp) { /* * apply last OID sub-identifier data to the information */ /* * already collected for this node. */ struct node *headp, *nextp; int ncount = 0; nextp = headp = nnp; while (nnp->next) { nextp = nnp; ncount++; nnp = nnp->next; } np->label = nnp->label; np->subid = nnp->subid; np->modid = nnp->modid; np->parent = nnp->parent; if (nnp->filename != NULL) { free(nnp->filename); } free(nnp); if (ncount) { nextp->next = np; np = headp; } } else { free_node(np); np = NULL; } return np; } /* * transfer data to tree from node * * move pointers for alloc'd data from np to tp. * this prevents them from being freed when np is released. * parent member is not moved. * * CAUTION: nodes may be repeats of existing tree nodes. * This can happen especially when resolving IMPORT clauses. * */ static void tree_from_node(struct tree *tp, struct node *np) { free_partial_tree(tp, FALSE); tp->label = np->label; np->label = NULL; tp->enums = np->enums; np->enums = NULL; tp->ranges = np->ranges; np->ranges = NULL; tp->indexes = np->indexes; np->indexes = NULL; tp->augments = np->augments; np->augments = NULL; tp->varbinds = np->varbinds; np->varbinds = NULL; tp->hint = np->hint; np->hint = NULL; tp->units = np->units; np->units = NULL; tp->description = np->description; np->description = NULL; tp->reference = np->reference; np->reference = NULL; tp->defaultValue = np->defaultValue; np->defaultValue = NULL; tp->subid = np->subid; tp->tc_index = np->tc_index; tp->type = translation_table[np->type]; tp->access = np->access; tp->status = np->status; set_function(tp); } #endif /* NETSNMP_DISABLE_MIB_LOADING */
./CrossVul/dataset_final_sorted/CWE-59/c/good_4226_4
crossvul-cpp_data_bad_1591_0
/* abrt-hook-ccpp.cpp - the hook for C/C++ crashing program Copyright (C) 2009 Zdenek Prikryl (zprikryl@redhat.com) Copyright (C) 2009 RedHat inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <sys/utsname.h> #include "libabrt.h" #define DUMP_SUID_UNSAFE 1 #define DUMP_SUID_SAFE 2 /* I want to use -Werror, but gcc-4.4 throws a curveball: * "warning: ignoring return value of 'ftruncate', declared with attribute warn_unused_result" * and (void) cast is not enough to shut it up! Oh God... */ #define IGNORE_RESULT(func_call) do { if (func_call) /* nothing */; } while (0) static char* malloc_readlink(const char *linkname) { char buf[PATH_MAX + 1]; int len; len = readlink(linkname, buf, sizeof(buf)-1); if (len >= 0) { buf[len] = '\0'; return xstrdup(buf); } return NULL; } /* Custom version of copyfd_xyz, * one which is able to write into two descriptors at once. */ #define CONFIG_FEATURE_COPYBUF_KB 4 static off_t copyfd_sparse(int src_fd, int dst_fd1, int dst_fd2, off_t size2) { off_t total = 0; int last_was_seek = 0; #if CONFIG_FEATURE_COPYBUF_KB <= 4 char buffer[CONFIG_FEATURE_COPYBUF_KB * 1024]; enum { buffer_size = sizeof(buffer) }; #else char *buffer; int buffer_size; /* We want page-aligned buffer, just in case kernel is clever * and can do page-aligned io more efficiently */ buffer = mmap(NULL, CONFIG_FEATURE_COPYBUF_KB * 1024, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, /* ignored: */ -1, 0); buffer_size = CONFIG_FEATURE_COPYBUF_KB * 1024; if (buffer == MAP_FAILED) { buffer = alloca(4 * 1024); buffer_size = 4 * 1024; } #endif while (1) { ssize_t rd = safe_read(src_fd, buffer, buffer_size); if (!rd) { /* eof */ if (last_was_seek) { if (lseek(dst_fd1, -1, SEEK_CUR) < 0 || safe_write(dst_fd1, "", 1) != 1 || (dst_fd2 >= 0 && (lseek(dst_fd2, -1, SEEK_CUR) < 0 || safe_write(dst_fd2, "", 1) != 1 ) ) ) { perror_msg("Write error"); total = -1; goto out; } } /* all done */ goto out; } if (rd < 0) { perror_msg("Read error"); total = -1; goto out; } /* checking sparseness */ ssize_t cnt = rd; while (--cnt >= 0) { if (buffer[cnt] != 0) { /* not sparse */ errno = 0; ssize_t wr1 = full_write(dst_fd1, buffer, rd); ssize_t wr2 = (dst_fd2 >= 0 ? full_write(dst_fd2, buffer, rd) : rd); if (wr1 < rd || wr2 < rd) { perror_msg("Write error"); total = -1; goto out; } last_was_seek = 0; goto adv; } } /* sparse */ xlseek(dst_fd1, rd, SEEK_CUR); if (dst_fd2 >= 0) xlseek(dst_fd2, rd, SEEK_CUR); last_was_seek = 1; adv: total += rd; size2 -= rd; if (size2 < 0) dst_fd2 = -1; //TODO: truncate to 0 or even delete the second file //(currently we delete the file later) } out: #if CONFIG_FEATURE_COPYBUF_KB > 4 if (buffer_size != 4 * 1024) munmap(buffer, buffer_size); #endif return total; } /* Global data */ static char *user_pwd; static char *proc_pid_status; static struct dump_dir *dd; static int user_core_fd = -1; /* * %s - signal number * %c - ulimit -c value * %p - pid * %u - uid * %g - gid * %t - UNIX time of dump * %e - executable filename * %h - hostname * %% - output one "%" */ /* Hook must be installed with exactly the same sequence of %c specifiers. * Last one, %h, may be omitted (we can find it out). */ static const char percent_specifiers[] = "%scpugteh"; static char *core_basename = (char*) "core"; /* * Used for error messages only. * It is either the same as core_basename if it is absolute, * or $PWD/core_basename. */ static char *full_core_basename; static char* get_executable(pid_t pid, int *fd_p) { char buf[sizeof("/proc/%lu/exe") + sizeof(long)*3]; sprintf(buf, "/proc/%lu/exe", (long)pid); if (fd_p) *fd_p = open(buf, O_RDONLY); /* might fail and return -1, it's ok */ char *executable = malloc_readlink(buf); if (!executable) return NULL; /* find and cut off " (deleted)" from the path */ char *deleted = executable + strlen(executable) - strlen(" (deleted)"); if (deleted > executable && strcmp(deleted, " (deleted)") == 0) { *deleted = '\0'; log("File '%s' seems to be deleted", executable); } /* find and cut off prelink suffixes from the path */ char *prelink = executable + strlen(executable) - strlen(".#prelink#.XXXXXX"); if (prelink > executable && strncmp(prelink, ".#prelink#.", strlen(".#prelink#.")) == 0) { log("File '%s' seems to be a prelink temporary file", executable); *prelink = '\0'; } return executable; } static char* get_cwd(pid_t pid) { char buf[sizeof("/proc/%lu/cwd") + sizeof(long)*3]; sprintf(buf, "/proc/%lu/cwd", (long)pid); return malloc_readlink(buf); } static char* get_rootdir(pid_t pid) { char buf[sizeof("/proc/%lu/root") + sizeof(long)*3]; sprintf(buf, "/proc/%lu/root", (long)pid); return malloc_readlink(buf); } static int get_fsuid(void) { int real, euid, saved; /* if we fail to parse the uid, then make it root only readable to be safe */ int fs_uid = 0; char *line = proc_pid_status; /* never NULL */ for (;;) { if (strncmp(line, "Uid", 3) == 0) { int n = sscanf(line, "Uid:\t%d\t%d\t%d\t%d\n", &real, &euid, &saved, &fs_uid); if (n != 4) { perror_msg_and_die("Can't parse Uid: line"); } break; } line = strchr(line, '\n'); if (!line) break; line++; } return fs_uid; } static int dump_suid_policy() { /* - values are: 0 - don't dump suided programs - in this case the hook is not called by kernel 1 - create coredump readable by fs_uid 2 - create coredump readable by root only */ int c; int suid_dump_policy = 0; const char *filename = "/proc/sys/fs/suid_dumpable"; FILE *f = fopen(filename, "r"); if (!f) { log("Can't open %s", filename); return suid_dump_policy; } c = fgetc(f); fclose(f); if (c != EOF) suid_dump_policy = c - '0'; //log("suid dump policy is: %i", suid_dump_policy); return suid_dump_policy; } static int open_user_core(uid_t uid, uid_t fsuid, pid_t pid, char **percent_values) { errno = 0; if (user_pwd == NULL || chdir(user_pwd) != 0 ) { perror_msg("Can't cd to '%s'", user_pwd); return -1; } struct passwd* pw = getpwuid(uid); gid_t gid = pw ? pw->pw_gid : uid; //log("setting uid: %i gid: %i", uid, gid); xsetegid(gid); xseteuid(fsuid); if (strcmp(core_basename, "core") == 0) { /* Mimic "core.PID" if requested */ char buf[] = "0\n"; int fd = open("/proc/sys/kernel/core_uses_pid", O_RDONLY); if (fd >= 0) { IGNORE_RESULT(read(fd, buf, sizeof(buf))); close(fd); } if (strcmp(buf, "1\n") == 0) { core_basename = xasprintf("%s.%lu", core_basename, (long)pid); } } else { /* Expand old core pattern, put expanded name in core_basename */ core_basename = xstrdup(core_basename); unsigned idx = 0; while (1) { char c = core_basename[idx]; if (!c) break; idx++; if (c != '%') continue; /* We just copied %, look at following char and expand %c */ c = core_basename[idx]; unsigned specifier_num = strchrnul(percent_specifiers, c) - percent_specifiers; if (percent_specifiers[specifier_num] != '\0') /* valid %c (might be %% too) */ { const char *val = "%"; if (specifier_num > 0) /* not %% */ val = percent_values[specifier_num - 1]; //log("c:'%c'", c); //log("val:'%s'", val); /* Replace %c at core_basename[idx] by its value */ idx--; char *old = core_basename; core_basename = xasprintf("%.*s%s%s", idx, core_basename, val, core_basename + idx + 2); //log("pos:'%*s|'", idx, ""); //log("new:'%s'", core_basename); //log("old:'%s'", old); free(old); idx += strlen(val); } /* else: invalid %c, % is already copied verbatim, * next loop iteration will copy c */ } } full_core_basename = core_basename; if (core_basename[0] != '/') core_basename = concat_path_file(user_pwd, core_basename); /* Open (create) compat core file. * man core: * There are various circumstances in which a core dump file * is not produced: * * [skipped obvious ones] * The process does not have permission to write the core file. * ...if a file with the same name exists and is not writable * or is not a regular file (e.g., it is a directory or a symbolic link). * * A file with the same name already exists, but there is more * than one hard link to that file. * * The file system where the core dump file would be created is full; * or has run out of inodes; or is mounted read-only; * or the user has reached their quota for the file system. * * The RLIMIT_CORE or RLIMIT_FSIZE resource limits for the process * are set to zero. * [we check RLIMIT_CORE, but how can we check RLIMIT_FSIZE?] * * The binary being executed by the process does not have * read permission enabled. [how we can check it here?] * * The process is executing a set-user-ID (set-group-ID) program * that is owned by a user (group) other than the real * user (group) ID of the process. [TODO?] * (However, see the description of the prctl(2) PR_SET_DUMPABLE operation, * and the description of the /proc/sys/fs/suid_dumpable file in proc(5).) */ struct stat sb; errno = 0; /* Do not O_TRUNC: if later checks fail, we do not want to have file already modified here */ int user_core_fd = open(core_basename, O_WRONLY | O_CREAT | O_NOFOLLOW, 0600); /* kernel makes 0600 too */ xsetegid(0); xseteuid(0); if (user_core_fd < 0 || fstat(user_core_fd, &sb) != 0 || !S_ISREG(sb.st_mode) || sb.st_nlink != 1 /* kernel internal dumper checks this too: if (inode->i_uid != current->fsuid) <fail>, need to mimic? */ ) { if (user_core_fd < 0) perror_msg("Can't open '%s'", full_core_basename); else perror_msg("'%s' is not a regular file with link count 1", full_core_basename); return -1; } if (ftruncate(user_core_fd, 0) != 0) { /* perror first, otherwise unlink may trash errno */ perror_msg("Can't truncate '%s' to size 0", full_core_basename); unlink(core_basename); return -1; } return user_core_fd; } static bool dump_fd_info(const char *dest_filename, char *source_filename, int source_base_ofs, uid_t uid, gid_t gid) { FILE *fp = fopen(dest_filename, "w"); if (!fp) return false; unsigned fd = 0; while (fd <= 99999) /* paranoia check */ { sprintf(source_filename + source_base_ofs, "fd/%u", fd); char *name = malloc_readlink(source_filename); if (!name) break; fprintf(fp, "%u:%s\n", fd, name); free(name); sprintf(source_filename + source_base_ofs, "fdinfo/%u", fd); fd++; FILE *in = fopen(source_filename, "r"); if (!in) continue; char buf[128]; while (fgets(buf, sizeof(buf)-1, in)) { /* in case the line is not terminated, terminate it */ char *eol = strchrnul(buf, '\n'); eol[0] = '\n'; eol[1] = '\0'; fputs(buf, fp); } fclose(in); } const int dest_fd = fileno(fp); if (fchown(dest_fd, uid, gid) < 0) { perror_msg("Can't change '%s' ownership to %lu:%lu", dest_filename, (long)uid, (long)gid); fclose(fp); unlink(dest_filename); return false; } fclose(fp); return true; } /* Like xopen, but on error, unlocks and deletes dd and user core */ static int create_or_die(const char *filename) { int fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, DEFAULT_DUMP_DIR_MODE); if (fd >= 0) { IGNORE_RESULT(fchown(fd, dd->dd_uid, dd->dd_gid)); return fd; } int sv_errno = errno; if (dd) dd_delete(dd); if (user_core_fd >= 0) { xchdir(user_pwd); unlink(core_basename); } errno = sv_errno; perror_msg_and_die("Can't open '%s'", filename); } int main(int argc, char** argv) { /* Kernel starts us with all fd's closed. * But it's dangerous: * fprintf(stderr) can dump messages into random fds, etc. * Ensure that if any of fd 0,1,2 is closed, we open it to /dev/null. */ int fd = xopen("/dev/null", O_RDWR); while (fd < 2) fd = xdup(fd); if (fd > 2) close(fd); if (argc < 8) { /* percent specifier: %s %c %p %u %g %t %e %h */ /* argv: [0] [1] [2] [3] [4] [5] [6] [7] [8]*/ error_msg_and_die("Usage: %s SIGNO CORE_SIZE_LIMIT PID UID GID TIME BINARY_NAME [HOSTNAME]", argv[0]); } /* Not needed on 2.6.30. * At least 2.6.18 has a bug where * argv[1] = "SIGNO CORE_SIZE_LIMIT PID ..." * argv[2] = "CORE_SIZE_LIMIT PID ..." * and so on. Fixing it: */ if (strchr(argv[1], ' ')) { int i; for (i = 1; argv[i]; i++) { strchrnul(argv[i], ' ')[0] = '\0'; } } logmode = LOGMODE_JOURNAL; /* Parse abrt.conf */ load_abrt_conf(); /* ... and plugins/CCpp.conf */ bool setting_MakeCompatCore; bool setting_SaveBinaryImage; { map_string_t *settings = new_map_string(); load_abrt_plugin_conf_file("CCpp.conf", settings); const char *value; value = get_map_string_item_or_NULL(settings, "MakeCompatCore"); setting_MakeCompatCore = value && string_to_bool(value); value = get_map_string_item_or_NULL(settings, "SaveBinaryImage"); setting_SaveBinaryImage = value && string_to_bool(value); value = get_map_string_item_or_NULL(settings, "VerboseLog"); if (value) g_verbose = xatoi_positive(value); free_map_string(settings); } errno = 0; const char* signal_str = argv[1]; int signal_no = xatoi_positive(signal_str); off_t ulimit_c = strtoull(argv[2], NULL, 10); if (ulimit_c < 0) /* unlimited? */ { /* set to max possible >0 value */ ulimit_c = ~((off_t)1 << (sizeof(off_t)*8-1)); } const char *pid_str = argv[3]; pid_t pid = xatoi_positive(argv[3]); uid_t uid = xatoi_positive(argv[4]); if (errno || pid <= 0) { perror_msg_and_die("PID '%s' or limit '%s' is bogus", argv[3], argv[2]); } { char *s = xmalloc_fopen_fgetline_fclose(VAR_RUN"/abrt/saved_core_pattern"); /* If we have a saved pattern and it's not a "|PROG ARGS" thing... */ if (s && s[0] != '|') core_basename = s; else free(s); } struct utsname uts; if (!argv[8]) /* no HOSTNAME? */ { uname(&uts); argv[8] = uts.nodename; } char path[PATH_MAX]; int src_fd_binary = -1; char *executable = get_executable(pid, setting_SaveBinaryImage ? &src_fd_binary : NULL); if (executable && strstr(executable, "/abrt-hook-ccpp")) { error_msg_and_die("PID %lu is '%s', not dumping it to avoid recursion", (long)pid, executable); } user_pwd = get_cwd(pid); /* may be NULL on error */ log_notice("user_pwd:'%s'", user_pwd); sprintf(path, "/proc/%lu/status", (long)pid); proc_pid_status = xmalloc_xopen_read_close(path, /*maxsz:*/ NULL); uid_t fsuid = uid; uid_t tmp_fsuid = get_fsuid(); int suid_policy = dump_suid_policy(); if (tmp_fsuid != uid) { /* use root for suided apps unless it's explicitly set to UNSAFE */ fsuid = 0; if (suid_policy == DUMP_SUID_UNSAFE) { fsuid = tmp_fsuid; } } /* Open a fd to compat coredump, if requested and is possible */ if (setting_MakeCompatCore && ulimit_c != 0) /* note: checks "user_pwd == NULL" inside; updates core_basename */ user_core_fd = open_user_core(uid, fsuid, pid, &argv[1]); if (executable == NULL) { /* readlink on /proc/$PID/exe failed, don't create abrt dump dir */ error_msg("Can't read /proc/%lu/exe link", (long)pid); goto create_user_core; } const char *signame = NULL; switch (signal_no) { case SIGILL : signame = "ILL" ; break; case SIGFPE : signame = "FPE" ; break; case SIGSEGV: signame = "SEGV"; break; case SIGBUS : signame = "BUS" ; break; //Bus error (bad memory access) case SIGABRT: signame = "ABRT"; break; //usually when abort() was called // We have real-world reports from users who see buggy programs // dying with SIGTRAP, uncommented it too: case SIGTRAP: signame = "TRAP"; break; //Trace/breakpoint trap // These usually aren't caused by bugs: //case SIGQUIT: signame = "QUIT"; break; //Quit from keyboard //case SIGSYS : signame = "SYS" ; break; //Bad argument to routine (SVr4) //case SIGXCPU: signame = "XCPU"; break; //CPU time limit exceeded (4.2BSD) //case SIGXFSZ: signame = "XFSZ"; break; //File size limit exceeded (4.2BSD) default: goto create_user_core; // not a signal we care about } if (!daemon_is_ok()) { /* not an error, exit with exit code 0 */ log("abrtd is not running. If it crashed, " "/proc/sys/kernel/core_pattern contains a stale value, " "consider resetting it to 'core'" ); goto create_user_core; } if (g_settings_nMaxCrashReportsSize > 0) { /* If free space is less than 1/4 of MaxCrashReportsSize... */ if (low_free_space(g_settings_nMaxCrashReportsSize, g_settings_dump_location)) goto create_user_core; } /* Check /var/tmp/abrt/last-ccpp marker, do not dump repeated crashes * if they happen too often. Else, write new marker value. */ snprintf(path, sizeof(path), "%s/last-ccpp", g_settings_dump_location); if (check_recent_crash_file(path, executable)) { /* It is a repeating crash */ goto create_user_core; } const char *last_slash = strrchr(executable, '/'); if (last_slash && strncmp(++last_slash, "abrt", 4) == 0) { /* If abrtd/abrt-foo crashes, we don't want to create a _directory_, * since that can make new copy of abrtd to process it, * and maybe crash again... * Unlike dirs, mere files are ignored by abrtd. */ snprintf(path, sizeof(path), "%s/%s-coredump", g_settings_dump_location, last_slash); int abrt_core_fd = xopen3(path, O_WRONLY | O_CREAT | O_TRUNC, 0600); off_t core_size = copyfd_eof(STDIN_FILENO, abrt_core_fd, COPYFD_SPARSE); if (core_size < 0 || fsync(abrt_core_fd) != 0) { unlink(path); /* copyfd_eof logs the error including errno string, * but it does not log file name */ error_msg_and_die("Error saving '%s'", path); } log("Saved core dump of pid %lu (%s) to %s (%llu bytes)", (long)pid, executable, path, (long long)core_size); return 0; } unsigned path_len = snprintf(path, sizeof(path), "%s/ccpp-%s-%lu.new", g_settings_dump_location, iso_date_string(NULL), (long)pid); if (path_len >= (sizeof(path) - sizeof("/"FILENAME_COREDUMP))) { goto create_user_core; } /* use fsuid instead of uid, so we don't expose any sensitive * information of suided app in /var/tmp/abrt */ dd = dd_create(path, fsuid, DEFAULT_DUMP_DIR_MODE); if (dd) { char *rootdir = get_rootdir(pid); dd_create_basic_files(dd, fsuid, (rootdir && strcmp(rootdir, "/") != 0) ? rootdir : NULL); char source_filename[sizeof("/proc/%lu/somewhat_long_name") + sizeof(long)*3]; int source_base_ofs = sprintf(source_filename, "/proc/%lu/smaps", (long)pid); source_base_ofs -= strlen("smaps"); char *dest_filename = concat_path_file(dd->dd_dirname, "also_somewhat_longish_name"); char *dest_base = strrchr(dest_filename, '/') + 1; // Disabled for now: /proc/PID/smaps tends to be BIG, // and not much more informative than /proc/PID/maps: //copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL); strcpy(source_filename + source_base_ofs, "maps"); strcpy(dest_base, FILENAME_MAPS); copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL); strcpy(source_filename + source_base_ofs, "limits"); strcpy(dest_base, FILENAME_LIMITS); copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL); strcpy(source_filename + source_base_ofs, "cgroup"); strcpy(dest_base, FILENAME_CGROUP); copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL); strcpy(dest_base, FILENAME_OPEN_FDS); dump_fd_info(dest_filename, source_filename, source_base_ofs, dd->dd_uid, dd->dd_gid); free(dest_filename); dd_save_text(dd, FILENAME_ANALYZER, "CCpp"); dd_save_text(dd, FILENAME_TYPE, "CCpp"); dd_save_text(dd, FILENAME_EXECUTABLE, executable); dd_save_text(dd, FILENAME_PID, pid_str); dd_save_text(dd, FILENAME_PROC_PID_STATUS, proc_pid_status); if (user_pwd) dd_save_text(dd, FILENAME_PWD, user_pwd); if (rootdir) { if (strcmp(rootdir, "/") != 0) dd_save_text(dd, FILENAME_ROOTDIR, rootdir); } char *reason = xasprintf("%s killed by SIG%s", last_slash, signame ? signame : signal_str); dd_save_text(dd, FILENAME_REASON, reason); free(reason); char *cmdline = get_cmdline(pid); dd_save_text(dd, FILENAME_CMDLINE, cmdline ? : ""); free(cmdline); char *environ = get_environ(pid); dd_save_text(dd, FILENAME_ENVIRON, environ ? : ""); free(environ); char *fips_enabled = xmalloc_fopen_fgetline_fclose("/proc/sys/crypto/fips_enabled"); if (fips_enabled) { if (strcmp(fips_enabled, "0") != 0) dd_save_text(dd, "fips_enabled", fips_enabled); free(fips_enabled); } dd_save_text(dd, FILENAME_ABRT_VERSION, VERSION); if (src_fd_binary > 0) { strcpy(path + path_len, "/"FILENAME_BINARY); int dst_fd = create_or_die(path); off_t sz = copyfd_eof(src_fd_binary, dst_fd, COPYFD_SPARSE); if (fsync(dst_fd) != 0 || close(dst_fd) != 0 || sz < 0) { dd_delete(dd); error_msg_and_die("Error saving '%s'", path); } close(src_fd_binary); } strcpy(path + path_len, "/"FILENAME_COREDUMP); int abrt_core_fd = create_or_die(path); /* We write both coredumps at once. * We can't write user coredump first, since it might be truncated * and thus can't be copied and used as abrt coredump; * and if we write abrt coredump first and then copy it as user one, * then we have a race when process exits but coredump does not exist yet: * $ echo -e '#include<signal.h>\nmain(){raise(SIGSEGV);}' | gcc -o test -x c - * $ rm -f core*; ulimit -c unlimited; ./test; ls -l core* * 21631 Segmentation fault (core dumped) ./test * ls: cannot access core*: No such file or directory <=== BAD */ off_t core_size = copyfd_sparse(STDIN_FILENO, abrt_core_fd, user_core_fd, ulimit_c); if (fsync(abrt_core_fd) != 0 || close(abrt_core_fd) != 0 || core_size < 0) { unlink(path); dd_delete(dd); if (user_core_fd >= 0) { xchdir(user_pwd); unlink(core_basename); } /* copyfd_sparse logs the error including errno string, * but it does not log file name */ error_msg_and_die("Error writing '%s'", path); } if (user_core_fd >= 0 /* error writing user coredump? */ && (fsync(user_core_fd) != 0 || close(user_core_fd) != 0 /* user coredump is too big? */ || (ulimit_c == 0 /* paranoia */ || core_size > ulimit_c) ) ) { /* nuke it (silently) */ xchdir(user_pwd); unlink(core_basename); } /* Because of #1211835 and #1126850 */ #if 0 /* Save JVM crash log if it exists. (JVM's coredump per se * is nearly useless for JVM developers) */ { char *java_log = xasprintf("/tmp/jvm-%lu/hs_error.log", (long)pid); int src_fd = open(java_log, O_RDONLY); free(java_log); /* If we couldn't open the error log in /tmp directory we can try to * read the log from the current directory. It may produce AVC, it * may produce some error log but all these are expected. */ if (src_fd < 0) { java_log = xasprintf("%s/hs_err_pid%lu.log", user_pwd, (long)pid); src_fd = open(java_log, O_RDONLY); free(java_log); } if (src_fd >= 0) { strcpy(path + path_len, "/hs_err.log"); int dst_fd = create_or_die(path); off_t sz = copyfd_eof(src_fd, dst_fd, COPYFD_SPARSE); if (close(dst_fd) != 0 || sz < 0) { dd_delete(dd); error_msg_and_die("Error saving '%s'", path); } close(src_fd); } } #endif /* We close dumpdir before we start catering for crash storm case. * Otherwise, delete_dump_dir's from other concurrent * CCpp's won't be able to delete our dump (their delete_dump_dir * will wait for us), and we won't be able to delete their dumps. * Classic deadlock. */ dd_close(dd); path[path_len] = '\0'; /* path now contains only directory name */ char *newpath = xstrndup(path, path_len - (sizeof(".new")-1)); if (rename(path, newpath) == 0) strcpy(path, newpath); free(newpath); log("Saved core dump of pid %lu (%s) to %s (%llu bytes)", (long)pid, executable, path, (long long)core_size); notify_new_path(path); /* rhbz#539551: "abrt going crazy when crashing process is respawned" */ if (g_settings_nMaxCrashReportsSize > 0) { /* x1.25 and round up to 64m: go a bit up, so that usual in-daemon trimming * kicks in first, and we don't "fight" with it: */ unsigned maxsize = g_settings_nMaxCrashReportsSize + g_settings_nMaxCrashReportsSize / 4; maxsize |= 63; trim_problem_dirs(g_settings_dump_location, maxsize * (double)(1024*1024), path); } free(rootdir); return 0; } /* We didn't create abrt dump, but may need to create compat coredump */ create_user_core: if (user_core_fd >= 0) { off_t core_size = copyfd_size(STDIN_FILENO, user_core_fd, ulimit_c, COPYFD_SPARSE); if (fsync(user_core_fd) != 0 || close(user_core_fd) != 0 || core_size < 0) { /* perror first, otherwise unlink may trash errno */ perror_msg("Error writing '%s'", full_core_basename); xchdir(user_pwd); unlink(core_basename); return 1; } if (ulimit_c == 0 || core_size > ulimit_c) { xchdir(user_pwd); unlink(core_basename); return 1; } log("Saved core dump of pid %lu to %s (%llu bytes)", (long)pid, full_core_basename, (long long)core_size); } return 0; }
./CrossVul/dataset_final_sorted/CWE-59/c/bad_1591_0
crossvul-cpp_data_good_3273_0
/** \ingroup payload * \file lib/fsm.c * File state machine to handle a payload from a package. */ #include "system.h" #include <utime.h> #include <errno.h> #if WITH_CAP #include <sys/capability.h> #endif #include <rpm/rpmte.h> #include <rpm/rpmts.h> #include <rpm/rpmlog.h> #include "rpmio/rpmio_internal.h" /* fdInit/FiniDigest */ #include "lib/fsm.h" #include "lib/rpmte_internal.h" /* XXX rpmfs */ #include "lib/rpmplugins.h" /* rpm plugins hooks */ #include "lib/rpmug.h" #include "debug.h" #define _FSM_DEBUG 0 int _fsm_debug = _FSM_DEBUG; /* XXX Failure to remove is not (yet) cause for failure. */ static int strict_erasures = 0; #define SUFFIX_RPMORIG ".rpmorig" #define SUFFIX_RPMSAVE ".rpmsave" #define SUFFIX_RPMNEW ".rpmnew" /* Default directory and file permissions if not mapped */ #define _dirPerms 0755 #define _filePerms 0644 /* * XXX Forward declarations for previously exported functions to avoid moving * things around needlessly */ static const char * fileActionString(rpmFileAction a); /** \ingroup payload * Build path to file from file info, optionally ornamented with suffix. * @param fi file info iterator * @param suffix suffix to use (NULL disables) * @retval path to file (malloced) */ static char * fsmFsPath(rpmfi fi, const char * suffix) { return rstrscat(NULL, rpmfiDN(fi), rpmfiBN(fi), suffix ? suffix : "", NULL); } /** \ingroup payload * Directory name iterator. */ typedef struct dnli_s { rpmfiles fi; char * active; int reverse; int isave; int i; } * DNLI_t; /** \ingroup payload * Destroy directory name iterator. * @param dnli directory name iterator * @retval NULL always */ static DNLI_t dnlFreeIterator(DNLI_t dnli) { if (dnli) { if (dnli->active) free(dnli->active); free(dnli); } return NULL; } /** \ingroup payload * Create directory name iterator. * @param fi file info set * @param fs file state set * @param reverse traverse directory names in reverse order? * @return directory name iterator */ static DNLI_t dnlInitIterator(rpmfiles fi, rpmfs fs, int reverse) { DNLI_t dnli; int i, j; int dc; if (fi == NULL) return NULL; dc = rpmfilesDC(fi); dnli = xcalloc(1, sizeof(*dnli)); dnli->fi = fi; dnli->reverse = reverse; dnli->i = (reverse ? dc : 0); if (dc) { dnli->active = xcalloc(dc, sizeof(*dnli->active)); int fc = rpmfilesFC(fi); /* Identify parent directories not skipped. */ for (i = 0; i < fc; i++) if (!XFA_SKIPPING(rpmfsGetAction(fs, i))) dnli->active[rpmfilesDI(fi, i)] = 1; /* Exclude parent directories that are explicitly included. */ for (i = 0; i < fc; i++) { int dil; size_t dnlen, bnlen; if (!S_ISDIR(rpmfilesFMode(fi, i))) continue; dil = rpmfilesDI(fi, i); dnlen = strlen(rpmfilesDN(fi, dil)); bnlen = strlen(rpmfilesBN(fi, i)); for (j = 0; j < dc; j++) { const char * dnl; size_t jlen; if (!dnli->active[j] || j == dil) continue; dnl = rpmfilesDN(fi, j); jlen = strlen(dnl); if (jlen != (dnlen+bnlen+1)) continue; if (!rstreqn(dnl, rpmfilesDN(fi, dil), dnlen)) continue; if (!rstreqn(dnl+dnlen, rpmfilesBN(fi, i), bnlen)) continue; if (dnl[dnlen+bnlen] != '/' || dnl[dnlen+bnlen+1] != '\0') continue; /* This directory is included in the package. */ dnli->active[j] = 0; break; } } /* Print only once per package. */ if (!reverse) { j = 0; for (i = 0; i < dc; i++) { if (!dnli->active[i]) continue; if (j == 0) { j = 1; rpmlog(RPMLOG_DEBUG, "========== Directories not explicitly included in package:\n"); } rpmlog(RPMLOG_DEBUG, "%10d %s\n", i, rpmfilesDN(fi, i)); } if (j) rpmlog(RPMLOG_DEBUG, "==========\n"); } } return dnli; } /** \ingroup payload * Return next directory name (from file info). * @param dnli directory name iterator * @return next directory name */ static const char * dnlNextIterator(DNLI_t dnli) { const char * dn = NULL; if (dnli) { rpmfiles fi = dnli->fi; int dc = rpmfilesDC(fi); int i = -1; if (dnli->active) do { i = (!dnli->reverse ? dnli->i++ : --dnli->i); } while (i >= 0 && i < dc && !dnli->active[i]); if (i >= 0 && i < dc) dn = rpmfilesDN(fi, i); else i = -1; dnli->isave = i; } return dn; } static int fsmSetFCaps(const char *path, const char *captxt) { int rc = 0; #if WITH_CAP if (captxt && *captxt != '\0') { cap_t fcaps = cap_from_text(captxt); if (fcaps == NULL || cap_set_file(path, fcaps) != 0) { rc = RPMERR_SETCAP_FAILED; } cap_free(fcaps); } #endif return rc; } /* Check dest is the same, empty and regular file with writeonly permissions */ static int linkSane(FD_t wfd, const char *dest) { struct stat sb, lsb; return (fstat(Fileno(wfd), &sb) == 0 && sb.st_size == 0 && (sb.st_mode & ~S_IFMT) == S_IWUSR && lstat(dest, &lsb) == 0 && S_ISREG(lsb.st_mode) && sb.st_dev == lsb.st_dev && sb.st_ino == lsb.st_ino); } /** \ingroup payload * Create file from payload stream. * @return 0 on success */ static int expandRegular(rpmfi fi, const char *dest, rpmpsm psm, int exclusive, int nodigest, int nocontent) { FD_t wfd = NULL; int rc = 0; /* Create the file with 0200 permissions (write by owner). */ { mode_t old_umask = umask(0577); wfd = Fopen(dest, exclusive ? "wx.ufdio" : "a.ufdio"); umask(old_umask); /* If reopening, make sure the file is what we expect */ if (!exclusive && wfd != NULL && !linkSane(wfd, dest)) { rc = RPMERR_OPEN_FAILED; goto exit; } } if (Ferror(wfd)) { rc = RPMERR_OPEN_FAILED; goto exit; } if (!nocontent) rc = rpmfiArchiveReadToFilePsm(fi, wfd, nodigest, psm); exit: if (wfd) { int myerrno = errno; Fclose(wfd); errno = myerrno; } return rc; } static int fsmMkfile(rpmfi fi, const char *dest, rpmfiles files, rpmpsm psm, int nodigest, int *setmeta, int * firsthardlink) { int rc = 0; int numHardlinks = rpmfiFNlink(fi); if (numHardlinks > 1) { /* Create first hardlinked file empty */ if (*firsthardlink < 0) { *firsthardlink = rpmfiFX(fi); rc = expandRegular(fi, dest, psm, 1, nodigest, 1); } else { /* Create hard links for others */ char *fn = rpmfilesFN(files, *firsthardlink); rc = link(fn, dest); if (rc < 0) { rc = RPMERR_LINK_FAILED; } free(fn); } } /* Write normal files or fill the last hardlinked (already existing) file with content */ if (numHardlinks<=1) { if (!rc) rc = expandRegular(fi, dest, psm, 1, nodigest, 0); } else if (rpmfiArchiveHasContent(fi)) { if (!rc) rc = expandRegular(fi, dest, psm, 0, nodigest, 0); *firsthardlink = -1; } else { *setmeta = 0; } return rc; } static int fsmReadLink(const char *path, char *buf, size_t bufsize, size_t *linklen) { ssize_t llen = readlink(path, buf, bufsize - 1); int rc = RPMERR_READLINK_FAILED; if (_fsm_debug) { rpmlog(RPMLOG_DEBUG, " %8s (%s, buf, %d) %s\n", __func__, path, (int)(bufsize -1), (llen < 0 ? strerror(errno) : "")); } if (llen >= 0) { buf[llen] = '\0'; rc = 0; *linklen = llen; } return rc; } static int fsmStat(const char *path, int dolstat, struct stat *sb) { int rc; if (dolstat){ rc = lstat(path, sb); } else { rc = stat(path, sb); } if (_fsm_debug && rc && errno != ENOENT) rpmlog(RPMLOG_DEBUG, " %8s (%s, ost) %s\n", __func__, path, (rc < 0 ? strerror(errno) : "")); if (rc < 0) { rc = (errno == ENOENT ? RPMERR_ENOENT : RPMERR_LSTAT_FAILED); /* Ensure consistent struct content on failure */ memset(sb, 0, sizeof(*sb)); } return rc; } static int fsmRmdir(const char *path) { int rc = rmdir(path); if (_fsm_debug) rpmlog(RPMLOG_DEBUG, " %8s (%s) %s\n", __func__, path, (rc < 0 ? strerror(errno) : "")); if (rc < 0) switch (errno) { case ENOENT: rc = RPMERR_ENOENT; break; case ENOTEMPTY: rc = RPMERR_ENOTEMPTY; break; default: rc = RPMERR_RMDIR_FAILED; break; } return rc; } static int fsmMkdir(const char *path, mode_t mode) { int rc = mkdir(path, (mode & 07777)); if (_fsm_debug) rpmlog(RPMLOG_DEBUG, " %8s (%s, 0%04o) %s\n", __func__, path, (unsigned)(mode & 07777), (rc < 0 ? strerror(errno) : "")); if (rc < 0) rc = RPMERR_MKDIR_FAILED; return rc; } static int fsmMkfifo(const char *path, mode_t mode) { int rc = mkfifo(path, (mode & 07777)); if (_fsm_debug) { rpmlog(RPMLOG_DEBUG, " %8s (%s, 0%04o) %s\n", __func__, path, (unsigned)(mode & 07777), (rc < 0 ? strerror(errno) : "")); } if (rc < 0) rc = RPMERR_MKFIFO_FAILED; return rc; } static int fsmMknod(const char *path, mode_t mode, dev_t dev) { /* FIX: check S_IFIFO or dev != 0 */ int rc = mknod(path, (mode & ~07777), dev); if (_fsm_debug) { rpmlog(RPMLOG_DEBUG, " %8s (%s, 0%o, 0x%x) %s\n", __func__, path, (unsigned)(mode & ~07777), (unsigned)dev, (rc < 0 ? strerror(errno) : "")); } if (rc < 0) rc = RPMERR_MKNOD_FAILED; return rc; } /** * Create (if necessary) directories not explicitly included in package. * @param files file data * @param fs file states * @param plugins rpm plugins handle * @return 0 on success */ static int fsmMkdirs(rpmfiles files, rpmfs fs, rpmPlugins plugins) { DNLI_t dnli = dnlInitIterator(files, fs, 0); struct stat sb; const char *dpath; int dc = rpmfilesDC(files); int rc = 0; int i; int ldnlen = 0; int ldnalloc = 0; char * ldn = NULL; short * dnlx = NULL; dnlx = (dc ? xcalloc(dc, sizeof(*dnlx)) : NULL); if (dnlx != NULL) while ((dpath = dnlNextIterator(dnli)) != NULL) { size_t dnlen = strlen(dpath); char * te, dn[dnlen+1]; dc = dnli->isave; if (dc < 0) continue; dnlx[dc] = dnlen; if (dnlen <= 1) continue; if (dnlen <= ldnlen && rstreq(dpath, ldn)) continue; /* Copy as we need to modify the string */ (void) stpcpy(dn, dpath); /* Assume '/' directory exists, "mkdir -p" for others if non-existent */ for (i = 1, te = dn + 1; *te != '\0'; te++, i++) { if (*te != '/') continue; *te = '\0'; /* Already validated? */ if (i < ldnlen && (ldn[i] == '/' || ldn[i] == '\0') && rstreqn(dn, ldn, i)) { *te = '/'; /* Move pre-existing path marker forward. */ dnlx[dc] = (te - dn); continue; } /* Validate next component of path. */ rc = fsmStat(dn, 1, &sb); /* lstat */ *te = '/'; /* Directory already exists? */ if (rc == 0 && S_ISDIR(sb.st_mode)) { /* Move pre-existing path marker forward. */ dnlx[dc] = (te - dn); } else if (rc == RPMERR_ENOENT) { *te = '\0'; mode_t mode = S_IFDIR | (_dirPerms & 07777); rpmFsmOp op = (FA_CREATE|FAF_UNOWNED); /* Run fsm file pre hook for all plugins */ rc = rpmpluginsCallFsmFilePre(plugins, NULL, dn, mode, op); if (!rc) rc = fsmMkdir(dn, mode); if (!rc) { rc = rpmpluginsCallFsmFilePrepare(plugins, NULL, dn, dn, mode, op); } /* Run fsm file post hook for all plugins */ rpmpluginsCallFsmFilePost(plugins, NULL, dn, mode, op, rc); if (!rc) { rpmlog(RPMLOG_DEBUG, "%s directory created with perms %04o\n", dn, (unsigned)(mode & 07777)); } *te = '/'; } if (rc) break; } if (rc) break; /* Save last validated path. */ if (ldnalloc < (dnlen + 1)) { ldnalloc = dnlen + 100; ldn = xrealloc(ldn, ldnalloc); } if (ldn != NULL) { /* XXX can't happen */ strcpy(ldn, dn); ldnlen = dnlen; } } free(dnlx); free(ldn); dnlFreeIterator(dnli); return rc; } static void removeSBITS(const char *path) { struct stat stb; if (lstat(path, &stb) == 0 && S_ISREG(stb.st_mode)) { if ((stb.st_mode & 06000) != 0) { (void) chmod(path, stb.st_mode & 0777); } #if WITH_CAP if (stb.st_mode & (S_IXUSR|S_IXGRP|S_IXOTH)) { (void) cap_set_file(path, NULL); } #endif } } static void fsmDebug(const char *fpath, rpmFileAction action, const struct stat *st) { rpmlog(RPMLOG_DEBUG, "%-10s %06o%3d (%4d,%4d)%6d %s\n", fileActionString(action), (int)st->st_mode, (int)st->st_nlink, (int)st->st_uid, (int)st->st_gid, (int)st->st_size, (fpath ? fpath : "")); } static int fsmSymlink(const char *opath, const char *path) { int rc = symlink(opath, path); if (_fsm_debug) { rpmlog(RPMLOG_DEBUG, " %8s (%s, %s) %s\n", __func__, opath, path, (rc < 0 ? strerror(errno) : "")); } if (rc < 0) rc = RPMERR_SYMLINK_FAILED; return rc; } static int fsmUnlink(const char *path) { int rc = 0; removeSBITS(path); rc = unlink(path); if (_fsm_debug) rpmlog(RPMLOG_DEBUG, " %8s (%s) %s\n", __func__, path, (rc < 0 ? strerror(errno) : "")); if (rc < 0) rc = (errno == ENOENT ? RPMERR_ENOENT : RPMERR_UNLINK_FAILED); return rc; } static int fsmRename(const char *opath, const char *path) { removeSBITS(path); int rc = rename(opath, path); #if defined(ETXTBSY) && defined(__HPUX__) /* XXX HP-UX (and other os'es) don't permit rename to busy files. */ if (rc && errno == ETXTBSY) { char *rmpath = NULL; rstrscat(&rmpath, path, "-RPMDELETE", NULL); rc = rename(path, rmpath); if (!rc) rc = rename(opath, path); free(rmpath); } #endif if (_fsm_debug) rpmlog(RPMLOG_DEBUG, " %8s (%s, %s) %s\n", __func__, opath, path, (rc < 0 ? strerror(errno) : "")); if (rc < 0) rc = (errno == EISDIR ? RPMERR_EXIST_AS_DIR : RPMERR_RENAME_FAILED); return rc; } static int fsmRemove(const char *path, mode_t mode) { return S_ISDIR(mode) ? fsmRmdir(path) : fsmUnlink(path); } static int fsmChown(const char *path, mode_t mode, uid_t uid, gid_t gid) { int rc = S_ISLNK(mode) ? lchown(path, uid, gid) : chown(path, uid, gid); if (rc < 0) { struct stat st; if (lstat(path, &st) == 0 && st.st_uid == uid && st.st_gid == gid) rc = 0; } if (_fsm_debug) rpmlog(RPMLOG_DEBUG, " %8s (%s, %d, %d) %s\n", __func__, path, (int)uid, (int)gid, (rc < 0 ? strerror(errno) : "")); if (rc < 0) rc = RPMERR_CHOWN_FAILED; return rc; } static int fsmChmod(const char *path, mode_t mode) { int rc = chmod(path, (mode & 07777)); if (rc < 0) { struct stat st; if (lstat(path, &st) == 0 && (st.st_mode & 07777) == (mode & 07777)) rc = 0; } if (_fsm_debug) rpmlog(RPMLOG_DEBUG, " %8s (%s, 0%04o) %s\n", __func__, path, (unsigned)(mode & 07777), (rc < 0 ? strerror(errno) : "")); if (rc < 0) rc = RPMERR_CHMOD_FAILED; return rc; } static int fsmUtime(const char *path, mode_t mode, time_t mtime) { int rc = 0; struct timeval stamps[2] = { { .tv_sec = mtime, .tv_usec = 0 }, { .tv_sec = mtime, .tv_usec = 0 }, }; #if HAVE_LUTIMES rc = lutimes(path, stamps); #else if (!S_ISLNK(mode)) rc = utimes(path, stamps); #endif if (_fsm_debug) rpmlog(RPMLOG_DEBUG, " %8s (%s, 0x%x) %s\n", __func__, path, (unsigned)mtime, (rc < 0 ? strerror(errno) : "")); if (rc < 0) rc = RPMERR_UTIME_FAILED; /* ...but utime error is not critical for directories */ if (rc && S_ISDIR(mode)) rc = 0; return rc; } static int fsmVerify(const char *path, rpmfi fi) { int rc; int saveerrno = errno; struct stat dsb; mode_t mode = rpmfiFMode(fi); rc = fsmStat(path, 1, &dsb); if (rc) return rc; if (S_ISREG(mode)) { /* HP-UX (and other os'es) don't permit unlink on busy files. */ char *rmpath = rstrscat(NULL, path, "-RPMDELETE", NULL); rc = fsmRename(path, rmpath); /* XXX shouldn't we take unlink return code here? */ if (!rc) (void) fsmUnlink(rmpath); else rc = RPMERR_UNLINK_FAILED; free(rmpath); return (rc ? rc : RPMERR_ENOENT); /* XXX HACK */ } else if (S_ISDIR(mode)) { if (S_ISDIR(dsb.st_mode)) return 0; if (S_ISLNK(dsb.st_mode)) { rc = fsmStat(path, 0, &dsb); if (rc == RPMERR_ENOENT) rc = 0; if (rc) return rc; errno = saveerrno; if (S_ISDIR(dsb.st_mode)) return 0; } } else if (S_ISLNK(mode)) { if (S_ISLNK(dsb.st_mode)) { char buf[8 * BUFSIZ]; size_t len; rc = fsmReadLink(path, buf, 8 * BUFSIZ, &len); errno = saveerrno; if (rc) return rc; if (rstreq(rpmfiFLink(fi), buf)) return 0; } } else if (S_ISFIFO(mode)) { if (S_ISFIFO(dsb.st_mode)) return 0; } else if (S_ISCHR(mode) || S_ISBLK(mode)) { if ((S_ISCHR(dsb.st_mode) || S_ISBLK(dsb.st_mode)) && (dsb.st_rdev == rpmfiFRdev(fi))) return 0; } else if (S_ISSOCK(mode)) { if (S_ISSOCK(dsb.st_mode)) return 0; } /* XXX shouldn't do this with commit/undo. */ rc = fsmUnlink(path); if (rc == 0) rc = RPMERR_ENOENT; return (rc ? rc : RPMERR_ENOENT); /* XXX HACK */ } #define IS_DEV_LOG(_x) \ ((_x) != NULL && strlen(_x) >= (sizeof("/dev/log")-1) && \ rstreqn((_x), "/dev/log", sizeof("/dev/log")-1) && \ ((_x)[sizeof("/dev/log")-1] == '\0' || \ (_x)[sizeof("/dev/log")-1] == ';')) /* Rename pre-existing modified or unmanaged file. */ static int fsmBackup(rpmfi fi, rpmFileAction action) { int rc = 0; const char *suffix = NULL; if (!(rpmfiFFlags(fi) & RPMFILE_GHOST)) { switch (action) { case FA_SAVE: suffix = SUFFIX_RPMSAVE; break; case FA_BACKUP: suffix = SUFFIX_RPMORIG; break; default: break; } } if (suffix) { char * opath = fsmFsPath(fi, NULL); char * path = fsmFsPath(fi, suffix); rc = fsmRename(opath, path); if (!rc) { rpmlog(RPMLOG_WARNING, _("%s saved as %s\n"), opath, path); } free(path); free(opath); } return rc; } static int fsmSetmeta(const char *path, rpmfi fi, rpmPlugins plugins, rpmFileAction action, const struct stat * st, int nofcaps) { int rc = 0; const char *dest = rpmfiFN(fi); if (!rc && !getuid()) { rc = fsmChown(path, st->st_mode, st->st_uid, st->st_gid); } if (!rc && !S_ISLNK(st->st_mode)) { rc = fsmChmod(path, st->st_mode); } /* Set file capabilities (if enabled) */ if (!rc && !nofcaps && S_ISREG(st->st_mode) && !getuid()) { rc = fsmSetFCaps(path, rpmfiFCaps(fi)); } if (!rc) { rc = fsmUtime(path, st->st_mode, rpmfiFMtime(fi)); } if (!rc) { rc = rpmpluginsCallFsmFilePrepare(plugins, fi, path, dest, st->st_mode, action); } return rc; } static int fsmCommit(char **path, rpmfi fi, rpmFileAction action, const char *suffix) { int rc = 0; /* XXX Special case /dev/log, which shouldn't be packaged anyways */ if (!(S_ISSOCK(rpmfiFMode(fi)) && IS_DEV_LOG(*path))) { const char *nsuffix = (action == FA_ALTNAME) ? SUFFIX_RPMNEW : NULL; char *dest = *path; /* Construct final destination path (nsuffix is usually NULL) */ if (suffix) dest = fsmFsPath(fi, nsuffix); /* Rename temporary to final file name if needed. */ if (dest != *path) { rc = fsmRename(*path, dest); if (!rc && nsuffix) { char * opath = fsmFsPath(fi, NULL); rpmlog(RPMLOG_WARNING, _("%s created as %s\n"), opath, dest); free(opath); } free(*path); *path = dest; } } return rc; } /** * Return formatted string representation of file disposition. * @param a file disposition * @return formatted string */ static const char * fileActionString(rpmFileAction a) { switch (a) { case FA_UNKNOWN: return "unknown"; case FA_CREATE: return "create"; case FA_BACKUP: return "backup"; case FA_SAVE: return "save"; case FA_SKIP: return "skip"; case FA_ALTNAME: return "altname"; case FA_ERASE: return "erase"; case FA_SKIPNSTATE: return "skipnstate"; case FA_SKIPNETSHARED: return "skipnetshared"; case FA_SKIPCOLOR: return "skipcolor"; case FA_TOUCH: return "touch"; default: return "???"; } } /* Remember any non-regular file state for recording in the rpmdb */ static void setFileState(rpmfs fs, int i) { switch (rpmfsGetAction(fs, i)) { case FA_SKIPNSTATE: rpmfsSetState(fs, i, RPMFILE_STATE_NOTINSTALLED); break; case FA_SKIPNETSHARED: rpmfsSetState(fs, i, RPMFILE_STATE_NETSHARED); break; case FA_SKIPCOLOR: rpmfsSetState(fs, i, RPMFILE_STATE_WRONGCOLOR); break; case FA_TOUCH: rpmfsSetState(fs, i, RPMFILE_STATE_NORMAL); break; default: break; } } int rpmPackageFilesInstall(rpmts ts, rpmte te, rpmfiles files, rpmpsm psm, char ** failedFile) { FD_t payload = rpmtePayload(te); rpmfi fi = rpmfiNewArchiveReader(payload, files, RPMFI_ITER_READ_ARCHIVE); rpmfs fs = rpmteGetFileStates(te); rpmPlugins plugins = rpmtsPlugins(ts); struct stat sb; int saveerrno = errno; int rc = 0; int nodigest = (rpmtsFlags(ts) & RPMTRANS_FLAG_NOFILEDIGEST) ? 1 : 0; int nofcaps = (rpmtsFlags(ts) & RPMTRANS_FLAG_NOCAPS) ? 1 : 0; int firsthardlink = -1; int skip; rpmFileAction action; char *tid = NULL; const char *suffix; char *fpath = NULL; if (fi == NULL) { rc = RPMERR_BAD_MAGIC; goto exit; } /* transaction id used for temporary path suffix while installing */ rasprintf(&tid, ";%08x", (unsigned)rpmtsGetTid(ts)); /* Detect and create directories not explicitly in package. */ rc = fsmMkdirs(files, fs, plugins); while (!rc) { /* Read next payload header. */ rc = rpmfiNext(fi); if (rc < 0) { if (rc == RPMERR_ITER_END) rc = 0; break; } action = rpmfsGetAction(fs, rpmfiFX(fi)); skip = XFA_SKIPPING(action); suffix = S_ISDIR(rpmfiFMode(fi)) ? NULL : tid; if (action != FA_TOUCH) { fpath = fsmFsPath(fi, suffix); } else { fpath = fsmFsPath(fi, ""); } /* Remap file perms, owner, and group. */ rc = rpmfiStat(fi, 1, &sb); fsmDebug(fpath, action, &sb); /* Exit on error. */ if (rc) break; /* Run fsm file pre hook for all plugins */ rc = rpmpluginsCallFsmFilePre(plugins, fi, fpath, sb.st_mode, action); if (rc) { skip = 1; } else { setFileState(fs, rpmfiFX(fi)); } if (!skip) { int setmeta = 1; /* Directories replacing something need early backup */ if (!suffix) { rc = fsmBackup(fi, action); } /* Assume file does't exist when tmp suffix is in use */ if (!suffix) { rc = fsmVerify(fpath, fi); } else { rc = (action == FA_TOUCH) ? 0 : RPMERR_ENOENT; } if (S_ISREG(sb.st_mode)) { if (rc == RPMERR_ENOENT) { rc = fsmMkfile(fi, fpath, files, psm, nodigest, &setmeta, &firsthardlink); } } else if (S_ISDIR(sb.st_mode)) { if (rc == RPMERR_ENOENT) { mode_t mode = sb.st_mode; mode &= ~07777; mode |= 00700; rc = fsmMkdir(fpath, mode); } } else if (S_ISLNK(sb.st_mode)) { if (rc == RPMERR_ENOENT) { rc = fsmSymlink(rpmfiFLink(fi), fpath); } } else if (S_ISFIFO(sb.st_mode)) { /* This mimics cpio S_ISSOCK() behavior but probably isn't right */ if (rc == RPMERR_ENOENT) { rc = fsmMkfifo(fpath, 0000); } } else if (S_ISCHR(sb.st_mode) || S_ISBLK(sb.st_mode) || S_ISSOCK(sb.st_mode)) { if (rc == RPMERR_ENOENT) { rc = fsmMknod(fpath, sb.st_mode, sb.st_rdev); } } else { /* XXX Special case /dev/log, which shouldn't be packaged anyways */ if (!IS_DEV_LOG(fpath)) rc = RPMERR_UNKNOWN_FILETYPE; } /* Set permissions, timestamps etc for non-hardlink entries */ if (!rc && setmeta) { rc = fsmSetmeta(fpath, fi, plugins, action, &sb, nofcaps); } } else if (firsthardlink >= 0 && rpmfiArchiveHasContent(fi)) { /* we skip the hard linked file containing the content */ /* write the content to the first used instead */ char *fn = rpmfilesFN(files, firsthardlink); rc = expandRegular(fi, fn, psm, 0, nodigest, 0); firsthardlink = -1; free(fn); } if (rc) { if (!skip) { /* XXX only erase if temp fn w suffix is in use */ if (suffix && (action != FA_TOUCH)) { (void) fsmRemove(fpath, sb.st_mode); } errno = saveerrno; } } else { /* Notify on success. */ rpmpsmNotify(psm, RPMCALLBACK_INST_PROGRESS, rpmfiArchiveTell(fi)); if (!skip) { /* Backup file if needed. Directories are handled earlier */ if (suffix) rc = fsmBackup(fi, action); if (!rc) rc = fsmCommit(&fpath, fi, action, suffix); } } if (rc) *failedFile = xstrdup(fpath); /* Run fsm file post hook for all plugins */ rpmpluginsCallFsmFilePost(plugins, fi, fpath, sb.st_mode, action, rc); fpath = _free(fpath); } rpmswAdd(rpmtsOp(ts, RPMTS_OP_UNCOMPRESS), fdOp(payload, FDSTAT_READ)); rpmswAdd(rpmtsOp(ts, RPMTS_OP_DIGEST), fdOp(payload, FDSTAT_DIGEST)); exit: /* No need to bother with close errors on read */ rpmfiArchiveClose(fi); rpmfiFree(fi); Fclose(payload); free(tid); free(fpath); return rc; } int rpmPackageFilesRemove(rpmts ts, rpmte te, rpmfiles files, rpmpsm psm, char ** failedFile) { rpmfi fi = rpmfilesIter(files, RPMFI_ITER_BACK); rpmfs fs = rpmteGetFileStates(te); rpmPlugins plugins = rpmtsPlugins(ts); struct stat sb; int rc = 0; char *fpath = NULL; while (!rc && rpmfiNext(fi) >= 0) { rpmFileAction action = rpmfsGetAction(fs, rpmfiFX(fi)); fpath = fsmFsPath(fi, NULL); rc = fsmStat(fpath, 1, &sb); fsmDebug(fpath, action, &sb); /* Run fsm file pre hook for all plugins */ rc = rpmpluginsCallFsmFilePre(plugins, fi, fpath, sb.st_mode, action); if (!XFA_SKIPPING(action)) rc = fsmBackup(fi, action); /* Remove erased files. */ if (action == FA_ERASE) { int missingok = (rpmfiFFlags(fi) & (RPMFILE_MISSINGOK | RPMFILE_GHOST)); rc = fsmRemove(fpath, sb.st_mode); /* * Missing %ghost or %missingok entries are not errors. * XXX: Are non-existent files ever an actual error here? Afterall * that's exactly what we're trying to accomplish here, * and complaining about job already done seems like kinderkarten * level "But it was MY turn!" whining... */ if (rc == RPMERR_ENOENT && missingok) { rc = 0; } /* * Dont whine on non-empty directories for now. We might be able * to track at least some of the expected failures though, * such as when we knowingly left config file backups etc behind. */ if (rc == RPMERR_ENOTEMPTY) { rc = 0; } if (rc) { int lvl = strict_erasures ? RPMLOG_ERR : RPMLOG_WARNING; rpmlog(lvl, _("%s %s: remove failed: %s\n"), S_ISDIR(sb.st_mode) ? _("directory") : _("file"), fpath, strerror(errno)); } } /* Run fsm file post hook for all plugins */ rpmpluginsCallFsmFilePost(plugins, fi, fpath, sb.st_mode, action, rc); /* XXX Failure to remove is not (yet) cause for failure. */ if (!strict_erasures) rc = 0; if (rc) *failedFile = xstrdup(fpath); if (rc == 0) { /* Notify on success. */ /* On erase we're iterating backwards, fixup for progress */ rpm_loff_t amount = rpmfiFC(fi) - rpmfiFX(fi); rpmpsmNotify(psm, RPMCALLBACK_UNINST_PROGRESS, amount); } fpath = _free(fpath); } free(fpath); rpmfiFree(fi); return rc; }
./CrossVul/dataset_final_sorted/CWE-59/c/good_3273_0
crossvul-cpp_data_bad_436_9
/* * Soft: Keepalived is a failover program for the LVS project * <www.linuxvirtualserver.org>. It monitor & manipulate * a loadbalanced server pool using multi-layer checks. * * Part: Memory management framework. This framework is used to * find any memory leak. * * Authors: Alexandre Cassen, <acassen@linux-vs.org> * Jan Holmberg, <jan@artech.net> * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. * * Copyright (C) 2001-2017 Alexandre Cassen, <acassen@gmail.com> */ #include "config.h" #ifdef _MEM_CHECK_ #include <assert.h> #include <unistd.h> #include <fcntl.h> #include <stdlib.h> #include <time.h> #include <limits.h> #endif #include <errno.h> #include <string.h> #include "memory.h" #include "utils.h" #include "bitops.h" #include "logger.h" #ifdef _MEM_CHECK_ #include "timer.h" #include "rbtree.h" #include "list_head.h" /* Global var */ size_t mem_allocated; /* Total memory used in Bytes */ static size_t max_mem_allocated; /* Maximum memory used in Bytes */ static const char *terminate_banner; /* banner string for report file */ static bool skip_mem_check_final; #endif static void * xalloc(unsigned long size) { void *mem = malloc(size); if (mem == NULL) { if (__test_bit(DONT_FORK_BIT, &debug)) perror("Keepalived"); else log_message(LOG_INFO, "Keepalived xalloc() error - %s", strerror(errno)); exit(EXIT_FAILURE); } #ifdef _MEM_CHECK_ mem_allocated += size - sizeof(long); if (mem_allocated > max_mem_allocated) max_mem_allocated = mem_allocated; #endif return mem; } void * zalloc(unsigned long size) { void *mem = xalloc(size); if (mem) memset(mem, 0, size); return mem; } /* KeepAlived memory management. in debug mode, * help finding eventual memory leak. * Allocation memory types manipulated are : * * +-type------------------+-meaning------------------+ * ! FREE_SLOT ! Free slot ! * ! OVERRUN ! Overrun ! * ! FREE_NULL ! free null ! * ! REALLOC_NULL ! realloc null ! * ! DOUBLE_FREE ! double free ! * ! REALLOC_DOUBLE_FREE ! realloc freed block ! * ! FREE_NOT_ALLOC ! Not previously allocated ! * ! REALLOC_NOT_ALLOC ! Not previously allocated ! * ! MALLOC_ZERO_SIZE ! malloc with size 0 ! * ! REALLOC_ZERO_SIZE ! realloc with size 0 ! * ! LAST_FREE ! Last free list ! * ! ALLOCATED ! Allocated ! * +-----------------------+--------------------------+ * * global variable debug bit MEM_ERR_DETECT_BIT used to * flag some memory error. * */ #ifdef _MEM_CHECK_ enum slot_type { FREE_SLOT = 0, OVERRUN, FREE_NULL, REALLOC_NULL, DOUBLE_FREE, REALLOC_DOUBLE_FREE, FREE_NOT_ALLOC, REALLOC_NOT_ALLOC, MALLOC_ZERO_SIZE, REALLOC_ZERO_SIZE, LAST_FREE, ALLOCATED, } ; #define TIME_STR_LEN 9 #if ULONG_MAX == 0xffffffffffffffffUL #define CHECK_VAL 0xa5a55a5aa5a55a5aUL #elif ULONG_MAX == 0xffffffffUL #define CHECK_VAL 0xa5a55a5aUL #else #define CHECK_VAL 0xa5a5 #endif #define FREE_LIST_SIZE 256 typedef struct { enum slot_type type; int line; const char *func; const char *file; void *ptr; size_t size; union { list_head_t l; /* When on free list */ rb_node_t t; }; unsigned seq_num; } MEMCHECK; /* Last free pointers */ static LH_LIST_HEAD(free_list); static unsigned free_list_size; /* alloc_list entries used for 1000 VRRP instance each with VMAC interfaces is 33589 */ static rb_root_t alloc_list = RB_ROOT; static LH_LIST_HEAD(bad_list); static unsigned number_alloc_list; /* number of alloc_list allocation entries */ static unsigned max_alloc_list; static unsigned num_mallocs; static unsigned num_reallocs; static unsigned seq_num; static FILE *log_op = NULL; static inline int memcheck_ptr_cmp(MEMCHECK *m1, MEMCHECK *m2) { return m1->ptr - m2->ptr; } static inline int memcheck_seq_cmp(MEMCHECK *m1, MEMCHECK *m2) { return m1->seq_num - m2->seq_num; } static const char * format_time(void) { static char time_buf[TIME_STR_LEN+1]; strftime(time_buf, sizeof time_buf, "%T ", localtime(&time_now.tv_sec)); return time_buf; } void memcheck_log(const char *called_func, const char *param, const char *file, const char *function, int line) { int len = strlen(called_func) + (param ? strlen(param) : 0); if ((len = 36 - len) < 0) len = 0; fprintf(log_op, "%s%*s%s(%s) at %s, %d, %s\n", format_time(), len, "", called_func, param ? param : "", file, line, function); } static MEMCHECK * get_free_alloc_entry(void) { MEMCHECK *entry; /* If number on free list < 256, allocate new entry, otherwise take head */ if (free_list_size < 256) entry = malloc(sizeof *entry); else { entry = list_first_entry(&free_list, MEMCHECK, l); list_head_del(&entry->l); free_list_size--; } entry->seq_num = seq_num++; return entry; } void * keepalived_malloc(size_t size, const char *file, const char *function, int line) { void *buf; MEMCHECK *entry, *entry2; buf = zalloc(size + sizeof (unsigned long)); *(unsigned long *) ((char *) buf + size) = size + CHECK_VAL; entry = get_free_alloc_entry(); entry->ptr = buf; entry->size = size; entry->file = file; entry->func = function; entry->line = line; entry->type = ALLOCATED; rb_insert_sort(&alloc_list, entry, t, memcheck_ptr_cmp); if (++number_alloc_list > max_alloc_list) max_alloc_list = number_alloc_list; fprintf(log_op, "%szalloc [%3d:%3d], %9p, %4zu at %s, %3d, %s%s\n", format_time(), entry->seq_num, number_alloc_list, buf, size, file, line, function, !size ? " - size is 0" : ""); #ifdef _MEM_CHECK_LOG_ if (__test_bit(MEM_CHECK_LOG_BIT, &debug)) log_message(LOG_INFO, "zalloc[%3d:%3d], %9p, %4zu at %s, %3d, %s", entry->seq_num, number_alloc_list, buf, size, file, line, function); #endif num_mallocs++; if (!size) { /* Record malloc with 0 size */ entry2 = get_free_alloc_entry(); *entry2 = *entry; entry2->type = MALLOC_ZERO_SIZE; list_add_tail(&entry2->l, &bad_list); } return buf; } static void * keepalived_free_realloc_common(void *buffer, size_t size, const char *file, const char *function, int line, bool is_realloc) { unsigned long check; MEMCHECK *entry, *entry2, *le; MEMCHECK search = {.ptr = buffer}; /* If nullpointer remember */ if (buffer == NULL) { entry = get_free_alloc_entry(); entry->ptr = NULL; entry->size = size; entry->file = file; entry->func = function; entry->line = line; entry->type = !size ? FREE_NULL : REALLOC_NULL; if (!is_realloc) fprintf(log_op, "%s%-7s%9s, %9s, %4s at %s, %3d, %s\n", format_time(), "free", "ERROR", "NULL", "", file, line, function); else fprintf(log_op, "%s%-7s%9s, %9s, %4zu at %s, %3d, %s%s\n", format_time(), "realloc", "ERROR", "NULL", size, file, line, function, size ? " *** converted to malloc" : ""); __set_bit(MEM_ERR_DETECT_BIT, &debug); list_add_tail(&entry->l, &bad_list); return !size ? NULL : keepalived_malloc(size, file, function, line); } entry = rb_search(&alloc_list, &search, t, memcheck_ptr_cmp); /* Not found */ if (!entry) { entry = get_free_alloc_entry(); entry->ptr = buffer; entry->size = size; entry->file = file; entry->func = function; entry->line = line; entry->type = !size ? FREE_NOT_ALLOC : REALLOC_NOT_ALLOC; entry->seq_num = seq_num++; if (!is_realloc) fprintf(log_op, "%s%-7s%9s, %9p, at %s, %3d, %s - not found\n", format_time(), "free", "ERROR", buffer, file, line, function); else fprintf(log_op, "%s%-7s%9s, %9p, %4zu at %s, %3d, %s - not found\n", format_time(), "realloc", "ERROR", buffer, size, file, line, function); __set_bit(MEM_ERR_DETECT_BIT, &debug); list_for_each_entry_reverse(le, &free_list, l) { if (le->ptr == buffer && le->type == LAST_FREE) { fprintf (log_op, "%11s-> pointer last released at [%3d:%3d], at %s, %3d, %s\n", "", le->seq_num, number_alloc_list, le->file, le->line, le->func); entry->type = !size ? DOUBLE_FREE : REALLOC_DOUBLE_FREE; break; } }; list_add_tail(&entry->l, &bad_list); return NULL; } check = entry->size + CHECK_VAL; if (*(unsigned long *)((char *)buffer + entry->size) != check) { entry2 = get_free_alloc_entry(); *entry2 = *entry; entry2->type = OVERRUN; list_add_tail(&entry2->l, &bad_list); fprintf(log_op, "%s%s corrupt, buffer overrun [%3d:%3d], %9p, %4zu at %s, %3d, %s\n", format_time(), !is_realloc ? "free" : "realloc", entry->seq_num, number_alloc_list, buffer, entry->size, file, line, function); dump_buffer(entry->ptr, entry->size + sizeof (check), log_op, TIME_STR_LEN); fprintf(log_op, "%*sCheck_sum\n", TIME_STR_LEN, ""); dump_buffer((char *) &check, sizeof(check), log_op, TIME_STR_LEN); __set_bit(MEM_ERR_DETECT_BIT, &debug); } mem_allocated -= entry->size; if (!size) { free(buffer); if (is_realloc) { fprintf(log_op, "%s%-7s[%3d:%3d], %9p, %4zu at %s, %3d, %s -> %9s, %4s at %s, %3d, %s\n", format_time(), "realloc", entry->seq_num, number_alloc_list, entry->ptr, entry->size, entry->file, entry->line, entry->func, "made free", "", file, line, function); /* Record bad realloc */ entry2 = get_free_alloc_entry(); *entry2 = *entry; entry2->type = REALLOC_ZERO_SIZE; entry2->file = file; entry2->line = line; entry2->func = function; list_add_tail(&entry2->l, &bad_list); } else fprintf(log_op, "%s%-7s[%3d:%3d], %9p, %4zu at %s, %3d, %s -> %9s, %4s at %s, %3d, %s\n", format_time(), "free", entry->seq_num, number_alloc_list, entry->ptr, entry->size, entry->file, entry->line, entry->func, "NULL", "", file, line, function); #ifdef _MEM_CHECK_LOG_ if (__test_bit(MEM_CHECK_LOG_BIT, &debug)) log_message(LOG_INFO, "%-7s[%3d:%3d], %9p, %4zu at %s, %3d, %s", is_realloc ? "realloc" : "free", entry->seq_num, number_alloc_list, buffer, entry->size, file, line, function); #endif entry->file = file; entry->line = line; entry->func = function; entry->type = LAST_FREE; rb_erase(&entry->t, &alloc_list); list_add_tail(&entry->l, &free_list); free_list_size++; number_alloc_list--; return NULL; } buffer = realloc(buffer, size + sizeof (unsigned long)); mem_allocated += size; if (mem_allocated > max_mem_allocated) max_mem_allocated = mem_allocated; fprintf(log_op, "%srealloc[%3d:%3d], %9p, %4zu at %s, %3d, %s -> %9p, %4zu at %s, %3d, %s\n", format_time(), entry->seq_num, number_alloc_list, entry->ptr, entry->size, entry->file, entry->line, entry->func, buffer, size, file, line, function); #ifdef _MEM_CHECK_LOG_ if (__test_bit(MEM_CHECK_LOG_BIT, &debug)) log_message(LOG_INFO, "realloc[%3d:%3d], %9p, %4zu at %s, %3d, %s -> %9p, %4zu at %s, %3d, %s", entry->seq_num, number_alloc_list, entry->ptr, entry->size, entry->file, entry->line, entry->func, buffer, size, file, line, function); #endif *(unsigned long *) ((char *) buffer + size) = size + CHECK_VAL; if (entry->ptr != buffer) { rb_erase(&entry->t, &alloc_list); entry->ptr = buffer; rb_insert_sort(&alloc_list, entry, t, memcheck_ptr_cmp); } else entry->ptr = buffer; entry->size = size; entry->file = file; entry->line = line; entry->func = function; num_reallocs++; return buffer; } void keepalived_free(void *buffer, const char *file, const char *function, int line) { keepalived_free_realloc_common(buffer, 0, file, function, line, false); } void * keepalived_realloc(void *buffer, size_t size, const char *file, const char *function, int line) { return keepalived_free_realloc_common(buffer, size, file, function, line, true); } static void keepalived_alloc_log(bool final) { unsigned int overrun = 0, badptr = 0, zero_size = 0; size_t sum = 0; MEMCHECK *entry; if (final) { /* If this is a forked child, we don't want the dump */ if (skip_mem_check_final) return; fprintf(log_op, "\n---[ Keepalived memory dump for (%s) ]---\n\n", terminate_banner); } else fprintf(log_op, "\n---[ Keepalived memory dump for (%s) at %s ]---\n\n", terminate_banner, format_time()); /* List the blocks currently allocated */ if (!RB_EMPTY_ROOT(&alloc_list)) { fprintf(log_op, "Entries %s\n\n", final ? "not released" : "currently allocated"); rb_for_each_entry(entry, &alloc_list, t) { sum += entry->size; fprintf(log_op, "%9p [%3d:%3d], %4zu at %s, %3d, %s", entry->ptr, entry->seq_num, number_alloc_list, entry->size, entry->file, entry->line, entry->func); if (entry->type != ALLOCATED) fprintf(log_op, " type = %d", entry->type); fprintf(log_op, "\n"); } } if (!list_empty(&bad_list)) { if (!RB_EMPTY_ROOT(&alloc_list)) fprintf(log_op, "\n"); fprintf(log_op, "Bad entry list\n\n"); list_for_each_entry(entry, &bad_list, l) { switch (entry->type) { case FREE_NULL: badptr++; fprintf(log_op, "%9s %9s, %4s at %s, %3d, %s - null pointer to free\n", "NULL", "", "", entry->file, entry->line, entry->func); break; case REALLOC_NULL: badptr++; fprintf(log_op, "%9s %9s, %4zu at %s, %3d, %s - null pointer to realloc (converted to malloc)\n", "NULL", "", entry->size, entry->file, entry->line, entry->func); break; case FREE_NOT_ALLOC: badptr++; fprintf(log_op, "%9p %9s, %4s at %s, %3d, %s - pointer not found for free\n", entry->ptr, "", "", entry->file, entry->line, entry->func); break; case REALLOC_NOT_ALLOC: badptr++; fprintf(log_op, "%9p %9s, %4zu at %s, %3d, %s - pointer not found for realloc\n", entry->ptr, "", entry->size, entry->file, entry->line, entry->func); break; case DOUBLE_FREE: badptr++; fprintf(log_op, "%9p %9s, %4s at %s, %3d, %s - double free of pointer\n", entry->ptr, "", "", entry->file, entry->line, entry->func); break; case REALLOC_DOUBLE_FREE: badptr++; fprintf(log_op, "%9p %9s, %4zu at %s, %3d, %s - realloc 0 size already freed\n", entry->ptr, "", entry->size, entry->file, entry->line, entry->func); break; case OVERRUN: overrun++; fprintf(log_op, "%9p [%3d:%3d], %4zu at %s, %3d, %s - buffer overrun\n", entry->ptr, entry->seq_num, number_alloc_list, entry->size, entry->file, entry->line, entry->func); break; case MALLOC_ZERO_SIZE: zero_size++; fprintf(log_op, "%9p [%3d:%3d], %4zu at %s, %3d, %s - malloc zero size\n", entry->ptr, entry->seq_num, number_alloc_list, entry->size, entry->file, entry->line, entry->func); break; case REALLOC_ZERO_SIZE: zero_size++; fprintf(log_op, "%9p [%3d:%3d], %4zu at %s, %3d, %s - realloc zero size (handled as free)\n", entry->ptr, entry->seq_num, number_alloc_list, entry->size, entry->file, entry->line, entry->func); break; case ALLOCATED: /* not used - avoid compiler warning */ case FREE_SLOT: case LAST_FREE: break; } } } fprintf(log_op, "\n\n---[ Keepalived memory dump summary for (%s) ]---\n", terminate_banner); fprintf(log_op, "Total number of bytes %s...: %zu\n", final ? "not freed" : "allocated", sum); fprintf(log_op, "Number of entries %s.......: %d\n", final ? "not freed" : "allocated", number_alloc_list); fprintf(log_op, "Maximum allocated entries.........: %d\n", max_alloc_list); fprintf(log_op, "Maximum memory allocated..........: %zu\n", max_mem_allocated); fprintf(log_op, "Number of mallocs.................: %d\n", num_mallocs); fprintf(log_op, "Number of reallocs................: %d\n", num_reallocs); fprintf(log_op, "Number of bad entries.............: %d\n", badptr); fprintf(log_op, "Number of buffer overrun..........: %d\n", overrun); fprintf(log_op, "Number of 0 size allocations......: %d\n\n", zero_size); if (sum != mem_allocated) fprintf(log_op, "ERROR - sum of allocated %zu != mem_allocated %zu\n", sum, mem_allocated); if (final) { if (sum || number_alloc_list || badptr || overrun) fprintf(log_op, "=> Program seems to have some memory problem !!!\n\n"); else fprintf(log_op, "=> Program seems to be memory allocation safe...\n\n"); } } static void keepalived_free_final(void) { keepalived_alloc_log(true); } void keepalived_alloc_dump(void) { keepalived_alloc_log(false); } void mem_log_init(const char* prog_name, const char *banner) { size_t log_name_len; char *log_name; if (__test_bit(LOG_CONSOLE_BIT, &debug)) { log_op = stderr; return; } if (log_op) fclose(log_op); log_name_len = 5 + strlen(prog_name) + 5 + 7 + 4 + 1; /* "/tmp/" + prog_name + "_mem." + PID + ".log" + '\0" */ log_name = malloc(log_name_len); if (!log_name) { log_message(LOG_INFO, "Unable to malloc log file name"); log_op = stderr; return; } snprintf(log_name, log_name_len, "/tmp/%s_mem.%d.log", prog_name, getpid()); log_op = fopen(log_name, "a"); if (log_op == NULL) { log_message(LOG_INFO, "Unable to open %s for appending", log_name); log_op = stderr; } else { int fd = fileno(log_op); /* We don't want any children to inherit the log file */ fcntl(fd, F_SETFD, fcntl(fd, F_GETFD) | FD_CLOEXEC); /* Make the log output line buffered. This was to ensure that * children didn't inherit the buffer, but the CLOEXEC above * should resolve that. */ setlinebuf(log_op); fprintf(log_op, "\n"); } free(log_name); terminate_banner = banner; } void skip_mem_dump(void) { skip_mem_check_final = true; } void enable_mem_log_termination(void) { atexit(keepalived_free_final); } #endif
./CrossVul/dataset_final_sorted/CWE-59/c/bad_436_9
crossvul-cpp_data_bad_4226_4
/* * parse.c * */ /* Portions of this file are subject to the following copyrights. See * the Net-SNMP's COPYING file for more details and other copyrights * that may apply: */ /****************************************************************** Copyright 1989, 1991, 1992 by Carnegie Mellon University All Rights Reserved Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation, and that the name of CMU not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. CMU DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL CMU BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ******************************************************************/ /* * Copyright � 2003 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms specified in the COPYING file * distributed with the Net-SNMP package. */ #include <net-snmp/net-snmp-config.h> #include <net-snmp/net-snmp-features.h> #ifndef NETSNMP_DISABLE_MIB_LOADING #if HAVE_LIMITS_H #include <limits.h> #endif #include <stdio.h> #if HAVE_STDLIB_H #include <stdlib.h> #endif #if HAVE_STRING_H #include <string.h> #else #include <strings.h> #endif #include <ctype.h> #include <sys/types.h> #if HAVE_SYS_STAT_H #include <sys/stat.h> #endif /* * Wow. This is ugly. -- Wes */ #if HAVE_DIRENT_H # include <dirent.h> # define NAMLEN(dirent) strlen((dirent)->d_name) #else # define dirent direct # define NAMLEN(dirent) (dirent)->d_namlen # if HAVE_SYS_NDIR_H # include <sys/ndir.h> # endif # if HAVE_SYS_DIR_H # include <sys/dir.h> # endif # if HAVE_NDIR_H # include <ndir.h> # endif #endif #if TIME_WITH_SYS_TIME # include <sys/time.h> # include <time.h> #else # if HAVE_SYS_TIME_H # include <sys/time.h> # else # include <time.h> # endif #endif #if HAVE_NETINET_IN_H #include <netinet/in.h> #endif #if defined(HAVE_REGEX_H) && defined(HAVE_REGCOMP) #include <regex.h> #endif #if HAVE_UNISTD_H #include <unistd.h> #endif #if HAVE_DMALLOC_H #include <dmalloc.h> #endif #include <errno.h> #include <net-snmp/types.h> #include <net-snmp/output_api.h> #include <net-snmp/config_api.h> #include <net-snmp/utilities.h> #include <net-snmp/library/parse.h> #include <net-snmp/library/mib.h> #include <net-snmp/library/snmp_api.h> #include <net-snmp/library/tools.h> netsnmp_feature_child_of(find_module, mib_api) netsnmp_feature_child_of(get_tc_description, mib_api) /* * A linked list of nodes. */ struct node { struct node *next; char *label; /* This node's (unique) textual name */ u_long subid; /* This node's integer subidentifier */ int modid; /* The module containing this node */ char *parent; /* The parent's textual name */ int tc_index; /* index into tclist (-1 if NA) */ int type; /* The type of object this represents */ int access; int status; struct enum_list *enums; /* (optional) list of enumerated integers */ struct range_list *ranges; struct index_list *indexes; char *augments; struct varbind_list *varbinds; char *hint; char *units; char *description; /* description (a quoted string) */ char *reference; /* references (a quoted string) */ char *defaultValue; char *filename; int lineno; }; /* * This is one element of an object identifier with either an integer * subidentifier, or a textual string label, or both. * The subid is -1 if not present, and label is NULL if not present. */ struct subid_s { int subid; int modid; char *label; }; #define MAXTC 16384 struct tc { /* textual conventions */ int type; int modid; char *descriptor; char *hint; struct enum_list *enums; struct range_list *ranges; char *description; } tclist[MAXTC]; int mibLine = 0; const char *File = "(none)"; static int anonymous = 0; struct objgroup { char *name; int line; struct objgroup *next; } *objgroups = NULL, *objects = NULL, *notifs = NULL; #define SYNTAX_MASK 0x80 /* * types of tokens * Tokens wiht the SYNTAX_MASK bit set are syntax tokens */ #define CONTINUE -1 #define ENDOFFILE 0 #define LABEL 1 #define SUBTREE 2 #define SYNTAX 3 #define OBJID (4 | SYNTAX_MASK) #define OCTETSTR (5 | SYNTAX_MASK) #define INTEGER (6 | SYNTAX_MASK) #define NETADDR (7 | SYNTAX_MASK) #define IPADDR (8 | SYNTAX_MASK) #define COUNTER (9 | SYNTAX_MASK) #define GAUGE (10 | SYNTAX_MASK) #define TIMETICKS (11 | SYNTAX_MASK) #define KW_OPAQUE (12 | SYNTAX_MASK) #define NUL (13 | SYNTAX_MASK) #define SEQUENCE 14 #define OF 15 /* SEQUENCE OF */ #define OBJTYPE 16 #define ACCESS 17 #define READONLY 18 #define READWRITE 19 #define WRITEONLY 20 #ifdef NOACCESS #undef NOACCESS /* agent 'NOACCESS' token */ #endif #define NOACCESS 21 #define STATUS 22 #define MANDATORY 23 #define KW_OPTIONAL 24 #define OBSOLETE 25 /* * #define RECOMMENDED 26 */ #define PUNCT 27 #define EQUALS 28 #define NUMBER 29 #define LEFTBRACKET 30 #define RIGHTBRACKET 31 #define LEFTPAREN 32 #define RIGHTPAREN 33 #define COMMA 34 #define DESCRIPTION 35 #define QUOTESTRING 36 #define INDEX 37 #define DEFVAL 38 #define DEPRECATED 39 #define SIZE 40 #define BITSTRING (41 | SYNTAX_MASK) #define NSAPADDRESS (42 | SYNTAX_MASK) #define COUNTER64 (43 | SYNTAX_MASK) #define OBJGROUP 44 #define NOTIFTYPE 45 #define AUGMENTS 46 #define COMPLIANCE 47 #define READCREATE 48 #define UNITS 49 #define REFERENCE 50 #define NUM_ENTRIES 51 #define MODULEIDENTITY 52 #define LASTUPDATED 53 #define ORGANIZATION 54 #define CONTACTINFO 55 #define UINTEGER32 (56 | SYNTAX_MASK) #define CURRENT 57 #define DEFINITIONS 58 #define END 59 #define SEMI 60 #define TRAPTYPE 61 #define ENTERPRISE 62 /* * #define DISPLAYSTR (63 | SYNTAX_MASK) */ #define BEGIN 64 #define IMPORTS 65 #define EXPORTS 66 #define ACCNOTIFY 67 #define BAR 68 #define RANGE 69 #define CONVENTION 70 #define DISPLAYHINT 71 #define FROM 72 #define AGENTCAP 73 #define MACRO 74 #define IMPLIED 75 #define SUPPORTS 76 #define INCLUDES 77 #define VARIATION 78 #define REVISION 79 #define NOTIMPL 80 #define OBJECTS 81 #define NOTIFICATIONS 82 #define MODULE 83 #define MINACCESS 84 #define PRODREL 85 #define WRSYNTAX 86 #define CREATEREQ 87 #define NOTIFGROUP 88 #define MANDATORYGROUPS 89 #define GROUP 90 #define OBJECT 91 #define IDENTIFIER 92 #define CHOICE 93 #define LEFTSQBRACK 95 #define RIGHTSQBRACK 96 #define IMPLICIT 97 #define APPSYNTAX (98 | SYNTAX_MASK) #define OBJSYNTAX (99 | SYNTAX_MASK) #define SIMPLESYNTAX (100 | SYNTAX_MASK) #define OBJNAME (101 | SYNTAX_MASK) #define NOTIFNAME (102 | SYNTAX_MASK) #define VARIABLES 103 #define UNSIGNED32 (104 | SYNTAX_MASK) #define INTEGER32 (105 | SYNTAX_MASK) #define OBJIDENTITY 106 /* * Beware of reaching SYNTAX_MASK (0x80) */ struct tok { const char *name; /* token name */ int len; /* length not counting nul */ int token; /* value */ int hash; /* hash of name */ struct tok *next; /* pointer to next in hash table */ }; static struct tok tokens[] = { {"obsolete", sizeof("obsolete") - 1, OBSOLETE} , {"Opaque", sizeof("Opaque") - 1, KW_OPAQUE} , {"optional", sizeof("optional") - 1, KW_OPTIONAL} , {"LAST-UPDATED", sizeof("LAST-UPDATED") - 1, LASTUPDATED} , {"ORGANIZATION", sizeof("ORGANIZATION") - 1, ORGANIZATION} , {"CONTACT-INFO", sizeof("CONTACT-INFO") - 1, CONTACTINFO} , {"MODULE-IDENTITY", sizeof("MODULE-IDENTITY") - 1, MODULEIDENTITY} , {"MODULE-COMPLIANCE", sizeof("MODULE-COMPLIANCE") - 1, COMPLIANCE} , {"DEFINITIONS", sizeof("DEFINITIONS") - 1, DEFINITIONS} , {"END", sizeof("END") - 1, END} , {"AUGMENTS", sizeof("AUGMENTS") - 1, AUGMENTS} , {"not-accessible", sizeof("not-accessible") - 1, NOACCESS} , {"write-only", sizeof("write-only") - 1, WRITEONLY} , {"NsapAddress", sizeof("NsapAddress") - 1, NSAPADDRESS} , {"UNITS", sizeof("Units") - 1, UNITS} , {"REFERENCE", sizeof("REFERENCE") - 1, REFERENCE} , {"NUM-ENTRIES", sizeof("NUM-ENTRIES") - 1, NUM_ENTRIES} , {"BITSTRING", sizeof("BITSTRING") - 1, BITSTRING} , {"BIT", sizeof("BIT") - 1, CONTINUE} , {"BITS", sizeof("BITS") - 1, BITSTRING} , {"Counter64", sizeof("Counter64") - 1, COUNTER64} , {"TimeTicks", sizeof("TimeTicks") - 1, TIMETICKS} , {"NOTIFICATION-TYPE", sizeof("NOTIFICATION-TYPE") - 1, NOTIFTYPE} , {"OBJECT-GROUP", sizeof("OBJECT-GROUP") - 1, OBJGROUP} , {"OBJECT-IDENTITY", sizeof("OBJECT-IDENTITY") - 1, OBJIDENTITY} , {"IDENTIFIER", sizeof("IDENTIFIER") - 1, IDENTIFIER} , {"OBJECT", sizeof("OBJECT") - 1, OBJECT} , {"NetworkAddress", sizeof("NetworkAddress") - 1, NETADDR} , {"Gauge", sizeof("Gauge") - 1, GAUGE} , {"Gauge32", sizeof("Gauge32") - 1, GAUGE} , {"Unsigned32", sizeof("Unsigned32") - 1, UNSIGNED32} , {"read-write", sizeof("read-write") - 1, READWRITE} , {"read-create", sizeof("read-create") - 1, READCREATE} , {"OCTETSTRING", sizeof("OCTETSTRING") - 1, OCTETSTR} , {"OCTET", sizeof("OCTET") - 1, CONTINUE} , {"OF", sizeof("OF") - 1, OF} , {"SEQUENCE", sizeof("SEQUENCE") - 1, SEQUENCE} , {"NULL", sizeof("NULL") - 1, NUL} , {"IpAddress", sizeof("IpAddress") - 1, IPADDR} , {"UInteger32", sizeof("UInteger32") - 1, UINTEGER32} , {"INTEGER", sizeof("INTEGER") - 1, INTEGER} , {"Integer32", sizeof("Integer32") - 1, INTEGER32} , {"Counter", sizeof("Counter") - 1, COUNTER} , {"Counter32", sizeof("Counter32") - 1, COUNTER} , {"read-only", sizeof("read-only") - 1, READONLY} , {"DESCRIPTION", sizeof("DESCRIPTION") - 1, DESCRIPTION} , {"INDEX", sizeof("INDEX") - 1, INDEX} , {"DEFVAL", sizeof("DEFVAL") - 1, DEFVAL} , {"deprecated", sizeof("deprecated") - 1, DEPRECATED} , {"SIZE", sizeof("SIZE") - 1, SIZE} , {"MAX-ACCESS", sizeof("MAX-ACCESS") - 1, ACCESS} , {"ACCESS", sizeof("ACCESS") - 1, ACCESS} , {"mandatory", sizeof("mandatory") - 1, MANDATORY} , {"current", sizeof("current") - 1, CURRENT} , {"STATUS", sizeof("STATUS") - 1, STATUS} , {"SYNTAX", sizeof("SYNTAX") - 1, SYNTAX} , {"OBJECT-TYPE", sizeof("OBJECT-TYPE") - 1, OBJTYPE} , {"TRAP-TYPE", sizeof("TRAP-TYPE") - 1, TRAPTYPE} , {"ENTERPRISE", sizeof("ENTERPRISE") - 1, ENTERPRISE} , {"BEGIN", sizeof("BEGIN") - 1, BEGIN} , {"IMPORTS", sizeof("IMPORTS") - 1, IMPORTS} , {"EXPORTS", sizeof("EXPORTS") - 1, EXPORTS} , {"accessible-for-notify", sizeof("accessible-for-notify") - 1, ACCNOTIFY} , {"TEXTUAL-CONVENTION", sizeof("TEXTUAL-CONVENTION") - 1, CONVENTION} , {"NOTIFICATION-GROUP", sizeof("NOTIFICATION-GROUP") - 1, NOTIFGROUP} , {"DISPLAY-HINT", sizeof("DISPLAY-HINT") - 1, DISPLAYHINT} , {"FROM", sizeof("FROM") - 1, FROM} , {"AGENT-CAPABILITIES", sizeof("AGENT-CAPABILITIES") - 1, AGENTCAP} , {"MACRO", sizeof("MACRO") - 1, MACRO} , {"IMPLIED", sizeof("IMPLIED") - 1, IMPLIED} , {"SUPPORTS", sizeof("SUPPORTS") - 1, SUPPORTS} , {"INCLUDES", sizeof("INCLUDES") - 1, INCLUDES} , {"VARIATION", sizeof("VARIATION") - 1, VARIATION} , {"REVISION", sizeof("REVISION") - 1, REVISION} , {"not-implemented", sizeof("not-implemented") - 1, NOTIMPL} , {"OBJECTS", sizeof("OBJECTS") - 1, OBJECTS} , {"NOTIFICATIONS", sizeof("NOTIFICATIONS") - 1, NOTIFICATIONS} , {"MODULE", sizeof("MODULE") - 1, MODULE} , {"MIN-ACCESS", sizeof("MIN-ACCESS") - 1, MINACCESS} , {"PRODUCT-RELEASE", sizeof("PRODUCT-RELEASE") - 1, PRODREL} , {"WRITE-SYNTAX", sizeof("WRITE-SYNTAX") - 1, WRSYNTAX} , {"CREATION-REQUIRES", sizeof("CREATION-REQUIRES") - 1, CREATEREQ} , {"MANDATORY-GROUPS", sizeof("MANDATORY-GROUPS") - 1, MANDATORYGROUPS} , {"GROUP", sizeof("GROUP") - 1, GROUP} , {"CHOICE", sizeof("CHOICE") - 1, CHOICE} , {"IMPLICIT", sizeof("IMPLICIT") - 1, IMPLICIT} , {"ObjectSyntax", sizeof("ObjectSyntax") - 1, OBJSYNTAX} , {"SimpleSyntax", sizeof("SimpleSyntax") - 1, SIMPLESYNTAX} , {"ApplicationSyntax", sizeof("ApplicationSyntax") - 1, APPSYNTAX} , {"ObjectName", sizeof("ObjectName") - 1, OBJNAME} , {"NotificationName", sizeof("NotificationName") - 1, NOTIFNAME} , {"VARIABLES", sizeof("VARIABLES") - 1, VARIABLES} , {NULL} }; static struct module_compatability *module_map_head; static struct module_compatability module_map[] = { {"RFC1065-SMI", "RFC1155-SMI", NULL, 0}, {"RFC1066-MIB", "RFC1156-MIB", NULL, 0}, /* * 'mib' -> 'mib-2' */ {"RFC1156-MIB", "RFC1158-MIB", NULL, 0}, /* * 'snmpEnableAuthTraps' -> 'snmpEnableAuthenTraps' */ {"RFC1158-MIB", "RFC1213-MIB", NULL, 0}, /* * 'nullOID' -> 'zeroDotZero' */ {"RFC1155-SMI", "SNMPv2-SMI", NULL, 0}, {"RFC1213-MIB", "SNMPv2-SMI", "mib-2", 0}, {"RFC1213-MIB", "SNMPv2-MIB", "sys", 3}, {"RFC1213-MIB", "IF-MIB", "if", 2}, {"RFC1213-MIB", "IP-MIB", "ip", 2}, {"RFC1213-MIB", "IP-MIB", "icmp", 4}, {"RFC1213-MIB", "TCP-MIB", "tcp", 3}, {"RFC1213-MIB", "UDP-MIB", "udp", 3}, {"RFC1213-MIB", "SNMPv2-SMI", "transmission", 0}, {"RFC1213-MIB", "SNMPv2-MIB", "snmp", 4}, {"RFC1231-MIB", "TOKENRING-MIB", NULL, 0}, {"RFC1271-MIB", "RMON-MIB", NULL, 0}, {"RFC1286-MIB", "SOURCE-ROUTING-MIB", "dot1dSr", 7}, {"RFC1286-MIB", "BRIDGE-MIB", NULL, 0}, {"RFC1315-MIB", "FRAME-RELAY-DTE-MIB", NULL, 0}, {"RFC1316-MIB", "CHARACTER-MIB", NULL, 0}, {"RFC1406-MIB", "DS1-MIB", NULL, 0}, {"RFC-1213", "RFC1213-MIB", NULL, 0}, }; #define MODULE_NOT_FOUND 0 #define MODULE_LOADED_OK 1 #define MODULE_ALREADY_LOADED 2 /* * #define MODULE_LOAD_FAILED 3 */ #define MODULE_LOAD_FAILED MODULE_NOT_FOUND #define MODULE_SYNTAX_ERROR 4 int gMibError = 0,gLoop = 0; static char *gpMibErrorString; char gMibNames[STRINGMAX]; #define HASHSIZE 32 #define BUCKET(x) (x & (HASHSIZE-1)) #define NHASHSIZE 128 #define NBUCKET(x) (x & (NHASHSIZE-1)) static struct tok *buckets[HASHSIZE]; static struct node *nbuckets[NHASHSIZE]; static struct tree *tbuckets[NHASHSIZE]; static struct module *module_head = NULL; static struct node *orphan_nodes = NULL; NETSNMP_IMPORT struct tree *tree_head; struct tree *tree_head = NULL; #define NUMBER_OF_ROOT_NODES 3 static struct module_import root_imports[NUMBER_OF_ROOT_NODES]; static int current_module = 0; static int max_module = 0; static int first_err_module = 1; static char *last_err_module = NULL; /* no repeats on "Cannot find module..." */ static void tree_from_node(struct tree *tp, struct node *np); static void do_subtree(struct tree *, struct node **); static void do_linkup(struct module *, struct node *); static void dump_module_list(void); static int get_token(FILE *, char *, int); static int parseQuoteString(FILE *, char *, int); static int tossObjectIdentifier(FILE *); static int name_hash(const char *); static void init_node_hash(struct node *); static void print_error(const char *, const char *, int); static void free_tree(struct tree *); static void free_partial_tree(struct tree *, int); static void free_node(struct node *); static void build_translation_table(void); static void init_tree_roots(void); static void merge_anon_children(struct tree *, struct tree *); static void unlink_tbucket(struct tree *); static void unlink_tree(struct tree *); static int getoid(FILE *, struct subid_s *, int); static struct node *parse_objectid(FILE *, char *); static int get_tc(const char *, int, int *, struct enum_list **, struct range_list **, char **); static int get_tc_index(const char *, int); static struct enum_list *parse_enumlist(FILE *, struct enum_list **); static struct range_list *parse_ranges(FILE * fp, struct range_list **); static struct node *parse_asntype(FILE *, char *, int *, char *); static struct node *parse_objecttype(FILE *, char *); static struct node *parse_objectgroup(FILE *, char *, int, struct objgroup **); static struct node *parse_notificationDefinition(FILE *, char *); static struct node *parse_trapDefinition(FILE *, char *); static struct node *parse_compliance(FILE *, char *); static struct node *parse_capabilities(FILE *, char *); static struct node *parse_moduleIdentity(FILE *, char *); static struct node *parse_macro(FILE *, char *); static void parse_imports(FILE *); static struct node *parse(FILE *, struct node *); static int read_module_internal(const char *); static int read_module_replacements(const char *); static int read_import_replacements(const char *, struct module_import *); static void new_module(const char *, const char *); static struct node *merge_parse_objectid(struct node *, FILE *, char *); static struct index_list *getIndexes(FILE * fp, struct index_list **); static struct varbind_list *getVarbinds(FILE * fp, struct varbind_list **); static void free_indexes(struct index_list **); static void free_varbinds(struct varbind_list **); static void free_ranges(struct range_list **); static void free_enums(struct enum_list **); static struct range_list *copy_ranges(struct range_list *); static struct enum_list *copy_enums(struct enum_list *); static u_int compute_match(const char *search_base, const char *key); void snmp_mib_toggle_options_usage(const char *lead, FILE * outf) { fprintf(outf, "%su: %sallow the use of underlines in MIB symbols\n", lead, ((netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_PARSE_LABEL)) ? "dis" : "")); fprintf(outf, "%sc: %sallow the use of \"--\" to terminate comments\n", lead, ((netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_COMMENT_TERM)) ? "" : "dis")); fprintf(outf, "%sd: %ssave the DESCRIPTIONs of the MIB objects\n", lead, ((netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_SAVE_MIB_DESCRS)) ? "do not " : "")); fprintf(outf, "%se: disable errors when MIB symbols conflict\n", lead); fprintf(outf, "%sw: enable warnings when MIB symbols conflict\n", lead); fprintf(outf, "%sW: enable detailed warnings when MIB symbols conflict\n", lead); fprintf(outf, "%sR: replace MIB symbols from latest module\n", lead); } char * snmp_mib_toggle_options(char *options) { if (options) { while (*options) { switch (*options) { case 'u': netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_PARSE_LABEL, !netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_PARSE_LABEL)); break; case 'c': netsnmp_ds_toggle_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_COMMENT_TERM); break; case 'e': netsnmp_ds_toggle_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_ERRORS); break; case 'w': netsnmp_ds_set_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_WARNINGS, 1); break; case 'W': netsnmp_ds_set_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_WARNINGS, 2); break; case 'd': netsnmp_ds_toggle_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_SAVE_MIB_DESCRS); break; case 'R': netsnmp_ds_toggle_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_REPLACE); break; default: /* * return at the unknown option */ return options; } options++; } } return NULL; } static int name_hash(const char *name) { int hash = 0; const char *cp; if (!name) return 0; for (cp = name; *cp; cp++) hash += tolower((unsigned char)(*cp)); return (hash); } void netsnmp_init_mib_internals(void) { register struct tok *tp; register int b, i; int max_modc; if (tree_head) return; /* * Set up hash list of pre-defined tokens */ memset(buckets, 0, sizeof(buckets)); for (tp = tokens; tp->name; tp++) { tp->hash = name_hash(tp->name); b = BUCKET(tp->hash); if (buckets[b]) tp->next = buckets[b]; /* BUG ??? */ buckets[b] = tp; } /* * Initialise other internal structures */ max_modc = sizeof(module_map) / sizeof(module_map[0]) - 1; for (i = 0; i < max_modc; ++i) module_map[i].next = &(module_map[i + 1]); module_map[max_modc].next = NULL; module_map_head = module_map; memset(nbuckets, 0, sizeof(nbuckets)); memset(tbuckets, 0, sizeof(tbuckets)); memset(tclist, 0, MAXTC * sizeof(struct tc)); build_translation_table(); init_tree_roots(); /* Set up initial roots */ /* * Relies on 'add_mibdir' having set up the modules */ } #ifndef NETSNMP_NO_LEGACY_DEFINITIONS void init_mib_internals(void) { netsnmp_init_mib_internals(); } #endif static void init_node_hash(struct node *nodes) { struct node *np, *nextp; int hash; memset(nbuckets, 0, sizeof(nbuckets)); for (np = nodes; np;) { nextp = np->next; hash = NBUCKET(name_hash(np->parent)); np->next = nbuckets[hash]; nbuckets[hash] = np; np = nextp; } } static int erroneousMibs = 0; netsnmp_feature_child_of(parse_get_error_count, netsnmp_unused) #ifndef NETSNMP_FEATURE_REMOVE_PARSE_GET_ERROR_COUNT int get_mib_parse_error_count(void) { return erroneousMibs; } #endif /* NETSNMP_FEATURE_REMOVE_PARSE_GET_ERROR_COUNT */ static void print_error(const char *str, const char *token, int type) { erroneousMibs++; if (!netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_ERRORS)) return; DEBUGMSGTL(("parse-mibs", "\n")); if (type == ENDOFFILE) snmp_log(LOG_ERR, "%s (EOF): At line %d in %s\n", str, mibLine, File); else if (token && *token) snmp_log(LOG_ERR, "%s (%s): At line %d in %s\n", str, token, mibLine, File); else snmp_log(LOG_ERR, "%s: At line %d in %s\n", str, mibLine, File); } static void print_module_not_found(const char *cp) { if (first_err_module) { snmp_log(LOG_ERR, "MIB search path: %s\n", netsnmp_get_mib_directory()); first_err_module = 0; } if (!last_err_module || strcmp(cp, last_err_module)) print_error("Cannot find module", cp, CONTINUE); if (last_err_module) free(last_err_module); last_err_module = strdup(cp); } static struct node * alloc_node(int modid) { struct node *np; np = (struct node *) calloc(1, sizeof(struct node)); if (np) { np->tc_index = -1; np->modid = modid; np->filename = strdup(File); np->lineno = mibLine; } return np; } static void unlink_tbucket(struct tree *tp) { int hash = NBUCKET(name_hash(tp->label)); struct tree *otp = NULL, *ntp = tbuckets[hash]; while (ntp && ntp != tp) { otp = ntp; ntp = ntp->next; } if (!ntp) snmp_log(LOG_EMERG, "Can't find %s in tbuckets\n", tp->label); else if (otp) otp->next = ntp->next; else tbuckets[hash] = tp->next; } static void unlink_tree(struct tree *tp) { struct tree *otp = NULL, *ntp = tp->parent; if (!ntp) { /* this tree has no parent */ DEBUGMSGTL(("unlink_tree", "Tree node %s has no parent\n", tp->label)); } else { ntp = ntp->child_list; while (ntp && ntp != tp) { otp = ntp; ntp = ntp->next_peer; } if (!ntp) snmp_log(LOG_EMERG, "Can't find %s in %s's children\n", tp->label, tp->parent->label); else if (otp) otp->next_peer = ntp->next_peer; else tp->parent->child_list = tp->next_peer; } if (tree_head == tp) tree_head = tp->next_peer; } static void free_partial_tree(struct tree *tp, int keep_label) { if (!tp) return; /* * remove the data from this tree node */ free_enums(&tp->enums); free_ranges(&tp->ranges); free_indexes(&tp->indexes); free_varbinds(&tp->varbinds); if (!keep_label) SNMP_FREE(tp->label); SNMP_FREE(tp->hint); SNMP_FREE(tp->units); SNMP_FREE(tp->description); SNMP_FREE(tp->reference); SNMP_FREE(tp->augments); SNMP_FREE(tp->defaultValue); } /* * free a tree node. Note: the node must already have been unlinked * from the tree when calling this routine */ static void free_tree(struct tree *Tree) { if (!Tree) return; unlink_tbucket(Tree); free_partial_tree(Tree, FALSE); if (Tree->module_list != &Tree->modid) free(Tree->module_list); free(Tree); } static void free_node(struct node *np) { if (!np) return; free_enums(&np->enums); free_ranges(&np->ranges); free_indexes(&np->indexes); free_varbinds(&np->varbinds); if (np->label) free(np->label); if (np->hint) free(np->hint); if (np->units) free(np->units); if (np->description) free(np->description); if (np->reference) free(np->reference); if (np->defaultValue) free(np->defaultValue); if (np->parent) free(np->parent); if (np->augments) free(np->augments); if (np->filename) free(np->filename); free((char *) np); } static void print_range_value(FILE * fp, int type, struct range_list * rp) { switch (type) { case TYPE_INTEGER: case TYPE_INTEGER32: if (rp->low == rp->high) fprintf(fp, "%d", rp->low); else fprintf(fp, "%d..%d", rp->low, rp->high); break; case TYPE_UNSIGNED32: case TYPE_OCTETSTR: case TYPE_GAUGE: case TYPE_UINTEGER: if (rp->low == rp->high) fprintf(fp, "%u", (unsigned)rp->low); else fprintf(fp, "%u..%u", (unsigned)rp->low, (unsigned)rp->high); break; default: /* No other range types allowed */ break; } } #ifdef TEST static void print_nodes(FILE * fp, struct node *root) { struct enum_list *ep; struct index_list *ip; struct varbind_list *vp; struct node *np; for (np = root; np; np = np->next) { fprintf(fp, "%s ::= { %s %ld } (%d)\n", np->label, np->parent, np->subid, np->type); if (np->tc_index >= 0) fprintf(fp, " TC = %s\n", tclist[np->tc_index].descriptor); if (np->enums) { fprintf(fp, " Enums: \n"); for (ep = np->enums; ep; ep = ep->next) { fprintf(fp, " %s(%d)\n", ep->label, ep->value); } } if (np->ranges) { struct range_list *rp; fprintf(fp, " Ranges: "); for (rp = np->ranges; rp; rp = rp->next) { fprintf(fp, "\n "); print_range_value(fp, np->type, rp); } fprintf(fp, "\n"); } if (np->indexes) { fprintf(fp, " Indexes: \n"); for (ip = np->indexes; ip; ip = ip->next) { fprintf(fp, " %s\n", ip->ilabel); } } if (np->augments) fprintf(fp, " Augments: %s\n", np->augments); if (np->varbinds) { fprintf(fp, " Varbinds: \n"); for (vp = np->varbinds; vp; vp = vp->next) { fprintf(fp, " %s\n", vp->vblabel); } } if (np->hint) fprintf(fp, " Hint: %s\n", np->hint); if (np->units) fprintf(fp, " Units: %s\n", np->units); if (np->defaultValue) fprintf(fp, " DefaultValue: %s\n", np->defaultValue); } } #endif void print_subtree(FILE * f, struct tree *tree, int count) { struct tree *tp; int i; char modbuf[256]; for (i = 0; i < count; i++) fprintf(f, " "); fprintf(f, "Children of %s(%ld):\n", tree->label, tree->subid); count++; for (tp = tree->child_list; tp; tp = tp->next_peer) { for (i = 0; i < count; i++) fprintf(f, " "); fprintf(f, "%s:%s(%ld) type=%d", module_name(tp->module_list[0], modbuf), tp->label, tp->subid, tp->type); if (tp->tc_index != -1) fprintf(f, " tc=%d", tp->tc_index); if (tp->hint) fprintf(f, " hint=%s", tp->hint); if (tp->units) fprintf(f, " units=%s", tp->units); if (tp->number_modules > 1) { fprintf(f, " modules:"); for (i = 1; i < tp->number_modules; i++) fprintf(f, " %s", module_name(tp->module_list[i], modbuf)); } fprintf(f, "\n"); } for (tp = tree->child_list; tp; tp = tp->next_peer) { if (tp->child_list) print_subtree(f, tp, count); } } void print_ascii_dump_tree(FILE * f, struct tree *tree, int count) { struct tree *tp; count++; for (tp = tree->child_list; tp; tp = tp->next_peer) { fprintf(f, "%s OBJECT IDENTIFIER ::= { %s %ld }\n", tp->label, tree->label, tp->subid); } for (tp = tree->child_list; tp; tp = tp->next_peer) { if (tp->child_list) print_ascii_dump_tree(f, tp, count); } } static int translation_table[256]; static void build_translation_table(void) { int count; for (count = 0; count < 256; count++) { switch (count) { case OBJID: translation_table[count] = TYPE_OBJID; break; case OCTETSTR: translation_table[count] = TYPE_OCTETSTR; break; case INTEGER: translation_table[count] = TYPE_INTEGER; break; case NETADDR: translation_table[count] = TYPE_NETADDR; break; case IPADDR: translation_table[count] = TYPE_IPADDR; break; case COUNTER: translation_table[count] = TYPE_COUNTER; break; case GAUGE: translation_table[count] = TYPE_GAUGE; break; case TIMETICKS: translation_table[count] = TYPE_TIMETICKS; break; case KW_OPAQUE: translation_table[count] = TYPE_OPAQUE; break; case NUL: translation_table[count] = TYPE_NULL; break; case COUNTER64: translation_table[count] = TYPE_COUNTER64; break; case BITSTRING: translation_table[count] = TYPE_BITSTRING; break; case NSAPADDRESS: translation_table[count] = TYPE_NSAPADDRESS; break; case INTEGER32: translation_table[count] = TYPE_INTEGER32; break; case UINTEGER32: translation_table[count] = TYPE_UINTEGER; break; case UNSIGNED32: translation_table[count] = TYPE_UNSIGNED32; break; case TRAPTYPE: translation_table[count] = TYPE_TRAPTYPE; break; case NOTIFTYPE: translation_table[count] = TYPE_NOTIFTYPE; break; case NOTIFGROUP: translation_table[count] = TYPE_NOTIFGROUP; break; case OBJGROUP: translation_table[count] = TYPE_OBJGROUP; break; case MODULEIDENTITY: translation_table[count] = TYPE_MODID; break; case OBJIDENTITY: translation_table[count] = TYPE_OBJIDENTITY; break; case AGENTCAP: translation_table[count] = TYPE_AGENTCAP; break; case COMPLIANCE: translation_table[count] = TYPE_MODCOMP; break; default: translation_table[count] = TYPE_OTHER; break; } } } static void init_tree_roots(void) { struct tree *tp, *lasttp; int base_modid; int hash; base_modid = which_module("SNMPv2-SMI"); if (base_modid == -1) base_modid = which_module("RFC1155-SMI"); if (base_modid == -1) base_modid = which_module("RFC1213-MIB"); /* * build root node */ tp = (struct tree *) calloc(1, sizeof(struct tree)); if (tp == NULL) return; tp->label = strdup("joint-iso-ccitt"); tp->modid = base_modid; tp->number_modules = 1; tp->module_list = &(tp->modid); tp->subid = 2; tp->tc_index = -1; set_function(tp); /* from mib.c */ hash = NBUCKET(name_hash(tp->label)); tp->next = tbuckets[hash]; tbuckets[hash] = tp; lasttp = tp; root_imports[0].label = strdup(tp->label); root_imports[0].modid = base_modid; /* * build root node */ tp = (struct tree *) calloc(1, sizeof(struct tree)); if (tp == NULL) return; tp->next_peer = lasttp; tp->label = strdup("ccitt"); tp->modid = base_modid; tp->number_modules = 1; tp->module_list = &(tp->modid); tp->subid = 0; tp->tc_index = -1; set_function(tp); /* from mib.c */ hash = NBUCKET(name_hash(tp->label)); tp->next = tbuckets[hash]; tbuckets[hash] = tp; lasttp = tp; root_imports[1].label = strdup(tp->label); root_imports[1].modid = base_modid; /* * build root node */ tp = (struct tree *) calloc(1, sizeof(struct tree)); if (tp == NULL) return; tp->next_peer = lasttp; tp->label = strdup("iso"); tp->modid = base_modid; tp->number_modules = 1; tp->module_list = &(tp->modid); tp->subid = 1; tp->tc_index = -1; set_function(tp); /* from mib.c */ hash = NBUCKET(name_hash(tp->label)); tp->next = tbuckets[hash]; tbuckets[hash] = tp; lasttp = tp; root_imports[2].label = strdup(tp->label); root_imports[2].modid = base_modid; tree_head = tp; } #ifdef STRICT_MIB_PARSEING #define label_compare strcasecmp #else #define label_compare strcmp #endif struct tree * find_tree_node(const char *name, int modid) { struct tree *tp, *headtp; int count, *int_p; if (!name || !*name) return (NULL); headtp = tbuckets[NBUCKET(name_hash(name))]; for (tp = headtp; tp; tp = tp->next) { if (tp->label && !label_compare(tp->label, name)) { if (modid == -1) /* Any module */ return (tp); for (int_p = tp->module_list, count = 0; count < tp->number_modules; ++count, ++int_p) if (*int_p == modid) return (tp); } } return (NULL); } /* * computes a value which represents how close name1 is to name2. * * high scores mean a worse match. * * (yes, the algorithm sucks!) */ #define MAX_BAD 0xffffff static u_int compute_match(const char *search_base, const char *key) { #if defined(HAVE_REGEX_H) && defined(HAVE_REGCOMP) int rc; regex_t parsetree; regmatch_t pmatch; rc = regcomp(&parsetree, key, REG_ICASE | REG_EXTENDED); if (rc == 0) rc = regexec(&parsetree, search_base, 1, &pmatch, 0); regfree(&parsetree); if (rc == 0) { /* * found */ return pmatch.rm_so; } #else /* use our own wildcard matcher */ /* * first find the longest matching substring (ick) */ char *first = NULL, *result = NULL, *entry; const char *position; char *newkey = strdup(key); char *st; entry = strtok_r(newkey, "*", &st); position = search_base; while (entry) { result = strcasestr(position, entry); if (result == NULL) { free(newkey); return MAX_BAD; } if (first == NULL) first = result; position = result + strlen(entry); entry = strtok_r(NULL, "*", &st); } free(newkey); if (result) return (first - search_base); #endif /* * not found */ return MAX_BAD; } /* * Find the tree node that best matches the pattern string. * Use the "reported" flag such that only one match * is attempted for every node. * * Warning! This function may recurse. * * Caller _must_ invoke clear_tree_flags before first call * to this function. This function may be called multiple times * to ensure that the entire tree is traversed. */ struct tree * find_best_tree_node(const char *pattrn, struct tree *tree_top, u_int * match) { struct tree *tp, *best_so_far = NULL, *retptr; u_int old_match = MAX_BAD, new_match = MAX_BAD; if (!pattrn || !*pattrn) return (NULL); if (!tree_top) tree_top = get_tree_head(); for (tp = tree_top; tp; tp = tp->next_peer) { if (!tp->reported && tp->label) new_match = compute_match(tp->label, pattrn); tp->reported = 1; if (new_match < old_match) { best_so_far = tp; old_match = new_match; } if (new_match == 0) break; /* this is the best result we can get */ if (tp->child_list) { retptr = find_best_tree_node(pattrn, tp->child_list, &new_match); if (new_match < old_match) { best_so_far = retptr; old_match = new_match; } if (new_match == 0) break; /* this is the best result we can get */ } } if (match) *match = old_match; return (best_so_far); } static void merge_anon_children(struct tree *tp1, struct tree *tp2) /* * NB: tp1 is the 'anonymous' node */ { struct tree *child1, *child2, *previous; for (child1 = tp1->child_list; child1;) { for (child2 = tp2->child_list, previous = NULL; child2; previous = child2, child2 = child2->next_peer) { if (child1->subid == child2->subid) { /* * Found 'matching' children, * so merge them */ if (!strncmp(child1->label, ANON, ANON_LEN)) { merge_anon_children(child1, child2); child1->child_list = NULL; previous = child1; /* Finished with 'child1' */ child1 = child1->next_peer; free_tree(previous); goto next; } else if (!strncmp(child2->label, ANON, ANON_LEN)) { merge_anon_children(child2, child1); if (previous) previous->next_peer = child2->next_peer; else tp2->child_list = child2->next_peer; free_tree(child2); previous = child1; /* Move 'child1' to 'tp2' */ child1 = child1->next_peer; previous->next_peer = tp2->child_list; tp2->child_list = previous; for (previous = tp2->child_list; previous; previous = previous->next_peer) previous->parent = tp2; goto next; } else if (!label_compare(child1->label, child2->label)) { if (netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_WARNINGS)) { snmp_log(LOG_WARNING, "Warning: %s.%ld is both %s and %s (%s)\n", tp2->label, child1->subid, child1->label, child2->label, File); } continue; } else { /* * Two copies of the same node. * 'child2' adopts the children of 'child1' */ if (child2->child_list) { for (previous = child2->child_list; previous->next_peer; previous = previous->next_peer); /* Find the end of the list */ previous->next_peer = child1->child_list; } else child2->child_list = child1->child_list; for (previous = child1->child_list; previous; previous = previous->next_peer) previous->parent = child2; child1->child_list = NULL; previous = child1; /* Finished with 'child1' */ child1 = child1->next_peer; free_tree(previous); goto next; } } } /* * If no match, move 'child1' to 'tp2' child_list */ if (child1) { previous = child1; child1 = child1->next_peer; previous->parent = tp2; previous->next_peer = tp2->child_list; tp2->child_list = previous; } next:; } } /* * Find all the children of root in the list of nodes. Link them into the * tree and out of the nodes list. */ static void do_subtree(struct tree *root, struct node **nodes) { struct tree *tp, *anon_tp = NULL; struct tree *xroot = root; struct node *np, **headp; struct node *oldnp = NULL, *child_list = NULL, *childp = NULL; int hash; int *int_p; while (xroot->next_peer && xroot->next_peer->subid == root->subid) { #if 0 printf("xroot: %s.%s => %s\n", xroot->parent->label, xroot->label, xroot->next_peer->label); #endif xroot = xroot->next_peer; } tp = root; headp = &nbuckets[NBUCKET(name_hash(tp->label))]; /* * Search each of the nodes for one whose parent is root, and * move each into a separate list. */ for (np = *headp; np; np = np->next) { if (!label_compare(tp->label, np->parent)) { /* * take this node out of the node list */ if (oldnp == NULL) { *headp = np->next; /* fix root of node list */ } else { oldnp->next = np->next; /* link around this node */ } if (child_list) childp->next = np; else child_list = np; childp = np; } else { oldnp = np; } } if (childp) childp->next = NULL; /* * Take each element in the child list and place it into the tree. */ for (np = child_list; np; np = np->next) { struct tree *otp = NULL; struct tree *xxroot = xroot; anon_tp = NULL; tp = xroot->child_list; if (np->subid == -1) { /* * name ::= { parent } */ np->subid = xroot->subid; tp = xroot; xxroot = xroot->parent; } while (tp) { if (tp->subid == np->subid) break; else { otp = tp; tp = tp->next_peer; } } if (tp) { if (!label_compare(tp->label, np->label)) { /* * Update list of modules */ int_p = malloc((tp->number_modules + 1) * sizeof(int)); if (int_p == NULL) return; memcpy(int_p, tp->module_list, tp->number_modules * sizeof(int)); int_p[tp->number_modules] = np->modid; if (tp->module_list != &tp->modid) free(tp->module_list); ++tp->number_modules; tp->module_list = int_p; if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_REPLACE)) { /* * Replace from node */ tree_from_node(tp, np); } /* * Handle children */ do_subtree(tp, nodes); continue; } if (!strncmp(np->label, ANON, ANON_LEN) || !strncmp(tp->label, ANON, ANON_LEN)) { anon_tp = tp; /* Need to merge these two trees later */ } else if (netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_WARNINGS)) { snmp_log(LOG_WARNING, "Warning: %s.%ld is both %s and %s (%s)\n", root->label, np->subid, tp->label, np->label, File); } } tp = (struct tree *) calloc(1, sizeof(struct tree)); if (tp == NULL) return; tp->parent = xxroot; tp->modid = np->modid; tp->number_modules = 1; tp->module_list = &(tp->modid); tree_from_node(tp, np); tp->next_peer = otp ? otp->next_peer : xxroot->child_list; if (otp) otp->next_peer = tp; else xxroot->child_list = tp; hash = NBUCKET(name_hash(tp->label)); tp->next = tbuckets[hash]; tbuckets[hash] = tp; do_subtree(tp, nodes); if (anon_tp) { if (!strncmp(tp->label, ANON, ANON_LEN)) { /* * The new node is anonymous, * so merge it with the existing one. */ merge_anon_children(tp, anon_tp); /* * unlink and destroy tp */ unlink_tree(tp); free_tree(tp); } else if (!strncmp(anon_tp->label, ANON, ANON_LEN)) { struct tree *ntp; /* * The old node was anonymous, * so merge it with the existing one, * and fill in the full information. */ merge_anon_children(anon_tp, tp); /* * unlink anon_tp from the hash */ unlink_tbucket(anon_tp); /* * get rid of old contents of anon_tp */ free_partial_tree(anon_tp, FALSE); /* * put in the current information */ anon_tp->label = tp->label; anon_tp->child_list = tp->child_list; anon_tp->modid = tp->modid; anon_tp->tc_index = tp->tc_index; anon_tp->type = tp->type; anon_tp->enums = tp->enums; anon_tp->indexes = tp->indexes; anon_tp->augments = tp->augments; anon_tp->varbinds = tp->varbinds; anon_tp->ranges = tp->ranges; anon_tp->hint = tp->hint; anon_tp->units = tp->units; anon_tp->description = tp->description; anon_tp->reference = tp->reference; anon_tp->defaultValue = tp->defaultValue; anon_tp->parent = tp->parent; set_function(anon_tp); /* * update parent pointer in moved children */ ntp = anon_tp->child_list; while (ntp) { ntp->parent = anon_tp; ntp = ntp->next_peer; } /* * hash in anon_tp in its new place */ hash = NBUCKET(name_hash(anon_tp->label)); anon_tp->next = tbuckets[hash]; tbuckets[hash] = anon_tp; /* * unlink and destroy tp */ unlink_tbucket(tp); unlink_tree(tp); free(tp); } else { /* * Uh? One of these two should have been anonymous! */ if (netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_WARNINGS)) { snmp_log(LOG_WARNING, "Warning: expected anonymous node (either %s or %s) in %s\n", tp->label, anon_tp->label, File); } } anon_tp = NULL; } } /* * free all nodes that were copied into tree */ oldnp = NULL; for (np = child_list; np; np = np->next) { if (oldnp) free_node(oldnp); oldnp = np; } if (oldnp) free_node(oldnp); } static void do_linkup(struct module *mp, struct node *np) { struct module_import *mip; struct node *onp, *oldp, *newp; struct tree *tp; int i, more; /* * All modules implicitly import * the roots of the tree */ if (snmp_get_do_debugging() > 1) dump_module_list(); DEBUGMSGTL(("parse-mibs", "Processing IMPORTS for module %d %s\n", mp->modid, mp->name)); if (mp->no_imports == 0) { mp->no_imports = NUMBER_OF_ROOT_NODES; mp->imports = root_imports; } /* * Build the tree */ init_node_hash(np); for (i = 0, mip = mp->imports; i < mp->no_imports; ++i, ++mip) { char modbuf[256]; DEBUGMSGTL(("parse-mibs", " Processing import: %s\n", mip->label)); if (get_tc_index(mip->label, mip->modid) != -1) continue; tp = find_tree_node(mip->label, mip->modid); if (!tp) { if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_ERRORS)) snmp_log(LOG_WARNING, "Did not find '%s' in module %s (%s)\n", mip->label, module_name(mip->modid, modbuf), File); continue; } do_subtree(tp, &np); } /* * If any nodes left over, * check that they're not the result of a "fully qualified" * name, and then add them to the list of orphans */ if (!np) return; for (tp = tree_head; tp; tp = tp->next_peer) do_subtree(tp, &np); if (!np) return; /* * quietly move all internal references to the orphan list */ oldp = orphan_nodes; do { for (i = 0; i < NHASHSIZE; i++) for (onp = nbuckets[i]; onp; onp = onp->next) { struct node *op = NULL; int hash = NBUCKET(name_hash(onp->label)); np = nbuckets[hash]; while (np) { if (label_compare(onp->label, np->parent)) { op = np; np = np->next; } else { if (op) op->next = np->next; else nbuckets[hash] = np->next; DEBUGMSGTL(("parse-mibs", "Moving %s to orphanage", np->label)); np->next = orphan_nodes; orphan_nodes = np; op = NULL; np = nbuckets[hash]; } } } newp = orphan_nodes; more = 0; for (onp = orphan_nodes; onp != oldp; onp = onp->next) { struct node *op = NULL; int hash = NBUCKET(name_hash(onp->label)); np = nbuckets[hash]; while (np) { if (label_compare(onp->label, np->parent)) { op = np; np = np->next; } else { if (op) op->next = np->next; else nbuckets[hash] = np->next; np->next = orphan_nodes; orphan_nodes = np; op = NULL; np = nbuckets[hash]; more = 1; } } } oldp = newp; } while (more); /* * complain about left over nodes */ for (np = orphan_nodes; np && np->next; np = np->next); /* find the end of the orphan list */ for (i = 0; i < NHASHSIZE; i++) if (nbuckets[i]) { if (orphan_nodes) onp = np->next = nbuckets[i]; else onp = orphan_nodes = nbuckets[i]; nbuckets[i] = NULL; while (onp) { snmp_log(LOG_WARNING, "Unlinked OID in %s: %s ::= { %s %ld }\n", (mp->name ? mp->name : "<no module>"), (onp->label ? onp->label : "<no label>"), (onp->parent ? onp->parent : "<no parent>"), onp->subid); snmp_log(LOG_WARNING, "Undefined identifier: %s near line %d of %s\n", (onp->parent ? onp->parent : "<no parent>"), onp->lineno, onp->filename); np = onp; onp = onp->next; } } return; } /* * Takes a list of the form: * { iso org(3) dod(6) 1 } * and creates several nodes, one for each parent-child pair. * Returns 0 on error. */ static int getoid(FILE * fp, struct subid_s *id, /* an array of subids */ int length) { /* the length of the array */ register int count; int type; char token[MAXTOKEN]; if ((type = get_token(fp, token, MAXTOKEN)) != LEFTBRACKET) { print_error("Expected \"{\"", token, type); return 0; } type = get_token(fp, token, MAXTOKEN); for (count = 0; count < length; count++, id++) { id->label = NULL; id->modid = current_module; id->subid = -1; if (type == RIGHTBRACKET) return count; if (type == LABEL) { /* * this entry has a label */ id->label = strdup(token); type = get_token(fp, token, MAXTOKEN); if (type == LEFTPAREN) { type = get_token(fp, token, MAXTOKEN); if (type == NUMBER) { id->subid = strtoul(token, NULL, 10); if ((type = get_token(fp, token, MAXTOKEN)) != RIGHTPAREN) { print_error("Expected a closing parenthesis", token, type); return 0; } } else { print_error("Expected a number", token, type); return 0; } } else { continue; } } else if (type == NUMBER) { /* * this entry has just an integer sub-identifier */ id->subid = strtoul(token, NULL, 10); } else { print_error("Expected label or number", token, type); return 0; } type = get_token(fp, token, MAXTOKEN); } print_error("Too long OID", token, type); return 0; } /* * Parse a sequence of object subidentifiers for the given name. * The "label OBJECT IDENTIFIER ::=" portion has already been parsed. * * The majority of cases take this form : * label OBJECT IDENTIFIER ::= { parent 2 } * where a parent label and a child subidentifier number are specified. * * Variations on the theme include cases where a number appears with * the parent, or intermediate subidentifiers are specified by label, * by number, or both. * * Here are some representative samples : * internet OBJECT IDENTIFIER ::= { iso org(3) dod(6) 1 } * mgmt OBJECT IDENTIFIER ::= { internet 2 } * rptrInfoHealth OBJECT IDENTIFIER ::= { snmpDot3RptrMgt 0 4 } * * Here is a very rare form : * iso OBJECT IDENTIFIER ::= { 1 } * * Returns NULL on error. When this happens, memory may be leaked. */ static struct node * parse_objectid(FILE * fp, char *name) { register int count; register struct subid_s *op, *nop; int length; struct subid_s loid[32]; struct node *np, *root = NULL, *oldnp = NULL; struct tree *tp; if ((length = getoid(fp, loid, 32)) == 0) { print_error("Bad object identifier", NULL, CONTINUE); return NULL; } /* * Handle numeric-only object identifiers, * by labelling the first sub-identifier */ op = loid; if (!op->label) { if (length == 1) { print_error("Attempt to define a root oid", name, OBJECT); return NULL; } for (tp = tree_head; tp; tp = tp->next_peer) if ((int) tp->subid == op->subid) { op->label = strdup(tp->label); break; } } /* * Handle "label OBJECT-IDENTIFIER ::= { subid }" */ if (length == 1) { op = loid; np = alloc_node(op->modid); if (np == NULL) return (NULL); np->subid = op->subid; np->label = strdup(name); np->parent = op->label; return np; } /* * For each parent-child subid pair in the subid array, * create a node and link it into the node list. */ for (count = 0, op = loid, nop = loid + 1; count < (length - 1); count++, op++, nop++) { /* * every node must have parent's name and child's name or number */ /* * XX the next statement is always true -- does it matter ?? */ if (op->label && (nop->label || (nop->subid != -1))) { np = alloc_node(nop->modid); if (np == NULL) goto err; if (root == NULL) root = np; np->parent = strdup(op->label); if (count == (length - 2)) { /* * The name for this node is the label for this entry */ np->label = strdup(name); if (np->label == NULL) goto err; } else { if (!nop->label) { nop->label = (char *) malloc(20 + ANON_LEN); if (nop->label == NULL) goto err; sprintf(nop->label, "%s%d", ANON, anonymous++); } np->label = strdup(nop->label); } if (nop->subid != -1) np->subid = nop->subid; else print_error("Warning: This entry is pretty silly", np->label, CONTINUE); /* * set up next entry */ if (oldnp) oldnp->next = np; oldnp = np; } /* end if(op->label... */ } out: /* * free the loid array */ for (count = 0, op = loid; count < length; count++, op++) { if (op->label) free(op->label); } return root; err: for (; root; root = np) { np = root->next; free_node(root); } goto out; } static int get_tc(const char *descriptor, int modid, int *tc_index, struct enum_list **ep, struct range_list **rp, char **hint) { int i; struct tc *tcp; i = get_tc_index(descriptor, modid); if (tc_index) *tc_index = i; if (i != -1) { tcp = &tclist[i]; if (ep) { free_enums(ep); *ep = copy_enums(tcp->enums); } if (rp) { free_ranges(rp); *rp = copy_ranges(tcp->ranges); } if (hint) { if (*hint) free(*hint); *hint = (tcp->hint ? strdup(tcp->hint) : NULL); } return tcp->type; } return LABEL; } /* * return index into tclist of given TC descriptor * return -1 if not found */ static int get_tc_index(const char *descriptor, int modid) { int i; struct tc *tcp; struct module *mp; struct module_import *mip; /* * Check that the descriptor isn't imported * by searching the import list */ for (mp = module_head; mp; mp = mp->next) if (mp->modid == modid) break; if (mp) for (i = 0, mip = mp->imports; i < mp->no_imports; ++i, ++mip) { if (!label_compare(mip->label, descriptor)) { /* * Found it - so amend the module ID */ modid = mip->modid; break; } } for (i = 0, tcp = tclist; i < MAXTC; i++, tcp++) { if (tcp->type == 0) break; if (!label_compare(descriptor, tcp->descriptor) && ((modid == tcp->modid) || (modid == -1))) { return i; } } return -1; } /* * translate integer tc_index to string identifier from tclist * * * * Returns pointer to string in table (should not be modified) or NULL */ const char * get_tc_descriptor(int tc_index) { if (tc_index < 0 || tc_index >= MAXTC) return NULL; return (tclist[tc_index].descriptor); } #ifndef NETSNMP_FEATURE_REMOVE_GET_TC_DESCRIPTION /* used in the perl module */ const char * get_tc_description(int tc_index) { if (tc_index < 0 || tc_index >= MAXTC) return NULL; return (tclist[tc_index].description); } #endif /* NETSNMP_FEATURE_REMOVE_GET_TC_DESCRIPTION */ /* * Parses an enumeration list of the form: * { label(value) label(value) ... } * The initial { has already been parsed. * Returns NULL on error. */ static struct enum_list * parse_enumlist(FILE * fp, struct enum_list **retp) { register int type; char token[MAXTOKEN]; struct enum_list *ep = NULL, **epp = &ep; free_enums(retp); while ((type = get_token(fp, token, MAXTOKEN)) != ENDOFFILE) { if (type == RIGHTBRACKET) break; /* some enums use "deprecated" to indicate a no longer value label */ /* (EG: IP-MIB's IpAddressStatusTC) */ if (type == LABEL || type == DEPRECATED) { /* * this is an enumerated label */ *epp = (struct enum_list *) calloc(1, sizeof(struct enum_list)); if (*epp == NULL) return (NULL); /* * a reasonable approximation for the length */ (*epp)->label = strdup(token); type = get_token(fp, token, MAXTOKEN); if (type != LEFTPAREN) { print_error("Expected \"(\"", token, type); return NULL; } type = get_token(fp, token, MAXTOKEN); if (type != NUMBER) { print_error("Expected integer", token, type); return NULL; } (*epp)->value = strtol(token, NULL, 10); type = get_token(fp, token, MAXTOKEN); if (type != RIGHTPAREN) { print_error("Expected \")\"", token, type); return NULL; } epp = &(*epp)->next; } } if (type == ENDOFFILE) { print_error("Expected \"}\"", token, type); return NULL; } *retp = ep; return ep; } static struct range_list * parse_ranges(FILE * fp, struct range_list **retp) { int low, high; char nexttoken[MAXTOKEN]; int nexttype; struct range_list *rp = NULL, **rpp = &rp; int size = 0, taken = 1; free_ranges(retp); nexttype = get_token(fp, nexttoken, MAXTOKEN); if (nexttype == SIZE) { size = 1; taken = 0; nexttype = get_token(fp, nexttoken, MAXTOKEN); if (nexttype != LEFTPAREN) print_error("Expected \"(\" after SIZE", nexttoken, nexttype); } do { if (!taken) nexttype = get_token(fp, nexttoken, MAXTOKEN); else taken = 0; high = low = strtoul(nexttoken, NULL, 10); nexttype = get_token(fp, nexttoken, MAXTOKEN); if (nexttype == RANGE) { nexttype = get_token(fp, nexttoken, MAXTOKEN); errno = 0; high = strtoul(nexttoken, NULL, 10); if ( errno == ERANGE ) { if (netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_WARNINGS)) snmp_log(LOG_WARNING, "Warning: Upper bound not handled correctly (%s != %d): At line %d in %s\n", nexttoken, high, mibLine, File); } nexttype = get_token(fp, nexttoken, MAXTOKEN); } *rpp = (struct range_list *) calloc(1, sizeof(struct range_list)); if (*rpp == NULL) break; (*rpp)->low = low; (*rpp)->high = high; rpp = &(*rpp)->next; } while (nexttype == BAR); if (size) { if (nexttype != RIGHTPAREN) print_error("Expected \")\" after SIZE", nexttoken, nexttype); nexttype = get_token(fp, nexttoken, nexttype); } if (nexttype != RIGHTPAREN) print_error("Expected \")\"", nexttoken, nexttype); *retp = rp; return rp; } /* * Parses an asn type. Structures are ignored by this parser. * Returns NULL on error. */ static struct node * parse_asntype(FILE * fp, char *name, int *ntype, char *ntoken) { int type, i; char token[MAXTOKEN]; char quoted_string_buffer[MAXQUOTESTR]; char *hint = NULL; char *descr = NULL; struct tc *tcp; int level; type = get_token(fp, token, MAXTOKEN); if (type == SEQUENCE || type == CHOICE) { level = 0; while ((type = get_token(fp, token, MAXTOKEN)) != ENDOFFILE) { if (type == LEFTBRACKET) { level++; } else if (type == RIGHTBRACKET && --level == 0) { *ntype = get_token(fp, ntoken, MAXTOKEN); return NULL; } } print_error("Expected \"}\"", token, type); return NULL; } else if (type == LEFTBRACKET) { struct node *np; int ch_next = '{'; ungetc(ch_next, fp); np = parse_objectid(fp, name); if (np != NULL) { *ntype = get_token(fp, ntoken, MAXTOKEN); return np; } return NULL; } else if (type == LEFTSQBRACK) { int size = 0; do { type = get_token(fp, token, MAXTOKEN); } while (type != ENDOFFILE && type != RIGHTSQBRACK); if (type != RIGHTSQBRACK) { print_error("Expected \"]\"", token, type); return NULL; } type = get_token(fp, token, MAXTOKEN); if (type == IMPLICIT) type = get_token(fp, token, MAXTOKEN); *ntype = get_token(fp, ntoken, MAXTOKEN); if (*ntype == LEFTPAREN) { switch (type) { case OCTETSTR: *ntype = get_token(fp, ntoken, MAXTOKEN); if (*ntype != SIZE) { print_error("Expected SIZE", ntoken, *ntype); return NULL; } size = 1; *ntype = get_token(fp, ntoken, MAXTOKEN); if (*ntype != LEFTPAREN) { print_error("Expected \"(\" after SIZE", ntoken, *ntype); return NULL; } /* FALL THROUGH */ case INTEGER: *ntype = get_token(fp, ntoken, MAXTOKEN); do { if (*ntype != NUMBER) print_error("Expected NUMBER", ntoken, *ntype); *ntype = get_token(fp, ntoken, MAXTOKEN); if (*ntype == RANGE) { *ntype = get_token(fp, ntoken, MAXTOKEN); if (*ntype != NUMBER) print_error("Expected NUMBER", ntoken, *ntype); *ntype = get_token(fp, ntoken, MAXTOKEN); } } while (*ntype == BAR); if (*ntype != RIGHTPAREN) { print_error("Expected \")\"", ntoken, *ntype); return NULL; } *ntype = get_token(fp, ntoken, MAXTOKEN); if (size) { if (*ntype != RIGHTPAREN) { print_error("Expected \")\" to terminate SIZE", ntoken, *ntype); return NULL; } *ntype = get_token(fp, ntoken, MAXTOKEN); } } } return NULL; } else { if (type == CONVENTION) { while (type != SYNTAX && type != ENDOFFILE) { if (type == DISPLAYHINT) { type = get_token(fp, token, MAXTOKEN); if (type != QUOTESTRING) { print_error("DISPLAY-HINT must be string", token, type); } else { free(hint); hint = strdup(token); } } else if (type == DESCRIPTION && netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_SAVE_MIB_DESCRS)) { type = get_token(fp, quoted_string_buffer, MAXQUOTESTR); if (type != QUOTESTRING) { print_error("DESCRIPTION must be string", token, type); } else { free(descr); descr = strdup(quoted_string_buffer); } } else type = get_token(fp, quoted_string_buffer, MAXQUOTESTR); } type = get_token(fp, token, MAXTOKEN); if (type == OBJECT) { type = get_token(fp, token, MAXTOKEN); if (type != IDENTIFIER) { print_error("Expected IDENTIFIER", token, type); goto err; } type = OBJID; } } else if (type == OBJECT) { type = get_token(fp, token, MAXTOKEN); if (type != IDENTIFIER) { print_error("Expected IDENTIFIER", token, type); goto err; } type = OBJID; } if (type == LABEL) { type = get_tc(token, current_module, NULL, NULL, NULL, NULL); } /* * textual convention */ for (i = 0; i < MAXTC; i++) { if (tclist[i].type == 0) break; } if (i == MAXTC) { print_error("Too many textual conventions", token, type); goto err; } if (!(type & SYNTAX_MASK)) { print_error("Textual convention doesn't map to real type", token, type); goto err; } tcp = &tclist[i]; tcp->modid = current_module; tcp->descriptor = strdup(name); tcp->hint = hint; tcp->description = descr; tcp->type = type; *ntype = get_token(fp, ntoken, MAXTOKEN); if (*ntype == LEFTPAREN) { tcp->ranges = parse_ranges(fp, &tcp->ranges); *ntype = get_token(fp, ntoken, MAXTOKEN); } else if (*ntype == LEFTBRACKET) { /* * if there is an enumeration list, parse it */ tcp->enums = parse_enumlist(fp, &tcp->enums); *ntype = get_token(fp, ntoken, MAXTOKEN); } return NULL; } err: SNMP_FREE(descr); SNMP_FREE(hint); return NULL; } /* * Parses an OBJECT TYPE macro. * Returns 0 on error. */ static struct node * parse_objecttype(FILE * fp, char *name) { register int type; char token[MAXTOKEN]; char nexttoken[MAXTOKEN]; char quoted_string_buffer[MAXQUOTESTR]; int nexttype, tctype; register struct node *np; type = get_token(fp, token, MAXTOKEN); if (type != SYNTAX) { print_error("Bad format for OBJECT-TYPE", token, type); return NULL; } np = alloc_node(current_module); if (np == NULL) return (NULL); type = get_token(fp, token, MAXTOKEN); if (type == OBJECT) { type = get_token(fp, token, MAXTOKEN); if (type != IDENTIFIER) { print_error("Expected IDENTIFIER", token, type); free_node(np); return NULL; } type = OBJID; } if (type == LABEL) { int tmp_index; tctype = get_tc(token, current_module, &tmp_index, &np->enums, &np->ranges, &np->hint); if (tctype == LABEL && netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_WARNINGS) > 1) { print_error("Warning: No known translation for type", token, type); } type = tctype; np->tc_index = tmp_index; /* store TC for later reference */ } np->type = type; nexttype = get_token(fp, nexttoken, MAXTOKEN); switch (type) { case SEQUENCE: if (nexttype == OF) { nexttype = get_token(fp, nexttoken, MAXTOKEN); nexttype = get_token(fp, nexttoken, MAXTOKEN); } break; case INTEGER: case INTEGER32: case UINTEGER32: case UNSIGNED32: case COUNTER: case GAUGE: case BITSTRING: case LABEL: if (nexttype == LEFTBRACKET) { /* * if there is an enumeration list, parse it */ np->enums = parse_enumlist(fp, &np->enums); nexttype = get_token(fp, nexttoken, MAXTOKEN); } else if (nexttype == LEFTPAREN) { /* * if there is a range list, parse it */ np->ranges = parse_ranges(fp, &np->ranges); nexttype = get_token(fp, nexttoken, MAXTOKEN); } break; case OCTETSTR: case KW_OPAQUE: /* * parse any SIZE specification */ if (nexttype == LEFTPAREN) { nexttype = get_token(fp, nexttoken, MAXTOKEN); if (nexttype == SIZE) { nexttype = get_token(fp, nexttoken, MAXTOKEN); if (nexttype == LEFTPAREN) { np->ranges = parse_ranges(fp, &np->ranges); nexttype = get_token(fp, nexttoken, MAXTOKEN); /* ) */ if (nexttype == RIGHTPAREN) { nexttype = get_token(fp, nexttoken, MAXTOKEN); break; } } } print_error("Bad SIZE syntax", token, type); free_node(np); return NULL; } break; case OBJID: case NETADDR: case IPADDR: case TIMETICKS: case NUL: case NSAPADDRESS: case COUNTER64: break; default: print_error("Bad syntax", token, type); free_node(np); return NULL; } if (nexttype == UNITS) { type = get_token(fp, quoted_string_buffer, MAXQUOTESTR); if (type != QUOTESTRING) { print_error("Bad UNITS", quoted_string_buffer, type); free_node(np); return NULL; } np->units = strdup(quoted_string_buffer); nexttype = get_token(fp, nexttoken, MAXTOKEN); } if (nexttype != ACCESS) { print_error("Should be ACCESS", nexttoken, nexttype); free_node(np); return NULL; } type = get_token(fp, token, MAXTOKEN); if (type != READONLY && type != READWRITE && type != WRITEONLY && type != NOACCESS && type != READCREATE && type != ACCNOTIFY) { print_error("Bad ACCESS type", token, type); free_node(np); return NULL; } np->access = type; type = get_token(fp, token, MAXTOKEN); if (type != STATUS) { print_error("Should be STATUS", token, type); free_node(np); return NULL; } type = get_token(fp, token, MAXTOKEN); if (type != MANDATORY && type != CURRENT && type != KW_OPTIONAL && type != OBSOLETE && type != DEPRECATED) { print_error("Bad STATUS", token, type); free_node(np); return NULL; } np->status = type; /* * Optional parts of the OBJECT-TYPE macro */ type = get_token(fp, token, MAXTOKEN); while (type != EQUALS && type != ENDOFFILE) { switch (type) { case DESCRIPTION: type = get_token(fp, quoted_string_buffer, MAXQUOTESTR); if (type != QUOTESTRING) { print_error("Bad DESCRIPTION", quoted_string_buffer, type); free_node(np); return NULL; } if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_SAVE_MIB_DESCRS)) { np->description = strdup(quoted_string_buffer); } break; case REFERENCE: type = get_token(fp, quoted_string_buffer, MAXQUOTESTR); if (type != QUOTESTRING) { print_error("Bad REFERENCE", quoted_string_buffer, type); free_node(np); return NULL; } np->reference = strdup(quoted_string_buffer); break; case INDEX: if (np->augments) { print_error("Cannot have both INDEX and AUGMENTS", token, type); free_node(np); return NULL; } np->indexes = getIndexes(fp, &np->indexes); if (np->indexes == NULL) { print_error("Bad INDEX list", token, type); free_node(np); return NULL; } break; case AUGMENTS: if (np->indexes) { print_error("Cannot have both INDEX and AUGMENTS", token, type); free_node(np); return NULL; } np->indexes = getIndexes(fp, &np->indexes); if (np->indexes == NULL) { print_error("Bad AUGMENTS list", token, type); free_node(np); return NULL; } np->augments = strdup(np->indexes->ilabel); free_indexes(&np->indexes); break; case DEFVAL: /* * Mark's defVal section */ type = get_token(fp, quoted_string_buffer, MAXTOKEN); if (type != LEFTBRACKET) { print_error("Bad DEFAULTVALUE", quoted_string_buffer, type); free_node(np); return NULL; } { int level = 1; char defbuf[512]; defbuf[0] = 0; while (1) { type = get_token(fp, quoted_string_buffer, MAXTOKEN); if ((type == RIGHTBRACKET && --level == 0) || type == ENDOFFILE) break; else if (type == LEFTBRACKET) level++; if (type == QUOTESTRING) strlcat(defbuf, "\\\"", sizeof(defbuf)); strlcat(defbuf, quoted_string_buffer, sizeof(defbuf)); if (type == QUOTESTRING) strlcat(defbuf, "\\\"", sizeof(defbuf)); strlcat(defbuf, " ", sizeof(defbuf)); } if (type != RIGHTBRACKET) { print_error("Bad DEFAULTVALUE", quoted_string_buffer, type); free_node(np); return NULL; } defbuf[strlen(defbuf) - 1] = 0; np->defaultValue = strdup(defbuf); } break; case NUM_ENTRIES: if (tossObjectIdentifier(fp) != OBJID) { print_error("Bad Object Identifier", token, type); free_node(np); return NULL; } break; default: print_error("Bad format of optional clauses", token, type); free_node(np); return NULL; } type = get_token(fp, token, MAXTOKEN); } if (type != EQUALS) { print_error("Bad format", token, type); free_node(np); return NULL; } return merge_parse_objectid(np, fp, name); } /* * Parses an OBJECT GROUP macro. * Returns 0 on error. * * Also parses object-identity, since they are similar (ignore STATUS). * - WJH 10/96 */ static struct node * parse_objectgroup(FILE * fp, char *name, int what, struct objgroup **ol) { int type; char token[MAXTOKEN]; char quoted_string_buffer[MAXQUOTESTR]; struct node *np; np = alloc_node(current_module); if (np == NULL) return (NULL); type = get_token(fp, token, MAXTOKEN); if (type == what) { type = get_token(fp, token, MAXTOKEN); if (type != LEFTBRACKET) { print_error("Expected \"{\"", token, type); goto skip; } do { struct objgroup *o; type = get_token(fp, token, MAXTOKEN); if (type != LABEL) { print_error("Bad identifier", token, type); goto skip; } o = (struct objgroup *) malloc(sizeof(struct objgroup)); if (!o) { print_error("Resource failure", token, type); goto skip; } o->line = mibLine; o->name = strdup(token); o->next = *ol; *ol = o; type = get_token(fp, token, MAXTOKEN); } while (type == COMMA); if (type != RIGHTBRACKET) { print_error("Expected \"}\" after list", token, type); goto skip; } type = get_token(fp, token, type); } if (type != STATUS) { print_error("Expected STATUS", token, type); goto skip; } type = get_token(fp, token, MAXTOKEN); if (type != CURRENT && type != DEPRECATED && type != OBSOLETE) { print_error("Bad STATUS value", token, type); goto skip; } type = get_token(fp, token, MAXTOKEN); if (type != DESCRIPTION) { print_error("Expected DESCRIPTION", token, type); goto skip; } type = get_token(fp, quoted_string_buffer, MAXQUOTESTR); if (type != QUOTESTRING) { print_error("Bad DESCRIPTION", quoted_string_buffer, type); free_node(np); return NULL; } if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_SAVE_MIB_DESCRS)) { np->description = strdup(quoted_string_buffer); } type = get_token(fp, token, MAXTOKEN); if (type == REFERENCE) { type = get_token(fp, quoted_string_buffer, MAXQUOTESTR); if (type != QUOTESTRING) { print_error("Bad REFERENCE", quoted_string_buffer, type); free_node(np); return NULL; } np->reference = strdup(quoted_string_buffer); type = get_token(fp, token, MAXTOKEN); } if (type != EQUALS) print_error("Expected \"::=\"", token, type); skip: while (type != EQUALS && type != ENDOFFILE) type = get_token(fp, token, MAXTOKEN); return merge_parse_objectid(np, fp, name); } /* * Parses a NOTIFICATION-TYPE macro. * Returns 0 on error. */ static struct node * parse_notificationDefinition(FILE * fp, char *name) { register int type; char token[MAXTOKEN]; char quoted_string_buffer[MAXQUOTESTR]; register struct node *np; np = alloc_node(current_module); if (np == NULL) return (NULL); type = get_token(fp, token, MAXTOKEN); while (type != EQUALS && type != ENDOFFILE) { switch (type) { case DESCRIPTION: type = get_token(fp, quoted_string_buffer, MAXQUOTESTR); if (type != QUOTESTRING) { print_error("Bad DESCRIPTION", quoted_string_buffer, type); free_node(np); return NULL; } if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_SAVE_MIB_DESCRS)) { np->description = strdup(quoted_string_buffer); } break; case REFERENCE: type = get_token(fp, quoted_string_buffer, MAXQUOTESTR); if (type != QUOTESTRING) { print_error("Bad REFERENCE", quoted_string_buffer, type); free_node(np); return NULL; } np->reference = strdup(quoted_string_buffer); break; case OBJECTS: np->varbinds = getVarbinds(fp, &np->varbinds); if (!np->varbinds) { print_error("Bad OBJECTS list", token, type); free_node(np); return NULL; } break; default: /* * NOTHING */ break; } type = get_token(fp, token, MAXTOKEN); } return merge_parse_objectid(np, fp, name); } /* * Parses a TRAP-TYPE macro. * Returns 0 on error. */ static struct node * parse_trapDefinition(FILE * fp, char *name) { register int type; char token[MAXTOKEN]; char quoted_string_buffer[MAXQUOTESTR]; register struct node *np; np = alloc_node(current_module); if (np == NULL) return (NULL); type = get_token(fp, token, MAXTOKEN); while (type != EQUALS && type != ENDOFFILE) { switch (type) { case DESCRIPTION: type = get_token(fp, quoted_string_buffer, MAXQUOTESTR); if (type != QUOTESTRING) { print_error("Bad DESCRIPTION", quoted_string_buffer, type); free_node(np); return NULL; } if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_SAVE_MIB_DESCRS)) { np->description = strdup(quoted_string_buffer); } break; case REFERENCE: /* I'm not sure REFERENCEs are legal in smiv1 traps??? */ type = get_token(fp, quoted_string_buffer, MAXQUOTESTR); if (type != QUOTESTRING) { print_error("Bad REFERENCE", quoted_string_buffer, type); free_node(np); return NULL; } np->reference = strdup(quoted_string_buffer); break; case ENTERPRISE: type = get_token(fp, token, MAXTOKEN); if (type == LEFTBRACKET) { type = get_token(fp, token, MAXTOKEN); if (type != LABEL) { print_error("Bad Trap Format", token, type); free_node(np); return NULL; } np->parent = strdup(token); /* * Get right bracket */ type = get_token(fp, token, MAXTOKEN); } else if (type == LABEL) { np->parent = strdup(token); } else { free_node(np); return NULL; } break; case VARIABLES: np->varbinds = getVarbinds(fp, &np->varbinds); if (!np->varbinds) { print_error("Bad VARIABLES list", token, type); free_node(np); return NULL; } break; default: /* * NOTHING */ break; } type = get_token(fp, token, MAXTOKEN); } type = get_token(fp, token, MAXTOKEN); np->label = strdup(name); if (type != NUMBER) { print_error("Expected a Number", token, type); free_node(np); return NULL; } np->subid = strtoul(token, NULL, 10); np->next = alloc_node(current_module); if (np->next == NULL) { free_node(np); return (NULL); } /* Catch the syntax error */ if (np->parent == NULL) { free_node(np->next); free_node(np); gMibError = MODULE_SYNTAX_ERROR; return (NULL); } np->next->parent = np->parent; np->parent = (char *) malloc(strlen(np->parent) + 2); if (np->parent == NULL) { free_node(np->next); free_node(np); return (NULL); } strcpy(np->parent, np->next->parent); strcat(np->parent, "#"); np->next->label = strdup(np->parent); return np; } /* * Parses a compliance macro * Returns 0 on error. */ static int eat_syntax(FILE * fp, char *token, int maxtoken) { int type, nexttype; struct node *np = alloc_node(current_module); char nexttoken[MAXTOKEN]; if (!np) return 0; type = get_token(fp, token, maxtoken); nexttype = get_token(fp, nexttoken, MAXTOKEN); switch (type) { case INTEGER: case INTEGER32: case UINTEGER32: case UNSIGNED32: case COUNTER: case GAUGE: case BITSTRING: case LABEL: if (nexttype == LEFTBRACKET) { /* * if there is an enumeration list, parse it */ np->enums = parse_enumlist(fp, &np->enums); nexttype = get_token(fp, nexttoken, MAXTOKEN); } else if (nexttype == LEFTPAREN) { /* * if there is a range list, parse it */ np->ranges = parse_ranges(fp, &np->ranges); nexttype = get_token(fp, nexttoken, MAXTOKEN); } break; case OCTETSTR: case KW_OPAQUE: /* * parse any SIZE specification */ if (nexttype == LEFTPAREN) { nexttype = get_token(fp, nexttoken, MAXTOKEN); if (nexttype == SIZE) { nexttype = get_token(fp, nexttoken, MAXTOKEN); if (nexttype == LEFTPAREN) { np->ranges = parse_ranges(fp, &np->ranges); nexttype = get_token(fp, nexttoken, MAXTOKEN); /* ) */ if (nexttype == RIGHTPAREN) { nexttype = get_token(fp, nexttoken, MAXTOKEN); break; } } } print_error("Bad SIZE syntax", token, type); free_node(np); return nexttype; } break; case OBJID: case NETADDR: case IPADDR: case TIMETICKS: case NUL: case NSAPADDRESS: case COUNTER64: break; default: print_error("Bad syntax", token, type); free_node(np); return nexttype; } free_node(np); return nexttype; } static int compliance_lookup(const char *name, int modid) { if (modid == -1) { struct objgroup *op = (struct objgroup *) malloc(sizeof(struct objgroup)); if (!op) return 0; op->next = objgroups; op->name = strdup(name); op->line = mibLine; objgroups = op; return 1; } else return find_tree_node(name, modid) != NULL; } static struct node * parse_compliance(FILE * fp, char *name) { int type; char token[MAXTOKEN]; char quoted_string_buffer[MAXQUOTESTR]; struct node *np; np = alloc_node(current_module); if (np == NULL) return (NULL); type = get_token(fp, token, MAXTOKEN); if (type != STATUS) { print_error("Expected STATUS", token, type); goto skip; } type = get_token(fp, token, MAXTOKEN); if (type != CURRENT && type != DEPRECATED && type != OBSOLETE) { print_error("Bad STATUS", token, type); goto skip; } type = get_token(fp, token, MAXTOKEN); if (type != DESCRIPTION) { print_error("Expected DESCRIPTION", token, type); goto skip; } type = get_token(fp, quoted_string_buffer, MAXQUOTESTR); if (type != QUOTESTRING) { print_error("Bad DESCRIPTION", quoted_string_buffer, type); goto skip; } if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_SAVE_MIB_DESCRS)) np->description = strdup(quoted_string_buffer); type = get_token(fp, token, MAXTOKEN); if (type == REFERENCE) { type = get_token(fp, quoted_string_buffer, MAXTOKEN); if (type != QUOTESTRING) { print_error("Bad REFERENCE", quoted_string_buffer, type); goto skip; } np->reference = strdup(quoted_string_buffer); type = get_token(fp, token, MAXTOKEN); } if (type != MODULE) { print_error("Expected MODULE", token, type); goto skip; } while (type == MODULE) { int modid = -1; char modname[MAXTOKEN]; type = get_token(fp, token, MAXTOKEN); if (type == LABEL && strcmp(token, module_name(current_module, modname))) { modid = read_module_internal(token); if (modid != MODULE_LOADED_OK && modid != MODULE_ALREADY_LOADED) { print_error("Unknown module", token, type); goto skip; } modid = which_module(token); type = get_token(fp, token, MAXTOKEN); } if (type == MANDATORYGROUPS) { type = get_token(fp, token, MAXTOKEN); if (type != LEFTBRACKET) { print_error("Expected \"{\"", token, type); goto skip; } do { type = get_token(fp, token, MAXTOKEN); if (type != LABEL) { print_error("Bad group name", token, type); goto skip; } if (!compliance_lookup(token, modid)) print_error("Unknown group", token, type); type = get_token(fp, token, MAXTOKEN); } while (type == COMMA); if (type != RIGHTBRACKET) { print_error("Expected \"}\"", token, type); goto skip; } type = get_token(fp, token, MAXTOKEN); } while (type == GROUP || type == OBJECT) { if (type == GROUP) { type = get_token(fp, token, MAXTOKEN); if (type != LABEL) { print_error("Bad group name", token, type); goto skip; } if (!compliance_lookup(token, modid)) print_error("Unknown group", token, type); type = get_token(fp, token, MAXTOKEN); } else { type = get_token(fp, token, MAXTOKEN); if (type != LABEL) { print_error("Bad object name", token, type); goto skip; } if (!compliance_lookup(token, modid)) print_error("Unknown group", token, type); type = get_token(fp, token, MAXTOKEN); if (type == SYNTAX) type = eat_syntax(fp, token, MAXTOKEN); if (type == WRSYNTAX) type = eat_syntax(fp, token, MAXTOKEN); if (type == MINACCESS) { type = get_token(fp, token, MAXTOKEN); if (type != NOACCESS && type != ACCNOTIFY && type != READONLY && type != WRITEONLY && type != READCREATE && type != READWRITE) { print_error("Bad MIN-ACCESS spec", token, type); goto skip; } type = get_token(fp, token, MAXTOKEN); } } if (type != DESCRIPTION) { print_error("Expected DESCRIPTION", token, type); goto skip; } type = get_token(fp, token, MAXTOKEN); if (type != QUOTESTRING) { print_error("Bad DESCRIPTION", token, type); goto skip; } type = get_token(fp, token, MAXTOKEN); } } skip: while (type != EQUALS && type != ENDOFFILE) type = get_token(fp, quoted_string_buffer, MAXQUOTESTR); return merge_parse_objectid(np, fp, name); } /* * Parses a capabilities macro * Returns 0 on error. */ static struct node * parse_capabilities(FILE * fp, char *name) { int type; char token[MAXTOKEN]; char quoted_string_buffer[MAXQUOTESTR]; struct node *np; np = alloc_node(current_module); if (np == NULL) return (NULL); type = get_token(fp, token, MAXTOKEN); if (type != PRODREL) { print_error("Expected PRODUCT-RELEASE", token, type); goto skip; } type = get_token(fp, token, MAXTOKEN); if (type != QUOTESTRING) { print_error("Expected STRING after PRODUCT-RELEASE", token, type); goto skip; } type = get_token(fp, token, MAXTOKEN); if (type != STATUS) { print_error("Expected STATUS", token, type); goto skip; } type = get_token(fp, token, MAXTOKEN); if (type != CURRENT && type != OBSOLETE) { print_error("STATUS should be current or obsolete", token, type); goto skip; } type = get_token(fp, token, MAXTOKEN); if (type != DESCRIPTION) { print_error("Expected DESCRIPTION", token, type); goto skip; } type = get_token(fp, quoted_string_buffer, MAXTOKEN); if (type != QUOTESTRING) { print_error("Bad DESCRIPTION", quoted_string_buffer, type); goto skip; } if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_SAVE_MIB_DESCRS)) { np->description = strdup(quoted_string_buffer); } type = get_token(fp, token, MAXTOKEN); if (type == REFERENCE) { type = get_token(fp, quoted_string_buffer, MAXTOKEN); if (type != QUOTESTRING) { print_error("Bad REFERENCE", quoted_string_buffer, type); goto skip; } np->reference = strdup(quoted_string_buffer); type = get_token(fp, token, type); } while (type == SUPPORTS) { int modid; struct tree *tp; type = get_token(fp, token, MAXTOKEN); if (type != LABEL) { print_error("Bad module name", token, type); goto skip; } modid = read_module_internal(token); if (modid != MODULE_LOADED_OK && modid != MODULE_ALREADY_LOADED) { print_error("Module not found", token, type); goto skip; } modid = which_module(token); type = get_token(fp, token, MAXTOKEN); if (type != INCLUDES) { print_error("Expected INCLUDES", token, type); goto skip; } type = get_token(fp, token, MAXTOKEN); if (type != LEFTBRACKET) { print_error("Expected \"{\"", token, type); goto skip; } do { type = get_token(fp, token, MAXTOKEN); if (type != LABEL) { print_error("Expected group name", token, type); goto skip; } tp = find_tree_node(token, modid); if (!tp) print_error("Group not found in module", token, type); type = get_token(fp, token, MAXTOKEN); } while (type == COMMA); if (type != RIGHTBRACKET) { print_error("Expected \"}\" after group list", token, type); goto skip; } type = get_token(fp, token, MAXTOKEN); while (type == VARIATION) { type = get_token(fp, token, MAXTOKEN); if (type != LABEL) { print_error("Bad object name", token, type); goto skip; } tp = find_tree_node(token, modid); if (!tp) print_error("Object not found in module", token, type); type = get_token(fp, token, MAXTOKEN); if (type == SYNTAX) { type = eat_syntax(fp, token, MAXTOKEN); } if (type == WRSYNTAX) { type = eat_syntax(fp, token, MAXTOKEN); } if (type == ACCESS) { type = get_token(fp, token, MAXTOKEN); if (type != ACCNOTIFY && type != READONLY && type != READWRITE && type != READCREATE && type != WRITEONLY && type != NOTIMPL) { print_error("Bad ACCESS", token, type); goto skip; } type = get_token(fp, token, MAXTOKEN); } if (type == CREATEREQ) { type = get_token(fp, token, MAXTOKEN); if (type != LEFTBRACKET) { print_error("Expected \"{\"", token, type); goto skip; } do { type = get_token(fp, token, MAXTOKEN); if (type != LABEL) { print_error("Bad object name in list", token, type); goto skip; } type = get_token(fp, token, MAXTOKEN); } while (type == COMMA); if (type != RIGHTBRACKET) { print_error("Expected \"}\" after list", token, type); goto skip; } type = get_token(fp, token, MAXTOKEN); } if (type == DEFVAL) { int level = 1; type = get_token(fp, token, MAXTOKEN); if (type != LEFTBRACKET) { print_error("Expected \"{\" after DEFVAL", token, type); goto skip; } do { type = get_token(fp, token, MAXTOKEN); if (type == LEFTBRACKET) level++; else if (type == RIGHTBRACKET) level--; } while ((type != RIGHTBRACKET || level != 0) && type != ENDOFFILE); if (type != RIGHTBRACKET) { print_error("Missing \"}\" after DEFVAL", token, type); goto skip; } type = get_token(fp, token, MAXTOKEN); } if (type != DESCRIPTION) { print_error("Expected DESCRIPTION", token, type); goto skip; } type = get_token(fp, quoted_string_buffer, MAXTOKEN); if (type != QUOTESTRING) { print_error("Bad DESCRIPTION", quoted_string_buffer, type); goto skip; } type = get_token(fp, token, MAXTOKEN); } } if (type != EQUALS) print_error("Expected \"::=\"", token, type); skip: while (type != EQUALS && type != ENDOFFILE) { type = get_token(fp, quoted_string_buffer, MAXQUOTESTR); } return merge_parse_objectid(np, fp, name); } /* * Parses a module identity macro * Returns 0 on error. */ static void check_utc(const char *utc) { int len, year, month, day, hour, minute; len = strlen(utc); if (utc[len - 1] != 'Z' && utc[len - 1] != 'z') { print_error("Timestamp should end with Z", utc, QUOTESTRING); return; } if (len == 11) { len = sscanf(utc, "%2d%2d%2d%2d%2dZ", &year, &month, &day, &hour, &minute); year += 1900; } else if (len == 13) len = sscanf(utc, "%4d%2d%2d%2d%2dZ", &year, &month, &day, &hour, &minute); else { print_error("Bad timestamp format (11 or 13 characters)", utc, QUOTESTRING); return; } if (len != 5) { print_error("Bad timestamp format", utc, QUOTESTRING); return; } if (month < 1 || month > 12) print_error("Bad month in timestamp", utc, QUOTESTRING); if (day < 1 || day > 31) print_error("Bad day in timestamp", utc, QUOTESTRING); if (hour < 0 || hour > 23) print_error("Bad hour in timestamp", utc, QUOTESTRING); if (minute < 0 || minute > 59) print_error("Bad minute in timestamp", utc, QUOTESTRING); } static struct node * parse_moduleIdentity(FILE * fp, char *name) { register int type; char token[MAXTOKEN]; char quoted_string_buffer[MAXQUOTESTR]; register struct node *np; np = alloc_node(current_module); if (np == NULL) return (NULL); type = get_token(fp, token, MAXTOKEN); if (type != LASTUPDATED) { print_error("Expected LAST-UPDATED", token, type); goto skip; } type = get_token(fp, token, MAXTOKEN); if (type != QUOTESTRING) { print_error("Need STRING for LAST-UPDATED", token, type); goto skip; } check_utc(token); type = get_token(fp, token, MAXTOKEN); if (type != ORGANIZATION) { print_error("Expected ORGANIZATION", token, type); goto skip; } type = get_token(fp, token, MAXTOKEN); if (type != QUOTESTRING) { print_error("Bad ORGANIZATION", token, type); goto skip; } type = get_token(fp, token, MAXTOKEN); if (type != CONTACTINFO) { print_error("Expected CONTACT-INFO", token, type); goto skip; } type = get_token(fp, quoted_string_buffer, MAXQUOTESTR); if (type != QUOTESTRING) { print_error("Bad CONTACT-INFO", quoted_string_buffer, type); goto skip; } type = get_token(fp, token, MAXTOKEN); if (type != DESCRIPTION) { print_error("Expected DESCRIPTION", token, type); goto skip; } type = get_token(fp, quoted_string_buffer, MAXQUOTESTR); if (type != QUOTESTRING) { print_error("Bad DESCRIPTION", quoted_string_buffer, type); goto skip; } if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_SAVE_MIB_DESCRS)) { np->description = strdup(quoted_string_buffer); } type = get_token(fp, token, MAXTOKEN); while (type == REVISION) { type = get_token(fp, token, MAXTOKEN); if (type != QUOTESTRING) { print_error("Bad REVISION", token, type); goto skip; } check_utc(token); type = get_token(fp, token, MAXTOKEN); if (type != DESCRIPTION) { print_error("Expected DESCRIPTION", token, type); goto skip; } type = get_token(fp, quoted_string_buffer, MAXQUOTESTR); if (type != QUOTESTRING) { print_error("Bad DESCRIPTION", quoted_string_buffer, type); goto skip; } type = get_token(fp, token, MAXTOKEN); } if (type != EQUALS) print_error("Expected \"::=\"", token, type); skip: while (type != EQUALS && type != ENDOFFILE) { type = get_token(fp, quoted_string_buffer, MAXQUOTESTR); } return merge_parse_objectid(np, fp, name); } /* * Parses a MACRO definition * Expect BEGIN, discard everything to end. * Returns 0 on error. */ static struct node * parse_macro(FILE * fp, char *name) { register int type; char token[MAXTOKEN]; struct node *np; int iLine = mibLine; np = alloc_node(current_module); if (np == NULL) return (NULL); type = get_token(fp, token, sizeof(token)); while (type != EQUALS && type != ENDOFFILE) { type = get_token(fp, token, sizeof(token)); } if (type != EQUALS) { if (np) free_node(np); return NULL; } while (type != BEGIN && type != ENDOFFILE) { type = get_token(fp, token, sizeof(token)); } if (type != BEGIN) { if (np) free_node(np); return NULL; } while (type != END && type != ENDOFFILE) { type = get_token(fp, token, sizeof(token)); } if (type != END) { if (np) free_node(np); return NULL; } if (netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_WARNINGS)) { snmp_log(LOG_WARNING, "%s MACRO (lines %d..%d parsed and ignored).\n", name, iLine, mibLine); } return np; } /* * Parses a module import clause * loading any modules referenced */ static void parse_imports(FILE * fp) { register int type; char token[MAXTOKEN]; char modbuf[256]; #define MAX_IMPORTS 256 struct module_import import_list[MAX_IMPORTS]; int this_module; struct module *mp; int import_count = 0; /* Total number of imported descriptors */ int i = 0, old_i; /* index of first import from each module */ type = get_token(fp, token, MAXTOKEN); /* * Parse the IMPORTS clause */ while (type != SEMI && type != ENDOFFILE) { if (type == LABEL) { if (import_count == MAX_IMPORTS) { print_error("Too many imported symbols", token, type); do { type = get_token(fp, token, MAXTOKEN); } while (type != SEMI && type != ENDOFFILE); return; } import_list[import_count++].label = strdup(token); } else if (type == FROM) { type = get_token(fp, token, MAXTOKEN); if (import_count == i) { /* All imports are handled internally */ type = get_token(fp, token, MAXTOKEN); continue; } this_module = which_module(token); for (old_i = i; i < import_count; ++i) import_list[i].modid = this_module; /* * Recursively read any pre-requisite modules */ if (read_module_internal(token) == MODULE_NOT_FOUND) { int found = 0; for (; old_i < import_count; ++old_i) { found += read_import_replacements(token, &import_list[old_i]); } if (!found) print_module_not_found(token); } } type = get_token(fp, token, MAXTOKEN); } /* Initialize modid in case the module name was missing. */ for (; i < import_count; ++i) import_list[i].modid = -1; /* * Save the import information * in the global module table */ for (mp = module_head; mp; mp = mp->next) if (mp->modid == current_module) { if (import_count == 0) return; if (mp->imports && (mp->imports != root_imports)) { /* * this can happen if all modules are in one source file. */ for (i = 0; i < mp->no_imports; ++i) { DEBUGMSGTL(("parse-mibs", "#### freeing Module %d '%s' %d\n", mp->modid, mp->imports[i].label, mp->imports[i].modid)); free((char *) mp->imports[i].label); } free((char *) mp->imports); } mp->imports = (struct module_import *) calloc(import_count, sizeof(struct module_import)); if (mp->imports == NULL) return; for (i = 0; i < import_count; ++i) { mp->imports[i].label = import_list[i].label; mp->imports[i].modid = import_list[i].modid; DEBUGMSGTL(("parse-mibs", "#### adding Module %d '%s' %d\n", mp->modid, mp->imports[i].label, mp->imports[i].modid)); } mp->no_imports = import_count; return; } /* * Shouldn't get this far */ print_module_not_found(module_name(current_module, modbuf)); return; } /* * MIB module handling routines */ static void dump_module_list(void) { struct module *mp = module_head; DEBUGMSGTL(("parse-mibs", "Module list:\n")); while (mp) { DEBUGMSGTL(("parse-mibs", " %s %d %s %d\n", mp->name, mp->modid, mp->file, mp->no_imports)); mp = mp->next; } } int which_module(const char *name) { struct module *mp; for (mp = module_head; mp; mp = mp->next) if (!label_compare(mp->name, name)) return (mp->modid); DEBUGMSGTL(("parse-mibs", "Module %s not found\n", name)); return (-1); } /* * module_name - copy module name to user buffer, return ptr to same. */ char * module_name(int modid, char *cp) { struct module *mp; for (mp = module_head; mp; mp = mp->next) if (mp->modid == modid) { strcpy(cp, mp->name); return (cp); } if (modid != -1) DEBUGMSGTL(("parse-mibs", "Module %d not found\n", modid)); sprintf(cp, "#%d", modid); return (cp); } /* * Backwards compatability * Read newer modules that replace the one specified:- * either all of them (read_module_replacements), * or those relating to a specified identifier (read_import_replacements) * plus an interface to add new replacement requirements */ netsnmp_feature_child_of(parse_add_module_replacement, netsnmp_unused) #ifndef NETSNMP_FEATURE_REMOVE_PARSE_ADD_MODULE_REPLACEMENT void add_module_replacement(const char *old_module, const char *new_module_name, const char *tag, int len) { struct module_compatability *mcp; mcp = (struct module_compatability *) calloc(1, sizeof(struct module_compatability)); if (mcp == NULL) return; mcp->old_module = strdup(old_module); mcp->new_module = strdup(new_module_name); if (tag) mcp->tag = strdup(tag); mcp->tag_len = len; mcp->next = module_map_head; module_map_head = mcp; } #endif /* NETSNMP_FEATURE_REMOVE_PARSE_ADD_MODULE_REPLACEMENT */ static int read_module_replacements(const char *name) { struct module_compatability *mcp; for (mcp = module_map_head; mcp; mcp = mcp->next) { if (!label_compare(mcp->old_module, name)) { if (netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_WARNINGS)) { snmp_log(LOG_WARNING, "Loading replacement module %s for %s (%s)\n", mcp->new_module, name, File); } (void) netsnmp_read_module(mcp->new_module); return 1; } } return 0; } static int read_import_replacements(const char *old_module_name, struct module_import *identifier) { struct module_compatability *mcp; /* * Look for matches first */ for (mcp = module_map_head; mcp; mcp = mcp->next) { if (!label_compare(mcp->old_module, old_module_name)) { if ( /* exact match */ (mcp->tag_len == 0 && (mcp->tag == NULL || !label_compare(mcp->tag, identifier->label))) || /* * prefix match */ (mcp->tag_len != 0 && !strncmp(mcp->tag, identifier->label, mcp->tag_len)) ) { if (netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_WARNINGS)) { snmp_log(LOG_WARNING, "Importing %s from replacement module %s instead of %s (%s)\n", identifier->label, mcp->new_module, old_module_name, File); } (void) netsnmp_read_module(mcp->new_module); identifier->modid = which_module(mcp->new_module); return 1; /* finished! */ } } } /* * If no exact match, load everything relevant */ return read_module_replacements(old_module_name); } /* * Read in the named module * Returns the root of the whole tree * (by analogy with 'read_mib') */ static int read_module_internal(const char *name) { struct module *mp; FILE *fp; struct node *np; netsnmp_init_mib_internals(); for (mp = module_head; mp; mp = mp->next) if (!label_compare(mp->name, name)) { const char *oldFile = File; int oldLine = mibLine; int oldModule = current_module; if (mp->no_imports != -1) { DEBUGMSGTL(("parse-mibs", "Module %s already loaded\n", name)); return MODULE_ALREADY_LOADED; } if ((fp = fopen(mp->file, "r")) == NULL) { int rval; if (errno == ENOTDIR || errno == ENOENT) rval = MODULE_NOT_FOUND; else rval = MODULE_LOAD_FAILED; snmp_log_perror(mp->file); return rval; } #ifdef HAVE_FLOCKFILE flockfile(fp); #endif mp->no_imports = 0; /* Note that we've read the file */ File = mp->file; mibLine = 1; current_module = mp->modid; /* * Parse the file */ np = parse(fp, NULL); #ifdef HAVE_FUNLOCKFILE funlockfile(fp); #endif fclose(fp); File = oldFile; mibLine = oldLine; current_module = oldModule; if ((np == NULL) && (gMibError == MODULE_SYNTAX_ERROR) ) return MODULE_SYNTAX_ERROR; return MODULE_LOADED_OK; } return MODULE_NOT_FOUND; } void adopt_orphans(void) { struct node *np, *onp; struct tree *tp; int i, adopted = 1; if (!orphan_nodes) return; init_node_hash(orphan_nodes); orphan_nodes = NULL; while (adopted) { adopted = 0; for (i = 0; i < NHASHSIZE; i++) if (nbuckets[i]) { for (np = nbuckets[i]; np != NULL; np = np->next) { tp = find_tree_node(np->parent, -1); if (tp) { do_subtree(tp, &np); adopted = 1; /* * if do_subtree adopted the entire bucket, stop */ if(NULL == nbuckets[i]) break; /* * do_subtree may modify nbuckets, and if np * was adopted, np->next probably isn't an orphan * anymore. if np is still in the bucket (do_subtree * didn't adopt it) keep on plugging. otherwise * start over, at the top of the bucket. */ for(onp = nbuckets[i]; onp; onp = onp->next) if(onp == np) break; if(NULL == onp) { /* not in the list */ np = nbuckets[i]; /* start over */ } } } } } /* * Report on outstanding orphans * and link them back into the orphan list */ for (i = 0; i < NHASHSIZE; i++) if (nbuckets[i]) { if (orphan_nodes) onp = np->next = nbuckets[i]; else onp = orphan_nodes = nbuckets[i]; nbuckets[i] = NULL; while (onp) { char modbuf[256]; snmp_log(LOG_WARNING, "Cannot adopt OID in %s: %s ::= { %s %ld }\n", module_name(onp->modid, modbuf), (onp->label ? onp->label : "<no label>"), (onp->parent ? onp->parent : "<no parent>"), onp->subid); np = onp; onp = onp->next; } } } #ifndef NETSNMP_NO_LEGACY_DEFINITIONS struct tree * read_module(const char *name) { return netsnmp_read_module(name); } #endif struct tree * netsnmp_read_module(const char *name) { int status = 0; status = read_module_internal(name); if (status == MODULE_NOT_FOUND) { if (!read_module_replacements(name)) print_module_not_found(name); } else if (status == MODULE_SYNTAX_ERROR) { gMibError = 0; gLoop = 1; strncat(gMibNames, " ", sizeof(gMibNames) - strlen(gMibNames) - 1); strncat(gMibNames, name, sizeof(gMibNames) - strlen(gMibNames) - 1); } return tree_head; } /* * Prototype definition */ void unload_module_by_ID(int modID, struct tree *tree_top); void unload_module_by_ID(int modID, struct tree *tree_top) { struct tree *tp, *next; int i; for (tp = tree_top; tp; tp = next) { /* * Essentially, this is equivalent to the code fragment: * if (tp->modID == modID) * tp->number_modules--; * but handles one tree node being part of several modules, * and possible multiple copies of the same module ID. */ int nmod = tp->number_modules; if (nmod > 0) { /* in some module */ /* * Remove all copies of this module ID */ int cnt = 0, *pi1, *pi2 = tp->module_list; for (i = 0, pi1 = pi2; i < nmod; i++, pi2++) { if (*pi2 == modID) continue; cnt++; *pi1++ = *pi2; } if (nmod != cnt) { /* in this module */ /* * if ( (nmod - cnt) > 1) * printf("Dup modid %d, %d times, '%s'\n", tp->modid, (nmod-cnt), tp->label); fflush(stdout); ?* XXDEBUG */ tp->number_modules = cnt; switch (cnt) { case 0: tp->module_list[0] = -1; /* Mark unused, */ /* FALL THROUGH */ case 1: /* save the remaining module */ if (&(tp->modid) != tp->module_list) { tp->modid = tp->module_list[0]; free(tp->module_list); tp->module_list = &(tp->modid); } break; default: break; } } /* if tree node is in this module */ } /* * if tree node is in some module */ next = tp->next_peer; /* * OK - that's dealt with *this* node. * Now let's look at the children. * (Isn't recursion wonderful!) */ if (tp->child_list) unload_module_by_ID(modID, tp->child_list); if (tp->number_modules == 0) { /* * This node isn't needed any more (except perhaps * for the sake of the children) */ if (tp->child_list == NULL) { unlink_tree(tp); free_tree(tp); } else { free_partial_tree(tp, TRUE); } } } } #ifndef NETSNMP_NO_LEGACY_DEFINITIONS int unload_module(const char *name) { return netsnmp_unload_module(name); } #endif int netsnmp_unload_module(const char *name) { struct module *mp; int modID = -1; for (mp = module_head; mp; mp = mp->next) if (!label_compare(mp->name, name)) { modID = mp->modid; break; } if (modID == -1) { DEBUGMSGTL(("unload-mib", "Module %s not found to unload\n", name)); return MODULE_NOT_FOUND; } unload_module_by_ID(modID, tree_head); mp->no_imports = -1; /* mark as unloaded */ return MODULE_LOADED_OK; /* Well, you know what I mean! */ } /* * Clear module map, tree nodes, textual convention table. */ void unload_all_mibs(void) { struct module *mp; struct module_compatability *mcp; struct tc *ptc; unsigned int i; for (mcp = module_map_head; mcp; mcp = module_map_head) { if (mcp == module_map) break; module_map_head = mcp->next; if (mcp->tag) free(NETSNMP_REMOVE_CONST(char *, mcp->tag)); free(NETSNMP_REMOVE_CONST(char *, mcp->old_module)); free(NETSNMP_REMOVE_CONST(char *, mcp->new_module)); free(mcp); } for (mp = module_head; mp; mp = module_head) { struct module_import *mi = mp->imports; if (mi) { for (i = 0; i < (unsigned int)mp->no_imports; ++i) { SNMP_FREE((mi + i)->label); } mp->no_imports = 0; if (mi == root_imports) memset(mi, 0, sizeof(*mi)); else free(mi); } unload_module_by_ID(mp->modid, tree_head); module_head = mp->next; free(mp->name); free(mp->file); free(mp); } unload_module_by_ID(-1, tree_head); /* * tree nodes are cleared */ for (i = 0, ptc = tclist; i < MAXTC; i++, ptc++) { if (ptc->type == 0) continue; free_enums(&ptc->enums); free_ranges(&ptc->ranges); free(ptc->descriptor); if (ptc->hint) free(ptc->hint); if (ptc->description) free(ptc->description); } memset(tclist, 0, MAXTC * sizeof(struct tc)); memset(buckets, 0, sizeof(buckets)); memset(nbuckets, 0, sizeof(nbuckets)); memset(tbuckets, 0, sizeof(tbuckets)); for (i = 0; i < sizeof(root_imports) / sizeof(root_imports[0]); i++) { SNMP_FREE(root_imports[i].label); } max_module = 0; current_module = 0; module_map_head = NULL; SNMP_FREE(last_err_module); } static void new_module(const char *name, const char *file) { struct module *mp; for (mp = module_head; mp; mp = mp->next) if (!label_compare(mp->name, name)) { DEBUGMSGTL(("parse-mibs", " Module %s already noted\n", name)); /* * Not the same file */ if (label_compare(mp->file, file)) { DEBUGMSGTL(("parse-mibs", " %s is now in %s\n", name, file)); if (netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_WARNINGS)) { snmp_log(LOG_WARNING, "Warning: Module %s was in %s now is %s\n", name, mp->file, file); } /* * Use the new one in preference */ free(mp->file); mp->file = strdup(file); } return; } /* * Add this module to the list */ DEBUGMSGTL(("parse-mibs", " Module %d %s is in %s\n", max_module, name, file)); mp = (struct module *) calloc(1, sizeof(struct module)); if (mp == NULL) return; mp->name = strdup(name); mp->file = strdup(file); mp->imports = NULL; mp->no_imports = -1; /* Not yet loaded */ mp->modid = max_module; ++max_module; mp->next = module_head; /* Or add to the *end* of the list? */ module_head = mp; } static void scan_objlist(struct node *root, struct module *mp, struct objgroup *list, const char *error) { int oLine = mibLine; while (list) { struct objgroup *gp = list; struct node *np; list = list->next; np = root; while (np) if (label_compare(np->label, gp->name)) np = np->next; else break; if (!np) { int i; struct module_import *mip; /* if not local, check if it was IMPORTed */ for (i = 0, mip = mp->imports; i < mp->no_imports; i++, mip++) if (strcmp(mip->label, gp->name) == 0) break; if (i == mp->no_imports) { mibLine = gp->line; print_error(error, gp->name, QUOTESTRING); } } free(gp->name); free(gp); } mibLine = oLine; } /* * Parses a mib file and returns a linked list of nodes found in the file. * Returns NULL on error. */ static struct node * parse(FILE * fp, struct node *root) { #ifdef TEST extern void xmalloc_stats(FILE *); #endif char token[MAXTOKEN]; char name[MAXTOKEN+1]; int type = LABEL; int lasttype = LABEL; #define BETWEEN_MIBS 1 #define IN_MIB 2 int state = BETWEEN_MIBS; struct node *np, *nnp; struct objgroup *oldgroups = NULL, *oldobjects = NULL, *oldnotifs = NULL; DEBUGMSGTL(("parse-file", "Parsing file: %s...\n", File)); if (last_err_module) free(last_err_module); last_err_module = NULL; np = root; if (np != NULL) { /* * now find end of chain */ while (np->next) np = np->next; } while (type != ENDOFFILE) { if (lasttype == CONTINUE) lasttype = type; else type = lasttype = get_token(fp, token, MAXTOKEN); switch (type) { case END: if (state != IN_MIB) { print_error("Error, END before start of MIB", NULL, type); gMibError = MODULE_SYNTAX_ERROR; return NULL; } else { struct module *mp; #ifdef TEST printf("\nNodes for Module %s:\n", name); print_nodes(stdout, root); #endif for (mp = module_head; mp; mp = mp->next) if (mp->modid == current_module) break; scan_objlist(root, mp, objgroups, "Undefined OBJECT-GROUP"); scan_objlist(root, mp, objects, "Undefined OBJECT"); scan_objlist(root, mp, notifs, "Undefined NOTIFICATION"); objgroups = oldgroups; objects = oldobjects; notifs = oldnotifs; do_linkup(mp, root); np = root = NULL; } state = BETWEEN_MIBS; #ifdef TEST if (netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_WARNINGS)) { /* xmalloc_stats(stderr); */ } #endif continue; case IMPORTS: parse_imports(fp); continue; case EXPORTS: while (type != SEMI && type != ENDOFFILE) type = get_token(fp, token, MAXTOKEN); continue; case LABEL: case INTEGER: case INTEGER32: case UINTEGER32: case UNSIGNED32: case COUNTER: case COUNTER64: case GAUGE: case IPADDR: case NETADDR: case NSAPADDRESS: case OBJSYNTAX: case APPSYNTAX: case SIMPLESYNTAX: case OBJNAME: case NOTIFNAME: case KW_OPAQUE: case TIMETICKS: break; case ENDOFFILE: continue; default: strlcpy(name, token, sizeof(name)); type = get_token(fp, token, MAXTOKEN); nnp = NULL; if (type == MACRO) { nnp = parse_macro(fp, name); if (nnp == NULL) { print_error("Bad parse of MACRO", NULL, type); gMibError = MODULE_SYNTAX_ERROR; /* * return NULL; */ } free_node(nnp); /* IGNORE */ nnp = NULL; } else print_error(name, "is a reserved word", lasttype); continue; /* see if we can parse the rest of the file */ } strlcpy(name, token, sizeof(name)); type = get_token(fp, token, MAXTOKEN); nnp = NULL; /* * Handle obsolete method to assign an object identifier to a * module */ if (lasttype == LABEL && type == LEFTBRACKET) { while (type != RIGHTBRACKET && type != ENDOFFILE) type = get_token(fp, token, MAXTOKEN); if (type == ENDOFFILE) { print_error("Expected \"}\"", token, type); gMibError = MODULE_SYNTAX_ERROR; return NULL; } type = get_token(fp, token, MAXTOKEN); } switch (type) { case DEFINITIONS: if (state != BETWEEN_MIBS) { print_error("Error, nested MIBS", NULL, type); gMibError = MODULE_SYNTAX_ERROR; return NULL; } state = IN_MIB; current_module = which_module(name); oldgroups = objgroups; objgroups = NULL; oldobjects = objects; objects = NULL; oldnotifs = notifs; notifs = NULL; if (current_module == -1) { new_module(name, File); current_module = which_module(name); } DEBUGMSGTL(("parse-mibs", "Parsing MIB: %d %s\n", current_module, name)); while ((type = get_token(fp, token, MAXTOKEN)) != ENDOFFILE) if (type == BEGIN) break; break; case OBJTYPE: nnp = parse_objecttype(fp, name); if (nnp == NULL) { print_error("Bad parse of OBJECT-TYPE", NULL, type); gMibError = MODULE_SYNTAX_ERROR; return NULL; } break; case OBJGROUP: nnp = parse_objectgroup(fp, name, OBJECTS, &objects); if (nnp == NULL) { print_error("Bad parse of OBJECT-GROUP", NULL, type); gMibError = MODULE_SYNTAX_ERROR; return NULL; } break; case NOTIFGROUP: nnp = parse_objectgroup(fp, name, NOTIFICATIONS, &notifs); if (nnp == NULL) { print_error("Bad parse of NOTIFICATION-GROUP", NULL, type); gMibError = MODULE_SYNTAX_ERROR; return NULL; } break; case TRAPTYPE: nnp = parse_trapDefinition(fp, name); if (nnp == NULL) { print_error("Bad parse of TRAP-TYPE", NULL, type); gMibError = MODULE_SYNTAX_ERROR; return NULL; } break; case NOTIFTYPE: nnp = parse_notificationDefinition(fp, name); if (nnp == NULL) { print_error("Bad parse of NOTIFICATION-TYPE", NULL, type); gMibError = MODULE_SYNTAX_ERROR; return NULL; } break; case COMPLIANCE: nnp = parse_compliance(fp, name); if (nnp == NULL) { print_error("Bad parse of MODULE-COMPLIANCE", NULL, type); gMibError = MODULE_SYNTAX_ERROR; return NULL; } break; case AGENTCAP: nnp = parse_capabilities(fp, name); if (nnp == NULL) { print_error("Bad parse of AGENT-CAPABILITIES", NULL, type); gMibError = MODULE_SYNTAX_ERROR; return NULL; } break; case MACRO: nnp = parse_macro(fp, name); if (nnp == NULL) { print_error("Bad parse of MACRO", NULL, type); gMibError = MODULE_SYNTAX_ERROR; /* * return NULL; */ } free_node(nnp); /* IGNORE */ nnp = NULL; break; case MODULEIDENTITY: nnp = parse_moduleIdentity(fp, name); if (nnp == NULL) { print_error("Bad parse of MODULE-IDENTITY", NULL, type); gMibError = MODULE_SYNTAX_ERROR; return NULL; } break; case OBJIDENTITY: nnp = parse_objectgroup(fp, name, OBJECTS, &objects); if (nnp == NULL) { print_error("Bad parse of OBJECT-IDENTITY", NULL, type); gMibError = MODULE_SYNTAX_ERROR; return NULL; } break; case OBJECT: type = get_token(fp, token, MAXTOKEN); if (type != IDENTIFIER) { print_error("Expected IDENTIFIER", token, type); gMibError = MODULE_SYNTAX_ERROR; return NULL; } type = get_token(fp, token, MAXTOKEN); if (type != EQUALS) { print_error("Expected \"::=\"", token, type); gMibError = MODULE_SYNTAX_ERROR; return NULL; } nnp = parse_objectid(fp, name); if (nnp == NULL) { print_error("Bad parse of OBJECT IDENTIFIER", NULL, type); gMibError = MODULE_SYNTAX_ERROR; return NULL; } break; case EQUALS: nnp = parse_asntype(fp, name, &type, token); lasttype = CONTINUE; break; case ENDOFFILE: break; default: print_error("Bad operator", token, type); gMibError = MODULE_SYNTAX_ERROR; return NULL; } if (nnp) { if (np) np->next = nnp; else np = root = nnp; while (np->next) np = np->next; if (np->type == TYPE_OTHER) np->type = type; } } DEBUGMSGTL(("parse-file", "End of file (%s)\n", File)); return root; } /* * return zero if character is not a label character. */ static int is_labelchar(int ich) { if ((isalnum(ich)) || (ich == '-')) return 1; if (ich == '_' && netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_PARSE_LABEL)) { return 1; } return 0; } /** * Read a single character from a file. Assumes that the caller has invoked * flockfile(). Uses fgetc_unlocked() instead of getc() since the former is * implemented as an inline function in glibc. See also bug 3447196 * (http://sourceforge.net/tracker/?func=detail&aid=3447196&group_id=12694&atid=112694). */ static int netsnmp_getc(FILE *stream) { #ifdef HAVE_FGETC_UNLOCKED return fgetc_unlocked(stream); #else return getc(stream); #endif } /* * Parses a token from the file. The type of the token parsed is returned, * and the text is placed in the string pointed to by token. * Warning: this method may recurse. */ static int get_token(FILE * fp, char *token, int maxtlen) { register int ch, ch_next; register char *cp = token; register int hash = 0; register struct tok *tp; int too_long = 0; enum { bdigits, xdigits, other } seenSymbols; /* * skip all white space */ do { ch = netsnmp_getc(fp); if (ch == '\n') mibLine++; } while (isspace(ch) && ch != EOF); *cp++ = ch; *cp = '\0'; switch (ch) { case EOF: return ENDOFFILE; case '"': return parseQuoteString(fp, token, maxtlen); case '\'': /* binary or hex constant */ seenSymbols = bdigits; while ((ch = netsnmp_getc(fp)) != EOF && ch != '\'') { switch (seenSymbols) { case bdigits: if (ch == '0' || ch == '1') break; seenSymbols = xdigits; /* FALL THROUGH */ case xdigits: if (isxdigit(ch)) break; seenSymbols = other; case other: break; } if (cp - token < maxtlen - 2) *cp++ = ch; } if (ch == '\'') { unsigned long val = 0; char *run = token + 1; ch = netsnmp_getc(fp); switch (ch) { case EOF: return ENDOFFILE; case 'b': case 'B': if (seenSymbols > bdigits) { *cp++ = '\''; *cp = 0; return LABEL; } while (run != cp) val = val * 2 + *run++ - '0'; break; case 'h': case 'H': if (seenSymbols > xdigits) { *cp++ = '\''; *cp = 0; return LABEL; } while (run != cp) { ch = *run++; if ('0' <= ch && ch <= '9') val = val * 16 + ch - '0'; else if ('a' <= ch && ch <= 'f') val = val * 16 + ch - 'a' + 10; else if ('A' <= ch && ch <= 'F') val = val * 16 + ch - 'A' + 10; } break; default: *cp++ = '\''; *cp = 0; return LABEL; } sprintf(token, "%ld", val); return NUMBER; } else return LABEL; case '(': return LEFTPAREN; case ')': return RIGHTPAREN; case '{': return LEFTBRACKET; case '}': return RIGHTBRACKET; case '[': return LEFTSQBRACK; case ']': return RIGHTSQBRACK; case ';': return SEMI; case ',': return COMMA; case '|': return BAR; case '.': ch_next = netsnmp_getc(fp); if (ch_next == '.') return RANGE; ungetc(ch_next, fp); return LABEL; case ':': ch_next = netsnmp_getc(fp); if (ch_next != ':') { ungetc(ch_next, fp); return LABEL; } ch_next = netsnmp_getc(fp); if (ch_next != '=') { ungetc(ch_next, fp); return LABEL; } return EQUALS; case '-': ch_next = netsnmp_getc(fp); if (ch_next == '-') { if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_COMMENT_TERM)) { /* * Treat the rest of this line as a comment. */ while ((ch_next != EOF) && (ch_next != '\n')) ch_next = netsnmp_getc(fp); } else { /* * Treat the rest of the line or until another '--' as a comment */ /* * (this is the "technically" correct way to parse comments) */ ch = ' '; ch_next = netsnmp_getc(fp); while (ch_next != EOF && ch_next != '\n' && (ch != '-' || ch_next != '-')) { ch = ch_next; ch_next = netsnmp_getc(fp); } } if (ch_next == EOF) return ENDOFFILE; if (ch_next == '\n') mibLine++; return get_token(fp, token, maxtlen); } ungetc(ch_next, fp); /* fallthrough */ default: /* * Accumulate characters until end of token is found. Then attempt to * match this token as a reserved word. If a match is found, return the * type. Else it is a label. */ if (!is_labelchar(ch)) return LABEL; hash += tolower(ch); more: while (is_labelchar(ch_next = netsnmp_getc(fp))) { hash += tolower(ch_next); if (cp - token < maxtlen - 1) *cp++ = ch_next; else too_long = 1; } ungetc(ch_next, fp); *cp = '\0'; if (too_long) print_error("Warning: token too long", token, CONTINUE); for (tp = buckets[BUCKET(hash)]; tp; tp = tp->next) { if ((tp->hash == hash) && (!label_compare(tp->name, token))) break; } if (tp) { if (tp->token != CONTINUE) return (tp->token); while (isspace((ch_next = netsnmp_getc(fp)))) if (ch_next == '\n') mibLine++; if (ch_next == EOF) return ENDOFFILE; if (isalnum(ch_next)) { *cp++ = ch_next; hash += tolower(ch_next); goto more; } } if (token[0] == '-' || isdigit((unsigned char)(token[0]))) { for (cp = token + 1; *cp; cp++) if (!isdigit((unsigned char)(*cp))) return LABEL; return NUMBER; } return LABEL; } } netsnmp_feature_child_of(parse_get_token, netsnmp_unused) #ifndef NETSNMP_FEATURE_REMOVE_PARSE_GET_TOKEN int snmp_get_token(FILE * fp, char *token, int maxtlen) { return get_token(fp, token, maxtlen); } #endif /* NETSNMP_FEATURE_REMOVE_PARSE_GET_TOKEN */ int add_mibfile(const char* tmpstr, const char* d_name, FILE *ip ) { FILE *fp; char token[MAXTOKEN], token2[MAXTOKEN]; /* * which module is this */ if ((fp = fopen(tmpstr, "r")) == NULL) { snmp_log_perror(tmpstr); return 1; } DEBUGMSGTL(("parse-mibs", "Checking file: %s...\n", tmpstr)); mibLine = 1; File = tmpstr; if (get_token(fp, token, MAXTOKEN) != LABEL) { fclose(fp); return 1; } /* * simple test for this being a MIB */ if (get_token(fp, token2, MAXTOKEN) == DEFINITIONS) { new_module(token, tmpstr); if (ip) fprintf(ip, "%s %s\n", token, d_name); fclose(fp); return 0; } else { fclose(fp); return 1; } } static int elemcmp(const void *a, const void *b) { const char *const *s1 = a, *const *s2 = b; return strcmp(*s1, *s2); } /* * Scan a directory and return all filenames found as an array of pointers to * directory entries (@result). */ static int scan_directory(char ***result, const char *dirname) { DIR *dir, *dir2; struct dirent *file; char **filenames = NULL; int fname_len, i, filename_count = 0, array_size = 0; char *tmpstr; *result = NULL; dir = opendir(dirname); if (!dir) return -1; while ((file = readdir(dir))) { /* * Only parse file names that don't begin with a '.' * Also skip files ending in '~', or starting/ending * with '#' which are typically editor backup files. */ fname_len = strlen(file->d_name); if (fname_len > 0 && file->d_name[0] != '.' && file->d_name[0] != '#' && file->d_name[fname_len-1] != '#' && file->d_name[fname_len-1] != '~') { if (asprintf(&tmpstr, "%s/%s", dirname, file->d_name) < 0) continue; dir2 = opendir(tmpstr); if (dir2) { /* file is a directory, don't read it */ closedir(dir2); } else { if (filename_count >= array_size) { char **new_filenames; array_size = (array_size + 16) * 2; new_filenames = realloc(filenames, array_size * sizeof(filenames[0])); if (!new_filenames) { free(tmpstr); for (i = 0; i < filename_count; i++) free(filenames[i]); free(filenames); closedir(dir); return -1; } filenames = new_filenames; } filenames[filename_count++] = tmpstr; tmpstr = NULL; } free(tmpstr); } } closedir(dir); if (filenames) qsort(filenames, filename_count, sizeof(filenames[0]), elemcmp); *result = filenames; return filename_count; } /* For Win32 platforms, the directory does not maintain a last modification * date that we can compare with the modification date of the .index file. * Therefore there is no way to know whether any .index file is valid. * This is the reason for the #if !(defined(WIN32) || defined(cygwin)) * in the add_mibdir function */ int add_mibdir(const char *dirname) { FILE *ip; const char *oldFile = File; char **filenames; int count = 0; int filename_count, i; #if !(defined(WIN32) || defined(cygwin)) char *token; char space; char newline; struct stat dir_stat, idx_stat; char tmpstr[300]; char tmpstr1[300]; #endif DEBUGMSGTL(("parse-mibs", "Scanning directory %s\n", dirname)); #if !(defined(WIN32) || defined(cygwin)) token = netsnmp_mibindex_lookup( dirname ); if (token && stat(token, &idx_stat) == 0 && stat(dirname, &dir_stat) == 0) { if (dir_stat.st_mtime < idx_stat.st_mtime) { DEBUGMSGTL(("parse-mibs", "The index is good\n")); if ((ip = fopen(token, "r")) != NULL) { fgets(tmpstr, sizeof(tmpstr), ip); /* Skip dir line */ while (fscanf(ip, "%127s%c%299[^\n]%c", token, &space, tmpstr, &newline) == 4) { /* * If an overflow of the token or tmpstr buffers has been * found log a message and break out of the while loop, * thus the rest of the file tokens will be ignored. */ if (space != ' ' || newline != '\n') { snmp_log(LOG_ERR, "add_mibdir: strings scanned in from %s/%s " \ "are too large. count = %d\n ", dirname, ".index", count); break; } snprintf(tmpstr1, sizeof(tmpstr1), "%s/%s", dirname, tmpstr); tmpstr1[ sizeof(tmpstr1)-1 ] = 0; new_module(token, tmpstr1); count++; } fclose(ip); return count; } else DEBUGMSGTL(("parse-mibs", "Can't read index\n")); } else DEBUGMSGTL(("parse-mibs", "Index outdated\n")); } else DEBUGMSGTL(("parse-mibs", "No index\n")); #endif filename_count = scan_directory(&filenames, dirname); if (filename_count >= 0) { ip = netsnmp_mibindex_new(dirname); for (i = 0; i < filename_count; i++) { if (add_mibfile(filenames[i], strrchr(filenames[i], '/'), ip) == 0) count++; free(filenames[i]); } File = oldFile; if (ip) fclose(ip); free(filenames); return (count); } else DEBUGMSGTL(("parse-mibs","cannot open MIB directory %s\n", dirname)); return (-1); } /* * Returns the root of the whole tree * (for backwards compatability) */ struct tree * read_mib(const char *filename) { FILE *fp; char token[MAXTOKEN]; fp = fopen(filename, "r"); if (fp == NULL) { snmp_log_perror(filename); return NULL; } mibLine = 1; File = filename; DEBUGMSGTL(("parse-mibs", "Parsing file: %s...\n", filename)); if (get_token(fp, token, MAXTOKEN) != LABEL) { snmp_log(LOG_ERR, "Failed to parse MIB file %s\n", filename); fclose(fp); return NULL; } fclose(fp); new_module(token, filename); (void) netsnmp_read_module(token); return tree_head; } struct tree * read_all_mibs(void) { struct module *mp; for (mp = module_head; mp; mp = mp->next) if (mp->no_imports == -1) netsnmp_read_module(mp->name); adopt_orphans(); /* If entered the syntax error loop in "read_module()" */ if (gLoop == 1) { gLoop = 0; free(gpMibErrorString); gpMibErrorString = NULL; if (asprintf(&gpMibErrorString, "Error in parsing MIB module(s): %s !" " Unable to load corresponding MIB(s)", gMibNames) < 0) { snmp_log(LOG_CRIT, "failed to allocated memory for gpMibErrorString\n"); } } /* Caller's responsibility to free this memory */ tree_head->parseErrorString = gpMibErrorString; return tree_head; } #ifdef TEST int main(int argc, char *argv[]) { int i; struct tree *tp; netsnmp_ds_set_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_WARNINGS, 2); netsnmp_init_mib(); if (argc == 1) (void) read_all_mibs(); else for (i = 1; i < argc; i++) read_mib(argv[i]); for (tp = tree_head; tp; tp = tp->next_peer) print_subtree(stdout, tp, 0); free_tree(tree_head); return 0; } #endif /* TEST */ static int parseQuoteString(FILE * fp, char *token, int maxtlen) { register int ch; int count = 0; int too_long = 0; char *token_start = token; for (ch = netsnmp_getc(fp); ch != EOF; ch = netsnmp_getc(fp)) { if (ch == '\r') continue; if (ch == '\n') { mibLine++; } else if (ch == '"') { *token = '\0'; if (too_long && netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_WARNINGS) > 1) { /* * show short form for brevity sake */ char ch_save = *(token_start + 50); *(token_start + 50) = '\0'; print_error("Warning: string too long", token_start, QUOTESTRING); *(token_start + 50) = ch_save; } return QUOTESTRING; } /* * maximum description length check. If greater, keep parsing * but truncate the string */ if (++count < maxtlen) *token++ = ch; else too_long = 1; } return 0; } /* * struct index_list * * getIndexes(FILE *fp): * This routine parses a string like { blah blah blah } and returns a * list of the strings enclosed within it. * */ static struct index_list * getIndexes(FILE * fp, struct index_list **retp) { int type; char token[MAXTOKEN]; char nextIsImplied = 0; struct index_list *mylist = NULL; struct index_list **mypp = &mylist; free_indexes(retp); type = get_token(fp, token, MAXTOKEN); if (type != LEFTBRACKET) { return NULL; } type = get_token(fp, token, MAXTOKEN); while (type != RIGHTBRACKET && type != ENDOFFILE) { if ((type == LABEL) || (type & SYNTAX_MASK)) { *mypp = (struct index_list *) calloc(1, sizeof(struct index_list)); if (*mypp) { (*mypp)->ilabel = strdup(token); (*mypp)->isimplied = nextIsImplied; mypp = &(*mypp)->next; nextIsImplied = 0; } } else if (type == IMPLIED) { nextIsImplied = 1; } type = get_token(fp, token, MAXTOKEN); } *retp = mylist; return mylist; } static struct varbind_list * getVarbinds(FILE * fp, struct varbind_list **retp) { int type; char token[MAXTOKEN]; struct varbind_list *mylist = NULL; struct varbind_list **mypp = &mylist; free_varbinds(retp); type = get_token(fp, token, MAXTOKEN); if (type != LEFTBRACKET) { return NULL; } type = get_token(fp, token, MAXTOKEN); while (type != RIGHTBRACKET && type != ENDOFFILE) { if ((type == LABEL) || (type & SYNTAX_MASK)) { *mypp = (struct varbind_list *) calloc(1, sizeof(struct varbind_list)); if (*mypp) { (*mypp)->vblabel = strdup(token); mypp = &(*mypp)->next; } } type = get_token(fp, token, MAXTOKEN); } *retp = mylist; return mylist; } static void free_indexes(struct index_list **spp) { if (spp && *spp) { struct index_list *pp, *npp; pp = *spp; *spp = NULL; while (pp) { npp = pp->next; if (pp->ilabel) free(pp->ilabel); free(pp); pp = npp; } } } static void free_varbinds(struct varbind_list **spp) { if (spp && *spp) { struct varbind_list *pp, *npp; pp = *spp; *spp = NULL; while (pp) { npp = pp->next; if (pp->vblabel) free(pp->vblabel); free(pp); pp = npp; } } } static void free_ranges(struct range_list **spp) { if (spp && *spp) { struct range_list *pp, *npp; pp = *spp; *spp = NULL; while (pp) { npp = pp->next; free(pp); pp = npp; } } } static void free_enums(struct enum_list **spp) { if (spp && *spp) { struct enum_list *pp, *npp; pp = *spp; *spp = NULL; while (pp) { npp = pp->next; if (pp->label) free(pp->label); free(pp); pp = npp; } } } static struct enum_list * copy_enums(struct enum_list *sp) { struct enum_list *xp = NULL, **spp = &xp; while (sp) { *spp = (struct enum_list *) calloc(1, sizeof(struct enum_list)); if (!*spp) break; (*spp)->label = strdup(sp->label); (*spp)->value = sp->value; spp = &(*spp)->next; sp = sp->next; } return (xp); } static struct range_list * copy_ranges(struct range_list *sp) { struct range_list *xp = NULL, **spp = &xp; while (sp) { *spp = (struct range_list *) calloc(1, sizeof(struct range_list)); if (!*spp) break; (*spp)->low = sp->low; (*spp)->high = sp->high; spp = &(*spp)->next; sp = sp->next; } return (xp); } /* * This routine parses a string like { blah blah blah } and returns OBJID if * it is well formed, and NULL if not. */ static int tossObjectIdentifier(FILE * fp) { int type; char token[MAXTOKEN]; int bracketcount = 1; type = get_token(fp, token, MAXTOKEN); if (type != LEFTBRACKET) return 0; while ((type != RIGHTBRACKET || bracketcount > 0) && type != ENDOFFILE) { type = get_token(fp, token, MAXTOKEN); if (type == LEFTBRACKET) bracketcount++; else if (type == RIGHTBRACKET) bracketcount--; } if (type == RIGHTBRACKET) return OBJID; else return 0; } /* Find node in any MIB module Used by Perl modules */ struct tree * find_node(const char *name, struct tree *subtree) { /* Unused */ return (find_tree_node(name, -1)); } netsnmp_feature_child_of(parse_find_node2, netsnmp_unused) #ifndef NETSNMP_FEATURE_REMOVE_PARSE_FIND_NODE2 struct tree * find_node2(const char *name, const char *module) { int modid = -1; if (module) { modid = which_module(module); } if (modid == -1) { return (NULL); } return (find_tree_node(name, modid)); } #endif /* NETSNMP_FEATURE_REMOVE_PARSE_FIND_NODE2 */ #ifndef NETSNMP_FEATURE_REMOVE_FIND_MODULE /* Used in the perl module */ struct module * find_module(int mid) { struct module *mp; for (mp = module_head; mp != NULL; mp = mp->next) { if (mp->modid == mid) break; } return mp; } #endif /* NETSNMP_FEATURE_REMOVE_FIND_MODULE */ static char leave_indent[256]; static int leave_was_simple; static void print_mib_leaves(FILE * f, struct tree *tp, int width) { struct tree *ntp; char *ip = leave_indent + strlen(leave_indent) - 1; char last_ipch = *ip; *ip = '+'; if (tp->type == TYPE_OTHER || tp->type > TYPE_SIMPLE_LAST) { fprintf(f, "%s--%s(%ld)\n", leave_indent, tp->label, tp->subid); if (tp->indexes) { struct index_list *xp = tp->indexes; int first = 1, cpos = 0, len, cmax = width - strlen(leave_indent) - 12; *ip = last_ipch; fprintf(f, "%s | Index: ", leave_indent); while (xp) { if (first) first = 0; else fprintf(f, ", "); cpos += (len = strlen(xp->ilabel) + 2); if (cpos > cmax) { fprintf(f, "\n"); fprintf(f, "%s | ", leave_indent); cpos = len; } fprintf(f, "%s", xp->ilabel); xp = xp->next; } fprintf(f, "\n"); *ip = '+'; } } else { const char *acc, *typ; int size = 0; switch (tp->access) { case MIB_ACCESS_NOACCESS: acc = "----"; break; case MIB_ACCESS_READONLY: acc = "-R--"; break; case MIB_ACCESS_WRITEONLY: acc = "--W-"; break; case MIB_ACCESS_READWRITE: acc = "-RW-"; break; case MIB_ACCESS_NOTIFY: acc = "---N"; break; case MIB_ACCESS_CREATE: acc = "CR--"; break; default: acc = " "; break; } switch (tp->type) { case TYPE_OBJID: typ = "ObjID "; break; case TYPE_OCTETSTR: typ = "String "; size = 1; break; case TYPE_INTEGER: if (tp->enums) typ = "EnumVal "; else typ = "INTEGER "; break; case TYPE_NETADDR: typ = "NetAddr "; break; case TYPE_IPADDR: typ = "IpAddr "; break; case TYPE_COUNTER: typ = "Counter "; break; case TYPE_GAUGE: typ = "Gauge "; break; case TYPE_TIMETICKS: typ = "TimeTicks"; break; case TYPE_OPAQUE: typ = "Opaque "; size = 1; break; case TYPE_NULL: typ = "Null "; break; case TYPE_COUNTER64: typ = "Counter64"; break; case TYPE_BITSTRING: typ = "BitString"; break; case TYPE_NSAPADDRESS: typ = "NsapAddr "; break; case TYPE_UNSIGNED32: typ = "Unsigned "; break; case TYPE_UINTEGER: typ = "UInteger "; break; case TYPE_INTEGER32: typ = "Integer32"; break; default: typ = " "; break; } fprintf(f, "%s-- %s %s %s(%ld)\n", leave_indent, acc, typ, tp->label, tp->subid); *ip = last_ipch; if (tp->tc_index >= 0) fprintf(f, "%s Textual Convention: %s\n", leave_indent, tclist[tp->tc_index].descriptor); if (tp->enums) { struct enum_list *ep = tp->enums; int cpos = 0, cmax = width - strlen(leave_indent) - 16; fprintf(f, "%s Values: ", leave_indent); while (ep) { char buf[80]; int bufw; if (ep != tp->enums) fprintf(f, ", "); snprintf(buf, sizeof(buf), "%s(%d)", ep->label, ep->value); buf[ sizeof(buf)-1 ] = 0; cpos += (bufw = strlen(buf) + 2); if (cpos >= cmax) { fprintf(f, "\n%s ", leave_indent); cpos = bufw; } fprintf(f, "%s", buf); ep = ep->next; } fprintf(f, "\n"); } if (tp->ranges) { struct range_list *rp = tp->ranges; if (size) fprintf(f, "%s Size: ", leave_indent); else fprintf(f, "%s Range: ", leave_indent); while (rp) { if (rp != tp->ranges) fprintf(f, " | "); print_range_value(f, tp->type, rp); rp = rp->next; } fprintf(f, "\n"); } } *ip = last_ipch; strcat(leave_indent, " |"); leave_was_simple = tp->type != TYPE_OTHER; { int i, j, count = 0; struct leave { oid id; struct tree *tp; } *leaves, *lp; for (ntp = tp->child_list; ntp; ntp = ntp->next_peer) count++; if (count) { leaves = (struct leave *) calloc(count, sizeof(struct leave)); if (!leaves) return; for (ntp = tp->child_list, count = 0; ntp; ntp = ntp->next_peer) { for (i = 0, lp = leaves; i < count; i++, lp++) if (lp->id >= ntp->subid) break; for (j = count; j > i; j--) leaves[j] = leaves[j - 1]; lp->id = ntp->subid; lp->tp = ntp; count++; } for (i = 1, lp = leaves; i <= count; i++, lp++) { if (!leave_was_simple || lp->tp->type == 0) fprintf(f, "%s\n", leave_indent); if (i == count) ip[3] = ' '; print_mib_leaves(f, lp->tp, width); } free(leaves); leave_was_simple = 0; } } ip[1] = 0; } void print_mib_tree(FILE * f, struct tree *tp, int width) { leave_indent[0] = ' '; leave_indent[1] = 0; leave_was_simple = 1; print_mib_leaves(f, tp, width); } /* * Merge the parsed object identifier with the existing node. * If there is a problem with the identifier, release the existing node. */ static struct node * merge_parse_objectid(struct node *np, FILE * fp, char *name) { struct node *nnp; /* * printf("merge defval --> %s\n",np->defaultValue); */ nnp = parse_objectid(fp, name); if (nnp) { /* * apply last OID sub-identifier data to the information */ /* * already collected for this node. */ struct node *headp, *nextp; int ncount = 0; nextp = headp = nnp; while (nnp->next) { nextp = nnp; ncount++; nnp = nnp->next; } np->label = nnp->label; np->subid = nnp->subid; np->modid = nnp->modid; np->parent = nnp->parent; if (nnp->filename != NULL) { free(nnp->filename); } free(nnp); if (ncount) { nextp->next = np; np = headp; } } else { free_node(np); np = NULL; } return np; } /* * transfer data to tree from node * * move pointers for alloc'd data from np to tp. * this prevents them from being freed when np is released. * parent member is not moved. * * CAUTION: nodes may be repeats of existing tree nodes. * This can happen especially when resolving IMPORT clauses. * */ static void tree_from_node(struct tree *tp, struct node *np) { free_partial_tree(tp, FALSE); tp->label = np->label; np->label = NULL; tp->enums = np->enums; np->enums = NULL; tp->ranges = np->ranges; np->ranges = NULL; tp->indexes = np->indexes; np->indexes = NULL; tp->augments = np->augments; np->augments = NULL; tp->varbinds = np->varbinds; np->varbinds = NULL; tp->hint = np->hint; np->hint = NULL; tp->units = np->units; np->units = NULL; tp->description = np->description; np->description = NULL; tp->reference = np->reference; np->reference = NULL; tp->defaultValue = np->defaultValue; np->defaultValue = NULL; tp->subid = np->subid; tp->tc_index = np->tc_index; tp->type = translation_table[np->type]; tp->access = np->access; tp->status = np->status; set_function(tp); } #endif /* NETSNMP_DISABLE_MIB_LOADING */
./CrossVul/dataset_final_sorted/CWE-59/c/bad_4226_4
crossvul-cpp_data_good_4226_3
/* * mib.c * * $Id$ * * Update: 1998-07-17 <jhy@gsu.edu> * Added print_oid_report* functions. * */ /* Portions of this file are subject to the following copyrights. See * the Net-SNMP's COPYING file for more details and other copyrights * that may apply: */ /********************************************************************** Copyright 1988, 1989, 1991, 1992 by Carnegie Mellon University All Rights Reserved Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation, and that the name of CMU not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. CMU DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL CMU BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ******************************************************************/ /* * Copyright � 2003 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms specified in the COPYING file * distributed with the Net-SNMP package. * * Portions of this file are copyrighted by: * Copyright (c) 2016 VMware, Inc. All rights reserved. * Use is subject to license terms specified in the COPYING file * distributed with the Net-SNMP package. */ #include <net-snmp/net-snmp-config.h> #include <net-snmp/net-snmp-features.h> #include <stdio.h> #include <ctype.h> #include <sys/types.h> #if HAVE_DIRENT_H # include <dirent.h> # define NAMLEN(dirent) strlen((dirent)->d_name) #else # define dirent direct # define NAMLEN(dirent) (dirent)->d_namlen # if HAVE_SYS_NDIR_H # include <sys/ndir.h> # endif # if HAVE_SYS_DIR_H # include <sys/dir.h> # endif # if HAVE_NDIR_H # include <ndir.h> # endif #endif #ifdef HAVE_INTTYPES_H #include <inttypes.h> #endif #if HAVE_NETINET_IN_H #include <netinet/in.h> #endif #if TIME_WITH_SYS_TIME # include <sys/time.h> # include <time.h> #else # if HAVE_SYS_TIME_H # include <sys/time.h> # else # include <time.h> # endif #endif #if HAVE_STRING_H #include <string.h> #else #include <strings.h> #endif #if HAVE_STDLIB_H #include <stdlib.h> #endif #if HAVE_SYS_SELECT_H #include <sys/select.h> #endif #if HAVE_UNISTD_H #include <unistd.h> #endif #if HAVE_DMALLOC_H #include <dmalloc.h> #endif #include <net-snmp/types.h> #include <net-snmp/output_api.h> #include <net-snmp/config_api.h> #include <net-snmp/utilities.h> #include <net-snmp/library/asn1.h> #include <net-snmp/library/snmp_api.h> #include <net-snmp/library/mib.h> #include <net-snmp/library/parse.h> #include <net-snmp/library/int64.h> #include <net-snmp/library/snmp_client.h> netsnmp_feature_child_of(mib_api, libnetsnmp) netsnmp_feature_child_of(mib_strings_all, mib_api) netsnmp_feature_child_of(mib_snprint, mib_strings_all) netsnmp_feature_child_of(mib_snprint_description, mib_strings_all) netsnmp_feature_child_of(mib_snprint_variable, mib_strings_all) netsnmp_feature_child_of(mib_string_conversions, mib_strings_all) netsnmp_feature_child_of(print_mib, mib_strings_all) netsnmp_feature_child_of(snprint_objid, mib_strings_all) netsnmp_feature_child_of(snprint_value, mib_strings_all) netsnmp_feature_child_of(mib_to_asn_type, mib_api) /** @defgroup mib_utilities mib parsing and datatype manipulation routines. * @ingroup library * * @{ */ static char *uptimeString(u_long, char *, size_t); #ifndef NETSNMP_DISABLE_MIB_LOADING static struct tree *_get_realloc_symbol(const oid * objid, size_t objidlen, struct tree *subtree, u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, int *buf_overflow, struct index_list *in_dices, size_t * end_of_known); static int print_tree_node(u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, struct tree *tp, int width); static void handle_mibdirs_conf(const char *token, char *line); static void handle_mibs_conf(const char *token, char *line); static void handle_mibfile_conf(const char *token, char *line); #endif /*NETSNMP_DISABLE_MIB_LOADING */ static void _oid_finish_printing(const oid * objid, size_t objidlen, u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, int *buf_overflow); /* * helper functions for get_module_node */ #ifndef NETSNMP_DISABLE_MIB_LOADING static int node_to_oid(struct tree *, oid *, size_t *); static int _add_strings_to_oid(struct tree *, char *, oid *, size_t *, size_t); #else static int _add_strings_to_oid(void *, char *, oid *, size_t *, size_t); #endif /* NETSNMP_DISABLE_MIB_LOADING */ #ifndef NETSNMP_DISABLE_MIB_LOADING NETSNMP_IMPORT struct tree *tree_head; static struct tree *tree_top; NETSNMP_IMPORT struct tree *Mib; struct tree *Mib; /* Backwards compatibility */ #endif /* NETSNMP_DISABLE_MIB_LOADING */ static char Standard_Prefix[] = ".1.3.6.1.2.1"; /* * Set default here as some uses of read_objid require valid pointer. */ #ifndef NETSNMP_DISABLE_MIB_LOADING static char *Prefix = &Standard_Prefix[0]; #endif /* NETSNMP_DISABLE_MIB_LOADING */ typedef struct _PrefixList { const char *str; int len; } *PrefixListPtr, PrefixList; /* * Here are the prefix strings. * Note that the first one finds the value of Prefix or Standard_Prefix. * Any of these MAY start with period; all will NOT end with period. * Period is added where needed. See use of Prefix in this module. */ PrefixList mib_prefixes[] = { {&Standard_Prefix[0]}, /* placeholder for Prefix data */ {".iso.org.dod.internet.mgmt.mib-2"}, {".iso.org.dod.internet.experimental"}, {".iso.org.dod.internet.private"}, {".iso.org.dod.internet.snmpParties"}, {".iso.org.dod.internet.snmpSecrets"}, {NULL, 0} /* end of list */ }; enum inet_address_type { IPV4 = 1, IPV6 = 2, IPV4Z = 3, IPV6Z = 4, DNS = 16 }; /** * @internal * Converts timeticks to hours, minutes, seconds string. * * @param timeticks The timeticks to convert. * @param buf Buffer to write to, has to be at * least 40 Bytes large. * * @return The buffer. */ static char * uptimeString(u_long timeticks, char *buf, size_t buflen) { int centisecs, seconds, minutes, hours, days; if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_NUMERIC_TIMETICKS)) { snprintf(buf, buflen, "%lu", timeticks); return buf; } centisecs = timeticks % 100; timeticks /= 100; days = timeticks / (60 * 60 * 24); timeticks %= (60 * 60 * 24); hours = timeticks / (60 * 60); timeticks %= (60 * 60); minutes = timeticks / 60; seconds = timeticks % 60; if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT)) snprintf(buf, buflen, "%d:%d:%02d:%02d.%02d", days, hours, minutes, seconds, centisecs); else { if (days == 0) { snprintf(buf, buflen, "%d:%02d:%02d.%02d", hours, minutes, seconds, centisecs); } else if (days == 1) { snprintf(buf, buflen, "%d day, %d:%02d:%02d.%02d", days, hours, minutes, seconds, centisecs); } else { snprintf(buf, buflen, "%d days, %d:%02d:%02d.%02d", days, hours, minutes, seconds, centisecs); } } return buf; } /** * @internal * Prints the character pointed to if in human-readable ASCII range, * otherwise prints a dot. * * @param buf Buffer to print the character to. * @param ch Character to print. */ static void sprint_char(char *buf, const u_char ch) { if (isprint(ch) || isspace(ch)) { sprintf(buf, "%c", (int) ch); } else { sprintf(buf, "."); } } /** * Prints a hexadecimal string into a buffer. * * The characters pointed by *cp are encoded as hexadecimal string. * * If allow_realloc is true the buffer will be (re)allocated to fit in the * needed size. (Note: *buf may change due to this.) * * @param buf address of the buffer to print to. * @param buf_len address to an integer containing the size of buf. * @param out_len incremented by the number of characters printed. * @param allow_realloc if not zero reallocate the buffer to fit the * needed size. * @param cp the array of characters to encode. * @param line_len the array length of cp. * * @return 1 on success, or 0 on failure (out of memory, or buffer to * small when not allowed to realloc.) */ int _sprint_hexstring_line(u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, const u_char * cp, size_t line_len) { const u_char *tp; const u_char *cp2 = cp; size_t lenleft = line_len; /* * Make sure there's enough room for the hex output.... */ while ((*out_len + line_len*3+1) >= *buf_len) { if (!(allow_realloc && snmp_realloc(buf, buf_len))) { return 0; } } /* * .... and display the hex values themselves.... */ for (; lenleft >= 8; lenleft-=8) { sprintf((char *) (*buf + *out_len), "%02X %02X %02X %02X %02X %02X %02X %02X ", cp[0], cp[1], cp[2], cp[3], cp[4], cp[5], cp[6], cp[7]); *out_len += strlen((char *) (*buf + *out_len)); cp += 8; } for (; lenleft > 0; lenleft--) { sprintf((char *) (*buf + *out_len), "%02X ", *cp++); *out_len += strlen((char *) (*buf + *out_len)); } /* * .... plus (optionally) do the same for the ASCII equivalent. */ if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PRINT_HEX_TEXT)) { while ((*out_len + line_len+5) >= *buf_len) { if (!(allow_realloc && snmp_realloc(buf, buf_len))) { return 0; } } sprintf((char *) (*buf + *out_len), " ["); *out_len += strlen((char *) (*buf + *out_len)); for (tp = cp2; tp < cp; tp++) { sprint_char((char *) (*buf + *out_len), *tp); (*out_len)++; } sprintf((char *) (*buf + *out_len), "]"); *out_len += strlen((char *) (*buf + *out_len)); } return 1; } int sprint_realloc_hexstring(u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, const u_char * cp, size_t len) { int line_len = netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_HEX_OUTPUT_LENGTH); if (line_len <= 0) line_len = len; for (; (int)len > line_len; len -= line_len) { if(!_sprint_hexstring_line(buf, buf_len, out_len, allow_realloc, cp, line_len)) return 0; *(*buf + (*out_len)++) = '\n'; *(*buf + *out_len) = 0; cp += line_len; } if(!_sprint_hexstring_line(buf, buf_len, out_len, allow_realloc, cp, len)) return 0; *(*buf + *out_len) = 0; return 1; } /** * Prints an ascii string into a buffer. * * The characters pointed by *cp are encoded as an ascii string. * * If allow_realloc is true the buffer will be (re)allocated to fit in the * needed size. (Note: *buf may change due to this.) * * @param buf address of the buffer to print to. * @param buf_len address to an integer containing the size of buf. * @param out_len incremented by the number of characters printed. * @param allow_realloc if not zero reallocate the buffer to fit the * needed size. * @param cp the array of characters to encode. * @param len the array length of cp. * * @return 1 on success, or 0 on failure (out of memory, or buffer to * small when not allowed to realloc.) */ int sprint_realloc_asciistring(u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, const u_char * cp, size_t len) { int i; for (i = 0; i < (int) len; i++) { if (isprint(*cp) || isspace(*cp)) { if (*cp == '\\' || *cp == '"') { if ((*out_len >= *buf_len) && !(allow_realloc && snmp_realloc(buf, buf_len))) { return 0; } *(*buf + (*out_len)++) = '\\'; } if ((*out_len >= *buf_len) && !(allow_realloc && snmp_realloc(buf, buf_len))) { return 0; } *(*buf + (*out_len)++) = *cp++; } else { if ((*out_len >= *buf_len) && !(allow_realloc && snmp_realloc(buf, buf_len))) { return 0; } *(*buf + (*out_len)++) = '.'; cp++; } } if ((*out_len >= *buf_len) && !(allow_realloc && snmp_realloc(buf, buf_len))) { return 0; } *(*buf + *out_len) = '\0'; return 1; } /** * Prints an octet string into a buffer. * * The variable var is encoded as octet string. * * If allow_realloc is true the buffer will be (re)allocated to fit in the * needed size. (Note: *buf may change due to this.) * * @param buf Address of the buffer to print to. * @param buf_len Address to an integer containing the size of buf. * @param out_len Incremented by the number of characters printed. * @param allow_realloc if not zero reallocate the buffer to fit the * needed size. * @param var The variable to encode. * @param enums The enumeration ff this variable is enumerated. may be NULL. * @param hint Contents of the DISPLAY-HINT clause of the MIB. * See RFC 1903 Section 3.1 for details. may be NULL. * @param units Contents of the UNITS clause of the MIB. may be NULL. * * @return 1 on success, or 0 on failure (out of memory, or buffer to * small when not allowed to realloc.) */ int sprint_realloc_octet_string(u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, const netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { size_t saved_out_len = *out_len; const char *saved_hint = hint; int hex = 0, x = 0; u_char *cp; int output_format, cnt; if (var->type != ASN_OCTET_STR) { if (!netsnmp_ds_get_boolean( NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICKE_PRINT)) { const char str[] = "Wrong Type (should be OCTET STRING): "; if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, str)) return 0; } return sprint_realloc_by_type(buf, buf_len, out_len, allow_realloc, var, NULL, NULL, NULL); } if (hint) { int repeat, width = 1; long value; char code = 'd', separ = 0, term = 0, ch, intbuf[32]; #define HEX2DIGIT_NEED_INIT 3 char hex2digit = HEX2DIGIT_NEED_INIT; u_char *ecp; if (!netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT)) { if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, "STRING: ")) { return 0; } } cp = var->val.string; ecp = cp + var->val_len; while (cp < ecp) { repeat = 1; if (*hint) { if (*hint == '*') { repeat = *cp++; hint++; } width = 0; while ('0' <= *hint && *hint <= '9') width = (width * 10) + (*hint++ - '0'); code = *hint++; if ((ch = *hint) && ch != '*' && (ch < '0' || ch > '9') && (width != 0 || (ch != 'x' && ch != 'd' && ch != 'o'))) separ = *hint++; else separ = 0; if ((ch = *hint) && ch != '*' && (ch < '0' || ch > '9') && (width != 0 || (ch != 'x' && ch != 'd' && ch != 'o'))) term = *hint++; else term = 0; if (width == 0) /* Handle malformed hint strings */ width = 1; } while (repeat && cp < ecp) { value = 0; if (code != 'a' && code != 't') { for (x = 0; x < width; x++) { value = value * 256 + *cp++; } } switch (code) { case 'x': if (HEX2DIGIT_NEED_INIT == hex2digit) hex2digit = netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_2DIGIT_HEX_OUTPUT); /* * if value is < 16, it will be a single hex digit. If the * width is 1 (we are outputting a byte at a time), pat it * to 2 digits if NETSNMP_DS_LIB_2DIGIT_HEX_OUTPUT is set * or all of the following are true: * - we do not have a separation character * - there is no hint left (or there never was a hint) * * e.g. for the data 0xAA01BB, would anyone really ever * want the string "AA1BB"?? */ if (((value < 16) && (1 == width)) && (hex2digit || ((0 == separ) && (0 == *hint)))) { sprintf(intbuf, "0%lx", value); } else { sprintf(intbuf, "%lx", value); } if (!snmp_cstrcat (buf, buf_len, out_len, allow_realloc, intbuf)) { return 0; } break; case 'd': sprintf(intbuf, "%ld", value); if (!snmp_cstrcat (buf, buf_len, out_len, allow_realloc, intbuf)) { return 0; } break; case 'o': sprintf(intbuf, "%lo", value); if (!snmp_cstrcat (buf, buf_len, out_len, allow_realloc, intbuf)) { return 0; } break; case 't': /* new in rfc 3411 */ case 'a': /* A string hint gives the max size - we may not need this much */ cnt = SNMP_MIN(width, ecp - cp); while ((*out_len + cnt + 1) > *buf_len) { if (!allow_realloc || !snmp_realloc(buf, buf_len)) return 0; } if (memchr(cp, '\0', cnt) == NULL) { /* No embedded '\0' - use memcpy() to preserve UTF-8 */ memcpy(*buf + *out_len, cp, cnt); *out_len += cnt; *(*buf + *out_len) = '\0'; } else if (!sprint_realloc_asciistring(buf, buf_len, out_len, allow_realloc, cp, cnt)) { return 0; } cp += cnt; break; default: *out_len = saved_out_len; if (snmp_cstrcat(buf, buf_len, out_len, allow_realloc, "(Bad hint ignored: ") && snmp_cstrcat(buf, buf_len, out_len, allow_realloc, saved_hint) && snmp_cstrcat(buf, buf_len, out_len, allow_realloc, ") ")) { return sprint_realloc_octet_string(buf, buf_len, out_len, allow_realloc, var, enums, NULL, NULL); } else { return 0; } } if (cp < ecp && separ) { while ((*out_len + 1) >= *buf_len) { if (!(allow_realloc && snmp_realloc(buf, buf_len))) { return 0; } } *(*buf + *out_len) = separ; (*out_len)++; *(*buf + *out_len) = '\0'; } repeat--; } if (term && cp < ecp) { while ((*out_len + 1) >= *buf_len) { if (!(allow_realloc && snmp_realloc(buf, buf_len))) { return 0; } } *(*buf + *out_len) = term; (*out_len)++; *(*buf + *out_len) = '\0'; } } if (units) { return (snmp_cstrcat (buf, buf_len, out_len, allow_realloc, " ") && snmp_cstrcat(buf, buf_len, out_len, allow_realloc, units)); } if ((*out_len >= *buf_len) && !(allow_realloc && snmp_realloc(buf, buf_len))) { return 0; } *(*buf + *out_len) = '\0'; return 1; } output_format = netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_STRING_OUTPUT_FORMAT); if (0 == output_format) { output_format = NETSNMP_STRING_OUTPUT_GUESS; } switch (output_format) { case NETSNMP_STRING_OUTPUT_GUESS: hex = 0; for (cp = var->val.string, x = 0; x < (int) var->val_len; x++, cp++) { if (!isprint(*cp) && !isspace(*cp)) { hex = 1; } } break; case NETSNMP_STRING_OUTPUT_ASCII: hex = 0; break; case NETSNMP_STRING_OUTPUT_HEX: hex = 1; break; } if (var->val_len == 0) { return snmp_cstrcat(buf, buf_len, out_len, allow_realloc, "\"\""); } if (hex) { if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT)) { if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, "\"")) { return 0; } } else { if (!snmp_cstrcat (buf, buf_len, out_len, allow_realloc, "Hex-STRING: ")) { return 0; } } if (!sprint_realloc_hexstring(buf, buf_len, out_len, allow_realloc, var->val.string, var->val_len)) { return 0; } if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT)) { if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, "\"")) { return 0; } } } else { if (!netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT)) { if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, "STRING: ")) { return 0; } } if (!snmp_cstrcat (buf, buf_len, out_len, allow_realloc, "\"")) { return 0; } if (!sprint_realloc_asciistring (buf, buf_len, out_len, allow_realloc, var->val.string, var->val_len)) { return 0; } if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, "\"")) { return 0; } } if (units) { return (snmp_cstrcat(buf, buf_len, out_len, allow_realloc, " ") && snmp_cstrcat(buf, buf_len, out_len, allow_realloc, units)); } return 1; } #ifdef NETSNMP_WITH_OPAQUE_SPECIAL_TYPES /** * Prints a float into a buffer. * * The variable var is encoded as a floating point value. * * If allow_realloc is true the buffer will be (re)allocated to fit in the * needed size. (Note: *buf may change due to this.) * * @param buf Address of the buffer to print to. * @param buf_len Address to an integer containing the size of buf. * @param out_len Incremented by the number of characters printed. * @param allow_realloc if not zero reallocate the buffer to fit the * needed size. * @param var The variable to encode. * @param enums The enumeration ff this variable is enumerated. may be NULL. * @param hint Contents of the DISPLAY-HINT clause of the MIB. * See RFC 1903 Section 3.1 for details. may be NULL. * @param units Contents of the UNITS clause of the MIB. may be NULL. * * @return 1 on success, or 0 on failure (out of memory, or buffer to * small when not allowed to realloc.) */ int sprint_realloc_float(u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, const netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { char *printf_format_string = NULL; if (var->type != ASN_OPAQUE_FLOAT) { if (!netsnmp_ds_get_boolean( NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICKE_PRINT)) { u_char str[] = "Wrong Type (should be Float): "; if (!snmp_strcat(buf, buf_len, out_len, allow_realloc, str)) return 0; } return sprint_realloc_by_type(buf, buf_len, out_len, allow_realloc, var, NULL, NULL, NULL); } if (!netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT)) { if (!snmp_cstrcat (buf, buf_len, out_len, allow_realloc, "Opaque: Float: ")) { return 0; } } /* * How much space needed for max. length float? 128 is overkill. */ while ((*out_len + 128 + 1) >= *buf_len) { if (!(allow_realloc && snmp_realloc(buf, buf_len))) { return 0; } } printf_format_string = make_printf_format_string("%f"); if (!printf_format_string) { return 0; } snprintf((char *)(*buf + *out_len), 128, printf_format_string, *var->val.floatVal); free(printf_format_string); *out_len += strlen((char *) (*buf + *out_len)); if (units) { return (snmp_cstrcat(buf, buf_len, out_len, allow_realloc, " ") && snmp_cstrcat(buf, buf_len, out_len, allow_realloc, units)); } return 1; } /** * Prints a double into a buffer. * * The variable var is encoded as a double precision floating point value. * * If allow_realloc is true the buffer will be (re)allocated to fit in the * needed size. (Note: *buf may change due to this.) * * @param buf Address of the buffer to print to. * @param buf_len Address to an integer containing the size of buf. * @param out_len Incremented by the number of characters printed. * @param allow_realloc if not zero reallocate the buffer to fit the * needed size. * @param var The variable to encode. * @param enums The enumeration ff this variable is enumerated. may be NULL. * @param hint Contents of the DISPLAY-HINT clause of the MIB. * See RFC 1903 Section 3.1 for details. may be NULL. * @param units Contents of the UNITS clause of the MIB. may be NULL. * * @return 1 on success, or 0 on failure (out of memory, or buffer to * small when not allowed to realloc.) */ int sprint_realloc_double(u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, const netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { char *printf_format_string = NULL; if (var->type != ASN_OPAQUE_DOUBLE) { if (!netsnmp_ds_get_boolean( NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICKE_PRINT)) { u_char str[] = "Wrong Type (should be Double): "; if (!snmp_strcat(buf, buf_len, out_len, allow_realloc, str)) return 0; } return sprint_realloc_by_type(buf, buf_len, out_len, allow_realloc, var, NULL, NULL, NULL); } if (!netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT)) { if (!snmp_cstrcat (buf, buf_len, out_len, allow_realloc, "Opaque: Float: ")) { return 0; } } /* * How much space needed for max. length double? 128 is overkill. */ while ((*out_len + 128 + 1) >= *buf_len) { if (!(allow_realloc && snmp_realloc(buf, buf_len))) { return 0; } } printf_format_string = make_printf_format_string("%f"); if (!printf_format_string) { return 0; } snprintf((char *)(*buf + *out_len), 128, printf_format_string, *var->val.doubleVal); free(printf_format_string); *out_len += strlen((char *) (*buf + *out_len)); if (units) { return (snmp_cstrcat (buf, buf_len, out_len, allow_realloc, " ") && snmp_cstrcat(buf, buf_len, out_len, allow_realloc, units)); } return 1; } #endif /* NETSNMP_WITH_OPAQUE_SPECIAL_TYPES */ /** * Prints a counter into a buffer. * * The variable var is encoded as a counter value. * * If allow_realloc is true the buffer will be (re)allocated to fit in the * needed size. (Note: *buf may change due to this.) * * @param buf Address of the buffer to print to. * @param buf_len Address to an integer containing the size of buf. * @param out_len Incremented by the number of characters printed. * @param allow_realloc if not zero reallocate the buffer to fit the * needed size. * @param var The variable to encode. * @param enums The enumeration ff this variable is enumerated. may be NULL. * @param hint Contents of the DISPLAY-HINT clause of the MIB. * See RFC 1903 Section 3.1 for details. may be NULL. * @param units Contents of the UNITS clause of the MIB. may be NULL. * * @return 1 on success, or 0 on failure (out of memory, or buffer to * small when not allowed to realloc.) */ int sprint_realloc_counter64(u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, const netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { char a64buf[I64CHARSZ + 1]; if (var->type != ASN_COUNTER64 #ifdef NETSNMP_WITH_OPAQUE_SPECIAL_TYPES && var->type != ASN_OPAQUE_COUNTER64 && var->type != ASN_OPAQUE_I64 && var->type != ASN_OPAQUE_U64 #endif ) { if (!netsnmp_ds_get_boolean( NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICKE_PRINT)) { u_char str[] = "Wrong Type (should be Counter64): "; if (!snmp_strcat(buf, buf_len, out_len, allow_realloc, str)) return 0; } return sprint_realloc_by_type(buf, buf_len, out_len, allow_realloc, var, NULL, NULL, NULL); } if (!netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT)) { #ifdef NETSNMP_WITH_OPAQUE_SPECIAL_TYPES if (var->type != ASN_COUNTER64) { if (!snmp_cstrcat (buf, buf_len, out_len, allow_realloc, "Opaque: ")) { return 0; } } #endif #ifdef NETSNMP_WITH_OPAQUE_SPECIAL_TYPES switch (var->type) { case ASN_OPAQUE_U64: if (!snmp_cstrcat (buf, buf_len, out_len, allow_realloc, "UInt64: ")) { return 0; } break; case ASN_OPAQUE_I64: if (!snmp_cstrcat (buf, buf_len, out_len, allow_realloc, "Int64: ")) { return 0; } break; case ASN_COUNTER64: case ASN_OPAQUE_COUNTER64: #endif if (!snmp_cstrcat (buf, buf_len, out_len, allow_realloc, "Counter64: ")) { return 0; } #ifdef NETSNMP_WITH_OPAQUE_SPECIAL_TYPES } #endif } #ifdef NETSNMP_WITH_OPAQUE_SPECIAL_TYPES if (var->type == ASN_OPAQUE_I64) { printI64(a64buf, var->val.counter64); if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, a64buf)) { return 0; } } else { #endif printU64(a64buf, var->val.counter64); if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, a64buf)) { return 0; } #ifdef NETSNMP_WITH_OPAQUE_SPECIAL_TYPES } #endif if (units) { return (snmp_cstrcat(buf, buf_len, out_len, allow_realloc, " ") && snmp_cstrcat(buf, buf_len, out_len, allow_realloc, units)); } return 1; } /** * Prints an object identifier into a buffer. * * If allow_realloc is true the buffer will be (re)allocated to fit in the * needed size. (Note: *buf may change due to this.) * * @param buf Address of the buffer to print to. * @param buf_len Address to an integer containing the size of buf. * @param out_len Incremented by the number of characters printed. * @param allow_realloc if not zero reallocate the buffer to fit the * needed size. * @param var The variable to encode. * @param enums The enumeration ff this variable is enumerated. may be NULL. * @param hint Contents of the DISPLAY-HINT clause of the MIB. * See RFC 1903 Section 3.1 for details. may be NULL. * @param units Contents of the UNITS clause of the MIB. may be NULL. * * @return 1 on success, or 0 on failure (out of memory, or buffer to * small when not allowed to realloc.) */ int sprint_realloc_opaque(u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, const netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { if (var->type != ASN_OPAQUE #ifdef NETSNMP_WITH_OPAQUE_SPECIAL_TYPES && var->type != ASN_OPAQUE_COUNTER64 && var->type != ASN_OPAQUE_U64 && var->type != ASN_OPAQUE_I64 && var->type != ASN_OPAQUE_FLOAT && var->type != ASN_OPAQUE_DOUBLE #endif /* NETSNMP_WITH_OPAQUE_SPECIAL_TYPES */ ) { if (!netsnmp_ds_get_boolean( NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICKE_PRINT)) { u_char str[] = "Wrong Type (should be Opaque): "; if (!snmp_strcat(buf, buf_len, out_len, allow_realloc, str)) return 0; } return sprint_realloc_by_type(buf, buf_len, out_len, allow_realloc, var, NULL, NULL, NULL); } #ifdef NETSNMP_WITH_OPAQUE_SPECIAL_TYPES switch (var->type) { case ASN_OPAQUE_COUNTER64: case ASN_OPAQUE_U64: case ASN_OPAQUE_I64: return sprint_realloc_counter64(buf, buf_len, out_len, allow_realloc, var, enums, hint, units); break; case ASN_OPAQUE_FLOAT: return sprint_realloc_float(buf, buf_len, out_len, allow_realloc, var, enums, hint, units); break; case ASN_OPAQUE_DOUBLE: return sprint_realloc_double(buf, buf_len, out_len, allow_realloc, var, enums, hint, units); break; case ASN_OPAQUE: #endif if (!netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT)) { u_char str[] = "OPAQUE: "; if (!snmp_strcat(buf, buf_len, out_len, allow_realloc, str)) { return 0; } } if (!sprint_realloc_hexstring(buf, buf_len, out_len, allow_realloc, var->val.string, var->val_len)) { return 0; } #ifdef NETSNMP_WITH_OPAQUE_SPECIAL_TYPES } #endif if (units) { return (snmp_strcat (buf, buf_len, out_len, allow_realloc, (const u_char *) " ") && snmp_strcat(buf, buf_len, out_len, allow_realloc, (const u_char *) units)); } return 1; } /** * Prints an object identifier into a buffer. * * If allow_realloc is true the buffer will be (re)allocated to fit in the * needed size. (Note: *buf may change due to this.) * * @param buf Address of the buffer to print to. * @param buf_len Address to an integer containing the size of buf. * @param out_len Incremented by the number of characters printed. * @param allow_realloc if not zero reallocate the buffer to fit the * needed size. * @param var The variable to encode. * @param enums The enumeration ff this variable is enumerated. may be NULL. * @param hint Contents of the DISPLAY-HINT clause of the MIB. * See RFC 1903 Section 3.1 for details. may be NULL. * @param units Contents of the UNITS clause of the MIB. may be NULL. * * @return 1 on success, or 0 on failure (out of memory, or buffer to * small when not allowed to realloc.) */ int sprint_realloc_object_identifier(u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, const netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { int buf_overflow = 0; if (var->type != ASN_OBJECT_ID) { if (!netsnmp_ds_get_boolean( NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICKE_PRINT)) { u_char str[] = "Wrong Type (should be OBJECT IDENTIFIER): "; if (!snmp_strcat(buf, buf_len, out_len, allow_realloc, str)) return 0; } return sprint_realloc_by_type(buf, buf_len, out_len, allow_realloc, var, NULL, NULL, NULL); } if (!netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT)) { u_char str[] = "OID: "; if (!snmp_strcat(buf, buf_len, out_len, allow_realloc, str)) { return 0; } } netsnmp_sprint_realloc_objid_tree(buf, buf_len, out_len, allow_realloc, &buf_overflow, (oid *) (var->val.objid), var->val_len / sizeof(oid)); if (buf_overflow) { return 0; } if (units) { return (snmp_strcat (buf, buf_len, out_len, allow_realloc, (const u_char *) " ") && snmp_strcat(buf, buf_len, out_len, allow_realloc, (const u_char *) units)); } return 1; } /** * Prints a timetick variable into a buffer. * * If allow_realloc is true the buffer will be (re)allocated to fit in the * needed size. (Note: *buf may change due to this.) * * @param buf Address of the buffer to print to. * @param buf_len Address to an integer containing the size of buf. * @param out_len Incremented by the number of characters printed. * @param allow_realloc if not zero reallocate the buffer to fit the * needed size. * @param var The variable to encode. * @param enums The enumeration ff this variable is enumerated. may be NULL. * @param hint Contents of the DISPLAY-HINT clause of the MIB. * See RFC 1903 Section 3.1 for details. may be NULL. * @param units Contents of the UNITS clause of the MIB. may be NULL. * * @return 1 on success, or 0 on failure (out of memory, or buffer to * small when not allowed to realloc.) */ int sprint_realloc_timeticks(u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, const netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { char timebuf[40]; if (var->type != ASN_TIMETICKS) { if (!netsnmp_ds_get_boolean( NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICKE_PRINT)) { u_char str[] = "Wrong Type (should be Timeticks): "; if (!snmp_strcat(buf, buf_len, out_len, allow_realloc, str)) return 0; } return sprint_realloc_by_type(buf, buf_len, out_len, allow_realloc, var, NULL, NULL, NULL); } if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_NUMERIC_TIMETICKS)) { char str[32]; sprintf(str, "%lu", *(u_long *) var->val.integer); if (!snmp_strcat (buf, buf_len, out_len, allow_realloc, (const u_char *) str)) { return 0; } return 1; } if (!netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT)) { char str[32]; sprintf(str, "Timeticks: (%lu) ", *(u_long *) var->val.integer); if (!snmp_strcat (buf, buf_len, out_len, allow_realloc, (const u_char *) str)) { return 0; } } uptimeString(*(u_long *) (var->val.integer), timebuf, sizeof(timebuf)); if (!snmp_strcat (buf, buf_len, out_len, allow_realloc, (const u_char *) timebuf)) { return 0; } if (units) { return (snmp_strcat (buf, buf_len, out_len, allow_realloc, (const u_char *) " ") && snmp_strcat(buf, buf_len, out_len, allow_realloc, (const u_char *) units)); } return 1; } /** * Prints an integer according to the hint into a buffer. * * If allow_realloc is true the buffer will be (re)allocated to fit in the * needed size. (Note: *buf may change due to this.) * * @param buf Address of the buffer to print to. * @param buf_len Address to an integer containing the size of buf. * @param out_len Incremented by the number of characters printed. * @param allow_realloc if not zero reallocate the buffer to fit the * needed size. * @param val The variable to encode. * @param decimaltype 'd' or 'u' depending on integer type * @param hint Contents of the DISPLAY-HINT clause of the MIB. * See RFC 1903 Section 3.1 for details. may _NOT_ be NULL. * @param units Contents of the UNITS clause of the MIB. may be NULL. * * @return 1 on success, or 0 on failure (out of memory, or buffer to * small when not allowed to realloc.) */ int sprint_realloc_hinted_integer(u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, long val, const char decimaltype, const char *hint, const char *units) { char fmt[10] = "%l@", tmp[256]; int shift = 0, len, negative = 0; if (hint[0] == 'd') { /* * We might *actually* want a 'u' here. */ if (hint[1] == '-') shift = atoi(hint + 2); fmt[2] = decimaltype; if (val < 0) { negative = 1; val = -val; } } else { /* * DISPLAY-HINT character is 'b', 'o', or 'x'. */ fmt[2] = hint[0]; } if (hint[0] == 'b') { unsigned long int bit = 0x80000000LU; char *bp = tmp; while (bit) { *bp++ = val & bit ? '1' : '0'; bit >>= 1; } *bp = 0; } else sprintf(tmp, fmt, val); if (shift != 0) { len = strlen(tmp); if (shift <= len) { tmp[len + 1] = 0; while (shift--) { tmp[len] = tmp[len - 1]; len--; } tmp[len] = '.'; } else { tmp[shift + 1] = 0; while (shift) { if (len-- > 0) { tmp[shift] = tmp[len]; } else { tmp[shift] = '0'; } shift--; } tmp[0] = '.'; } } if (negative) { len = strlen(tmp)+1; while (len) { tmp[len] = tmp[len-1]; len--; } tmp[0] = '-'; } return snmp_strcat(buf, buf_len, out_len, allow_realloc, (u_char *)tmp); } /** * Prints an integer into a buffer. * * If allow_realloc is true the buffer will be (re)allocated to fit in the * needed size. (Note: *buf may change due to this.) * * @param buf Address of the buffer to print to. * @param buf_len Address to an integer containing the size of buf. * @param out_len Incremented by the number of characters printed. * @param allow_realloc if not zero reallocate the buffer to fit the * needed size. * @param var The variable to encode. * @param enums The enumeration ff this variable is enumerated. may be NULL. * @param hint Contents of the DISPLAY-HINT clause of the MIB. * See RFC 1903 Section 3.1 for details. may be NULL. * @param units Contents of the UNITS clause of the MIB. may be NULL. * * @return 1 on success, or 0 on failure (out of memory, or buffer to * small when not allowed to realloc.) */ int sprint_realloc_integer(u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, const netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { char *enum_string = NULL; if (var->type != ASN_INTEGER) { if (!netsnmp_ds_get_boolean( NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICKE_PRINT)) { u_char str[] = "Wrong Type (should be INTEGER): "; if (!snmp_strcat(buf, buf_len, out_len, allow_realloc, str)) return 0; } return sprint_realloc_by_type(buf, buf_len, out_len, allow_realloc, var, NULL, NULL, NULL); } for (; enums; enums = enums->next) { if (enums->value == *var->val.integer) { enum_string = enums->label; break; } } if (!netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT)) { if (!snmp_strcat(buf, buf_len, out_len, allow_realloc, (const u_char *) "INTEGER: ")) { return 0; } } if (enum_string == NULL || netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PRINT_NUMERIC_ENUM)) { if (hint) { if (!(sprint_realloc_hinted_integer(buf, buf_len, out_len, allow_realloc, *var->val.integer, 'd', hint, units))) { return 0; } } else { char str[32]; sprintf(str, "%ld", *var->val.integer); if (!snmp_strcat (buf, buf_len, out_len, allow_realloc, (const u_char *) str)) { return 0; } } } else if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT)) { if (!snmp_strcat (buf, buf_len, out_len, allow_realloc, (const u_char *) enum_string)) { return 0; } } else { char str[32]; sprintf(str, "(%ld)", *var->val.integer); if (!snmp_strcat (buf, buf_len, out_len, allow_realloc, (const u_char *) enum_string)) { return 0; } if (!snmp_strcat (buf, buf_len, out_len, allow_realloc, (const u_char *) str)) { return 0; } } if (units) { return (snmp_strcat (buf, buf_len, out_len, allow_realloc, (const u_char *) " ") && snmp_strcat(buf, buf_len, out_len, allow_realloc, (const u_char *) units)); } return 1; } /** * Prints an unsigned integer into a buffer. * * If allow_realloc is true the buffer will be (re)allocated to fit in the * needed size. (Note: *buf may change due to this.) * * @param buf Address of the buffer to print to. * @param buf_len Address to an integer containing the size of buf. * @param out_len Incremented by the number of characters printed. * @param allow_realloc if not zero reallocate the buffer to fit the * needed size. * @param var The variable to encode. * @param enums The enumeration ff this variable is enumerated. may be NULL. * @param hint Contents of the DISPLAY-HINT clause of the MIB. * See RFC 1903 Section 3.1 for details. may be NULL. * @param units Contents of the UNITS clause of the MIB. may be NULL. * * @return 1 on success, or 0 on failure (out of memory, or buffer to * small when not allowed to realloc.) */ int sprint_realloc_uinteger(u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, const netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { char *enum_string = NULL; if (var->type != ASN_UINTEGER) { if (!netsnmp_ds_get_boolean( NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICKE_PRINT)) { u_char str[] = "Wrong Type (should be UInteger32): "; if (!snmp_strcat(buf, buf_len, out_len, allow_realloc, str)) return 0; } return sprint_realloc_by_type(buf, buf_len, out_len, allow_realloc, var, NULL, NULL, NULL); } for (; enums; enums = enums->next) { if (enums->value == *var->val.integer) { enum_string = enums->label; break; } } if (enum_string == NULL || netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PRINT_NUMERIC_ENUM)) { if (hint) { if (!(sprint_realloc_hinted_integer(buf, buf_len, out_len, allow_realloc, *var->val.integer, 'u', hint, units))) { return 0; } } else { char str[32]; sprintf(str, "%lu", *var->val.integer); if (!snmp_strcat (buf, buf_len, out_len, allow_realloc, (const u_char *) str)) { return 0; } } } else if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT)) { if (!snmp_strcat (buf, buf_len, out_len, allow_realloc, (const u_char *) enum_string)) { return 0; } } else { char str[32]; sprintf(str, "(%lu)", *var->val.integer); if (!snmp_strcat (buf, buf_len, out_len, allow_realloc, (const u_char *) enum_string)) { return 0; } if (!snmp_strcat (buf, buf_len, out_len, allow_realloc, (const u_char *) str)) { return 0; } } if (units) { return (snmp_strcat (buf, buf_len, out_len, allow_realloc, (const u_char *) " ") && snmp_strcat(buf, buf_len, out_len, allow_realloc, (const u_char *) units)); } return 1; } /** * Prints a gauge value into a buffer. * * If allow_realloc is true the buffer will be (re)allocated to fit in the * needed size. (Note: *buf may change due to this.) * * @param buf Address of the buffer to print to. * @param buf_len Address to an integer containing the size of buf. * @param out_len Incremented by the number of characters printed. * @param allow_realloc if not zero reallocate the buffer to fit the * needed size. * @param var The variable to encode. * @param enums The enumeration ff this variable is enumerated. may be NULL. * @param hint Contents of the DISPLAY-HINT clause of the MIB. * See RFC 1903 Section 3.1 for details. may be NULL. * @param units Contents of the UNITS clause of the MIB. may be NULL. * * @return 1 on success, or 0 on failure (out of memory, or buffer to * small when not allowed to realloc.) */ int sprint_realloc_gauge(u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, const netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { char tmp[32]; if (var->type != ASN_GAUGE) { if (!netsnmp_ds_get_boolean( NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICKE_PRINT)) { u_char str[] = "Wrong Type (should be Gauge32 or Unsigned32): "; if (!snmp_strcat(buf, buf_len, out_len, allow_realloc, str)) return 0; } return sprint_realloc_by_type(buf, buf_len, out_len, allow_realloc, var, NULL, NULL, NULL); } if (!netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT)) { u_char str[] = "Gauge32: "; if (!snmp_strcat(buf, buf_len, out_len, allow_realloc, str)) { return 0; } } if (hint) { if (!sprint_realloc_hinted_integer(buf, buf_len, out_len, allow_realloc, *var->val.integer, 'u', hint, units)) { return 0; } } else { sprintf(tmp, "%u", (unsigned int)(*var->val.integer & 0xffffffff)); if (!snmp_strcat (buf, buf_len, out_len, allow_realloc, (const u_char *) tmp)) { return 0; } } if (units) { return (snmp_strcat (buf, buf_len, out_len, allow_realloc, (const u_char *) " ") && snmp_strcat(buf, buf_len, out_len, allow_realloc, (const u_char *) units)); } return 1; } /** * Prints a counter value into a buffer. * * If allow_realloc is true the buffer will be (re)allocated to fit in the * needed size. (Note: *buf may change due to this.) * * @param buf Address of the buffer to print to. * @param buf_len Address to an integer containing the size of buf. * @param out_len Incremented by the number of characters printed. * @param allow_realloc if not zero reallocate the buffer to fit the * needed size. * @param var The variable to encode. * @param enums The enumeration ff this variable is enumerated. may be NULL. * @param hint Contents of the DISPLAY-HINT clause of the MIB. * See RFC 1903 Section 3.1 for details. may be NULL. * @param units Contents of the UNITS clause of the MIB. may be NULL. * * @return 1 on success, or 0 on failure (out of memory, or buffer to * small when not allowed to realloc.) */ int sprint_realloc_counter(u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, const netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { char tmp[32]; if (var->type != ASN_COUNTER) { if (!netsnmp_ds_get_boolean( NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICKE_PRINT)) { u_char str[] = "Wrong Type (should be Counter32): "; if (!snmp_strcat(buf, buf_len, out_len, allow_realloc, str)) return 0; } return sprint_realloc_by_type(buf, buf_len, out_len, allow_realloc, var, NULL, NULL, NULL); } if (!netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT)) { u_char str[] = "Counter32: "; if (!snmp_strcat(buf, buf_len, out_len, allow_realloc, str)) { return 0; } } sprintf(tmp, "%u", (unsigned int)(*var->val.integer & 0xffffffff)); if (!snmp_strcat (buf, buf_len, out_len, allow_realloc, (const u_char *) tmp)) { return 0; } if (units) { return (snmp_strcat (buf, buf_len, out_len, allow_realloc, (const u_char *) " ") && snmp_strcat(buf, buf_len, out_len, allow_realloc, (const u_char *) units)); } return 1; } /** * Prints a network address into a buffer. * * If allow_realloc is true the buffer will be (re)allocated to fit in the * needed size. (Note: *buf may change due to this.) * * @param buf Address of the buffer to print to. * @param buf_len Address to an integer containing the size of buf. * @param out_len Incremented by the number of characters printed. * @param allow_realloc if not zero reallocate the buffer to fit the * needed size. * @param var The variable to encode. * @param enums The enumeration ff this variable is enumerated. may be NULL. * @param hint Contents of the DISPLAY-HINT clause of the MIB. * See RFC 1903 Section 3.1 for details. may be NULL. * @param units Contents of the UNITS clause of the MIB. may be NULL. * * @return 1 on success, or 0 on failure (out of memory, or buffer to * small when not allowed to realloc.) */ int sprint_realloc_networkaddress(u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, const netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { size_t i; if (var->type != ASN_IPADDRESS) { if (!netsnmp_ds_get_boolean( NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICKE_PRINT)) { u_char str[] = "Wrong Type (should be NetworkAddress): "; if (!snmp_strcat(buf, buf_len, out_len, allow_realloc, str)) return 0; } return sprint_realloc_by_type(buf, buf_len, out_len, allow_realloc, var, NULL, NULL, NULL); } if (!netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT)) { u_char str[] = "Network Address: "; if (!snmp_strcat(buf, buf_len, out_len, allow_realloc, str)) { return 0; } } while ((*out_len + (var->val_len * 3) + 2) >= *buf_len) { if (!(allow_realloc && snmp_realloc(buf, buf_len))) { return 0; } } for (i = 0; i < var->val_len; i++) { sprintf((char *) (*buf + *out_len), "%02X", var->val.string[i]); *out_len += 2; if (i < var->val_len - 1) { *(*buf + *out_len) = ':'; (*out_len)++; } } return 1; } /** * Prints an ip-address into a buffer. * * If allow_realloc is true the buffer will be (re)allocated to fit in the * needed size. (Note: *buf may change due to this.) * * @param buf Address of the buffer to print to. * @param buf_len Address to an integer containing the size of buf. * @param out_len Incremented by the number of characters printed. * @param allow_realloc if not zero reallocate the buffer to fit the * needed size. * @param var The variable to encode. * @param enums The enumeration ff this variable is enumerated. may be NULL. * @param hint Contents of the DISPLAY-HINT clause of the MIB. * See RFC 1903 Section 3.1 for details. may be NULL. * @param units Contents of the UNITS clause of the MIB. may be NULL. * * @return 1 on success, or 0 on failure (out of memory, or buffer to * small when not allowed to realloc.) */ int sprint_realloc_ipaddress(u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, const netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { u_char *ip = var->val.string; if (var->type != ASN_IPADDRESS) { if (!netsnmp_ds_get_boolean( NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICKE_PRINT)) { u_char str[] = "Wrong Type (should be IpAddress): "; if (!snmp_strcat(buf, buf_len, out_len, allow_realloc, str)) return 0; } return sprint_realloc_by_type(buf, buf_len, out_len, allow_realloc, var, NULL, NULL, NULL); } if (!netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT)) { u_char str[] = "IpAddress: "; if (!snmp_strcat(buf, buf_len, out_len, allow_realloc, str)) { return 0; } } while ((*out_len + 17) >= *buf_len) { if (!(allow_realloc && snmp_realloc(buf, buf_len))) { return 0; } } if (ip) sprintf((char *) (*buf + *out_len), "%d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]); *out_len += strlen((char *) (*buf + *out_len)); return 1; } /** * Prints a null value into a buffer. * * If allow_realloc is true the buffer will be (re)allocated to fit in the * needed size. (Note: *buf may change due to this.) * * @param buf Address of the buffer to print to. * @param buf_len Address to an integer containing the size of buf. * @param out_len Incremented by the number of characters printed. * @param allow_realloc if not zero reallocate the buffer to fit the * needed size. * @param var The variable to encode. * @param enums The enumeration ff this variable is enumerated. may be NULL. * @param hint Contents of the DISPLAY-HINT clause of the MIB. * See RFC 1903 Section 3.1 for details. may be NULL. * @param units Contents of the UNITS clause of the MIB. may be NULL. * * @return 1 on success, or 0 on failure (out of memory, or buffer to * small when not allowed to realloc.) */ int sprint_realloc_null(u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, const netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { u_char str[] = "NULL"; if (var->type != ASN_NULL) { if (!netsnmp_ds_get_boolean( NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICKE_PRINT)) { u_char str[] = "Wrong Type (should be NULL): "; if (!snmp_strcat(buf, buf_len, out_len, allow_realloc, str)) return 0; } return sprint_realloc_by_type(buf, buf_len, out_len, allow_realloc, var, NULL, NULL, NULL); } return snmp_strcat(buf, buf_len, out_len, allow_realloc, str); } /** * Prints a bit string into a buffer. * * If allow_realloc is true the buffer will be (re)allocated to fit in the * needed size. (Note: *buf may change due to this.) * * @param buf Address of the buffer to print to. * @param buf_len Address to an integer containing the size of buf. * @param out_len Incremented by the number of characters printed. * @param allow_realloc if not zero reallocate the buffer to fit the * needed size. * @param var The variable to encode. * @param enums The enumeration ff this variable is enumerated. may be NULL. * @param hint Contents of the DISPLAY-HINT clause of the MIB. * See RFC 1903 Section 3.1 for details. may be NULL. * @param units Contents of the UNITS clause of the MIB. may be NULL. * * @return 1 on success, or 0 on failure (out of memory, or buffer to * small when not allowed to realloc.) */ int sprint_realloc_bitstring(u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, const netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { int len, bit; u_char *cp; char *enum_string; if (var->type != ASN_BIT_STR && var->type != ASN_OCTET_STR) { if (!netsnmp_ds_get_boolean( NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICKE_PRINT)) { u_char str[] = "Wrong Type (should be BITS): "; if (!snmp_strcat(buf, buf_len, out_len, allow_realloc, str)) return 0; } return sprint_realloc_by_type(buf, buf_len, out_len, allow_realloc, var, NULL, NULL, NULL); } if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT)) { u_char str[] = "\""; if (!snmp_strcat(buf, buf_len, out_len, allow_realloc, str)) { return 0; } } else { u_char str[] = "BITS: "; if (!snmp_strcat(buf, buf_len, out_len, allow_realloc, str)) { return 0; } } if (!sprint_realloc_hexstring(buf, buf_len, out_len, allow_realloc, var->val.bitstring, var->val_len)) { return 0; } if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT)) { u_char str[] = "\""; if (!snmp_strcat(buf, buf_len, out_len, allow_realloc, str)) { return 0; } } else { cp = var->val.bitstring; for (len = 0; len < (int) var->val_len; len++) { for (bit = 0; bit < 8; bit++) { if (*cp & (0x80 >> bit)) { enum_string = NULL; for (; enums; enums = enums->next) { if (enums->value == (len * 8) + bit) { enum_string = enums->label; break; } } if (enum_string == NULL || netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PRINT_NUMERIC_ENUM)) { char str[32]; sprintf(str, "%d ", (len * 8) + bit); if (!snmp_strcat (buf, buf_len, out_len, allow_realloc, (const u_char *) str)) { return 0; } } else { char str[32]; sprintf(str, "(%d) ", (len * 8) + bit); if (!snmp_strcat (buf, buf_len, out_len, allow_realloc, (const u_char *) enum_string)) { return 0; } if (!snmp_strcat (buf, buf_len, out_len, allow_realloc, (const u_char *) str)) { return 0; } } } } cp++; } } return 1; } int sprint_realloc_nsapaddress(u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, const netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { if (var->type != ASN_NSAP) { if (!netsnmp_ds_get_boolean( NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICKE_PRINT)) { u_char str[] = "Wrong Type (should be NsapAddress): "; if (!snmp_strcat(buf, buf_len, out_len, allow_realloc, str)) return 0; } return sprint_realloc_by_type(buf, buf_len, out_len, allow_realloc, var, NULL, NULL, NULL); } if (!netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT)) { u_char str[] = "NsapAddress: "; if (!snmp_strcat(buf, buf_len, out_len, allow_realloc, str)) { return 0; } } return sprint_realloc_hexstring(buf, buf_len, out_len, allow_realloc, var->val.string, var->val_len); } /** * Fallback routine for a bad type, prints "Variable has bad type" into a buffer. * * If allow_realloc is true the buffer will be (re)allocated to fit in the * needed size. (Note: *buf may change due to this.) * * @param buf Address of the buffer to print to. * @param buf_len Address to an integer containing the size of buf. * @param out_len Incremented by the number of characters printed. * @param allow_realloc if not zero reallocate the buffer to fit the * needed size. * @param var The variable to encode. * @param enums The enumeration ff this variable is enumerated. may be NULL. * @param hint Contents of the DISPLAY-HINT clause of the MIB. * See RFC 1903 Section 3.1 for details. may be NULL. * @param units Contents of the UNITS clause of the MIB. may be NULL. * * @return 1 on success, or 0 on failure (out of memory, or buffer to * small when not allowed to realloc.) */ int sprint_realloc_badtype(u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, const netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { u_char str[] = "Variable has bad type"; return snmp_strcat(buf, buf_len, out_len, allow_realloc, str); } /** * Universal print routine, prints a variable into a buffer according to the variable * type. * * If allow_realloc is true the buffer will be (re)allocated to fit in the * needed size. (Note: *buf may change due to this.) * * @param buf Address of the buffer to print to. * @param buf_len Address to an integer containing the size of buf. * @param out_len Incremented by the number of characters printed. * @param allow_realloc if not zero reallocate the buffer to fit the * needed size. * @param var The variable to encode. * @param enums The enumeration ff this variable is enumerated. may be NULL. * @param hint Contents of the DISPLAY-HINT clause of the MIB. * See RFC 1903 Section 3.1 for details. may be NULL. * @param units Contents of the UNITS clause of the MIB. may be NULL. * * @return 1 on success, or 0 on failure (out of memory, or buffer to * small when not allowed to realloc.) */ int sprint_realloc_by_type(u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, const netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { DEBUGMSGTL(("output", "sprint_by_type, type %d\n", var->type)); switch (var->type) { case ASN_INTEGER: return sprint_realloc_integer(buf, buf_len, out_len, allow_realloc, var, enums, hint, units); case ASN_OCTET_STR: return sprint_realloc_octet_string(buf, buf_len, out_len, allow_realloc, var, enums, hint, units); case ASN_BIT_STR: return sprint_realloc_bitstring(buf, buf_len, out_len, allow_realloc, var, enums, hint, units); case ASN_OPAQUE: return sprint_realloc_opaque(buf, buf_len, out_len, allow_realloc, var, enums, hint, units); case ASN_OBJECT_ID: return sprint_realloc_object_identifier(buf, buf_len, out_len, allow_realloc, var, enums, hint, units); case ASN_TIMETICKS: return sprint_realloc_timeticks(buf, buf_len, out_len, allow_realloc, var, enums, hint, units); case ASN_GAUGE: return sprint_realloc_gauge(buf, buf_len, out_len, allow_realloc, var, enums, hint, units); case ASN_COUNTER: return sprint_realloc_counter(buf, buf_len, out_len, allow_realloc, var, enums, hint, units); case ASN_IPADDRESS: return sprint_realloc_ipaddress(buf, buf_len, out_len, allow_realloc, var, enums, hint, units); case ASN_NULL: return sprint_realloc_null(buf, buf_len, out_len, allow_realloc, var, enums, hint, units); case ASN_UINTEGER: return sprint_realloc_uinteger(buf, buf_len, out_len, allow_realloc, var, enums, hint, units); case ASN_COUNTER64: #ifdef NETSNMP_WITH_OPAQUE_SPECIAL_TYPES case ASN_OPAQUE_U64: case ASN_OPAQUE_I64: case ASN_OPAQUE_COUNTER64: #endif /* NETSNMP_WITH_OPAQUE_SPECIAL_TYPES */ return sprint_realloc_counter64(buf, buf_len, out_len, allow_realloc, var, enums, hint, units); #ifdef NETSNMP_WITH_OPAQUE_SPECIAL_TYPES case ASN_OPAQUE_FLOAT: return sprint_realloc_float(buf, buf_len, out_len, allow_realloc, var, enums, hint, units); case ASN_OPAQUE_DOUBLE: return sprint_realloc_double(buf, buf_len, out_len, allow_realloc, var, enums, hint, units); #endif /* NETSNMP_WITH_OPAQUE_SPECIAL_TYPES */ default: DEBUGMSGTL(("sprint_by_type", "bad type: %d\n", var->type)); return sprint_realloc_badtype(buf, buf_len, out_len, allow_realloc, var, enums, hint, units); } } /** * Generates a prinf format string. * * The original format string is combined with the optional * NETSNMP_DS_LIB_OUTPUT_PRECISION string (the -Op parameter). * * Example: * If the original format string is "%f", and the NETSNMP_DS_LIB_OUTPUT_PRECISION * is "5.2", the returned format string will be "%5.2f". * * The PRECISION string is inserted after the '%' of the original format string. * To prevent buffer overflow if NETSNMP_DS_LIB_OUTPUT_PRECISION is set to an * illegal size (e.g. with -Op 10000) snprintf should be used to prevent buffer * overflow. * * @param printf_format_default The format string used by the original printf. * * @return The address of of the new allocated format string (which must be freed * if no longer used), or NULL if any error (malloc). */ char * make_printf_format_string(const char *printf_format_default) { const char *cp_printf_format_default; const char *printf_precision; const char *cp_printf_precision; char *printf_format_string; char *cp_out; char c; printf_precision = netsnmp_ds_get_string(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OUTPUT_PRECISION); if (!printf_precision) { printf_precision = ""; } /* reserve new format string buffer */ printf_format_string = (char *) malloc(strlen(printf_format_default)+strlen(printf_precision)+1); if (!printf_format_string) { DEBUGMSGTL(("make_printf_format_string", "malloc failed\n")); return NULL; } /* copy default format string, including the '%' */ cp_out = printf_format_string; cp_printf_format_default = printf_format_default; while((c = *cp_printf_format_default) != '\0') { *cp_out++ = c; cp_printf_format_default++; if (c == '%') break; } /* insert the precision string */ cp_printf_precision = printf_precision; while ((c = *cp_printf_precision++) != '\0') { *cp_out++ = c; } /* copy the remaining default format string, including the terminating '\0' */ strcpy(cp_out, cp_printf_format_default); DEBUGMSGTL(("make_printf_format_string", "\"%s\"+\"%s\"->\"%s\"\n", printf_format_default, printf_precision, printf_format_string)); return printf_format_string; } #ifndef NETSNMP_DISABLE_MIB_LOADING /** * Retrieves the tree head. * * @return the tree head. */ struct tree * get_tree_head(void) { return (tree_head); } static char *confmibdir = NULL; static char *confmibs = NULL; static void handle_mibdirs_conf(const char *token, char *line) { char *ctmp; if (confmibdir) { if ((*line == '+') || (*line == '-')) { ctmp = (char *) malloc(strlen(confmibdir) + strlen(line) + 2); if (!ctmp) { DEBUGMSGTL(("read_config:initmib", "mibdir conf malloc failed")); return; } if(*line++ == '+') sprintf(ctmp, "%s%c%s", confmibdir, ENV_SEPARATOR_CHAR, line); else sprintf(ctmp, "%s%c%s", line, ENV_SEPARATOR_CHAR, confmibdir); } else { ctmp = strdup(line); if (!ctmp) { DEBUGMSGTL(("read_config:initmib", "mibs conf malloc failed")); return; } } SNMP_FREE(confmibdir); } else { ctmp = strdup(line); if (!ctmp) { DEBUGMSGTL(("read_config:initmib", "mibs conf malloc failed")); return; } } confmibdir = ctmp; DEBUGMSGTL(("read_config:initmib", "using mibdirs: %s\n", confmibdir)); } static void handle_mibs_conf(const char *token, char *line) { char *ctmp; if (confmibs) { if ((*line == '+') || (*line == '-')) { ctmp = (char *) malloc(strlen(confmibs) + strlen(line) + 2); if (!ctmp) { DEBUGMSGTL(("read_config:initmib", "mibs conf malloc failed")); return; } if(*line++ == '+') sprintf(ctmp, "%s%c%s", confmibs, ENV_SEPARATOR_CHAR, line); else sprintf(ctmp, "%s%c%s", line, ENV_SEPARATOR_CHAR, confmibdir); } else { ctmp = strdup(line); if (!ctmp) { DEBUGMSGTL(("read_config:initmib", "mibs conf malloc failed")); return; } } SNMP_FREE(confmibs); } else { ctmp = strdup(line); if (!ctmp) { DEBUGMSGTL(("read_config:initmib", "mibs conf malloc failed")); return; } } confmibs = ctmp; DEBUGMSGTL(("read_config:initmib", "using mibs: %s\n", confmibs)); } static void handle_mibfile_conf(const char *token, char *line) { DEBUGMSGTL(("read_config:initmib", "reading mibfile: %s\n", line)); read_mib(line); } #endif static void handle_print_numeric(const char *token, char *line) { const char *value; char *st; value = strtok_r(line, " \t\n", &st); if (value && ( (strcasecmp(value, "yes") == 0) || (strcasecmp(value, "true") == 0) || (*value == '1') )) { netsnmp_ds_set_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OID_OUTPUT_FORMAT, NETSNMP_OID_OUTPUT_NUMERIC); } } char * snmp_out_options(char *options, int argc, char *const *argv) { while (*options) { switch (*options++) { case '0': netsnmp_ds_toggle_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_2DIGIT_HEX_OUTPUT); break; case 'a': netsnmp_ds_set_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_STRING_OUTPUT_FORMAT, NETSNMP_STRING_OUTPUT_ASCII); break; case 'b': netsnmp_ds_toggle_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_DONT_BREAKDOWN_OIDS); break; case 'e': netsnmp_ds_toggle_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PRINT_NUMERIC_ENUM); break; case 'E': netsnmp_ds_toggle_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_ESCAPE_QUOTES); break; case 'f': netsnmp_ds_set_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OID_OUTPUT_FORMAT, NETSNMP_OID_OUTPUT_FULL); break; case 'n': netsnmp_ds_set_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OID_OUTPUT_FORMAT, NETSNMP_OID_OUTPUT_NUMERIC); break; case 'p': /* What if argc/argv are null ? */ if (!*(options)) { options = argv[optind++]; } netsnmp_ds_set_string(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OUTPUT_PRECISION, options); return NULL; /* -Op... is a standalone option, so we're done here */ case 'q': netsnmp_ds_toggle_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT); break; case 'Q': netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICKE_PRINT, 1); netsnmp_ds_toggle_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT); break; case 's': netsnmp_ds_set_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OID_OUTPUT_FORMAT, NETSNMP_OID_OUTPUT_SUFFIX); break; case 'S': netsnmp_ds_set_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OID_OUTPUT_FORMAT, NETSNMP_OID_OUTPUT_MODULE); break; case 't': netsnmp_ds_toggle_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_NUMERIC_TIMETICKS); break; case 'T': netsnmp_ds_toggle_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PRINT_HEX_TEXT); break; case 'u': netsnmp_ds_set_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OID_OUTPUT_FORMAT, NETSNMP_OID_OUTPUT_UCD); break; case 'U': netsnmp_ds_toggle_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_DONT_PRINT_UNITS); break; case 'v': netsnmp_ds_toggle_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PRINT_BARE_VALUE); break; case 'x': netsnmp_ds_set_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_STRING_OUTPUT_FORMAT, NETSNMP_STRING_OUTPUT_HEX); break; case 'X': netsnmp_ds_toggle_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_EXTENDED_INDEX); break; default: return options - 1; } } return NULL; } char * snmp_out_toggle_options(char *options) { return snmp_out_options( options, 0, NULL ); } void snmp_out_toggle_options_usage(const char *lead, FILE * outf) { fprintf(outf, "%s0: print leading 0 for single-digit hex characters\n", lead); fprintf(outf, "%sa: print all strings in ascii format\n", lead); fprintf(outf, "%sb: do not break OID indexes down\n", lead); fprintf(outf, "%se: print enums numerically\n", lead); fprintf(outf, "%sE: escape quotes in string indices\n", lead); fprintf(outf, "%sf: print full OIDs on output\n", lead); fprintf(outf, "%sn: print OIDs numerically\n", lead); fprintf(outf, "%sp PRECISION: display floating point values with specified PRECISION (printf format string)\n", lead); fprintf(outf, "%sq: quick print for easier parsing\n", lead); fprintf(outf, "%sQ: quick print with equal-signs\n", lead); /* @@JDW */ fprintf(outf, "%ss: print only last symbolic element of OID\n", lead); fprintf(outf, "%sS: print MIB module-id plus last element\n", lead); fprintf(outf, "%st: print timeticks unparsed as numeric integers\n", lead); fprintf(outf, "%sT: print human-readable text along with hex strings\n", lead); fprintf(outf, "%su: print OIDs using UCD-style prefix suppression\n", lead); fprintf(outf, "%sU: don't print units\n", lead); fprintf(outf, "%sv: print values only (not OID = value)\n", lead); fprintf(outf, "%sx: print all strings in hex format\n", lead); fprintf(outf, "%sX: extended index format\n", lead); } char * snmp_in_options(char *optarg, int argc, char *const *argv) { char *cp; for (cp = optarg; *cp; cp++) { switch (*cp) { case 'b': netsnmp_ds_toggle_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_REGEX_ACCESS); break; case 'R': netsnmp_ds_toggle_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_RANDOM_ACCESS); break; case 'r': netsnmp_ds_toggle_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_DONT_CHECK_RANGE); break; case 'h': netsnmp_ds_toggle_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_NO_DISPLAY_HINT); break; case 'u': netsnmp_ds_toggle_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_READ_UCD_STYLE_OID); break; case 's': /* What if argc/argv are null ? */ if (!*(++cp)) cp = argv[optind++]; netsnmp_ds_set_string(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OIDSUFFIX, cp); return NULL; /* -Is... is a standalone option, so we're done here */ case 'S': /* What if argc/argv are null ? */ if (!*(++cp)) cp = argv[optind++]; netsnmp_ds_set_string(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OIDPREFIX, cp); return NULL; /* -IS... is a standalone option, so we're done here */ default: /* * Here? Or in snmp_parse_args? snmp_log(LOG_ERR, "Unknown input option passed to -I: %c.\n", *cp); */ return cp; } } return NULL; } char * snmp_in_toggle_options(char *options) { return snmp_in_options( options, 0, NULL ); } /** * Prints out a help usage for the in* toggle options. * * @param lead The lead to print for every line. * @param outf The file descriptor to write to. * */ void snmp_in_toggle_options_usage(const char *lead, FILE * outf) { fprintf(outf, "%sb: do best/regex matching to find a MIB node\n", lead); fprintf(outf, "%sh: don't apply DISPLAY-HINTs\n", lead); fprintf(outf, "%sr: do not check values for range/type legality\n", lead); fprintf(outf, "%sR: do random access to OID labels\n", lead); fprintf(outf, "%su: top-level OIDs must have '.' prefix (UCD-style)\n", lead); fprintf(outf, "%ss SUFFIX: Append all textual OIDs with SUFFIX before parsing\n", lead); fprintf(outf, "%sS PREFIX: Prepend all textual OIDs with PREFIX before parsing\n", lead); } /*** * */ void register_mib_handlers(void) { #ifndef NETSNMP_DISABLE_MIB_LOADING register_prenetsnmp_mib_handler("snmp", "mibdirs", handle_mibdirs_conf, NULL, "[mib-dirs|+mib-dirs|-mib-dirs]"); register_prenetsnmp_mib_handler("snmp", "mibs", handle_mibs_conf, NULL, "[mib-tokens|+mib-tokens]"); register_config_handler("snmp", "mibfile", handle_mibfile_conf, NULL, "mibfile-to-read"); /* * register the snmp.conf configuration handlers for default * parsing behaviour */ netsnmp_ds_register_premib(ASN_BOOLEAN, "snmp", "showMibErrors", NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_ERRORS); netsnmp_ds_register_premib(ASN_BOOLEAN, "snmp", "commentToEOL", /* Describes actual behaviour */ NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_COMMENT_TERM); netsnmp_ds_register_premib(ASN_BOOLEAN, "snmp", "strictCommentTerm", /* Backward compatibility */ NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_COMMENT_TERM); netsnmp_ds_register_premib(ASN_BOOLEAN, "snmp", "mibAllowUnderline", NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_PARSE_LABEL); netsnmp_ds_register_premib(ASN_INTEGER, "snmp", "mibWarningLevel", NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_WARNINGS); netsnmp_ds_register_premib(ASN_BOOLEAN, "snmp", "mibReplaceWithLatest", NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_REPLACE); #endif netsnmp_ds_register_premib(ASN_BOOLEAN, "snmp", "printNumericEnums", NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PRINT_NUMERIC_ENUM); register_prenetsnmp_mib_handler("snmp", "printNumericOids", handle_print_numeric, NULL, "(1|yes|true|0|no|false)"); netsnmp_ds_register_premib(ASN_BOOLEAN, "snmp", "escapeQuotes", NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_ESCAPE_QUOTES); netsnmp_ds_register_premib(ASN_BOOLEAN, "snmp", "dontBreakdownOids", NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_DONT_BREAKDOWN_OIDS); netsnmp_ds_register_premib(ASN_BOOLEAN, "snmp", "quickPrinting", NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT); netsnmp_ds_register_premib(ASN_BOOLEAN, "snmp", "numericTimeticks", NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_NUMERIC_TIMETICKS); netsnmp_ds_register_premib(ASN_INTEGER, "snmp", "oidOutputFormat", NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OID_OUTPUT_FORMAT); netsnmp_ds_register_premib(ASN_INTEGER, "snmp", "suffixPrinting", NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OID_OUTPUT_FORMAT); netsnmp_ds_register_premib(ASN_BOOLEAN, "snmp", "extendedIndex", NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_EXTENDED_INDEX); netsnmp_ds_register_premib(ASN_BOOLEAN, "snmp", "printHexText", NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PRINT_HEX_TEXT); netsnmp_ds_register_premib(ASN_BOOLEAN, "snmp", "printValueOnly", NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PRINT_BARE_VALUE); netsnmp_ds_register_premib(ASN_BOOLEAN, "snmp", "dontPrintUnits", NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_DONT_PRINT_UNITS); netsnmp_ds_register_premib(ASN_INTEGER, "snmp", "hexOutputLength", NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_HEX_OUTPUT_LENGTH); } #ifndef NETSNMP_DISABLE_MIB_LOADING /* * function : netsnmp_set_mib_directory * - This function sets the string of the directories * from which the MIB modules will be searched or * loaded. * arguments: const char *dir, which are the directories * from which the MIB modules will be searched or * loaded. * returns : - */ void netsnmp_set_mib_directory(const char *dir) { const char *newdir; char *olddir, *tmpdir = NULL; DEBUGTRACE; if (NULL == dir) { return; } olddir = netsnmp_ds_get_string(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIBDIRS); if (olddir) { if ((*dir == '+') || (*dir == '-')) { /** New dir starts with '+', thus we add it. */ tmpdir = (char *)malloc(strlen(dir) + strlen(olddir) + 2); if (!tmpdir) { DEBUGMSGTL(("read_config:initmib", "set mibdir malloc failed")); return; } if (*dir++ == '+') sprintf(tmpdir, "%s%c%s", olddir, ENV_SEPARATOR_CHAR, dir); else sprintf(tmpdir, "%s%c%s", dir, ENV_SEPARATOR_CHAR, olddir); newdir = tmpdir; } else { newdir = dir; } } else { /** If dir starts with '+' skip '+' it. */ newdir = ((*dir == '+') ? ++dir : dir); } netsnmp_ds_set_string(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIBDIRS, newdir); /** set_string calls strdup, so if we allocated memory, free it */ if (tmpdir == newdir) { SNMP_FREE(tmpdir); } } /* * function : netsnmp_get_mib_directory * - This function returns a string of the directories * from which the MIB modules will be searched or * loaded. * If the value still does not exists, it will be made * from the evironment variable 'MIBDIRS' and/or the * default. * arguments: - * returns : char * of the directories in which the MIB modules * will be searched/loaded. */ char * netsnmp_get_mib_directory(void) { char *dir; DEBUGTRACE; dir = netsnmp_ds_get_string(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIBDIRS); if (dir == NULL) { DEBUGMSGTL(("get_mib_directory", "no mib directories set\n")); /** Check if the environment variable is set */ dir = netsnmp_getenv("MIBDIRS"); if (dir == NULL) { DEBUGMSGTL(("get_mib_directory", "no mib directories set by environment\n")); /** Not set use hard coded path */ if (confmibdir == NULL) { DEBUGMSGTL(("get_mib_directory", "no mib directories set by config\n")); netsnmp_set_mib_directory(NETSNMP_DEFAULT_MIBDIRS); } else if ((*confmibdir == '+') || (*confmibdir == '-')) { DEBUGMSGTL(("get_mib_directory", "mib directories set by config (but added)\n")); netsnmp_set_mib_directory(NETSNMP_DEFAULT_MIBDIRS); netsnmp_set_mib_directory(confmibdir); } else { DEBUGMSGTL(("get_mib_directory", "mib directories set by config\n")); netsnmp_set_mib_directory(confmibdir); } } else if ((*dir == '+') || (*dir == '-')) { DEBUGMSGTL(("get_mib_directory", "mib directories set by environment (but added)\n")); netsnmp_set_mib_directory(NETSNMP_DEFAULT_MIBDIRS); netsnmp_set_mib_directory(dir); } else { DEBUGMSGTL(("get_mib_directory", "mib directories set by environment\n")); netsnmp_set_mib_directory(dir); } dir = netsnmp_ds_get_string(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIBDIRS); } DEBUGMSGTL(("get_mib_directory", "mib directories set '%s'\n", dir)); return(dir); } /* * function : netsnmp_fixup_mib_directory * arguments: - * returns : - */ void netsnmp_fixup_mib_directory(void) { char *homepath = netsnmp_getenv("HOME"); char *mibpath = netsnmp_get_mib_directory(); char *oldmibpath = NULL; char *ptr_home; char *new_mibpath; DEBUGTRACE; if (homepath && mibpath) { DEBUGMSGTL(("fixup_mib_directory", "mib directories '%s'\n", mibpath)); while ((ptr_home = strstr(mibpath, "$HOME"))) { new_mibpath = (char *)malloc(strlen(mibpath) - strlen("$HOME") + strlen(homepath)+1); if (new_mibpath) { *ptr_home = 0; /* null out the spot where we stop copying */ sprintf(new_mibpath, "%s%s%s", mibpath, homepath, ptr_home + strlen("$HOME")); /** swap in the new value and repeat */ mibpath = new_mibpath; if (oldmibpath != NULL) { SNMP_FREE(oldmibpath); } oldmibpath = new_mibpath; } else { break; } } netsnmp_set_mib_directory(mibpath); /* The above copies the mibpath for us, so... */ if (oldmibpath != NULL) { SNMP_FREE(oldmibpath); } } } /** * Initialises the mib reader. * * Reads in all settings from the environment. */ void netsnmp_init_mib(void) { const char *prefix; char *env_var, *entry; PrefixListPtr pp = &mib_prefixes[0]; char *st = NULL; if (Mib) return; netsnmp_init_mib_internals(); /* * Initialise the MIB directory/ies */ netsnmp_fixup_mib_directory(); env_var = strdup(netsnmp_get_mib_directory()); if (!env_var) return; DEBUGMSGTL(("init_mib", "Seen MIBDIRS: Looking in '%s' for mib dirs ...\n", env_var)); entry = strtok_r(env_var, ENV_SEPARATOR, &st); while (entry) { add_mibdir(entry); entry = strtok_r(NULL, ENV_SEPARATOR, &st); } SNMP_FREE(env_var); env_var = netsnmp_getenv("MIBFILES"); if (env_var != NULL) { if (*env_var == '+') entry = strtok_r(env_var+1, ENV_SEPARATOR, &st); else entry = strtok_r(env_var, ENV_SEPARATOR, &st); while (entry) { add_mibfile(entry, NULL); entry = strtok_r(NULL, ENV_SEPARATOR, &st); } } netsnmp_init_mib_internals(); /* * Read in any modules or mibs requested */ env_var = netsnmp_getenv("MIBS"); if (env_var == NULL) { if (confmibs != NULL) env_var = strdup(confmibs); else env_var = strdup(NETSNMP_DEFAULT_MIBS); } else { env_var = strdup(env_var); } if (env_var && ((*env_var == '+') || (*env_var == '-'))) { entry = (char *) malloc(strlen(NETSNMP_DEFAULT_MIBS) + strlen(env_var) + 2); if (!entry) { DEBUGMSGTL(("init_mib", "env mibs malloc failed")); SNMP_FREE(env_var); return; } else { if (*env_var == '+') sprintf(entry, "%s%c%s", NETSNMP_DEFAULT_MIBS, ENV_SEPARATOR_CHAR, env_var+1); else sprintf(entry, "%s%c%s", env_var+1, ENV_SEPARATOR_CHAR, NETSNMP_DEFAULT_MIBS ); } SNMP_FREE(env_var); env_var = entry; } DEBUGMSGTL(("init_mib", "Seen MIBS: Looking in '%s' for mib files ...\n", env_var)); entry = strtok_r(env_var, ENV_SEPARATOR, &st); while (entry) { if (strcasecmp(entry, DEBUG_ALWAYS_TOKEN) == 0) { read_all_mibs(); } else if (strstr(entry, "/") != NULL) { read_mib(entry); } else { netsnmp_read_module(entry); } entry = strtok_r(NULL, ENV_SEPARATOR, &st); } adopt_orphans(); SNMP_FREE(env_var); env_var = netsnmp_getenv("MIBFILES"); if (env_var != NULL) { if ((*env_var == '+') || (*env_var == '-')) { #ifdef NETSNMP_DEFAULT_MIBFILES entry = (char *) malloc(strlen(NETSNMP_DEFAULT_MIBFILES) + strlen(env_var) + 2); if (!entry) { DEBUGMSGTL(("init_mib", "env mibfiles malloc failed")); } else { if (*env_var++ == '+') sprintf(entry, "%s%c%s", NETSNMP_DEFAULT_MIBFILES, ENV_SEPARATOR_CHAR, env_var ); else sprintf(entry, "%s%c%s", env_var, ENV_SEPARATOR_CHAR, NETSNMP_DEFAULT_MIBFILES ); } SNMP_FREE(env_var); env_var = entry; #else env_var = strdup(env_var + 1); #endif } else { env_var = strdup(env_var); } } else { #ifdef NETSNMP_DEFAULT_MIBFILES env_var = strdup(NETSNMP_DEFAULT_MIBFILES); #endif } if (env_var != NULL) { DEBUGMSGTL(("init_mib", "Seen MIBFILES: Looking in '%s' for mib files ...\n", env_var)); entry = strtok_r(env_var, ENV_SEPARATOR, &st); while (entry) { read_mib(entry); entry = strtok_r(NULL, ENV_SEPARATOR, &st); } SNMP_FREE(env_var); } prefix = netsnmp_getenv("PREFIX"); if (!prefix) prefix = Standard_Prefix; Prefix = (char *) malloc(strlen(prefix) + 2); if (!Prefix) DEBUGMSGTL(("init_mib", "Prefix malloc failed")); else strcpy(Prefix, prefix); DEBUGMSGTL(("init_mib", "Seen PREFIX: Looking in '%s' for prefix ...\n", Prefix)); /* * remove trailing dot */ if (Prefix) { env_var = &Prefix[strlen(Prefix) - 1]; if (*env_var == '.') *env_var = '\0'; } pp->str = Prefix; /* fixup first mib_prefix entry */ /* * now that the list of prefixes is built, save each string length. */ while (pp->str) { pp->len = strlen(pp->str); pp++; } Mib = tree_head; /* Backwards compatibility */ tree_top = (struct tree *) calloc(1, sizeof(struct tree)); /* * XX error check ? */ if (tree_top) { tree_top->label = strdup("(top)"); tree_top->child_list = tree_head; } } #ifndef NETSNMP_NO_LEGACY_DEFINITIONS void init_mib(void) { netsnmp_init_mib(); } #endif /** * Unloads all mibs. */ void shutdown_mib(void) { unload_all_mibs(); if (tree_top) { if (tree_top->label) SNMP_FREE(tree_top->label); SNMP_FREE(tree_top); } tree_head = NULL; Mib = NULL; if (Prefix != NULL && Prefix != &Standard_Prefix[0]) SNMP_FREE(Prefix); if (Prefix) Prefix = NULL; SNMP_FREE(confmibs); SNMP_FREE(confmibdir); } /** * Prints the MIBs to the file fp. * * @param fp The file descriptor to print to. */ #ifndef NETSNMP_FEATURE_REMOVE_PRINT_MIB void print_mib(FILE * fp) { print_subtree(fp, tree_head, 0); } #endif /* NETSNMP_FEATURE_REMOVE_PRINT_MIB */ void print_ascii_dump(FILE * fp) { fprintf(fp, "dump DEFINITIONS ::= BEGIN\n"); print_ascii_dump_tree(fp, tree_head, 0); fprintf(fp, "END\n"); } /** * Set's the printing function printomat in a subtree according * it's type * * @param subtree The subtree to set. */ void set_function(struct tree *subtree) { subtree->printer = NULL; switch (subtree->type) { case TYPE_OBJID: subtree->printomat = sprint_realloc_object_identifier; break; case TYPE_OCTETSTR: subtree->printomat = sprint_realloc_octet_string; break; case TYPE_INTEGER: subtree->printomat = sprint_realloc_integer; break; case TYPE_INTEGER32: subtree->printomat = sprint_realloc_integer; break; case TYPE_NETADDR: subtree->printomat = sprint_realloc_networkaddress; break; case TYPE_IPADDR: subtree->printomat = sprint_realloc_ipaddress; break; case TYPE_COUNTER: subtree->printomat = sprint_realloc_counter; break; case TYPE_GAUGE: subtree->printomat = sprint_realloc_gauge; break; case TYPE_TIMETICKS: subtree->printomat = sprint_realloc_timeticks; break; case TYPE_OPAQUE: subtree->printomat = sprint_realloc_opaque; break; case TYPE_NULL: subtree->printomat = sprint_realloc_null; break; case TYPE_BITSTRING: subtree->printomat = sprint_realloc_bitstring; break; case TYPE_NSAPADDRESS: subtree->printomat = sprint_realloc_nsapaddress; break; case TYPE_COUNTER64: subtree->printomat = sprint_realloc_counter64; break; case TYPE_UINTEGER: subtree->printomat = sprint_realloc_uinteger; break; case TYPE_UNSIGNED32: subtree->printomat = sprint_realloc_gauge; break; case TYPE_OTHER: default: subtree->printomat = sprint_realloc_by_type; break; } } #endif /* NETSNMP_DISABLE_MIB_LOADING */ /** * Reads an object identifier from an input string into internal OID form. * * When called, out_len must hold the maximum length of the output array. * * @param input the input string. * @param output the oid wirte. * @param out_len number of subid's in output. * * @return 1 if successful. * * If an error occurs, this function returns 0 and MAY set snmp_errno. * snmp_errno is NOT set if SET_SNMP_ERROR evaluates to nothing. * This can make multi-threaded use a tiny bit more robust. */ int read_objid(const char *input, oid * output, size_t * out_len) { /* number of subid's in "output" */ #ifndef NETSNMP_DISABLE_MIB_LOADING struct tree *root = tree_top; char buf[SPRINT_MAX_LEN]; #endif /* NETSNMP_DISABLE_MIB_LOADING */ int ret, max_out_len; char *name, ch; const char *cp; cp = input; while ((ch = *cp)) { if (('0' <= ch && ch <= '9') || ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') || ch == '-') cp++; else break; } #ifndef NETSNMP_DISABLE_MIB_LOADING if (ch == ':') return get_node(input, output, out_len); #endif /* NETSNMP_DISABLE_MIB_LOADING */ if (*input == '.') input++; #ifndef NETSNMP_DISABLE_MIB_LOADING else if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_READ_UCD_STYLE_OID)) { /* * get past leading '.', append '.' to Prefix. */ if (*Prefix == '.') strlcpy(buf, Prefix + 1, sizeof(buf)); else strlcpy(buf, Prefix, sizeof(buf)); strlcat(buf, ".", sizeof(buf)); strlcat(buf, input, sizeof(buf)); input = buf; } #endif /* NETSNMP_DISABLE_MIB_LOADING */ #ifndef NETSNMP_DISABLE_MIB_LOADING if ((root == NULL) && (tree_head != NULL)) { root = tree_head; } else if (root == NULL) { SET_SNMP_ERROR(SNMPERR_NOMIB); *out_len = 0; return 0; } #endif /* NETSNMP_DISABLE_MIB_LOADING */ name = strdup(input); max_out_len = *out_len; *out_len = 0; #ifndef NETSNMP_DISABLE_MIB_LOADING if ((ret = _add_strings_to_oid(root, name, output, out_len, max_out_len)) <= 0) #else if ((ret = _add_strings_to_oid(NULL, name, output, out_len, max_out_len)) <= 0) #endif /* NETSNMP_DISABLE_MIB_LOADING */ { if (ret == 0) ret = SNMPERR_UNKNOWN_OBJID; SET_SNMP_ERROR(ret); SNMP_FREE(name); return 0; } SNMP_FREE(name); return 1; } /** * */ void netsnmp_sprint_realloc_objid(u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, int *buf_overflow, const oid * objid, size_t objidlen) { u_char *tbuf = NULL, *cp = NULL; size_t tbuf_len = 256, tout_len = 0; int tbuf_overflow = 0; int output_format; if ((tbuf = (u_char *) calloc(tbuf_len, 1)) == NULL) { tbuf_overflow = 1; } else { *tbuf = '.'; tout_len = 1; } _oid_finish_printing(objid, objidlen, &tbuf, &tbuf_len, &tout_len, allow_realloc, &tbuf_overflow); if (tbuf_overflow) { if (!*buf_overflow) { snmp_strcat(buf, buf_len, out_len, allow_realloc, tbuf); *buf_overflow = 1; } SNMP_FREE(tbuf); return; } output_format = netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OID_OUTPUT_FORMAT); if (0 == output_format) { output_format = NETSNMP_OID_OUTPUT_NUMERIC; } switch (output_format) { case NETSNMP_OID_OUTPUT_FULL: case NETSNMP_OID_OUTPUT_NUMERIC: case NETSNMP_OID_OUTPUT_SUFFIX: case NETSNMP_OID_OUTPUT_MODULE: cp = tbuf; break; case NETSNMP_OID_OUTPUT_NONE: default: cp = NULL; } if (!*buf_overflow && !snmp_strcat(buf, buf_len, out_len, allow_realloc, cp)) { *buf_overflow = 1; } SNMP_FREE(tbuf); } /** * */ #ifdef NETSNMP_DISABLE_MIB_LOADING void netsnmp_sprint_realloc_objid_tree(u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, int *buf_overflow, const oid * objid, size_t objidlen) { netsnmp_sprint_realloc_objid(buf, buf_len, out_len, allow_realloc, buf_overflow, objid, objidlen); } #else struct tree * netsnmp_sprint_realloc_objid_tree(u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, int *buf_overflow, const oid * objid, size_t objidlen) { u_char *tbuf = NULL, *cp = NULL; size_t tbuf_len = 512, tout_len = 0; struct tree *subtree = tree_head; size_t midpoint_offset = 0; int tbuf_overflow = 0; int output_format; if ((tbuf = (u_char *) calloc(tbuf_len, 1)) == NULL) { tbuf_overflow = 1; } else { *tbuf = '.'; tout_len = 1; } subtree = _get_realloc_symbol(objid, objidlen, subtree, &tbuf, &tbuf_len, &tout_len, allow_realloc, &tbuf_overflow, NULL, &midpoint_offset); if (tbuf_overflow) { if (!*buf_overflow) { snmp_strcat(buf, buf_len, out_len, allow_realloc, tbuf); *buf_overflow = 1; } SNMP_FREE(tbuf); return subtree; } output_format = netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OID_OUTPUT_FORMAT); if (0 == output_format) { output_format = NETSNMP_OID_OUTPUT_MODULE; } switch (output_format) { case NETSNMP_OID_OUTPUT_FULL: case NETSNMP_OID_OUTPUT_NUMERIC: cp = tbuf; break; case NETSNMP_OID_OUTPUT_SUFFIX: case NETSNMP_OID_OUTPUT_MODULE: for (cp = tbuf; *cp; cp++); if (midpoint_offset != 0) { cp = tbuf + midpoint_offset - 2; /* beyond the '.' */ } else { while (cp >= tbuf) { if (isalpha(*cp)) { break; } cp--; } } while (cp >= tbuf) { if (*cp == '.') { break; } cp--; } cp++; if ((NETSNMP_OID_OUTPUT_MODULE == output_format) && cp > tbuf) { char modbuf[256] = { 0 }, *mod = module_name(subtree->modid, modbuf); /* * Don't add the module ID if it's just numeric (i.e. we couldn't look * it up properly. */ if (!*buf_overflow && modbuf[0] != '#') { if (!snmp_strcat (buf, buf_len, out_len, allow_realloc, (const u_char *) mod) || !snmp_strcat(buf, buf_len, out_len, allow_realloc, (const u_char *) "::")) { *buf_overflow = 1; } } } break; case NETSNMP_OID_OUTPUT_UCD: { PrefixListPtr pp = &mib_prefixes[0]; size_t ilen, tlen; const char *testcp; cp = tbuf; tlen = strlen((char *) tbuf); while (pp->str) { ilen = pp->len; testcp = pp->str; if ((tlen > ilen) && memcmp(tbuf, testcp, ilen) == 0) { cp += (ilen + 1); break; } pp++; } break; } case NETSNMP_OID_OUTPUT_NONE: default: cp = NULL; } if (!*buf_overflow && !snmp_strcat(buf, buf_len, out_len, allow_realloc, cp)) { *buf_overflow = 1; } SNMP_FREE(tbuf); return subtree; } #endif /* NETSNMP_DISABLE_MIB_LOADING */ int sprint_realloc_objid(u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, const oid * objid, size_t objidlen) { int buf_overflow = 0; netsnmp_sprint_realloc_objid_tree(buf, buf_len, out_len, allow_realloc, &buf_overflow, objid, objidlen); return !buf_overflow; } #ifndef NETSNMP_FEATURE_REMOVE_SPRINT_OBJID int snprint_objid(char *buf, size_t buf_len, const oid * objid, size_t objidlen) { size_t out_len = 0; if (sprint_realloc_objid((u_char **) & buf, &buf_len, &out_len, 0, objid, objidlen)) { return (int) out_len; } else { return -1; } } #endif /* NETSNMP_FEATURE_REMOVE_SPRINT_OBJID */ /** * Prints an oid to stdout. * * @param objid The oid to print * @param objidlen The length of oidid. */ void print_objid(const oid * objid, size_t objidlen) { /* number of subidentifiers */ fprint_objid(stdout, objid, objidlen); } /** * Prints an oid to a file descriptor. * * @param f The file descriptor to print to. * @param objid The oid to print * @param objidlen The length of oidid. */ void fprint_objid(FILE * f, const oid * objid, size_t objidlen) { /* number of subidentifiers */ u_char *buf = NULL; size_t buf_len = 256, out_len = 0; int buf_overflow = 0; if ((buf = (u_char *) calloc(buf_len, 1)) == NULL) { fprintf(f, "[TRUNCATED]\n"); return; } else { netsnmp_sprint_realloc_objid_tree(&buf, &buf_len, &out_len, 1, &buf_overflow, objid, objidlen); if (buf_overflow) { fprintf(f, "%s [TRUNCATED]\n", buf); } else { fprintf(f, "%s\n", buf); } } SNMP_FREE(buf); } int sprint_realloc_variable(u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, const oid * objid, size_t objidlen, const netsnmp_variable_list * variable) { int buf_overflow = 0; #ifndef NETSNMP_DISABLE_MIB_LOADING struct tree *subtree = tree_head; subtree = #endif /* NETSNMP_DISABLE_MIB_LOADING */ netsnmp_sprint_realloc_objid_tree(buf, buf_len, out_len, allow_realloc, &buf_overflow, objid, objidlen); if (buf_overflow) { return 0; } if (!netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PRINT_BARE_VALUE)) { if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICKE_PRINT)) { if (!snmp_strcat (buf, buf_len, out_len, allow_realloc, (const u_char *) " = ")) { return 0; } } else { if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT)) { if (!snmp_strcat (buf, buf_len, out_len, allow_realloc, (const u_char *) " ")) { return 0; } } else { if (!snmp_strcat (buf, buf_len, out_len, allow_realloc, (const u_char *) " = ")) { return 0; } } /* end if-else NETSNMP_DS_LIB_QUICK_PRINT */ } /* end if-else NETSNMP_DS_LIB_QUICKE_PRINT */ } else { *out_len = 0; } if (variable->type == SNMP_NOSUCHOBJECT) { return snmp_strcat(buf, buf_len, out_len, allow_realloc, (const u_char *) "No Such Object available on this agent at this OID"); } else if (variable->type == SNMP_NOSUCHINSTANCE) { return snmp_strcat(buf, buf_len, out_len, allow_realloc, (const u_char *) "No Such Instance currently exists at this OID"); } else if (variable->type == SNMP_ENDOFMIBVIEW) { return snmp_strcat(buf, buf_len, out_len, allow_realloc, (const u_char *) "No more variables left in this MIB View (It is past the end of the MIB tree)"); #ifndef NETSNMP_DISABLE_MIB_LOADING } else if (subtree) { const char *units = NULL; const char *hint = NULL; if (!netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_DONT_PRINT_UNITS)) { units = subtree->units; } if (!netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_NO_DISPLAY_HINT)) { hint = subtree->hint; } if (subtree->printomat) { return (*subtree->printomat) (buf, buf_len, out_len, allow_realloc, variable, subtree->enums, hint, units); } else { return sprint_realloc_by_type(buf, buf_len, out_len, allow_realloc, variable, subtree->enums, hint, units); } #endif /* NETSNMP_DISABLE_MIB_LOADING */ } else { /* * Handle rare case where tree is empty. */ return sprint_realloc_by_type(buf, buf_len, out_len, allow_realloc, variable, NULL, NULL, NULL); } } #ifndef NETSNMP_FEATURE_REMOVE_SNPRINT_VARABLE int snprint_variable(char *buf, size_t buf_len, const oid * objid, size_t objidlen, const netsnmp_variable_list * variable) { size_t out_len = 0; if (sprint_realloc_variable((u_char **) & buf, &buf_len, &out_len, 0, objid, objidlen, variable)) { return (int) out_len; } else { return -1; } } #endif /* NETSNMP_FEATURE_REMOVE_SNPRINT_VARABLE */ /** * Prints a variable to stdout. * * @param objid The object id. * @param objidlen The length of teh object id. * @param variable The variable to print. */ void print_variable(const oid * objid, size_t objidlen, const netsnmp_variable_list * variable) { fprint_variable(stdout, objid, objidlen, variable); } /** * Prints a variable to a file descriptor. * * @param f The file descriptor to print to. * @param objid The object id. * @param objidlen The length of teh object id. * @param variable The variable to print. */ void fprint_variable(FILE * f, const oid * objid, size_t objidlen, const netsnmp_variable_list * variable) { u_char *buf = NULL; size_t buf_len = 256, out_len = 0; if ((buf = (u_char *) calloc(buf_len, 1)) == NULL) { fprintf(f, "[TRUNCATED]\n"); return; } else { if (sprint_realloc_variable(&buf, &buf_len, &out_len, 1, objid, objidlen, variable)) { fprintf(f, "%s\n", buf); } else { fprintf(f, "%s [TRUNCATED]\n", buf); } } SNMP_FREE(buf); } int sprint_realloc_value(u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, const oid * objid, size_t objidlen, const netsnmp_variable_list * variable) { if (variable->type == SNMP_NOSUCHOBJECT) { return snmp_strcat(buf, buf_len, out_len, allow_realloc, (const u_char *) "No Such Object available on this agent at this OID"); } else if (variable->type == SNMP_NOSUCHINSTANCE) { return snmp_strcat(buf, buf_len, out_len, allow_realloc, (const u_char *) "No Such Instance currently exists at this OID"); } else if (variable->type == SNMP_ENDOFMIBVIEW) { return snmp_strcat(buf, buf_len, out_len, allow_realloc, (const u_char *) "No more variables left in this MIB View (It is past the end of the MIB tree)"); } else { #ifndef NETSNMP_DISABLE_MIB_LOADING const char *units = NULL; struct tree *subtree = tree_head; subtree = get_tree(objid, objidlen, subtree); if (subtree && !netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_DONT_PRINT_UNITS)) { units = subtree->units; } if (subtree) { if(subtree->printomat) { return (*subtree->printomat) (buf, buf_len, out_len, allow_realloc, variable, subtree->enums, subtree->hint, units); } else { return sprint_realloc_by_type(buf, buf_len, out_len, allow_realloc, variable, subtree->enums, subtree->hint, units); } } #endif /* NETSNMP_DISABLE_MIB_LOADING */ return sprint_realloc_by_type(buf, buf_len, out_len, allow_realloc, variable, NULL, NULL, NULL); } } #ifndef NETSNMP_FEATURE_REMOVE_SNPRINT_VALUE /* used in the perl module */ int snprint_value(char *buf, size_t buf_len, const oid * objid, size_t objidlen, const netsnmp_variable_list * variable) { size_t out_len = 0; if (sprint_realloc_value((u_char **) & buf, &buf_len, &out_len, 0, objid, objidlen, variable)) { return (int) out_len; } else { return -1; } } #endif /* NETSNMP_FEATURE_REMOVE_SNPRINT_VALUE */ void print_value(const oid * objid, size_t objidlen, const netsnmp_variable_list * variable) { fprint_value(stdout, objid, objidlen, variable); } void fprint_value(FILE * f, const oid * objid, size_t objidlen, const netsnmp_variable_list * variable) { u_char *buf = NULL; size_t buf_len = 256, out_len = 0; if ((buf = (u_char *) calloc(buf_len, 1)) == NULL) { fprintf(f, "[TRUNCATED]\n"); return; } else { if (sprint_realloc_value(&buf, &buf_len, &out_len, 1, objid, objidlen, variable)) { fprintf(f, "%s\n", buf); } else { fprintf(f, "%s [TRUNCATED]\n", buf); } } SNMP_FREE(buf); } /** * Takes the value in VAR and turns it into an OID segment in var->name. * * @param var The variable. * * @return SNMPERR_SUCCESS or SNMPERR_GENERR */ int build_oid_segment(netsnmp_variable_list * var) { int i; uint32_t ipaddr; if (var->name && var->name != var->name_loc) SNMP_FREE(var->name); switch (var->type) { case ASN_INTEGER: case ASN_COUNTER: case ASN_GAUGE: case ASN_TIMETICKS: var->name_length = 1; var->name = var->name_loc; var->name[0] = *(var->val.integer); break; case ASN_IPADDRESS: var->name_length = 4; var->name = var->name_loc; memcpy(&ipaddr, var->val.string, sizeof(ipaddr)); var->name[0] = (ipaddr >> 24) & 0xff; var->name[1] = (ipaddr >> 16) & 0xff; var->name[2] = (ipaddr >> 8) & 0xff; var->name[3] = (ipaddr >> 0) & 0xff; break; case ASN_PRIV_IMPLIED_OBJECT_ID: var->name_length = var->val_len / sizeof(oid); if (var->name_length > (sizeof(var->name_loc) / sizeof(oid))) var->name = (oid *) malloc(sizeof(oid) * (var->name_length)); else var->name = var->name_loc; if (var->name == NULL) return SNMPERR_GENERR; for (i = 0; i < (int) var->name_length; i++) var->name[i] = var->val.objid[i]; break; case ASN_OBJECT_ID: var->name_length = var->val_len / sizeof(oid) + 1; if (var->name_length > (sizeof(var->name_loc) / sizeof(oid))) var->name = (oid *) malloc(sizeof(oid) * (var->name_length)); else var->name = var->name_loc; if (var->name == NULL) return SNMPERR_GENERR; var->name[0] = var->name_length - 1; for (i = 0; i < (int) var->name_length - 1; i++) var->name[i + 1] = var->val.objid[i]; break; case ASN_PRIV_IMPLIED_OCTET_STR: var->name_length = var->val_len; if (var->name_length > (sizeof(var->name_loc) / sizeof(oid))) var->name = (oid *) malloc(sizeof(oid) * (var->name_length)); else var->name = var->name_loc; if (var->name == NULL) return SNMPERR_GENERR; for (i = 0; i < (int) var->val_len; i++) var->name[i] = (oid) var->val.string[i]; break; case ASN_OPAQUE: case ASN_OCTET_STR: var->name_length = var->val_len + 1; if (var->name_length > (sizeof(var->name_loc) / sizeof(oid))) var->name = (oid *) malloc(sizeof(oid) * (var->name_length)); else var->name = var->name_loc; if (var->name == NULL) return SNMPERR_GENERR; var->name[0] = (oid) var->val_len; for (i = 0; i < (int) var->val_len; i++) var->name[i + 1] = (oid) var->val.string[i]; break; default: DEBUGMSGTL(("build_oid_segment", "invalid asn type: %d\n", var->type)); return SNMPERR_GENERR; } if (var->name_length > MAX_OID_LEN) { DEBUGMSGTL(("build_oid_segment", "Something terribly wrong, namelen = %lu\n", (unsigned long)var->name_length)); return SNMPERR_GENERR; } return SNMPERR_SUCCESS; } int build_oid_noalloc(oid * in, size_t in_len, size_t * out_len, oid * prefix, size_t prefix_len, netsnmp_variable_list * indexes) { netsnmp_variable_list *var; if (prefix) { if (in_len < prefix_len) return SNMPERR_GENERR; memcpy(in, prefix, prefix_len * sizeof(oid)); *out_len = prefix_len; } else { *out_len = 0; } for (var = indexes; var != NULL; var = var->next_variable) { if (build_oid_segment(var) != SNMPERR_SUCCESS) return SNMPERR_GENERR; if (var->name_length + *out_len <= in_len) { memcpy(&(in[*out_len]), var->name, sizeof(oid) * var->name_length); *out_len += var->name_length; } else { return SNMPERR_GENERR; } } DEBUGMSGTL(("build_oid_noalloc", "generated: ")); DEBUGMSGOID(("build_oid_noalloc", in, *out_len)); DEBUGMSG(("build_oid_noalloc", "\n")); return SNMPERR_SUCCESS; } int build_oid(oid ** out, size_t * out_len, oid * prefix, size_t prefix_len, netsnmp_variable_list * indexes) { oid tmpout[MAX_OID_LEN]; /* * xxx-rks: inefficent. try only building segments to find index len: * for (var = indexes; var != NULL; var = var->next_variable) { * if (build_oid_segment(var) != SNMPERR_SUCCESS) * return SNMPERR_GENERR; * *out_len += var->name_length; * * then see if it fits in existing buffer, or realloc buffer. */ if (build_oid_noalloc(tmpout, sizeof(tmpout), out_len, prefix, prefix_len, indexes) != SNMPERR_SUCCESS) return SNMPERR_GENERR; /** xxx-rks: should free previous value? */ snmp_clone_mem((void **) out, (void *) tmpout, *out_len * sizeof(oid)); return SNMPERR_SUCCESS; } /* * vblist_out must contain a pre-allocated string of variables into * which indexes can be extracted based on the previously existing * types in the variable chain * returns: * SNMPERR_GENERR on error * SNMPERR_SUCCESS on success */ int parse_oid_indexes(oid * oidIndex, size_t oidLen, netsnmp_variable_list * data) { netsnmp_variable_list *var = data; while (var && oidLen > 0) { if (parse_one_oid_index(&oidIndex, &oidLen, var, 0) != SNMPERR_SUCCESS) break; var = var->next_variable; } if (var != NULL || oidLen != 0) return SNMPERR_GENERR; return SNMPERR_SUCCESS; } int parse_one_oid_index(oid ** oidStart, size_t * oidLen, netsnmp_variable_list * data, int complete) { netsnmp_variable_list *var = data; oid tmpout[MAX_OID_LEN]; unsigned int i; unsigned int uitmp = 0; oid *oidIndex = *oidStart; if (var == NULL || ((*oidLen == 0) && (complete == 0))) return SNMPERR_GENERR; else { switch (var->type) { case ASN_INTEGER: case ASN_COUNTER: case ASN_GAUGE: case ASN_TIMETICKS: if (*oidLen) { snmp_set_var_value(var, (u_char *) oidIndex++, sizeof(oid)); --(*oidLen); } else { snmp_set_var_value(var, (u_char *) oidLen, sizeof(long)); } DEBUGMSGTL(("parse_oid_indexes", "Parsed int(%d): %ld\n", var->type, *var->val.integer)); break; case ASN_IPADDRESS: if ((4 > *oidLen) && (complete == 0)) return SNMPERR_GENERR; for (i = 0; i < 4 && i < *oidLen; ++i) { if (oidIndex[i] > 255) { DEBUGMSGTL(("parse_oid_indexes", "illegal oid in index: %" NETSNMP_PRIo "d\n", oidIndex[0])); return SNMPERR_GENERR; /* sub-identifier too large */ } uitmp = uitmp + (oidIndex[i] << (8*(3-i))); } if (4 > (int) (*oidLen)) { oidIndex += *oidLen; (*oidLen) = 0; } else { oidIndex += 4; (*oidLen) -= 4; } uitmp = htonl(uitmp); /* put it in proper order for byte copies */ uitmp = snmp_set_var_value(var, (u_char *) &uitmp, 4); DEBUGMSGTL(("parse_oid_indexes", "Parsed ipaddr(%d): %d.%d.%d.%d\n", var->type, var->val.string[0], var->val.string[1], var->val.string[2], var->val.string[3])); break; case ASN_OBJECT_ID: case ASN_PRIV_IMPLIED_OBJECT_ID: if (var->type == ASN_PRIV_IMPLIED_OBJECT_ID) { /* * might not be implied, might be fixed len. check if * caller set up val len, and use it if they did. */ if (0 == var->val_len) uitmp = *oidLen; else { DEBUGMSGTL(("parse_oid_indexes:fix", "fixed len oid\n")); uitmp = var->val_len; } } else { if (*oidLen) { uitmp = *oidIndex++; --(*oidLen); } else { uitmp = 0; } if ((uitmp > *oidLen) && (complete == 0)) return SNMPERR_GENERR; } if (uitmp > MAX_OID_LEN) return SNMPERR_GENERR; /* too big and illegal */ if (uitmp > *oidLen) { memcpy(tmpout, oidIndex, sizeof(oid) * (*oidLen)); memset(&tmpout[*oidLen], 0x00, sizeof(oid) * (uitmp - *oidLen)); snmp_set_var_value(var, (u_char *) tmpout, sizeof(oid) * uitmp); oidIndex += *oidLen; (*oidLen) = 0; } else { snmp_set_var_value(var, (u_char *) oidIndex, sizeof(oid) * uitmp); oidIndex += uitmp; (*oidLen) -= uitmp; } DEBUGMSGTL(("parse_oid_indexes", "Parsed oid: ")); DEBUGMSGOID(("parse_oid_indexes", var->val.objid, var->val_len / sizeof(oid))); DEBUGMSG(("parse_oid_indexes", "\n")); break; case ASN_OPAQUE: case ASN_OCTET_STR: case ASN_PRIV_IMPLIED_OCTET_STR: if (var->type == ASN_PRIV_IMPLIED_OCTET_STR) { /* * might not be implied, might be fixed len. check if * caller set up val len, and use it if they did. */ if (0 == var->val_len) uitmp = *oidLen; else { DEBUGMSGTL(("parse_oid_indexes:fix", "fixed len str\n")); uitmp = var->val_len; } } else { if (*oidLen) { uitmp = *oidIndex++; --(*oidLen); } else { uitmp = 0; } if ((uitmp > *oidLen) && (complete == 0)) return SNMPERR_GENERR; } /* * we handle this one ourselves since we don't have * pre-allocated memory to copy from using * snmp_set_var_value() */ if (uitmp == 0) break; /* zero length strings shouldn't malloc */ if (uitmp > MAX_OID_LEN) return SNMPERR_GENERR; /* too big and illegal */ /* * malloc by size+1 to allow a null to be appended. */ var->val_len = uitmp; var->val.string = (u_char *) calloc(1, uitmp + 1); if (var->val.string == NULL) return SNMPERR_GENERR; if ((size_t)uitmp > (*oidLen)) { for (i = 0; i < *oidLen; ++i) var->val.string[i] = (u_char) * oidIndex++; for (i = *oidLen; i < uitmp; ++i) var->val.string[i] = '\0'; (*oidLen) = 0; } else { for (i = 0; i < uitmp; ++i) var->val.string[i] = (u_char) * oidIndex++; (*oidLen) -= uitmp; } var->val.string[uitmp] = '\0'; DEBUGMSGTL(("parse_oid_indexes", "Parsed str(%d): %s\n", var->type, var->val.string)); break; default: DEBUGMSGTL(("parse_oid_indexes", "invalid asn type: %d\n", var->type)); return SNMPERR_GENERR; } } (*oidStart) = oidIndex; return SNMPERR_SUCCESS; } /* * dump_realloc_oid_to_inetaddress: * return 0 for failure, * return 1 for success, * return 2 for not handled */ int dump_realloc_oid_to_inetaddress(const int addr_type, const oid * objid, size_t objidlen, u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, char quotechar) { int i, len; char intbuf[64], *p; char *const end = intbuf + sizeof(intbuf); unsigned char *zc; unsigned long zone; if (!buf) return 1; for (i = 0; i < objidlen; i++) if (objid[i] < 0 || objid[i] > 255) return 2; p = intbuf; *p++ = quotechar; switch (addr_type) { case IPV4: case IPV4Z: if ((addr_type == IPV4 && objidlen != 4) || (addr_type == IPV4Z && objidlen != 8)) return 2; len = snprintf(p, end - p, "%" NETSNMP_PRIo "u.%" NETSNMP_PRIo "u." "%" NETSNMP_PRIo "u.%" NETSNMP_PRIo "u", objid[0], objid[1], objid[2], objid[3]); p += len; if (p >= end) return 2; if (addr_type == IPV4Z) { zc = (unsigned char*)&zone; zc[0] = objid[4]; zc[1] = objid[5]; zc[2] = objid[6]; zc[3] = objid[7]; zone = ntohl(zone); len = snprintf(p, end - p, "%%%lu", zone); p += len; if (p >= end) return 2; } break; case IPV6: case IPV6Z: if ((addr_type == IPV6 && objidlen != 16) || (addr_type == IPV6Z && objidlen != 20)) return 2; len = 0; for (i = 0; i < 16; i ++) { len = snprintf(p, end - p, "%s%02" NETSNMP_PRIo "x", i ? ":" : "", objid[i]); p += len; if (p >= end) return 2; } if (addr_type == IPV6Z) { zc = (unsigned char*)&zone; zc[0] = objid[16]; zc[1] = objid[17]; zc[2] = objid[18]; zc[3] = objid[19]; zone = ntohl(zone); len = snprintf(p, end - p, "%%%lu", zone); p += len; if (p >= end) return 2; } break; case DNS: default: /* DNS can just be handled by dump_realloc_oid_to_string() */ return 2; } *p++ = quotechar; if (p >= end) return 2; *p++ = '\0'; if (p >= end) return 2; return snmp_cstrcat(buf, buf_len, out_len, allow_realloc, intbuf); } int dump_realloc_oid_to_string(const oid * objid, size_t objidlen, u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, char quotechar) { if (buf) { int i, alen; for (i = 0, alen = 0; i < (int) objidlen; i++) { oid tst = objid[i]; if ((tst > 254) || (!isprint(tst))) { tst = (oid) '.'; } if (alen == 0) { if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_ESCAPE_QUOTES)) { while ((*out_len + 2) >= *buf_len) { if (!(allow_realloc && snmp_realloc(buf, buf_len))) { return 0; } } *(*buf + *out_len) = '\\'; (*out_len)++; } while ((*out_len + 2) >= *buf_len) { if (!(allow_realloc && snmp_realloc(buf, buf_len))) { return 0; } } *(*buf + *out_len) = quotechar; (*out_len)++; } while ((*out_len + 2) >= *buf_len) { if (!(allow_realloc && snmp_realloc(buf, buf_len))) { return 0; } } *(*buf + *out_len) = (char) tst; (*out_len)++; alen++; } if (alen) { if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_ESCAPE_QUOTES)) { while ((*out_len + 2) >= *buf_len) { if (!(allow_realloc && snmp_realloc(buf, buf_len))) { return 0; } } *(*buf + *out_len) = '\\'; (*out_len)++; } while ((*out_len + 2) >= *buf_len) { if (!(allow_realloc && snmp_realloc(buf, buf_len))) { return 0; } } *(*buf + *out_len) = quotechar; (*out_len)++; } *(*buf + *out_len) = '\0'; } return 1; } void _oid_finish_printing(const oid * objid, size_t objidlen, u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, int *buf_overflow) { char intbuf[64]; if (*buf != NULL && *(*buf + *out_len - 1) != '.') { if (!*buf_overflow && !snmp_strcat(buf, buf_len, out_len, allow_realloc, (const u_char *) ".")) { *buf_overflow = 1; } } while (objidlen-- > 0) { /* output rest of name, uninterpreted */ sprintf(intbuf, "%" NETSNMP_PRIo "u.", *objid++); if (!*buf_overflow && !snmp_strcat(buf, buf_len, out_len, allow_realloc, (const u_char *) intbuf)) { *buf_overflow = 1; } } if (*buf != NULL) { *(*buf + *out_len - 1) = '\0'; /* remove trailing dot */ *out_len = *out_len - 1; } } #ifndef NETSNMP_DISABLE_MIB_LOADING static void _get_realloc_symbol_octet_string(size_t numids, const oid * objid, u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, int *buf_overflow, struct tree* tp) { netsnmp_variable_list var = { 0 }; u_char buffer[1024]; size_t i; for (i = 0; i < numids; i++) buffer[i] = (u_char) objid[i]; var.type = ASN_OCTET_STR; var.val.string = buffer; var.val_len = numids; if (!*buf_overflow) { if (!sprint_realloc_octet_string(buf, buf_len, out_len, allow_realloc, &var, NULL, tp->hint, NULL)) { *buf_overflow = 1; } } } static struct tree * _get_realloc_symbol(const oid * objid, size_t objidlen, struct tree *subtree, u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, int *buf_overflow, struct index_list *in_dices, size_t * end_of_known) { struct tree *return_tree = NULL; int extended_index = netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_EXTENDED_INDEX); int output_format = netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OID_OUTPUT_FORMAT); char intbuf[64]; struct tree *orgtree = subtree; if (!objid || !buf) { return NULL; } for (; subtree; subtree = subtree->next_peer) { if (*objid == subtree->subid) { while (subtree->next_peer && subtree->next_peer->subid == *objid) subtree = subtree->next_peer; if (subtree->indexes) { in_dices = subtree->indexes; } else if (subtree->augments) { struct tree *tp2 = find_tree_node(subtree->augments, -1); if (tp2) { in_dices = tp2->indexes; } } if (!strncmp(subtree->label, ANON, ANON_LEN) || (NETSNMP_OID_OUTPUT_NUMERIC == output_format)) { sprintf(intbuf, "%lu", subtree->subid); if (!*buf_overflow && !snmp_strcat(buf, buf_len, out_len, allow_realloc, (const u_char *) intbuf)) { *buf_overflow = 1; } } else { if (!*buf_overflow && !snmp_strcat(buf, buf_len, out_len, allow_realloc, (const u_char *) subtree->label)) { *buf_overflow = 1; } } if (objidlen > 1) { if (!*buf_overflow && !snmp_strcat(buf, buf_len, out_len, allow_realloc, (const u_char *) ".")) { *buf_overflow = 1; } return_tree = _get_realloc_symbol(objid + 1, objidlen - 1, subtree->child_list, buf, buf_len, out_len, allow_realloc, buf_overflow, in_dices, end_of_known); } if (return_tree != NULL) { return return_tree; } else { return subtree; } } } if (end_of_known) { *end_of_known = *out_len; } /* * Subtree not found. */ if (orgtree && in_dices && objidlen > 0) { sprintf(intbuf, "%" NETSNMP_PRIo "u.", *objid); if (!*buf_overflow && !snmp_strcat(buf, buf_len, out_len, allow_realloc, (const u_char *) intbuf)) { *buf_overflow = 1; } objid++; objidlen--; } while (in_dices && (objidlen > 0) && (NETSNMP_OID_OUTPUT_NUMERIC != output_format) && !netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_DONT_BREAKDOWN_OIDS)) { size_t numids; struct tree *tp; tp = find_tree_node(in_dices->ilabel, -1); if (!tp) { /* * Can't find an index in the mib tree. Bail. */ goto finish_it; } if (extended_index) { if (*buf != NULL && *(*buf + *out_len - 1) == '.') { (*out_len)--; } if (!*buf_overflow && !snmp_strcat(buf, buf_len, out_len, allow_realloc, (const u_char *) "[")) { *buf_overflow = 1; } } switch (tp->type) { case TYPE_OCTETSTR: if (extended_index && tp->hint) { if (in_dices->isimplied) { numids = objidlen; if (numids > objidlen) goto finish_it; } else if (tp->ranges && !tp->ranges->next && tp->ranges->low == tp->ranges->high) { numids = tp->ranges->low; if (numids > objidlen) goto finish_it; } else { numids = *objid; if (numids >= objidlen) goto finish_it; objid++; objidlen--; } if (numids > objidlen) goto finish_it; _get_realloc_symbol_octet_string(numids, objid, buf, buf_len, out_len, allow_realloc, buf_overflow, tp); } else if (in_dices->isimplied) { numids = objidlen; if (numids > objidlen) goto finish_it; if (!*buf_overflow) { if (!dump_realloc_oid_to_string (objid, numids, buf, buf_len, out_len, allow_realloc, '\'')) { *buf_overflow = 1; } } } else if (tp->ranges && !tp->ranges->next && tp->ranges->low == tp->ranges->high) { /* * a fixed-length octet string */ numids = tp->ranges->low; if (numids > objidlen) goto finish_it; if (!*buf_overflow) { if (!dump_realloc_oid_to_string (objid, numids, buf, buf_len, out_len, allow_realloc, '\'')) { *buf_overflow = 1; } } } else { numids = (size_t) * objid + 1; if (numids > objidlen) goto finish_it; if (numids == 1) { if (netsnmp_ds_get_boolean (NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_ESCAPE_QUOTES)) { if (!*buf_overflow && !snmp_strcat(buf, buf_len, out_len, allow_realloc, (const u_char *) "\\")) { *buf_overflow = 1; } } if (!*buf_overflow && !snmp_strcat(buf, buf_len, out_len, allow_realloc, (const u_char *) "\"")) { *buf_overflow = 1; } if (netsnmp_ds_get_boolean (NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_ESCAPE_QUOTES)) { if (!*buf_overflow && !snmp_strcat(buf, buf_len, out_len, allow_realloc, (const u_char *) "\\")) { *buf_overflow = 1; } } if (!*buf_overflow && !snmp_strcat(buf, buf_len, out_len, allow_realloc, (const u_char *) "\"")) { *buf_overflow = 1; } } else { if (!*buf_overflow) { struct tree * next_peer; int normal_handling = 1; if (tp->next_peer) { next_peer = tp->next_peer; } /* Try handling the InetAddress in the OID, in case of failure, * use the normal_handling. */ if (tp->next_peer && tp->tc_index != -1 && next_peer->tc_index != -1 && strcmp(get_tc_descriptor(tp->tc_index), "InetAddress") == 0 && strcmp(get_tc_descriptor(next_peer->tc_index), "InetAddressType") == 0 ) { int ret; int addr_type = *(objid - 1); ret = dump_realloc_oid_to_inetaddress(addr_type, objid + 1, numids - 1, buf, buf_len, out_len, allow_realloc, '"'); if (ret != 2) { normal_handling = 0; if (ret == 0) { *buf_overflow = 1; } } } if (normal_handling && !dump_realloc_oid_to_string (objid + 1, numids - 1, buf, buf_len, out_len, allow_realloc, '"')) { *buf_overflow = 1; } } } } objid += numids; objidlen -= numids; break; case TYPE_INTEGER32: case TYPE_UINTEGER: case TYPE_UNSIGNED32: case TYPE_GAUGE: case TYPE_INTEGER: if (tp->enums) { struct enum_list *ep = tp->enums; while (ep && ep->value != (int) (*objid)) { ep = ep->next; } if (ep) { if (!*buf_overflow && !snmp_strcat(buf, buf_len, out_len, allow_realloc, (const u_char *) ep->label)) { *buf_overflow = 1; } } else { sprintf(intbuf, "%" NETSNMP_PRIo "u", *objid); if (!*buf_overflow && !snmp_strcat(buf, buf_len, out_len, allow_realloc, (const u_char *) intbuf)) { *buf_overflow = 1; } } } else { sprintf(intbuf, "%" NETSNMP_PRIo "u", *objid); if (!*buf_overflow && !snmp_strcat(buf, buf_len, out_len, allow_realloc, (const u_char *) intbuf)) { *buf_overflow = 1; } } objid++; objidlen--; break; case TYPE_TIMETICKS: /* In an index, this is probably a timefilter */ if (extended_index) { uptimeString( *objid, intbuf, sizeof( intbuf ) ); } else { sprintf(intbuf, "%" NETSNMP_PRIo "u", *objid); } if (!*buf_overflow && !snmp_strcat(buf, buf_len, out_len, allow_realloc, (const u_char *) intbuf)) { *buf_overflow = 1; } objid++; objidlen--; break; case TYPE_OBJID: if (in_dices->isimplied) { numids = objidlen; } else { numids = (size_t) * objid + 1; } if (numids > objidlen) goto finish_it; if (extended_index) { if (in_dices->isimplied) { if (!*buf_overflow && !netsnmp_sprint_realloc_objid_tree(buf, buf_len, out_len, allow_realloc, buf_overflow, objid, numids)) { *buf_overflow = 1; } } else { if (!*buf_overflow && !netsnmp_sprint_realloc_objid_tree(buf, buf_len, out_len, allow_realloc, buf_overflow, objid + 1, numids - 1)) { *buf_overflow = 1; } } } else { _get_realloc_symbol(objid, numids, NULL, buf, buf_len, out_len, allow_realloc, buf_overflow, NULL, NULL); } objid += (numids); objidlen -= (numids); break; case TYPE_IPADDR: if (objidlen < 4) goto finish_it; sprintf(intbuf, "%" NETSNMP_PRIo "u.%" NETSNMP_PRIo "u." "%" NETSNMP_PRIo "u.%" NETSNMP_PRIo "u", objid[0], objid[1], objid[2], objid[3]); objid += 4; objidlen -= 4; if (!*buf_overflow && !snmp_strcat(buf, buf_len, out_len, allow_realloc, (const u_char *) intbuf)) { *buf_overflow = 1; } break; case TYPE_NETADDR:{ oid ntype = *objid++; objidlen--; sprintf(intbuf, "%" NETSNMP_PRIo "u.", ntype); if (!*buf_overflow && !snmp_strcat(buf, buf_len, out_len, allow_realloc, (const u_char *) intbuf)) { *buf_overflow = 1; } if (ntype == 1 && objidlen >= 4) { sprintf(intbuf, "%" NETSNMP_PRIo "u.%" NETSNMP_PRIo "u." "%" NETSNMP_PRIo "u.%" NETSNMP_PRIo "u", objid[0], objid[1], objid[2], objid[3]); if (!*buf_overflow && !snmp_strcat(buf, buf_len, out_len, allow_realloc, (const u_char *) intbuf)) { *buf_overflow = 1; } objid += 4; objidlen -= 4; } else { goto finish_it; } } break; case TYPE_NSAPADDRESS: default: goto finish_it; break; } if (extended_index) { if (!*buf_overflow && !snmp_strcat(buf, buf_len, out_len, allow_realloc, (const u_char *) "]")) { *buf_overflow = 1; } } else { if (!*buf_overflow && !snmp_strcat(buf, buf_len, out_len, allow_realloc, (const u_char *) ".")) { *buf_overflow = 1; } } in_dices = in_dices->next; } finish_it: _oid_finish_printing(objid, objidlen, buf, buf_len, out_len, allow_realloc, buf_overflow); return NULL; } struct tree * get_tree(const oid * objid, size_t objidlen, struct tree *subtree) { struct tree *return_tree = NULL; for (; subtree; subtree = subtree->next_peer) { if (*objid == subtree->subid) goto found; } return NULL; found: while (subtree->next_peer && subtree->next_peer->subid == *objid) subtree = subtree->next_peer; if (objidlen > 1) return_tree = get_tree(objid + 1, objidlen - 1, subtree->child_list); if (return_tree != NULL) return return_tree; else return subtree; } /** * Prints on oid description on stdout. * * @see fprint_description */ void print_description(oid * objid, size_t objidlen, /* number of subidentifiers */ int width) { fprint_description(stdout, objid, objidlen, width); } /** * Prints on oid description into a file descriptor. * * @param f The file descriptor to print to. * @param objid The object identifier. * @param objidlen The object id length. * @param width Number of subidentifiers. */ void fprint_description(FILE * f, oid * objid, size_t objidlen, int width) { u_char *buf = NULL; size_t buf_len = 256, out_len = 0; if ((buf = (u_char *) calloc(buf_len, 1)) == NULL) { fprintf(f, "[TRUNCATED]\n"); return; } else { if (!sprint_realloc_description(&buf, &buf_len, &out_len, 1, objid, objidlen, width)) { fprintf(f, "%s [TRUNCATED]\n", buf); } else { fprintf(f, "%s\n", buf); } } SNMP_FREE(buf); } #ifndef NETSNMP_FEATURE_REMOVE_MIB_SNPRINT_DESCRIPTION int snprint_description(char *buf, size_t buf_len, oid * objid, size_t objidlen, int width) { size_t out_len = 0; if (sprint_realloc_description((u_char **) & buf, &buf_len, &out_len, 0, objid, objidlen, width)) { return (int) out_len; } else { return -1; } } #endif /* NETSNMP_FEATURE_REMOVE_MIB_SNPRINT_DESCRIPTION */ int sprint_realloc_description(u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, oid * objid, size_t objidlen, int width) { struct tree *tp = get_tree(objid, objidlen, tree_head); struct tree *subtree = tree_head; int pos, len; char tmpbuf[128]; const char *cp; if (NULL == tp) return 0; if (tp->type <= TYPE_SIMPLE_LAST) cp = " OBJECT-TYPE"; else switch (tp->type) { case TYPE_TRAPTYPE: cp = " TRAP-TYPE"; break; case TYPE_NOTIFTYPE: cp = " NOTIFICATION-TYPE"; break; case TYPE_OBJGROUP: cp = " OBJECT-GROUP"; break; case TYPE_AGENTCAP: cp = " AGENT-CAPABILITIES"; break; case TYPE_MODID: cp = " MODULE-IDENTITY"; break; case TYPE_OBJIDENTITY: cp = " OBJECT-IDENTITY"; break; case TYPE_MODCOMP: cp = " MODULE-COMPLIANCE"; break; default: sprintf(tmpbuf, " type_%d", tp->type); cp = tmpbuf; } if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, tp->label) || !snmp_cstrcat(buf, buf_len, out_len, allow_realloc, cp) || !snmp_cstrcat(buf, buf_len, out_len, allow_realloc, "\n")) { return 0; } if (!print_tree_node(buf, buf_len, out_len, allow_realloc, tp, width)) return 0; if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, "::= {")) return 0; pos = 5; while (objidlen > 1) { for (; subtree; subtree = subtree->next_peer) { if (*objid == subtree->subid) { while (subtree->next_peer && subtree->next_peer->subid == *objid) subtree = subtree->next_peer; if (strncmp(subtree->label, ANON, ANON_LEN)) { snprintf(tmpbuf, sizeof(tmpbuf), " %s(%lu)", subtree->label, subtree->subid); tmpbuf[ sizeof(tmpbuf)-1 ] = 0; } else sprintf(tmpbuf, " %lu", subtree->subid); len = strlen(tmpbuf); if (pos + len + 2 > width) { if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, "\n ")) return 0; pos = 5; } if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, tmpbuf)) return 0; pos += len; objid++; objidlen--; break; } } if (subtree) subtree = subtree->child_list; else break; } while (objidlen > 1) { sprintf(tmpbuf, " %" NETSNMP_PRIo "u", *objid); len = strlen(tmpbuf); if (pos + len + 2 > width) { if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, "\n ")) return 0; pos = 5; } if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, tmpbuf)) return 0; pos += len; objid++; objidlen--; } sprintf(tmpbuf, " %" NETSNMP_PRIo "u }", *objid); len = strlen(tmpbuf); if (pos + len + 2 > width) { if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, "\n ")) return 0; pos = 5; } if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, tmpbuf)) return 0; return 1; } static int print_tree_node(u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, struct tree *tp, int width) { const char *cp; char str[MAXTOKEN]; int i, prevmod, pos, len; if (tp) { module_name(tp->modid, str); if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, " -- FROM\t") || !snmp_cstrcat(buf, buf_len, out_len, allow_realloc, str)) return 0; pos = 16+strlen(str); for (i = 1, prevmod = tp->modid; i < tp->number_modules; i++) { if (prevmod != tp->module_list[i]) { module_name(tp->module_list[i], str); len = strlen(str); if (pos + len + 2 > width) { if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, ",\n --\t\t")) return 0; pos = 16; } else { if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, ", ")) return 0; pos += 2; } if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, str)) return 0; pos += len; } prevmod = tp->module_list[i]; } if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, "\n")) return 0; if (tp->tc_index != -1) { if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, " -- TEXTUAL CONVENTION ") || !snmp_cstrcat(buf, buf_len, out_len, allow_realloc, get_tc_descriptor(tp->tc_index)) || !snmp_cstrcat(buf, buf_len, out_len, allow_realloc, "\n")) return 0; } switch (tp->type) { case TYPE_OBJID: cp = "OBJECT IDENTIFIER"; break; case TYPE_OCTETSTR: cp = "OCTET STRING"; break; case TYPE_INTEGER: cp = "INTEGER"; break; case TYPE_NETADDR: cp = "NetworkAddress"; break; case TYPE_IPADDR: cp = "IpAddress"; break; case TYPE_COUNTER: cp = "Counter32"; break; case TYPE_GAUGE: cp = "Gauge32"; break; case TYPE_TIMETICKS: cp = "TimeTicks"; break; case TYPE_OPAQUE: cp = "Opaque"; break; case TYPE_NULL: cp = "NULL"; break; case TYPE_COUNTER64: cp = "Counter64"; break; case TYPE_BITSTRING: cp = "BITS"; break; case TYPE_NSAPADDRESS: cp = "NsapAddress"; break; case TYPE_UINTEGER: cp = "UInteger32"; break; case TYPE_UNSIGNED32: cp = "Unsigned32"; break; case TYPE_INTEGER32: cp = "Integer32"; break; default: cp = NULL; break; } #if NETSNMP_ENABLE_TESTING_CODE if (!cp && (tp->ranges || tp->enums)) { /* ranges without type ? */ sprintf(str, "?0 with %s %s ?", tp->ranges ? "Range" : "", tp->enums ? "Enum" : ""); cp = str; } #endif /* NETSNMP_ENABLE_TESTING_CODE */ if (cp) if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, " SYNTAX\t") || !snmp_cstrcat(buf, buf_len, out_len, allow_realloc, cp)) return 0; if (tp->ranges) { struct range_list *rp = tp->ranges; int first = 1; if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, " (")) return 0; while (rp) { switch (tp->type) { case TYPE_INTEGER: case TYPE_INTEGER32: if (rp->low == rp->high) sprintf(str, "%s%d", (first ? "" : " | "), rp->low ); else sprintf(str, "%s%d..%d", (first ? "" : " | "), rp->low, rp->high); break; case TYPE_UNSIGNED32: case TYPE_OCTETSTR: case TYPE_GAUGE: case TYPE_UINTEGER: if (rp->low == rp->high) sprintf(str, "%s%u", (first ? "" : " | "), (unsigned)rp->low ); else sprintf(str, "%s%u..%u", (first ? "" : " | "), (unsigned)rp->low, (unsigned)rp->high); break; default: /* No other range types allowed */ break; } if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, str)) return 0; if (first) first = 0; rp = rp->next; } if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, ") ")) return 0; } if (tp->enums) { struct enum_list *ep = tp->enums; int first = 1; if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, " {")) return 0; pos = 16 + strlen(cp) + 2; while (ep) { if (first) first = 0; else if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, ", ")) return 0; snprintf(str, sizeof(str), "%s(%d)", ep->label, ep->value); str[ sizeof(str)-1 ] = 0; len = strlen(str); if (pos + len + 2 > width) { if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, "\n\t\t ")) return 0; pos = 18; } if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, str)) return 0; pos += len + 2; ep = ep->next; } if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, "} ")) return 0; } if (cp) if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, "\n")) return 0; if (tp->hint) if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, " DISPLAY-HINT\t\"") || !snmp_cstrcat(buf, buf_len, out_len, allow_realloc, tp->hint) || !snmp_cstrcat(buf, buf_len, out_len, allow_realloc, "\"\n")) return 0; if (tp->units) if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, " UNITS\t\t\"") || !snmp_cstrcat(buf, buf_len, out_len, allow_realloc, tp->units) || !snmp_cstrcat(buf, buf_len, out_len, allow_realloc, "\"\n")) return 0; switch (tp->access) { case MIB_ACCESS_READONLY: cp = "read-only"; break; case MIB_ACCESS_READWRITE: cp = "read-write"; break; case MIB_ACCESS_WRITEONLY: cp = "write-only"; break; case MIB_ACCESS_NOACCESS: cp = "not-accessible"; break; case MIB_ACCESS_NOTIFY: cp = "accessible-for-notify"; break; case MIB_ACCESS_CREATE: cp = "read-create"; break; case 0: cp = NULL; break; default: sprintf(str, "access_%d", tp->access); cp = str; } if (cp) if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, " MAX-ACCESS\t") || !snmp_cstrcat(buf, buf_len, out_len, allow_realloc, cp) || !snmp_cstrcat(buf, buf_len, out_len, allow_realloc, "\n")) return 0; switch (tp->status) { case MIB_STATUS_MANDATORY: cp = "mandatory"; break; case MIB_STATUS_OPTIONAL: cp = "optional"; break; case MIB_STATUS_OBSOLETE: cp = "obsolete"; break; case MIB_STATUS_DEPRECATED: cp = "deprecated"; break; case MIB_STATUS_CURRENT: cp = "current"; break; case 0: cp = NULL; break; default: sprintf(str, "status_%d", tp->status); cp = str; } #if NETSNMP_ENABLE_TESTING_CODE if (!cp && (tp->indexes)) { /* index without status ? */ sprintf(str, "?0 with %s ?", tp->indexes ? "Index" : ""); cp = str; } #endif /* NETSNMP_ENABLE_TESTING_CODE */ if (cp) if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, " STATUS\t") || !snmp_cstrcat(buf, buf_len, out_len, allow_realloc, cp) || !snmp_cstrcat(buf, buf_len, out_len, allow_realloc, "\n")) return 0; if (tp->augments) if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, " AUGMENTS\t{ ") || !snmp_cstrcat(buf, buf_len, out_len, allow_realloc, tp->augments) || !snmp_cstrcat(buf, buf_len, out_len, allow_realloc, " }\n")) return 0; if (tp->indexes) { struct index_list *ip = tp->indexes; int first = 1; if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, " INDEX\t\t{ ")) return 0; pos = 16 + 2; while (ip) { if (first) first = 0; else if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, ", ")) return 0; snprintf(str, sizeof(str), "%s%s", ip->isimplied ? "IMPLIED " : "", ip->ilabel); str[ sizeof(str)-1 ] = 0; len = strlen(str); if (pos + len + 2 > width) { if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, "\n\t\t ")) return 0; pos = 16 + 2; } if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, str)) return 0; pos += len + 2; ip = ip->next; } if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, " }\n")) return 0; } if (tp->varbinds) { struct varbind_list *vp = tp->varbinds; int first = 1; if (tp->type == TYPE_TRAPTYPE) { if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, " VARIABLES\t{ ")) return 0; } else { if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, " OBJECTS\t{ ")) return 0; } pos = 16 + 2; while (vp) { if (first) first = 0; else if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, ", ")) return 0; strlcpy(str, vp->vblabel, sizeof(str)); len = strlen(str); if (pos + len + 2 > width) { if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, "\n\t\t ")) return 0; pos = 16 + 2; } if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, str)) return 0; pos += len + 2; vp = vp->next; } if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, " }\n")) return 0; } if (tp->description) if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, " DESCRIPTION\t\"") || !snmp_cstrcat(buf, buf_len, out_len, allow_realloc, tp->description) || !snmp_cstrcat(buf, buf_len, out_len, allow_realloc, "\"\n")) return 0; if (tp->defaultValue) if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, " DEFVAL\t{ ") || !snmp_cstrcat(buf, buf_len, out_len, allow_realloc, tp->defaultValue) || !snmp_cstrcat(buf, buf_len, out_len, allow_realloc, " }\n")) return 0; } else if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, "No description\n")) return 0; return 1; } int get_module_node(const char *fname, const char *module, oid * objid, size_t * objidlen) { int modid, rc = 0; struct tree *tp; char *name, *cp; if (!strcmp(module, "ANY")) modid = -1; else { netsnmp_read_module(module); modid = which_module(module); if (modid == -1) return 0; } /* * Isolate the first component of the name ... */ name = strdup(fname); cp = strchr(name, '.'); if (cp != NULL) { *cp = '\0'; cp++; } /* * ... and locate it in the tree. */ tp = find_tree_node(name, modid); if (tp) { size_t maxlen = *objidlen; /* * Set the first element of the object ID */ if (node_to_oid(tp, objid, objidlen)) { rc = 1; /* * If the name requested was more than one element, * tag on the rest of the components */ if (cp != NULL) rc = _add_strings_to_oid(tp, cp, objid, objidlen, maxlen); } } SNMP_FREE(name); return (rc); } /** * @internal * * Populates the object identifier from a node in the MIB hierarchy. * Builds up the object ID, working backwards, * starting from the end of the objid buffer. * When the top of the MIB tree is reached, the buffer is adjusted. * * The buffer length is set to the number of subidentifiers * for the object identifier associated with the MIB node. * * @return the number of subidentifiers copied. * * If 0 is returned, the objid buffer is too small, * and the buffer contents are indeterminate. * The buffer length can be used to create a larger buffer. */ static int node_to_oid(struct tree *tp, oid * objid, size_t * objidlen) { int numids, lenids; oid *op; if (!tp || !objid || !objidlen) return 0; lenids = (int) *objidlen; op = objid + lenids; /* points after the last element */ for (numids = 0; tp; tp = tp->parent, numids++) { if (numids >= lenids) continue; --op; *op = tp->subid; } *objidlen = (size_t) numids; if (numids > lenids) { return 0; } if (numids < lenids) memmove(objid, op, numids * sizeof(oid)); return (numids); } /* * Replace \x with x stop at eos_marker * return NULL if eos_marker not found */ static char *_apply_escapes(char *src, char eos_marker) { char *dst; int backslash = 0; dst = src; while (*src) { if (backslash) { backslash = 0; *dst++ = *src; } else { if (eos_marker == *src) break; if ('\\' == *src) { backslash = 1; } else { *dst++ = *src; } } src++; } if (!*src) { /* never found eos_marker */ return NULL; } else { *dst = 0; return src; } } #endif /* NETSNMP_DISABLE_MIB_LOADING */ static int #ifndef NETSNMP_DISABLE_MIB_LOADING _add_strings_to_oid(struct tree *tp, char *cp, oid * objid, size_t * objidlen, size_t maxlen) #else _add_strings_to_oid(void *tp, char *cp, oid * objid, size_t * objidlen, size_t maxlen) #endif /* NETSNMP_DISABLE_MIB_LOADING */ { oid subid; char *fcp, *ecp, *cp2 = NULL; char doingquote; int len = -1; #ifndef NETSNMP_DISABLE_MIB_LOADING struct tree *tp2 = NULL; struct index_list *in_dices = NULL; int pos = -1; int check = !netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_DONT_CHECK_RANGE); int do_hint = !netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_NO_DISPLAY_HINT); int len_index = 1000000; while (cp && tp && tp->child_list) { fcp = cp; tp2 = tp->child_list; /* * Isolate the next entry */ cp2 = strchr(cp, '.'); if (cp2) *cp2++ = '\0'; /* * Search for the appropriate child */ if (isdigit((unsigned char)(*cp))) { subid = strtoul(cp, &ecp, 0); if (*ecp) goto bad_id; while (tp2 && tp2->subid != subid) tp2 = tp2->next_peer; } else { while (tp2 && strcmp(tp2->label, fcp)) tp2 = tp2->next_peer; if (!tp2) goto bad_id; subid = tp2->subid; } if (*objidlen >= maxlen) goto bad_id; while (tp2 && tp2->next_peer && tp2->next_peer->subid == subid) tp2 = tp2->next_peer; objid[*objidlen] = subid; (*objidlen)++; cp = cp2; if (!tp2) break; tp = tp2; } if (tp && !tp->child_list) { if ((tp2 = tp->parent)) { if (tp2->indexes) in_dices = tp2->indexes; else if (tp2->augments) { tp2 = find_tree_node(tp2->augments, -1); if (tp2) in_dices = tp2->indexes; } } tp = NULL; } while (cp && in_dices) { fcp = cp; tp = find_tree_node(in_dices->ilabel, -1); if (!tp) break; switch (tp->type) { case TYPE_INTEGER: case TYPE_INTEGER32: case TYPE_UINTEGER: case TYPE_UNSIGNED32: case TYPE_TIMETICKS: /* * Isolate the next entry */ cp2 = strchr(cp, '.'); if (cp2) *cp2++ = '\0'; if (isdigit((unsigned char)(*cp))) { subid = strtoul(cp, &ecp, 0); if (*ecp) goto bad_id; } else { if (tp->enums) { struct enum_list *ep = tp->enums; while (ep && strcmp(ep->label, cp)) ep = ep->next; if (!ep) goto bad_id; subid = ep->value; } else goto bad_id; } if (check && tp->ranges) { struct range_list *rp = tp->ranges; int ok = 0; if (tp->type == TYPE_INTEGER || tp->type == TYPE_INTEGER32) { while (!ok && rp) { if ((rp->low <= (int) subid) && ((int) subid <= rp->high)) ok = 1; else rp = rp->next; } } else { /* check unsigned range */ while (!ok && rp) { if (((unsigned int)rp->low <= subid) && (subid <= (unsigned int)rp->high)) ok = 1; else rp = rp->next; } } if (!ok) goto bad_id; } if (*objidlen >= maxlen) goto bad_id; objid[*objidlen] = subid; (*objidlen)++; break; case TYPE_IPADDR: if (*objidlen + 4 > maxlen) goto bad_id; for (subid = 0; cp && subid < 4; subid++) { fcp = cp; cp2 = strchr(cp, '.'); if (cp2) *cp2++ = 0; objid[*objidlen] = strtoul(cp, &ecp, 0); if (*ecp) goto bad_id; if (check && objid[*objidlen] > 255) goto bad_id; (*objidlen)++; cp = cp2; } break; case TYPE_OCTETSTR: if (tp->ranges && !tp->ranges->next && tp->ranges->low == tp->ranges->high) len = tp->ranges->low; else len = -1; pos = 0; if (*cp == '"' || *cp == '\'') { doingquote = *cp++; /* * insert length if requested */ if (!in_dices->isimplied && len == -1) { if (doingquote == '\'') { snmp_set_detail ("'-quote is for fixed length strings"); return 0; } if (*objidlen >= maxlen) goto bad_id; len_index = *objidlen; (*objidlen)++; } else if (doingquote == '"') { snmp_set_detail ("\"-quote is for variable length strings"); return 0; } cp2 = _apply_escapes(cp, doingquote); if (!cp2) goto bad_id; else { unsigned char *new_val; int new_val_len; int parsed_hint = 0; const char *parsed_value; if (do_hint && tp->hint) { parsed_value = parse_octet_hint(tp->hint, cp, &new_val, &new_val_len); parsed_hint = parsed_value == NULL; } if (parsed_hint) { int i; for (i = 0; i < new_val_len; i++) { if (*objidlen >= maxlen) goto bad_id; objid[ *objidlen ] = new_val[i]; (*objidlen)++; pos++; } SNMP_FREE(new_val); } else { while(*cp) { if (*objidlen >= maxlen) goto bad_id; objid[ *objidlen ] = *cp++; (*objidlen)++; pos++; } } } cp2++; if (!*cp2) cp2 = NULL; else if (*cp2 != '.') goto bad_id; else cp2++; if (check) { if (len == -1) { struct range_list *rp = tp->ranges; int ok = 0; while (rp && !ok) if (rp->low <= pos && pos <= rp->high) ok = 1; else rp = rp->next; if (!ok) goto bad_id; if (!in_dices->isimplied) objid[len_index] = pos; } else if (pos != len) goto bad_id; } else if (len == -1 && !in_dices->isimplied) objid[len_index] = pos; } else { if (!in_dices->isimplied && len == -1) { fcp = cp; cp2 = strchr(cp, '.'); if (cp2) *cp2++ = 0; len = strtoul(cp, &ecp, 0); if (*ecp) goto bad_id; if (*objidlen + len + 1 >= maxlen) goto bad_id; objid[*objidlen] = len; (*objidlen)++; cp = cp2; } while (len && cp) { fcp = cp; cp2 = strchr(cp, '.'); if (cp2) *cp2++ = 0; objid[*objidlen] = strtoul(cp, &ecp, 0); if (*ecp) goto bad_id; if (check && objid[*objidlen] > 255) goto bad_id; (*objidlen)++; len--; cp = cp2; } } break; case TYPE_OBJID: in_dices = NULL; cp2 = cp; break; case TYPE_NETADDR: fcp = cp; cp2 = strchr(cp, '.'); if (cp2) *cp2++ = 0; subid = strtoul(cp, &ecp, 0); if (*ecp) goto bad_id; if (*objidlen + 1 >= maxlen) goto bad_id; objid[*objidlen] = subid; (*objidlen)++; cp = cp2; if (subid == 1) { for (len = 0; cp && len < 4; len++) { fcp = cp; cp2 = strchr(cp, '.'); if (cp2) *cp2++ = 0; subid = strtoul(cp, &ecp, 0); if (*ecp) goto bad_id; if (*objidlen + 1 >= maxlen) goto bad_id; if (check && subid > 255) goto bad_id; objid[*objidlen] = subid; (*objidlen)++; cp = cp2; } } else { in_dices = NULL; } break; default: snmp_log(LOG_ERR, "Unexpected index type: %d %s %s\n", tp->type, in_dices->ilabel, cp); in_dices = NULL; cp2 = cp; break; } cp = cp2; if (in_dices) in_dices = in_dices->next; } #endif /* NETSNMP_DISABLE_MIB_LOADING */ while (cp) { fcp = cp; switch (*cp) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': cp2 = strchr(cp, '.'); if (cp2) *cp2++ = 0; subid = strtoul(cp, &ecp, 0); if (*ecp) goto bad_id; if (*objidlen >= maxlen) goto bad_id; objid[*objidlen] = subid; (*objidlen)++; break; case '"': case '\'': doingquote = *cp++; /* * insert length if requested */ if (doingquote == '"') { if (*objidlen >= maxlen) goto bad_id; objid[*objidlen] = len = strchr(cp, doingquote) - cp; (*objidlen)++; } while (*cp && *cp != doingquote) { if (*objidlen >= maxlen) goto bad_id; objid[*objidlen] = *cp++; (*objidlen)++; } cp2 = cp + 1; if (!*cp2) cp2 = NULL; else if (*cp2 == '.') cp2++; else goto bad_id; break; default: goto bad_id; } cp = cp2; } return 1; bad_id: { char buf[256]; #ifndef NETSNMP_DISABLE_MIB_LOADING if (in_dices) snprintf(buf, sizeof(buf), "Index out of range: %s (%s)", fcp, in_dices->ilabel); else if (tp) snprintf(buf, sizeof(buf), "Sub-id not found: %s -> %s", tp->label, fcp); else #endif /* NETSNMP_DISABLE_MIB_LOADING */ snprintf(buf, sizeof(buf), "%s", fcp); buf[ sizeof(buf)-1 ] = 0; snmp_set_detail(buf); } return 0; } #ifndef NETSNMP_DISABLE_MIB_LOADING /** * @see comments on find_best_tree_node for usage after first time. */ int get_wild_node(const char *name, oid * objid, size_t * objidlen) { struct tree *tp = find_best_tree_node(name, tree_head, NULL); if (!tp) return 0; return get_node(tp->label, objid, objidlen); } int get_node(const char *name, oid * objid, size_t * objidlen) { const char *cp; char ch; int res; cp = name; while ((ch = *cp)) if (('0' <= ch && ch <= '9') || ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') || ch == '-') cp++; else break; if (ch != ':') if (*name == '.') res = get_module_node(name + 1, "ANY", objid, objidlen); else res = get_module_node(name, "ANY", objid, objidlen); else { char *module; /* * requested name is of the form * "module:subidentifier" */ module = (char *) malloc((size_t) (cp - name + 1)); if (!module) return SNMPERR_GENERR; sprintf(module, "%.*s", (int) (cp - name), name); cp++; /* cp now point to the subidentifier */ if (*cp == ':') cp++; /* * 'cp' and 'name' *do* go that way round! */ res = get_module_node(cp, module, objid, objidlen); SNMP_FREE(module); } if (res == 0) { SET_SNMP_ERROR(SNMPERR_UNKNOWN_OBJID); } return res; } #endif /* NETSNMP_DISABLE_MIB_LOADING */ #ifdef testing main(int argc, char *argv[]) { oid objid[MAX_OID_LEN]; int objidlen = MAX_OID_LEN; int count; netsnmp_variable_list variable; netsnmp_init_mib(); if (argc < 2) print_subtree(stdout, tree_head, 0); variable.type = ASN_INTEGER; variable.val.integer = 3; variable.val_len = 4; for (argc--; argc; argc--, argv++) { objidlen = MAX_OID_LEN; printf("read_objid(%s) = %d\n", argv[1], read_objid(argv[1], objid, &objidlen)); for (count = 0; count < objidlen; count++) printf("%d.", objid[count]); printf("\n"); print_variable(objid, objidlen, &variable); } } #endif /* testing */ #ifndef NETSNMP_DISABLE_MIB_LOADING /* * initialize: no peers included in the report. */ void clear_tree_flags(register struct tree *tp) { for (; tp; tp = tp->next_peer) { tp->reported = 0; if (tp->child_list) clear_tree_flags(tp->child_list); /*RECURSE*/} } /* * Update: 1998-07-17 <jhy@gsu.edu> * Added print_oid_report* functions. */ static int print_subtree_oid_report_labeledoid = 0; static int print_subtree_oid_report_oid = 0; static int print_subtree_oid_report_symbolic = 0; static int print_subtree_oid_report_mibchildoid = 0; static int print_subtree_oid_report_suffix = 0; /* * These methods recurse. */ static void print_parent_labeledoid(FILE *, struct tree *); static void print_parent_oid(FILE *, struct tree *); static void print_parent_mibchildoid(FILE *, struct tree *); static void print_parent_label(FILE *, struct tree *); static void print_subtree_oid_report(FILE *, struct tree *, int); void print_oid_report(FILE * fp) { struct tree *tp; clear_tree_flags(tree_head); for (tp = tree_head; tp; tp = tp->next_peer) print_subtree_oid_report(fp, tp, 0); } void print_oid_report_enable_labeledoid(void) { print_subtree_oid_report_labeledoid = 1; } void print_oid_report_enable_oid(void) { print_subtree_oid_report_oid = 1; } void print_oid_report_enable_suffix(void) { print_subtree_oid_report_suffix = 1; } void print_oid_report_enable_symbolic(void) { print_subtree_oid_report_symbolic = 1; } void print_oid_report_enable_mibchildoid(void) { print_subtree_oid_report_mibchildoid = 1; } /* * helper methods for print_subtree_oid_report() * each one traverses back up the node tree * until there is no parent. Then, the label combination * is output, such that the parent is displayed first. * * Warning: these methods are all recursive. */ static void print_parent_labeledoid(FILE * f, struct tree *tp) { if (tp) { if (tp->parent) { print_parent_labeledoid(f, tp->parent); /*RECURSE*/} fprintf(f, ".%s(%lu)", tp->label, tp->subid); } } static void print_parent_oid(FILE * f, struct tree *tp) { if (tp) { if (tp->parent) { print_parent_oid(f, tp->parent); /*RECURSE*/} fprintf(f, ".%lu", tp->subid); } } static void print_parent_mibchildoid(FILE * f, struct tree *tp) { static struct tree *temp; unsigned long elems[100]; int elem_cnt = 0; int i = 0; temp = tp; if (temp) { while (temp->parent) { elems[elem_cnt++] = temp->subid; temp = temp->parent; } elems[elem_cnt++] = temp->subid; } for (i = elem_cnt - 1; i >= 0; i--) { if (i == elem_cnt - 1) { fprintf(f, "%lu", elems[i]); } else { fprintf(f, ".%lu", elems[i]); } } } static void print_parent_label(FILE * f, struct tree *tp) { if (tp) { if (tp->parent) { print_parent_label(f, tp->parent); /*RECURSE*/} fprintf(f, ".%s", tp->label); } } /** * @internal * This methods generates variations on the original print_subtree() report. * Traverse the tree depth first, from least to greatest sub-identifier. * Warning: this methods recurses and calls methods that recurse. * * @param f File descriptor to print to. * @param tree ??? * @param count ??? */ static void print_subtree_oid_report(FILE * f, struct tree *tree, int count) { struct tree *tp; count++; /* * sanity check */ if (!tree) { return; } /* * find the not reported peer with the lowest sub-identifier. * if no more, break the loop and cleanup. * set "reported" flag, and create report for this peer. * recurse using the children of this peer, if any. */ while (1) { register struct tree *ntp; tp = NULL; for (ntp = tree->child_list; ntp; ntp = ntp->next_peer) { if (ntp->reported) continue; if (!tp || (tp->subid > ntp->subid)) tp = ntp; } if (!tp) break; tp->reported = 1; if (print_subtree_oid_report_labeledoid) { print_parent_labeledoid(f, tp); fprintf(f, "\n"); } if (print_subtree_oid_report_oid) { print_parent_oid(f, tp); fprintf(f, "\n"); } if (print_subtree_oid_report_symbolic) { print_parent_label(f, tp); fprintf(f, "\n"); } if (print_subtree_oid_report_mibchildoid) { fprintf(f, "\"%s\"\t", tp->label); fprintf(f, "\t\t\""); print_parent_mibchildoid(f, tp); fprintf(f, "\"\n"); } if (print_subtree_oid_report_suffix) { int i; for (i = 0; i < count; i++) fprintf(f, " "); fprintf(f, "%s(%ld) type=%d", tp->label, tp->subid, tp->type); if (tp->tc_index != -1) fprintf(f, " tc=%d", tp->tc_index); if (tp->hint) fprintf(f, " hint=%s", tp->hint); if (tp->units) fprintf(f, " units=%s", tp->units); fprintf(f, "\n"); } print_subtree_oid_report(f, tp, count); /*RECURSE*/} } #endif /* NETSNMP_DISABLE_MIB_LOADING */ /** * Converts timeticks to hours, minutes, seconds string. * * @param timeticks The timeticks to convert. * @param buf Buffer to write to, has to be at * least 40 Bytes large. * * @return The buffer * * @see uptimeString */ char * uptime_string(u_long timeticks, char *buf) { return uptime_string_n( timeticks, buf, 40); } char * uptime_string_n(u_long timeticks, char *buf, size_t buflen) { uptimeString(timeticks, buf, buflen); return buf; } /** * Given a string, parses an oid out of it (if possible). * It will try to parse it based on predetermined configuration if * present or by every method possible otherwise. * If a suffix has been registered using NETSNMP_DS_LIB_OIDSUFFIX, it * will be appended to the input string before processing. * * @param argv The OID to string parse * @param root An OID array where the results are stored. * @param rootlen The max length of the array going in and the data * length coming out. * * @return The root oid pointer if successful, or NULL otherwise. */ oid * snmp_parse_oid(const char *argv, oid * root, size_t * rootlen) { #ifndef NETSNMP_DISABLE_MIB_LOADING size_t savlen = *rootlen; #endif /* NETSNMP_DISABLE_MIB_LOADING */ static size_t tmpbuf_len = 0; static char *tmpbuf = NULL; const char *suffix, *prefix; suffix = netsnmp_ds_get_string(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OIDSUFFIX); prefix = netsnmp_ds_get_string(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OIDPREFIX); if ((suffix && suffix[0]) || (prefix && prefix[0])) { if (!suffix) suffix = ""; if (!prefix) prefix = ""; if ((strlen(suffix) + strlen(prefix) + strlen(argv) + 2) > tmpbuf_len) { tmpbuf_len = strlen(suffix) + strlen(argv) + strlen(prefix) + 2; tmpbuf = malloc(tmpbuf_len); } snprintf(tmpbuf, tmpbuf_len, "%s%s%s%s", prefix, argv, ((suffix[0] == '.' || suffix[0] == '\0') ? "" : "."), suffix); argv = tmpbuf; DEBUGMSGTL(("snmp_parse_oid","Parsing: %s\n",argv)); } #ifndef NETSNMP_DISABLE_MIB_LOADING if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_RANDOM_ACCESS) || strchr(argv, ':')) { if (get_node(argv, root, rootlen)) { free(tmpbuf); return root; } } else if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_REGEX_ACCESS)) { clear_tree_flags(tree_head); if (get_wild_node(argv, root, rootlen)) { free(tmpbuf); return root; } } else { #endif /* NETSNMP_DISABLE_MIB_LOADING */ if (read_objid(argv, root, rootlen)) { free(tmpbuf); return root; } #ifndef NETSNMP_DISABLE_MIB_LOADING *rootlen = savlen; if (get_node(argv, root, rootlen)) { free(tmpbuf); return root; } *rootlen = savlen; DEBUGMSGTL(("parse_oid", "wildly parsing\n")); clear_tree_flags(tree_head); if (get_wild_node(argv, root, rootlen)) { free(tmpbuf); return root; } } #endif /* NETSNMP_DISABLE_MIB_LOADING */ free(tmpbuf); return NULL; } #ifndef NETSNMP_DISABLE_MIB_LOADING /* * Use DISPLAY-HINT to parse a value into an octet string. * * note that "1d1d", "11" could have come from an octet string that * looked like { 1, 1 } or an octet string that looked like { 11 } * because of this, it's doubtful that anyone would use such a display * string. Therefore, the parser ignores this case. */ struct parse_hints { int length; int repeat; int format; int separator; int terminator; unsigned char *result; int result_max; int result_len; }; static void parse_hints_reset(struct parse_hints *ph) { ph->length = 0; ph->repeat = 0; ph->format = 0; ph->separator = 0; ph->terminator = 0; } static void parse_hints_ctor(struct parse_hints *ph) { parse_hints_reset(ph); ph->result = NULL; ph->result_max = 0; ph->result_len = 0; } static int parse_hints_add_result_octet(struct parse_hints *ph, unsigned char octet) { if (!(ph->result_len < ph->result_max)) { ph->result_max = ph->result_len + 32; if (!ph->result) { ph->result = (unsigned char *)malloc(ph->result_max); } else { ph->result = (unsigned char *)realloc(ph->result, ph->result_max); } } if (!ph->result) { return 0; /* failed */ } ph->result[ph->result_len++] = octet; return 1; /* success */ } static int parse_hints_parse(struct parse_hints *ph, const char **v_in_out) { const char *v = *v_in_out; char *nv; int base; int repeats = 0; int repeat_fixup = ph->result_len; if (ph->repeat) { if (!parse_hints_add_result_octet(ph, 0)) { return 0; } } do { base = 0; switch (ph->format) { case 'x': base += 6; /* fall through */ case 'd': base += 2; /* fall through */ case 'o': base += 8; /* fall through */ { int i; unsigned long number = strtol(v, &nv, base); if (nv == v) return 0; v = nv; for (i = 0; i < ph->length; i++) { int shift = 8 * (ph->length - 1 - i); if (!parse_hints_add_result_octet(ph, (u_char)(number >> shift) )) { return 0; /* failed */ } } } break; case 'a': { int i; for (i = 0; i < ph->length && *v; i++) { if (!parse_hints_add_result_octet(ph, *v++)) { return 0; /* failed */ } } } break; } repeats++; if (ph->separator && *v) { if (*v == ph->separator) { v++; } else { return 0; /* failed */ } } if (ph->terminator) { if (*v == ph->terminator) { v++; break; } } } while (ph->repeat && *v); if (ph->repeat) { ph->result[repeat_fixup] = repeats; } *v_in_out = v; return 1; } static void parse_hints_length_add_digit(struct parse_hints *ph, int digit) { ph->length *= 10; ph->length += digit - '0'; } const char *parse_octet_hint(const char *hint, const char *value, unsigned char **new_val, int *new_val_len) { const char *h = hint; const char *v = value; struct parse_hints ph; int retval = 1; /* See RFC 1443 */ enum { HINT_1_2, HINT_2_3, HINT_1_2_4, HINT_1_2_5 } state = HINT_1_2; parse_hints_ctor(&ph); while (*h && *v && retval) { switch (state) { case HINT_1_2: if ('*' == *h) { ph.repeat = 1; state = HINT_2_3; } else if (isdigit((unsigned char)(*h))) { parse_hints_length_add_digit(&ph, *h); state = HINT_2_3; } else { return v; /* failed */ } break; case HINT_2_3: if (isdigit((unsigned char)(*h))) { parse_hints_length_add_digit(&ph, *h); /* state = HINT_2_3 */ } else if ('x' == *h || 'd' == *h || 'o' == *h || 'a' == *h) { ph.format = *h; state = HINT_1_2_4; } else { return v; /* failed */ } break; case HINT_1_2_4: if ('*' == *h) { retval = parse_hints_parse(&ph, &v); parse_hints_reset(&ph); ph.repeat = 1; state = HINT_2_3; } else if (isdigit((unsigned char)(*h))) { retval = parse_hints_parse(&ph, &v); parse_hints_reset(&ph); parse_hints_length_add_digit(&ph, *h); state = HINT_2_3; } else { ph.separator = *h; state = HINT_1_2_5; } break; case HINT_1_2_5: if ('*' == *h) { retval = parse_hints_parse(&ph, &v); parse_hints_reset(&ph); ph.repeat = 1; state = HINT_2_3; } else if (isdigit((unsigned char)(*h))) { retval = parse_hints_parse(&ph, &v); parse_hints_reset(&ph); parse_hints_length_add_digit(&ph, *h); state = HINT_2_3; } else { ph.terminator = *h; retval = parse_hints_parse(&ph, &v); parse_hints_reset(&ph); state = HINT_1_2; } break; } h++; } while (*v && retval) { retval = parse_hints_parse(&ph, &v); } if (retval) { *new_val = ph.result; *new_val_len = ph.result_len; } else { if (ph.result) { SNMP_FREE(ph.result); } *new_val = NULL; *new_val_len = 0; } return retval ? NULL : v; } #endif /* NETSNMP_DISABLE_MIB_LOADING */ #ifdef test_display_hint int main(int argc, const char **argv) { const char *hint; const char *value; unsigned char *new_val; int new_val_len; char *r; if (argc < 3) { fprintf(stderr, "usage: dh <hint> <value>\n"); exit(2); } hint = argv[1]; value = argv[2]; r = parse_octet_hint(hint, value, &new_val, &new_val_len); printf("{\"%s\", \"%s\"}: \n\t", hint, value); if (r) { *r = 0; printf("returned failed\n"); printf("value syntax error at: %s\n", value); } else { int i; printf("returned success\n"); for (i = 0; i < new_val_len; i++) { int c = new_val[i] & 0xFF; printf("%02X(%c) ", c, isprint(c) ? c : ' '); } SNMP_FREE(new_val); } printf("\n"); exit(0); } #endif /* test_display_hint */ #ifndef NETSNMP_FEATURE_REMOVE_MIB_TO_ASN_TYPE u_char mib_to_asn_type(int mib_type) { switch (mib_type) { case TYPE_OBJID: return ASN_OBJECT_ID; case TYPE_OCTETSTR: return ASN_OCTET_STR; case TYPE_NETADDR: case TYPE_IPADDR: return ASN_IPADDRESS; case TYPE_INTEGER32: case TYPE_INTEGER: return ASN_INTEGER; case TYPE_COUNTER: return ASN_COUNTER; case TYPE_GAUGE: return ASN_GAUGE; case TYPE_TIMETICKS: return ASN_TIMETICKS; case TYPE_OPAQUE: return ASN_OPAQUE; case TYPE_NULL: return ASN_NULL; case TYPE_COUNTER64: return ASN_COUNTER64; case TYPE_BITSTRING: return ASN_BIT_STR; case TYPE_UINTEGER: case TYPE_UNSIGNED32: return ASN_UNSIGNED; case TYPE_NSAPADDRESS: return ASN_NSAP; } return -1; } #endif /* NETSNMP_FEATURE_REMOVE_MIB_TO_ASN_TYPE */ /** * Converts a string to its OID form. * in example "hello" = 5 . 'h' . 'e' . 'l' . 'l' . 'o' * * @param S The string. * @param O The oid. * @param L The length of the oid. * * @return 0 on Sucess, 1 on failure. */ #ifndef NETSNMP_FEATURE_REMOVE_MIB_STRING_CONVERSIONS int netsnmp_str2oid(const char *S, oid * O, int L) { const char *c = S; oid *o = &O[1]; --L; /* leave room for length prefix */ for (; *c && L; --L, ++o, ++c) *o = *c; /* * make sure we got to the end of the string */ if (*c != 0) return 1; /* * set the length of the oid */ *O = c - S; return 0; } /** * Converts an OID to its character form. * in example 5 . 1 . 2 . 3 . 4 . 5 = 12345 * * @param C The character buffer. * @param L The length of the buffer. * @param O The oid. * * @return 0 on Sucess, 1 on failure. */ int netsnmp_oid2chars(char *C, int L, const oid * O) { char *c = C; const oid *o = &O[1]; if (L < (int)*O) return 1; L = *O; /** length */ for (; L; --L, ++o, ++c) { if (*o > 0xFF) return 1; *c = (char)*o; } return 0; } /** * Converts an OID to its string form. * in example 5 . 'h' . 'e' . 'l' . 'l' . 'o' = "hello\0" (null terminated) * * @param S The character string buffer. * @param L The length of the string buffer. * @param O The oid. * * @return 0 on Sucess, 1 on failure. */ int netsnmp_oid2str(char *S, int L, oid * O) { int rc; if (L <= (int)*O) return 1; rc = netsnmp_oid2chars(S, L, O); if (rc) return 1; S[ *O ] = 0; return 0; } #endif /* NETSNMP_FEATURE_REMOVE_MIB_STRING_CONVERSIONS */ #ifndef NETSNMP_FEATURE_REMOVE_MIB_SNPRINT int snprint_by_type(char *buf, size_t buf_len, netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { size_t out_len = 0; if (sprint_realloc_by_type((u_char **) & buf, &buf_len, &out_len, 0, var, enums, hint, units)) return (int) out_len; else return -1; } int snprint_hexstring(char *buf, size_t buf_len, const u_char * cp, size_t len) { size_t out_len = 0; if (sprint_realloc_hexstring((u_char **) & buf, &buf_len, &out_len, 0, cp, len)) return (int) out_len; else return -1; } int snprint_asciistring(char *buf, size_t buf_len, const u_char * cp, size_t len) { size_t out_len = 0; if (sprint_realloc_asciistring ((u_char **) & buf, &buf_len, &out_len, 0, cp, len)) return (int) out_len; else return -1; } int snprint_octet_string(char *buf, size_t buf_len, const netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { size_t out_len = 0; if (sprint_realloc_octet_string ((u_char **) & buf, &buf_len, &out_len, 0, var, enums, hint, units)) return (int) out_len; else return -1; } int snprint_opaque(char *buf, size_t buf_len, const netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { size_t out_len = 0; if (sprint_realloc_opaque((u_char **) & buf, &buf_len, &out_len, 0, var, enums, hint, units)) return (int) out_len; else return -1; } int snprint_object_identifier(char *buf, size_t buf_len, const netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { size_t out_len = 0; if (sprint_realloc_object_identifier ((u_char **) & buf, &buf_len, &out_len, 0, var, enums, hint, units)) return (int) out_len; else return -1; } int snprint_timeticks(char *buf, size_t buf_len, const netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { size_t out_len = 0; if (sprint_realloc_timeticks((u_char **) & buf, &buf_len, &out_len, 0, var, enums, hint, units)) return (int) out_len; else return -1; } int snprint_hinted_integer(char *buf, size_t buf_len, long val, const char *hint, const char *units) { size_t out_len = 0; if (sprint_realloc_hinted_integer ((u_char **) & buf, &buf_len, &out_len, 0, val, 'd', hint, units)) return (int) out_len; else return -1; } int snprint_integer(char *buf, size_t buf_len, const netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { size_t out_len = 0; if (sprint_realloc_integer((u_char **) & buf, &buf_len, &out_len, 0, var, enums, hint, units)) return (int) out_len; else return -1; } int snprint_uinteger(char *buf, size_t buf_len, const netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { size_t out_len = 0; if (sprint_realloc_uinteger((u_char **) & buf, &buf_len, &out_len, 0, var, enums, hint, units)) return (int) out_len; else return -1; } int snprint_gauge(char *buf, size_t buf_len, const netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { size_t out_len = 0; if (sprint_realloc_gauge((u_char **) & buf, &buf_len, &out_len, 0, var, enums, hint, units)) return (int) out_len; else return -1; } int snprint_counter(char *buf, size_t buf_len, const netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { size_t out_len = 0; if (sprint_realloc_counter((u_char **) & buf, &buf_len, &out_len, 0, var, enums, hint, units)) return (int) out_len; else return -1; } int snprint_networkaddress(char *buf, size_t buf_len, const netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { size_t out_len = 0; if (sprint_realloc_networkaddress ((u_char **) & buf, &buf_len, &out_len, 0, var, enums, hint, units)) return (int) out_len; else return -1; } int snprint_ipaddress(char *buf, size_t buf_len, const netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { size_t out_len = 0; if (sprint_realloc_ipaddress((u_char **) & buf, &buf_len, &out_len, 0, var, enums, hint, units)) return (int) out_len; else return -1; } int snprint_null(char *buf, size_t buf_len, const netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { size_t out_len = 0; if (sprint_realloc_null((u_char **) & buf, &buf_len, &out_len, 0, var, enums, hint, units)) return (int) out_len; else return -1; } int snprint_bitstring(char *buf, size_t buf_len, const netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { size_t out_len = 0; if (sprint_realloc_bitstring((u_char **) & buf, &buf_len, &out_len, 0, var, enums, hint, units)) return (int) out_len; else return -1; } int snprint_nsapaddress(char *buf, size_t buf_len, const netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { size_t out_len = 0; if (sprint_realloc_nsapaddress ((u_char **) & buf, &buf_len, &out_len, 0, var, enums, hint, units)) return (int) out_len; else return -1; } int snprint_counter64(char *buf, size_t buf_len, const netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { size_t out_len = 0; if (sprint_realloc_counter64((u_char **) & buf, &buf_len, &out_len, 0, var, enums, hint, units)) return (int) out_len; else return -1; } int snprint_badtype(char *buf, size_t buf_len, const netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { size_t out_len = 0; if (sprint_realloc_badtype((u_char **) & buf, &buf_len, &out_len, 0, var, enums, hint, units)) return (int) out_len; else return -1; } #ifdef NETSNMP_WITH_OPAQUE_SPECIAL_TYPES int snprint_float(char *buf, size_t buf_len, const netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { size_t out_len = 0; if (sprint_realloc_float((u_char **) & buf, &buf_len, &out_len, 0, var, enums, hint, units)) return (int) out_len; else return -1; } int snprint_double(char *buf, size_t buf_len, const netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { size_t out_len = 0; if (sprint_realloc_double((u_char **) & buf, &buf_len, &out_len, 0, var, enums, hint, units)) return (int) out_len; else return -1; } #endif #endif /* NETSNMP_FEATURE_REMOVE_MIB_SNPRINT */ /** @} */
./CrossVul/dataset_final_sorted/CWE-59/c/good_4226_3
crossvul-cpp_data_good_2241_0
/* * linux/fs/namei.c * * Copyright (C) 1991, 1992 Linus Torvalds */ /* * Some corrections by tytso. */ /* [Feb 1997 T. Schoebel-Theuer] Complete rewrite of the pathname * lookup logic. */ /* [Feb-Apr 2000, AV] Rewrite to the new namespace architecture. */ #include <linux/init.h> #include <linux/export.h> #include <linux/kernel.h> #include <linux/slab.h> #include <linux/fs.h> #include <linux/namei.h> #include <linux/pagemap.h> #include <linux/fsnotify.h> #include <linux/personality.h> #include <linux/security.h> #include <linux/ima.h> #include <linux/syscalls.h> #include <linux/mount.h> #include <linux/audit.h> #include <linux/capability.h> #include <linux/file.h> #include <linux/fcntl.h> #include <linux/device_cgroup.h> #include <linux/fs_struct.h> #include <linux/posix_acl.h> #include <asm/uaccess.h> #include "internal.h" #include "mount.h" /* [Feb-1997 T. Schoebel-Theuer] * Fundamental changes in the pathname lookup mechanisms (namei) * were necessary because of omirr. The reason is that omirr needs * to know the _real_ pathname, not the user-supplied one, in case * of symlinks (and also when transname replacements occur). * * The new code replaces the old recursive symlink resolution with * an iterative one (in case of non-nested symlink chains). It does * this with calls to <fs>_follow_link(). * As a side effect, dir_namei(), _namei() and follow_link() are now * replaced with a single function lookup_dentry() that can handle all * the special cases of the former code. * * With the new dcache, the pathname is stored at each inode, at least as * long as the refcount of the inode is positive. As a side effect, the * size of the dcache depends on the inode cache and thus is dynamic. * * [29-Apr-1998 C. Scott Ananian] Updated above description of symlink * resolution to correspond with current state of the code. * * Note that the symlink resolution is not *completely* iterative. * There is still a significant amount of tail- and mid- recursion in * the algorithm. Also, note that <fs>_readlink() is not used in * lookup_dentry(): lookup_dentry() on the result of <fs>_readlink() * may return different results than <fs>_follow_link(). Many virtual * filesystems (including /proc) exhibit this behavior. */ /* [24-Feb-97 T. Schoebel-Theuer] Side effects caused by new implementation: * New symlink semantics: when open() is called with flags O_CREAT | O_EXCL * and the name already exists in form of a symlink, try to create the new * name indicated by the symlink. The old code always complained that the * name already exists, due to not following the symlink even if its target * is nonexistent. The new semantics affects also mknod() and link() when * the name is a symlink pointing to a non-existent name. * * I don't know which semantics is the right one, since I have no access * to standards. But I found by trial that HP-UX 9.0 has the full "new" * semantics implemented, while SunOS 4.1.1 and Solaris (SunOS 5.4) have the * "old" one. Personally, I think the new semantics is much more logical. * Note that "ln old new" where "new" is a symlink pointing to a non-existing * file does succeed in both HP-UX and SunOs, but not in Solaris * and in the old Linux semantics. */ /* [16-Dec-97 Kevin Buhr] For security reasons, we change some symlink * semantics. See the comments in "open_namei" and "do_link" below. * * [10-Sep-98 Alan Modra] Another symlink change. */ /* [Feb-Apr 2000 AV] Complete rewrite. Rules for symlinks: * inside the path - always follow. * in the last component in creation/removal/renaming - never follow. * if LOOKUP_FOLLOW passed - follow. * if the pathname has trailing slashes - follow. * otherwise - don't follow. * (applied in that order). * * [Jun 2000 AV] Inconsistent behaviour of open() in case if flags==O_CREAT * restored for 2.4. This is the last surviving part of old 4.2BSD bug. * During the 2.4 we need to fix the userland stuff depending on it - * hopefully we will be able to get rid of that wart in 2.5. So far only * XEmacs seems to be relying on it... */ /* * [Sep 2001 AV] Single-semaphore locking scheme (kudos to David Holland) * implemented. Let's see if raised priority of ->s_vfs_rename_mutex gives * any extra contention... */ /* In order to reduce some races, while at the same time doing additional * checking and hopefully speeding things up, we copy filenames to the * kernel data space before using them.. * * POSIX.1 2.4: an empty pathname is invalid (ENOENT). * PATH_MAX includes the nul terminator --RR. */ void final_putname(struct filename *name) { if (name->separate) { __putname(name->name); kfree(name); } else { __putname(name); } } #define EMBEDDED_NAME_MAX (PATH_MAX - sizeof(struct filename)) static struct filename * getname_flags(const char __user *filename, int flags, int *empty) { struct filename *result, *err; int len; long max; char *kname; result = audit_reusename(filename); if (result) return result; result = __getname(); if (unlikely(!result)) return ERR_PTR(-ENOMEM); /* * First, try to embed the struct filename inside the names_cache * allocation */ kname = (char *)result + sizeof(*result); result->name = kname; result->separate = false; max = EMBEDDED_NAME_MAX; recopy: len = strncpy_from_user(kname, filename, max); if (unlikely(len < 0)) { err = ERR_PTR(len); goto error; } /* * Uh-oh. We have a name that's approaching PATH_MAX. Allocate a * separate struct filename so we can dedicate the entire * names_cache allocation for the pathname, and re-do the copy from * userland. */ if (len == EMBEDDED_NAME_MAX && max == EMBEDDED_NAME_MAX) { kname = (char *)result; result = kzalloc(sizeof(*result), GFP_KERNEL); if (!result) { err = ERR_PTR(-ENOMEM); result = (struct filename *)kname; goto error; } result->name = kname; result->separate = true; max = PATH_MAX; goto recopy; } /* The empty path is special. */ if (unlikely(!len)) { if (empty) *empty = 1; err = ERR_PTR(-ENOENT); if (!(flags & LOOKUP_EMPTY)) goto error; } err = ERR_PTR(-ENAMETOOLONG); if (unlikely(len >= PATH_MAX)) goto error; result->uptr = filename; result->aname = NULL; audit_getname(result); return result; error: final_putname(result); return err; } struct filename * getname(const char __user * filename) { return getname_flags(filename, 0, NULL); } /* * The "getname_kernel()" interface doesn't do pathnames longer * than EMBEDDED_NAME_MAX. Deal with it - you're a kernel user. */ struct filename * getname_kernel(const char * filename) { struct filename *result; char *kname; int len; len = strlen(filename); if (len >= EMBEDDED_NAME_MAX) return ERR_PTR(-ENAMETOOLONG); result = __getname(); if (unlikely(!result)) return ERR_PTR(-ENOMEM); kname = (char *)result + sizeof(*result); result->name = kname; result->uptr = NULL; result->aname = NULL; result->separate = false; strlcpy(kname, filename, EMBEDDED_NAME_MAX); return result; } #ifdef CONFIG_AUDITSYSCALL void putname(struct filename *name) { if (unlikely(!audit_dummy_context())) return audit_putname(name); final_putname(name); } #endif static int check_acl(struct inode *inode, int mask) { #ifdef CONFIG_FS_POSIX_ACL struct posix_acl *acl; if (mask & MAY_NOT_BLOCK) { acl = get_cached_acl_rcu(inode, ACL_TYPE_ACCESS); if (!acl) return -EAGAIN; /* no ->get_acl() calls in RCU mode... */ if (acl == ACL_NOT_CACHED) return -ECHILD; return posix_acl_permission(inode, acl, mask & ~MAY_NOT_BLOCK); } acl = get_acl(inode, ACL_TYPE_ACCESS); if (IS_ERR(acl)) return PTR_ERR(acl); if (acl) { int error = posix_acl_permission(inode, acl, mask); posix_acl_release(acl); return error; } #endif return -EAGAIN; } /* * This does the basic permission checking */ static int acl_permission_check(struct inode *inode, int mask) { unsigned int mode = inode->i_mode; if (likely(uid_eq(current_fsuid(), inode->i_uid))) mode >>= 6; else { if (IS_POSIXACL(inode) && (mode & S_IRWXG)) { int error = check_acl(inode, mask); if (error != -EAGAIN) return error; } if (in_group_p(inode->i_gid)) mode >>= 3; } /* * If the DACs are ok we don't need any capability check. */ if ((mask & ~mode & (MAY_READ | MAY_WRITE | MAY_EXEC)) == 0) return 0; return -EACCES; } /** * generic_permission - check for access rights on a Posix-like filesystem * @inode: inode to check access rights for * @mask: right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC, ...) * * Used to check for read/write/execute permissions on a file. * We use "fsuid" for this, letting us set arbitrary permissions * for filesystem access without changing the "normal" uids which * are used for other things. * * generic_permission is rcu-walk aware. It returns -ECHILD in case an rcu-walk * request cannot be satisfied (eg. requires blocking or too much complexity). * It would then be called again in ref-walk mode. */ int generic_permission(struct inode *inode, int mask) { int ret; /* * Do the basic permission checks. */ ret = acl_permission_check(inode, mask); if (ret != -EACCES) return ret; if (S_ISDIR(inode->i_mode)) { /* DACs are overridable for directories */ if (capable_wrt_inode_uidgid(inode, CAP_DAC_OVERRIDE)) return 0; if (!(mask & MAY_WRITE)) if (capable_wrt_inode_uidgid(inode, CAP_DAC_READ_SEARCH)) return 0; return -EACCES; } /* * Read/write DACs are always overridable. * Executable DACs are overridable when there is * at least one exec bit set. */ if (!(mask & MAY_EXEC) || (inode->i_mode & S_IXUGO)) if (capable_wrt_inode_uidgid(inode, CAP_DAC_OVERRIDE)) return 0; /* * Searching includes executable on directories, else just read. */ mask &= MAY_READ | MAY_WRITE | MAY_EXEC; if (mask == MAY_READ) if (capable_wrt_inode_uidgid(inode, CAP_DAC_READ_SEARCH)) return 0; return -EACCES; } EXPORT_SYMBOL(generic_permission); /* * We _really_ want to just do "generic_permission()" without * even looking at the inode->i_op values. So we keep a cache * flag in inode->i_opflags, that says "this has not special * permission function, use the fast case". */ static inline int do_inode_permission(struct inode *inode, int mask) { if (unlikely(!(inode->i_opflags & IOP_FASTPERM))) { if (likely(inode->i_op->permission)) return inode->i_op->permission(inode, mask); /* This gets set once for the inode lifetime */ spin_lock(&inode->i_lock); inode->i_opflags |= IOP_FASTPERM; spin_unlock(&inode->i_lock); } return generic_permission(inode, mask); } /** * __inode_permission - Check for access rights to a given inode * @inode: Inode to check permission on * @mask: Right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC) * * Check for read/write/execute permissions on an inode. * * When checking for MAY_APPEND, MAY_WRITE must also be set in @mask. * * This does not check for a read-only file system. You probably want * inode_permission(). */ int __inode_permission(struct inode *inode, int mask) { int retval; if (unlikely(mask & MAY_WRITE)) { /* * Nobody gets write access to an immutable file. */ if (IS_IMMUTABLE(inode)) return -EACCES; } retval = do_inode_permission(inode, mask); if (retval) return retval; retval = devcgroup_inode_permission(inode, mask); if (retval) return retval; return security_inode_permission(inode, mask); } /** * sb_permission - Check superblock-level permissions * @sb: Superblock of inode to check permission on * @inode: Inode to check permission on * @mask: Right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC) * * Separate out file-system wide checks from inode-specific permission checks. */ static int sb_permission(struct super_block *sb, struct inode *inode, int mask) { if (unlikely(mask & MAY_WRITE)) { umode_t mode = inode->i_mode; /* Nobody gets write access to a read-only fs. */ if ((sb->s_flags & MS_RDONLY) && (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) return -EROFS; } return 0; } /** * inode_permission - Check for access rights to a given inode * @inode: Inode to check permission on * @mask: Right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC) * * Check for read/write/execute permissions on an inode. We use fs[ug]id for * this, letting us set arbitrary permissions for filesystem access without * changing the "normal" UIDs which are used for other things. * * When checking for MAY_APPEND, MAY_WRITE must also be set in @mask. */ int inode_permission(struct inode *inode, int mask) { int retval; retval = sb_permission(inode->i_sb, inode, mask); if (retval) return retval; return __inode_permission(inode, mask); } EXPORT_SYMBOL(inode_permission); /** * path_get - get a reference to a path * @path: path to get the reference to * * Given a path increment the reference count to the dentry and the vfsmount. */ void path_get(const struct path *path) { mntget(path->mnt); dget(path->dentry); } EXPORT_SYMBOL(path_get); /** * path_put - put a reference to a path * @path: path to put the reference to * * Given a path decrement the reference count to the dentry and the vfsmount. */ void path_put(const struct path *path) { dput(path->dentry); mntput(path->mnt); } EXPORT_SYMBOL(path_put); /* * Path walking has 2 modes, rcu-walk and ref-walk (see * Documentation/filesystems/path-lookup.txt). In situations when we can't * continue in RCU mode, we attempt to drop out of rcu-walk mode and grab * normal reference counts on dentries and vfsmounts to transition to rcu-walk * mode. Refcounts are grabbed at the last known good point before rcu-walk * got stuck, so ref-walk may continue from there. If this is not successful * (eg. a seqcount has changed), then failure is returned and it's up to caller * to restart the path walk from the beginning in ref-walk mode. */ /** * unlazy_walk - try to switch to ref-walk mode. * @nd: nameidata pathwalk data * @dentry: child of nd->path.dentry or NULL * Returns: 0 on success, -ECHILD on failure * * unlazy_walk attempts to legitimize the current nd->path, nd->root and dentry * for ref-walk mode. @dentry must be a path found by a do_lookup call on * @nd or NULL. Must be called from rcu-walk context. */ static int unlazy_walk(struct nameidata *nd, struct dentry *dentry) { struct fs_struct *fs = current->fs; struct dentry *parent = nd->path.dentry; BUG_ON(!(nd->flags & LOOKUP_RCU)); /* * After legitimizing the bastards, terminate_walk() * will do the right thing for non-RCU mode, and all our * subsequent exit cases should rcu_read_unlock() * before returning. Do vfsmount first; if dentry * can't be legitimized, just set nd->path.dentry to NULL * and rely on dput(NULL) being a no-op. */ if (!legitimize_mnt(nd->path.mnt, nd->m_seq)) return -ECHILD; nd->flags &= ~LOOKUP_RCU; if (!lockref_get_not_dead(&parent->d_lockref)) { nd->path.dentry = NULL; goto out; } /* * For a negative lookup, the lookup sequence point is the parents * sequence point, and it only needs to revalidate the parent dentry. * * For a positive lookup, we need to move both the parent and the * dentry from the RCU domain to be properly refcounted. And the * sequence number in the dentry validates *both* dentry counters, * since we checked the sequence number of the parent after we got * the child sequence number. So we know the parent must still * be valid if the child sequence number is still valid. */ if (!dentry) { if (read_seqcount_retry(&parent->d_seq, nd->seq)) goto out; BUG_ON(nd->inode != parent->d_inode); } else { if (!lockref_get_not_dead(&dentry->d_lockref)) goto out; if (read_seqcount_retry(&dentry->d_seq, nd->seq)) goto drop_dentry; } /* * Sequence counts matched. Now make sure that the root is * still valid and get it if required. */ if (nd->root.mnt && !(nd->flags & LOOKUP_ROOT)) { spin_lock(&fs->lock); if (nd->root.mnt != fs->root.mnt || nd->root.dentry != fs->root.dentry) goto unlock_and_drop_dentry; path_get(&nd->root); spin_unlock(&fs->lock); } rcu_read_unlock(); return 0; unlock_and_drop_dentry: spin_unlock(&fs->lock); drop_dentry: rcu_read_unlock(); dput(dentry); goto drop_root_mnt; out: rcu_read_unlock(); drop_root_mnt: if (!(nd->flags & LOOKUP_ROOT)) nd->root.mnt = NULL; return -ECHILD; } static inline int d_revalidate(struct dentry *dentry, unsigned int flags) { return dentry->d_op->d_revalidate(dentry, flags); } /** * complete_walk - successful completion of path walk * @nd: pointer nameidata * * If we had been in RCU mode, drop out of it and legitimize nd->path. * Revalidate the final result, unless we'd already done that during * the path walk or the filesystem doesn't ask for it. Return 0 on * success, -error on failure. In case of failure caller does not * need to drop nd->path. */ static int complete_walk(struct nameidata *nd) { struct dentry *dentry = nd->path.dentry; int status; if (nd->flags & LOOKUP_RCU) { nd->flags &= ~LOOKUP_RCU; if (!(nd->flags & LOOKUP_ROOT)) nd->root.mnt = NULL; if (!legitimize_mnt(nd->path.mnt, nd->m_seq)) { rcu_read_unlock(); return -ECHILD; } if (unlikely(!lockref_get_not_dead(&dentry->d_lockref))) { rcu_read_unlock(); mntput(nd->path.mnt); return -ECHILD; } if (read_seqcount_retry(&dentry->d_seq, nd->seq)) { rcu_read_unlock(); dput(dentry); mntput(nd->path.mnt); return -ECHILD; } rcu_read_unlock(); } if (likely(!(nd->flags & LOOKUP_JUMPED))) return 0; if (likely(!(dentry->d_flags & DCACHE_OP_WEAK_REVALIDATE))) return 0; status = dentry->d_op->d_weak_revalidate(dentry, nd->flags); if (status > 0) return 0; if (!status) status = -ESTALE; path_put(&nd->path); return status; } static __always_inline void set_root(struct nameidata *nd) { if (!nd->root.mnt) get_fs_root(current->fs, &nd->root); } static int link_path_walk(const char *, struct nameidata *); static __always_inline void set_root_rcu(struct nameidata *nd) { if (!nd->root.mnt) { struct fs_struct *fs = current->fs; unsigned seq; do { seq = read_seqcount_begin(&fs->seq); nd->root = fs->root; nd->seq = __read_seqcount_begin(&nd->root.dentry->d_seq); } while (read_seqcount_retry(&fs->seq, seq)); } } static void path_put_conditional(struct path *path, struct nameidata *nd) { dput(path->dentry); if (path->mnt != nd->path.mnt) mntput(path->mnt); } static inline void path_to_nameidata(const struct path *path, struct nameidata *nd) { if (!(nd->flags & LOOKUP_RCU)) { dput(nd->path.dentry); if (nd->path.mnt != path->mnt) mntput(nd->path.mnt); } nd->path.mnt = path->mnt; nd->path.dentry = path->dentry; } /* * Helper to directly jump to a known parsed path from ->follow_link, * caller must have taken a reference to path beforehand. */ void nd_jump_link(struct nameidata *nd, struct path *path) { path_put(&nd->path); nd->path = *path; nd->inode = nd->path.dentry->d_inode; nd->flags |= LOOKUP_JUMPED; } static inline void put_link(struct nameidata *nd, struct path *link, void *cookie) { struct inode *inode = link->dentry->d_inode; if (inode->i_op->put_link) inode->i_op->put_link(link->dentry, nd, cookie); path_put(link); } int sysctl_protected_symlinks __read_mostly = 0; int sysctl_protected_hardlinks __read_mostly = 0; /** * may_follow_link - Check symlink following for unsafe situations * @link: The path of the symlink * @nd: nameidata pathwalk data * * In the case of the sysctl_protected_symlinks sysctl being enabled, * CAP_DAC_OVERRIDE needs to be specifically ignored if the symlink is * in a sticky world-writable directory. This is to protect privileged * processes from failing races against path names that may change out * from under them by way of other users creating malicious symlinks. * It will permit symlinks to be followed only when outside a sticky * world-writable directory, or when the uid of the symlink and follower * match, or when the directory owner matches the symlink's owner. * * Returns 0 if following the symlink is allowed, -ve on error. */ static inline int may_follow_link(struct path *link, struct nameidata *nd) { const struct inode *inode; const struct inode *parent; if (!sysctl_protected_symlinks) return 0; /* Allowed if owner and follower match. */ inode = link->dentry->d_inode; if (uid_eq(current_cred()->fsuid, inode->i_uid)) return 0; /* Allowed if parent directory not sticky and world-writable. */ parent = nd->path.dentry->d_inode; if ((parent->i_mode & (S_ISVTX|S_IWOTH)) != (S_ISVTX|S_IWOTH)) return 0; /* Allowed if parent directory and link owner match. */ if (uid_eq(parent->i_uid, inode->i_uid)) return 0; audit_log_link_denied("follow_link", link); path_put_conditional(link, nd); path_put(&nd->path); return -EACCES; } /** * safe_hardlink_source - Check for safe hardlink conditions * @inode: the source inode to hardlink from * * Return false if at least one of the following conditions: * - inode is not a regular file * - inode is setuid * - inode is setgid and group-exec * - access failure for read and write * * Otherwise returns true. */ static bool safe_hardlink_source(struct inode *inode) { umode_t mode = inode->i_mode; /* Special files should not get pinned to the filesystem. */ if (!S_ISREG(mode)) return false; /* Setuid files should not get pinned to the filesystem. */ if (mode & S_ISUID) return false; /* Executable setgid files should not get pinned to the filesystem. */ if ((mode & (S_ISGID | S_IXGRP)) == (S_ISGID | S_IXGRP)) return false; /* Hardlinking to unreadable or unwritable sources is dangerous. */ if (inode_permission(inode, MAY_READ | MAY_WRITE)) return false; return true; } /** * may_linkat - Check permissions for creating a hardlink * @link: the source to hardlink from * * Block hardlink when all of: * - sysctl_protected_hardlinks enabled * - fsuid does not match inode * - hardlink source is unsafe (see safe_hardlink_source() above) * - not CAP_FOWNER * * Returns 0 if successful, -ve on error. */ static int may_linkat(struct path *link) { const struct cred *cred; struct inode *inode; if (!sysctl_protected_hardlinks) return 0; cred = current_cred(); inode = link->dentry->d_inode; /* Source inode owner (or CAP_FOWNER) can hardlink all they like, * otherwise, it must be a safe source. */ if (uid_eq(cred->fsuid, inode->i_uid) || safe_hardlink_source(inode) || capable(CAP_FOWNER)) return 0; audit_log_link_denied("linkat", link); return -EPERM; } static __always_inline int follow_link(struct path *link, struct nameidata *nd, void **p) { struct dentry *dentry = link->dentry; int error; char *s; BUG_ON(nd->flags & LOOKUP_RCU); if (link->mnt == nd->path.mnt) mntget(link->mnt); error = -ELOOP; if (unlikely(current->total_link_count >= 40)) goto out_put_nd_path; cond_resched(); current->total_link_count++; touch_atime(link); nd_set_link(nd, NULL); error = security_inode_follow_link(link->dentry, nd); if (error) goto out_put_nd_path; nd->last_type = LAST_BIND; *p = dentry->d_inode->i_op->follow_link(dentry, nd); error = PTR_ERR(*p); if (IS_ERR(*p)) goto out_put_nd_path; error = 0; s = nd_get_link(nd); if (s) { if (unlikely(IS_ERR(s))) { path_put(&nd->path); put_link(nd, link, *p); return PTR_ERR(s); } if (*s == '/') { set_root(nd); path_put(&nd->path); nd->path = nd->root; path_get(&nd->root); nd->flags |= LOOKUP_JUMPED; } nd->inode = nd->path.dentry->d_inode; error = link_path_walk(s, nd); if (unlikely(error)) put_link(nd, link, *p); } return error; out_put_nd_path: *p = NULL; path_put(&nd->path); path_put(link); return error; } static int follow_up_rcu(struct path *path) { struct mount *mnt = real_mount(path->mnt); struct mount *parent; struct dentry *mountpoint; parent = mnt->mnt_parent; if (&parent->mnt == path->mnt) return 0; mountpoint = mnt->mnt_mountpoint; path->dentry = mountpoint; path->mnt = &parent->mnt; return 1; } /* * follow_up - Find the mountpoint of path's vfsmount * * Given a path, find the mountpoint of its source file system. * Replace @path with the path of the mountpoint in the parent mount. * Up is towards /. * * Return 1 if we went up a level and 0 if we were already at the * root. */ int follow_up(struct path *path) { struct mount *mnt = real_mount(path->mnt); struct mount *parent; struct dentry *mountpoint; read_seqlock_excl(&mount_lock); parent = mnt->mnt_parent; if (parent == mnt) { read_sequnlock_excl(&mount_lock); return 0; } mntget(&parent->mnt); mountpoint = dget(mnt->mnt_mountpoint); read_sequnlock_excl(&mount_lock); dput(path->dentry); path->dentry = mountpoint; mntput(path->mnt); path->mnt = &parent->mnt; return 1; } EXPORT_SYMBOL(follow_up); /* * Perform an automount * - return -EISDIR to tell follow_managed() to stop and return the path we * were called with. */ static int follow_automount(struct path *path, unsigned flags, bool *need_mntput) { struct vfsmount *mnt; int err; if (!path->dentry->d_op || !path->dentry->d_op->d_automount) return -EREMOTE; /* We don't want to mount if someone's just doing a stat - * unless they're stat'ing a directory and appended a '/' to * the name. * * We do, however, want to mount if someone wants to open or * create a file of any type under the mountpoint, wants to * traverse through the mountpoint or wants to open the * mounted directory. Also, autofs may mark negative dentries * as being automount points. These will need the attentions * of the daemon to instantiate them before they can be used. */ if (!(flags & (LOOKUP_PARENT | LOOKUP_DIRECTORY | LOOKUP_OPEN | LOOKUP_CREATE | LOOKUP_AUTOMOUNT)) && path->dentry->d_inode) return -EISDIR; current->total_link_count++; if (current->total_link_count >= 40) return -ELOOP; mnt = path->dentry->d_op->d_automount(path); if (IS_ERR(mnt)) { /* * The filesystem is allowed to return -EISDIR here to indicate * it doesn't want to automount. For instance, autofs would do * this so that its userspace daemon can mount on this dentry. * * However, we can only permit this if it's a terminal point in * the path being looked up; if it wasn't then the remainder of * the path is inaccessible and we should say so. */ if (PTR_ERR(mnt) == -EISDIR && (flags & LOOKUP_PARENT)) return -EREMOTE; return PTR_ERR(mnt); } if (!mnt) /* mount collision */ return 0; if (!*need_mntput) { /* lock_mount() may release path->mnt on error */ mntget(path->mnt); *need_mntput = true; } err = finish_automount(mnt, path); switch (err) { case -EBUSY: /* Someone else made a mount here whilst we were busy */ return 0; case 0: path_put(path); path->mnt = mnt; path->dentry = dget(mnt->mnt_root); return 0; default: return err; } } /* * Handle a dentry that is managed in some way. * - Flagged for transit management (autofs) * - Flagged as mountpoint * - Flagged as automount point * * This may only be called in refwalk mode. * * Serialization is taken care of in namespace.c */ static int follow_managed(struct path *path, unsigned flags) { struct vfsmount *mnt = path->mnt; /* held by caller, must be left alone */ unsigned managed; bool need_mntput = false; int ret = 0; /* Given that we're not holding a lock here, we retain the value in a * local variable for each dentry as we look at it so that we don't see * the components of that value change under us */ while (managed = ACCESS_ONCE(path->dentry->d_flags), managed &= DCACHE_MANAGED_DENTRY, unlikely(managed != 0)) { /* Allow the filesystem to manage the transit without i_mutex * being held. */ if (managed & DCACHE_MANAGE_TRANSIT) { BUG_ON(!path->dentry->d_op); BUG_ON(!path->dentry->d_op->d_manage); ret = path->dentry->d_op->d_manage(path->dentry, false); if (ret < 0) break; } /* Transit to a mounted filesystem. */ if (managed & DCACHE_MOUNTED) { struct vfsmount *mounted = lookup_mnt(path); if (mounted) { dput(path->dentry); if (need_mntput) mntput(path->mnt); path->mnt = mounted; path->dentry = dget(mounted->mnt_root); need_mntput = true; continue; } /* Something is mounted on this dentry in another * namespace and/or whatever was mounted there in this * namespace got unmounted before lookup_mnt() could * get it */ } /* Handle an automount point */ if (managed & DCACHE_NEED_AUTOMOUNT) { ret = follow_automount(path, flags, &need_mntput); if (ret < 0) break; continue; } /* We didn't change the current path point */ break; } if (need_mntput && path->mnt == mnt) mntput(path->mnt); if (ret == -EISDIR) ret = 0; return ret < 0 ? ret : need_mntput; } int follow_down_one(struct path *path) { struct vfsmount *mounted; mounted = lookup_mnt(path); if (mounted) { dput(path->dentry); mntput(path->mnt); path->mnt = mounted; path->dentry = dget(mounted->mnt_root); return 1; } return 0; } EXPORT_SYMBOL(follow_down_one); static inline bool managed_dentry_might_block(struct dentry *dentry) { return (dentry->d_flags & DCACHE_MANAGE_TRANSIT && dentry->d_op->d_manage(dentry, true) < 0); } /* * Try to skip to top of mountpoint pile in rcuwalk mode. Fail if * we meet a managed dentry that would need blocking. */ static bool __follow_mount_rcu(struct nameidata *nd, struct path *path, struct inode **inode) { for (;;) { struct mount *mounted; /* * Don't forget we might have a non-mountpoint managed dentry * that wants to block transit. */ if (unlikely(managed_dentry_might_block(path->dentry))) return false; if (!d_mountpoint(path->dentry)) return true; mounted = __lookup_mnt(path->mnt, path->dentry); if (!mounted) break; path->mnt = &mounted->mnt; path->dentry = mounted->mnt.mnt_root; nd->flags |= LOOKUP_JUMPED; nd->seq = read_seqcount_begin(&path->dentry->d_seq); /* * Update the inode too. We don't need to re-check the * dentry sequence number here after this d_inode read, * because a mount-point is always pinned. */ *inode = path->dentry->d_inode; } return read_seqretry(&mount_lock, nd->m_seq); } static int follow_dotdot_rcu(struct nameidata *nd) { set_root_rcu(nd); while (1) { if (nd->path.dentry == nd->root.dentry && nd->path.mnt == nd->root.mnt) { break; } if (nd->path.dentry != nd->path.mnt->mnt_root) { struct dentry *old = nd->path.dentry; struct dentry *parent = old->d_parent; unsigned seq; seq = read_seqcount_begin(&parent->d_seq); if (read_seqcount_retry(&old->d_seq, nd->seq)) goto failed; nd->path.dentry = parent; nd->seq = seq; break; } if (!follow_up_rcu(&nd->path)) break; nd->seq = read_seqcount_begin(&nd->path.dentry->d_seq); } while (d_mountpoint(nd->path.dentry)) { struct mount *mounted; mounted = __lookup_mnt(nd->path.mnt, nd->path.dentry); if (!mounted) break; nd->path.mnt = &mounted->mnt; nd->path.dentry = mounted->mnt.mnt_root; nd->seq = read_seqcount_begin(&nd->path.dentry->d_seq); if (!read_seqretry(&mount_lock, nd->m_seq)) goto failed; } nd->inode = nd->path.dentry->d_inode; return 0; failed: nd->flags &= ~LOOKUP_RCU; if (!(nd->flags & LOOKUP_ROOT)) nd->root.mnt = NULL; rcu_read_unlock(); return -ECHILD; } /* * Follow down to the covering mount currently visible to userspace. At each * point, the filesystem owning that dentry may be queried as to whether the * caller is permitted to proceed or not. */ int follow_down(struct path *path) { unsigned managed; int ret; while (managed = ACCESS_ONCE(path->dentry->d_flags), unlikely(managed & DCACHE_MANAGED_DENTRY)) { /* Allow the filesystem to manage the transit without i_mutex * being held. * * We indicate to the filesystem if someone is trying to mount * something here. This gives autofs the chance to deny anyone * other than its daemon the right to mount on its * superstructure. * * The filesystem may sleep at this point. */ if (managed & DCACHE_MANAGE_TRANSIT) { BUG_ON(!path->dentry->d_op); BUG_ON(!path->dentry->d_op->d_manage); ret = path->dentry->d_op->d_manage( path->dentry, false); if (ret < 0) return ret == -EISDIR ? 0 : ret; } /* Transit to a mounted filesystem. */ if (managed & DCACHE_MOUNTED) { struct vfsmount *mounted = lookup_mnt(path); if (!mounted) break; dput(path->dentry); mntput(path->mnt); path->mnt = mounted; path->dentry = dget(mounted->mnt_root); continue; } /* Don't handle automount points here */ break; } return 0; } EXPORT_SYMBOL(follow_down); /* * Skip to top of mountpoint pile in refwalk mode for follow_dotdot() */ static void follow_mount(struct path *path) { while (d_mountpoint(path->dentry)) { struct vfsmount *mounted = lookup_mnt(path); if (!mounted) break; dput(path->dentry); mntput(path->mnt); path->mnt = mounted; path->dentry = dget(mounted->mnt_root); } } static void follow_dotdot(struct nameidata *nd) { set_root(nd); while(1) { struct dentry *old = nd->path.dentry; if (nd->path.dentry == nd->root.dentry && nd->path.mnt == nd->root.mnt) { break; } if (nd->path.dentry != nd->path.mnt->mnt_root) { /* rare case of legitimate dget_parent()... */ nd->path.dentry = dget_parent(nd->path.dentry); dput(old); break; } if (!follow_up(&nd->path)) break; } follow_mount(&nd->path); nd->inode = nd->path.dentry->d_inode; } /* * This looks up the name in dcache, possibly revalidates the old dentry and * allocates a new one if not found or not valid. In the need_lookup argument * returns whether i_op->lookup is necessary. * * dir->d_inode->i_mutex must be held */ static struct dentry *lookup_dcache(struct qstr *name, struct dentry *dir, unsigned int flags, bool *need_lookup) { struct dentry *dentry; int error; *need_lookup = false; dentry = d_lookup(dir, name); if (dentry) { if (dentry->d_flags & DCACHE_OP_REVALIDATE) { error = d_revalidate(dentry, flags); if (unlikely(error <= 0)) { if (error < 0) { dput(dentry); return ERR_PTR(error); } else if (!d_invalidate(dentry)) { dput(dentry); dentry = NULL; } } } } if (!dentry) { dentry = d_alloc(dir, name); if (unlikely(!dentry)) return ERR_PTR(-ENOMEM); *need_lookup = true; } return dentry; } /* * Call i_op->lookup on the dentry. The dentry must be negative and * unhashed. * * dir->d_inode->i_mutex must be held */ static struct dentry *lookup_real(struct inode *dir, struct dentry *dentry, unsigned int flags) { struct dentry *old; /* Don't create child dentry for a dead directory. */ if (unlikely(IS_DEADDIR(dir))) { dput(dentry); return ERR_PTR(-ENOENT); } old = dir->i_op->lookup(dir, dentry, flags); if (unlikely(old)) { dput(dentry); dentry = old; } return dentry; } static struct dentry *__lookup_hash(struct qstr *name, struct dentry *base, unsigned int flags) { bool need_lookup; struct dentry *dentry; dentry = lookup_dcache(name, base, flags, &need_lookup); if (!need_lookup) return dentry; return lookup_real(base->d_inode, dentry, flags); } /* * It's more convoluted than I'd like it to be, but... it's still fairly * small and for now I'd prefer to have fast path as straight as possible. * It _is_ time-critical. */ static int lookup_fast(struct nameidata *nd, struct path *path, struct inode **inode) { struct vfsmount *mnt = nd->path.mnt; struct dentry *dentry, *parent = nd->path.dentry; int need_reval = 1; int status = 1; int err; /* * Rename seqlock is not required here because in the off chance * of a false negative due to a concurrent rename, we're going to * do the non-racy lookup, below. */ if (nd->flags & LOOKUP_RCU) { unsigned seq; dentry = __d_lookup_rcu(parent, &nd->last, &seq); if (!dentry) goto unlazy; /* * This sequence count validates that the inode matches * the dentry name information from lookup. */ *inode = dentry->d_inode; if (read_seqcount_retry(&dentry->d_seq, seq)) return -ECHILD; /* * This sequence count validates that the parent had no * changes while we did the lookup of the dentry above. * * The memory barrier in read_seqcount_begin of child is * enough, we can use __read_seqcount_retry here. */ if (__read_seqcount_retry(&parent->d_seq, nd->seq)) return -ECHILD; nd->seq = seq; if (unlikely(dentry->d_flags & DCACHE_OP_REVALIDATE)) { status = d_revalidate(dentry, nd->flags); if (unlikely(status <= 0)) { if (status != -ECHILD) need_reval = 0; goto unlazy; } } path->mnt = mnt; path->dentry = dentry; if (unlikely(!__follow_mount_rcu(nd, path, inode))) goto unlazy; if (unlikely(path->dentry->d_flags & DCACHE_NEED_AUTOMOUNT)) goto unlazy; return 0; unlazy: if (unlazy_walk(nd, dentry)) return -ECHILD; } else { dentry = __d_lookup(parent, &nd->last); } if (unlikely(!dentry)) goto need_lookup; if (unlikely(dentry->d_flags & DCACHE_OP_REVALIDATE) && need_reval) status = d_revalidate(dentry, nd->flags); if (unlikely(status <= 0)) { if (status < 0) { dput(dentry); return status; } if (!d_invalidate(dentry)) { dput(dentry); goto need_lookup; } } path->mnt = mnt; path->dentry = dentry; err = follow_managed(path, nd->flags); if (unlikely(err < 0)) { path_put_conditional(path, nd); return err; } if (err) nd->flags |= LOOKUP_JUMPED; *inode = path->dentry->d_inode; return 0; need_lookup: return 1; } /* Fast lookup failed, do it the slow way */ static int lookup_slow(struct nameidata *nd, struct path *path) { struct dentry *dentry, *parent; int err; parent = nd->path.dentry; BUG_ON(nd->inode != parent->d_inode); mutex_lock(&parent->d_inode->i_mutex); dentry = __lookup_hash(&nd->last, parent, nd->flags); mutex_unlock(&parent->d_inode->i_mutex); if (IS_ERR(dentry)) return PTR_ERR(dentry); path->mnt = nd->path.mnt; path->dentry = dentry; err = follow_managed(path, nd->flags); if (unlikely(err < 0)) { path_put_conditional(path, nd); return err; } if (err) nd->flags |= LOOKUP_JUMPED; return 0; } static inline int may_lookup(struct nameidata *nd) { if (nd->flags & LOOKUP_RCU) { int err = inode_permission(nd->inode, MAY_EXEC|MAY_NOT_BLOCK); if (err != -ECHILD) return err; if (unlazy_walk(nd, NULL)) return -ECHILD; } return inode_permission(nd->inode, MAY_EXEC); } static inline int handle_dots(struct nameidata *nd, int type) { if (type == LAST_DOTDOT) { if (nd->flags & LOOKUP_RCU) { if (follow_dotdot_rcu(nd)) return -ECHILD; } else follow_dotdot(nd); } return 0; } static void terminate_walk(struct nameidata *nd) { if (!(nd->flags & LOOKUP_RCU)) { path_put(&nd->path); } else { nd->flags &= ~LOOKUP_RCU; if (!(nd->flags & LOOKUP_ROOT)) nd->root.mnt = NULL; rcu_read_unlock(); } } /* * Do we need to follow links? We _really_ want to be able * to do this check without having to look at inode->i_op, * so we keep a cache of "no, this doesn't need follow_link" * for the common case. */ static inline int should_follow_link(struct dentry *dentry, int follow) { return unlikely(d_is_symlink(dentry)) ? follow : 0; } static inline int walk_component(struct nameidata *nd, struct path *path, int follow) { struct inode *inode; int err; /* * "." and ".." are special - ".." especially so because it has * to be able to know about the current root directory and * parent relationships. */ if (unlikely(nd->last_type != LAST_NORM)) return handle_dots(nd, nd->last_type); err = lookup_fast(nd, path, &inode); if (unlikely(err)) { if (err < 0) goto out_err; err = lookup_slow(nd, path); if (err < 0) goto out_err; inode = path->dentry->d_inode; } err = -ENOENT; if (!inode || d_is_negative(path->dentry)) goto out_path_put; if (should_follow_link(path->dentry, follow)) { if (nd->flags & LOOKUP_RCU) { if (unlikely(unlazy_walk(nd, path->dentry))) { err = -ECHILD; goto out_err; } } BUG_ON(inode != path->dentry->d_inode); return 1; } path_to_nameidata(path, nd); nd->inode = inode; return 0; out_path_put: path_to_nameidata(path, nd); out_err: terminate_walk(nd); return err; } /* * This limits recursive symlink follows to 8, while * limiting consecutive symlinks to 40. * * Without that kind of total limit, nasty chains of consecutive * symlinks can cause almost arbitrarily long lookups. */ static inline int nested_symlink(struct path *path, struct nameidata *nd) { int res; if (unlikely(current->link_count >= MAX_NESTED_LINKS)) { path_put_conditional(path, nd); path_put(&nd->path); return -ELOOP; } BUG_ON(nd->depth >= MAX_NESTED_LINKS); nd->depth++; current->link_count++; do { struct path link = *path; void *cookie; res = follow_link(&link, nd, &cookie); if (res) break; res = walk_component(nd, path, LOOKUP_FOLLOW); put_link(nd, &link, cookie); } while (res > 0); current->link_count--; nd->depth--; return res; } /* * We can do the critical dentry name comparison and hashing * operations one word at a time, but we are limited to: * * - Architectures with fast unaligned word accesses. We could * do a "get_unaligned()" if this helps and is sufficiently * fast. * * - non-CONFIG_DEBUG_PAGEALLOC configurations (so that we * do not trap on the (extremely unlikely) case of a page * crossing operation. * * - Furthermore, we need an efficient 64-bit compile for the * 64-bit case in order to generate the "number of bytes in * the final mask". Again, that could be replaced with a * efficient population count instruction or similar. */ #ifdef CONFIG_DCACHE_WORD_ACCESS #include <asm/word-at-a-time.h> #ifdef CONFIG_64BIT static inline unsigned int fold_hash(unsigned long hash) { hash += hash >> (8*sizeof(int)); return hash; } #else /* 32-bit case */ #define fold_hash(x) (x) #endif unsigned int full_name_hash(const unsigned char *name, unsigned int len) { unsigned long a, mask; unsigned long hash = 0; for (;;) { a = load_unaligned_zeropad(name); if (len < sizeof(unsigned long)) break; hash += a; hash *= 9; name += sizeof(unsigned long); len -= sizeof(unsigned long); if (!len) goto done; } mask = bytemask_from_count(len); hash += mask & a; done: return fold_hash(hash); } EXPORT_SYMBOL(full_name_hash); /* * Calculate the length and hash of the path component, and * return the length of the component; */ static inline unsigned long hash_name(const char *name, unsigned int *hashp) { unsigned long a, b, adata, bdata, mask, hash, len; const struct word_at_a_time constants = WORD_AT_A_TIME_CONSTANTS; hash = a = 0; len = -sizeof(unsigned long); do { hash = (hash + a) * 9; len += sizeof(unsigned long); a = load_unaligned_zeropad(name+len); b = a ^ REPEAT_BYTE('/'); } while (!(has_zero(a, &adata, &constants) | has_zero(b, &bdata, &constants))); adata = prep_zero_mask(a, adata, &constants); bdata = prep_zero_mask(b, bdata, &constants); mask = create_zero_mask(adata | bdata); hash += a & zero_bytemask(mask); *hashp = fold_hash(hash); return len + find_zero(mask); } #else unsigned int full_name_hash(const unsigned char *name, unsigned int len) { unsigned long hash = init_name_hash(); while (len--) hash = partial_name_hash(*name++, hash); return end_name_hash(hash); } EXPORT_SYMBOL(full_name_hash); /* * We know there's a real path component here of at least * one character. */ static inline unsigned long hash_name(const char *name, unsigned int *hashp) { unsigned long hash = init_name_hash(); unsigned long len = 0, c; c = (unsigned char)*name; do { len++; hash = partial_name_hash(c, hash); c = (unsigned char)name[len]; } while (c && c != '/'); *hashp = end_name_hash(hash); return len; } #endif /* * Name resolution. * This is the basic name resolution function, turning a pathname into * the final dentry. We expect 'base' to be positive and a directory. * * Returns 0 and nd will have valid dentry and mnt on success. * Returns error and drops reference to input namei data on failure. */ static int link_path_walk(const char *name, struct nameidata *nd) { struct path next; int err; while (*name=='/') name++; if (!*name) return 0; /* At this point we know we have a real path component. */ for(;;) { struct qstr this; long len; int type; err = may_lookup(nd); if (err) break; len = hash_name(name, &this.hash); this.name = name; this.len = len; type = LAST_NORM; if (name[0] == '.') switch (len) { case 2: if (name[1] == '.') { type = LAST_DOTDOT; nd->flags |= LOOKUP_JUMPED; } break; case 1: type = LAST_DOT; } if (likely(type == LAST_NORM)) { struct dentry *parent = nd->path.dentry; nd->flags &= ~LOOKUP_JUMPED; if (unlikely(parent->d_flags & DCACHE_OP_HASH)) { err = parent->d_op->d_hash(parent, &this); if (err < 0) break; } } nd->last = this; nd->last_type = type; if (!name[len]) return 0; /* * If it wasn't NUL, we know it was '/'. Skip that * slash, and continue until no more slashes. */ do { len++; } while (unlikely(name[len] == '/')); if (!name[len]) return 0; name += len; err = walk_component(nd, &next, LOOKUP_FOLLOW); if (err < 0) return err; if (err) { err = nested_symlink(&next, nd); if (err) return err; } if (!d_can_lookup(nd->path.dentry)) { err = -ENOTDIR; break; } } terminate_walk(nd); return err; } static int path_init(int dfd, const char *name, unsigned int flags, struct nameidata *nd, struct file **fp) { int retval = 0; nd->last_type = LAST_ROOT; /* if there are only slashes... */ nd->flags = flags | LOOKUP_JUMPED; nd->depth = 0; if (flags & LOOKUP_ROOT) { struct dentry *root = nd->root.dentry; struct inode *inode = root->d_inode; if (*name) { if (!d_can_lookup(root)) return -ENOTDIR; retval = inode_permission(inode, MAY_EXEC); if (retval) return retval; } nd->path = nd->root; nd->inode = inode; if (flags & LOOKUP_RCU) { rcu_read_lock(); nd->seq = __read_seqcount_begin(&nd->path.dentry->d_seq); nd->m_seq = read_seqbegin(&mount_lock); } else { path_get(&nd->path); } return 0; } nd->root.mnt = NULL; nd->m_seq = read_seqbegin(&mount_lock); if (*name=='/') { if (flags & LOOKUP_RCU) { rcu_read_lock(); set_root_rcu(nd); } else { set_root(nd); path_get(&nd->root); } nd->path = nd->root; } else if (dfd == AT_FDCWD) { if (flags & LOOKUP_RCU) { struct fs_struct *fs = current->fs; unsigned seq; rcu_read_lock(); do { seq = read_seqcount_begin(&fs->seq); nd->path = fs->pwd; nd->seq = __read_seqcount_begin(&nd->path.dentry->d_seq); } while (read_seqcount_retry(&fs->seq, seq)); } else { get_fs_pwd(current->fs, &nd->path); } } else { /* Caller must check execute permissions on the starting path component */ struct fd f = fdget_raw(dfd); struct dentry *dentry; if (!f.file) return -EBADF; dentry = f.file->f_path.dentry; if (*name) { if (!d_can_lookup(dentry)) { fdput(f); return -ENOTDIR; } } nd->path = f.file->f_path; if (flags & LOOKUP_RCU) { if (f.flags & FDPUT_FPUT) *fp = f.file; nd->seq = __read_seqcount_begin(&nd->path.dentry->d_seq); rcu_read_lock(); } else { path_get(&nd->path); fdput(f); } } nd->inode = nd->path.dentry->d_inode; return 0; } static inline int lookup_last(struct nameidata *nd, struct path *path) { if (nd->last_type == LAST_NORM && nd->last.name[nd->last.len]) nd->flags |= LOOKUP_FOLLOW | LOOKUP_DIRECTORY; nd->flags &= ~LOOKUP_PARENT; return walk_component(nd, path, nd->flags & LOOKUP_FOLLOW); } /* Returns 0 and nd will be valid on success; Retuns error, otherwise. */ static int path_lookupat(int dfd, const char *name, unsigned int flags, struct nameidata *nd) { struct file *base = NULL; struct path path; int err; /* * Path walking is largely split up into 2 different synchronisation * schemes, rcu-walk and ref-walk (explained in * Documentation/filesystems/path-lookup.txt). These share much of the * path walk code, but some things particularly setup, cleanup, and * following mounts are sufficiently divergent that functions are * duplicated. Typically there is a function foo(), and its RCU * analogue, foo_rcu(). * * -ECHILD is the error number of choice (just to avoid clashes) that * is returned if some aspect of an rcu-walk fails. Such an error must * be handled by restarting a traditional ref-walk (which will always * be able to complete). */ err = path_init(dfd, name, flags | LOOKUP_PARENT, nd, &base); if (unlikely(err)) return err; current->total_link_count = 0; err = link_path_walk(name, nd); if (!err && !(flags & LOOKUP_PARENT)) { err = lookup_last(nd, &path); while (err > 0) { void *cookie; struct path link = path; err = may_follow_link(&link, nd); if (unlikely(err)) break; nd->flags |= LOOKUP_PARENT; err = follow_link(&link, nd, &cookie); if (err) break; err = lookup_last(nd, &path); put_link(nd, &link, cookie); } } if (!err) err = complete_walk(nd); if (!err && nd->flags & LOOKUP_DIRECTORY) { if (!d_can_lookup(nd->path.dentry)) { path_put(&nd->path); err = -ENOTDIR; } } if (base) fput(base); if (nd->root.mnt && !(nd->flags & LOOKUP_ROOT)) { path_put(&nd->root); nd->root.mnt = NULL; } return err; } static int filename_lookup(int dfd, struct filename *name, unsigned int flags, struct nameidata *nd) { int retval = path_lookupat(dfd, name->name, flags | LOOKUP_RCU, nd); if (unlikely(retval == -ECHILD)) retval = path_lookupat(dfd, name->name, flags, nd); if (unlikely(retval == -ESTALE)) retval = path_lookupat(dfd, name->name, flags | LOOKUP_REVAL, nd); if (likely(!retval)) audit_inode(name, nd->path.dentry, flags & LOOKUP_PARENT); return retval; } static int do_path_lookup(int dfd, const char *name, unsigned int flags, struct nameidata *nd) { struct filename filename = { .name = name }; return filename_lookup(dfd, &filename, flags, nd); } /* does lookup, returns the object with parent locked */ struct dentry *kern_path_locked(const char *name, struct path *path) { struct nameidata nd; struct dentry *d; int err = do_path_lookup(AT_FDCWD, name, LOOKUP_PARENT, &nd); if (err) return ERR_PTR(err); if (nd.last_type != LAST_NORM) { path_put(&nd.path); return ERR_PTR(-EINVAL); } mutex_lock_nested(&nd.path.dentry->d_inode->i_mutex, I_MUTEX_PARENT); d = __lookup_hash(&nd.last, nd.path.dentry, 0); if (IS_ERR(d)) { mutex_unlock(&nd.path.dentry->d_inode->i_mutex); path_put(&nd.path); return d; } *path = nd.path; return d; } int kern_path(const char *name, unsigned int flags, struct path *path) { struct nameidata nd; int res = do_path_lookup(AT_FDCWD, name, flags, &nd); if (!res) *path = nd.path; return res; } EXPORT_SYMBOL(kern_path); /** * vfs_path_lookup - lookup a file path relative to a dentry-vfsmount pair * @dentry: pointer to dentry of the base directory * @mnt: pointer to vfs mount of the base directory * @name: pointer to file name * @flags: lookup flags * @path: pointer to struct path to fill */ int vfs_path_lookup(struct dentry *dentry, struct vfsmount *mnt, const char *name, unsigned int flags, struct path *path) { struct nameidata nd; int err; nd.root.dentry = dentry; nd.root.mnt = mnt; BUG_ON(flags & LOOKUP_PARENT); /* the first argument of do_path_lookup() is ignored with LOOKUP_ROOT */ err = do_path_lookup(AT_FDCWD, name, flags | LOOKUP_ROOT, &nd); if (!err) *path = nd.path; return err; } EXPORT_SYMBOL(vfs_path_lookup); /* * Restricted form of lookup. Doesn't follow links, single-component only, * needs parent already locked. Doesn't follow mounts. * SMP-safe. */ static struct dentry *lookup_hash(struct nameidata *nd) { return __lookup_hash(&nd->last, nd->path.dentry, nd->flags); } /** * lookup_one_len - filesystem helper to lookup single pathname component * @name: pathname component to lookup * @base: base directory to lookup from * @len: maximum length @len should be interpreted to * * Note that this routine is purely a helper for filesystem usage and should * not be called by generic code. Also note that by using this function the * nameidata argument is passed to the filesystem methods and a filesystem * using this helper needs to be prepared for that. */ struct dentry *lookup_one_len(const char *name, struct dentry *base, int len) { struct qstr this; unsigned int c; int err; WARN_ON_ONCE(!mutex_is_locked(&base->d_inode->i_mutex)); this.name = name; this.len = len; this.hash = full_name_hash(name, len); if (!len) return ERR_PTR(-EACCES); if (unlikely(name[0] == '.')) { if (len < 2 || (len == 2 && name[1] == '.')) return ERR_PTR(-EACCES); } while (len--) { c = *(const unsigned char *)name++; if (c == '/' || c == '\0') return ERR_PTR(-EACCES); } /* * See if the low-level filesystem might want * to use its own hash.. */ if (base->d_flags & DCACHE_OP_HASH) { int err = base->d_op->d_hash(base, &this); if (err < 0) return ERR_PTR(err); } err = inode_permission(base->d_inode, MAY_EXEC); if (err) return ERR_PTR(err); return __lookup_hash(&this, base, 0); } EXPORT_SYMBOL(lookup_one_len); int user_path_at_empty(int dfd, const char __user *name, unsigned flags, struct path *path, int *empty) { struct nameidata nd; struct filename *tmp = getname_flags(name, flags, empty); int err = PTR_ERR(tmp); if (!IS_ERR(tmp)) { BUG_ON(flags & LOOKUP_PARENT); err = filename_lookup(dfd, tmp, flags, &nd); putname(tmp); if (!err) *path = nd.path; } return err; } int user_path_at(int dfd, const char __user *name, unsigned flags, struct path *path) { return user_path_at_empty(dfd, name, flags, path, NULL); } EXPORT_SYMBOL(user_path_at); /* * NB: most callers don't do anything directly with the reference to the * to struct filename, but the nd->last pointer points into the name string * allocated by getname. So we must hold the reference to it until all * path-walking is complete. */ static struct filename * user_path_parent(int dfd, const char __user *path, struct nameidata *nd, unsigned int flags) { struct filename *s = getname(path); int error; /* only LOOKUP_REVAL is allowed in extra flags */ flags &= LOOKUP_REVAL; if (IS_ERR(s)) return s; error = filename_lookup(dfd, s, flags | LOOKUP_PARENT, nd); if (error) { putname(s); return ERR_PTR(error); } return s; } /** * mountpoint_last - look up last component for umount * @nd: pathwalk nameidata - currently pointing at parent directory of "last" * @path: pointer to container for result * * This is a special lookup_last function just for umount. In this case, we * need to resolve the path without doing any revalidation. * * The nameidata should be the result of doing a LOOKUP_PARENT pathwalk. Since * mountpoints are always pinned in the dcache, their ancestors are too. Thus, * in almost all cases, this lookup will be served out of the dcache. The only * cases where it won't are if nd->last refers to a symlink or the path is * bogus and it doesn't exist. * * Returns: * -error: if there was an error during lookup. This includes -ENOENT if the * lookup found a negative dentry. The nd->path reference will also be * put in this case. * * 0: if we successfully resolved nd->path and found it to not to be a * symlink that needs to be followed. "path" will also be populated. * The nd->path reference will also be put. * * 1: if we successfully resolved nd->last and found it to be a symlink * that needs to be followed. "path" will be populated with the path * to the link, and nd->path will *not* be put. */ static int mountpoint_last(struct nameidata *nd, struct path *path) { int error = 0; struct dentry *dentry; struct dentry *dir = nd->path.dentry; /* If we're in rcuwalk, drop out of it to handle last component */ if (nd->flags & LOOKUP_RCU) { if (unlazy_walk(nd, NULL)) { error = -ECHILD; goto out; } } nd->flags &= ~LOOKUP_PARENT; if (unlikely(nd->last_type != LAST_NORM)) { error = handle_dots(nd, nd->last_type); if (error) goto out; dentry = dget(nd->path.dentry); goto done; } mutex_lock(&dir->d_inode->i_mutex); dentry = d_lookup(dir, &nd->last); if (!dentry) { /* * No cached dentry. Mounted dentries are pinned in the cache, * so that means that this dentry is probably a symlink or the * path doesn't actually point to a mounted dentry. */ dentry = d_alloc(dir, &nd->last); if (!dentry) { error = -ENOMEM; mutex_unlock(&dir->d_inode->i_mutex); goto out; } dentry = lookup_real(dir->d_inode, dentry, nd->flags); error = PTR_ERR(dentry); if (IS_ERR(dentry)) { mutex_unlock(&dir->d_inode->i_mutex); goto out; } } mutex_unlock(&dir->d_inode->i_mutex); done: if (!dentry->d_inode || d_is_negative(dentry)) { error = -ENOENT; dput(dentry); goto out; } path->dentry = dentry; path->mnt = nd->path.mnt; if (should_follow_link(dentry, nd->flags & LOOKUP_FOLLOW)) return 1; mntget(path->mnt); follow_mount(path); error = 0; out: terminate_walk(nd); return error; } /** * path_mountpoint - look up a path to be umounted * @dfd: directory file descriptor to start walk from * @name: full pathname to walk * @path: pointer to container for result * @flags: lookup flags * * Look up the given name, but don't attempt to revalidate the last component. * Returns 0 and "path" will be valid on success; Returns error otherwise. */ static int path_mountpoint(int dfd, const char *name, struct path *path, unsigned int flags) { struct file *base = NULL; struct nameidata nd; int err; err = path_init(dfd, name, flags | LOOKUP_PARENT, &nd, &base); if (unlikely(err)) return err; current->total_link_count = 0; err = link_path_walk(name, &nd); if (err) goto out; err = mountpoint_last(&nd, path); while (err > 0) { void *cookie; struct path link = *path; err = may_follow_link(&link, &nd); if (unlikely(err)) break; nd.flags |= LOOKUP_PARENT; err = follow_link(&link, &nd, &cookie); if (err) break; err = mountpoint_last(&nd, path); put_link(&nd, &link, cookie); } out: if (base) fput(base); if (nd.root.mnt && !(nd.flags & LOOKUP_ROOT)) path_put(&nd.root); return err; } static int filename_mountpoint(int dfd, struct filename *s, struct path *path, unsigned int flags) { int error = path_mountpoint(dfd, s->name, path, flags | LOOKUP_RCU); if (unlikely(error == -ECHILD)) error = path_mountpoint(dfd, s->name, path, flags); if (unlikely(error == -ESTALE)) error = path_mountpoint(dfd, s->name, path, flags | LOOKUP_REVAL); if (likely(!error)) audit_inode(s, path->dentry, 0); return error; } /** * user_path_mountpoint_at - lookup a path from userland in order to umount it * @dfd: directory file descriptor * @name: pathname from userland * @flags: lookup flags * @path: pointer to container to hold result * * A umount is a special case for path walking. We're not actually interested * in the inode in this situation, and ESTALE errors can be a problem. We * simply want track down the dentry and vfsmount attached at the mountpoint * and avoid revalidating the last component. * * Returns 0 and populates "path" on success. */ int user_path_mountpoint_at(int dfd, const char __user *name, unsigned int flags, struct path *path) { struct filename *s = getname(name); int error; if (IS_ERR(s)) return PTR_ERR(s); error = filename_mountpoint(dfd, s, path, flags); putname(s); return error; } int kern_path_mountpoint(int dfd, const char *name, struct path *path, unsigned int flags) { struct filename s = {.name = name}; return filename_mountpoint(dfd, &s, path, flags); } EXPORT_SYMBOL(kern_path_mountpoint); /* * It's inline, so penalty for filesystems that don't use sticky bit is * minimal. */ static inline int check_sticky(struct inode *dir, struct inode *inode) { kuid_t fsuid = current_fsuid(); if (!(dir->i_mode & S_ISVTX)) return 0; if (uid_eq(inode->i_uid, fsuid)) return 0; if (uid_eq(dir->i_uid, fsuid)) return 0; return !capable_wrt_inode_uidgid(inode, CAP_FOWNER); } /* * Check whether we can remove a link victim from directory dir, check * whether the type of victim is right. * 1. We can't do it if dir is read-only (done in permission()) * 2. We should have write and exec permissions on dir * 3. We can't remove anything from append-only dir * 4. We can't do anything with immutable dir (done in permission()) * 5. If the sticky bit on dir is set we should either * a. be owner of dir, or * b. be owner of victim, or * c. have CAP_FOWNER capability * 6. If the victim is append-only or immutable we can't do antyhing with * links pointing to it. * 7. If we were asked to remove a directory and victim isn't one - ENOTDIR. * 8. If we were asked to remove a non-directory and victim isn't one - EISDIR. * 9. We can't remove a root or mountpoint. * 10. We don't allow removal of NFS sillyrenamed files; it's handled by * nfs_async_unlink(). */ static int may_delete(struct inode *dir, struct dentry *victim, bool isdir) { struct inode *inode = victim->d_inode; int error; if (d_is_negative(victim)) return -ENOENT; BUG_ON(!inode); BUG_ON(victim->d_parent->d_inode != dir); audit_inode_child(dir, victim, AUDIT_TYPE_CHILD_DELETE); error = inode_permission(dir, MAY_WRITE | MAY_EXEC); if (error) return error; if (IS_APPEND(dir)) return -EPERM; if (check_sticky(dir, inode) || IS_APPEND(inode) || IS_IMMUTABLE(inode) || IS_SWAPFILE(inode)) return -EPERM; if (isdir) { if (!d_is_dir(victim)) return -ENOTDIR; if (IS_ROOT(victim)) return -EBUSY; } else if (d_is_dir(victim)) return -EISDIR; if (IS_DEADDIR(dir)) return -ENOENT; if (victim->d_flags & DCACHE_NFSFS_RENAMED) return -EBUSY; return 0; } /* Check whether we can create an object with dentry child in directory * dir. * 1. We can't do it if child already exists (open has special treatment for * this case, but since we are inlined it's OK) * 2. We can't do it if dir is read-only (done in permission()) * 3. We should have write and exec permissions on dir * 4. We can't do it if dir is immutable (done in permission()) */ static inline int may_create(struct inode *dir, struct dentry *child) { audit_inode_child(dir, child, AUDIT_TYPE_CHILD_CREATE); if (child->d_inode) return -EEXIST; if (IS_DEADDIR(dir)) return -ENOENT; return inode_permission(dir, MAY_WRITE | MAY_EXEC); } /* * p1 and p2 should be directories on the same fs. */ struct dentry *lock_rename(struct dentry *p1, struct dentry *p2) { struct dentry *p; if (p1 == p2) { mutex_lock_nested(&p1->d_inode->i_mutex, I_MUTEX_PARENT); return NULL; } mutex_lock(&p1->d_inode->i_sb->s_vfs_rename_mutex); p = d_ancestor(p2, p1); if (p) { mutex_lock_nested(&p2->d_inode->i_mutex, I_MUTEX_PARENT); mutex_lock_nested(&p1->d_inode->i_mutex, I_MUTEX_CHILD); return p; } p = d_ancestor(p1, p2); if (p) { mutex_lock_nested(&p1->d_inode->i_mutex, I_MUTEX_PARENT); mutex_lock_nested(&p2->d_inode->i_mutex, I_MUTEX_CHILD); return p; } mutex_lock_nested(&p1->d_inode->i_mutex, I_MUTEX_PARENT); mutex_lock_nested(&p2->d_inode->i_mutex, I_MUTEX_CHILD); return NULL; } EXPORT_SYMBOL(lock_rename); void unlock_rename(struct dentry *p1, struct dentry *p2) { mutex_unlock(&p1->d_inode->i_mutex); if (p1 != p2) { mutex_unlock(&p2->d_inode->i_mutex); mutex_unlock(&p1->d_inode->i_sb->s_vfs_rename_mutex); } } EXPORT_SYMBOL(unlock_rename); int vfs_create(struct inode *dir, struct dentry *dentry, umode_t mode, bool want_excl) { int error = may_create(dir, dentry); if (error) return error; if (!dir->i_op->create) return -EACCES; /* shouldn't it be ENOSYS? */ mode &= S_IALLUGO; mode |= S_IFREG; error = security_inode_create(dir, dentry, mode); if (error) return error; error = dir->i_op->create(dir, dentry, mode, want_excl); if (!error) fsnotify_create(dir, dentry); return error; } EXPORT_SYMBOL(vfs_create); static int may_open(struct path *path, int acc_mode, int flag) { struct dentry *dentry = path->dentry; struct inode *inode = dentry->d_inode; int error; /* O_PATH? */ if (!acc_mode) return 0; if (!inode) return -ENOENT; switch (inode->i_mode & S_IFMT) { case S_IFLNK: return -ELOOP; case S_IFDIR: if (acc_mode & MAY_WRITE) return -EISDIR; break; case S_IFBLK: case S_IFCHR: if (path->mnt->mnt_flags & MNT_NODEV) return -EACCES; /*FALLTHRU*/ case S_IFIFO: case S_IFSOCK: flag &= ~O_TRUNC; break; } error = inode_permission(inode, acc_mode); if (error) return error; /* * An append-only file must be opened in append mode for writing. */ if (IS_APPEND(inode)) { if ((flag & O_ACCMODE) != O_RDONLY && !(flag & O_APPEND)) return -EPERM; if (flag & O_TRUNC) return -EPERM; } /* O_NOATIME can only be set by the owner or superuser */ if (flag & O_NOATIME && !inode_owner_or_capable(inode)) return -EPERM; return 0; } static int handle_truncate(struct file *filp) { struct path *path = &filp->f_path; struct inode *inode = path->dentry->d_inode; int error = get_write_access(inode); if (error) return error; /* * Refuse to truncate files with mandatory locks held on them. */ error = locks_verify_locked(filp); if (!error) error = security_path_truncate(path); if (!error) { error = do_truncate(path->dentry, 0, ATTR_MTIME|ATTR_CTIME|ATTR_OPEN, filp); } put_write_access(inode); return error; } static inline int open_to_namei_flags(int flag) { if ((flag & O_ACCMODE) == 3) flag--; return flag; } static int may_o_create(struct path *dir, struct dentry *dentry, umode_t mode) { int error = security_path_mknod(dir, dentry, mode, 0); if (error) return error; error = inode_permission(dir->dentry->d_inode, MAY_WRITE | MAY_EXEC); if (error) return error; return security_inode_create(dir->dentry->d_inode, dentry, mode); } /* * Attempt to atomically look up, create and open a file from a negative * dentry. * * Returns 0 if successful. The file will have been created and attached to * @file by the filesystem calling finish_open(). * * Returns 1 if the file was looked up only or didn't need creating. The * caller will need to perform the open themselves. @path will have been * updated to point to the new dentry. This may be negative. * * Returns an error code otherwise. */ static int atomic_open(struct nameidata *nd, struct dentry *dentry, struct path *path, struct file *file, const struct open_flags *op, bool got_write, bool need_lookup, int *opened) { struct inode *dir = nd->path.dentry->d_inode; unsigned open_flag = open_to_namei_flags(op->open_flag); umode_t mode; int error; int acc_mode; int create_error = 0; struct dentry *const DENTRY_NOT_SET = (void *) -1UL; bool excl; BUG_ON(dentry->d_inode); /* Don't create child dentry for a dead directory. */ if (unlikely(IS_DEADDIR(dir))) { error = -ENOENT; goto out; } mode = op->mode; if ((open_flag & O_CREAT) && !IS_POSIXACL(dir)) mode &= ~current_umask(); excl = (open_flag & (O_EXCL | O_CREAT)) == (O_EXCL | O_CREAT); if (excl) open_flag &= ~O_TRUNC; /* * Checking write permission is tricky, bacuse we don't know if we are * going to actually need it: O_CREAT opens should work as long as the * file exists. But checking existence breaks atomicity. The trick is * to check access and if not granted clear O_CREAT from the flags. * * Another problem is returing the "right" error value (e.g. for an * O_EXCL open we want to return EEXIST not EROFS). */ if (((open_flag & (O_CREAT | O_TRUNC)) || (open_flag & O_ACCMODE) != O_RDONLY) && unlikely(!got_write)) { if (!(open_flag & O_CREAT)) { /* * No O_CREATE -> atomicity not a requirement -> fall * back to lookup + open */ goto no_open; } else if (open_flag & (O_EXCL | O_TRUNC)) { /* Fall back and fail with the right error */ create_error = -EROFS; goto no_open; } else { /* No side effects, safe to clear O_CREAT */ create_error = -EROFS; open_flag &= ~O_CREAT; } } if (open_flag & O_CREAT) { error = may_o_create(&nd->path, dentry, mode); if (error) { create_error = error; if (open_flag & O_EXCL) goto no_open; open_flag &= ~O_CREAT; } } if (nd->flags & LOOKUP_DIRECTORY) open_flag |= O_DIRECTORY; file->f_path.dentry = DENTRY_NOT_SET; file->f_path.mnt = nd->path.mnt; error = dir->i_op->atomic_open(dir, dentry, file, open_flag, mode, opened); if (error < 0) { if (create_error && error == -ENOENT) error = create_error; goto out; } if (error) { /* returned 1, that is */ if (WARN_ON(file->f_path.dentry == DENTRY_NOT_SET)) { error = -EIO; goto out; } if (file->f_path.dentry) { dput(dentry); dentry = file->f_path.dentry; } if (*opened & FILE_CREATED) fsnotify_create(dir, dentry); if (!dentry->d_inode) { WARN_ON(*opened & FILE_CREATED); if (create_error) { error = create_error; goto out; } } else { if (excl && !(*opened & FILE_CREATED)) { error = -EEXIST; goto out; } } goto looked_up; } /* * We didn't have the inode before the open, so check open permission * here. */ acc_mode = op->acc_mode; if (*opened & FILE_CREATED) { WARN_ON(!(open_flag & O_CREAT)); fsnotify_create(dir, dentry); acc_mode = MAY_OPEN; } error = may_open(&file->f_path, acc_mode, open_flag); if (error) fput(file); out: dput(dentry); return error; no_open: if (need_lookup) { dentry = lookup_real(dir, dentry, nd->flags); if (IS_ERR(dentry)) return PTR_ERR(dentry); if (create_error) { int open_flag = op->open_flag; error = create_error; if ((open_flag & O_EXCL)) { if (!dentry->d_inode) goto out; } else if (!dentry->d_inode) { goto out; } else if ((open_flag & O_TRUNC) && S_ISREG(dentry->d_inode->i_mode)) { goto out; } /* will fail later, go on to get the right error */ } } looked_up: path->dentry = dentry; path->mnt = nd->path.mnt; return 1; } /* * Look up and maybe create and open the last component. * * Must be called with i_mutex held on parent. * * Returns 0 if the file was successfully atomically created (if necessary) and * opened. In this case the file will be returned attached to @file. * * Returns 1 if the file was not completely opened at this time, though lookups * and creations will have been performed and the dentry returned in @path will * be positive upon return if O_CREAT was specified. If O_CREAT wasn't * specified then a negative dentry may be returned. * * An error code is returned otherwise. * * FILE_CREATE will be set in @*opened if the dentry was created and will be * cleared otherwise prior to returning. */ static int lookup_open(struct nameidata *nd, struct path *path, struct file *file, const struct open_flags *op, bool got_write, int *opened) { struct dentry *dir = nd->path.dentry; struct inode *dir_inode = dir->d_inode; struct dentry *dentry; int error; bool need_lookup; *opened &= ~FILE_CREATED; dentry = lookup_dcache(&nd->last, dir, nd->flags, &need_lookup); if (IS_ERR(dentry)) return PTR_ERR(dentry); /* Cached positive dentry: will open in f_op->open */ if (!need_lookup && dentry->d_inode) goto out_no_open; if ((nd->flags & LOOKUP_OPEN) && dir_inode->i_op->atomic_open) { return atomic_open(nd, dentry, path, file, op, got_write, need_lookup, opened); } if (need_lookup) { BUG_ON(dentry->d_inode); dentry = lookup_real(dir_inode, dentry, nd->flags); if (IS_ERR(dentry)) return PTR_ERR(dentry); } /* Negative dentry, just create the file */ if (!dentry->d_inode && (op->open_flag & O_CREAT)) { umode_t mode = op->mode; if (!IS_POSIXACL(dir->d_inode)) mode &= ~current_umask(); /* * This write is needed to ensure that a * rw->ro transition does not occur between * the time when the file is created and when * a permanent write count is taken through * the 'struct file' in finish_open(). */ if (!got_write) { error = -EROFS; goto out_dput; } *opened |= FILE_CREATED; error = security_path_mknod(&nd->path, dentry, mode, 0); if (error) goto out_dput; error = vfs_create(dir->d_inode, dentry, mode, nd->flags & LOOKUP_EXCL); if (error) goto out_dput; } out_no_open: path->dentry = dentry; path->mnt = nd->path.mnt; return 1; out_dput: dput(dentry); return error; } /* * Handle the last step of open() */ static int do_last(struct nameidata *nd, struct path *path, struct file *file, const struct open_flags *op, int *opened, struct filename *name) { struct dentry *dir = nd->path.dentry; int open_flag = op->open_flag; bool will_truncate = (open_flag & O_TRUNC) != 0; bool got_write = false; int acc_mode = op->acc_mode; struct inode *inode; bool symlink_ok = false; struct path save_parent = { .dentry = NULL, .mnt = NULL }; bool retried = false; int error; nd->flags &= ~LOOKUP_PARENT; nd->flags |= op->intent; if (nd->last_type != LAST_NORM) { error = handle_dots(nd, nd->last_type); if (error) return error; goto finish_open; } if (!(open_flag & O_CREAT)) { if (nd->last.name[nd->last.len]) nd->flags |= LOOKUP_FOLLOW | LOOKUP_DIRECTORY; if (open_flag & O_PATH && !(nd->flags & LOOKUP_FOLLOW)) symlink_ok = true; /* we _can_ be in RCU mode here */ error = lookup_fast(nd, path, &inode); if (likely(!error)) goto finish_lookup; if (error < 0) goto out; BUG_ON(nd->inode != dir->d_inode); } else { /* create side of things */ /* * This will *only* deal with leaving RCU mode - LOOKUP_JUMPED * has been cleared when we got to the last component we are * about to look up */ error = complete_walk(nd); if (error) return error; audit_inode(name, dir, LOOKUP_PARENT); error = -EISDIR; /* trailing slashes? */ if (nd->last.name[nd->last.len]) goto out; } retry_lookup: if (op->open_flag & (O_CREAT | O_TRUNC | O_WRONLY | O_RDWR)) { error = mnt_want_write(nd->path.mnt); if (!error) got_write = true; /* * do _not_ fail yet - we might not need that or fail with * a different error; let lookup_open() decide; we'll be * dropping this one anyway. */ } mutex_lock(&dir->d_inode->i_mutex); error = lookup_open(nd, path, file, op, got_write, opened); mutex_unlock(&dir->d_inode->i_mutex); if (error <= 0) { if (error) goto out; if ((*opened & FILE_CREATED) || !S_ISREG(file_inode(file)->i_mode)) will_truncate = false; audit_inode(name, file->f_path.dentry, 0); goto opened; } if (*opened & FILE_CREATED) { /* Don't check for write permission, don't truncate */ open_flag &= ~O_TRUNC; will_truncate = false; acc_mode = MAY_OPEN; path_to_nameidata(path, nd); goto finish_open_created; } /* * create/update audit record if it already exists. */ if (d_is_positive(path->dentry)) audit_inode(name, path->dentry, 0); /* * If atomic_open() acquired write access it is dropped now due to * possible mount and symlink following (this might be optimized away if * necessary...) */ if (got_write) { mnt_drop_write(nd->path.mnt); got_write = false; } error = -EEXIST; if ((open_flag & (O_EXCL | O_CREAT)) == (O_EXCL | O_CREAT)) goto exit_dput; error = follow_managed(path, nd->flags); if (error < 0) goto exit_dput; if (error) nd->flags |= LOOKUP_JUMPED; BUG_ON(nd->flags & LOOKUP_RCU); inode = path->dentry->d_inode; finish_lookup: /* we _can_ be in RCU mode here */ error = -ENOENT; if (!inode || d_is_negative(path->dentry)) { path_to_nameidata(path, nd); goto out; } if (should_follow_link(path->dentry, !symlink_ok)) { if (nd->flags & LOOKUP_RCU) { if (unlikely(unlazy_walk(nd, path->dentry))) { error = -ECHILD; goto out; } } BUG_ON(inode != path->dentry->d_inode); return 1; } if ((nd->flags & LOOKUP_RCU) || nd->path.mnt != path->mnt) { path_to_nameidata(path, nd); } else { save_parent.dentry = nd->path.dentry; save_parent.mnt = mntget(path->mnt); nd->path.dentry = path->dentry; } nd->inode = inode; /* Why this, you ask? _Now_ we might have grown LOOKUP_JUMPED... */ finish_open: error = complete_walk(nd); if (error) { path_put(&save_parent); return error; } audit_inode(name, nd->path.dentry, 0); error = -EISDIR; if ((open_flag & O_CREAT) && d_is_dir(nd->path.dentry)) goto out; error = -ENOTDIR; if ((nd->flags & LOOKUP_DIRECTORY) && !d_can_lookup(nd->path.dentry)) goto out; if (!S_ISREG(nd->inode->i_mode)) will_truncate = false; if (will_truncate) { error = mnt_want_write(nd->path.mnt); if (error) goto out; got_write = true; } finish_open_created: error = may_open(&nd->path, acc_mode, open_flag); if (error) goto out; file->f_path.mnt = nd->path.mnt; error = finish_open(file, nd->path.dentry, NULL, opened); if (error) { if (error == -EOPENSTALE) goto stale_open; goto out; } opened: error = open_check_o_direct(file); if (error) goto exit_fput; error = ima_file_check(file, op->acc_mode); if (error) goto exit_fput; if (will_truncate) { error = handle_truncate(file); if (error) goto exit_fput; } out: if (got_write) mnt_drop_write(nd->path.mnt); path_put(&save_parent); terminate_walk(nd); return error; exit_dput: path_put_conditional(path, nd); goto out; exit_fput: fput(file); goto out; stale_open: /* If no saved parent or already retried then can't retry */ if (!save_parent.dentry || retried) goto out; BUG_ON(save_parent.dentry != dir); path_put(&nd->path); nd->path = save_parent; nd->inode = dir->d_inode; save_parent.mnt = NULL; save_parent.dentry = NULL; if (got_write) { mnt_drop_write(nd->path.mnt); got_write = false; } retried = true; goto retry_lookup; } static int do_tmpfile(int dfd, struct filename *pathname, struct nameidata *nd, int flags, const struct open_flags *op, struct file *file, int *opened) { static const struct qstr name = QSTR_INIT("/", 1); struct dentry *dentry, *child; struct inode *dir; int error = path_lookupat(dfd, pathname->name, flags | LOOKUP_DIRECTORY, nd); if (unlikely(error)) return error; error = mnt_want_write(nd->path.mnt); if (unlikely(error)) goto out; /* we want directory to be writable */ error = inode_permission(nd->inode, MAY_WRITE | MAY_EXEC); if (error) goto out2; dentry = nd->path.dentry; dir = dentry->d_inode; if (!dir->i_op->tmpfile) { error = -EOPNOTSUPP; goto out2; } child = d_alloc(dentry, &name); if (unlikely(!child)) { error = -ENOMEM; goto out2; } nd->flags &= ~LOOKUP_DIRECTORY; nd->flags |= op->intent; dput(nd->path.dentry); nd->path.dentry = child; error = dir->i_op->tmpfile(dir, nd->path.dentry, op->mode); if (error) goto out2; audit_inode(pathname, nd->path.dentry, 0); error = may_open(&nd->path, op->acc_mode, op->open_flag); if (error) goto out2; file->f_path.mnt = nd->path.mnt; error = finish_open(file, nd->path.dentry, NULL, opened); if (error) goto out2; error = open_check_o_direct(file); if (error) { fput(file); } else if (!(op->open_flag & O_EXCL)) { struct inode *inode = file_inode(file); spin_lock(&inode->i_lock); inode->i_state |= I_LINKABLE; spin_unlock(&inode->i_lock); } out2: mnt_drop_write(nd->path.mnt); out: path_put(&nd->path); return error; } 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; } struct file *do_filp_open(int dfd, struct filename *pathname, const struct open_flags *op) { struct nameidata nd; int flags = op->lookup_flags; struct file *filp; filp = path_openat(dfd, pathname, &nd, op, flags | LOOKUP_RCU); if (unlikely(filp == ERR_PTR(-ECHILD))) filp = path_openat(dfd, pathname, &nd, op, flags); if (unlikely(filp == ERR_PTR(-ESTALE))) filp = path_openat(dfd, pathname, &nd, op, flags | LOOKUP_REVAL); return filp; } struct file *do_file_open_root(struct dentry *dentry, struct vfsmount *mnt, const char *name, const struct open_flags *op) { struct nameidata nd; struct file *file; struct filename filename = { .name = name }; int flags = op->lookup_flags | LOOKUP_ROOT; nd.root.mnt = mnt; nd.root.dentry = dentry; if (d_is_symlink(dentry) && op->intent & LOOKUP_OPEN) return ERR_PTR(-ELOOP); file = path_openat(-1, &filename, &nd, op, flags | LOOKUP_RCU); if (unlikely(file == ERR_PTR(-ECHILD))) file = path_openat(-1, &filename, &nd, op, flags); if (unlikely(file == ERR_PTR(-ESTALE))) file = path_openat(-1, &filename, &nd, op, flags | LOOKUP_REVAL); return file; } struct dentry *kern_path_create(int dfd, const char *pathname, struct path *path, unsigned int lookup_flags) { struct dentry *dentry = ERR_PTR(-EEXIST); struct nameidata nd; int err2; int error; bool is_dir = (lookup_flags & LOOKUP_DIRECTORY); /* * Note that only LOOKUP_REVAL and LOOKUP_DIRECTORY matter here. Any * other flags passed in are ignored! */ lookup_flags &= LOOKUP_REVAL; error = do_path_lookup(dfd, pathname, LOOKUP_PARENT|lookup_flags, &nd); if (error) return ERR_PTR(error); /* * Yucky last component or no last component at all? * (foo/., foo/.., /////) */ if (nd.last_type != LAST_NORM) goto out; nd.flags &= ~LOOKUP_PARENT; nd.flags |= LOOKUP_CREATE | LOOKUP_EXCL; /* don't fail immediately if it's r/o, at least try to report other errors */ err2 = mnt_want_write(nd.path.mnt); /* * Do the final lookup. */ mutex_lock_nested(&nd.path.dentry->d_inode->i_mutex, I_MUTEX_PARENT); dentry = lookup_hash(&nd); if (IS_ERR(dentry)) goto unlock; error = -EEXIST; if (d_is_positive(dentry)) goto fail; /* * Special case - lookup gave negative, but... we had foo/bar/ * From the vfs_mknod() POV we just have a negative dentry - * all is fine. Let's be bastards - you had / on the end, you've * been asking for (non-existent) directory. -ENOENT for you. */ if (unlikely(!is_dir && nd.last.name[nd.last.len])) { error = -ENOENT; goto fail; } if (unlikely(err2)) { error = err2; goto fail; } *path = nd.path; return dentry; fail: dput(dentry); dentry = ERR_PTR(error); unlock: mutex_unlock(&nd.path.dentry->d_inode->i_mutex); if (!err2) mnt_drop_write(nd.path.mnt); out: path_put(&nd.path); return dentry; } EXPORT_SYMBOL(kern_path_create); void done_path_create(struct path *path, struct dentry *dentry) { dput(dentry); mutex_unlock(&path->dentry->d_inode->i_mutex); mnt_drop_write(path->mnt); path_put(path); } EXPORT_SYMBOL(done_path_create); struct dentry *user_path_create(int dfd, const char __user *pathname, struct path *path, unsigned int lookup_flags) { struct filename *tmp = getname(pathname); struct dentry *res; if (IS_ERR(tmp)) return ERR_CAST(tmp); res = kern_path_create(dfd, tmp->name, path, lookup_flags); putname(tmp); return res; } EXPORT_SYMBOL(user_path_create); int vfs_mknod(struct inode *dir, struct dentry *dentry, umode_t mode, dev_t dev) { int error = may_create(dir, dentry); if (error) return error; if ((S_ISCHR(mode) || S_ISBLK(mode)) && !capable(CAP_MKNOD)) return -EPERM; if (!dir->i_op->mknod) return -EPERM; error = devcgroup_inode_mknod(mode, dev); if (error) return error; error = security_inode_mknod(dir, dentry, mode, dev); if (error) return error; error = dir->i_op->mknod(dir, dentry, mode, dev); if (!error) fsnotify_create(dir, dentry); return error; } EXPORT_SYMBOL(vfs_mknod); static int may_mknod(umode_t mode) { switch (mode & S_IFMT) { case S_IFREG: case S_IFCHR: case S_IFBLK: case S_IFIFO: case S_IFSOCK: case 0: /* zero mode translates to S_IFREG */ return 0; case S_IFDIR: return -EPERM; default: return -EINVAL; } } SYSCALL_DEFINE4(mknodat, int, dfd, const char __user *, filename, umode_t, mode, unsigned, dev) { struct dentry *dentry; struct path path; int error; unsigned int lookup_flags = 0; error = may_mknod(mode); if (error) return error; retry: dentry = user_path_create(dfd, filename, &path, lookup_flags); if (IS_ERR(dentry)) return PTR_ERR(dentry); if (!IS_POSIXACL(path.dentry->d_inode)) mode &= ~current_umask(); error = security_path_mknod(&path, dentry, mode, dev); if (error) goto out; switch (mode & S_IFMT) { case 0: case S_IFREG: error = vfs_create(path.dentry->d_inode,dentry,mode,true); break; case S_IFCHR: case S_IFBLK: error = vfs_mknod(path.dentry->d_inode,dentry,mode, new_decode_dev(dev)); break; case S_IFIFO: case S_IFSOCK: error = vfs_mknod(path.dentry->d_inode,dentry,mode,0); break; } out: done_path_create(&path, dentry); if (retry_estale(error, lookup_flags)) { lookup_flags |= LOOKUP_REVAL; goto retry; } return error; } SYSCALL_DEFINE3(mknod, const char __user *, filename, umode_t, mode, unsigned, dev) { return sys_mknodat(AT_FDCWD, filename, mode, dev); } int vfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode) { int error = may_create(dir, dentry); unsigned max_links = dir->i_sb->s_max_links; if (error) return error; if (!dir->i_op->mkdir) return -EPERM; mode &= (S_IRWXUGO|S_ISVTX); error = security_inode_mkdir(dir, dentry, mode); if (error) return error; if (max_links && dir->i_nlink >= max_links) return -EMLINK; error = dir->i_op->mkdir(dir, dentry, mode); if (!error) fsnotify_mkdir(dir, dentry); return error; } EXPORT_SYMBOL(vfs_mkdir); SYSCALL_DEFINE3(mkdirat, int, dfd, const char __user *, pathname, umode_t, mode) { struct dentry *dentry; struct path path; int error; unsigned int lookup_flags = LOOKUP_DIRECTORY; retry: dentry = user_path_create(dfd, pathname, &path, lookup_flags); if (IS_ERR(dentry)) return PTR_ERR(dentry); if (!IS_POSIXACL(path.dentry->d_inode)) mode &= ~current_umask(); error = security_path_mkdir(&path, dentry, mode); if (!error) error = vfs_mkdir(path.dentry->d_inode, dentry, mode); done_path_create(&path, dentry); if (retry_estale(error, lookup_flags)) { lookup_flags |= LOOKUP_REVAL; goto retry; } return error; } SYSCALL_DEFINE2(mkdir, const char __user *, pathname, umode_t, mode) { return sys_mkdirat(AT_FDCWD, pathname, mode); } /* * The dentry_unhash() helper will try to drop the dentry early: we * should have a usage count of 1 if we're the only user of this * dentry, and if that is true (possibly after pruning the dcache), * then we drop the dentry now. * * A low-level filesystem can, if it choses, legally * do a * * if (!d_unhashed(dentry)) * return -EBUSY; * * if it cannot handle the case of removing a directory * that is still in use by something else.. */ void dentry_unhash(struct dentry *dentry) { shrink_dcache_parent(dentry); spin_lock(&dentry->d_lock); if (dentry->d_lockref.count == 1) __d_drop(dentry); spin_unlock(&dentry->d_lock); } EXPORT_SYMBOL(dentry_unhash); int vfs_rmdir(struct inode *dir, struct dentry *dentry) { int error = may_delete(dir, dentry, 1); if (error) return error; if (!dir->i_op->rmdir) return -EPERM; dget(dentry); mutex_lock(&dentry->d_inode->i_mutex); error = -EBUSY; if (d_mountpoint(dentry)) goto out; error = security_inode_rmdir(dir, dentry); if (error) goto out; shrink_dcache_parent(dentry); error = dir->i_op->rmdir(dir, dentry); if (error) goto out; dentry->d_inode->i_flags |= S_DEAD; dont_mount(dentry); out: mutex_unlock(&dentry->d_inode->i_mutex); dput(dentry); if (!error) d_delete(dentry); return error; } EXPORT_SYMBOL(vfs_rmdir); static long do_rmdir(int dfd, const char __user *pathname) { int error = 0; struct filename *name; struct dentry *dentry; struct nameidata nd; unsigned int lookup_flags = 0; retry: name = user_path_parent(dfd, pathname, &nd, lookup_flags); if (IS_ERR(name)) return PTR_ERR(name); switch(nd.last_type) { case LAST_DOTDOT: error = -ENOTEMPTY; goto exit1; case LAST_DOT: error = -EINVAL; goto exit1; case LAST_ROOT: error = -EBUSY; goto exit1; } nd.flags &= ~LOOKUP_PARENT; error = mnt_want_write(nd.path.mnt); if (error) goto exit1; mutex_lock_nested(&nd.path.dentry->d_inode->i_mutex, I_MUTEX_PARENT); dentry = lookup_hash(&nd); error = PTR_ERR(dentry); if (IS_ERR(dentry)) goto exit2; if (!dentry->d_inode) { error = -ENOENT; goto exit3; } error = security_path_rmdir(&nd.path, dentry); if (error) goto exit3; error = vfs_rmdir(nd.path.dentry->d_inode, dentry); exit3: dput(dentry); exit2: mutex_unlock(&nd.path.dentry->d_inode->i_mutex); mnt_drop_write(nd.path.mnt); exit1: path_put(&nd.path); putname(name); if (retry_estale(error, lookup_flags)) { lookup_flags |= LOOKUP_REVAL; goto retry; } return error; } SYSCALL_DEFINE1(rmdir, const char __user *, pathname) { return do_rmdir(AT_FDCWD, pathname); } /** * vfs_unlink - unlink a filesystem object * @dir: parent directory * @dentry: victim * @delegated_inode: returns victim inode, if the inode is delegated. * * The caller must hold dir->i_mutex. * * If vfs_unlink discovers a delegation, it will return -EWOULDBLOCK and * return a reference to the inode in delegated_inode. The caller * should then break the delegation on that inode and retry. Because * breaking a delegation may take a long time, the caller should drop * dir->i_mutex before doing so. * * Alternatively, a caller may pass NULL for delegated_inode. This may * be appropriate for callers that expect the underlying filesystem not * to be NFS exported. */ int vfs_unlink(struct inode *dir, struct dentry *dentry, struct inode **delegated_inode) { struct inode *target = dentry->d_inode; int error = may_delete(dir, dentry, 0); if (error) return error; if (!dir->i_op->unlink) return -EPERM; mutex_lock(&target->i_mutex); if (d_mountpoint(dentry)) error = -EBUSY; else { error = security_inode_unlink(dir, dentry); if (!error) { error = try_break_deleg(target, delegated_inode); if (error) goto out; error = dir->i_op->unlink(dir, dentry); if (!error) dont_mount(dentry); } } out: mutex_unlock(&target->i_mutex); /* We don't d_delete() NFS sillyrenamed files--they still exist. */ if (!error && !(dentry->d_flags & DCACHE_NFSFS_RENAMED)) { fsnotify_link_count(target); d_delete(dentry); } return error; } EXPORT_SYMBOL(vfs_unlink); /* * Make sure that the actual truncation of the file will occur outside its * directory's i_mutex. Truncate can take a long time if there is a lot of * writeout happening, and we don't want to prevent access to the directory * while waiting on the I/O. */ static long do_unlinkat(int dfd, const char __user *pathname) { int error; struct filename *name; struct dentry *dentry; struct nameidata nd; struct inode *inode = NULL; struct inode *delegated_inode = NULL; unsigned int lookup_flags = 0; retry: name = user_path_parent(dfd, pathname, &nd, lookup_flags); if (IS_ERR(name)) return PTR_ERR(name); error = -EISDIR; if (nd.last_type != LAST_NORM) goto exit1; nd.flags &= ~LOOKUP_PARENT; error = mnt_want_write(nd.path.mnt); if (error) goto exit1; retry_deleg: mutex_lock_nested(&nd.path.dentry->d_inode->i_mutex, I_MUTEX_PARENT); dentry = lookup_hash(&nd); error = PTR_ERR(dentry); if (!IS_ERR(dentry)) { /* Why not before? Because we want correct error value */ if (nd.last.name[nd.last.len]) goto slashes; inode = dentry->d_inode; if (d_is_negative(dentry)) goto slashes; ihold(inode); error = security_path_unlink(&nd.path, dentry); if (error) goto exit2; error = vfs_unlink(nd.path.dentry->d_inode, dentry, &delegated_inode); exit2: dput(dentry); } mutex_unlock(&nd.path.dentry->d_inode->i_mutex); if (inode) iput(inode); /* truncate the inode here */ inode = NULL; if (delegated_inode) { error = break_deleg_wait(&delegated_inode); if (!error) goto retry_deleg; } mnt_drop_write(nd.path.mnt); exit1: path_put(&nd.path); putname(name); if (retry_estale(error, lookup_flags)) { lookup_flags |= LOOKUP_REVAL; inode = NULL; goto retry; } return error; slashes: if (d_is_negative(dentry)) error = -ENOENT; else if (d_is_dir(dentry)) error = -EISDIR; else error = -ENOTDIR; goto exit2; } SYSCALL_DEFINE3(unlinkat, int, dfd, const char __user *, pathname, int, flag) { if ((flag & ~AT_REMOVEDIR) != 0) return -EINVAL; if (flag & AT_REMOVEDIR) return do_rmdir(dfd, pathname); return do_unlinkat(dfd, pathname); } SYSCALL_DEFINE1(unlink, const char __user *, pathname) { return do_unlinkat(AT_FDCWD, pathname); } int vfs_symlink(struct inode *dir, struct dentry *dentry, const char *oldname) { int error = may_create(dir, dentry); if (error) return error; if (!dir->i_op->symlink) return -EPERM; error = security_inode_symlink(dir, dentry, oldname); if (error) return error; error = dir->i_op->symlink(dir, dentry, oldname); if (!error) fsnotify_create(dir, dentry); return error; } EXPORT_SYMBOL(vfs_symlink); SYSCALL_DEFINE3(symlinkat, const char __user *, oldname, int, newdfd, const char __user *, newname) { int error; struct filename *from; struct dentry *dentry; struct path path; unsigned int lookup_flags = 0; from = getname(oldname); if (IS_ERR(from)) return PTR_ERR(from); retry: dentry = user_path_create(newdfd, newname, &path, lookup_flags); error = PTR_ERR(dentry); if (IS_ERR(dentry)) goto out_putname; error = security_path_symlink(&path, dentry, from->name); if (!error) error = vfs_symlink(path.dentry->d_inode, dentry, from->name); done_path_create(&path, dentry); if (retry_estale(error, lookup_flags)) { lookup_flags |= LOOKUP_REVAL; goto retry; } out_putname: putname(from); return error; } SYSCALL_DEFINE2(symlink, const char __user *, oldname, const char __user *, newname) { return sys_symlinkat(oldname, AT_FDCWD, newname); } /** * vfs_link - create a new link * @old_dentry: object to be linked * @dir: new parent * @new_dentry: where to create the new link * @delegated_inode: returns inode needing a delegation break * * The caller must hold dir->i_mutex * * If vfs_link discovers a delegation on the to-be-linked file in need * of breaking, it will return -EWOULDBLOCK and return a reference to the * inode in delegated_inode. The caller should then break the delegation * and retry. Because breaking a delegation may take a long time, the * caller should drop the i_mutex before doing so. * * Alternatively, a caller may pass NULL for delegated_inode. This may * be appropriate for callers that expect the underlying filesystem not * to be NFS exported. */ int vfs_link(struct dentry *old_dentry, struct inode *dir, struct dentry *new_dentry, struct inode **delegated_inode) { struct inode *inode = old_dentry->d_inode; unsigned max_links = dir->i_sb->s_max_links; int error; if (!inode) return -ENOENT; error = may_create(dir, new_dentry); if (error) return error; if (dir->i_sb != inode->i_sb) return -EXDEV; /* * A link to an append-only or immutable file cannot be created. */ if (IS_APPEND(inode) || IS_IMMUTABLE(inode)) return -EPERM; if (!dir->i_op->link) return -EPERM; if (S_ISDIR(inode->i_mode)) return -EPERM; error = security_inode_link(old_dentry, dir, new_dentry); if (error) return error; mutex_lock(&inode->i_mutex); /* Make sure we don't allow creating hardlink to an unlinked file */ if (inode->i_nlink == 0 && !(inode->i_state & I_LINKABLE)) error = -ENOENT; else if (max_links && inode->i_nlink >= max_links) error = -EMLINK; else { error = try_break_deleg(inode, delegated_inode); if (!error) error = dir->i_op->link(old_dentry, dir, new_dentry); } if (!error && (inode->i_state & I_LINKABLE)) { spin_lock(&inode->i_lock); inode->i_state &= ~I_LINKABLE; spin_unlock(&inode->i_lock); } mutex_unlock(&inode->i_mutex); if (!error) fsnotify_link(dir, inode, new_dentry); return error; } EXPORT_SYMBOL(vfs_link); /* * Hardlinks are often used in delicate situations. We avoid * security-related surprises by not following symlinks on the * newname. --KAB * * We don't follow them on the oldname either to be compatible * with linux 2.0, and to avoid hard-linking to directories * and other special files. --ADM */ SYSCALL_DEFINE5(linkat, int, olddfd, const char __user *, oldname, int, newdfd, const char __user *, newname, int, flags) { struct dentry *new_dentry; struct path old_path, new_path; struct inode *delegated_inode = NULL; int how = 0; int error; if ((flags & ~(AT_SYMLINK_FOLLOW | AT_EMPTY_PATH)) != 0) return -EINVAL; /* * To use null names we require CAP_DAC_READ_SEARCH * This ensures that not everyone will be able to create * handlink using the passed filedescriptor. */ if (flags & AT_EMPTY_PATH) { if (!capable(CAP_DAC_READ_SEARCH)) return -ENOENT; how = LOOKUP_EMPTY; } if (flags & AT_SYMLINK_FOLLOW) how |= LOOKUP_FOLLOW; retry: error = user_path_at(olddfd, oldname, how, &old_path); if (error) return error; new_dentry = user_path_create(newdfd, newname, &new_path, (how & LOOKUP_REVAL)); error = PTR_ERR(new_dentry); if (IS_ERR(new_dentry)) goto out; error = -EXDEV; if (old_path.mnt != new_path.mnt) goto out_dput; error = may_linkat(&old_path); if (unlikely(error)) goto out_dput; error = security_path_link(old_path.dentry, &new_path, new_dentry); if (error) goto out_dput; error = vfs_link(old_path.dentry, new_path.dentry->d_inode, new_dentry, &delegated_inode); out_dput: done_path_create(&new_path, new_dentry); if (delegated_inode) { error = break_deleg_wait(&delegated_inode); if (!error) { path_put(&old_path); goto retry; } } if (retry_estale(error, how)) { path_put(&old_path); how |= LOOKUP_REVAL; goto retry; } out: path_put(&old_path); return error; } SYSCALL_DEFINE2(link, const char __user *, oldname, const char __user *, newname) { return sys_linkat(AT_FDCWD, oldname, AT_FDCWD, newname, 0); } /** * vfs_rename - rename a filesystem object * @old_dir: parent of source * @old_dentry: source * @new_dir: parent of destination * @new_dentry: destination * @delegated_inode: returns an inode needing a delegation break * @flags: rename flags * * The caller must hold multiple mutexes--see lock_rename()). * * If vfs_rename discovers a delegation in need of breaking at either * the source or destination, it will return -EWOULDBLOCK and return a * reference to the inode in delegated_inode. The caller should then * break the delegation and retry. Because breaking a delegation may * take a long time, the caller should drop all locks before doing * so. * * Alternatively, a caller may pass NULL for delegated_inode. This may * be appropriate for callers that expect the underlying filesystem not * to be NFS exported. * * The worst of all namespace operations - renaming directory. "Perverted" * doesn't even start to describe it. Somebody in UCB had a heck of a trip... * Problems: * a) we can get into loop creation. Check is done in is_subdir(). * b) race potential - two innocent renames can create a loop together. * That's where 4.4 screws up. Current fix: serialization on * sb->s_vfs_rename_mutex. We might be more accurate, but that's another * story. * c) we have to lock _four_ objects - parents and victim (if it exists), * and source (if it is not a directory). * And that - after we got ->i_mutex on parents (until then we don't know * whether the target exists). Solution: try to be smart with locking * order for inodes. We rely on the fact that tree topology may change * only under ->s_vfs_rename_mutex _and_ that parent of the object we * move will be locked. Thus we can rank directories by the tree * (ancestors first) and rank all non-directories after them. * That works since everybody except rename does "lock parent, lookup, * lock child" and rename is under ->s_vfs_rename_mutex. * HOWEVER, it relies on the assumption that any object with ->lookup() * has no more than 1 dentry. If "hybrid" objects will ever appear, * we'd better make sure that there's no link(2) for them. * d) conversion from fhandle to dentry may come in the wrong moment - when * we are removing the target. Solution: we will have to grab ->i_mutex * in the fhandle_to_dentry code. [FIXME - current nfsfh.c relies on * ->i_mutex on parents, which works but leads to some truly excessive * locking]. */ int vfs_rename(struct inode *old_dir, struct dentry *old_dentry, struct inode *new_dir, struct dentry *new_dentry, struct inode **delegated_inode, unsigned int flags) { int error; bool is_dir = d_is_dir(old_dentry); const unsigned char *old_name; struct inode *source = old_dentry->d_inode; struct inode *target = new_dentry->d_inode; bool new_is_dir = false; unsigned max_links = new_dir->i_sb->s_max_links; if (source == target) return 0; error = may_delete(old_dir, old_dentry, is_dir); if (error) return error; if (!target) { error = may_create(new_dir, new_dentry); } else { new_is_dir = d_is_dir(new_dentry); if (!(flags & RENAME_EXCHANGE)) error = may_delete(new_dir, new_dentry, is_dir); else error = may_delete(new_dir, new_dentry, new_is_dir); } if (error) return error; if (!old_dir->i_op->rename) return -EPERM; if (flags && !old_dir->i_op->rename2) return -EINVAL; /* * If we are going to change the parent - check write permissions, * we'll need to flip '..'. */ if (new_dir != old_dir) { if (is_dir) { error = inode_permission(source, MAY_WRITE); if (error) return error; } if ((flags & RENAME_EXCHANGE) && new_is_dir) { error = inode_permission(target, MAY_WRITE); if (error) return error; } } error = security_inode_rename(old_dir, old_dentry, new_dir, new_dentry, flags); if (error) return error; old_name = fsnotify_oldname_init(old_dentry->d_name.name); dget(new_dentry); if (!is_dir || (flags & RENAME_EXCHANGE)) lock_two_nondirectories(source, target); else if (target) mutex_lock(&target->i_mutex); error = -EBUSY; if (d_mountpoint(old_dentry) || d_mountpoint(new_dentry)) goto out; if (max_links && new_dir != old_dir) { error = -EMLINK; if (is_dir && !new_is_dir && new_dir->i_nlink >= max_links) goto out; if ((flags & RENAME_EXCHANGE) && !is_dir && new_is_dir && old_dir->i_nlink >= max_links) goto out; } if (is_dir && !(flags & RENAME_EXCHANGE) && target) shrink_dcache_parent(new_dentry); if (!is_dir) { error = try_break_deleg(source, delegated_inode); if (error) goto out; } if (target && !new_is_dir) { error = try_break_deleg(target, delegated_inode); if (error) goto out; } if (!flags) { error = old_dir->i_op->rename(old_dir, old_dentry, new_dir, new_dentry); } else { error = old_dir->i_op->rename2(old_dir, old_dentry, new_dir, new_dentry, flags); } if (error) goto out; if (!(flags & RENAME_EXCHANGE) && target) { if (is_dir) target->i_flags |= S_DEAD; dont_mount(new_dentry); } if (!(old_dir->i_sb->s_type->fs_flags & FS_RENAME_DOES_D_MOVE)) { if (!(flags & RENAME_EXCHANGE)) d_move(old_dentry, new_dentry); else d_exchange(old_dentry, new_dentry); } out: if (!is_dir || (flags & RENAME_EXCHANGE)) unlock_two_nondirectories(source, target); else if (target) mutex_unlock(&target->i_mutex); dput(new_dentry); if (!error) { fsnotify_move(old_dir, new_dir, old_name, is_dir, !(flags & RENAME_EXCHANGE) ? target : NULL, old_dentry); if (flags & RENAME_EXCHANGE) { fsnotify_move(new_dir, old_dir, old_dentry->d_name.name, new_is_dir, NULL, new_dentry); } } fsnotify_oldname_free(old_name); return error; } EXPORT_SYMBOL(vfs_rename); SYSCALL_DEFINE5(renameat2, int, olddfd, const char __user *, oldname, int, newdfd, const char __user *, newname, unsigned int, flags) { struct dentry *old_dir, *new_dir; struct dentry *old_dentry, *new_dentry; struct dentry *trap; struct nameidata oldnd, newnd; struct inode *delegated_inode = NULL; struct filename *from; struct filename *to; unsigned int lookup_flags = 0; bool should_retry = false; int error; if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE)) return -EINVAL; if ((flags & RENAME_NOREPLACE) && (flags & RENAME_EXCHANGE)) return -EINVAL; retry: from = user_path_parent(olddfd, oldname, &oldnd, lookup_flags); if (IS_ERR(from)) { error = PTR_ERR(from); goto exit; } to = user_path_parent(newdfd, newname, &newnd, lookup_flags); if (IS_ERR(to)) { error = PTR_ERR(to); goto exit1; } error = -EXDEV; if (oldnd.path.mnt != newnd.path.mnt) goto exit2; old_dir = oldnd.path.dentry; error = -EBUSY; if (oldnd.last_type != LAST_NORM) goto exit2; new_dir = newnd.path.dentry; if (flags & RENAME_NOREPLACE) error = -EEXIST; if (newnd.last_type != LAST_NORM) goto exit2; error = mnt_want_write(oldnd.path.mnt); if (error) goto exit2; oldnd.flags &= ~LOOKUP_PARENT; newnd.flags &= ~LOOKUP_PARENT; if (!(flags & RENAME_EXCHANGE)) newnd.flags |= LOOKUP_RENAME_TARGET; retry_deleg: trap = lock_rename(new_dir, old_dir); old_dentry = lookup_hash(&oldnd); error = PTR_ERR(old_dentry); if (IS_ERR(old_dentry)) goto exit3; /* source must exist */ error = -ENOENT; if (d_is_negative(old_dentry)) goto exit4; new_dentry = lookup_hash(&newnd); error = PTR_ERR(new_dentry); if (IS_ERR(new_dentry)) goto exit4; error = -EEXIST; if ((flags & RENAME_NOREPLACE) && d_is_positive(new_dentry)) goto exit5; if (flags & RENAME_EXCHANGE) { error = -ENOENT; if (d_is_negative(new_dentry)) goto exit5; if (!d_is_dir(new_dentry)) { error = -ENOTDIR; if (newnd.last.name[newnd.last.len]) goto exit5; } } /* unless the source is a directory trailing slashes give -ENOTDIR */ if (!d_is_dir(old_dentry)) { error = -ENOTDIR; if (oldnd.last.name[oldnd.last.len]) goto exit5; if (!(flags & RENAME_EXCHANGE) && newnd.last.name[newnd.last.len]) goto exit5; } /* source should not be ancestor of target */ error = -EINVAL; if (old_dentry == trap) goto exit5; /* target should not be an ancestor of source */ if (!(flags & RENAME_EXCHANGE)) error = -ENOTEMPTY; if (new_dentry == trap) goto exit5; error = security_path_rename(&oldnd.path, old_dentry, &newnd.path, new_dentry, flags); if (error) goto exit5; error = vfs_rename(old_dir->d_inode, old_dentry, new_dir->d_inode, new_dentry, &delegated_inode, flags); exit5: dput(new_dentry); exit4: dput(old_dentry); exit3: unlock_rename(new_dir, old_dir); if (delegated_inode) { error = break_deleg_wait(&delegated_inode); if (!error) goto retry_deleg; } mnt_drop_write(oldnd.path.mnt); exit2: if (retry_estale(error, lookup_flags)) should_retry = true; path_put(&newnd.path); putname(to); exit1: path_put(&oldnd.path); putname(from); if (should_retry) { should_retry = false; lookup_flags |= LOOKUP_REVAL; goto retry; } exit: return error; } SYSCALL_DEFINE4(renameat, int, olddfd, const char __user *, oldname, int, newdfd, const char __user *, newname) { return sys_renameat2(olddfd, oldname, newdfd, newname, 0); } SYSCALL_DEFINE2(rename, const char __user *, oldname, const char __user *, newname) { return sys_renameat2(AT_FDCWD, oldname, AT_FDCWD, newname, 0); } int readlink_copy(char __user *buffer, int buflen, const char *link) { int len = PTR_ERR(link); if (IS_ERR(link)) goto out; len = strlen(link); if (len > (unsigned) buflen) len = buflen; if (copy_to_user(buffer, link, len)) len = -EFAULT; out: return len; } EXPORT_SYMBOL(readlink_copy); /* * A helper for ->readlink(). This should be used *ONLY* for symlinks that * have ->follow_link() touching nd only in nd_set_link(). Using (or not * using) it for any given inode is up to filesystem. */ int generic_readlink(struct dentry *dentry, char __user *buffer, int buflen) { struct nameidata nd; void *cookie; int res; nd.depth = 0; cookie = dentry->d_inode->i_op->follow_link(dentry, &nd); if (IS_ERR(cookie)) return PTR_ERR(cookie); res = readlink_copy(buffer, buflen, nd_get_link(&nd)); if (dentry->d_inode->i_op->put_link) dentry->d_inode->i_op->put_link(dentry, &nd, cookie); return res; } EXPORT_SYMBOL(generic_readlink); /* get the link contents into pagecache */ static char *page_getlink(struct dentry * dentry, struct page **ppage) { char *kaddr; struct page *page; struct address_space *mapping = dentry->d_inode->i_mapping; page = read_mapping_page(mapping, 0, NULL); if (IS_ERR(page)) return (char*)page; *ppage = page; kaddr = kmap(page); nd_terminate_link(kaddr, dentry->d_inode->i_size, PAGE_SIZE - 1); return kaddr; } int page_readlink(struct dentry *dentry, char __user *buffer, int buflen) { struct page *page = NULL; int res = readlink_copy(buffer, buflen, page_getlink(dentry, &page)); if (page) { kunmap(page); page_cache_release(page); } return res; } EXPORT_SYMBOL(page_readlink); void *page_follow_link_light(struct dentry *dentry, struct nameidata *nd) { struct page *page = NULL; nd_set_link(nd, page_getlink(dentry, &page)); return page; } EXPORT_SYMBOL(page_follow_link_light); void page_put_link(struct dentry *dentry, struct nameidata *nd, void *cookie) { struct page *page = cookie; if (page) { kunmap(page); page_cache_release(page); } } EXPORT_SYMBOL(page_put_link); /* * The nofs argument instructs pagecache_write_begin to pass AOP_FLAG_NOFS */ int __page_symlink(struct inode *inode, const char *symname, int len, int nofs) { struct address_space *mapping = inode->i_mapping; struct page *page; void *fsdata; int err; char *kaddr; unsigned int flags = AOP_FLAG_UNINTERRUPTIBLE; if (nofs) flags |= AOP_FLAG_NOFS; retry: err = pagecache_write_begin(NULL, mapping, 0, len-1, flags, &page, &fsdata); if (err) goto fail; kaddr = kmap_atomic(page); memcpy(kaddr, symname, len-1); kunmap_atomic(kaddr); err = pagecache_write_end(NULL, mapping, 0, len-1, len-1, page, fsdata); if (err < 0) goto fail; if (err < len-1) goto retry; mark_inode_dirty(inode); return 0; fail: return err; } EXPORT_SYMBOL(__page_symlink); int page_symlink(struct inode *inode, const char *symname, int len) { return __page_symlink(inode, symname, len, !(mapping_gfp_mask(inode->i_mapping) & __GFP_FS)); } EXPORT_SYMBOL(page_symlink); const struct inode_operations page_symlink_inode_operations = { .readlink = generic_readlink, .follow_link = page_follow_link_light, .put_link = page_put_link, }; EXPORT_SYMBOL(page_symlink_inode_operations);
./CrossVul/dataset_final_sorted/CWE-59/c/good_2241_0
crossvul-cpp_data_good_589_5
/* $Id: rc.c,v 1.116 2010/08/20 09:47:09 htrb Exp $ */ /* * Initialization file etc. */ #include "fm.h" #include "myctype.h" #include "proto.h" #include <stdio.h> #include <errno.h> #include "parsetag.h" #include "local.h" #include "regex.h" #include <stdlib.h> #include <stddef.h> struct param_ptr { char *name; int type; int inputtype; void *varptr; char *comment; void *select; }; struct param_section { char *name; struct param_ptr *params; }; struct rc_search_table { struct param_ptr *param; short uniq_pos; }; static struct rc_search_table *RC_search_table; static int RC_table_size; #define P_INT 0 #define P_SHORT 1 #define P_CHARINT 2 #define P_CHAR 3 #define P_STRING 4 #if defined(USE_SSL) && defined(USE_SSL_VERIFY) #define P_SSLPATH 5 #endif #ifdef USE_COLOR #define P_COLOR 6 #endif #ifdef USE_M17N #define P_CODE 7 #endif #define P_PIXELS 8 #define P_NZINT 9 #define P_SCALE 10 /* FIXME: gettextize here */ #ifdef USE_M17N static wc_ces OptionCharset = WC_CES_US_ASCII; /* FIXME: charset of source code */ static int OptionEncode = FALSE; #endif #define CMT_HELPER N_("External Viewer Setup") #define CMT_TABSTOP N_("Tab width in characters") #define CMT_INDENT_INCR N_("Indent for HTML rendering") #define CMT_PIXEL_PER_CHAR N_("Number of pixels per character (4.0...32.0)") #define CMT_PIXEL_PER_LINE N_("Number of pixels per line (4.0...64.0)") #define CMT_PAGERLINE N_("Number of remembered lines when used as a pager") #define CMT_HISTORY N_("Use URL history") #define CMT_HISTSIZE N_("Number of remembered URL") #define CMT_SAVEHIST N_("Save URL history") #define CMT_FRAME N_("Render frames automatically") #define CMT_ARGV_IS_URL N_("Treat argument without scheme as URL") #define CMT_TSELF N_("Use _self as default target") #define CMT_OPEN_TAB_BLANK N_("Open link on new tab if target is _blank or _new") #define CMT_OPEN_TAB_DL_LIST N_("Open download list panel on new tab") #define CMT_DISPLINK N_("Display link URL automatically") #define CMT_DISPLINKNUMBER N_("Display link numbers") #define CMT_DECODE_URL N_("Display decoded URL") #define CMT_DISPLINEINFO N_("Display current line number") #define CMT_DISP_IMAGE N_("Display inline images") #define CMT_PSEUDO_INLINES N_("Display pseudo-ALTs for inline images with no ALT or TITLE string") #ifdef USE_IMAGE #define CMT_AUTO_IMAGE N_("Load inline images automatically") #define CMT_MAX_LOAD_IMAGE N_("Maximum processes for parallel image loading") #define CMT_EXT_IMAGE_VIEWER N_("Use external image viewer") #define CMT_IMAGE_SCALE N_("Scale of image (%)") #define CMT_IMGDISPLAY N_("External command to display image") #define CMT_IMAGE_MAP_LIST N_("Use link list of image map") #endif #define CMT_MULTICOL N_("Display file names in multi-column format") #define CMT_ALT_ENTITY N_("Use ASCII equivalents to display entities") #define CMT_GRAPHIC_CHAR N_("Character type for border of table and menu") #define CMT_DISP_BORDERS N_("Display table borders, ignore value of BORDER") #define CMT_FOLD_TEXTAREA N_("Fold lines in TEXTAREA") #define CMT_DISP_INS_DEL N_("Display INS, DEL, S and STRIKE element") #define CMT_COLOR N_("Display with color") #define CMT_B_COLOR N_("Color of normal character") #define CMT_A_COLOR N_("Color of anchor") #define CMT_I_COLOR N_("Color of image link") #define CMT_F_COLOR N_("Color of form") #define CMT_ACTIVE_STYLE N_("Enable coloring of active link") #define CMT_C_COLOR N_("Color of currently active link") #define CMT_VISITED_ANCHOR N_("Use visited link color") #define CMT_V_COLOR N_("Color of visited link") #define CMT_BG_COLOR N_("Color of background") #define CMT_MARK_COLOR N_("Color of mark") #define CMT_USE_PROXY N_("Use proxy") #define CMT_HTTP_PROXY N_("URL of HTTP proxy host") #ifdef USE_SSL #define CMT_HTTPS_PROXY N_("URL of HTTPS proxy host") #endif /* USE_SSL */ #ifdef USE_GOPHER #define CMT_GOPHER_PROXY N_("URL of GOPHER proxy host") #endif /* USE_GOPHER */ #define CMT_FTP_PROXY N_("URL of FTP proxy host") #define CMT_NO_PROXY N_("Domains to be accessed directly (no proxy)") #define CMT_NOPROXY_NETADDR N_("Check noproxy by network address") #define CMT_NO_CACHE N_("Disable cache") #ifdef USE_NNTP #define CMT_NNTP_SERVER N_("News server") #define CMT_NNTP_MODE N_("Mode of news server") #define CMT_MAX_NEWS N_("Number of news messages") #endif #define CMT_DNS_ORDER N_("Order of name resolution") #define CMT_DROOT N_("Directory corresponding to / (document root)") #define CMT_PDROOT N_("Directory corresponding to /~user") #define CMT_CGIBIN N_("Directory corresponding to /cgi-bin") #define CMT_CONFIRM_QQ N_("Confirm when quitting with q") #define CMT_CLOSE_TAB_BACK N_("Close tab if buffer is last when back") #ifdef USE_MARK #define CMT_USE_MARK N_("Enable mark operations") #endif #define CMT_EMACS_LIKE_LINEEDIT N_("Enable Emacs-style line editing") #define CMT_VI_PREC_NUM N_("Enable vi-like numeric prefix") #define CMT_LABEL_TOPLINE N_("Move cursor to top line when going to label") #define CMT_NEXTPAGE_TOPLINE N_("Move cursor to top line when moving to next page") #define CMT_FOLD_LINE N_("Fold lines of plain text file") #define CMT_SHOW_NUM N_("Show line numbers") #define CMT_SHOW_SRCH_STR N_("Show search string") #define CMT_MIMETYPES N_("List of mime.types files") #define CMT_MAILCAP N_("List of mailcap files") #define CMT_URIMETHODMAP N_("List of urimethodmap files") #define CMT_EDITOR N_("Editor") #define CMT_MAILER N_("Mailer") #define CMT_MAILTO_OPTIONS N_("How to call Mailer for mailto URLs with options") #define CMT_EXTBRZ N_("External browser") #define CMT_EXTBRZ2 N_("2nd external browser") #define CMT_EXTBRZ3 N_("3rd external browser") #define CMT_EXTBRZ4 N_("4th external browser") #define CMT_EXTBRZ5 N_("5th external browser") #define CMT_EXTBRZ6 N_("6th external browser") #define CMT_EXTBRZ7 N_("7th external browser") #define CMT_EXTBRZ8 N_("8th external browser") #define CMT_EXTBRZ9 N_("9th external browser") #define CMT_DISABLE_SECRET_SECURITY_CHECK N_("Disable secret file security check") #define CMT_PASSWDFILE N_("Password file") #define CMT_PRE_FORM_FILE N_("File for setting form on loading") #define CMT_SITECONF_FILE N_("File for preferences for each site") #define CMT_FTPPASS N_("Password for anonymous FTP (your mail address)") #define CMT_FTPPASS_HOSTNAMEGEN N_("Generate domain part of password for FTP") #define CMT_USERAGENT N_("User-Agent identification string") #define CMT_ACCEPTENCODING N_("Accept-Encoding header") #define CMT_ACCEPTMEDIA N_("Accept header") #define CMT_ACCEPTLANG N_("Accept-Language header") #define CMT_MARK_ALL_PAGES N_("Treat URL-like strings as links in all pages") #define CMT_WRAP N_("Wrap search") #define CMT_VIEW_UNSEENOBJECTS N_("Display unseen objects (e.g. bgimage tag)") #define CMT_AUTO_UNCOMPRESS N_("Uncompress compressed data automatically when downloading") #ifdef __EMX__ #define CMT_BGEXTVIEW N_("Run external viewer in a separate session") #else #define CMT_BGEXTVIEW N_("Run external viewer in the background") #endif #define CMT_EXT_DIRLIST N_("Use external program for directory listing") #define CMT_DIRLIST_CMD N_("URL of directory listing command") #ifdef USE_DICT #define CMT_USE_DICTCOMMAND N_("Enable dictionary lookup through CGI") #define CMT_DICTCOMMAND N_("URL of dictionary lookup command") #endif /* USE_DICT */ #define CMT_IGNORE_NULL_IMG_ALT N_("Display link name for images lacking ALT") #define CMT_IFILE N_("Index file for directories") #define CMT_RETRY_HTTP N_("Prepend http:// to URL automatically") #define CMT_DEFAULT_URL N_("Default value for open-URL command") #define CMT_DECODE_CTE N_("Decode Content-Transfer-Encoding when saving") #define CMT_PRESERVE_TIMESTAMP N_("Preserve timestamp when saving") #ifdef USE_MOUSE #define CMT_MOUSE N_("Enable mouse") #define CMT_REVERSE_MOUSE N_("Scroll in reverse direction of mouse drag") #define CMT_RELATIVE_WHEEL_SCROLL N_("Behavior of wheel scroll speed") #define CMT_RELATIVE_WHEEL_SCROLL_RATIO N_("(A only)Scroll by # (%) of screen") #define CMT_FIXED_WHEEL_SCROLL_COUNT N_("(B only)Scroll by # lines") #endif /* USE_MOUSE */ #define CMT_CLEAR_BUF N_("Free memory of undisplayed buffers") #define CMT_NOSENDREFERER N_("Suppress `Referer:' header") #define CMT_IGNORE_CASE N_("Search case-insensitively") #define CMT_USE_LESSOPEN N_("Use LESSOPEN") #ifdef USE_SSL #ifdef USE_SSL_VERIFY #define CMT_SSL_VERIFY_SERVER N_("Perform SSL server verification") #define CMT_SSL_CERT_FILE N_("PEM encoded certificate file of client") #define CMT_SSL_KEY_FILE N_("PEM encoded private key file of client") #define CMT_SSL_CA_PATH N_("Path to directory for PEM encoded certificates of CAs") #define CMT_SSL_CA_FILE N_("File consisting of PEM encoded certificates of CAs") #endif /* USE_SSL_VERIFY */ #define CMT_SSL_FORBID_METHOD N_("List of forbidden SSL methods (2: SSLv2, 3: SSLv3, t: TLSv1.0, 5: TLSv1.1)") #endif /* USE_SSL */ #ifdef USE_COOKIE #define CMT_USECOOKIE N_("Enable cookie processing") #define CMT_SHOWCOOKIE N_("Print a message when receiving a cookie") #define CMT_ACCEPTCOOKIE N_("Accept cookies") #define CMT_ACCEPTBADCOOKIE N_("Action to be taken on invalid cookie") #define CMT_COOKIE_REJECT_DOMAINS N_("Domains to reject cookies from") #define CMT_COOKIE_ACCEPT_DOMAINS N_("Domains to accept cookies from") #define CMT_COOKIE_AVOID_WONG_NUMBER_OF_DOTS N_("Domains to avoid [wrong number of dots]") #endif #define CMT_FOLLOW_REDIRECTION N_("Number of redirections to follow") #define CMT_META_REFRESH N_("Enable processing of meta-refresh tag") #ifdef USE_MIGEMO #define CMT_USE_MIGEMO N_("Enable Migemo (Roma-ji search)") #define CMT_MIGEMO_COMMAND N_("Migemo command") #endif /* USE_MIGEMO */ #ifdef USE_M17N #define CMT_DISPLAY_CHARSET N_("Display charset") #define CMT_DOCUMENT_CHARSET N_("Default document charset") #define CMT_AUTO_DETECT N_("Automatic charset detect when loading") #define CMT_SYSTEM_CHARSET N_("System charset") #define CMT_FOLLOW_LOCALE N_("System charset follows locale(LC_CTYPE)") #define CMT_EXT_HALFDUMP N_("Output halfdump with display charset") #define CMT_USE_WIDE N_("Use multi column characters") #define CMT_USE_COMBINING N_("Use combining characters") #define CMT_EAST_ASIAN_WIDTH N_("Use double width for some Unicode characters") #define CMT_USE_LANGUAGE_TAG N_("Use Unicode language tags") #define CMT_UCS_CONV N_("Charset conversion using Unicode map") #define CMT_PRE_CONV N_("Charset conversion when loading") #define CMT_SEARCH_CONV N_("Adjust search string for document charset") #define CMT_FIX_WIDTH_CONV N_("Fix character width when conversion") #define CMT_USE_GB12345_MAP N_("Use GB 12345 Unicode map instead of GB 2312's") #define CMT_USE_JISX0201 N_("Use JIS X 0201 Roman for ISO-2022-JP") #define CMT_USE_JISC6226 N_("Use JIS C 6226:1978 for ISO-2022-JP") #define CMT_USE_JISX0201K N_("Use JIS X 0201 Katakana") #define CMT_USE_JISX0212 N_("Use JIS X 0212:1990 (Supplemental Kanji)") #define CMT_USE_JISX0213 N_("Use JIS X 0213:2000 (2000JIS)") #define CMT_STRICT_ISO2022 N_("Strict ISO-2022-JP/KR/CN") #define CMT_GB18030_AS_UCS N_("Treat 4 bytes char. of GB18030 as Unicode") #define CMT_SIMPLE_PRESERVE_SPACE N_("Simple Preserve space") #endif #define CMT_KEYMAP_FILE N_("keymap file") #define PI_TEXT 0 #define PI_ONOFF 1 #define PI_SEL_C 2 #ifdef USE_M17N #define PI_CODE 3 #endif struct sel_c { int value; char *cvalue; char *text; }; #ifdef USE_COLOR static struct sel_c colorstr[] = { {0, "black", N_("black")}, {1, "red", N_("red")}, {2, "green", N_("green")}, {3, "yellow", N_("yellow")}, {4, "blue", N_("blue")}, {5, "magenta", N_("magenta")}, {6, "cyan", N_("cyan")}, {7, "white", N_("white")}, {8, "terminal", N_("terminal")}, {0, NULL, NULL} }; #endif /* USE_COLOR */ #if 1 /* ANSI-C ? */ #define N_STR(x) #x #define N_S(x) (x), N_STR(x) #else /* for traditional cpp? */ static char n_s[][2] = { {'0', 0}, {'1', 0}, {'2', 0}, }; #define N_S(x) (x), n_s[(x)] #endif static struct sel_c defaulturls[] = { {N_S(DEFAULT_URL_EMPTY), N_("none")}, {N_S(DEFAULT_URL_CURRENT), N_("current URL")}, {N_S(DEFAULT_URL_LINK), N_("link URL")}, {0, NULL, NULL} }; static struct sel_c displayinsdel[] = { {N_S(DISPLAY_INS_DEL_SIMPLE), N_("simple")}, {N_S(DISPLAY_INS_DEL_NORMAL), N_("use tag")}, {N_S(DISPLAY_INS_DEL_FONTIFY), N_("fontify")}, {0, NULL, NULL} }; #ifdef USE_MOUSE static struct sel_c wheelmode[] = { {TRUE, "1", N_("A:relative to screen height")}, {FALSE, "0", N_("B:fixed speed")}, {0, NULL, NULL} }; #endif /* MOUSE */ #ifdef INET6 static struct sel_c dnsorders[] = { {N_S(DNS_ORDER_UNSPEC), N_("unspecified")}, {N_S(DNS_ORDER_INET_INET6), N_("inet inet6")}, {N_S(DNS_ORDER_INET6_INET), N_("inet6 inet")}, {N_S(DNS_ORDER_INET_ONLY), N_("inet only")}, {N_S(DNS_ORDER_INET6_ONLY), N_("inet6 only")}, {0, NULL, NULL} }; #endif /* INET6 */ #ifdef USE_COOKIE static struct sel_c badcookiestr[] = { {N_S(ACCEPT_BAD_COOKIE_DISCARD), N_("discard")}, #if 0 {N_S(ACCEPT_BAD_COOKIE_ACCEPT), N_("accept")}, #endif {N_S(ACCEPT_BAD_COOKIE_ASK), N_("ask")}, {0, NULL, NULL} }; #endif /* USE_COOKIE */ static struct sel_c mailtooptionsstr[] = { #ifdef USE_W3MMAILER {N_S(MAILTO_OPTIONS_USE_W3MMAILER), N_("use internal mailer instead")}, #endif {N_S(MAILTO_OPTIONS_IGNORE), N_("ignore options and use only the address")}, {N_S(MAILTO_OPTIONS_USE_MAILTO_URL), N_("use full mailto URL")}, {0, NULL, NULL} }; #ifdef USE_M17N static wc_ces_list *display_charset_str = NULL; static wc_ces_list *document_charset_str = NULL; static wc_ces_list *system_charset_str = NULL; static struct sel_c auto_detect_str[] = { {N_S(WC_OPT_DETECT_OFF), N_("OFF")}, {N_S(WC_OPT_DETECT_ISO_2022), N_("Only ISO 2022")}, {N_S(WC_OPT_DETECT_ON), N_("ON")}, {0, NULL, NULL} }; #endif static struct sel_c graphic_char_str[] = { {N_S(GRAPHIC_CHAR_ASCII), N_("ASCII")}, {N_S(GRAPHIC_CHAR_CHARSET), N_("charset specific")}, {N_S(GRAPHIC_CHAR_DEC), N_("DEC special graphics")}, {0, NULL, NULL} }; struct param_ptr params1[] = { {"tabstop", P_NZINT, PI_TEXT, (void *)&Tabstop, CMT_TABSTOP, NULL}, {"indent_incr", P_NZINT, PI_TEXT, (void *)&IndentIncr, CMT_INDENT_INCR, NULL}, {"pixel_per_char", P_PIXELS, PI_TEXT, (void *)&pixel_per_char, CMT_PIXEL_PER_CHAR, NULL}, #ifdef USE_IMAGE {"pixel_per_line", P_PIXELS, PI_TEXT, (void *)&pixel_per_line, CMT_PIXEL_PER_LINE, NULL}, #endif {"frame", P_CHARINT, PI_ONOFF, (void *)&RenderFrame, CMT_FRAME, NULL}, {"target_self", P_CHARINT, PI_ONOFF, (void *)&TargetSelf, CMT_TSELF, NULL}, {"open_tab_blank", P_INT, PI_ONOFF, (void *)&open_tab_blank, CMT_OPEN_TAB_BLANK, NULL}, {"open_tab_dl_list", P_INT, PI_ONOFF, (void *)&open_tab_dl_list, CMT_OPEN_TAB_DL_LIST, NULL}, {"display_link", P_INT, PI_ONOFF, (void *)&displayLink, CMT_DISPLINK, NULL}, {"display_link_number", P_INT, PI_ONOFF, (void *)&displayLinkNumber, CMT_DISPLINKNUMBER, NULL}, {"decode_url", P_INT, PI_ONOFF, (void *)&DecodeURL, CMT_DECODE_URL, NULL}, {"display_lineinfo", P_INT, PI_ONOFF, (void *)&displayLineInfo, CMT_DISPLINEINFO, NULL}, {"ext_dirlist", P_INT, PI_ONOFF, (void *)&UseExternalDirBuffer, CMT_EXT_DIRLIST, NULL}, {"dirlist_cmd", P_STRING, PI_TEXT, (void *)&DirBufferCommand, CMT_DIRLIST_CMD, NULL}, #ifdef USE_DICT {"use_dictcommand", P_INT, PI_ONOFF, (void *)&UseDictCommand, CMT_USE_DICTCOMMAND, NULL}, {"dictcommand", P_STRING, PI_TEXT, (void *)&DictCommand, CMT_DICTCOMMAND, NULL}, #endif /* USE_DICT */ {"multicol", P_INT, PI_ONOFF, (void *)&multicolList, CMT_MULTICOL, NULL}, {"alt_entity", P_CHARINT, PI_ONOFF, (void *)&UseAltEntity, CMT_ALT_ENTITY, NULL}, {"graphic_char", P_CHARINT, PI_SEL_C, (void *)&UseGraphicChar, CMT_GRAPHIC_CHAR, (void *)graphic_char_str}, {"display_borders", P_CHARINT, PI_ONOFF, (void *)&DisplayBorders, CMT_DISP_BORDERS, NULL}, {"fold_textarea", P_CHARINT, PI_ONOFF, (void *)&FoldTextarea, CMT_FOLD_TEXTAREA, NULL}, {"display_ins_del", P_INT, PI_SEL_C, (void *)&displayInsDel, CMT_DISP_INS_DEL, displayinsdel}, {"ignore_null_img_alt", P_INT, PI_ONOFF, (void *)&ignore_null_img_alt, CMT_IGNORE_NULL_IMG_ALT, NULL}, {"view_unseenobject", P_INT, PI_ONOFF, (void *)&view_unseenobject, CMT_VIEW_UNSEENOBJECTS, NULL}, /* XXX: emacs-w3m force to off display_image even if image options off */ {"display_image", P_INT, PI_ONOFF, (void *)&displayImage, CMT_DISP_IMAGE, NULL}, {"pseudo_inlines", P_INT, PI_ONOFF, (void *)&pseudoInlines, CMT_PSEUDO_INLINES, NULL}, #ifdef USE_IMAGE {"auto_image", P_INT, PI_ONOFF, (void *)&autoImage, CMT_AUTO_IMAGE, NULL}, {"max_load_image", P_INT, PI_TEXT, (void *)&maxLoadImage, CMT_MAX_LOAD_IMAGE, NULL}, {"ext_image_viewer", P_INT, PI_ONOFF, (void *)&useExtImageViewer, CMT_EXT_IMAGE_VIEWER, NULL}, {"image_scale", P_SCALE, PI_TEXT, (void *)&image_scale, CMT_IMAGE_SCALE, NULL}, {"imgdisplay", P_STRING, PI_TEXT, (void *)&Imgdisplay, CMT_IMGDISPLAY, NULL}, {"image_map_list", P_INT, PI_ONOFF, (void *)&image_map_list, CMT_IMAGE_MAP_LIST, NULL}, #endif {"fold_line", P_INT, PI_ONOFF, (void *)&FoldLine, CMT_FOLD_LINE, NULL}, {"show_lnum", P_INT, PI_ONOFF, (void *)&showLineNum, CMT_SHOW_NUM, NULL}, {"show_srch_str", P_INT, PI_ONOFF, (void *)&show_srch_str, CMT_SHOW_SRCH_STR, NULL}, {"label_topline", P_INT, PI_ONOFF, (void *)&label_topline, CMT_LABEL_TOPLINE, NULL}, {"nextpage_topline", P_INT, PI_ONOFF, (void *)&nextpage_topline, CMT_NEXTPAGE_TOPLINE, NULL}, {NULL, 0, 0, NULL, NULL, NULL}, }; #ifdef USE_COLOR struct param_ptr params2[] = { {"color", P_INT, PI_ONOFF, (void *)&useColor, CMT_COLOR, NULL}, {"basic_color", P_COLOR, PI_SEL_C, (void *)&basic_color, CMT_B_COLOR, (void *)colorstr}, {"anchor_color", P_COLOR, PI_SEL_C, (void *)&anchor_color, CMT_A_COLOR, (void *)colorstr}, {"image_color", P_COLOR, PI_SEL_C, (void *)&image_color, CMT_I_COLOR, (void *)colorstr}, {"form_color", P_COLOR, PI_SEL_C, (void *)&form_color, CMT_F_COLOR, (void *)colorstr}, #ifdef USE_BG_COLOR {"mark_color", P_COLOR, PI_SEL_C, (void *)&mark_color, CMT_MARK_COLOR, (void *)colorstr}, {"bg_color", P_COLOR, PI_SEL_C, (void *)&bg_color, CMT_BG_COLOR, (void *)colorstr}, #endif /* USE_BG_COLOR */ {"active_style", P_INT, PI_ONOFF, (void *)&useActiveColor, CMT_ACTIVE_STYLE, NULL}, {"active_color", P_COLOR, PI_SEL_C, (void *)&active_color, CMT_C_COLOR, (void *)colorstr}, {"visited_anchor", P_INT, PI_ONOFF, (void *)&useVisitedColor, CMT_VISITED_ANCHOR, NULL}, {"visited_color", P_COLOR, PI_SEL_C, (void *)&visited_color, CMT_V_COLOR, (void *)colorstr}, {NULL, 0, 0, NULL, NULL, NULL}, }; #endif /* USE_COLOR */ struct param_ptr params3[] = { {"pagerline", P_NZINT, PI_TEXT, (void *)&PagerMax, CMT_PAGERLINE, NULL}, #ifdef USE_HISTORY {"use_history", P_INT, PI_ONOFF, (void *)&UseHistory, CMT_HISTORY, NULL}, {"history", P_INT, PI_TEXT, (void *)&URLHistSize, CMT_HISTSIZE, NULL}, {"save_hist", P_INT, PI_ONOFF, (void *)&SaveURLHist, CMT_SAVEHIST, NULL}, #endif /* USE_HISTORY */ {"confirm_qq", P_INT, PI_ONOFF, (void *)&confirm_on_quit, CMT_CONFIRM_QQ, NULL}, {"close_tab_back", P_INT, PI_ONOFF, (void *)&close_tab_back, CMT_CLOSE_TAB_BACK, NULL}, #ifdef USE_MARK {"mark", P_INT, PI_ONOFF, (void *)&use_mark, CMT_USE_MARK, NULL}, #endif {"emacs_like_lineedit", P_INT, PI_ONOFF, (void *)&emacs_like_lineedit, CMT_EMACS_LIKE_LINEEDIT, NULL}, {"vi_prec_num", P_INT, PI_ONOFF, (void *)&vi_prec_num, CMT_VI_PREC_NUM, NULL}, {"mark_all_pages", P_INT, PI_ONOFF, (void *)&MarkAllPages, CMT_MARK_ALL_PAGES, NULL}, {"wrap_search", P_INT, PI_ONOFF, (void *)&WrapDefault, CMT_WRAP, NULL}, {"ignorecase_search", P_INT, PI_ONOFF, (void *)&IgnoreCase, CMT_IGNORE_CASE, NULL}, #ifdef USE_MIGEMO {"use_migemo", P_INT, PI_ONOFF, (void *)&use_migemo, CMT_USE_MIGEMO, NULL}, {"migemo_command", P_STRING, PI_TEXT, (void *)&migemo_command, CMT_MIGEMO_COMMAND, NULL}, #endif /* USE_MIGEMO */ #ifdef USE_MOUSE {"use_mouse", P_INT, PI_ONOFF, (void *)&use_mouse, CMT_MOUSE, NULL}, {"reverse_mouse", P_INT, PI_ONOFF, (void *)&reverse_mouse, CMT_REVERSE_MOUSE, NULL}, {"relative_wheel_scroll", P_INT, PI_SEL_C, (void *)&relative_wheel_scroll, CMT_RELATIVE_WHEEL_SCROLL, (void *)wheelmode}, {"relative_wheel_scroll_ratio", P_INT, PI_TEXT, (void *)&relative_wheel_scroll_ratio, CMT_RELATIVE_WHEEL_SCROLL_RATIO, NULL}, {"fixed_wheel_scroll_count", P_INT, PI_TEXT, (void *)&fixed_wheel_scroll_count, CMT_FIXED_WHEEL_SCROLL_COUNT, NULL}, #endif /* USE_MOUSE */ {"clear_buffer", P_INT, PI_ONOFF, (void *)&clear_buffer, CMT_CLEAR_BUF, NULL}, {"decode_cte", P_CHARINT, PI_ONOFF, (void *)&DecodeCTE, CMT_DECODE_CTE, NULL}, {"auto_uncompress", P_CHARINT, PI_ONOFF, (void *)&AutoUncompress, CMT_AUTO_UNCOMPRESS, NULL}, {"preserve_timestamp", P_CHARINT, PI_ONOFF, (void *)&PreserveTimestamp, CMT_PRESERVE_TIMESTAMP, NULL}, {"keymap_file", P_STRING, PI_TEXT, (void *)&keymap_file, CMT_KEYMAP_FILE, NULL}, {NULL, 0, 0, NULL, NULL, NULL}, }; struct param_ptr params4[] = { {"use_proxy", P_CHARINT, PI_ONOFF, (void *)&use_proxy, CMT_USE_PROXY, NULL}, {"http_proxy", P_STRING, PI_TEXT, (void *)&HTTP_proxy, CMT_HTTP_PROXY, NULL}, #ifdef USE_SSL {"https_proxy", P_STRING, PI_TEXT, (void *)&HTTPS_proxy, CMT_HTTPS_PROXY, NULL}, #endif /* USE_SSL */ #ifdef USE_GOPHER {"gopher_proxy", P_STRING, PI_TEXT, (void *)&GOPHER_proxy, CMT_GOPHER_PROXY, NULL}, #endif /* USE_GOPHER */ {"ftp_proxy", P_STRING, PI_TEXT, (void *)&FTP_proxy, CMT_FTP_PROXY, NULL}, {"no_proxy", P_STRING, PI_TEXT, (void *)&NO_proxy, CMT_NO_PROXY, NULL}, {"noproxy_netaddr", P_INT, PI_ONOFF, (void *)&NOproxy_netaddr, CMT_NOPROXY_NETADDR, NULL}, {"no_cache", P_CHARINT, PI_ONOFF, (void *)&NoCache, CMT_NO_CACHE, NULL}, {NULL, 0, 0, NULL, NULL, NULL}, }; struct param_ptr params5[] = { {"document_root", P_STRING, PI_TEXT, (void *)&document_root, CMT_DROOT, NULL}, {"personal_document_root", P_STRING, PI_TEXT, (void *)&personal_document_root, CMT_PDROOT, NULL}, {"cgi_bin", P_STRING, PI_TEXT, (void *)&cgi_bin, CMT_CGIBIN, NULL}, {"index_file", P_STRING, PI_TEXT, (void *)&index_file, CMT_IFILE, NULL}, {NULL, 0, 0, NULL, NULL, NULL}, }; struct param_ptr params6[] = { {"mime_types", P_STRING, PI_TEXT, (void *)&mimetypes_files, CMT_MIMETYPES, NULL}, {"mailcap", P_STRING, PI_TEXT, (void *)&mailcap_files, CMT_MAILCAP, NULL}, #ifdef USE_EXTERNAL_URI_LOADER {"urimethodmap", P_STRING, PI_TEXT, (void *)&urimethodmap_files, CMT_URIMETHODMAP, NULL}, #endif {"editor", P_STRING, PI_TEXT, (void *)&Editor, CMT_EDITOR, NULL}, {"mailto_options", P_INT, PI_SEL_C, (void *)&MailtoOptions, CMT_MAILTO_OPTIONS, (void *)mailtooptionsstr}, {"mailer", P_STRING, PI_TEXT, (void *)&Mailer, CMT_MAILER, NULL}, {"extbrowser", P_STRING, PI_TEXT, (void *)&ExtBrowser, CMT_EXTBRZ, NULL}, {"extbrowser2", P_STRING, PI_TEXT, (void *)&ExtBrowser2, CMT_EXTBRZ2, NULL}, {"extbrowser3", P_STRING, PI_TEXT, (void *)&ExtBrowser3, CMT_EXTBRZ3, NULL}, {"extbrowser4", P_STRING, PI_TEXT, (void *)&ExtBrowser4, CMT_EXTBRZ4, NULL}, {"extbrowser5", P_STRING, PI_TEXT, (void *)&ExtBrowser5, CMT_EXTBRZ5, NULL}, {"extbrowser6", P_STRING, PI_TEXT, (void *)&ExtBrowser6, CMT_EXTBRZ6, NULL}, {"extbrowser7", P_STRING, PI_TEXT, (void *)&ExtBrowser7, CMT_EXTBRZ7, NULL}, {"extbrowser8", P_STRING, PI_TEXT, (void *)&ExtBrowser8, CMT_EXTBRZ8, NULL}, {"extbrowser9", P_STRING, PI_TEXT, (void *)&ExtBrowser9, CMT_EXTBRZ9, NULL}, {"bgextviewer", P_INT, PI_ONOFF, (void *)&BackgroundExtViewer, CMT_BGEXTVIEW, NULL}, {"use_lessopen", P_INT, PI_ONOFF, (void *)&use_lessopen, CMT_USE_LESSOPEN, NULL}, {NULL, 0, 0, NULL, NULL, NULL}, }; #ifdef USE_SSL struct param_ptr params7[] = { {"ssl_forbid_method", P_STRING, PI_TEXT, (void *)&ssl_forbid_method, CMT_SSL_FORBID_METHOD, NULL}, #ifdef USE_SSL_VERIFY {"ssl_verify_server", P_INT, PI_ONOFF, (void *)&ssl_verify_server, CMT_SSL_VERIFY_SERVER, NULL}, {"ssl_cert_file", P_SSLPATH, PI_TEXT, (void *)&ssl_cert_file, CMT_SSL_CERT_FILE, NULL}, {"ssl_key_file", P_SSLPATH, PI_TEXT, (void *)&ssl_key_file, CMT_SSL_KEY_FILE, NULL}, {"ssl_ca_path", P_SSLPATH, PI_TEXT, (void *)&ssl_ca_path, CMT_SSL_CA_PATH, NULL}, {"ssl_ca_file", P_SSLPATH, PI_TEXT, (void *)&ssl_ca_file, CMT_SSL_CA_FILE, NULL}, #endif /* USE_SSL_VERIFY */ {NULL, 0, 0, NULL, NULL, NULL}, }; #endif /* USE_SSL */ #ifdef USE_COOKIE struct param_ptr params8[] = { {"use_cookie", P_INT, PI_ONOFF, (void *)&use_cookie, CMT_USECOOKIE, NULL}, {"show_cookie", P_INT, PI_ONOFF, (void *)&show_cookie, CMT_SHOWCOOKIE, NULL}, {"accept_cookie", P_INT, PI_ONOFF, (void *)&accept_cookie, CMT_ACCEPTCOOKIE, NULL}, {"accept_bad_cookie", P_INT, PI_SEL_C, (void *)&accept_bad_cookie, CMT_ACCEPTBADCOOKIE, (void *)badcookiestr}, {"cookie_reject_domains", P_STRING, PI_TEXT, (void *)&cookie_reject_domains, CMT_COOKIE_REJECT_DOMAINS, NULL}, {"cookie_accept_domains", P_STRING, PI_TEXT, (void *)&cookie_accept_domains, CMT_COOKIE_ACCEPT_DOMAINS, NULL}, {"cookie_avoid_wrong_number_of_dots", P_STRING, PI_TEXT, (void *)&cookie_avoid_wrong_number_of_dots, CMT_COOKIE_AVOID_WONG_NUMBER_OF_DOTS, NULL}, {NULL, 0, 0, NULL, NULL, NULL}, }; #endif struct param_ptr params9[] = { {"passwd_file", P_STRING, PI_TEXT, (void *)&passwd_file, CMT_PASSWDFILE, NULL}, {"disable_secret_security_check", P_INT, PI_ONOFF, (void *)&disable_secret_security_check, CMT_DISABLE_SECRET_SECURITY_CHECK, NULL}, {"ftppasswd", P_STRING, PI_TEXT, (void *)&ftppasswd, CMT_FTPPASS, NULL}, {"ftppass_hostnamegen", P_INT, PI_ONOFF, (void *)&ftppass_hostnamegen, CMT_FTPPASS_HOSTNAMEGEN, NULL}, {"pre_form_file", P_STRING, PI_TEXT, (void *)&pre_form_file, CMT_PRE_FORM_FILE, NULL}, {"siteconf_file", P_STRING, PI_TEXT, (void *)&siteconf_file, CMT_SITECONF_FILE, NULL}, {"user_agent", P_STRING, PI_TEXT, (void *)&UserAgent, CMT_USERAGENT, NULL}, {"no_referer", P_INT, PI_ONOFF, (void *)&NoSendReferer, CMT_NOSENDREFERER, NULL}, {"accept_language", P_STRING, PI_TEXT, (void *)&AcceptLang, CMT_ACCEPTLANG, NULL}, {"accept_encoding", P_STRING, PI_TEXT, (void *)&AcceptEncoding, CMT_ACCEPTENCODING, NULL}, {"accept_media", P_STRING, PI_TEXT, (void *)&AcceptMedia, CMT_ACCEPTMEDIA, NULL}, {"argv_is_url", P_CHARINT, PI_ONOFF, (void *)&ArgvIsURL, CMT_ARGV_IS_URL, NULL}, {"retry_http", P_INT, PI_ONOFF, (void *)&retryAsHttp, CMT_RETRY_HTTP, NULL}, {"default_url", P_INT, PI_SEL_C, (void *)&DefaultURLString, CMT_DEFAULT_URL, (void *)defaulturls}, {"follow_redirection", P_INT, PI_TEXT, &FollowRedirection, CMT_FOLLOW_REDIRECTION, NULL}, {"meta_refresh", P_CHARINT, PI_ONOFF, (void *)&MetaRefresh, CMT_META_REFRESH, NULL}, #ifdef INET6 {"dns_order", P_INT, PI_SEL_C, (void *)&DNS_order, CMT_DNS_ORDER, (void *)dnsorders}, #endif /* INET6 */ #ifdef USE_NNTP {"nntpserver", P_STRING, PI_TEXT, (void *)&NNTP_server, CMT_NNTP_SERVER, NULL}, {"nntpmode", P_STRING, PI_TEXT, (void *)&NNTP_mode, CMT_NNTP_MODE, NULL}, {"max_news", P_INT, PI_TEXT, (void *)&MaxNewsMessage, CMT_MAX_NEWS, NULL}, #endif {NULL, 0, 0, NULL, NULL, NULL}, }; #ifdef USE_M17N struct param_ptr params10[] = { {"display_charset", P_CODE, PI_CODE, (void *)&DisplayCharset, CMT_DISPLAY_CHARSET, (void *)&display_charset_str}, {"document_charset", P_CODE, PI_CODE, (void *)&DocumentCharset, CMT_DOCUMENT_CHARSET, (void *)&document_charset_str}, {"auto_detect", P_CHARINT, PI_SEL_C, (void *)&WcOption.auto_detect, CMT_AUTO_DETECT, (void *)auto_detect_str}, {"system_charset", P_CODE, PI_CODE, (void *)&SystemCharset, CMT_SYSTEM_CHARSET, (void *)&system_charset_str}, {"follow_locale", P_CHARINT, PI_ONOFF, (void *)&FollowLocale, CMT_FOLLOW_LOCALE, NULL}, {"ext_halfdump", P_CHARINT, PI_ONOFF, (void *)&ExtHalfdump, CMT_EXT_HALFDUMP, NULL}, {"use_wide", P_CHARINT, PI_ONOFF, (void *)&WcOption.use_wide, CMT_USE_WIDE, NULL}, {"use_combining", P_CHARINT, PI_ONOFF, (void *)&WcOption.use_combining, CMT_USE_COMBINING, NULL}, #ifdef USE_UNICODE {"east_asian_width", P_CHARINT, PI_ONOFF, (void *)&WcOption.east_asian_width, CMT_EAST_ASIAN_WIDTH, NULL}, {"use_language_tag", P_CHARINT, PI_ONOFF, (void *)&WcOption.use_language_tag, CMT_USE_LANGUAGE_TAG, NULL}, {"ucs_conv", P_CHARINT, PI_ONOFF, (void *)&WcOption.ucs_conv, CMT_UCS_CONV, NULL}, #endif {"pre_conv", P_CHARINT, PI_ONOFF, (void *)&WcOption.pre_conv, CMT_PRE_CONV, NULL}, {"search_conv", P_CHARINT, PI_ONOFF, (void *)&SearchConv, CMT_SEARCH_CONV, NULL}, {"fix_width_conv", P_CHARINT, PI_ONOFF, (void *)&WcOption.fix_width_conv, CMT_FIX_WIDTH_CONV, NULL}, #ifdef USE_UNICODE {"use_gb12345_map", P_CHARINT, PI_ONOFF, (void *)&WcOption.use_gb12345_map, CMT_USE_GB12345_MAP, NULL}, #endif {"use_jisx0201", P_CHARINT, PI_ONOFF, (void *)&WcOption.use_jisx0201, CMT_USE_JISX0201, NULL}, {"use_jisc6226", P_CHARINT, PI_ONOFF, (void *)&WcOption.use_jisc6226, CMT_USE_JISC6226, NULL}, {"use_jisx0201k", P_CHARINT, PI_ONOFF, (void *)&WcOption.use_jisx0201k, CMT_USE_JISX0201K, NULL}, {"use_jisx0212", P_CHARINT, PI_ONOFF, (void *)&WcOption.use_jisx0212, CMT_USE_JISX0212, NULL}, {"use_jisx0213", P_CHARINT, PI_ONOFF, (void *)&WcOption.use_jisx0213, CMT_USE_JISX0213, NULL}, {"strict_iso2022", P_CHARINT, PI_ONOFF, (void *)&WcOption.strict_iso2022, CMT_STRICT_ISO2022, NULL}, #ifdef USE_UNICODE {"gb18030_as_ucs", P_CHARINT, PI_ONOFF, (void *)&WcOption.gb18030_as_ucs, CMT_GB18030_AS_UCS, NULL}, #endif {"simple_preserve_space", P_CHARINT, PI_ONOFF, (void *)&SimplePreserveSpace, CMT_SIMPLE_PRESERVE_SPACE, NULL}, {NULL, 0, 0, NULL, NULL, NULL}, }; #endif struct param_section sections[] = { {N_("Display Settings"), params1}, #ifdef USE_COLOR {N_("Color Settings"), params2}, #endif /* USE_COLOR */ {N_("Miscellaneous Settings"), params3}, {N_("Directory Settings"), params5}, {N_("External Program Settings"), params6}, {N_("Network Settings"), params9}, {N_("Proxy Settings"), params4}, #ifdef USE_SSL {N_("SSL Settings"), params7}, #endif #ifdef USE_COOKIE {N_("Cookie Settings"), params8}, #endif #ifdef USE_M17N {N_("Charset Settings"), params10}, #endif {NULL, NULL} }; static Str to_str(struct param_ptr *p); static int compare_table(struct rc_search_table *a, struct rc_search_table *b) { return strcmp(a->param->name, b->param->name); } static void create_option_search_table() { int i, j, k; int diff1, diff2; char *p, *q; /* count table size */ RC_table_size = 0; for (j = 0; sections[j].name != NULL; j++) { i = 0; while (sections[j].params[i].name) { i++; RC_table_size++; } } RC_search_table = New_N(struct rc_search_table, RC_table_size); k = 0; for (j = 0; sections[j].name != NULL; j++) { i = 0; while (sections[j].params[i].name) { RC_search_table[k].param = &sections[j].params[i]; k++; i++; } } qsort(RC_search_table, RC_table_size, sizeof(struct rc_search_table), (int (*)(const void *, const void *))compare_table); diff2 = 0; for (i = 0; i < RC_table_size - 1; i++) { p = RC_search_table[i].param->name; q = RC_search_table[i + 1].param->name; for (j = 0; p[j] != '\0' && q[j] != '\0' && p[j] == q[j]; j++) ; diff1 = j; if (diff1 > diff2) RC_search_table[i].uniq_pos = diff1 + 1; else RC_search_table[i].uniq_pos = diff2 + 1; diff2 = diff1; } } struct param_ptr * search_param(char *name) { size_t b, e, i; int cmp; int len = strlen(name); for (b = 0, e = RC_table_size - 1; b <= e;) { i = (b + e) / 2; cmp = strncmp(name, RC_search_table[i].param->name, len); if (!cmp) { if (len >= RC_search_table[i].uniq_pos) { return RC_search_table[i].param; } else { while ((cmp = strcmp(name, RC_search_table[i].param->name)) <= 0) if (!cmp) return RC_search_table[i].param; else if (i == 0) return NULL; else i--; /* ambiguous */ return NULL; } } else if (cmp < 0) { if (i == 0) return NULL; e = i - 1; } else b = i + 1; } return NULL; } /* show parameter with bad options invokation */ void show_params(FILE * fp) { int i, j, l; const char *t = ""; char *cmt; #ifdef USE_M17N #ifdef ENABLE_NLS OptionCharset = SystemCharset; /* FIXME */ #endif #endif fputs("\nconfiguration parameters\n", fp); for (j = 0; sections[j].name != NULL; j++) { #ifdef USE_M17N if (!OptionEncode) cmt = wc_conv(_(sections[j].name), OptionCharset, InnerCharset)->ptr; else #endif cmt = sections[j].name; fprintf(fp, " section[%d]: %s\n", j, conv_to_system(cmt)); i = 0; while (sections[j].params[i].name) { switch (sections[j].params[i].type) { case P_INT: case P_SHORT: case P_CHARINT: case P_NZINT: t = (sections[j].params[i].inputtype == PI_ONOFF) ? "bool" : "number"; break; case P_CHAR: t = "char"; break; case P_STRING: t = "string"; break; #if defined(USE_SSL) && defined(USE_SSL_VERIFY) case P_SSLPATH: t = "path"; break; #endif #ifdef USE_COLOR case P_COLOR: t = "color"; break; #endif #ifdef USE_M17N case P_CODE: t = "charset"; break; #endif case P_PIXELS: t = "number"; break; case P_SCALE: t = "percent"; break; } #ifdef USE_M17N if (!OptionEncode) cmt = wc_conv(_(sections[j].params[i].comment), OptionCharset, InnerCharset)->ptr; else #endif cmt = sections[j].params[i].comment; l = 30 - (strlen(sections[j].params[i].name) + strlen(t)); if (l < 0) l = 1; fprintf(fp, " -o %s=<%s>%*s%s\n", sections[j].params[i].name, t, l, " ", conv_to_system(cmt)); i++; } } } int str_to_bool(char *value, int old) { if (value == NULL) return 1; switch (TOLOWER(*value)) { case '0': case 'f': /* false */ case 'n': /* no */ case 'u': /* undef */ return 0; case 'o': if (TOLOWER(value[1]) == 'f') /* off */ return 0; return 1; /* on */ case 't': if (TOLOWER(value[1]) == 'o') /* toggle */ return !old; return 1; /* true */ case '!': case 'r': /* reverse */ case 'x': /* exchange */ return !old; } return 1; } #ifdef USE_COLOR static int str_to_color(char *value) { if (value == NULL) return 8; /* terminal */ switch (TOLOWER(*value)) { case '0': return 0; /* black */ case '1': case 'r': return 1; /* red */ case '2': case 'g': return 2; /* green */ case '3': case 'y': return 3; /* yellow */ case '4': return 4; /* blue */ case '5': case 'm': return 5; /* magenta */ case '6': case 'c': return 6; /* cyan */ case '7': case 'w': return 7; /* white */ case '8': case 't': return 8; /* terminal */ case 'b': if (!strncasecmp(value, "blu", 3)) return 4; /* blue */ else return 0; /* black */ } return 8; /* terminal */ } #endif static int set_param(char *name, char *value) { struct param_ptr *p; double ppc; if (value == NULL) return 0; p = search_param(name); if (p == NULL) return 0; switch (p->type) { case P_INT: if (atoi(value) >= 0) *(int *)p->varptr = (p->inputtype == PI_ONOFF) ? str_to_bool(value, *(int *)p->varptr) : atoi(value); break; case P_NZINT: if (atoi(value) > 0) *(int *)p->varptr = atoi(value); break; case P_SHORT: *(short *)p->varptr = (p->inputtype == PI_ONOFF) ? str_to_bool(value, *(short *)p->varptr) : atoi(value); break; case P_CHARINT: *(char *)p->varptr = (p->inputtype == PI_ONOFF) ? str_to_bool(value, *(char *)p->varptr) : atoi(value); break; case P_CHAR: *(char *)p->varptr = value[0]; break; case P_STRING: *(char **)p->varptr = value; break; #if defined(USE_SSL) && defined(USE_SSL_VERIFY) case P_SSLPATH: if (value != NULL && value[0] != '\0') *(char **)p->varptr = rcFile(value); else *(char **)p->varptr = NULL; ssl_path_modified = 1; break; #endif #ifdef USE_COLOR case P_COLOR: *(int *)p->varptr = str_to_color(value); break; #endif #ifdef USE_M17N case P_CODE: *(wc_ces *) p->varptr = wc_guess_charset_short(value, *(wc_ces *) p->varptr); break; #endif case P_PIXELS: ppc = atof(value); if (ppc >= MINIMUM_PIXEL_PER_CHAR && ppc <= MAXIMUM_PIXEL_PER_CHAR * 2) *(double *)p->varptr = ppc; break; case P_SCALE: ppc = atof(value); if (ppc >= 10 && ppc <= 1000) *(double *)p->varptr = ppc; break; } return 1; } int set_param_option(char *option) { Str tmp = Strnew(); char *p = option, *q; while (*p && !IS_SPACE(*p) && *p != '=') Strcat_char(tmp, *p++); while (*p && IS_SPACE(*p)) p++; if (*p == '=') { p++; while (*p && IS_SPACE(*p)) p++; } Strlower(tmp); if (set_param(tmp->ptr, p)) goto option_assigned; q = tmp->ptr; if (!strncmp(q, "no", 2)) { /* -o noxxx, -o no-xxx, -o no_xxx */ q += 2; if (*q == '-' || *q == '_') q++; } else if (tmp->ptr[0] == '-') /* -o -xxx */ q++; else return 0; if (set_param(q, "0")) goto option_assigned; return 0; option_assigned: return 1; } char * get_param_option(char *name) { struct param_ptr *p; p = search_param(name); return p ? to_str(p)->ptr : NULL; } static void interpret_rc(FILE * f) { Str line; Str tmp; char *p; for (;;) { line = Strfgets(f); if (line->length == 0) /* end of file */ break; Strchop(line); if (line->length == 0) /* blank line */ continue; Strremovefirstspaces(line); if (line->ptr[0] == '#') /* comment */ continue; tmp = Strnew(); p = line->ptr; while (*p && !IS_SPACE(*p)) Strcat_char(tmp, *p++); while (*p && IS_SPACE(*p)) p++; Strlower(tmp); set_param(tmp->ptr, p); } } void parse_proxy() { if (non_null(HTTP_proxy)) parseURL(HTTP_proxy, &HTTP_proxy_parsed, NULL); #ifdef USE_SSL if (non_null(HTTPS_proxy)) parseURL(HTTPS_proxy, &HTTPS_proxy_parsed, NULL); #endif /* USE_SSL */ #ifdef USE_GOPHER if (non_null(GOPHER_proxy)) parseURL(GOPHER_proxy, &GOPHER_proxy_parsed, NULL); #endif if (non_null(FTP_proxy)) parseURL(FTP_proxy, &FTP_proxy_parsed, NULL); if (non_null(NO_proxy)) set_no_proxy(NO_proxy); } #ifdef USE_COOKIE void parse_cookie() { if (non_null(cookie_reject_domains)) Cookie_reject_domains = make_domain_list(cookie_reject_domains); if (non_null(cookie_accept_domains)) Cookie_accept_domains = make_domain_list(cookie_accept_domains); if (non_null(cookie_avoid_wrong_number_of_dots)) Cookie_avoid_wrong_number_of_dots_domains = make_domain_list(cookie_avoid_wrong_number_of_dots); } #endif #ifdef __EMX__ static int do_mkdir(const char *dir, long mode) { char *r, abs[_MAX_PATH]; size_t n; _abspath(abs, rc_dir, _MAX_PATH); /* Translate '\\' to '/' */ if (!(n = strlen(abs))) return -1; if (*(r = abs + n - 1) == '/') /* Ignore tailing slash if it is */ *r = 0; return mkdir(abs, mode); } #else /* not __EMX__ */ #ifdef __MINGW32_VERSION #define do_mkdir(dir,mode) mkdir(dir) #else #define do_mkdir(dir,mode) mkdir(dir,mode) #endif /* not __MINW32_VERSION */ #endif /* not __EMX__ */ static void loadSiteconf(void); void sync_with_option(void) { if (PagerMax < LINES) PagerMax = LINES; WrapSearch = WrapDefault; parse_proxy(); #ifdef USE_COOKIE parse_cookie(); #endif initMailcap(); initMimeTypes(); #ifdef USE_EXTERNAL_URI_LOADER initURIMethods(); #endif #ifdef USE_MIGEMO init_migemo(); #endif #ifdef USE_IMAGE if (fmInitialized && displayImage) initImage(); #else displayImage = FALSE; /* XXX */ #endif loadPasswd(); loadPreForm(); loadSiteconf(); if (AcceptLang == NULL || *AcceptLang == '\0') { /* TRANSLATORS: * AcceptLang default: this is used in Accept-Language: HTTP request * header. For example, ja.po should translate it as * "ja;q=1.0, en;q=0.5" like that. */ AcceptLang = _("en;q=1.0"); } if (AcceptEncoding == NULL || *AcceptEncoding == '\0') AcceptEncoding = acceptableEncoding(); if (AcceptMedia == NULL || *AcceptMedia == '\0') AcceptMedia = acceptableMimeTypes(); #ifdef USE_UNICODE update_utf8_symbol(); #endif if (fmInitialized) { initKeymap(FALSE); #ifdef USE_MOUSE initMouseAction(); #endif /* MOUSE */ #ifdef USE_MENU initMenu(); #endif /* MENU */ } } void init_rc(void) { int i; struct stat st; FILE *f; if (rc_dir != NULL) goto open_rc; rc_dir = expandPath(RC_DIR); i = strlen(rc_dir); if (i > 1 && rc_dir[i - 1] == '/') rc_dir[i - 1] = '\0'; #ifdef USE_M17N display_charset_str = wc_get_ces_list(); document_charset_str = display_charset_str; system_charset_str = display_charset_str; #endif if (stat(rc_dir, &st) < 0) { if (errno == ENOENT) { /* no directory */ if (do_mkdir(rc_dir, 0700) < 0) { /* fprintf(stderr, "Can't create config directory (%s)!\n", rc_dir); */ goto rc_dir_err; } else { stat(rc_dir, &st); } } else { /* fprintf(stderr, "Can't open config directory (%s)!\n", rc_dir); */ goto rc_dir_err; } } if (!S_ISDIR(st.st_mode)) { /* not a directory */ /* fprintf(stderr, "%s is not a directory!\n", rc_dir); */ goto rc_dir_err; } if (!(st.st_mode & S_IWUSR)) { /* fprintf(stderr, "%s is not writable!\n", rc_dir); */ goto rc_dir_err; } no_rc_dir = FALSE; tmp_dir = rc_dir; if (config_file == NULL) config_file = rcFile(CONFIG_FILE); create_option_search_table(); open_rc: /* open config file */ if ((f = fopen(etcFile(W3MCONFIG), "rt")) != NULL) { interpret_rc(f); fclose(f); } if ((f = fopen(confFile(CONFIG_FILE), "rt")) != NULL) { interpret_rc(f); fclose(f); } if (config_file && (f = fopen(config_file, "rt")) != NULL) { interpret_rc(f); fclose(f); } return; rc_dir_err: no_rc_dir = TRUE; if (((tmp_dir = getenv("TMPDIR")) == NULL || *tmp_dir == '\0') && ((tmp_dir = getenv("TMP")) == NULL || *tmp_dir == '\0') && ((tmp_dir = getenv("TEMP")) == NULL || *tmp_dir == '\0')) tmp_dir = "/tmp"; #ifdef HAVE_MKDTEMP tmp_dir = mkdtemp(Strnew_m_charp(tmp_dir, "/w3m-XXXXXX", NULL)->ptr); if (tmp_dir == NULL) tmp_dir = rc_dir; #endif create_option_search_table(); goto open_rc; } static char optionpanel_src1[] = "<html><head><title>Option Setting Panel</title></head><body>\ <h1 align=center>Option Setting Panel<br>(w3m version %s)</b></h1>\ <form method=post action=\"file:///$LIB/" W3MHELPERPANEL_CMDNAME "\">\ <input type=hidden name=mode value=panel>\ <input type=hidden name=cookie value=\"%s\">\ <input type=submit value=\"%s\">\ </form><br>\ <form method=internal action=option>"; static Str optionpanel_str = NULL; static Str to_str(struct param_ptr *p) { switch (p->type) { case P_INT: #ifdef USE_COLOR case P_COLOR: #endif #ifdef USE_M17N case P_CODE: return Sprintf("%d", (int)(*(wc_ces *) p->varptr)); #endif case P_NZINT: return Sprintf("%d", *(int *)p->varptr); case P_SHORT: return Sprintf("%d", *(short *)p->varptr); case P_CHARINT: return Sprintf("%d", *(char *)p->varptr); case P_CHAR: return Sprintf("%c", *(char *)p->varptr); case P_STRING: #if defined(USE_SSL) && defined(USE_SSL_VERIFY) case P_SSLPATH: #endif /* SystemCharset -> InnerCharset */ return Strnew_charp(conv_from_system(*(char **)p->varptr)); case P_PIXELS: case P_SCALE: return Sprintf("%g", *(double *)p->varptr); } /* not reached */ return NULL; } Buffer * load_option_panel(void) { Str src; struct param_ptr *p; struct sel_c *s; #ifdef USE_M17N wc_ces_list *c; #endif int x, i; Str tmp; Buffer *buf; if (optionpanel_str == NULL) optionpanel_str = Sprintf(optionpanel_src1, w3m_version, html_quote(localCookie()->ptr), _(CMT_HELPER)); #ifdef USE_M17N #ifdef ENABLE_NLS OptionCharset = SystemCharset; /* FIXME */ #endif if (!OptionEncode) { optionpanel_str = wc_Str_conv(optionpanel_str, OptionCharset, InnerCharset); for (i = 0; sections[i].name != NULL; i++) { sections[i].name = wc_conv(_(sections[i].name), OptionCharset, InnerCharset)->ptr; for (p = sections[i].params; p->name; p++) { p->comment = wc_conv(_(p->comment), OptionCharset, InnerCharset)->ptr; if (p->inputtype == PI_SEL_C #ifdef USE_COLOR && p->select != colorstr #endif ) { for (s = (struct sel_c *)p->select; s->text != NULL; s++) { s->text = wc_conv(_(s->text), OptionCharset, InnerCharset)->ptr; } } } } #ifdef USE_COLOR for (s = colorstr; s->text; s++) s->text = wc_conv(_(s->text), OptionCharset, InnerCharset)->ptr; #endif OptionEncode = TRUE; } #endif src = Strdup(optionpanel_str); Strcat_charp(src, "<table><tr><td>"); for (i = 0; sections[i].name != NULL; i++) { Strcat_m_charp(src, "<h1>", sections[i].name, "</h1>", NULL); p = sections[i].params; Strcat_charp(src, "<table width=100% cellpadding=0>"); while (p->name) { Strcat_m_charp(src, "<tr><td>", p->comment, NULL); Strcat(src, Sprintf("</td><td width=%d>", (int)(28 * pixel_per_char))); switch (p->inputtype) { case PI_TEXT: Strcat_m_charp(src, "<input type=text name=", p->name, " value=\"", html_quote(to_str(p)->ptr), "\">", NULL); break; case PI_ONOFF: x = atoi(to_str(p)->ptr); Strcat_m_charp(src, "<input type=radio name=", p->name, " value=1", (x ? " checked" : ""), ">YES&nbsp;&nbsp;<input type=radio name=", p->name, " value=0", (x ? "" : " checked"), ">NO", NULL); break; case PI_SEL_C: tmp = to_str(p); Strcat_m_charp(src, "<select name=", p->name, ">", NULL); for (s = (struct sel_c *)p->select; s->text != NULL; s++) { Strcat_charp(src, "<option value="); Strcat(src, Sprintf("%s\n", s->cvalue)); if ((p->type != P_CHAR && s->value == atoi(tmp->ptr)) || (p->type == P_CHAR && (char)s->value == *(tmp->ptr))) Strcat_charp(src, " selected"); Strcat_char(src, '>'); Strcat_charp(src, s->text); } Strcat_charp(src, "</select>"); break; #ifdef USE_M17N case PI_CODE: tmp = to_str(p); Strcat_m_charp(src, "<select name=", p->name, ">", NULL); for (c = *(wc_ces_list **) p->select; c->desc != NULL; c++) { Strcat_charp(src, "<option value="); Strcat(src, Sprintf("%s\n", c->name)); if (c->id == atoi(tmp->ptr)) Strcat_charp(src, " selected"); Strcat_char(src, '>'); Strcat_charp(src, c->desc); } Strcat_charp(src, "</select>"); break; #endif } Strcat_charp(src, "</td></tr>\n"); p++; } Strcat_charp(src, "<tr><td></td><td><p><input type=submit value=\"OK\"></td></tr>"); Strcat_charp(src, "</table><hr width=50%>"); } Strcat_charp(src, "</table></form></body></html>"); buf = loadHTMLString(src); #ifdef USE_M17N if (buf) buf->document_charset = OptionCharset; #endif return buf; } void panel_set_option(struct parsed_tagarg *arg) { FILE *f = NULL; char *p; Str s = Strnew(), tmp; if (config_file == NULL) { disp_message("There's no config file... config not saved", FALSE); } else { f = fopen(config_file, "wt"); if (f == NULL) { disp_message("Can't write option!", FALSE); } } while (arg) { /* InnerCharset -> SystemCharset */ if (arg->value) { p = conv_to_system(arg->value); if (set_param(arg->arg, p)) { tmp = Sprintf("%s %s\n", arg->arg, p); Strcat(tmp, s); s = tmp; } } arg = arg->next; } if (f) { fputs(s->ptr, f); fclose(f); } sync_with_option(); backBf(); } char * rcFile(char *base) { if (base && (base[0] == '/' || (base[0] == '.' && (base[1] == '/' || (base[1] == '.' && base[2] == '/'))) || (base[0] == '~' && base[1] == '/'))) /* /file, ./file, ../file, ~/file */ return expandPath(base); return expandPath(Strnew_m_charp(rc_dir, "/", base, NULL)->ptr); } char * auxbinFile(char *base) { return expandPath(Strnew_m_charp(w3m_auxbin_dir(), "/", base, NULL)->ptr); } #if 0 /* not used */ char * libFile(char *base) { return expandPath(Strnew_m_charp(w3m_lib_dir(), "/", base, NULL)->ptr); } #endif char * etcFile(char *base) { return expandPath(Strnew_m_charp(w3m_etc_dir(), "/", base, NULL)->ptr); } char * confFile(char *base) { return expandPath(Strnew_m_charp(w3m_conf_dir(), "/", base, NULL)->ptr); } #ifndef USE_HELP_CGI char * helpFile(char *base) { return expandPath(Strnew_m_charp(w3m_help_dir(), "/", base, NULL)->ptr); } #endif /* siteconf */ /* * url "<url>"|/<re-url>/|m@<re-url>@i [exact] * substitute_url "<destination-url>" * url_charset <charset> * no_referer_from on|off * no_referer_to on|off * * The last match wins. */ struct siteconf_rec { struct siteconf_rec *next; char *url; Regex *re_url; int url_exact; unsigned char mask[(SCONF_N_FIELD + 7) >> 3]; char *substitute_url; #ifdef USE_M17N wc_ces url_charset; #endif int no_referer_from; int no_referer_to; }; #define SCONF_TEST(ent, f) ((ent)->mask[(f)>>3] & (1U<<((f)&7))) #define SCONF_SET(ent, f) ((ent)->mask[(f)>>3] |= (1U<<((f)&7))) #define SCONF_CLEAR(ent, f) ((ent)->mask[(f)>>3] &= ~(1U<<((f)&7))) static struct siteconf_rec *siteconf_head = NULL; static struct siteconf_rec *newSiteconfRec(void); static struct siteconf_rec * newSiteconfRec(void) { struct siteconf_rec *ent; ent = New(struct siteconf_rec); ent->next = NULL; ent->url = NULL; ent->re_url = NULL; ent->url_exact = FALSE; memset(ent->mask, 0, sizeof(ent->mask)); ent->substitute_url = NULL; #ifdef USE_M17N ent->url_charset = 0; #endif return ent; } static void loadSiteconf(void) { char *efname; FILE *fp; Str line; struct siteconf_rec *ent = NULL; siteconf_head = NULL; if (!siteconf_file) return; if ((efname = expandPath(siteconf_file)) == NULL) return; fp = fopen(efname, "r"); if (fp == NULL) return; while (line = Strfgets(fp), line->length > 0) { char *p, *s; Strchop(line); p = line->ptr; SKIP_BLANKS(p); if (*p == '#' || *p == '\0') continue; s = getWord(&p); /* The "url" begins a new record. */ if (strcmp(s, "url") == 0) { char *url, *opt; struct siteconf_rec *newent; /* First, register the current record. */ if (ent) { ent->next = siteconf_head; siteconf_head = ent; ent = NULL; } /* Second, create a new record. */ newent = newSiteconfRec(); url = getRegexWord((const char **)&p, &newent->re_url); opt = getWord(&p); SKIP_BLANKS(p); if (!newent->re_url) { ParsedURL pu; if (!url || !*url) continue; parseURL2(url, &pu, NULL); newent->url = parsedURL2Str(&pu)->ptr; } /* If we have an extra or unknown option, ignore this record * for future extensions. */ if (strcmp(opt, "exact") == 0) { newent->url_exact = TRUE; } else if (*opt != 0) continue; if (*p) continue; ent = newent; continue; } /* If the current record is broken, skip to the next "url". */ if (!ent) continue; /* Fill the new record. */ if (strcmp(s, "substitute_url") == 0) { ent->substitute_url = getQWord(&p); SCONF_SET(ent, SCONF_SUBSTITUTE_URL); } #ifdef USE_M17N else if (strcmp(s, "url_charset") == 0) { char *charset = getWord(&p); ent->url_charset = (charset && *charset) ? wc_charset_to_ces(charset) : 0; SCONF_SET(ent, SCONF_URL_CHARSET); } #endif /* USE_M17N */ else if (strcmp(s, "no_referer_from") == 0) { ent->no_referer_from = str_to_bool(getWord(&p), 0); SCONF_SET(ent, SCONF_NO_REFERER_FROM); } else if (strcmp(s, "no_referer_to") == 0) { ent->no_referer_to = str_to_bool(getWord(&p), 0); SCONF_SET(ent, SCONF_NO_REFERER_TO); } } if (ent) { ent->next = siteconf_head; siteconf_head = ent; ent = NULL; } fclose(fp); } const void * querySiteconf(const ParsedURL *query_pu, int field) { const struct siteconf_rec *ent; Str u; char *firstp, *lastp; if (field < 0 || field >= SCONF_N_FIELD) return NULL; if (!query_pu || IS_EMPTY_PARSED_URL(query_pu)) return NULL; u = parsedURL2Str((ParsedURL *)query_pu); if (u->length == 0) return NULL; for (ent = siteconf_head; ent; ent = ent->next) { if (!SCONF_TEST(ent, field)) continue; if (ent->re_url) { if (RegexMatch(ent->re_url, u->ptr, u->length, 1)) { MatchedPosition(ent->re_url, &firstp, &lastp); if (!ent->url_exact) goto url_found; if (firstp != u->ptr || lastp == firstp) continue; if (*lastp == 0 || *lastp == '?' || *(lastp - 1) == '?' || *lastp == '#' || *(lastp - 1) == '#') goto url_found; } } else { int matchlen = strmatchlen(ent->url, u->ptr, u->length); if (matchlen == 0 || ent->url[matchlen] != 0) continue; firstp = u->ptr; lastp = u->ptr + matchlen; if (*lastp == 0 || *lastp == '?' || *(lastp - 1) == '?' || *lastp == '#' || *(lastp - 1) == '#') goto url_found; if (!ent->url_exact && (*lastp == '/' || *(lastp - 1) == '/')) goto url_found; } } return NULL; url_found: switch (field) { case SCONF_SUBSTITUTE_URL: if (ent->substitute_url && *ent->substitute_url) { Str tmp = Strnew_charp_n(u->ptr, firstp - u->ptr); Strcat_charp(tmp, ent->substitute_url); Strcat_charp(tmp, lastp); return tmp->ptr; } return NULL; #ifdef USE_M17N case SCONF_URL_CHARSET: return &ent->url_charset; #endif case SCONF_NO_REFERER_FROM: return &ent->no_referer_from; case SCONF_NO_REFERER_TO: return &ent->no_referer_to; } return NULL; }
./CrossVul/dataset_final_sorted/CWE-59/c/good_589_5
crossvul-cpp_data_good_1591_0
/* abrt-hook-ccpp.cpp - the hook for C/C++ crashing program Copyright (C) 2009 Zdenek Prikryl (zprikryl@redhat.com) Copyright (C) 2009 RedHat inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <sys/utsname.h> #include "libabrt.h" #define DUMP_SUID_UNSAFE 1 #define DUMP_SUID_SAFE 2 /* I want to use -Werror, but gcc-4.4 throws a curveball: * "warning: ignoring return value of 'ftruncate', declared with attribute warn_unused_result" * and (void) cast is not enough to shut it up! Oh God... */ #define IGNORE_RESULT(func_call) do { if (func_call) /* nothing */; } while (0) static char* malloc_readlink(const char *linkname) { char buf[PATH_MAX + 1]; int len; len = readlink(linkname, buf, sizeof(buf)-1); if (len >= 0) { buf[len] = '\0'; return xstrdup(buf); } return NULL; } /* Custom version of copyfd_xyz, * one which is able to write into two descriptors at once. */ #define CONFIG_FEATURE_COPYBUF_KB 4 static off_t copyfd_sparse(int src_fd, int dst_fd1, int dst_fd2, off_t size2) { off_t total = 0; int last_was_seek = 0; #if CONFIG_FEATURE_COPYBUF_KB <= 4 char buffer[CONFIG_FEATURE_COPYBUF_KB * 1024]; enum { buffer_size = sizeof(buffer) }; #else char *buffer; int buffer_size; /* We want page-aligned buffer, just in case kernel is clever * and can do page-aligned io more efficiently */ buffer = mmap(NULL, CONFIG_FEATURE_COPYBUF_KB * 1024, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, /* ignored: */ -1, 0); buffer_size = CONFIG_FEATURE_COPYBUF_KB * 1024; if (buffer == MAP_FAILED) { buffer = alloca(4 * 1024); buffer_size = 4 * 1024; } #endif while (1) { ssize_t rd = safe_read(src_fd, buffer, buffer_size); if (!rd) { /* eof */ if (last_was_seek) { if (lseek(dst_fd1, -1, SEEK_CUR) < 0 || safe_write(dst_fd1, "", 1) != 1 || (dst_fd2 >= 0 && (lseek(dst_fd2, -1, SEEK_CUR) < 0 || safe_write(dst_fd2, "", 1) != 1 ) ) ) { perror_msg("Write error"); total = -1; goto out; } } /* all done */ goto out; } if (rd < 0) { perror_msg("Read error"); total = -1; goto out; } /* checking sparseness */ ssize_t cnt = rd; while (--cnt >= 0) { if (buffer[cnt] != 0) { /* not sparse */ errno = 0; ssize_t wr1 = full_write(dst_fd1, buffer, rd); ssize_t wr2 = (dst_fd2 >= 0 ? full_write(dst_fd2, buffer, rd) : rd); if (wr1 < rd || wr2 < rd) { perror_msg("Write error"); total = -1; goto out; } last_was_seek = 0; goto adv; } } /* sparse */ xlseek(dst_fd1, rd, SEEK_CUR); if (dst_fd2 >= 0) xlseek(dst_fd2, rd, SEEK_CUR); last_was_seek = 1; adv: total += rd; size2 -= rd; if (size2 < 0) dst_fd2 = -1; //TODO: truncate to 0 or even delete the second file //(currently we delete the file later) } out: #if CONFIG_FEATURE_COPYBUF_KB > 4 if (buffer_size != 4 * 1024) munmap(buffer, buffer_size); #endif return total; } /* Global data */ static char *user_pwd; static char *proc_pid_status; static struct dump_dir *dd; static int user_core_fd = -1; /* * %s - signal number * %c - ulimit -c value * %p - pid * %u - uid * %g - gid * %t - UNIX time of dump * %e - executable filename * %h - hostname * %% - output one "%" */ /* Hook must be installed with exactly the same sequence of %c specifiers. * Last one, %h, may be omitted (we can find it out). */ static const char percent_specifiers[] = "%scpugteh"; static char *core_basename = (char*) "core"; /* * Used for error messages only. * It is either the same as core_basename if it is absolute, * or $PWD/core_basename. */ static char *full_core_basename; static char* get_executable(pid_t pid, int *fd_p) { char buf[sizeof("/proc/%lu/exe") + sizeof(long)*3]; sprintf(buf, "/proc/%lu/exe", (long)pid); if (fd_p) *fd_p = open(buf, O_RDONLY); /* might fail and return -1, it's ok */ char *executable = malloc_readlink(buf); if (!executable) return NULL; /* find and cut off " (deleted)" from the path */ char *deleted = executable + strlen(executable) - strlen(" (deleted)"); if (deleted > executable && strcmp(deleted, " (deleted)") == 0) { *deleted = '\0'; log("File '%s' seems to be deleted", executable); } /* find and cut off prelink suffixes from the path */ char *prelink = executable + strlen(executable) - strlen(".#prelink#.XXXXXX"); if (prelink > executable && strncmp(prelink, ".#prelink#.", strlen(".#prelink#.")) == 0) { log("File '%s' seems to be a prelink temporary file", executable); *prelink = '\0'; } return executable; } static char* get_cwd(pid_t pid) { char buf[sizeof("/proc/%lu/cwd") + sizeof(long)*3]; sprintf(buf, "/proc/%lu/cwd", (long)pid); return malloc_readlink(buf); } static char* get_rootdir(pid_t pid) { char buf[sizeof("/proc/%lu/root") + sizeof(long)*3]; sprintf(buf, "/proc/%lu/root", (long)pid); return malloc_readlink(buf); } static int get_fsuid(void) { int real, euid, saved; /* if we fail to parse the uid, then make it root only readable to be safe */ int fs_uid = 0; char *line = proc_pid_status; /* never NULL */ for (;;) { if (strncmp(line, "Uid", 3) == 0) { int n = sscanf(line, "Uid:\t%d\t%d\t%d\t%d\n", &real, &euid, &saved, &fs_uid); if (n != 4) { perror_msg_and_die("Can't parse Uid: line"); } break; } line = strchr(line, '\n'); if (!line) break; line++; } return fs_uid; } static int dump_suid_policy() { /* - values are: 0 - don't dump suided programs - in this case the hook is not called by kernel 1 - create coredump readable by fs_uid 2 - create coredump readable by root only */ int c; int suid_dump_policy = 0; const char *filename = "/proc/sys/fs/suid_dumpable"; FILE *f = fopen(filename, "r"); if (!f) { log("Can't open %s", filename); return suid_dump_policy; } c = fgetc(f); fclose(f); if (c != EOF) suid_dump_policy = c - '0'; //log("suid dump policy is: %i", suid_dump_policy); return suid_dump_policy; } static int open_user_core(uid_t uid, uid_t fsuid, pid_t pid, char **percent_values) { errno = 0; if (user_pwd == NULL || chdir(user_pwd) != 0 ) { perror_msg("Can't cd to '%s'", user_pwd); return -1; } struct passwd* pw = getpwuid(uid); gid_t gid = pw ? pw->pw_gid : uid; //log("setting uid: %i gid: %i", uid, gid); xsetegid(gid); xseteuid(fsuid); if (strcmp(core_basename, "core") == 0) { /* Mimic "core.PID" if requested */ char buf[] = "0\n"; int fd = open("/proc/sys/kernel/core_uses_pid", O_RDONLY); if (fd >= 0) { IGNORE_RESULT(read(fd, buf, sizeof(buf))); close(fd); } if (strcmp(buf, "1\n") == 0) { core_basename = xasprintf("%s.%lu", core_basename, (long)pid); } } else { /* Expand old core pattern, put expanded name in core_basename */ core_basename = xstrdup(core_basename); unsigned idx = 0; while (1) { char c = core_basename[idx]; if (!c) break; idx++; if (c != '%') continue; /* We just copied %, look at following char and expand %c */ c = core_basename[idx]; unsigned specifier_num = strchrnul(percent_specifiers, c) - percent_specifiers; if (percent_specifiers[specifier_num] != '\0') /* valid %c (might be %% too) */ { const char *val = "%"; if (specifier_num > 0) /* not %% */ val = percent_values[specifier_num - 1]; //log("c:'%c'", c); //log("val:'%s'", val); /* Replace %c at core_basename[idx] by its value */ idx--; char *old = core_basename; core_basename = xasprintf("%.*s%s%s", idx, core_basename, val, core_basename + idx + 2); //log("pos:'%*s|'", idx, ""); //log("new:'%s'", core_basename); //log("old:'%s'", old); free(old); idx += strlen(val); } /* else: invalid %c, % is already copied verbatim, * next loop iteration will copy c */ } } full_core_basename = core_basename; if (core_basename[0] != '/') core_basename = concat_path_file(user_pwd, core_basename); /* Open (create) compat core file. * man core: * There are various circumstances in which a core dump file * is not produced: * * [skipped obvious ones] * The process does not have permission to write the core file. * ...if a file with the same name exists and is not writable * or is not a regular file (e.g., it is a directory or a symbolic link). * * A file with the same name already exists, but there is more * than one hard link to that file. * * The file system where the core dump file would be created is full; * or has run out of inodes; or is mounted read-only; * or the user has reached their quota for the file system. * * The RLIMIT_CORE or RLIMIT_FSIZE resource limits for the process * are set to zero. * [we check RLIMIT_CORE, but how can we check RLIMIT_FSIZE?] * * The binary being executed by the process does not have * read permission enabled. [how we can check it here?] * * The process is executing a set-user-ID (set-group-ID) program * that is owned by a user (group) other than the real * user (group) ID of the process. [TODO?] * (However, see the description of the prctl(2) PR_SET_DUMPABLE operation, * and the description of the /proc/sys/fs/suid_dumpable file in proc(5).) */ struct stat sb; errno = 0; /* Do not O_TRUNC: if later checks fail, we do not want to have file already modified here */ int user_core_fd = open(core_basename, O_WRONLY | O_CREAT | O_NOFOLLOW, 0600); /* kernel makes 0600 too */ xsetegid(0); xseteuid(0); if (user_core_fd < 0 || fstat(user_core_fd, &sb) != 0 || !S_ISREG(sb.st_mode) || sb.st_nlink != 1 /* kernel internal dumper checks this too: if (inode->i_uid != current->fsuid) <fail>, need to mimic? */ ) { if (user_core_fd < 0) perror_msg("Can't open '%s'", full_core_basename); else perror_msg("'%s' is not a regular file with link count 1", full_core_basename); return -1; } if (ftruncate(user_core_fd, 0) != 0) { /* perror first, otherwise unlink may trash errno */ perror_msg("Can't truncate '%s' to size 0", full_core_basename); unlink(core_basename); return -1; } return user_core_fd; } static bool dump_fd_info(const char *dest_filename, char *source_filename, int source_base_ofs, uid_t uid, gid_t gid) { FILE *fp = fopen(dest_filename, "w"); if (!fp) return false; unsigned fd = 0; while (fd <= 99999) /* paranoia check */ { sprintf(source_filename + source_base_ofs, "fd/%u", fd); char *name = malloc_readlink(source_filename); if (!name) break; fprintf(fp, "%u:%s\n", fd, name); free(name); sprintf(source_filename + source_base_ofs, "fdinfo/%u", fd); fd++; FILE *in = fopen(source_filename, "r"); if (!in) continue; char buf[128]; while (fgets(buf, sizeof(buf)-1, in)) { /* in case the line is not terminated, terminate it */ char *eol = strchrnul(buf, '\n'); eol[0] = '\n'; eol[1] = '\0'; fputs(buf, fp); } fclose(in); } const int dest_fd = fileno(fp); if (fchown(dest_fd, uid, gid) < 0) { perror_msg("Can't change '%s' ownership to %lu:%lu", dest_filename, (long)uid, (long)gid); fclose(fp); unlink(dest_filename); return false; } fclose(fp); return true; } /* Like xopen, but on error, unlocks and deletes dd and user core */ static int create_or_die(const char *filename) { int fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, DEFAULT_DUMP_DIR_MODE); if (fd >= 0) { IGNORE_RESULT(fchown(fd, dd->dd_uid, dd->dd_gid)); return fd; } int sv_errno = errno; if (dd) dd_delete(dd); if (user_core_fd >= 0) { xchdir(user_pwd); unlink(core_basename); } errno = sv_errno; perror_msg_and_die("Can't open '%s'", filename); } int main(int argc, char** argv) { /* Kernel starts us with all fd's closed. * But it's dangerous: * fprintf(stderr) can dump messages into random fds, etc. * Ensure that if any of fd 0,1,2 is closed, we open it to /dev/null. */ int fd = xopen("/dev/null", O_RDWR); while (fd < 2) fd = xdup(fd); if (fd > 2) close(fd); if (argc < 8) { /* percent specifier: %s %c %p %u %g %t %e %h */ /* argv: [0] [1] [2] [3] [4] [5] [6] [7] [8]*/ error_msg_and_die("Usage: %s SIGNO CORE_SIZE_LIMIT PID UID GID TIME BINARY_NAME [HOSTNAME]", argv[0]); } /* Not needed on 2.6.30. * At least 2.6.18 has a bug where * argv[1] = "SIGNO CORE_SIZE_LIMIT PID ..." * argv[2] = "CORE_SIZE_LIMIT PID ..." * and so on. Fixing it: */ if (strchr(argv[1], ' ')) { int i; for (i = 1; argv[i]; i++) { strchrnul(argv[i], ' ')[0] = '\0'; } } logmode = LOGMODE_JOURNAL; /* Parse abrt.conf */ load_abrt_conf(); /* ... and plugins/CCpp.conf */ bool setting_MakeCompatCore; bool setting_SaveBinaryImage; { map_string_t *settings = new_map_string(); load_abrt_plugin_conf_file("CCpp.conf", settings); const char *value; value = get_map_string_item_or_NULL(settings, "MakeCompatCore"); setting_MakeCompatCore = value && string_to_bool(value); value = get_map_string_item_or_NULL(settings, "SaveBinaryImage"); setting_SaveBinaryImage = value && string_to_bool(value); value = get_map_string_item_or_NULL(settings, "VerboseLog"); if (value) g_verbose = xatoi_positive(value); free_map_string(settings); } errno = 0; const char* signal_str = argv[1]; int signal_no = xatoi_positive(signal_str); off_t ulimit_c = strtoull(argv[2], NULL, 10); if (ulimit_c < 0) /* unlimited? */ { /* set to max possible >0 value */ ulimit_c = ~((off_t)1 << (sizeof(off_t)*8-1)); } const char *pid_str = argv[3]; pid_t pid = xatoi_positive(argv[3]); uid_t uid = xatoi_positive(argv[4]); if (errno || pid <= 0) { perror_msg_and_die("PID '%s' or limit '%s' is bogus", argv[3], argv[2]); } { char *s = xmalloc_fopen_fgetline_fclose(VAR_RUN"/abrt/saved_core_pattern"); /* If we have a saved pattern and it's not a "|PROG ARGS" thing... */ if (s && s[0] != '|') core_basename = s; else free(s); } struct utsname uts; if (!argv[8]) /* no HOSTNAME? */ { uname(&uts); argv[8] = uts.nodename; } char path[PATH_MAX]; int src_fd_binary = -1; char *executable = get_executable(pid, setting_SaveBinaryImage ? &src_fd_binary : NULL); if (executable && strstr(executable, "/abrt-hook-ccpp")) { error_msg_and_die("PID %lu is '%s', not dumping it to avoid recursion", (long)pid, executable); } user_pwd = get_cwd(pid); /* may be NULL on error */ log_notice("user_pwd:'%s'", user_pwd); sprintf(path, "/proc/%lu/status", (long)pid); proc_pid_status = xmalloc_xopen_read_close(path, /*maxsz:*/ NULL); uid_t fsuid = uid; uid_t tmp_fsuid = get_fsuid(); int suid_policy = dump_suid_policy(); if (tmp_fsuid != uid) { /* use root for suided apps unless it's explicitly set to UNSAFE */ fsuid = 0; if (suid_policy == DUMP_SUID_UNSAFE) { fsuid = tmp_fsuid; } } /* Open a fd to compat coredump, if requested and is possible */ if (setting_MakeCompatCore && ulimit_c != 0) /* note: checks "user_pwd == NULL" inside; updates core_basename */ user_core_fd = open_user_core(uid, fsuid, pid, &argv[1]); if (executable == NULL) { /* readlink on /proc/$PID/exe failed, don't create abrt dump dir */ error_msg("Can't read /proc/%lu/exe link", (long)pid); goto create_user_core; } const char *signame = NULL; switch (signal_no) { case SIGILL : signame = "ILL" ; break; case SIGFPE : signame = "FPE" ; break; case SIGSEGV: signame = "SEGV"; break; case SIGBUS : signame = "BUS" ; break; //Bus error (bad memory access) case SIGABRT: signame = "ABRT"; break; //usually when abort() was called // We have real-world reports from users who see buggy programs // dying with SIGTRAP, uncommented it too: case SIGTRAP: signame = "TRAP"; break; //Trace/breakpoint trap // These usually aren't caused by bugs: //case SIGQUIT: signame = "QUIT"; break; //Quit from keyboard //case SIGSYS : signame = "SYS" ; break; //Bad argument to routine (SVr4) //case SIGXCPU: signame = "XCPU"; break; //CPU time limit exceeded (4.2BSD) //case SIGXFSZ: signame = "XFSZ"; break; //File size limit exceeded (4.2BSD) default: goto create_user_core; // not a signal we care about } if (!daemon_is_ok()) { /* not an error, exit with exit code 0 */ log("abrtd is not running. If it crashed, " "/proc/sys/kernel/core_pattern contains a stale value, " "consider resetting it to 'core'" ); goto create_user_core; } if (g_settings_nMaxCrashReportsSize > 0) { /* If free space is less than 1/4 of MaxCrashReportsSize... */ if (low_free_space(g_settings_nMaxCrashReportsSize, g_settings_dump_location)) goto create_user_core; } /* Check /var/tmp/abrt/last-ccpp marker, do not dump repeated crashes * if they happen too often. Else, write new marker value. */ snprintf(path, sizeof(path), "%s/last-ccpp", g_settings_dump_location); if (check_recent_crash_file(path, executable)) { /* It is a repeating crash */ goto create_user_core; } const char *last_slash = strrchr(executable, '/'); if (last_slash && strncmp(++last_slash, "abrt", 4) == 0) { /* If abrtd/abrt-foo crashes, we don't want to create a _directory_, * since that can make new copy of abrtd to process it, * and maybe crash again... * Unlike dirs, mere files are ignored by abrtd. */ snprintf(path, sizeof(path), "%s/%s-coredump", g_settings_dump_location, last_slash); int abrt_core_fd = xopen3(path, O_WRONLY | O_CREAT | O_TRUNC, 0600); off_t core_size = copyfd_eof(STDIN_FILENO, abrt_core_fd, COPYFD_SPARSE); if (core_size < 0 || fsync(abrt_core_fd) != 0) { unlink(path); /* copyfd_eof logs the error including errno string, * but it does not log file name */ error_msg_and_die("Error saving '%s'", path); } log("Saved core dump of pid %lu (%s) to %s (%llu bytes)", (long)pid, executable, path, (long long)core_size); return 0; } unsigned path_len = snprintf(path, sizeof(path), "%s/ccpp-%s-%lu.new", g_settings_dump_location, iso_date_string(NULL), (long)pid); if (path_len >= (sizeof(path) - sizeof("/"FILENAME_COREDUMP))) { goto create_user_core; } /* use fsuid instead of uid, so we don't expose any sensitive * information of suided app in /var/tmp/abrt */ dd = dd_create(path, fsuid, DEFAULT_DUMP_DIR_MODE); if (dd) { char *rootdir = get_rootdir(pid); dd_create_basic_files(dd, fsuid, NULL); char source_filename[sizeof("/proc/%lu/somewhat_long_name") + sizeof(long)*3]; int source_base_ofs = sprintf(source_filename, "/proc/%lu/smaps", (long)pid); source_base_ofs -= strlen("smaps"); char *dest_filename = concat_path_file(dd->dd_dirname, "also_somewhat_longish_name"); char *dest_base = strrchr(dest_filename, '/') + 1; // Disabled for now: /proc/PID/smaps tends to be BIG, // and not much more informative than /proc/PID/maps: //copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL); strcpy(source_filename + source_base_ofs, "maps"); strcpy(dest_base, FILENAME_MAPS); copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL); strcpy(source_filename + source_base_ofs, "limits"); strcpy(dest_base, FILENAME_LIMITS); copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL); strcpy(source_filename + source_base_ofs, "cgroup"); strcpy(dest_base, FILENAME_CGROUP); copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL); strcpy(dest_base, FILENAME_OPEN_FDS); dump_fd_info(dest_filename, source_filename, source_base_ofs, dd->dd_uid, dd->dd_gid); free(dest_filename); dd_save_text(dd, FILENAME_ANALYZER, "CCpp"); dd_save_text(dd, FILENAME_TYPE, "CCpp"); dd_save_text(dd, FILENAME_EXECUTABLE, executable); dd_save_text(dd, FILENAME_PID, pid_str); dd_save_text(dd, FILENAME_PROC_PID_STATUS, proc_pid_status); if (user_pwd) dd_save_text(dd, FILENAME_PWD, user_pwd); if (rootdir) { if (strcmp(rootdir, "/") != 0) dd_save_text(dd, FILENAME_ROOTDIR, rootdir); } char *reason = xasprintf("%s killed by SIG%s", last_slash, signame ? signame : signal_str); dd_save_text(dd, FILENAME_REASON, reason); free(reason); char *cmdline = get_cmdline(pid); dd_save_text(dd, FILENAME_CMDLINE, cmdline ? : ""); free(cmdline); char *environ = get_environ(pid); dd_save_text(dd, FILENAME_ENVIRON, environ ? : ""); free(environ); char *fips_enabled = xmalloc_fopen_fgetline_fclose("/proc/sys/crypto/fips_enabled"); if (fips_enabled) { if (strcmp(fips_enabled, "0") != 0) dd_save_text(dd, "fips_enabled", fips_enabled); free(fips_enabled); } dd_save_text(dd, FILENAME_ABRT_VERSION, VERSION); if (src_fd_binary > 0) { strcpy(path + path_len, "/"FILENAME_BINARY); int dst_fd = create_or_die(path); off_t sz = copyfd_eof(src_fd_binary, dst_fd, COPYFD_SPARSE); if (fsync(dst_fd) != 0 || close(dst_fd) != 0 || sz < 0) { dd_delete(dd); error_msg_and_die("Error saving '%s'", path); } close(src_fd_binary); } strcpy(path + path_len, "/"FILENAME_COREDUMP); int abrt_core_fd = create_or_die(path); /* We write both coredumps at once. * We can't write user coredump first, since it might be truncated * and thus can't be copied and used as abrt coredump; * and if we write abrt coredump first and then copy it as user one, * then we have a race when process exits but coredump does not exist yet: * $ echo -e '#include<signal.h>\nmain(){raise(SIGSEGV);}' | gcc -o test -x c - * $ rm -f core*; ulimit -c unlimited; ./test; ls -l core* * 21631 Segmentation fault (core dumped) ./test * ls: cannot access core*: No such file or directory <=== BAD */ off_t core_size = copyfd_sparse(STDIN_FILENO, abrt_core_fd, user_core_fd, ulimit_c); if (fsync(abrt_core_fd) != 0 || close(abrt_core_fd) != 0 || core_size < 0) { unlink(path); dd_delete(dd); if (user_core_fd >= 0) { xchdir(user_pwd); unlink(core_basename); } /* copyfd_sparse logs the error including errno string, * but it does not log file name */ error_msg_and_die("Error writing '%s'", path); } if (user_core_fd >= 0 /* error writing user coredump? */ && (fsync(user_core_fd) != 0 || close(user_core_fd) != 0 /* user coredump is too big? */ || (ulimit_c == 0 /* paranoia */ || core_size > ulimit_c) ) ) { /* nuke it (silently) */ xchdir(user_pwd); unlink(core_basename); } /* Because of #1211835 and #1126850 */ #if 0 /* Save JVM crash log if it exists. (JVM's coredump per se * is nearly useless for JVM developers) */ { char *java_log = xasprintf("/tmp/jvm-%lu/hs_error.log", (long)pid); int src_fd = open(java_log, O_RDONLY); free(java_log); /* If we couldn't open the error log in /tmp directory we can try to * read the log from the current directory. It may produce AVC, it * may produce some error log but all these are expected. */ if (src_fd < 0) { java_log = xasprintf("%s/hs_err_pid%lu.log", user_pwd, (long)pid); src_fd = open(java_log, O_RDONLY); free(java_log); } if (src_fd >= 0) { strcpy(path + path_len, "/hs_err.log"); int dst_fd = create_or_die(path); off_t sz = copyfd_eof(src_fd, dst_fd, COPYFD_SPARSE); if (close(dst_fd) != 0 || sz < 0) { dd_delete(dd); error_msg_and_die("Error saving '%s'", path); } close(src_fd); } } #endif /* We close dumpdir before we start catering for crash storm case. * Otherwise, delete_dump_dir's from other concurrent * CCpp's won't be able to delete our dump (their delete_dump_dir * will wait for us), and we won't be able to delete their dumps. * Classic deadlock. */ dd_close(dd); path[path_len] = '\0'; /* path now contains only directory name */ char *newpath = xstrndup(path, path_len - (sizeof(".new")-1)); if (rename(path, newpath) == 0) strcpy(path, newpath); free(newpath); log("Saved core dump of pid %lu (%s) to %s (%llu bytes)", (long)pid, executable, path, (long long)core_size); notify_new_path(path); /* rhbz#539551: "abrt going crazy when crashing process is respawned" */ if (g_settings_nMaxCrashReportsSize > 0) { /* x1.25 and round up to 64m: go a bit up, so that usual in-daemon trimming * kicks in first, and we don't "fight" with it: */ unsigned maxsize = g_settings_nMaxCrashReportsSize + g_settings_nMaxCrashReportsSize / 4; maxsize |= 63; trim_problem_dirs(g_settings_dump_location, maxsize * (double)(1024*1024), path); } free(rootdir); return 0; } /* We didn't create abrt dump, but may need to create compat coredump */ create_user_core: if (user_core_fd >= 0) { off_t core_size = copyfd_size(STDIN_FILENO, user_core_fd, ulimit_c, COPYFD_SPARSE); if (fsync(user_core_fd) != 0 || close(user_core_fd) != 0 || core_size < 0) { /* perror first, otherwise unlink may trash errno */ perror_msg("Error writing '%s'", full_core_basename); xchdir(user_pwd); unlink(core_basename); return 1; } if (ulimit_c == 0 || core_size > ulimit_c) { xchdir(user_pwd); unlink(core_basename); return 1; } log("Saved core dump of pid %lu to %s (%llu bytes)", (long)pid, full_core_basename, (long long)core_size); } return 0; }
./CrossVul/dataset_final_sorted/CWE-59/c/good_1591_0
crossvul-cpp_data_bad_3576_1
/* * internal.c: internal data structures and helpers * * Copyright (C) 2007-2011 David Lutterkort * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: David Lutterkort <dlutter@redhat.com> */ #include <config.h> #include <ctype.h> #include <stdio.h> #include <stdarg.h> #include <locale.h> #include "internal.h" #include "memory.h" #include "fa.h" #ifndef MIN # define MIN(a, b) ((a) < (b) ? (a) : (b)) #endif /* Cap file reads somwhat arbitrarily at 32 MB */ #define MAX_READ_LEN (32*1024*1024) int pathjoin(char **path, int nseg, ...) { va_list ap; va_start(ap, nseg); for (int i=0; i < nseg; i++) { const char *seg = va_arg(ap, const char *); if (seg == NULL) seg = "()"; int len = strlen(seg) + 1; if (*path != NULL) { len += strlen(*path) + 1; if (REALLOC_N(*path, len) == -1) { FREE(*path); return -1; } if (strlen(*path) == 0 || (*path)[strlen(*path)-1] != SEP) strcat(*path, "/"); if (seg[0] == SEP) seg += 1; strcat(*path, seg); } else { if ((*path = malloc(len)) == NULL) return -1; strcpy(*path, seg); } } va_end(ap); return 0; } /* Like gnulib's fread_file, but read no more than the specified maximum number of bytes. If the length of the input is <= max_len, and upon error while reading that data, it works just like fread_file. Taken verbatim from libvirt's util.c */ static char * fread_file_lim (FILE *stream, size_t max_len, size_t *length) { char *buf = NULL; size_t alloc = 0; size_t size = 0; int save_errno; for (;;) { size_t count; size_t requested; if (size + BUFSIZ + 1 > alloc) { char *new_buf; alloc += alloc / 2; if (alloc < size + BUFSIZ + 1) alloc = size + BUFSIZ + 1; new_buf = realloc (buf, alloc); if (!new_buf) { save_errno = errno; break; } buf = new_buf; } /* Ensure that (size + requested <= max_len); */ requested = MIN (size < max_len ? max_len - size : 0, alloc - size - 1); count = fread (buf + size, 1, requested, stream); size += count; if (count != requested || requested == 0) { save_errno = errno; if (ferror (stream)) break; buf[size] = '\0'; *length = size; return buf; } } free (buf); errno = save_errno; return NULL; } char* xread_file(const char *path) { FILE *fp = fopen(path, "r"); char *result; size_t len; if (!fp) return NULL; result = fread_file_lim(fp, MAX_READ_LEN, &len); fclose (fp); if (result != NULL && len <= MAX_READ_LEN && (int) len == len) return result; free(result); return NULL; } /* * Escape/unescape of string literals */ static const char *const escape_chars = "\a\b\t\n\v\f\r"; static const char *const escape_names = "abtnvfr"; char *unescape(const char *s, int len, const char *extra) { size_t size; const char *n; char *result, *t; int i; if (len < 0 || len > strlen(s)) len = strlen(s); size = 0; for (i=0; i < len; i++, size++) { if (s[i] == '\\' && strchr(escape_names, s[i+1])) { i += 1; } else if (s[i] == '\\' && extra && strchr(extra, s[i+1])) { i += 1; } } if (ALLOC_N(result, size + 1) < 0) return NULL; for (i = 0, t = result; i < len; i++, size++) { if (s[i] == '\\' && (n = strchr(escape_names, s[i+1])) != NULL) { *t++ = escape_chars[n - escape_names]; i += 1; } else if (s[i] == '\\' && extra && strchr(extra, s[i+1]) != NULL) { *t++ = s[i+1]; i += 1; } else { *t++ = s[i]; } } return result; } char *escape(const char *text, int cnt, const char *extra) { int len = 0; char *esc = NULL, *e; if (cnt < 0 || cnt > strlen(text)) cnt = strlen(text); for (int i=0; i < cnt; i++) { if (text[i] && (strchr(escape_chars, text[i]) != NULL)) len += 2; /* Escaped as '\x' */ else if (text[i] && extra && (strchr(extra, text[i]) != NULL)) len += 2; /* Escaped as '\x' */ else if (! isprint(text[i])) len += 4; /* Escaped as '\ooo' */ else len += 1; } if (ALLOC_N(esc, len+1) < 0) return NULL; e = esc; for (int i=0; i < cnt; i++) { char *p; if (text[i] && ((p = strchr(escape_chars, text[i])) != NULL)) { *e++ = '\\'; *e++ = escape_names[p - escape_chars]; } else if (text[i] && extra && (strchr(extra, text[i]) != NULL)) { *e++ = '\\'; *e++ = text[i]; } else if (! isprint(text[i])) { sprintf(e, "\\%03o", (unsigned char) text[i]); e += 4; } else { *e++ = text[i]; } } return esc; } int print_chars(FILE *out, const char *text, int cnt) { int total = 0; char *esc; if (text == NULL) { fprintf(out, "nil"); return 3; } if (cnt < 0) cnt = strlen(text); esc = escape(text, cnt, NULL); total = strlen(esc); if (out != NULL) fprintf(out, "%s", esc); free(esc); return total; } char *format_pos(const char *text, int pos) { static const int window = 28; char *buf = NULL, *left = NULL, *right = NULL; int before = pos; int llen, rlen; int r; if (before > window) before = window; left = escape(text + pos - before, before, NULL); if (left == NULL) goto done; right = escape(text + pos, window, NULL); if (right == NULL) goto done; llen = strlen(left); rlen = strlen(right); if (llen < window && rlen < window) { r = asprintf(&buf, "%*s%s|=|%s%-*s\n", window - llen, "<", left, right, window - rlen, ">"); } else if (strlen(left) < window) { r = asprintf(&buf, "%*s%s|=|%s>\n", window - llen, "<", left, right); } else if (strlen(right) < window) { r = asprintf(&buf, "<%s|=|%s%-*s\n", left, right, window - rlen, ">"); } else { r = asprintf(&buf, "<%s|=|%s>\n", left, right); } if (r < 0) { buf = NULL; } done: free(left); free(right); return buf; } void print_pos(FILE *out, const char *text, int pos) { char *format = format_pos(text, pos); if (format != NULL) { fputs(format, out); FREE(format); } } int __aug_init_memstream(struct memstream *ms) { MEMZERO(ms, 1); #if HAVE_OPEN_MEMSTREAM ms->stream = open_memstream(&(ms->buf), &(ms->size)); return ms->stream == NULL ? -1 : 0; #else ms->stream = tmpfile(); if (ms->stream == NULL) { return -1; } return 0; #endif } int __aug_close_memstream(struct memstream *ms) { #if !HAVE_OPEN_MEMSTREAM rewind(ms->stream); ms->buf = fread_file_lim(ms->stream, MAX_READ_LEN, &(ms->size)); #endif if (fclose(ms->stream) == EOF) { FREE(ms->buf); ms->size = 0; return -1; } return 0; } char *path_expand(struct tree *tree, const char *ppath) { struct tree *siblings = tree->parent->children; char *path; const char *label; int cnt = 0, ind = 0, r; list_for_each(t, siblings) { if (streqv(t->label, tree->label)) { cnt += 1; if (t == tree) ind = cnt; } } if (ppath == NULL) ppath = ""; if (tree == NULL) label = "(no_tree)"; else if (tree->label == NULL) label = "(none)"; else label = tree->label; if (cnt > 1) { r = asprintf(&path, "%s/%s[%d]", ppath, label, ind); } else { r = asprintf(&path, "%s/%s", ppath, label); } if (r == -1) return NULL; return path; } char *path_of_tree(struct tree *tree) { int depth, i; struct tree *t, **anc; char *path = NULL; for (t = tree, depth = 1; ! ROOT_P(t); depth++, t = t->parent); if (ALLOC_N(anc, depth) < 0) return NULL; for (t = tree, i = depth - 1; i >= 0; i--, t = t->parent) anc[i] = t; for (i = 0; i < depth; i++) { char *p = path_expand(anc[i], path); free(path); path = p; } FREE(anc); return path; } /* User-facing path cleaning */ static char *cleanstr(char *path, const char sep) { if (path == NULL || strlen(path) == 0) return path; char *e = path + strlen(path) - 1; while (e >= path && (*e == sep || isspace(*e))) *e-- = '\0'; return path; } char *cleanpath(char *path) { if (path == NULL || strlen(path) == 0) return path; if (STREQ(path, "/")) return path; return cleanstr(path, SEP); } const char *xstrerror(int errnum, char *buf, size_t len) { #ifdef HAVE_STRERROR_R # ifdef __USE_GNU /* Annoying linux specific API contract */ return strerror_r(errnum, buf, len); # else strerror_r(errnum, buf, len); return buf; # endif #else int n = snprintf(buf, len, "errno=%d", errnum); return (0 < n && n < len ? buf : "internal error: buffer too small in xstrerror"); #endif } int xasprintf(char **strp, const char *format, ...) { va_list args; int result; va_start (args, format); result = vasprintf (strp, format, args); va_end (args); if (result < 0) *strp = NULL; return result; } /* From libvirt's src/xen/block_stats.c */ int xstrtoint64(char const *s, int base, int64_t *result) { long long int lli; char *p; errno = 0; lli = strtoll(s, &p, base); if (errno || !(*p == 0 || *p == '\n') || p == s || (int64_t) lli != lli) return -1; *result = lli; return 0; } void calc_line_ofs(const char *text, size_t pos, size_t *line, size_t *ofs) { *line = 1; *ofs = 0; for (const char *t = text; t < text + pos; t++) { *ofs += 1; if (*t == '\n') { *ofs = 0; *line += 1; } } } #if HAVE_USELOCALE int regexp_c_locale(ATTRIBUTE_UNUSED char **u, ATTRIBUTE_UNUSED size_t *len) { /* On systems with uselocale, we are ok, since we make sure that we * switch to the "C" locale any time we enter through the public API */ return 0; } #else int regexp_c_locale(char **u, size_t *len) { /* Without uselocale, we need to expand character ranges */ int r; char *s = *u; size_t s_len, u_len; if (len == NULL) { len = &u_len; s_len = strlen(s); } else { s_len = *len; } r = fa_expand_char_ranges(s, s_len, u, len); if (r != 0) { *u = s; *len = s_len; } if (r < 0) return -1; /* Syntax errors will be caught when the result is compiled */ if (r > 0) return 0; free(s); return 1; } #endif #if ENABLE_DEBUG bool debugging(const char *category) { const char *debug = getenv("AUGEAS_DEBUG"); const char *s; if (debug == NULL) return false; for (s = debug; s != NULL; ) { if (STREQLEN(s, category, strlen(category))) return true; s = strchr(s, ':'); if (s != NULL) s+=1; } return false; } FILE *debug_fopen(const char *format, ...) { va_list ap; FILE *result = NULL; const char *dir; char *name = NULL, *path = NULL; int r; dir = getenv("AUGEAS_DEBUG_DIR"); if (dir == NULL) goto error; va_start(ap, format); r = vasprintf(&name, format, ap); va_end(ap); if (r < 0) goto error; r = xasprintf(&path, "%s/%s", dir, name); if (r < 0) goto error; result = fopen(path, "w"); error: free(name); free(path); return result; } #endif /* * Local variables: * indent-tabs-mode: nil * c-indent-level: 4 * c-basic-offset: 4 * tab-width: 4 * End: */
./CrossVul/dataset_final_sorted/CWE-59/c/bad_3576_1
crossvul-cpp_data_good_589_4
/* $Id: main.c,v 1.270 2010/08/24 10:11:51 htrb Exp $ */ #define MAINPROGRAM #include "fm.h" #include <stdio.h> #include <signal.h> #include <setjmp.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include <fcntl.h> #if defined(HAVE_WAITPID) || defined(HAVE_WAIT3) #include <sys/wait.h> #endif #include <time.h> #if defined(__CYGWIN__) && defined(USE_BINMODE_STREAM) #include <io.h> #endif #include "terms.h" #include "myctype.h" #include "regex.h" #ifdef USE_M17N #include "wc.h" #include "wtf.h" #ifdef USE_UNICODE #include "ucs.h" #endif #endif #ifdef USE_MOUSE #ifdef USE_GPM #include <gpm.h> #endif /* USE_GPM */ #if defined(USE_GPM) || defined(USE_SYSMOUSE) extern int do_getch(); #define getch() do_getch() #endif /* defined(USE_GPM) || defined(USE_SYSMOUSE) */ #endif #ifdef __MINGW32_VERSION #include <winsock.h> WSADATA WSAData; #endif #define DSTR_LEN 256 Hist *LoadHist; Hist *SaveHist; Hist *URLHist; Hist *ShellHist; Hist *TextHist; typedef struct _Event { int cmd; void *data; struct _Event *next; } Event; static Event *CurrentEvent = NULL; static Event *LastEvent = NULL; #ifdef USE_ALARM static AlarmEvent DefaultAlarm = { 0, AL_UNSET, FUNCNAME_nulcmd, NULL }; static AlarmEvent *CurrentAlarm = &DefaultAlarm; static MySignalHandler SigAlarm(SIGNAL_ARG); #endif #ifdef SIGWINCH static int need_resize_screen = FALSE; static MySignalHandler resize_hook(SIGNAL_ARG); static void resize_screen(void); #endif #ifdef SIGPIPE static MySignalHandler SigPipe(SIGNAL_ARG); #endif #ifdef USE_MARK static char *MarkString = NULL; #endif static char *SearchString = NULL; int (*searchRoutine) (Buffer *, char *); #ifndef __MINGW32_VERSION JMP_BUF IntReturn; #else _JBTYPE IntReturn[_JBLEN]; #endif /* __MINGW32_VERSION */ static void delBuffer(Buffer *buf); static void cmd_loadfile(char *path); static void cmd_loadURL(char *url, ParsedURL *current, char *referer, FormList *request); static void cmd_loadBuffer(Buffer *buf, int prop, int linkid); static void keyPressEventProc(int c); int show_params_p = 0; void show_params(FILE * fp); static char *getCurWord(Buffer *buf, int *spos, int *epos); static int display_ok = FALSE; static void do_dump(Buffer *); int prec_num = 0; int prev_key = -1; int on_target = 1; static int add_download_list = FALSE; void set_buffer_environ(Buffer *); static void save_buffer_position(Buffer *buf); static void _followForm(int); static void _goLine(char *); static void _newT(void); static void followTab(TabBuffer * tab); static void moveTab(TabBuffer * t, TabBuffer * t2, int right); static void _nextA(int); static void _prevA(int); static int check_target = TRUE; #define PREC_NUM (prec_num ? prec_num : 1) #define PREC_LIMIT 10000 static int searchKeyNum(void); #define help() fusage(stdout, 0) #define usage() fusage(stderr, 1) int enable_inline_image; /* 1 == mlterm OSC 5379, 2 == sixel */ static void fversion(FILE * f) { fprintf(f, "w3m version %s, options %s\n", w3m_version, #if LANG == JA "lang=ja" #else "lang=en" #endif #ifdef USE_M17N ",m17n" #endif #ifdef USE_IMAGE ",image" #endif #ifdef USE_COLOR ",color" #ifdef USE_ANSI_COLOR ",ansi-color" #endif #endif #ifdef USE_MOUSE ",mouse" #ifdef USE_GPM ",gpm" #endif #ifdef USE_SYSMOUSE ",sysmouse" #endif #endif #ifdef USE_MENU ",menu" #endif #ifdef USE_COOKIE ",cookie" #endif #ifdef USE_SSL ",ssl" #ifdef USE_SSL_VERIFY ",ssl-verify" #endif #endif #ifdef USE_EXTERNAL_URI_LOADER ",external-uri-loader" #endif #ifdef USE_W3MMAILER ",w3mmailer" #endif #ifdef USE_NNTP ",nntp" #endif #ifdef USE_GOPHER ",gopher" #endif #ifdef INET6 ",ipv6" #endif #ifdef USE_ALARM ",alarm" #endif #ifdef USE_MARK ",mark" #endif #ifdef USE_MIGEMO ",migemo" #endif ); } static void fusage(FILE * f, int err) { fversion(f); /* FIXME: gettextize? */ fprintf(f, "usage: w3m [options] [URL or filename]\noptions:\n"); fprintf(f, " -t tab set tab width\n"); fprintf(f, " -r ignore backspace effect\n"); fprintf(f, " -l line # of preserved line (default 10000)\n"); #ifdef USE_M17N fprintf(f, " -I charset document charset\n"); fprintf(f, " -O charset display/output charset\n"); #if 0 /* use -O{s|j|e} instead */ fprintf(f, " -e EUC-JP\n"); fprintf(f, " -s Shift_JIS\n"); fprintf(f, " -j JIS\n"); #endif #endif fprintf(f, " -B load bookmark\n"); fprintf(f, " -bookmark file specify bookmark file\n"); fprintf(f, " -T type specify content-type\n"); fprintf(f, " -m internet message mode\n"); fprintf(f, " -v visual startup mode\n"); #ifdef USE_COLOR fprintf(f, " -M monochrome display\n"); #endif /* USE_COLOR */ fprintf(f, " -N open URL of command line on each new tab\n"); fprintf(f, " -F automatically render frames\n"); fprintf(f, " -cols width specify column width (used with -dump)\n"); fprintf(f, " -ppc count specify the number of pixels per character (4.0...32.0)\n"); #ifdef USE_IMAGE fprintf(f, " -ppl count specify the number of pixels per line (4.0...64.0)\n"); #endif fprintf(f, " -dump dump formatted page into stdout\n"); fprintf(f, " -dump_head dump response of HEAD request into stdout\n"); fprintf(f, " -dump_source dump page source into stdout\n"); fprintf(f, " -dump_both dump HEAD and source into stdout\n"); fprintf(f, " -dump_extra dump HEAD, source, and extra information into stdout\n"); fprintf(f, " -post file use POST method with file content\n"); fprintf(f, " -header string insert string as a header\n"); fprintf(f, " +<num> goto <num> line\n"); fprintf(f, " -num show line number\n"); fprintf(f, " -no-proxy don't use proxy\n"); #ifdef INET6 fprintf(f, " -4 IPv4 only (-o dns_order=4)\n"); fprintf(f, " -6 IPv6 only (-o dns_order=6)\n"); #endif #ifdef USE_MOUSE fprintf(f, " -no-mouse don't use mouse\n"); #endif /* USE_MOUSE */ #ifdef USE_COOKIE fprintf(f, " -cookie use cookie (-no-cookie: don't use cookie)\n"); #endif /* USE_COOKIE */ fprintf(f, " -graph use DEC special graphics for border of table and menu\n"); fprintf(f, " -no-graph use ASCII character for border of table and menu\n"); #if 1 /* pager requires -s */ fprintf(f, " -s squeeze multiple blank lines\n"); #else fprintf(f, " -S squeeze multiple blank lines\n"); #endif fprintf(f, " -W toggle search wrap mode\n"); fprintf(f, " -X don't use termcap init/deinit\n"); fprintf(f, " -title[=TERM] set buffer name to terminal title string\n"); fprintf(f, " -o opt=value assign value to config option\n"); fprintf(f, " -show-option print all config options\n"); fprintf(f, " -config file specify config file\n"); fprintf(f, " -help print this usage message\n"); fprintf(f, " -version print w3m version\n"); fprintf(f, " -reqlog write request logfile\n"); fprintf(f, " -debug DO NOT USE\n"); if (show_params_p) show_params(f); exit(err); } #ifdef USE_M17N #ifdef __EMX__ static char *getCodePage(void); #endif #endif static GC_warn_proc orig_GC_warn_proc = NULL; #define GC_WARN_KEEP_MAX (20) static void wrap_GC_warn_proc(char *msg, GC_word arg) { if (fmInitialized) { /* *INDENT-OFF* */ static struct { char *msg; GC_word arg; } msg_ring[GC_WARN_KEEP_MAX]; /* *INDENT-ON* */ static int i = 0; static int n = 0; static int lock = 0; int j; j = (i + n) % (sizeof(msg_ring) / sizeof(msg_ring[0])); msg_ring[j].msg = msg; msg_ring[j].arg = arg; if (n < sizeof(msg_ring) / sizeof(msg_ring[0])) ++n; else ++i; if (!lock) { lock = 1; for (; n > 0; --n, ++i) { i %= sizeof(msg_ring) / sizeof(msg_ring[0]); printf(msg_ring[i].msg, (unsigned long)msg_ring[i].arg); sleep_till_anykey(1, 1); } lock = 0; } } else if (orig_GC_warn_proc) orig_GC_warn_proc(msg, arg); else fprintf(stderr, msg, (unsigned long)arg); } #ifdef SIGCHLD static void sig_chld(int signo) { int p_stat; pid_t pid; #ifdef HAVE_WAITPID while ((pid = waitpid(-1, &p_stat, WNOHANG)) > 0) #elif HAVE_WAIT3 while ((pid = wait3(&p_stat, WNOHANG, NULL)) > 0) #else if ((pid = wait(&p_stat)) > 0) #endif { DownloadList *d; if (WIFEXITED(p_stat)) { for (d = FirstDL; d != NULL; d = d->next) { if (d->pid == pid) { d->err = WEXITSTATUS(p_stat); break; } } } } mySignal(SIGCHLD, sig_chld); return; } #endif Str make_optional_header_string(char *s) { char *p; Str hs; if (strchr(s, '\n') || strchr(s, '\r')) return NULL; for (p = s; *p && *p != ':'; p++) ; if (*p != ':' || p == s) return NULL; hs = Strnew_size(strlen(s) + 3); Strcopy_charp_n(hs, s, p - s); if (!Strcasecmp_charp(hs, "content-type")) override_content_type = TRUE; Strcat_charp(hs, ": "); if (*(++p)) { /* not null header */ SKIP_BLANKS(p); /* skip white spaces */ Strcat_charp(hs, p); } Strcat_charp(hs, "\r\n"); return hs; } static void * die_oom(size_t bytes) { fprintf(stderr, "Out of memory: %lu bytes unavailable!\n", (unsigned long)bytes); exit(1); } int main(int argc, char **argv, char **envp) { Buffer *newbuf = NULL; char *p, c; int i; InputStream redin; char *line_str = NULL; char **load_argv; FormList *request; int load_argc = 0; int load_bookmark = FALSE; int visual_start = FALSE; int open_new_tab = FALSE; char search_header = FALSE; char *default_type = NULL; char *post_file = NULL; Str err_msg; #ifdef USE_M17N char *Locale = NULL; wc_uint8 auto_detect; #ifdef __EMX__ wc_ces CodePage; #endif #endif #if defined(DONT_CALL_GC_AFTER_FORK) && defined(USE_IMAGE) char **getimage_args = NULL; #endif /* defined(DONT_CALL_GC_AFTER_FORK) && defined(USE_IMAGE) */ GC_INIT(); #if (GC_VERSION_MAJOR>7) || ((GC_VERSION_MAJOR==7) && (GC_VERSION_MINOR>=2)) GC_set_oom_fn(die_oom); #else GC_oom_fn = die_oom; #endif #if defined(ENABLE_NLS) || (defined(USE_M17N) && defined(HAVE_LANGINFO_CODESET)) setlocale(LC_ALL, ""); #endif #ifdef ENABLE_NLS bindtextdomain(PACKAGE, LOCALEDIR); textdomain(PACKAGE); #endif #ifndef HAVE_SYS_ERRLIST prepare_sys_errlist(); #endif /* not HAVE_SYS_ERRLIST */ NO_proxy_domains = newTextList(); fileToDelete = newTextList(); load_argv = New_N(char *, argc - 1); load_argc = 0; CurrentDir = currentdir(); CurrentPid = (int)getpid(); #if defined(DONT_CALL_GC_AFTER_FORK) && defined(USE_IMAGE) if (argv[0] && *argv[0]) MyProgramName = argv[0]; #endif /* defined(DONT_CALL_GC_AFTER_FORK) && defined(USE_IMAGE) */ BookmarkFile = NULL; config_file = NULL; /* argument search 1 */ for (i = 1; i < argc; i++) { if (*argv[i] == '-') { if (!strcmp("-config", argv[i])) { argv[i] = "-dummy"; if (++i >= argc) usage(); config_file = argv[i]; argv[i] = "-dummy"; } else if (!strcmp("-h", argv[i]) || !strcmp("-help", argv[i])) help(); else if (!strcmp("-V", argv[i]) || !strcmp("-version", argv[i])) { fversion(stdout); exit(0); } } } #ifdef USE_M17N if (non_null(Locale = getenv("LC_ALL")) || non_null(Locale = getenv("LC_CTYPE")) || non_null(Locale = getenv("LANG"))) { DisplayCharset = wc_guess_locale_charset(Locale, DisplayCharset); DocumentCharset = wc_guess_locale_charset(Locale, DocumentCharset); SystemCharset = wc_guess_locale_charset(Locale, SystemCharset); } #ifdef __EMX__ CodePage = wc_guess_charset(getCodePage(), 0); if (CodePage) DisplayCharset = DocumentCharset = SystemCharset = CodePage; #endif #endif /* initializations */ init_rc(); LoadHist = newHist(); SaveHist = newHist(); ShellHist = newHist(); TextHist = newHist(); URLHist = newHist(); #ifdef USE_M17N if (FollowLocale && Locale) { DisplayCharset = wc_guess_locale_charset(Locale, DisplayCharset); SystemCharset = wc_guess_locale_charset(Locale, SystemCharset); } auto_detect = WcOption.auto_detect; BookmarkCharset = DocumentCharset; #endif if (!non_null(HTTP_proxy) && ((p = getenv("HTTP_PROXY")) || (p = getenv("http_proxy")) || (p = getenv("HTTP_proxy")))) HTTP_proxy = p; #ifdef USE_SSL if (!non_null(HTTPS_proxy) && ((p = getenv("HTTPS_PROXY")) || (p = getenv("https_proxy")) || (p = getenv("HTTPS_proxy")))) HTTPS_proxy = p; if (HTTPS_proxy == NULL && non_null(HTTP_proxy)) HTTPS_proxy = HTTP_proxy; #endif /* USE_SSL */ #ifdef USE_GOPHER if (!non_null(GOPHER_proxy) && ((p = getenv("GOPHER_PROXY")) || (p = getenv("gopher_proxy")) || (p = getenv("GOPHER_proxy")))) GOPHER_proxy = p; #endif /* USE_GOPHER */ if (!non_null(FTP_proxy) && ((p = getenv("FTP_PROXY")) || (p = getenv("ftp_proxy")) || (p = getenv("FTP_proxy")))) FTP_proxy = p; if (!non_null(NO_proxy) && ((p = getenv("NO_PROXY")) || (p = getenv("no_proxy")) || (p = getenv("NO_proxy")))) NO_proxy = p; #ifdef USE_NNTP if (!non_null(NNTP_server) && (p = getenv("NNTPSERVER")) != NULL) NNTP_server = p; if (!non_null(NNTP_mode) && (p = getenv("NNTPMODE")) != NULL) NNTP_mode = p; #endif if (!non_null(Editor) && (p = getenv("EDITOR")) != NULL) Editor = p; if (!non_null(Mailer) && (p = getenv("MAILER")) != NULL) Mailer = p; /* argument search 2 */ i = 1; while (i < argc) { if (*argv[i] == '-') { if (!strcmp("-t", argv[i])) { if (++i >= argc) usage(); if (atoi(argv[i]) > 0) Tabstop = atoi(argv[i]); } else if (!strcmp("-r", argv[i])) ShowEffect = FALSE; else if (!strcmp("-l", argv[i])) { if (++i >= argc) usage(); if (atoi(argv[i]) > 0) PagerMax = atoi(argv[i]); } #ifdef USE_M17N #if 0 /* use -O{s|j|e} instead */ else if (!strcmp("-s", argv[i])) DisplayCharset = WC_CES_SHIFT_JIS; else if (!strcmp("-j", argv[i])) DisplayCharset = WC_CES_ISO_2022_JP; else if (!strcmp("-e", argv[i])) DisplayCharset = WC_CES_EUC_JP; #endif else if (!strncmp("-I", argv[i], 2)) { if (argv[i][2] != '\0') p = argv[i] + 2; else { if (++i >= argc) usage(); p = argv[i]; } DocumentCharset = wc_guess_charset_short(p, DocumentCharset); WcOption.auto_detect = WC_OPT_DETECT_OFF; UseContentCharset = FALSE; } else if (!strncmp("-O", argv[i], 2)) { if (argv[i][2] != '\0') p = argv[i] + 2; else { if (++i >= argc) usage(); p = argv[i]; } DisplayCharset = wc_guess_charset_short(p, DisplayCharset); } #endif else if (!strcmp("-graph", argv[i])) UseGraphicChar = GRAPHIC_CHAR_DEC; else if (!strcmp("-no-graph", argv[i])) UseGraphicChar = GRAPHIC_CHAR_ASCII; else if (!strcmp("-T", argv[i])) { if (++i >= argc) usage(); DefaultType = default_type = argv[i]; } else if (!strcmp("-m", argv[i])) SearchHeader = search_header = TRUE; else if (!strcmp("-v", argv[i])) visual_start = TRUE; else if (!strcmp("-N", argv[i])) open_new_tab = TRUE; #ifdef USE_COLOR else if (!strcmp("-M", argv[i])) useColor = FALSE; #endif /* USE_COLOR */ else if (!strcmp("-B", argv[i])) load_bookmark = TRUE; else if (!strcmp("-bookmark", argv[i])) { if (++i >= argc) usage(); BookmarkFile = argv[i]; if (BookmarkFile[0] != '~' && BookmarkFile[0] != '/') { Str tmp = Strnew_charp(CurrentDir); if (Strlastchar(tmp) != '/') Strcat_char(tmp, '/'); Strcat_charp(tmp, BookmarkFile); BookmarkFile = cleanupName(tmp->ptr); } } else if (!strcmp("-F", argv[i])) RenderFrame = TRUE; else if (!strcmp("-W", argv[i])) { if (WrapDefault) WrapDefault = FALSE; else WrapDefault = TRUE; } else if (!strcmp("-dump", argv[i])) w3m_dump = DUMP_BUFFER; else if (!strcmp("-dump_source", argv[i])) w3m_dump = DUMP_SOURCE; else if (!strcmp("-dump_head", argv[i])) w3m_dump = DUMP_HEAD; else if (!strcmp("-dump_both", argv[i])) w3m_dump = (DUMP_HEAD | DUMP_SOURCE); else if (!strcmp("-dump_extra", argv[i])) w3m_dump = (DUMP_HEAD | DUMP_SOURCE | DUMP_EXTRA); else if (!strcmp("-halfdump", argv[i])) w3m_dump = DUMP_HALFDUMP; else if (!strcmp("-halfload", argv[i])) { w3m_dump = 0; w3m_halfload = TRUE; DefaultType = default_type = "text/html"; } else if (!strcmp("-backend", argv[i])) { w3m_backend = TRUE; } else if (!strcmp("-backend_batch", argv[i])) { w3m_backend = TRUE; if (++i >= argc) usage(); if (!backend_batch_commands) backend_batch_commands = newTextList(); pushText(backend_batch_commands, argv[i]); } else if (!strcmp("-cols", argv[i])) { if (++i >= argc) usage(); COLS = atoi(argv[i]); if (COLS > MAXIMUM_COLS) { COLS = MAXIMUM_COLS; } } else if (!strcmp("-ppc", argv[i])) { double ppc; if (++i >= argc) usage(); ppc = atof(argv[i]); if (ppc >= MINIMUM_PIXEL_PER_CHAR && ppc <= MAXIMUM_PIXEL_PER_CHAR) { pixel_per_char = ppc; set_pixel_per_char = TRUE; } } #ifdef USE_IMAGE else if (!strcmp("-ppl", argv[i])) { double ppc; if (++i >= argc) usage(); ppc = atof(argv[i]); if (ppc >= MINIMUM_PIXEL_PER_CHAR && ppc <= MAXIMUM_PIXEL_PER_CHAR * 2) { pixel_per_line = ppc; set_pixel_per_line = TRUE; } } #endif else if (!strcmp("-ri", argv[i])) { enable_inline_image = 1; } else if (!strcmp("-sixel", argv[i])) { enable_inline_image = 2; } else if (!strcmp("-num", argv[i])) showLineNum = TRUE; else if (!strcmp("-no-proxy", argv[i])) use_proxy = FALSE; #ifdef INET6 else if (!strcmp("-4", argv[i]) || !strcmp("-6", argv[i])) set_param_option(Sprintf("dns_order=%c", argv[i][1])->ptr); #endif else if (!strcmp("-post", argv[i])) { if (++i >= argc) usage(); post_file = argv[i]; } else if (!strcmp("-header", argv[i])) { Str hs; if (++i >= argc) usage(); if ((hs = make_optional_header_string(argv[i])) != NULL) { if (header_string == NULL) header_string = hs; else Strcat(header_string, hs); } while (argv[i][0]) { argv[i][0] = '\0'; argv[i]++; } } #ifdef USE_MOUSE else if (!strcmp("-no-mouse", argv[i])) { use_mouse = FALSE; } #endif /* USE_MOUSE */ #ifdef USE_COOKIE else if (!strcmp("-no-cookie", argv[i])) { use_cookie = FALSE; accept_cookie = FALSE; } else if (!strcmp("-cookie", argv[i])) { use_cookie = TRUE; accept_cookie = TRUE; } #endif /* USE_COOKIE */ #if 1 /* pager requires -s */ else if (!strcmp("-s", argv[i])) #else else if (!strcmp("-S", argv[i])) #endif squeezeBlankLine = TRUE; else if (!strcmp("-X", argv[i])) Do_not_use_ti_te = TRUE; else if (!strcmp("-title", argv[i])) displayTitleTerm = getenv("TERM"); else if (!strncmp("-title=", argv[i], 7)) displayTitleTerm = argv[i] + 7; else if (!strcmp("-o", argv[i]) || !strcmp("-show-option", argv[i])) { if (!strcmp("-show-option", argv[i]) || ++i >= argc || !strcmp(argv[i], "?")) { show_params(stdout); exit(0); } if (!set_param_option(argv[i])) { /* option set failed */ /* FIXME: gettextize? */ fprintf(stderr, "%s: bad option\n", argv[i]); show_params_p = 1; usage(); } } else if (!strcmp("-dummy", argv[i])) { /* do nothing */ } else if (!strcmp("-debug", argv[i])) { w3m_debug = TRUE; } else if (!strcmp("-reqlog",argv[i])) { w3m_reqlog=rcFile("request.log"); } #if defined(DONT_CALL_GC_AFTER_FORK) && defined(USE_IMAGE) else if (!strcmp("-$$getimage", argv[i])) { ++i; getimage_args = argv + i; i += 4; if (i > argc) usage(); } #endif /* defined(DONT_CALL_GC_AFTER_FORK) && defined(USE_IMAGE) */ else { usage(); } } else if (*argv[i] == '+') { line_str = argv[i] + 1; } else { load_argv[load_argc++] = argv[i]; } i++; } #ifdef __WATT32__ if (w3m_debug) dbug_init(); sock_init(); #endif #ifdef __MINGW32_VERSION { int err; WORD wVerReq; wVerReq = MAKEWORD(1, 1); err = WSAStartup(wVerReq, &WSAData); if (err != 0) { fprintf(stderr, "Can't find winsock\n"); return 1; } _fmode = _O_BINARY; } #endif FirstTab = NULL; LastTab = NULL; nTab = 0; CurrentTab = NULL; CurrentKey = -1; if (BookmarkFile == NULL) BookmarkFile = rcFile(BOOKMARK); if (!isatty(1) && !w3m_dump) { /* redirected output */ w3m_dump = DUMP_BUFFER; } if (w3m_dump) { if (COLS == 0) COLS = DEFAULT_COLS; } #ifdef USE_BINMODE_STREAM setmode(fileno(stdout), O_BINARY); #endif if (!w3m_dump && !w3m_backend) { fmInit(); #ifdef SIGWINCH mySignal(SIGWINCH, resize_hook); #else /* not SIGWINCH */ setlinescols(); setupscreen(); #endif /* not SIGWINCH */ } #ifdef USE_IMAGE else if (w3m_halfdump && displayImage) activeImage = TRUE; #endif sync_with_option(); #ifdef USE_COOKIE initCookie(); #endif /* USE_COOKIE */ #ifdef USE_HISTORY if (UseHistory) loadHistory(URLHist); #endif /* not USE_HISTORY */ #ifdef USE_M17N wtf_init(DocumentCharset, DisplayCharset); /* if (w3m_dump) * WcOption.pre_conv = WC_TRUE; */ #endif if (w3m_backend) backend(); #if defined(DONT_CALL_GC_AFTER_FORK) && defined(USE_IMAGE) if (getimage_args) { char *image_url = conv_from_system(getimage_args[0]); char *base_url = conv_from_system(getimage_args[1]); ParsedURL base_pu; parseURL2(base_url, &base_pu, NULL); image_source = getimage_args[2]; newbuf = loadGeneralFile(image_url, &base_pu, NULL, 0, NULL); if (!newbuf || !newbuf->real_type || strncasecmp(newbuf->real_type, "image/", 6)) unlink(getimage_args[2]); #if defined(HAVE_SYMLINK) && defined(HAVE_LSTAT) symlink(getimage_args[2], getimage_args[3]); #else { FILE *f = fopen(getimage_args[3], "w"); if (f) fclose(f); } #endif w3m_exit(0); } #endif /* defined(DONT_CALL_GC_AFTER_FORK) && defined(USE_IMAGE) */ if (w3m_dump) mySignal(SIGINT, SIG_IGN); #ifdef SIGCHLD mySignal(SIGCHLD, sig_chld); #endif #ifdef SIGPIPE mySignal(SIGPIPE, SigPipe); #endif #if (GC_VERSION_MAJOR>7) || ((GC_VERSION_MAJOR==7) && (GC_VERSION_MINOR>=2)) orig_GC_warn_proc = GC_get_warn_proc(); GC_set_warn_proc(wrap_GC_warn_proc); #else orig_GC_warn_proc = GC_set_warn_proc(wrap_GC_warn_proc); #endif err_msg = Strnew(); if (load_argc == 0) { /* no URL specified */ if (!isatty(0)) { redin = newFileStream(fdopen(dup(0), "rb"), (void (*)())pclose); newbuf = openGeneralPagerBuffer(redin); dup2(1, 0); } else if (load_bookmark) { newbuf = loadGeneralFile(BookmarkFile, NULL, NO_REFERER, 0, NULL); if (newbuf == NULL) Strcat_charp(err_msg, "w3m: Can't load bookmark.\n"); } else if (visual_start) { /* FIXME: gettextize? */ Str s_page; s_page = Strnew_charp ("<title>W3M startup page</title><center><b>Welcome to "); Strcat_charp(s_page, "<a href='http://w3m.sourceforge.net/'>"); Strcat_m_charp(s_page, "w3m</a>!<p><p>This is w3m version ", w3m_version, "<br>Written by <a href='mailto:aito@fw.ipsj.or.jp'>Akinori Ito</a>", NULL); newbuf = loadHTMLString(s_page); if (newbuf == NULL) Strcat_charp(err_msg, "w3m: Can't load string.\n"); else if (newbuf != NO_BUFFER) newbuf->bufferprop |= (BP_INTERNAL | BP_NO_URL); } else if ((p = getenv("HTTP_HOME")) != NULL || (p = getenv("WWW_HOME")) != NULL) { newbuf = loadGeneralFile(p, NULL, NO_REFERER, 0, NULL); if (newbuf == NULL) Strcat(err_msg, Sprintf("w3m: Can't load %s.\n", p)); else if (newbuf != NO_BUFFER) pushHashHist(URLHist, parsedURL2Str(&newbuf->currentURL)->ptr); } else { if (fmInitialized) fmTerm(); usage(); } if (newbuf == NULL) { if (fmInitialized) fmTerm(); if (err_msg->length) fprintf(stderr, "%s", err_msg->ptr); w3m_exit(2); } i = -1; } else { i = 0; } for (; i < load_argc; i++) { if (i >= 0) { SearchHeader = search_header; DefaultType = default_type; char *url; url = load_argv[i]; if (getURLScheme(&url) == SCM_MISSING && !ArgvIsURL) url = file_to_url(load_argv[i]); else url = url_encode(conv_from_system(load_argv[i]), NULL, 0); if (w3m_dump == DUMP_HEAD) { request = New(FormList); request->method = FORM_METHOD_HEAD; newbuf = loadGeneralFile(url, NULL, NO_REFERER, 0, request); } else { if (post_file && i == 0) { FILE *fp; Str body; if (!strcmp(post_file, "-")) fp = stdin; else fp = fopen(post_file, "r"); if (fp == NULL) { /* FIXME: gettextize? */ Strcat(err_msg, Sprintf("w3m: Can't open %s.\n", post_file)); continue; } body = Strfgetall(fp); if (fp != stdin) fclose(fp); request = newFormList(NULL, "post", NULL, NULL, NULL, NULL, NULL); request->body = body->ptr; request->boundary = NULL; request->length = body->length; } else { request = NULL; } newbuf = loadGeneralFile(url, NULL, NO_REFERER, 0, request); } if (newbuf == NULL) { /* FIXME: gettextize? */ Strcat(err_msg, Sprintf("w3m: Can't load %s.\n", load_argv[i])); continue; } else if (newbuf == NO_BUFFER) continue; switch (newbuf->real_scheme) { case SCM_MAILTO: break; case SCM_LOCAL: case SCM_LOCAL_CGI: unshiftHist(LoadHist, url); default: pushHashHist(URLHist, parsedURL2Str(&newbuf->currentURL)->ptr); break; } } else if (newbuf == NO_BUFFER) continue; if (newbuf->pagerSource || (newbuf->real_scheme == SCM_LOCAL && newbuf->header_source && newbuf->currentURL.file && strcmp(newbuf->currentURL.file, "-"))) newbuf->search_header = search_header; if (CurrentTab == NULL) { FirstTab = LastTab = CurrentTab = newTab(); nTab = 1; Firstbuf = Currentbuf = newbuf; } else if (open_new_tab) { _newT(); Currentbuf->nextBuffer = newbuf; delBuffer(Currentbuf); } else { Currentbuf->nextBuffer = newbuf; Currentbuf = newbuf; } if (!w3m_dump || w3m_dump == DUMP_BUFFER) { if (Currentbuf->frameset != NULL && RenderFrame) rFrame(); } if (w3m_dump) do_dump(Currentbuf); else { Currentbuf = newbuf; #ifdef USE_BUFINFO saveBufferInfo(); #endif } } if (w3m_dump) { if (err_msg->length) fprintf(stderr, "%s", err_msg->ptr); #ifdef USE_COOKIE save_cookies(); #endif /* USE_COOKIE */ w3m_exit(0); } if (add_download_list) { add_download_list = FALSE; CurrentTab = LastTab; if (!FirstTab) { FirstTab = LastTab = CurrentTab = newTab(); nTab = 1; } if (!Firstbuf || Firstbuf == NO_BUFFER) { Firstbuf = Currentbuf = newBuffer(INIT_BUFFER_WIDTH); Currentbuf->bufferprop = BP_INTERNAL | BP_NO_URL; Currentbuf->buffername = DOWNLOAD_LIST_TITLE; } else Currentbuf = Firstbuf; ldDL(); } else CurrentTab = FirstTab; if (!FirstTab || !Firstbuf || Firstbuf == NO_BUFFER) { if (newbuf == NO_BUFFER) { if (fmInitialized) /* FIXME: gettextize? */ inputChar("Hit any key to quit w3m:"); } if (fmInitialized) fmTerm(); if (err_msg->length) fprintf(stderr, "%s", err_msg->ptr); if (newbuf == NO_BUFFER) { #ifdef USE_COOKIE save_cookies(); #endif /* USE_COOKIE */ if (!err_msg->length) w3m_exit(0); } w3m_exit(2); } if (err_msg->length) disp_message_nsec(err_msg->ptr, FALSE, 1, TRUE, FALSE); SearchHeader = FALSE; DefaultType = NULL; #ifdef USE_M17N UseContentCharset = TRUE; WcOption.auto_detect = auto_detect; #endif Currentbuf = Firstbuf; displayBuffer(Currentbuf, B_FORCE_REDRAW); if (line_str) { _goLine(line_str); } for (;;) { if (add_download_list) { add_download_list = FALSE; ldDL(); } if (Currentbuf->submit) { Anchor *a = Currentbuf->submit; Currentbuf->submit = NULL; gotoLine(Currentbuf, a->start.line); Currentbuf->pos = a->start.pos; _followForm(TRUE); continue; } /* event processing */ if (CurrentEvent) { CurrentKey = -1; CurrentKeyData = NULL; CurrentCmdData = (char *)CurrentEvent->data; w3mFuncList[CurrentEvent->cmd].func(); CurrentCmdData = NULL; CurrentEvent = CurrentEvent->next; continue; } /* get keypress event */ #ifdef USE_ALARM if (Currentbuf->event) { if (Currentbuf->event->status != AL_UNSET) { CurrentAlarm = Currentbuf->event; if (CurrentAlarm->sec == 0) { /* refresh (0sec) */ Currentbuf->event = NULL; CurrentKey = -1; CurrentKeyData = NULL; CurrentCmdData = (char *)CurrentAlarm->data; w3mFuncList[CurrentAlarm->cmd].func(); CurrentCmdData = NULL; continue; } } else Currentbuf->event = NULL; } if (!Currentbuf->event) CurrentAlarm = &DefaultAlarm; #endif #ifdef USE_MOUSE mouse_action.in_action = FALSE; if (use_mouse) mouse_active(); #endif /* USE_MOUSE */ #ifdef USE_ALARM if (CurrentAlarm->sec > 0) { mySignal(SIGALRM, SigAlarm); alarm(CurrentAlarm->sec); } #endif #ifdef SIGWINCH mySignal(SIGWINCH, resize_hook); #endif #ifdef USE_IMAGE if (activeImage && displayImage && Currentbuf->img && !Currentbuf->image_loaded) { do { #ifdef SIGWINCH if (need_resize_screen) resize_screen(); #endif loadImage(Currentbuf, IMG_FLAG_NEXT); } while (sleep_till_anykey(1, 0) <= 0); } #ifdef SIGWINCH else #endif #endif #ifdef SIGWINCH { do { if (need_resize_screen) resize_screen(); } while (sleep_till_anykey(1, 0) <= 0); } #endif c = getch(); #ifdef USE_ALARM if (CurrentAlarm->sec > 0) { alarm(0); } #endif #ifdef USE_MOUSE if (use_mouse) mouse_inactive(); #endif /* USE_MOUSE */ if (IS_ASCII(c)) { /* Ascii */ if (('0' <= c) && (c <= '9') && (prec_num || (GlobalKeymap[c] == FUNCNAME_nulcmd))) { prec_num = prec_num * 10 + (int)(c - '0'); if (prec_num > PREC_LIMIT) prec_num = PREC_LIMIT; } else { set_buffer_environ(Currentbuf); save_buffer_position(Currentbuf); keyPressEventProc((int)c); prec_num = 0; } } prev_key = CurrentKey; CurrentKey = -1; CurrentKeyData = NULL; } } static void keyPressEventProc(int c) { CurrentKey = c; w3mFuncList[(int)GlobalKeymap[c]].func(); } void pushEvent(int cmd, void *data) { Event *event; event = New(Event); event->cmd = cmd; event->data = data; event->next = NULL; if (CurrentEvent) LastEvent->next = event; else CurrentEvent = event; LastEvent = event; } static void dump_source(Buffer *buf) { FILE *f; int c; if (buf->sourcefile == NULL) return; f = fopen(buf->sourcefile, "r"); if (f == NULL) return; while ((c = fgetc(f)) != EOF) { putchar(c); } fclose(f); } static void dump_head(Buffer *buf) { TextListItem *ti; if (buf->document_header == NULL) { if (w3m_dump & DUMP_EXTRA) printf("\n"); return; } for (ti = buf->document_header->first; ti; ti = ti->next) { #ifdef USE_M17N printf("%s", wc_conv_strict(ti->ptr, InnerCharset, buf->document_charset)->ptr); #else printf("%s", ti->ptr); #endif } puts(""); } static void dump_extra(Buffer *buf) { printf("W3m-current-url: %s\n", parsedURL2Str(&buf->currentURL)->ptr); if (buf->baseURL) printf("W3m-base-url: %s\n", parsedURL2Str(buf->baseURL)->ptr); #ifdef USE_M17N printf("W3m-document-charset: %s\n", wc_ces_to_charset(buf->document_charset)); #endif #ifdef USE_SSL if (buf->ssl_certificate) { Str tmp = Strnew(); char *p; for (p = buf->ssl_certificate; *p; p++) { Strcat_char(tmp, *p); if (*p == '\n') { for (; *(p + 1) == '\n'; p++) ; if (*(p + 1)) Strcat_char(tmp, '\t'); } } if (Strlastchar(tmp) != '\n') Strcat_char(tmp, '\n'); printf("W3m-ssl-certificate: %s", tmp->ptr); } #endif } static int cmp_anchor_hseq(const void *a, const void *b) { return (*((const Anchor **) a))->hseq - (*((const Anchor **) b))->hseq; } static void do_dump(Buffer *buf) { MySignalHandler(*volatile prevtrap) (SIGNAL_ARG) = NULL; prevtrap = mySignal(SIGINT, intTrap); if (SETJMP(IntReturn) != 0) { mySignal(SIGINT, prevtrap); return; } if (w3m_dump & DUMP_EXTRA) dump_extra(buf); if (w3m_dump & DUMP_HEAD) dump_head(buf); if (w3m_dump & DUMP_SOURCE) dump_source(buf); if (w3m_dump == DUMP_BUFFER) { int i; saveBuffer(buf, stdout, FALSE); if (displayLinkNumber && buf->href) { int nanchor = buf->href->nanchor; printf("\nReferences:\n\n"); Anchor **in_order = New_N(Anchor *, buf->href->nanchor); for (i = 0; i < nanchor; i++) in_order[i] = buf->href->anchors + i; qsort(in_order, nanchor, sizeof(Anchor *), cmp_anchor_hseq); for (i = 0; i < nanchor; i++) { ParsedURL pu; char *url; if (in_order[i]->slave) continue; parseURL2(in_order[i]->url, &pu, baseURL(buf)); url = url_decode2(parsedURL2Str(&pu)->ptr, Currentbuf); printf("[%d] %s\n", in_order[i]->hseq + 1, url); } } } mySignal(SIGINT, prevtrap); } DEFUN(nulcmd, NOTHING NULL @@@, "Do nothing") { /* do nothing */ } #ifdef __EMX__ DEFUN(pcmap, PCMAP, "pcmap") { w3mFuncList[(int)PcKeymap[(int)getch()]].func(); } #else /* not __EMX__ */ void pcmap(void) { } #endif static void escKeyProc(int c, int esc, unsigned char *map) { if (CurrentKey >= 0 && CurrentKey & K_MULTI) { unsigned char **mmap; mmap = (unsigned char **)getKeyData(MULTI_KEY(CurrentKey)); if (!mmap) return; switch (esc) { case K_ESCD: map = mmap[3]; break; case K_ESCB: map = mmap[2]; break; case K_ESC: map = mmap[1]; break; default: map = mmap[0]; break; } esc |= (CurrentKey & ~0xFFFF); } CurrentKey = esc | c; w3mFuncList[(int)map[c]].func(); } DEFUN(escmap, ESCMAP, "ESC map") { char c; c = getch(); if (IS_ASCII(c)) escKeyProc((int)c, K_ESC, EscKeymap); } DEFUN(escbmap, ESCBMAP, "ESC [ map") { char c; c = getch(); if (IS_DIGIT(c)) { escdmap(c); return; } if (IS_ASCII(c)) escKeyProc((int)c, K_ESCB, EscBKeymap); } void escdmap(char c) { int d; d = (int)c - (int)'0'; c = getch(); if (IS_DIGIT(c)) { d = d * 10 + (int)c - (int)'0'; c = getch(); } if (c == '~') escKeyProc((int)d, K_ESCD, EscDKeymap); } DEFUN(multimap, MULTIMAP, "multimap") { char c; c = getch(); if (IS_ASCII(c)) { CurrentKey = K_MULTI | (CurrentKey << 16) | c; escKeyProc((int)c, 0, NULL); } } void tmpClearBuffer(Buffer *buf) { if (buf->pagerSource == NULL && writeBufferCache(buf) == 0) { buf->firstLine = NULL; buf->topLine = NULL; buf->currentLine = NULL; buf->lastLine = NULL; } } static Str currentURL(void); #ifdef USE_BUFINFO void saveBufferInfo() { FILE *fp; if (w3m_dump) return; if ((fp = fopen(rcFile("bufinfo"), "w")) == NULL) { return; } fprintf(fp, "%s\n", currentURL()->ptr); fclose(fp); } #endif static void pushBuffer(Buffer *buf) { Buffer *b; #ifdef USE_IMAGE deleteImage(Currentbuf); #endif if (clear_buffer) tmpClearBuffer(Currentbuf); if (Firstbuf == Currentbuf) { buf->nextBuffer = Firstbuf; Firstbuf = Currentbuf = buf; } else if ((b = prevBuffer(Firstbuf, Currentbuf)) != NULL) { b->nextBuffer = buf; buf->nextBuffer = Currentbuf; Currentbuf = buf; } #ifdef USE_BUFINFO saveBufferInfo(); #endif } static void delBuffer(Buffer *buf) { if (buf == NULL) return; if (Currentbuf == buf) Currentbuf = buf->nextBuffer; Firstbuf = deleteBuffer(Firstbuf, buf); if (!Currentbuf) Currentbuf = Firstbuf; } static void repBuffer(Buffer *oldbuf, Buffer *buf) { Firstbuf = replaceBuffer(Firstbuf, oldbuf, buf); Currentbuf = buf; } MySignalHandler intTrap(SIGNAL_ARG) { /* Interrupt catcher */ LONGJMP(IntReturn, 0); SIGNAL_RETURN; } #ifdef SIGWINCH static MySignalHandler resize_hook(SIGNAL_ARG) { need_resize_screen = TRUE; mySignal(SIGWINCH, resize_hook); SIGNAL_RETURN; } static void resize_screen(void) { need_resize_screen = FALSE; setlinescols(); setupscreen(); if (CurrentTab) displayBuffer(Currentbuf, B_FORCE_REDRAW); } #endif /* SIGWINCH */ #ifdef SIGPIPE static MySignalHandler SigPipe(SIGNAL_ARG) { #ifdef USE_MIGEMO init_migemo(); #endif mySignal(SIGPIPE, SigPipe); SIGNAL_RETURN; } #endif /* * Command functions: These functions are called with a keystroke. */ static void nscroll(int n, int mode) { Buffer *buf = Currentbuf; Line *top = buf->topLine, *cur = buf->currentLine; int lnum, tlnum, llnum, diff_n; if (buf->firstLine == NULL) return; lnum = cur->linenumber; buf->topLine = lineSkip(buf, top, n, FALSE); if (buf->topLine == top) { lnum += n; if (lnum < buf->topLine->linenumber) lnum = buf->topLine->linenumber; else if (lnum > buf->lastLine->linenumber) lnum = buf->lastLine->linenumber; } else { tlnum = buf->topLine->linenumber; llnum = buf->topLine->linenumber + buf->LINES - 1; if (nextpage_topline) diff_n = 0; else diff_n = n - (tlnum - top->linenumber); if (lnum < tlnum) lnum = tlnum + diff_n; if (lnum > llnum) lnum = llnum + diff_n; } gotoLine(buf, lnum); arrangeLine(buf); if (n > 0) { if (buf->currentLine->bpos && buf->currentLine->bwidth >= buf->currentColumn + buf->visualpos) cursorDown(buf, 1); else { while (buf->currentLine->next && buf->currentLine->next->bpos && buf->currentLine->bwidth + buf->currentLine->width < buf->currentColumn + buf->visualpos) cursorDown0(buf, 1); } } else { if (buf->currentLine->bwidth + buf->currentLine->width < buf->currentColumn + buf->visualpos) cursorUp(buf, 1); else { while (buf->currentLine->prev && buf->currentLine->bpos && buf->currentLine->bwidth >= buf->currentColumn + buf->visualpos) cursorUp0(buf, 1); } } displayBuffer(buf, mode); } /* Move page forward */ DEFUN(pgFore, NEXT_PAGE, "Scroll down one page") { if (vi_prec_num) nscroll(searchKeyNum() * (Currentbuf->LINES - 1), B_NORMAL); else nscroll(prec_num ? searchKeyNum() : searchKeyNum() * (Currentbuf->LINES - 1), prec_num ? B_SCROLL : B_NORMAL); } /* Move page backward */ DEFUN(pgBack, PREV_PAGE, "Scroll up one page") { if (vi_prec_num) nscroll(-searchKeyNum() * (Currentbuf->LINES - 1), B_NORMAL); else nscroll(-(prec_num ? searchKeyNum() : searchKeyNum() * (Currentbuf->LINES - 1)), prec_num ? B_SCROLL : B_NORMAL); } /* Move half page forward */ DEFUN(hpgFore, NEXT_HALF_PAGE, "Scroll down half a page") { nscroll(searchKeyNum() * (Currentbuf->LINES / 2 - 1), B_NORMAL); } /* Move half page backward */ DEFUN(hpgBack, PREV_HALF_PAGE, "Scroll up half a page") { nscroll(-searchKeyNum() * (Currentbuf->LINES / 2 - 1), B_NORMAL); } /* 1 line up */ DEFUN(lup1, UP, "Scroll the screen up one line") { nscroll(searchKeyNum(), B_SCROLL); } /* 1 line down */ DEFUN(ldown1, DOWN, "Scroll the screen down one line") { nscroll(-searchKeyNum(), B_SCROLL); } /* move cursor position to the center of screen */ DEFUN(ctrCsrV, CENTER_V, "Center on cursor line") { int offsety; if (Currentbuf->firstLine == NULL) return; offsety = Currentbuf->LINES / 2 - Currentbuf->cursorY; if (offsety != 0) { #if 0 Currentbuf->currentLine = lineSkip(Currentbuf, Currentbuf->currentLine, offsety, FALSE); #endif Currentbuf->topLine = lineSkip(Currentbuf, Currentbuf->topLine, -offsety, FALSE); arrangeLine(Currentbuf); displayBuffer(Currentbuf, B_NORMAL); } } DEFUN(ctrCsrH, CENTER_H, "Center on cursor column") { int offsetx; if (Currentbuf->firstLine == NULL) return; offsetx = Currentbuf->cursorX - Currentbuf->COLS / 2; if (offsetx != 0) { columnSkip(Currentbuf, offsetx); arrangeCursor(Currentbuf); displayBuffer(Currentbuf, B_NORMAL); } } /* Redraw screen */ DEFUN(rdrwSc, REDRAW, "Draw the screen anew") { clear(); arrangeCursor(Currentbuf); displayBuffer(Currentbuf, B_FORCE_REDRAW); } static void clear_mark(Line *l) { int pos; if (!l) return; for (pos = 0; pos < l->size; pos++) l->propBuf[pos] &= ~PE_MARK; } /* search by regular expression */ static int srchcore(char *volatile str, int (*func) (Buffer *, char *)) { MySignalHandler(*prevtrap) (); volatile int i, result = SR_NOTFOUND; if (str != NULL && str != SearchString) SearchString = str; if (SearchString == NULL || *SearchString == '\0') return SR_NOTFOUND; str = conv_search_string(SearchString, DisplayCharset); prevtrap = mySignal(SIGINT, intTrap); crmode(); if (SETJMP(IntReturn) == 0) { for (i = 0; i < PREC_NUM; i++) { result = func(Currentbuf, str); if (i < PREC_NUM - 1 && result & SR_FOUND) clear_mark(Currentbuf->currentLine); } } mySignal(SIGINT, prevtrap); term_raw(); return result; } static void disp_srchresult(int result, char *prompt, char *str) { if (str == NULL) str = ""; if (result & SR_NOTFOUND) disp_message(Sprintf("Not found: %s", str)->ptr, TRUE); else if (result & SR_WRAPPED) disp_message(Sprintf("Search wrapped: %s", str)->ptr, TRUE); else if (show_srch_str) disp_message(Sprintf("%s%s", prompt, str)->ptr, TRUE); } static int dispincsrch(int ch, Str buf, Lineprop *prop) { static Buffer sbuf; static Line *currentLine; static int pos; char *str; int do_next_search = FALSE; if (ch == 0 && buf == NULL) { SAVE_BUFPOSITION(&sbuf); /* search starting point */ currentLine = sbuf.currentLine; pos = sbuf.pos; return -1; } str = buf->ptr; switch (ch) { case 022: /* C-r */ searchRoutine = backwardSearch; do_next_search = TRUE; break; case 023: /* C-s */ searchRoutine = forwardSearch; do_next_search = TRUE; break; #ifdef USE_MIGEMO case 034: migemo_active = -migemo_active; goto done; #endif default: if (ch >= 0) return ch; /* use InputKeymap */ } if (do_next_search) { if (*str) { if (searchRoutine == forwardSearch) Currentbuf->pos += 1; SAVE_BUFPOSITION(&sbuf); if (srchcore(str, searchRoutine) == SR_NOTFOUND && searchRoutine == forwardSearch) { Currentbuf->pos -= 1; SAVE_BUFPOSITION(&sbuf); } arrangeCursor(Currentbuf); displayBuffer(Currentbuf, B_FORCE_REDRAW); clear_mark(Currentbuf->currentLine); return -1; } else return 020; /* _prev completion for C-s C-s */ } else if (*str) { RESTORE_BUFPOSITION(&sbuf); arrangeCursor(Currentbuf); srchcore(str, searchRoutine); arrangeCursor(Currentbuf); currentLine = Currentbuf->currentLine; pos = Currentbuf->pos; } displayBuffer(Currentbuf, B_FORCE_REDRAW); clear_mark(Currentbuf->currentLine); #ifdef USE_MIGEMO done: while (*str++ != '\0') { if (migemo_active > 0) *prop++ |= PE_UNDER; else *prop++ &= ~PE_UNDER; } #endif return -1; } void isrch(int (*func) (Buffer *, char *), char *prompt) { char *str; Buffer sbuf; SAVE_BUFPOSITION(&sbuf); dispincsrch(0, NULL, NULL); /* initialize incremental search state */ searchRoutine = func; str = inputLineHistSearch(prompt, NULL, IN_STRING, TextHist, dispincsrch); if (str == NULL) { RESTORE_BUFPOSITION(&sbuf); } displayBuffer(Currentbuf, B_FORCE_REDRAW); } void srch(int (*func) (Buffer *, char *), char *prompt) { char *str; int result; int disp = FALSE; int pos; str = searchKeyData(); if (str == NULL || *str == '\0') { str = inputStrHist(prompt, NULL, TextHist); if (str != NULL && *str == '\0') str = SearchString; if (str == NULL) { displayBuffer(Currentbuf, B_NORMAL); return; } disp = TRUE; } pos = Currentbuf->pos; if (func == forwardSearch) Currentbuf->pos += 1; result = srchcore(str, func); if (result & SR_FOUND) clear_mark(Currentbuf->currentLine); else Currentbuf->pos = pos; displayBuffer(Currentbuf, B_NORMAL); if (disp) disp_srchresult(result, prompt, str); searchRoutine = func; } /* Search regular expression forward */ DEFUN(srchfor, SEARCH SEARCH_FORE WHEREIS, "Search forward") { srch(forwardSearch, "Forward: "); } DEFUN(isrchfor, ISEARCH, "Incremental search forward") { isrch(forwardSearch, "I-search: "); } /* Search regular expression backward */ DEFUN(srchbak, SEARCH_BACK, "Search backward") { srch(backwardSearch, "Backward: "); } DEFUN(isrchbak, ISEARCH_BACK, "Incremental search backward") { isrch(backwardSearch, "I-search backward: "); } static void srch_nxtprv(int reverse) { int result; /* *INDENT-OFF* */ static int (*routine[2]) (Buffer *, char *) = { forwardSearch, backwardSearch }; /* *INDENT-ON* */ if (searchRoutine == NULL) { /* FIXME: gettextize? */ disp_message("No previous regular expression", TRUE); return; } if (reverse != 0) reverse = 1; if (searchRoutine == backwardSearch) reverse ^= 1; if (reverse == 0) Currentbuf->pos += 1; result = srchcore(SearchString, routine[reverse]); if (result & SR_FOUND) clear_mark(Currentbuf->currentLine); else { if (reverse == 0) Currentbuf->pos -= 1; } displayBuffer(Currentbuf, B_NORMAL); disp_srchresult(result, (reverse ? "Backward: " : "Forward: "), SearchString); } /* Search next matching */ DEFUN(srchnxt, SEARCH_NEXT, "Continue search forward") { srch_nxtprv(0); } /* Search previous matching */ DEFUN(srchprv, SEARCH_PREV, "Continue search backward") { srch_nxtprv(1); } static void shiftvisualpos(Buffer *buf, int shift) { Line *l = buf->currentLine; buf->visualpos -= shift; if (buf->visualpos - l->bwidth >= buf->COLS) buf->visualpos = l->bwidth + buf->COLS - 1; else if (buf->visualpos - l->bwidth < 0) buf->visualpos = l->bwidth; arrangeLine(buf); if (buf->visualpos - l->bwidth == -shift && buf->cursorX == 0) buf->visualpos = l->bwidth; } /* Shift screen left */ DEFUN(shiftl, SHIFT_LEFT, "Shift screen left") { int column; if (Currentbuf->firstLine == NULL) return; column = Currentbuf->currentColumn; columnSkip(Currentbuf, searchKeyNum() * (-Currentbuf->COLS + 1) + 1); shiftvisualpos(Currentbuf, Currentbuf->currentColumn - column); displayBuffer(Currentbuf, B_NORMAL); } /* Shift screen right */ DEFUN(shiftr, SHIFT_RIGHT, "Shift screen right") { int column; if (Currentbuf->firstLine == NULL) return; column = Currentbuf->currentColumn; columnSkip(Currentbuf, searchKeyNum() * (Currentbuf->COLS - 1) - 1); shiftvisualpos(Currentbuf, Currentbuf->currentColumn - column); displayBuffer(Currentbuf, B_NORMAL); } DEFUN(col1R, RIGHT, "Shift screen one column right") { Buffer *buf = Currentbuf; Line *l = buf->currentLine; int j, column, n = searchKeyNum(); if (l == NULL) return; for (j = 0; j < n; j++) { column = buf->currentColumn; columnSkip(Currentbuf, 1); if (column == buf->currentColumn) break; shiftvisualpos(Currentbuf, 1); } displayBuffer(Currentbuf, B_NORMAL); } DEFUN(col1L, LEFT, "Shift screen one column left") { Buffer *buf = Currentbuf; Line *l = buf->currentLine; int j, n = searchKeyNum(); if (l == NULL) return; for (j = 0; j < n; j++) { if (buf->currentColumn == 0) break; columnSkip(Currentbuf, -1); shiftvisualpos(Currentbuf, -1); } displayBuffer(Currentbuf, B_NORMAL); } DEFUN(setEnv, SETENV, "Set environment variable") { char *env; char *var, *value; CurrentKeyData = NULL; /* not allowed in w3m-control: */ env = searchKeyData(); if (env == NULL || *env == '\0' || strchr(env, '=') == NULL) { if (env != NULL && *env != '\0') env = Sprintf("%s=", env)->ptr; env = inputStrHist("Set environ: ", env, TextHist); if (env == NULL || *env == '\0') { displayBuffer(Currentbuf, B_NORMAL); return; } } if ((value = strchr(env, '=')) != NULL && value > env) { var = allocStr(env, value - env); value++; set_environ(var, value); } displayBuffer(Currentbuf, B_NORMAL); } DEFUN(pipeBuf, PIPE_BUF, "Pipe current buffer through a shell command and display output") { Buffer *buf; char *cmd, *tmpf; FILE *f; CurrentKeyData = NULL; /* not allowed in w3m-control: */ cmd = searchKeyData(); if (cmd == NULL || *cmd == '\0') { /* FIXME: gettextize? */ cmd = inputLineHist("Pipe buffer to: ", "", IN_COMMAND, ShellHist); } if (cmd != NULL) cmd = conv_to_system(cmd); if (cmd == NULL || *cmd == '\0') { displayBuffer(Currentbuf, B_NORMAL); return; } tmpf = tmpfname(TMPF_DFL, NULL)->ptr; f = fopen(tmpf, "w"); if (f == NULL) { /* FIXME: gettextize? */ disp_message(Sprintf("Can't save buffer to %s", cmd)->ptr, TRUE); return; } saveBuffer(Currentbuf, f, TRUE); fclose(f); buf = getpipe(myExtCommand(cmd, shell_quote(tmpf), TRUE)->ptr); if (buf == NULL) { disp_message("Execution failed", TRUE); return; } else { buf->filename = cmd; buf->buffername = Sprintf("%s %s", PIPEBUFFERNAME, conv_from_system(cmd))->ptr; buf->bufferprop |= (BP_INTERNAL | BP_NO_URL); if (buf->type == NULL) buf->type = "text/plain"; buf->currentURL.file = "-"; pushBuffer(buf); } displayBuffer(Currentbuf, B_FORCE_REDRAW); } /* Execute shell command and read output ac pipe. */ DEFUN(pipesh, PIPE_SHELL, "Execute shell command and display output") { Buffer *buf; char *cmd; CurrentKeyData = NULL; /* not allowed in w3m-control: */ cmd = searchKeyData(); if (cmd == NULL || *cmd == '\0') { cmd = inputLineHist("(read shell[pipe])!", "", IN_COMMAND, ShellHist); } if (cmd != NULL) cmd = conv_to_system(cmd); if (cmd == NULL || *cmd == '\0') { displayBuffer(Currentbuf, B_NORMAL); return; } buf = getpipe(cmd); if (buf == NULL) { disp_message("Execution failed", TRUE); return; } else { buf->bufferprop |= (BP_INTERNAL | BP_NO_URL); if (buf->type == NULL) buf->type = "text/plain"; pushBuffer(buf); } displayBuffer(Currentbuf, B_FORCE_REDRAW); } /* Execute shell command and load entire output to buffer */ DEFUN(readsh, READ_SHELL, "Execute shell command and display output") { Buffer *buf; MySignalHandler(*prevtrap) (); char *cmd; CurrentKeyData = NULL; /* not allowed in w3m-control: */ cmd = searchKeyData(); if (cmd == NULL || *cmd == '\0') { cmd = inputLineHist("(read shell)!", "", IN_COMMAND, ShellHist); } if (cmd != NULL) cmd = conv_to_system(cmd); if (cmd == NULL || *cmd == '\0') { displayBuffer(Currentbuf, B_NORMAL); return; } prevtrap = mySignal(SIGINT, intTrap); crmode(); buf = getshell(cmd); mySignal(SIGINT, prevtrap); term_raw(); if (buf == NULL) { /* FIXME: gettextize? */ disp_message("Execution failed", TRUE); return; } else { buf->bufferprop |= (BP_INTERNAL | BP_NO_URL); if (buf->type == NULL) buf->type = "text/plain"; pushBuffer(buf); } displayBuffer(Currentbuf, B_FORCE_REDRAW); } /* Execute shell command */ DEFUN(execsh, EXEC_SHELL SHELL, "Execute shell command and display output") { char *cmd; CurrentKeyData = NULL; /* not allowed in w3m-control: */ cmd = searchKeyData(); if (cmd == NULL || *cmd == '\0') { cmd = inputLineHist("(exec shell)!", "", IN_COMMAND, ShellHist); } if (cmd != NULL) cmd = conv_to_system(cmd); if (cmd != NULL && *cmd != '\0') { fmTerm(); printf("\n"); system(cmd); /* FIXME: gettextize? */ printf("\n[Hit any key]"); fflush(stdout); fmInit(); getch(); } displayBuffer(Currentbuf, B_FORCE_REDRAW); } /* Load file */ DEFUN(ldfile, LOAD, "Open local file in a new buffer") { char *fn; fn = searchKeyData(); if (fn == NULL || *fn == '\0') { /* FIXME: gettextize? */ fn = inputFilenameHist("(Load)Filename? ", NULL, LoadHist); } if (fn != NULL) fn = conv_to_system(fn); if (fn == NULL || *fn == '\0') { displayBuffer(Currentbuf, B_NORMAL); return; } cmd_loadfile(fn); } /* Load help file */ DEFUN(ldhelp, HELP, "Show help panel") { #ifdef USE_HELP_CGI char *lang; int n; Str tmp; lang = AcceptLang; n = strcspn(lang, ";, \t"); tmp = Sprintf("file:///$LIB/" HELP_CGI CGI_EXTENSION "?version=%s&lang=%s", Str_form_quote(Strnew_charp(w3m_version))->ptr, Str_form_quote(Strnew_charp_n(lang, n))->ptr); cmd_loadURL(tmp->ptr, NULL, NO_REFERER, NULL); #else cmd_loadURL(helpFile(HELP_FILE), NULL, NO_REFERER, NULL); #endif } static void cmd_loadfile(char *fn) { Buffer *buf; buf = loadGeneralFile(file_to_url(fn), NULL, NO_REFERER, 0, NULL); if (buf == NULL) { /* FIXME: gettextize? */ char *emsg = Sprintf("%s not found", conv_from_system(fn))->ptr; disp_err_message(emsg, FALSE); } else if (buf != NO_BUFFER) { pushBuffer(buf); if (RenderFrame && Currentbuf->frameset != NULL) rFrame(); } displayBuffer(Currentbuf, B_NORMAL); } /* Move cursor left */ static void _movL(int n) { int i, m = searchKeyNum(); if (Currentbuf->firstLine == NULL) return; for (i = 0; i < m; i++) cursorLeft(Currentbuf, n); displayBuffer(Currentbuf, B_NORMAL); } DEFUN(movL, MOVE_LEFT, "Cursor left") { _movL(Currentbuf->COLS / 2); } DEFUN(movL1, MOVE_LEFT1, "Cursor left. With edge touched, slide") { _movL(1); } /* Move cursor downward */ static void _movD(int n) { int i, m = searchKeyNum(); if (Currentbuf->firstLine == NULL) return; for (i = 0; i < m; i++) cursorDown(Currentbuf, n); displayBuffer(Currentbuf, B_NORMAL); } DEFUN(movD, MOVE_DOWN, "Cursor down") { _movD((Currentbuf->LINES + 1) / 2); } DEFUN(movD1, MOVE_DOWN1, "Cursor down. With edge touched, slide") { _movD(1); } /* move cursor upward */ static void _movU(int n) { int i, m = searchKeyNum(); if (Currentbuf->firstLine == NULL) return; for (i = 0; i < m; i++) cursorUp(Currentbuf, n); displayBuffer(Currentbuf, B_NORMAL); } DEFUN(movU, MOVE_UP, "Cursor up") { _movU((Currentbuf->LINES + 1) / 2); } DEFUN(movU1, MOVE_UP1, "Cursor up. With edge touched, slide") { _movU(1); } /* Move cursor right */ static void _movR(int n) { int i, m = searchKeyNum(); if (Currentbuf->firstLine == NULL) return; for (i = 0; i < m; i++) cursorRight(Currentbuf, n); displayBuffer(Currentbuf, B_NORMAL); } DEFUN(movR, MOVE_RIGHT, "Cursor right") { _movR(Currentbuf->COLS / 2); } DEFUN(movR1, MOVE_RIGHT1, "Cursor right. With edge touched, slide") { _movR(1); } /* movLW, movRW */ /* * From: Takashi Nishimoto <g96p0935@mse.waseda.ac.jp> Date: Mon, 14 Jun * 1999 09:29:56 +0900 */ #if defined(USE_M17N) && defined(USE_UNICODE) #define nextChar(s, l) do { (s)++; } while ((s) < (l)->len && (l)->propBuf[s] & PC_WCHAR2) #define prevChar(s, l) do { (s)--; } while ((s) > 0 && (l)->propBuf[s] & PC_WCHAR2) static wc_uint32 getChar(char *p) { return wc_any_to_ucs(wtf_parse1((wc_uchar **)&p)); } static int is_wordchar(wc_uint32 c) { return wc_is_ucs_alnum(c); } #else #define nextChar(s, l) (s)++ #define prevChar(s, l) (s)-- #define getChar(p) ((int)*(p)) static int is_wordchar(int c) { return IS_ALNUM(c); } #endif static int prev_nonnull_line(Line *line) { Line *l; for (l = line; l != NULL && l->len == 0; l = l->prev) ; if (l == NULL || l->len == 0) return -1; Currentbuf->currentLine = l; if (l != line) Currentbuf->pos = Currentbuf->currentLine->len; return 0; } DEFUN(movLW, PREV_WORD, "Move to the previous word") { char *lb; Line *pline, *l; int ppos; int i, n = searchKeyNum(); if (Currentbuf->firstLine == NULL) return; for (i = 0; i < n; i++) { pline = Currentbuf->currentLine; ppos = Currentbuf->pos; if (prev_nonnull_line(Currentbuf->currentLine) < 0) goto end; while (1) { l = Currentbuf->currentLine; lb = l->lineBuf; while (Currentbuf->pos > 0) { int tmp = Currentbuf->pos; prevChar(tmp, l); if (is_wordchar(getChar(&lb[tmp]))) break; Currentbuf->pos = tmp; } if (Currentbuf->pos > 0) break; if (prev_nonnull_line(Currentbuf->currentLine->prev) < 0) { Currentbuf->currentLine = pline; Currentbuf->pos = ppos; goto end; } Currentbuf->pos = Currentbuf->currentLine->len; } l = Currentbuf->currentLine; lb = l->lineBuf; while (Currentbuf->pos > 0) { int tmp = Currentbuf->pos; prevChar(tmp, l); if (!is_wordchar(getChar(&lb[tmp]))) break; Currentbuf->pos = tmp; } } end: arrangeCursor(Currentbuf); displayBuffer(Currentbuf, B_NORMAL); } static int next_nonnull_line(Line *line) { Line *l; for (l = line; l != NULL && l->len == 0; l = l->next) ; if (l == NULL || l->len == 0) return -1; Currentbuf->currentLine = l; if (l != line) Currentbuf->pos = 0; return 0; } DEFUN(movRW, NEXT_WORD, "Move to the next word") { char *lb; Line *pline, *l; int ppos; int i, n = searchKeyNum(); if (Currentbuf->firstLine == NULL) return; for (i = 0; i < n; i++) { pline = Currentbuf->currentLine; ppos = Currentbuf->pos; if (next_nonnull_line(Currentbuf->currentLine) < 0) goto end; l = Currentbuf->currentLine; lb = l->lineBuf; while (Currentbuf->pos < l->len && is_wordchar(getChar(&lb[Currentbuf->pos]))) nextChar(Currentbuf->pos, l); while (1) { while (Currentbuf->pos < l->len && !is_wordchar(getChar(&lb[Currentbuf->pos]))) nextChar(Currentbuf->pos, l); if (Currentbuf->pos < l->len) break; if (next_nonnull_line(Currentbuf->currentLine->next) < 0) { Currentbuf->currentLine = pline; Currentbuf->pos = ppos; goto end; } Currentbuf->pos = 0; l = Currentbuf->currentLine; lb = l->lineBuf; } } end: arrangeCursor(Currentbuf); displayBuffer(Currentbuf, B_NORMAL); } static void _quitfm(int confirm) { char *ans = "y"; if (checkDownloadList()) /* FIXME: gettextize? */ ans = inputChar("Download process retains. " "Do you want to exit w3m? (y/n)"); else if (confirm) /* FIXME: gettextize? */ ans = inputChar("Do you want to exit w3m? (y/n)"); if (!(ans && TOLOWER(*ans) == 'y')) { displayBuffer(Currentbuf, B_NORMAL); return; } term_title(""); /* XXX */ #ifdef USE_IMAGE if (activeImage) termImage(); #endif fmTerm(); #ifdef USE_COOKIE save_cookies(); #endif /* USE_COOKIE */ #ifdef USE_HISTORY if (UseHistory && SaveURLHist) saveHistory(URLHist, URLHistSize); #endif /* USE_HISTORY */ w3m_exit(0); } /* Quit */ DEFUN(quitfm, ABORT EXIT, "Quit at once") { _quitfm(FALSE); } /* Question and Quit */ DEFUN(qquitfm, QUIT, "Quit with confirmation request") { _quitfm(confirm_on_quit); } /* Select buffer */ DEFUN(selBuf, SELECT, "Display buffer-stack panel") { Buffer *buf; int ok; char cmd; ok = FALSE; do { buf = selectBuffer(Firstbuf, Currentbuf, &cmd); switch (cmd) { case 'B': ok = TRUE; break; case '\n': case ' ': Currentbuf = buf; ok = TRUE; break; case 'D': delBuffer(buf); if (Firstbuf == NULL) { /* No more buffer */ Firstbuf = nullBuffer(); Currentbuf = Firstbuf; } break; case 'q': qquitfm(); break; case 'Q': quitfm(); break; } } while (!ok); for (buf = Firstbuf; buf != NULL; buf = buf->nextBuffer) { if (buf == Currentbuf) continue; #ifdef USE_IMAGE deleteImage(buf); #endif if (clear_buffer) tmpClearBuffer(buf); } displayBuffer(Currentbuf, B_FORCE_REDRAW); } /* Suspend (on BSD), or run interactive shell (on SysV) */ DEFUN(susp, INTERRUPT SUSPEND, "Suspend w3m to background") { #ifndef SIGSTOP char *shell; #endif /* not SIGSTOP */ move(LASTLINE, 0); clrtoeolx(); refresh(); fmTerm(); #ifndef SIGSTOP shell = getenv("SHELL"); if (shell == NULL) shell = "/bin/sh"; system(shell); #else /* SIGSTOP */ #ifdef SIGTSTP signal(SIGTSTP, SIG_DFL); /* just in case */ /* * Note: If susp() was called from SIGTSTP handler, * unblocking SIGTSTP would be required here. * Currently not. */ kill(0, SIGTSTP); /* stop whole job, not a single process */ #else kill((pid_t) 0, SIGSTOP); #endif #endif /* SIGSTOP */ fmInit(); displayBuffer(Currentbuf, B_FORCE_REDRAW); } /* Go to specified line */ static void _goLine(char *l) { if (l == NULL || *l == '\0' || Currentbuf->currentLine == NULL) { displayBuffer(Currentbuf, B_FORCE_REDRAW); return; } Currentbuf->pos = 0; if (((*l == '^') || (*l == '$')) && prec_num) { gotoRealLine(Currentbuf, prec_num); } else if (*l == '^') { Currentbuf->topLine = Currentbuf->currentLine = Currentbuf->firstLine; } else if (*l == '$') { Currentbuf->topLine = lineSkip(Currentbuf, Currentbuf->lastLine, -(Currentbuf->LINES + 1) / 2, TRUE); Currentbuf->currentLine = Currentbuf->lastLine; } else gotoRealLine(Currentbuf, atoi(l)); arrangeCursor(Currentbuf); displayBuffer(Currentbuf, B_FORCE_REDRAW); } DEFUN(goLine, GOTO_LINE, "Go to the specified line") { char *str = searchKeyData(); if (prec_num) _goLine("^"); else if (str) _goLine(str); else /* FIXME: gettextize? */ _goLine(inputStr("Goto line: ", "")); } DEFUN(goLineF, BEGIN, "Go to the first line") { _goLine("^"); } DEFUN(goLineL, END, "Go to the last line") { _goLine("$"); } /* Go to the beginning of the line */ DEFUN(linbeg, LINE_BEGIN, "Go to the beginning of the line") { if (Currentbuf->firstLine == NULL) return; while (Currentbuf->currentLine->prev && Currentbuf->currentLine->bpos) cursorUp0(Currentbuf, 1); Currentbuf->pos = 0; arrangeCursor(Currentbuf); displayBuffer(Currentbuf, B_NORMAL); } /* Go to the bottom of the line */ DEFUN(linend, LINE_END, "Go to the end of the line") { if (Currentbuf->firstLine == NULL) return; while (Currentbuf->currentLine->next && Currentbuf->currentLine->next->bpos) cursorDown0(Currentbuf, 1); Currentbuf->pos = Currentbuf->currentLine->len - 1; arrangeCursor(Currentbuf); displayBuffer(Currentbuf, B_NORMAL); } static int cur_real_linenumber(Buffer *buf) { Line *l, *cur = buf->currentLine; int n; if (!cur) return 1; n = cur->real_linenumber ? cur->real_linenumber : 1; for (l = buf->firstLine; l && l != cur && l->real_linenumber == 0; l = l->next) { /* header */ if (l->bpos == 0) n++; } return n; } /* Run editor on the current buffer */ DEFUN(editBf, EDIT, "Edit local source") { char *fn = Currentbuf->filename; Str cmd; if (fn == NULL || Currentbuf->pagerSource != NULL || /* Behaving as a pager */ (Currentbuf->type == NULL && Currentbuf->edit == NULL) || /* Reading shell */ Currentbuf->real_scheme != SCM_LOCAL || !strcmp(Currentbuf->currentURL.file, "-") || /* file is std input */ Currentbuf->bufferprop & BP_FRAME) { /* Frame */ disp_err_message("Can't edit other than local file", TRUE); return; } if (Currentbuf->edit) cmd = unquote_mailcap(Currentbuf->edit, Currentbuf->real_type, fn, checkHeader(Currentbuf, "Content-Type:"), NULL); else cmd = myEditor(Editor, shell_quote(fn), cur_real_linenumber(Currentbuf)); fmTerm(); system(cmd->ptr); fmInit(); displayBuffer(Currentbuf, B_FORCE_REDRAW); reload(); } /* Run editor on the current screen */ DEFUN(editScr, EDIT_SCREEN, "Edit rendered copy of document") { char *tmpf; FILE *f; tmpf = tmpfname(TMPF_DFL, NULL)->ptr; f = fopen(tmpf, "w"); if (f == NULL) { /* FIXME: gettextize? */ disp_err_message(Sprintf("Can't open %s", tmpf)->ptr, TRUE); return; } saveBuffer(Currentbuf, f, TRUE); fclose(f); fmTerm(); system(myEditor(Editor, shell_quote(tmpf), cur_real_linenumber(Currentbuf))->ptr); fmInit(); unlink(tmpf); displayBuffer(Currentbuf, B_FORCE_REDRAW); } #ifdef USE_MARK /* Set / unset mark */ DEFUN(_mark, MARK, "Set/unset mark") { Line *l; if (!use_mark) return; if (Currentbuf->firstLine == NULL) return; l = Currentbuf->currentLine; l->propBuf[Currentbuf->pos] ^= PE_MARK; displayBuffer(Currentbuf, B_FORCE_REDRAW); } /* Go to next mark */ DEFUN(nextMk, NEXT_MARK, "Go to the next mark") { Line *l; int i; if (!use_mark) return; if (Currentbuf->firstLine == NULL) return; i = Currentbuf->pos + 1; l = Currentbuf->currentLine; if (i >= l->len) { i = 0; l = l->next; } while (l != NULL) { for (; i < l->len; i++) { if (l->propBuf[i] & PE_MARK) { Currentbuf->currentLine = l; Currentbuf->pos = i; arrangeCursor(Currentbuf); displayBuffer(Currentbuf, B_NORMAL); return; } } l = l->next; i = 0; } /* FIXME: gettextize? */ disp_message("No mark exist after here", TRUE); } /* Go to previous mark */ DEFUN(prevMk, PREV_MARK, "Go to the previous mark") { Line *l; int i; if (!use_mark) return; if (Currentbuf->firstLine == NULL) return; i = Currentbuf->pos - 1; l = Currentbuf->currentLine; if (i < 0) { l = l->prev; if (l != NULL) i = l->len - 1; } while (l != NULL) { for (; i >= 0; i--) { if (l->propBuf[i] & PE_MARK) { Currentbuf->currentLine = l; Currentbuf->pos = i; arrangeCursor(Currentbuf); displayBuffer(Currentbuf, B_NORMAL); return; } } l = l->prev; if (l != NULL) i = l->len - 1; } /* FIXME: gettextize? */ disp_message("No mark exist before here", TRUE); } /* Mark place to which the regular expression matches */ DEFUN(reMark, REG_MARK, "Mark all occurences of a pattern") { Line *l; char *str; char *p, *p1, *p2; if (!use_mark) return; str = searchKeyData(); if (str == NULL || *str == '\0') { str = inputStrHist("(Mark)Regexp: ", MarkString, TextHist); if (str == NULL || *str == '\0') { displayBuffer(Currentbuf, B_NORMAL); return; } } str = conv_search_string(str, DisplayCharset); if ((str = regexCompile(str, 1)) != NULL) { disp_message(str, TRUE); return; } MarkString = str; for (l = Currentbuf->firstLine; l != NULL; l = l->next) { p = l->lineBuf; for (;;) { if (regexMatch(p, &l->lineBuf[l->len] - p, p == l->lineBuf) == 1) { matchedPosition(&p1, &p2); l->propBuf[p1 - l->lineBuf] |= PE_MARK; p = p2; } else break; } } displayBuffer(Currentbuf, B_FORCE_REDRAW); } #endif /* USE_MARK */ static Buffer * loadNormalBuf(Buffer *buf, int renderframe) { pushBuffer(buf); if (renderframe && RenderFrame && Currentbuf->frameset != NULL) rFrame(); return buf; } static Buffer * loadLink(char *url, char *target, char *referer, FormList *request) { Buffer *buf, *nfbuf; union frameset_element *f_element = NULL; int flag = 0; ParsedURL *base, pu; const int *no_referer_ptr; message(Sprintf("loading %s", url)->ptr, 0, 0); refresh(); no_referer_ptr = query_SCONF_NO_REFERER_FROM(&Currentbuf->currentURL); base = baseURL(Currentbuf); if ((no_referer_ptr && *no_referer_ptr) || base == NULL || base->scheme == SCM_LOCAL || base->scheme == SCM_LOCAL_CGI) referer = NO_REFERER; if (referer == NULL) referer = parsedURL2Str(&Currentbuf->currentURL)->ptr; buf = loadGeneralFile(url, baseURL(Currentbuf), referer, flag, request); if (buf == NULL) { char *emsg = Sprintf("Can't load %s", url)->ptr; disp_err_message(emsg, FALSE); return NULL; } parseURL2(url, &pu, base); pushHashHist(URLHist, parsedURL2Str(&pu)->ptr); if (buf == NO_BUFFER) { return NULL; } if (!on_target) /* open link as an indivisual page */ return loadNormalBuf(buf, TRUE); if (do_download) /* download (thus no need to render frames) */ return loadNormalBuf(buf, FALSE); if (target == NULL || /* no target specified (that means this page is not a frame page) */ !strcmp(target, "_top") || /* this link is specified to be opened as an indivisual * page */ !(Currentbuf->bufferprop & BP_FRAME) /* This page is not a frame page */ ) { return loadNormalBuf(buf, TRUE); } nfbuf = Currentbuf->linkBuffer[LB_N_FRAME]; if (nfbuf == NULL) { /* original page (that contains <frameset> tag) doesn't exist */ return loadNormalBuf(buf, TRUE); } f_element = search_frame(nfbuf->frameset, target); if (f_element == NULL) { /* specified target doesn't exist in this frameset */ return loadNormalBuf(buf, TRUE); } /* frame page */ /* stack current frameset */ pushFrameTree(&(nfbuf->frameQ), copyFrameSet(nfbuf->frameset), Currentbuf); /* delete frame view buffer */ delBuffer(Currentbuf); Currentbuf = nfbuf; /* nfbuf->frameset = copyFrameSet(nfbuf->frameset); */ resetFrameElement(f_element, buf, referer, request); discardBuffer(buf); rFrame(); { Anchor *al = NULL; char *label = pu.label; if (label && f_element->element->attr == F_BODY) { al = searchAnchor(f_element->body->nameList, label); } if (!al) { label = Strnew_m_charp("_", target, NULL)->ptr; al = searchURLLabel(Currentbuf, label); } if (al) { gotoLine(Currentbuf, al->start.line); if (label_topline) Currentbuf->topLine = lineSkip(Currentbuf, Currentbuf->topLine, Currentbuf->currentLine-> linenumber - Currentbuf->topLine->linenumber, FALSE); Currentbuf->pos = al->start.pos; arrangeCursor(Currentbuf); } } displayBuffer(Currentbuf, B_NORMAL); return buf; } static void gotoLabel(char *label) { Buffer *buf; Anchor *al; int i; al = searchURLLabel(Currentbuf, label); if (al == NULL) { /* FIXME: gettextize? */ disp_message(Sprintf("%s is not found", label)->ptr, TRUE); return; } buf = newBuffer(Currentbuf->width); copyBuffer(buf, Currentbuf); for (i = 0; i < MAX_LB; i++) buf->linkBuffer[i] = NULL; buf->currentURL.label = allocStr(label, -1); pushHashHist(URLHist, parsedURL2Str(&buf->currentURL)->ptr); (*buf->clone)++; pushBuffer(buf); gotoLine(Currentbuf, al->start.line); if (label_topline) Currentbuf->topLine = lineSkip(Currentbuf, Currentbuf->topLine, Currentbuf->currentLine->linenumber - Currentbuf->topLine->linenumber, FALSE); Currentbuf->pos = al->start.pos; arrangeCursor(Currentbuf); displayBuffer(Currentbuf, B_FORCE_REDRAW); return; } static int handleMailto(char *url) { Str to; char *pos; if (strncasecmp(url, "mailto:", 7)) return 0; #ifdef USE_W3MMAILER if (! non_null(Mailer) || MailtoOptions == MAILTO_OPTIONS_USE_W3MMAILER) return 0; #else if (!non_null(Mailer)) { /* FIXME: gettextize? */ disp_err_message("no mailer is specified", TRUE); return 1; } #endif /* invoke external mailer */ if (MailtoOptions == MAILTO_OPTIONS_USE_MAILTO_URL) { to = Strnew_charp(html_unquote(url)); } else { to = Strnew_charp(url + 7); if ((pos = strchr(to->ptr, '?')) != NULL) Strtruncate(to, pos - to->ptr); } fmTerm(); system(myExtCommand(Mailer, shell_quote(file_unquote(to->ptr)), FALSE)->ptr); fmInit(); displayBuffer(Currentbuf, B_FORCE_REDRAW); pushHashHist(URLHist, url); return 1; } /* follow HREF link */ DEFUN(followA, GOTO_LINK, "Follow current hyperlink in a new buffer") { Anchor *a; ParsedURL u; #ifdef USE_IMAGE int x = 0, y = 0, map = 0; #endif char *url; if (Currentbuf->firstLine == NULL) return; #ifdef USE_IMAGE a = retrieveCurrentImg(Currentbuf); if (a && a->image && a->image->map) { _followForm(FALSE); return; } if (a && a->image && a->image->ismap) { getMapXY(Currentbuf, a, &x, &y); map = 1; } #else a = retrieveCurrentMap(Currentbuf); if (a) { _followForm(FALSE); return; } #endif a = retrieveCurrentAnchor(Currentbuf); if (a == NULL) { _followForm(FALSE); return; } if (*a->url == '#') { /* index within this buffer */ gotoLabel(a->url + 1); return; } parseURL2(a->url, &u, baseURL(Currentbuf)); if (Strcmp(parsedURL2Str(&u), parsedURL2Str(&Currentbuf->currentURL)) == 0) { /* index within this buffer */ if (u.label) { gotoLabel(u.label); return; } } if (handleMailto(a->url)) return; #if 0 else if (!strncasecmp(a->url, "news:", 5) && strchr(a->url, '@') == NULL) { /* news:newsgroup is not supported */ /* FIXME: gettextize? */ disp_err_message("news:newsgroup_name is not supported", TRUE); return; } #endif /* USE_NNTP */ url = a->url; #ifdef USE_IMAGE if (map) url = Sprintf("%s?%d,%d", a->url, x, y)->ptr; #endif if (check_target && open_tab_blank && a->target && (!strcasecmp(a->target, "_new") || !strcasecmp(a->target, "_blank"))) { Buffer *buf; _newT(); buf = Currentbuf; loadLink(url, a->target, a->referer, NULL); if (buf != Currentbuf) delBuffer(buf); else deleteTab(CurrentTab); displayBuffer(Currentbuf, B_FORCE_REDRAW); return; } loadLink(url, a->target, a->referer, NULL); displayBuffer(Currentbuf, B_NORMAL); } /* follow HREF link in the buffer */ void bufferA(void) { on_target = FALSE; followA(); on_target = TRUE; } /* view inline image */ DEFUN(followI, VIEW_IMAGE, "Display image in viewer") { Anchor *a; Buffer *buf; if (Currentbuf->firstLine == NULL) return; a = retrieveCurrentImg(Currentbuf); if (a == NULL) return; /* FIXME: gettextize? */ message(Sprintf("loading %s", a->url)->ptr, 0, 0); refresh(); buf = loadGeneralFile(a->url, baseURL(Currentbuf), NULL, 0, NULL); if (buf == NULL) { /* FIXME: gettextize? */ char *emsg = Sprintf("Can't load %s", a->url)->ptr; disp_err_message(emsg, FALSE); } else if (buf != NO_BUFFER) { pushBuffer(buf); } displayBuffer(Currentbuf, B_NORMAL); } static FormItemList * save_submit_formlist(FormItemList *src) { FormList *list; FormList *srclist; FormItemList *srcitem; FormItemList *item; FormItemList *ret = NULL; #ifdef MENU_SELECT FormSelectOptionItem *opt; FormSelectOptionItem *curopt; FormSelectOptionItem *srcopt; #endif /* MENU_SELECT */ if (src == NULL) return NULL; srclist = src->parent; list = New(FormList); list->method = srclist->method; list->action = Strdup(srclist->action); #ifdef USE_M17N list->charset = srclist->charset; #endif list->enctype = srclist->enctype; list->nitems = srclist->nitems; list->body = srclist->body; list->boundary = srclist->boundary; list->length = srclist->length; for (srcitem = srclist->item; srcitem; srcitem = srcitem->next) { item = New(FormItemList); item->type = srcitem->type; item->name = Strdup(srcitem->name); item->value = Strdup(srcitem->value); item->checked = srcitem->checked; item->accept = srcitem->accept; item->size = srcitem->size; item->rows = srcitem->rows; item->maxlength = srcitem->maxlength; item->readonly = srcitem->readonly; #ifdef MENU_SELECT opt = curopt = NULL; for (srcopt = srcitem->select_option; srcopt; srcopt = srcopt->next) { if (!srcopt->checked) continue; opt = New(FormSelectOptionItem); opt->value = Strdup(srcopt->value); opt->label = Strdup(srcopt->label); opt->checked = srcopt->checked; if (item->select_option == NULL) { item->select_option = curopt = opt; } else { curopt->next = opt; curopt = curopt->next; } } item->select_option = opt; if (srcitem->label) item->label = Strdup(srcitem->label); #endif /* MENU_SELECT */ item->parent = list; item->next = NULL; if (list->lastitem == NULL) { list->item = list->lastitem = item; } else { list->lastitem->next = item; list->lastitem = item; } if (srcitem == src) ret = item; } return ret; } #ifdef USE_M17N static Str conv_form_encoding(Str val, FormItemList *fi, Buffer *buf) { wc_ces charset = SystemCharset; if (fi->parent->charset) charset = fi->parent->charset; else if (buf->document_charset && buf->document_charset != WC_CES_US_ASCII) charset = buf->document_charset; return wc_Str_conv_strict(val, InnerCharset, charset); } #else #define conv_form_encoding(val, fi, buf) (val) #endif static void query_from_followform(Str *query, FormItemList *fi, int multipart) { FormItemList *f2; FILE *body = NULL; if (multipart) { *query = tmpfname(TMPF_DFL, NULL); body = fopen((*query)->ptr, "w"); if (body == NULL) { return; } fi->parent->body = (*query)->ptr; fi->parent->boundary = Sprintf("------------------------------%d%ld%ld%ld", CurrentPid, fi->parent, fi->parent->body, fi->parent->boundary)->ptr; } *query = Strnew(); for (f2 = fi->parent->item; f2; f2 = f2->next) { if (f2->name == NULL) continue; /* <ISINDEX> is translated into single text form */ if (f2->name->length == 0 && (multipart || f2->type != FORM_INPUT_TEXT)) continue; switch (f2->type) { case FORM_INPUT_RESET: /* do nothing */ continue; case FORM_INPUT_SUBMIT: case FORM_INPUT_IMAGE: if (f2 != fi || f2->value == NULL) continue; break; case FORM_INPUT_RADIO: case FORM_INPUT_CHECKBOX: if (!f2->checked) continue; } if (multipart) { if (f2->type == FORM_INPUT_IMAGE) { int x = 0, y = 0; #ifdef USE_IMAGE getMapXY(Currentbuf, retrieveCurrentImg(Currentbuf), &x, &y); #endif *query = Strdup(conv_form_encoding(f2->name, fi, Currentbuf)); Strcat_charp(*query, ".x"); form_write_data(body, fi->parent->boundary, (*query)->ptr, Sprintf("%d", x)->ptr); *query = Strdup(conv_form_encoding(f2->name, fi, Currentbuf)); Strcat_charp(*query, ".y"); form_write_data(body, fi->parent->boundary, (*query)->ptr, Sprintf("%d", y)->ptr); } else if (f2->name && f2->name->length > 0 && f2->value != NULL) { /* not IMAGE */ *query = conv_form_encoding(f2->value, fi, Currentbuf); if (f2->type == FORM_INPUT_FILE) form_write_from_file(body, fi->parent->boundary, conv_form_encoding(f2->name, fi, Currentbuf)->ptr, (*query)->ptr, Str_conv_to_system(f2->value)->ptr); else form_write_data(body, fi->parent->boundary, conv_form_encoding(f2->name, fi, Currentbuf)->ptr, (*query)->ptr); } } else { /* not multipart */ if (f2->type == FORM_INPUT_IMAGE) { int x = 0, y = 0; #ifdef USE_IMAGE getMapXY(Currentbuf, retrieveCurrentImg(Currentbuf), &x, &y); #endif Strcat(*query, Str_form_quote(conv_form_encoding (f2->name, fi, Currentbuf))); Strcat(*query, Sprintf(".x=%d&", x)); Strcat(*query, Str_form_quote(conv_form_encoding (f2->name, fi, Currentbuf))); Strcat(*query, Sprintf(".y=%d", y)); } else { /* not IMAGE */ if (f2->name && f2->name->length > 0) { Strcat(*query, Str_form_quote(conv_form_encoding (f2->name, fi, Currentbuf))); Strcat_char(*query, '='); } if (f2->value != NULL) { if (fi->parent->method == FORM_METHOD_INTERNAL) Strcat(*query, Str_form_quote(f2->value)); else { Strcat(*query, Str_form_quote(conv_form_encoding (f2->value, fi, Currentbuf))); } } } if (f2->next) Strcat_char(*query, '&'); } } if (multipart) { fprintf(body, "--%s--\r\n", fi->parent->boundary); fclose(body); } else { /* remove trailing & */ while (Strlastchar(*query) == '&') Strshrink(*query, 1); } } /* submit form */ DEFUN(submitForm, SUBMIT, "Submit form") { _followForm(TRUE); } /* process form */ void followForm(void) { _followForm(FALSE); } static void _followForm(int submit) { Anchor *a, *a2; char *p; FormItemList *fi, *f2; Str tmp, tmp2; int multipart = 0, i; if (Currentbuf->firstLine == NULL) return; a = retrieveCurrentForm(Currentbuf); if (a == NULL) return; fi = (FormItemList *)a->url; switch (fi->type) { case FORM_INPUT_TEXT: if (submit) goto do_submit; if (fi->readonly) /* FIXME: gettextize? */ disp_message_nsec("Read only field!", FALSE, 1, TRUE, FALSE); /* FIXME: gettextize? */ p = inputStrHist("TEXT:", fi->value ? fi->value->ptr : NULL, TextHist); if (p == NULL || fi->readonly) break; fi->value = Strnew_charp(p); formUpdateBuffer(a, Currentbuf, fi); if (fi->accept || fi->parent->nitems == 1) goto do_submit; break; case FORM_INPUT_FILE: if (submit) goto do_submit; if (fi->readonly) /* FIXME: gettextize? */ disp_message_nsec("Read only field!", FALSE, 1, TRUE, FALSE); /* FIXME: gettextize? */ p = inputFilenameHist("Filename:", fi->value ? fi->value->ptr : NULL, NULL); if (p == NULL || fi->readonly) break; fi->value = Strnew_charp(p); formUpdateBuffer(a, Currentbuf, fi); if (fi->accept || fi->parent->nitems == 1) goto do_submit; break; case FORM_INPUT_PASSWORD: if (submit) goto do_submit; if (fi->readonly) { /* FIXME: gettextize? */ disp_message_nsec("Read only field!", FALSE, 1, TRUE, FALSE); break; } /* FIXME: gettextize? */ p = inputLine("Password:", fi->value ? fi->value->ptr : NULL, IN_PASSWORD); if (p == NULL) break; fi->value = Strnew_charp(p); formUpdateBuffer(a, Currentbuf, fi); if (fi->accept) goto do_submit; break; case FORM_TEXTAREA: if (submit) goto do_submit; if (fi->readonly) /* FIXME: gettextize? */ disp_message_nsec("Read only field!", FALSE, 1, TRUE, FALSE); input_textarea(fi); formUpdateBuffer(a, Currentbuf, fi); break; case FORM_INPUT_RADIO: if (submit) goto do_submit; if (fi->readonly) { /* FIXME: gettextize? */ disp_message_nsec("Read only field!", FALSE, 1, TRUE, FALSE); break; } formRecheckRadio(a, Currentbuf, fi); break; case FORM_INPUT_CHECKBOX: if (submit) goto do_submit; if (fi->readonly) { /* FIXME: gettextize? */ disp_message_nsec("Read only field!", FALSE, 1, TRUE, FALSE); break; } fi->checked = !fi->checked; formUpdateBuffer(a, Currentbuf, fi); break; #ifdef MENU_SELECT case FORM_SELECT: if (submit) goto do_submit; if (!formChooseOptionByMenu(fi, Currentbuf->cursorX - Currentbuf->pos + a->start.pos + Currentbuf->rootX, Currentbuf->cursorY + Currentbuf->rootY)) break; formUpdateBuffer(a, Currentbuf, fi); if (fi->parent->nitems == 1) goto do_submit; break; #endif /* MENU_SELECT */ case FORM_INPUT_IMAGE: case FORM_INPUT_SUBMIT: case FORM_INPUT_BUTTON: do_submit: tmp = Strnew(); multipart = (fi->parent->method == FORM_METHOD_POST && fi->parent->enctype == FORM_ENCTYPE_MULTIPART); query_from_followform(&tmp, fi, multipart); tmp2 = Strdup(fi->parent->action); if (!Strcmp_charp(tmp2, "!CURRENT_URL!")) { /* It means "current URL" */ tmp2 = parsedURL2Str(&Currentbuf->currentURL); if ((p = strchr(tmp2->ptr, '?')) != NULL) Strshrink(tmp2, (tmp2->ptr + tmp2->length) - p); } if (fi->parent->method == FORM_METHOD_GET) { if ((p = strchr(tmp2->ptr, '?')) != NULL) Strshrink(tmp2, (tmp2->ptr + tmp2->length) - p); Strcat_charp(tmp2, "?"); Strcat(tmp2, tmp); loadLink(tmp2->ptr, a->target, NULL, NULL); } else if (fi->parent->method == FORM_METHOD_POST) { Buffer *buf; if (multipart) { struct stat st; stat(fi->parent->body, &st); fi->parent->length = st.st_size; } else { fi->parent->body = tmp->ptr; fi->parent->length = tmp->length; } buf = loadLink(tmp2->ptr, a->target, NULL, fi->parent); if (multipart) { unlink(fi->parent->body); } if (buf && !(buf->bufferprop & BP_REDIRECTED)) { /* buf must be Currentbuf */ /* BP_REDIRECTED means that the buffer is obtained through * Location: header. In this case, buf->form_submit must not be set * because the page is not loaded by POST method but GET method. */ buf->form_submit = save_submit_formlist(fi); } } else if ((fi->parent->method == FORM_METHOD_INTERNAL && (!Strcmp_charp(fi->parent->action, "map") || !Strcmp_charp(fi->parent->action, "none"))) || Currentbuf->bufferprop & BP_INTERNAL) { /* internal */ do_internal(tmp2->ptr, tmp->ptr); } else { disp_err_message("Can't send form because of illegal method.", FALSE); } break; case FORM_INPUT_RESET: for (i = 0; i < Currentbuf->formitem->nanchor; i++) { a2 = &Currentbuf->formitem->anchors[i]; f2 = (FormItemList *)a2->url; if (f2->parent == fi->parent && f2->name && f2->value && f2->type != FORM_INPUT_SUBMIT && f2->type != FORM_INPUT_HIDDEN && f2->type != FORM_INPUT_RESET) { f2->value = f2->init_value; f2->checked = f2->init_checked; #ifdef MENU_SELECT f2->label = f2->init_label; f2->selected = f2->init_selected; #endif /* MENU_SELECT */ formUpdateBuffer(a2, Currentbuf, f2); } } break; case FORM_INPUT_HIDDEN: default: break; } displayBuffer(Currentbuf, B_FORCE_REDRAW); } /* go to the top anchor */ DEFUN(topA, LINK_BEGIN, "Move to the first hyperlink") { HmarkerList *hl = Currentbuf->hmarklist; BufferPoint *po; Anchor *an; int hseq = 0; if (Currentbuf->firstLine == NULL) return; if (!hl || hl->nmark == 0) return; if (prec_num > hl->nmark) hseq = hl->nmark - 1; else if (prec_num > 0) hseq = prec_num - 1; do { if (hseq >= hl->nmark) return; po = hl->marks + hseq; an = retrieveAnchor(Currentbuf->href, po->line, po->pos); if (an == NULL) an = retrieveAnchor(Currentbuf->formitem, po->line, po->pos); hseq++; } while (an == NULL); gotoLine(Currentbuf, po->line); Currentbuf->pos = po->pos; arrangeCursor(Currentbuf); displayBuffer(Currentbuf, B_NORMAL); } /* go to the last anchor */ DEFUN(lastA, LINK_END, "Move to the last hyperlink") { HmarkerList *hl = Currentbuf->hmarklist; BufferPoint *po; Anchor *an; int hseq; if (Currentbuf->firstLine == NULL) return; if (!hl || hl->nmark == 0) return; if (prec_num >= hl->nmark) hseq = 0; else if (prec_num > 0) hseq = hl->nmark - prec_num; else hseq = hl->nmark - 1; do { if (hseq < 0) return; po = hl->marks + hseq; an = retrieveAnchor(Currentbuf->href, po->line, po->pos); if (an == NULL) an = retrieveAnchor(Currentbuf->formitem, po->line, po->pos); hseq--; } while (an == NULL); gotoLine(Currentbuf, po->line); Currentbuf->pos = po->pos; arrangeCursor(Currentbuf); displayBuffer(Currentbuf, B_NORMAL); } /* go to the nth anchor */ DEFUN(nthA, LINK_N, "Go to the nth link") { HmarkerList *hl = Currentbuf->hmarklist; BufferPoint *po; Anchor *an; int n = searchKeyNum(); if (n < 0 || n > hl->nmark) return; if (Currentbuf->firstLine == NULL) return; if (!hl || hl->nmark == 0) return; po = hl->marks + n-1; an = retrieveAnchor(Currentbuf->href, po->line, po->pos); if (an == NULL) an = retrieveAnchor(Currentbuf->formitem, po->line, po->pos); if (an == NULL) return; gotoLine(Currentbuf, po->line); Currentbuf->pos = po->pos; arrangeCursor(Currentbuf); displayBuffer(Currentbuf, B_NORMAL); } /* go to the next anchor */ DEFUN(nextA, NEXT_LINK, "Move to the next hyperlink") { _nextA(FALSE); } /* go to the previous anchor */ DEFUN(prevA, PREV_LINK, "Move to the previous hyperlink") { _prevA(FALSE); } /* go to the next visited anchor */ DEFUN(nextVA, NEXT_VISITED, "Move to the next visited hyperlink") { _nextA(TRUE); } /* go to the previous visited anchor */ DEFUN(prevVA, PREV_VISITED, "Move to the previous visited hyperlink") { _prevA(TRUE); } /* go to the next [visited] anchor */ static void _nextA(int visited) { HmarkerList *hl = Currentbuf->hmarklist; BufferPoint *po; Anchor *an, *pan; int i, x, y, n = searchKeyNum(); ParsedURL url; if (Currentbuf->firstLine == NULL) return; if (!hl || hl->nmark == 0) return; an = retrieveCurrentAnchor(Currentbuf); if (visited != TRUE && an == NULL) an = retrieveCurrentForm(Currentbuf); y = Currentbuf->currentLine->linenumber; x = Currentbuf->pos; if (visited == TRUE) { n = hl->nmark; } for (i = 0; i < n; i++) { pan = an; if (an && an->hseq >= 0) { int hseq = an->hseq + 1; do { if (hseq >= hl->nmark) { if (visited == TRUE) return; an = pan; goto _end; } po = &hl->marks[hseq]; an = retrieveAnchor(Currentbuf->href, po->line, po->pos); if (visited != TRUE && an == NULL) an = retrieveAnchor(Currentbuf->formitem, po->line, po->pos); hseq++; if (visited == TRUE && an) { parseURL2(an->url, &url, baseURL(Currentbuf)); if (getHashHist(URLHist, parsedURL2Str(&url)->ptr)) { goto _end; } } } while (an == NULL || an == pan); } else { an = closest_next_anchor(Currentbuf->href, NULL, x, y); if (visited != TRUE) an = closest_next_anchor(Currentbuf->formitem, an, x, y); if (an == NULL) { if (visited == TRUE) return; an = pan; break; } x = an->start.pos; y = an->start.line; if (visited == TRUE) { parseURL2(an->url, &url, baseURL(Currentbuf)); if (getHashHist(URLHist, parsedURL2Str(&url)->ptr)) { goto _end; } } } } if (visited == TRUE) return; _end: if (an == NULL || an->hseq < 0) return; po = &hl->marks[an->hseq]; gotoLine(Currentbuf, po->line); Currentbuf->pos = po->pos; arrangeCursor(Currentbuf); displayBuffer(Currentbuf, B_NORMAL); } /* go to the previous anchor */ static void _prevA(int visited) { HmarkerList *hl = Currentbuf->hmarklist; BufferPoint *po; Anchor *an, *pan; int i, x, y, n = searchKeyNum(); ParsedURL url; if (Currentbuf->firstLine == NULL) return; if (!hl || hl->nmark == 0) return; an = retrieveCurrentAnchor(Currentbuf); if (visited != TRUE && an == NULL) an = retrieveCurrentForm(Currentbuf); y = Currentbuf->currentLine->linenumber; x = Currentbuf->pos; if (visited == TRUE) { n = hl->nmark; } for (i = 0; i < n; i++) { pan = an; if (an && an->hseq >= 0) { int hseq = an->hseq - 1; do { if (hseq < 0) { if (visited == TRUE) return; an = pan; goto _end; } po = hl->marks + hseq; an = retrieveAnchor(Currentbuf->href, po->line, po->pos); if (visited != TRUE && an == NULL) an = retrieveAnchor(Currentbuf->formitem, po->line, po->pos); hseq--; if (visited == TRUE && an) { parseURL2(an->url, &url, baseURL(Currentbuf)); if (getHashHist(URLHist, parsedURL2Str(&url)->ptr)) { goto _end; } } } while (an == NULL || an == pan); } else { an = closest_prev_anchor(Currentbuf->href, NULL, x, y); if (visited != TRUE) an = closest_prev_anchor(Currentbuf->formitem, an, x, y); if (an == NULL) { if (visited == TRUE) return; an = pan; break; } x = an->start.pos; y = an->start.line; if (visited == TRUE && an) { parseURL2(an->url, &url, baseURL(Currentbuf)); if (getHashHist(URLHist, parsedURL2Str(&url)->ptr)) { goto _end; } } } } if (visited == TRUE) return; _end: if (an == NULL || an->hseq < 0) return; po = hl->marks + an->hseq; gotoLine(Currentbuf, po->line); Currentbuf->pos = po->pos; arrangeCursor(Currentbuf); displayBuffer(Currentbuf, B_NORMAL); } /* go to the next left/right anchor */ static void nextX(int d, int dy) { HmarkerList *hl = Currentbuf->hmarklist; Anchor *an, *pan; Line *l; int i, x, y, n = searchKeyNum(); if (Currentbuf->firstLine == NULL) return; if (!hl || hl->nmark == 0) return; an = retrieveCurrentAnchor(Currentbuf); if (an == NULL) an = retrieveCurrentForm(Currentbuf); l = Currentbuf->currentLine; x = Currentbuf->pos; y = l->linenumber; pan = NULL; for (i = 0; i < n; i++) { if (an) x = (d > 0) ? an->end.pos : an->start.pos - 1; an = NULL; while (1) { for (; x >= 0 && x < l->len; x += d) { an = retrieveAnchor(Currentbuf->href, y, x); if (!an) an = retrieveAnchor(Currentbuf->formitem, y, x); if (an) { pan = an; break; } } if (!dy || an) break; l = (dy > 0) ? l->next : l->prev; if (!l) break; x = (d > 0) ? 0 : l->len - 1; y = l->linenumber; } if (!an) break; } if (pan == NULL) return; gotoLine(Currentbuf, y); Currentbuf->pos = pan->start.pos; arrangeCursor(Currentbuf); displayBuffer(Currentbuf, B_NORMAL); } /* go to the next downward/upward anchor */ static void nextY(int d) { HmarkerList *hl = Currentbuf->hmarklist; Anchor *an, *pan; int i, x, y, n = searchKeyNum(); int hseq; if (Currentbuf->firstLine == NULL) return; if (!hl || hl->nmark == 0) return; an = retrieveCurrentAnchor(Currentbuf); if (an == NULL) an = retrieveCurrentForm(Currentbuf); x = Currentbuf->pos; y = Currentbuf->currentLine->linenumber + d; pan = NULL; hseq = -1; for (i = 0; i < n; i++) { if (an) hseq = abs(an->hseq); an = NULL; for (; y >= 0 && y <= Currentbuf->lastLine->linenumber; y += d) { an = retrieveAnchor(Currentbuf->href, y, x); if (!an) an = retrieveAnchor(Currentbuf->formitem, y, x); if (an && hseq != abs(an->hseq)) { pan = an; break; } } if (!an) break; } if (pan == NULL) return; gotoLine(Currentbuf, pan->start.line); arrangeLine(Currentbuf); displayBuffer(Currentbuf, B_NORMAL); } /* go to the next left anchor */ DEFUN(nextL, NEXT_LEFT, "Move left to the next hyperlink") { nextX(-1, 0); } /* go to the next left-up anchor */ DEFUN(nextLU, NEXT_LEFT_UP, "Move left or upward to the next hyperlink") { nextX(-1, -1); } /* go to the next right anchor */ DEFUN(nextR, NEXT_RIGHT, "Move right to the next hyperlink") { nextX(1, 0); } /* go to the next right-down anchor */ DEFUN(nextRD, NEXT_RIGHT_DOWN, "Move right or downward to the next hyperlink") { nextX(1, 1); } /* go to the next downward anchor */ DEFUN(nextD, NEXT_DOWN, "Move downward to the next hyperlink") { nextY(1); } /* go to the next upward anchor */ DEFUN(nextU, NEXT_UP, "Move upward to the next hyperlink") { nextY(-1); } /* go to the next bufferr */ DEFUN(nextBf, NEXT, "Switch to the next buffer") { Buffer *buf; int i; for (i = 0; i < PREC_NUM; i++) { buf = prevBuffer(Firstbuf, Currentbuf); if (!buf) { if (i == 0) return; break; } Currentbuf = buf; } displayBuffer(Currentbuf, B_FORCE_REDRAW); } /* go to the previous bufferr */ DEFUN(prevBf, PREV, "Switch to the previous buffer") { Buffer *buf; int i; for (i = 0; i < PREC_NUM; i++) { buf = Currentbuf->nextBuffer; if (!buf) { if (i == 0) return; break; } Currentbuf = buf; } displayBuffer(Currentbuf, B_FORCE_REDRAW); } static int checkBackBuffer(Buffer *buf) { Buffer *fbuf = buf->linkBuffer[LB_N_FRAME]; if (fbuf) { if (fbuf->frameQ) return TRUE; /* Currentbuf has stacked frames */ /* when no frames stacked and next is frame source, try next's * nextBuffer */ if (RenderFrame && fbuf == buf->nextBuffer) { if (fbuf->nextBuffer != NULL) return TRUE; else return FALSE; } } if (buf->nextBuffer) return TRUE; return FALSE; } /* delete current buffer and back to the previous buffer */ DEFUN(backBf, BACK, "Close current buffer and return to the one below in stack") { Buffer *buf = Currentbuf->linkBuffer[LB_N_FRAME]; if (!checkBackBuffer(Currentbuf)) { if (close_tab_back && nTab >= 1) { deleteTab(CurrentTab); displayBuffer(Currentbuf, B_FORCE_REDRAW); } else /* FIXME: gettextize? */ disp_message("Can't go back...", TRUE); return; } delBuffer(Currentbuf); if (buf) { if (buf->frameQ) { struct frameset *fs; long linenumber = buf->frameQ->linenumber; long top = buf->frameQ->top_linenumber; int pos = buf->frameQ->pos; int currentColumn = buf->frameQ->currentColumn; AnchorList *formitem = buf->frameQ->formitem; fs = popFrameTree(&(buf->frameQ)); deleteFrameSet(buf->frameset); buf->frameset = fs; if (buf == Currentbuf) { rFrame(); Currentbuf->topLine = lineSkip(Currentbuf, Currentbuf->firstLine, top - 1, FALSE); gotoLine(Currentbuf, linenumber); Currentbuf->pos = pos; Currentbuf->currentColumn = currentColumn; arrangeCursor(Currentbuf); formResetBuffer(Currentbuf, formitem); } } else if (RenderFrame && buf == Currentbuf) { delBuffer(Currentbuf); } } displayBuffer(Currentbuf, B_FORCE_REDRAW); } DEFUN(deletePrevBuf, DELETE_PREVBUF, "Delete previous buffer (mainly for local CGI-scripts)") { Buffer *buf = Currentbuf->nextBuffer; if (buf) delBuffer(buf); } static void cmd_loadURL(char *url, ParsedURL *current, char *referer, FormList *request) { Buffer *buf; if (handleMailto(url)) return; #if 0 if (!strncasecmp(url, "news:", 5) && strchr(url, '@') == NULL) { /* news:newsgroup is not supported */ /* FIXME: gettextize? */ disp_err_message("news:newsgroup_name is not supported", TRUE); return; } #endif /* USE_NNTP */ refresh(); buf = loadGeneralFile(url, current, referer, 0, request); if (buf == NULL) { /* FIXME: gettextize? */ char *emsg = Sprintf("Can't load %s", conv_from_system(url))->ptr; disp_err_message(emsg, FALSE); } else if (buf != NO_BUFFER) { pushBuffer(buf); if (RenderFrame && Currentbuf->frameset != NULL) rFrame(); } displayBuffer(Currentbuf, B_NORMAL); } /* go to specified URL */ static void goURL0(char *prompt, int relative) { char *url, *referer; ParsedURL p_url, *current; Buffer *cur_buf = Currentbuf; const int *no_referer_ptr; url = searchKeyData(); if (url == NULL) { Hist *hist = copyHist(URLHist); Anchor *a; current = baseURL(Currentbuf); if (current) { char *c_url = parsedURL2Str(current)->ptr; if (DefaultURLString == DEFAULT_URL_CURRENT) url = url_decode2(c_url, NULL); else pushHist(hist, c_url); } a = retrieveCurrentAnchor(Currentbuf); if (a) { char *a_url; parseURL2(a->url, &p_url, current); a_url = parsedURL2Str(&p_url)->ptr; if (DefaultURLString == DEFAULT_URL_LINK) url = url_decode2(a_url, Currentbuf); else pushHist(hist, a_url); } url = inputLineHist(prompt, url, IN_URL, hist); if (url != NULL) SKIP_BLANKS(url); } if (relative) { no_referer_ptr = query_SCONF_NO_REFERER_FROM(&Currentbuf->currentURL); current = baseURL(Currentbuf); if ((no_referer_ptr && *no_referer_ptr) || current == NULL || current->scheme == SCM_LOCAL || current->scheme == SCM_LOCAL_CGI) referer = NO_REFERER; else referer = parsedURL2Str(&Currentbuf->currentURL)->ptr; url = url_encode(url, current, Currentbuf->document_charset); } else { current = NULL; referer = NULL; url = url_encode(url, NULL, 0); } if (url == NULL || *url == '\0') { displayBuffer(Currentbuf, B_FORCE_REDRAW); return; } if (*url == '#') { gotoLabel(url + 1); return; } parseURL2(url, &p_url, current); pushHashHist(URLHist, parsedURL2Str(&p_url)->ptr); cmd_loadURL(url, current, referer, NULL); if (Currentbuf != cur_buf) /* success */ pushHashHist(URLHist, parsedURL2Str(&Currentbuf->currentURL)->ptr); } DEFUN(goURL, GOTO, "Open specified document in a new buffer") { goURL0("Goto URL: ", FALSE); } DEFUN(gorURL, GOTO_RELATIVE, "Go to relative address") { goURL0("Goto relative URL: ", TRUE); } static void cmd_loadBuffer(Buffer *buf, int prop, int linkid) { if (buf == NULL) { disp_err_message("Can't load string", FALSE); } else if (buf != NO_BUFFER) { buf->bufferprop |= (BP_INTERNAL | prop); if (!(buf->bufferprop & BP_NO_URL)) copyParsedURL(&buf->currentURL, &Currentbuf->currentURL); if (linkid != LB_NOLINK) { buf->linkBuffer[REV_LB[linkid]] = Currentbuf; Currentbuf->linkBuffer[linkid] = buf; } pushBuffer(buf); } displayBuffer(Currentbuf, B_FORCE_REDRAW); } /* load bookmark */ DEFUN(ldBmark, BOOKMARK VIEW_BOOKMARK, "View bookmarks") { cmd_loadURL(BookmarkFile, NULL, NO_REFERER, NULL); } /* Add current to bookmark */ DEFUN(adBmark, ADD_BOOKMARK, "Add current page to bookmarks") { Str tmp; FormList *request; tmp = Sprintf("mode=panel&cookie=%s&bmark=%s&url=%s&title=%s" #ifdef USE_M17N "&charset=%s" #endif , (Str_form_quote(localCookie()))->ptr, (Str_form_quote(Strnew_charp(BookmarkFile)))->ptr, (Str_form_quote(parsedURL2Str(&Currentbuf->currentURL)))-> ptr, #ifdef USE_M17N (Str_form_quote(wc_conv_strict(Currentbuf->buffername, InnerCharset, BookmarkCharset)))->ptr, wc_ces_to_charset(BookmarkCharset)); #else (Str_form_quote(Strnew_charp(Currentbuf->buffername)))->ptr); #endif request = newFormList(NULL, "post", NULL, NULL, NULL, NULL, NULL); request->body = tmp->ptr; request->length = tmp->length; cmd_loadURL("file:///$LIB/" W3MBOOKMARK_CMDNAME, NULL, NO_REFERER, request); } /* option setting */ DEFUN(ldOpt, OPTIONS, "Display options setting panel") { cmd_loadBuffer(load_option_panel(), BP_NO_URL, LB_NOLINK); } /* set an option */ DEFUN(setOpt, SET_OPTION, "Set option") { char *opt; CurrentKeyData = NULL; /* not allowed in w3m-control: */ opt = searchKeyData(); if (opt == NULL || *opt == '\0' || strchr(opt, '=') == NULL) { if (opt != NULL && *opt != '\0') { char *v = get_param_option(opt); opt = Sprintf("%s=%s", opt, v ? v : "")->ptr; } opt = inputStrHist("Set option: ", opt, TextHist); if (opt == NULL || *opt == '\0') { displayBuffer(Currentbuf, B_NORMAL); return; } } if (set_param_option(opt)) sync_with_option(); displayBuffer(Currentbuf, B_REDRAW_IMAGE); } /* error message list */ DEFUN(msgs, MSGS, "Display error messages") { cmd_loadBuffer(message_list_panel(), BP_NO_URL, LB_NOLINK); } /* page info */ DEFUN(pginfo, INFO, "Display information about the current document") { Buffer *buf; if ((buf = Currentbuf->linkBuffer[LB_N_INFO]) != NULL) { Currentbuf = buf; displayBuffer(Currentbuf, B_NORMAL); return; } if ((buf = Currentbuf->linkBuffer[LB_INFO]) != NULL) delBuffer(buf); buf = page_info_panel(Currentbuf); cmd_loadBuffer(buf, BP_NORMAL, LB_INFO); } void follow_map(struct parsed_tagarg *arg) { char *name = tag_get_value(arg, "link"); #if defined(MENU_MAP) || defined(USE_IMAGE) Anchor *an; MapArea *a; int x, y; ParsedURL p_url; an = retrieveCurrentImg(Currentbuf); x = Currentbuf->cursorX + Currentbuf->rootX; y = Currentbuf->cursorY + Currentbuf->rootY; a = follow_map_menu(Currentbuf, name, an, x, y); if (a == NULL || a->url == NULL || *(a->url) == '\0') { #endif #ifndef MENU_MAP Buffer *buf = follow_map_panel(Currentbuf, name); if (buf != NULL) cmd_loadBuffer(buf, BP_NORMAL, LB_NOLINK); #endif #if defined(MENU_MAP) || defined(USE_IMAGE) return; } if (*(a->url) == '#') { gotoLabel(a->url + 1); return; } parseURL2(a->url, &p_url, baseURL(Currentbuf)); pushHashHist(URLHist, parsedURL2Str(&p_url)->ptr); if (check_target && open_tab_blank && a->target && (!strcasecmp(a->target, "_new") || !strcasecmp(a->target, "_blank"))) { Buffer *buf; _newT(); buf = Currentbuf; cmd_loadURL(a->url, baseURL(Currentbuf), parsedURL2Str(&Currentbuf->currentURL)->ptr, NULL); if (buf != Currentbuf) delBuffer(buf); else deleteTab(CurrentTab); displayBuffer(Currentbuf, B_FORCE_REDRAW); return; } cmd_loadURL(a->url, baseURL(Currentbuf), parsedURL2Str(&Currentbuf->currentURL)->ptr, NULL); #endif } #ifdef USE_MENU /* link menu */ DEFUN(linkMn, LINK_MENU, "Pop up link element menu") { LinkList *l = link_menu(Currentbuf); ParsedURL p_url; if (!l || !l->url) return; if (*(l->url) == '#') { gotoLabel(l->url + 1); return; } parseURL2(l->url, &p_url, baseURL(Currentbuf)); pushHashHist(URLHist, parsedURL2Str(&p_url)->ptr); cmd_loadURL(l->url, baseURL(Currentbuf), parsedURL2Str(&Currentbuf->currentURL)->ptr, NULL); } static void anchorMn(Anchor *(*menu_func) (Buffer *), int go) { Anchor *a; BufferPoint *po; if (!Currentbuf->href || !Currentbuf->hmarklist) return; a = menu_func(Currentbuf); if (!a || a->hseq < 0) return; po = &Currentbuf->hmarklist->marks[a->hseq]; gotoLine(Currentbuf, po->line); Currentbuf->pos = po->pos; arrangeCursor(Currentbuf); displayBuffer(Currentbuf, B_NORMAL); if (go) followA(); } /* accesskey */ DEFUN(accessKey, ACCESSKEY, "Pop up accesskey menu") { anchorMn(accesskey_menu, TRUE); } /* list menu */ DEFUN(listMn, LIST_MENU, "Pop up menu for hyperlinks to browse to") { anchorMn(list_menu, TRUE); } DEFUN(movlistMn, MOVE_LIST_MENU, "Pop up menu to navigate between hyperlinks") { anchorMn(list_menu, FALSE); } #endif /* link,anchor,image list */ DEFUN(linkLst, LIST, "Show all URLs referenced") { Buffer *buf; buf = link_list_panel(Currentbuf); if (buf != NULL) { #ifdef USE_M17N buf->document_charset = Currentbuf->document_charset; #endif cmd_loadBuffer(buf, BP_NORMAL, LB_NOLINK); } } #ifdef USE_COOKIE /* cookie list */ DEFUN(cooLst, COOKIE, "View cookie list") { Buffer *buf; buf = cookie_list_panel(); if (buf != NULL) cmd_loadBuffer(buf, BP_NO_URL, LB_NOLINK); } #endif /* USE_COOKIE */ #ifdef USE_HISTORY /* History page */ DEFUN(ldHist, HISTORY, "Show browsing history") { cmd_loadBuffer(historyBuffer(URLHist), BP_NO_URL, LB_NOLINK); } #endif /* USE_HISTORY */ /* download HREF link */ DEFUN(svA, SAVE_LINK, "Save hyperlink target") { CurrentKeyData = NULL; /* not allowed in w3m-control: */ do_download = TRUE; followA(); do_download = FALSE; } /* download IMG link */ DEFUN(svI, SAVE_IMAGE, "Save inline image") { CurrentKeyData = NULL; /* not allowed in w3m-control: */ do_download = TRUE; followI(); do_download = FALSE; } /* save buffer */ DEFUN(svBuf, PRINT SAVE_SCREEN, "Save rendered document") { char *qfile = NULL, *file; FILE *f; int is_pipe; CurrentKeyData = NULL; /* not allowed in w3m-control: */ file = searchKeyData(); if (file == NULL || *file == '\0') { /* FIXME: gettextize? */ qfile = inputLineHist("Save buffer to: ", NULL, IN_COMMAND, SaveHist); if (qfile == NULL || *qfile == '\0') { displayBuffer(Currentbuf, B_NORMAL); return; } } file = conv_to_system(qfile ? qfile : file); if (*file == '|') { is_pipe = TRUE; f = popen(file + 1, "w"); } else { if (qfile) { file = unescape_spaces(Strnew_charp(qfile))->ptr; file = conv_to_system(file); } file = expandPath(file); if (checkOverWrite(file) < 0) { displayBuffer(Currentbuf, B_NORMAL); return; } f = fopen(file, "w"); is_pipe = FALSE; } if (f == NULL) { /* FIXME: gettextize? */ char *emsg = Sprintf("Can't open %s", conv_from_system(file))->ptr; disp_err_message(emsg, TRUE); return; } saveBuffer(Currentbuf, f, TRUE); if (is_pipe) pclose(f); else fclose(f); displayBuffer(Currentbuf, B_NORMAL); } /* save source */ DEFUN(svSrc, DOWNLOAD SAVE, "Save document source") { char *file; if (Currentbuf->sourcefile == NULL) return; CurrentKeyData = NULL; /* not allowed in w3m-control: */ PermitSaveToPipe = TRUE; if (Currentbuf->real_scheme == SCM_LOCAL) file = conv_from_system(guess_save_name(NULL, Currentbuf->currentURL. real_file)); else file = guess_save_name(Currentbuf, Currentbuf->currentURL.file); doFileCopy(Currentbuf->sourcefile, file); PermitSaveToPipe = FALSE; displayBuffer(Currentbuf, B_NORMAL); } static void _peekURL(int only_img) { Anchor *a; ParsedURL pu; static Str s = NULL; #ifdef USE_M17N static Lineprop *p = NULL; Lineprop *pp; #endif static int offset = 0, n; if (Currentbuf->firstLine == NULL) return; if (CurrentKey == prev_key && s != NULL) { if (s->length - offset >= COLS) offset++; else if (s->length <= offset) /* bug ? */ offset = 0; goto disp; } else { offset = 0; } s = NULL; a = (only_img ? NULL : retrieveCurrentAnchor(Currentbuf)); if (a == NULL) { a = (only_img ? NULL : retrieveCurrentForm(Currentbuf)); if (a == NULL) { a = retrieveCurrentImg(Currentbuf); if (a == NULL) return; } else s = Strnew_charp(form2str((FormItemList *)a->url)); } if (s == NULL) { parseURL2(a->url, &pu, baseURL(Currentbuf)); s = parsedURL2Str(&pu); } if (DecodeURL) s = Strnew_charp(url_decode2(s->ptr, Currentbuf)); #ifdef USE_M17N s = checkType(s, &pp, NULL); p = NewAtom_N(Lineprop, s->length); bcopy((void *)pp, (void *)p, s->length * sizeof(Lineprop)); #endif disp: n = searchKeyNum(); if (n > 1 && s->length > (n - 1) * (COLS - 1)) offset = (n - 1) * (COLS - 1); #ifdef USE_M17N while (offset < s->length && p[offset] & PC_WCHAR2) offset++; #endif disp_message_nomouse(&s->ptr[offset], TRUE); } /* peek URL */ DEFUN(peekURL, PEEK_LINK, "Show target address") { _peekURL(0); } /* peek URL of image */ DEFUN(peekIMG, PEEK_IMG, "Show image address") { _peekURL(1); } /* show current URL */ static Str currentURL(void) { if (Currentbuf->bufferprop & BP_INTERNAL) return Strnew_size(0); return parsedURL2Str(&Currentbuf->currentURL); } DEFUN(curURL, PEEK, "Show current address") { static Str s = NULL; #ifdef USE_M17N static Lineprop *p = NULL; Lineprop *pp; #endif static int offset = 0, n; if (Currentbuf->bufferprop & BP_INTERNAL) return; if (CurrentKey == prev_key && s != NULL) { if (s->length - offset >= COLS) offset++; else if (s->length <= offset) /* bug ? */ offset = 0; } else { offset = 0; s = currentURL(); if (DecodeURL) s = Strnew_charp(url_decode2(s->ptr, NULL)); #ifdef USE_M17N s = checkType(s, &pp, NULL); p = NewAtom_N(Lineprop, s->length); bcopy((void *)pp, (void *)p, s->length * sizeof(Lineprop)); #endif } n = searchKeyNum(); if (n > 1 && s->length > (n - 1) * (COLS - 1)) offset = (n - 1) * (COLS - 1); #ifdef USE_M17N while (offset < s->length && p[offset] & PC_WCHAR2) offset++; #endif disp_message_nomouse(&s->ptr[offset], TRUE); } /* view HTML source */ DEFUN(vwSrc, SOURCE VIEW, "Toggle between HTML shown or processed") { Buffer *buf; if (Currentbuf->type == NULL || Currentbuf->bufferprop & BP_FRAME) return; if ((buf = Currentbuf->linkBuffer[LB_SOURCE]) != NULL || (buf = Currentbuf->linkBuffer[LB_N_SOURCE]) != NULL) { Currentbuf = buf; displayBuffer(Currentbuf, B_NORMAL); return; } if (Currentbuf->sourcefile == NULL) { if (Currentbuf->pagerSource && !strcasecmp(Currentbuf->type, "text/plain")) { #ifdef USE_M17N wc_ces old_charset; wc_bool old_fix_width_conv; #endif FILE *f; Str tmpf = tmpfname(TMPF_SRC, NULL); f = fopen(tmpf->ptr, "w"); if (f == NULL) return; #ifdef USE_M17N old_charset = DisplayCharset; old_fix_width_conv = WcOption.fix_width_conv; DisplayCharset = (Currentbuf->document_charset != WC_CES_US_ASCII) ? Currentbuf->document_charset : 0; WcOption.fix_width_conv = WC_FALSE; #endif saveBufferBody(Currentbuf, f, TRUE); #ifdef USE_M17N DisplayCharset = old_charset; WcOption.fix_width_conv = old_fix_width_conv; #endif fclose(f); Currentbuf->sourcefile = tmpf->ptr; } else { return; } } buf = newBuffer(INIT_BUFFER_WIDTH); if (is_html_type(Currentbuf->type)) { buf->type = "text/plain"; if (Currentbuf->real_type && is_html_type(Currentbuf->real_type)) buf->real_type = "text/plain"; else buf->real_type = Currentbuf->real_type; buf->buffername = Sprintf("source of %s", Currentbuf->buffername)->ptr; buf->linkBuffer[LB_N_SOURCE] = Currentbuf; Currentbuf->linkBuffer[LB_SOURCE] = buf; } else if (!strcasecmp(Currentbuf->type, "text/plain")) { buf->type = "text/html"; if (Currentbuf->real_type && !strcasecmp(Currentbuf->real_type, "text/plain")) buf->real_type = "text/html"; else buf->real_type = Currentbuf->real_type; buf->buffername = Sprintf("HTML view of %s", Currentbuf->buffername)->ptr; buf->linkBuffer[LB_SOURCE] = Currentbuf; Currentbuf->linkBuffer[LB_N_SOURCE] = buf; } else { return; } buf->currentURL = Currentbuf->currentURL; buf->real_scheme = Currentbuf->real_scheme; buf->filename = Currentbuf->filename; buf->sourcefile = Currentbuf->sourcefile; buf->header_source = Currentbuf->header_source; buf->search_header = Currentbuf->search_header; #ifdef USE_M17N buf->document_charset = Currentbuf->document_charset; #endif buf->clone = Currentbuf->clone; (*buf->clone)++; buf->need_reshape = TRUE; reshapeBuffer(buf); pushBuffer(buf); displayBuffer(Currentbuf, B_NORMAL); } /* reload */ DEFUN(reload, RELOAD, "Load current document anew") { Buffer *buf, *fbuf = NULL, sbuf; #ifdef USE_M17N wc_ces old_charset; #endif Str url; FormList *request; int multipart; if (Currentbuf->bufferprop & BP_INTERNAL) { if (!strcmp(Currentbuf->buffername, DOWNLOAD_LIST_TITLE)) { ldDL(); return; } /* FIXME: gettextize? */ disp_err_message("Can't reload...", TRUE); return; } if (Currentbuf->currentURL.scheme == SCM_LOCAL && !strcmp(Currentbuf->currentURL.file, "-")) { /* file is std input */ /* FIXME: gettextize? */ disp_err_message("Can't reload stdin", TRUE); return; } copyBuffer(&sbuf, Currentbuf); if (Currentbuf->bufferprop & BP_FRAME && (fbuf = Currentbuf->linkBuffer[LB_N_FRAME])) { if (fmInitialized) { message("Rendering frame", 0, 0); refresh(); } if (!(buf = renderFrame(fbuf, 1))) { displayBuffer(Currentbuf, B_NORMAL); return; } if (fbuf->linkBuffer[LB_FRAME]) { if (buf->sourcefile && fbuf->linkBuffer[LB_FRAME]->sourcefile && !strcmp(buf->sourcefile, fbuf->linkBuffer[LB_FRAME]->sourcefile)) fbuf->linkBuffer[LB_FRAME]->sourcefile = NULL; delBuffer(fbuf->linkBuffer[LB_FRAME]); } fbuf->linkBuffer[LB_FRAME] = buf; buf->linkBuffer[LB_N_FRAME] = fbuf; pushBuffer(buf); Currentbuf = buf; if (Currentbuf->firstLine) { COPY_BUFROOT(Currentbuf, &sbuf); restorePosition(Currentbuf, &sbuf); } displayBuffer(Currentbuf, B_FORCE_REDRAW); return; } else if (Currentbuf->frameset != NULL) fbuf = Currentbuf->linkBuffer[LB_FRAME]; multipart = 0; if (Currentbuf->form_submit) { request = Currentbuf->form_submit->parent; if (request->method == FORM_METHOD_POST && request->enctype == FORM_ENCTYPE_MULTIPART) { Str query; struct stat st; multipart = 1; query_from_followform(&query, Currentbuf->form_submit, multipart); stat(request->body, &st); request->length = st.st_size; } } else { request = NULL; } url = parsedURL2Str(&Currentbuf->currentURL); /* FIXME: gettextize? */ message("Reloading...", 0, 0); refresh(); #ifdef USE_M17N old_charset = DocumentCharset; if (Currentbuf->document_charset != WC_CES_US_ASCII) DocumentCharset = Currentbuf->document_charset; #endif SearchHeader = Currentbuf->search_header; DefaultType = Currentbuf->real_type; buf = loadGeneralFile(url->ptr, NULL, NO_REFERER, RG_NOCACHE, request); #ifdef USE_M17N DocumentCharset = old_charset; #endif SearchHeader = FALSE; DefaultType = NULL; if (multipart) unlink(request->body); if (buf == NULL) { /* FIXME: gettextize? */ disp_err_message("Can't reload...", TRUE); return; } else if (buf == NO_BUFFER) { displayBuffer(Currentbuf, B_NORMAL); return; } if (fbuf != NULL) Firstbuf = deleteBuffer(Firstbuf, fbuf); repBuffer(Currentbuf, buf); if ((buf->type != NULL) && (sbuf.type != NULL) && ((!strcasecmp(buf->type, "text/plain") && is_html_type(sbuf.type)) || (is_html_type(buf->type) && !strcasecmp(sbuf.type, "text/plain")))) { vwSrc(); if (Currentbuf != buf) Firstbuf = deleteBuffer(Firstbuf, buf); } Currentbuf->search_header = sbuf.search_header; Currentbuf->form_submit = sbuf.form_submit; if (Currentbuf->firstLine) { COPY_BUFROOT(Currentbuf, &sbuf); restorePosition(Currentbuf, &sbuf); } displayBuffer(Currentbuf, B_FORCE_REDRAW); } /* reshape */ DEFUN(reshape, RESHAPE, "Re-render document") { Currentbuf->need_reshape = TRUE; reshapeBuffer(Currentbuf); displayBuffer(Currentbuf, B_FORCE_REDRAW); } #ifdef USE_M17N static void _docCSet(wc_ces charset) { if (Currentbuf->bufferprop & BP_INTERNAL) return; if (Currentbuf->sourcefile == NULL) { disp_message("Can't reload...", FALSE); return; } Currentbuf->document_charset = charset; Currentbuf->need_reshape = TRUE; displayBuffer(Currentbuf, B_FORCE_REDRAW); } void change_charset(struct parsed_tagarg *arg) { Buffer *buf = Currentbuf->linkBuffer[LB_N_INFO]; wc_ces charset; if (buf == NULL) return; delBuffer(Currentbuf); Currentbuf = buf; if (Currentbuf->bufferprop & BP_INTERNAL) return; charset = Currentbuf->document_charset; for (; arg; arg = arg->next) { if (!strcmp(arg->arg, "charset")) charset = atoi(arg->value); } _docCSet(charset); } DEFUN(docCSet, CHARSET, "Change the character encoding for the current document") { char *cs; wc_ces charset; cs = searchKeyData(); if (cs == NULL || *cs == '\0') /* FIXME: gettextize? */ cs = inputStr("Document charset: ", wc_ces_to_charset(Currentbuf->document_charset)); charset = wc_guess_charset_short(cs, 0); if (charset == 0) { displayBuffer(Currentbuf, B_NORMAL); return; } _docCSet(charset); } DEFUN(defCSet, DEFAULT_CHARSET, "Change the default character encoding") { char *cs; wc_ces charset; cs = searchKeyData(); if (cs == NULL || *cs == '\0') /* FIXME: gettextize? */ cs = inputStr("Default document charset: ", wc_ces_to_charset(DocumentCharset)); charset = wc_guess_charset_short(cs, 0); if (charset != 0) DocumentCharset = charset; displayBuffer(Currentbuf, B_NORMAL); } #endif /* mark URL-like patterns as anchors */ void chkURLBuffer(Buffer *buf) { static char *url_like_pat[] = { "https?://[a-zA-Z0-9][a-zA-Z0-9:%\\-\\./?=~_\\&+@#,\\$;]*[a-zA-Z0-9_/=\\-]", "file:/[a-zA-Z0-9:%\\-\\./=_\\+@#,\\$;]*", #ifdef USE_GOPHER "gopher://[a-zA-Z0-9][a-zA-Z0-9:%\\-\\./_]*", #endif /* USE_GOPHER */ "ftp://[a-zA-Z0-9][a-zA-Z0-9:%\\-\\./=_+@#,\\$]*[a-zA-Z0-9_/]", #ifdef USE_NNTP "news:[^<> ][^<> ]*", "nntp://[a-zA-Z0-9][a-zA-Z0-9:%\\-\\./_]*", #endif /* USE_NNTP */ #ifndef USE_W3MMAILER /* see also chkExternalURIBuffer() */ "mailto:[^<> ][^<> ]*@[a-zA-Z0-9][a-zA-Z0-9\\-\\._]*[a-zA-Z0-9]", #endif #ifdef INET6 "https?://[a-zA-Z0-9:%\\-\\./_@]*\\[[a-fA-F0-9:][a-fA-F0-9:\\.]*\\][a-zA-Z0-9:%\\-\\./?=~_\\&+@#,\\$;]*", "ftp://[a-zA-Z0-9:%\\-\\./_@]*\\[[a-fA-F0-9:][a-fA-F0-9:\\.]*\\][a-zA-Z0-9:%\\-\\./=_+@#,\\$]*", #endif /* INET6 */ NULL }; int i; for (i = 0; url_like_pat[i]; i++) { reAnchor(buf, url_like_pat[i]); } #ifdef USE_EXTERNAL_URI_LOADER chkExternalURIBuffer(buf); #endif buf->check_url |= CHK_URL; } DEFUN(chkURL, MARK_URL, "Turn URL-like strings into hyperlinks") { chkURLBuffer(Currentbuf); displayBuffer(Currentbuf, B_FORCE_REDRAW); } DEFUN(chkWORD, MARK_WORD, "Turn current word into hyperlink") { char *p; int spos, epos; p = getCurWord(Currentbuf, &spos, &epos); if (p == NULL) return; reAnchorWord(Currentbuf, Currentbuf->currentLine, spos, epos); displayBuffer(Currentbuf, B_FORCE_REDRAW); } #ifdef USE_NNTP /* mark Message-ID-like patterns as NEWS anchors */ void chkNMIDBuffer(Buffer *buf) { static char *url_like_pat[] = { "<[!-;=?-~]+@[a-zA-Z0-9\\.\\-_]+>", NULL, }; int i; for (i = 0; url_like_pat[i]; i++) { reAnchorNews(buf, url_like_pat[i]); } buf->check_url |= CHK_NMID; } DEFUN(chkNMID, MARK_MID, "Turn Message-ID-like strings into hyperlinks") { chkNMIDBuffer(Currentbuf); displayBuffer(Currentbuf, B_FORCE_REDRAW); } #endif /* USE_NNTP */ /* render frames */ DEFUN(rFrame, FRAME, "Toggle rendering HTML frames") { Buffer *buf; if ((buf = Currentbuf->linkBuffer[LB_FRAME]) != NULL) { Currentbuf = buf; displayBuffer(Currentbuf, B_NORMAL); return; } if (Currentbuf->frameset == NULL) { if ((buf = Currentbuf->linkBuffer[LB_N_FRAME]) != NULL) { Currentbuf = buf; displayBuffer(Currentbuf, B_NORMAL); } return; } if (fmInitialized) { message("Rendering frame", 0, 0); refresh(); } buf = renderFrame(Currentbuf, 0); if (buf == NULL) { displayBuffer(Currentbuf, B_NORMAL); return; } buf->linkBuffer[LB_N_FRAME] = Currentbuf; Currentbuf->linkBuffer[LB_FRAME] = buf; pushBuffer(buf); if (fmInitialized && display_ok) displayBuffer(Currentbuf, B_FORCE_REDRAW); } /* spawn external browser */ static void invoke_browser(char *url) { Str cmd; char *browser = NULL; int bg = 0, len; CurrentKeyData = NULL; /* not allowed in w3m-control: */ browser = searchKeyData(); if (browser == NULL || *browser == '\0') { switch (prec_num) { case 0: case 1: browser = ExtBrowser; break; case 2: browser = ExtBrowser2; break; case 3: browser = ExtBrowser3; break; case 4: browser = ExtBrowser4; break; case 5: browser = ExtBrowser5; break; case 6: browser = ExtBrowser6; break; case 7: browser = ExtBrowser7; break; case 8: browser = ExtBrowser8; break; case 9: browser = ExtBrowser9; break; } if (browser == NULL || *browser == '\0') { browser = inputStr("Browse command: ", NULL); if (browser != NULL) browser = conv_to_system(browser); } } else { browser = conv_to_system(browser); } if (browser == NULL || *browser == '\0') { displayBuffer(Currentbuf, B_NORMAL); return; } if ((len = strlen(browser)) >= 2 && browser[len - 1] == '&' && browser[len - 2] != '\\') { browser = allocStr(browser, len - 2); bg = 1; } cmd = myExtCommand(browser, shell_quote(url), FALSE); Strremovetrailingspaces(cmd); fmTerm(); mySystem(cmd->ptr, bg); fmInit(); displayBuffer(Currentbuf, B_FORCE_REDRAW); } DEFUN(extbrz, EXTERN, "Display using an external browser") { if (Currentbuf->bufferprop & BP_INTERNAL) { /* FIXME: gettextize? */ disp_err_message("Can't browse...", TRUE); return; } if (Currentbuf->currentURL.scheme == SCM_LOCAL && !strcmp(Currentbuf->currentURL.file, "-")) { /* file is std input */ /* FIXME: gettextize? */ disp_err_message("Can't browse stdin", TRUE); return; } invoke_browser(parsedURL2Str(&Currentbuf->currentURL)->ptr); } DEFUN(linkbrz, EXTERN_LINK, "Display target using an external browser") { Anchor *a; ParsedURL pu; if (Currentbuf->firstLine == NULL) return; a = retrieveCurrentAnchor(Currentbuf); if (a == NULL) return; parseURL2(a->url, &pu, baseURL(Currentbuf)); invoke_browser(parsedURL2Str(&pu)->ptr); } /* show current line number and number of lines in the entire document */ DEFUN(curlno, LINE_INFO, "Display current position in document") { Line *l = Currentbuf->currentLine; Str tmp; int cur = 0, all = 0, col = 0, len = 0; if (l != NULL) { cur = l->real_linenumber; col = l->bwidth + Currentbuf->currentColumn + Currentbuf->cursorX + 1; while (l->next && l->next->bpos) l = l->next; if (l->width < 0) l->width = COLPOS(l, l->len); len = l->bwidth + l->width; } if (Currentbuf->lastLine) all = Currentbuf->lastLine->real_linenumber; if (Currentbuf->pagerSource && !(Currentbuf->bufferprop & BP_CLOSE)) tmp = Sprintf("line %d col %d/%d", cur, col, len); else tmp = Sprintf("line %d/%d (%d%%) col %d/%d", cur, all, (int)((double)cur * 100.0 / (double)(all ? all : 1) + 0.5), col, len); #ifdef USE_M17N Strcat_charp(tmp, " "); Strcat_charp(tmp, wc_ces_to_charset_desc(Currentbuf->document_charset)); #endif disp_message(tmp->ptr, FALSE); } #ifdef USE_IMAGE DEFUN(dispI, DISPLAY_IMAGE, "Restart loading and drawing of images") { if (!displayImage) initImage(); if (!activeImage) return; displayImage = TRUE; /* * if (!(Currentbuf->type && is_html_type(Currentbuf->type))) * return; */ Currentbuf->image_flag = IMG_FLAG_AUTO; Currentbuf->need_reshape = TRUE; displayBuffer(Currentbuf, B_REDRAW_IMAGE); } DEFUN(stopI, STOP_IMAGE, "Stop loading and drawing of images") { if (!activeImage) return; /* * if (!(Currentbuf->type && is_html_type(Currentbuf->type))) * return; */ Currentbuf->image_flag = IMG_FLAG_SKIP; displayBuffer(Currentbuf, B_REDRAW_IMAGE); } #endif #ifdef USE_MOUSE static int mouse_scroll_line(void) { if (relative_wheel_scroll) return (relative_wheel_scroll_ratio * LASTLINE + 99) / 100; else return fixed_wheel_scroll_count; } static TabBuffer * posTab(int x, int y) { TabBuffer *tab; if (mouse_action.menu_str && x < mouse_action.menu_width && y == 0) return NO_TABBUFFER; if (y > LastTab->y) return NULL; for (tab = FirstTab; tab; tab = tab->nextTab) { if (tab->x1 <= x && x <= tab->x2 && tab->y == y) return tab; } return NULL; } static void do_mouse_action(int btn, int x, int y) { MouseActionMap *map = NULL; int ny = -1; if (nTab > 1 || mouse_action.menu_str) ny = LastTab->y + 1; switch (btn) { case MOUSE_BTN1_DOWN: btn = 0; break; case MOUSE_BTN2_DOWN: btn = 1; break; case MOUSE_BTN3_DOWN: btn = 2; break; default: return; } if (y < ny) { if (mouse_action.menu_str && x >= 0 && x < mouse_action.menu_width) { if (mouse_action.menu_map[btn]) map = &mouse_action.menu_map[btn][x]; } else map = &mouse_action.tab_map[btn]; } else if (y == LASTLINE) { if (mouse_action.lastline_str && x >= 0 && x < mouse_action.lastline_width) { if (mouse_action.lastline_map[btn]) map = &mouse_action.lastline_map[btn][x]; } } else if (y > ny) { if (y == Currentbuf->cursorY + Currentbuf->rootY && (x == Currentbuf->cursorX + Currentbuf->rootX #ifdef USE_M17N || (WcOption.use_wide && Currentbuf->currentLine != NULL && (CharType(Currentbuf->currentLine->propBuf[Currentbuf->pos]) == PC_KANJI1) && x == Currentbuf->cursorX + Currentbuf->rootX + 1) #endif )) { if (retrieveCurrentAnchor(Currentbuf) || retrieveCurrentForm(Currentbuf)) { map = &mouse_action.active_map[btn]; if (!(map && map->func)) map = &mouse_action.anchor_map[btn]; } } else { int cx = Currentbuf->cursorX, cy = Currentbuf->cursorY; cursorXY(Currentbuf, x - Currentbuf->rootX, y - Currentbuf->rootY); if (y == Currentbuf->cursorY + Currentbuf->rootY && (x == Currentbuf->cursorX + Currentbuf->rootX #ifdef USE_M17N || (WcOption.use_wide && Currentbuf->currentLine != NULL && (CharType(Currentbuf->currentLine-> propBuf[Currentbuf->pos]) == PC_KANJI1) && x == Currentbuf->cursorX + Currentbuf->rootX + 1) #endif ) && (retrieveCurrentAnchor(Currentbuf) || retrieveCurrentForm(Currentbuf))) map = &mouse_action.anchor_map[btn]; cursorXY(Currentbuf, cx, cy); } } else { return; } if (!(map && map->func)) map = &mouse_action.default_map[btn]; if (map && map->func) { mouse_action.in_action = TRUE; mouse_action.cursorX = x; mouse_action.cursorY = y; CurrentKey = -1; CurrentKeyData = NULL; CurrentCmdData = map->data; (*map->func) (); CurrentCmdData = NULL; } } static void process_mouse(int btn, int x, int y) { int delta_x, delta_y, i; static int press_btn = MOUSE_BTN_RESET, press_x, press_y; TabBuffer *t; int ny = -1; if (nTab > 1 || mouse_action.menu_str) ny = LastTab->y + 1; if (btn == MOUSE_BTN_UP) { switch (press_btn) { case MOUSE_BTN1_DOWN: if (press_y == y && press_x == x) do_mouse_action(press_btn, x, y); else if (ny > 0 && y < ny) { if (press_y < ny) { moveTab(posTab(press_x, press_y), posTab(x, y), (press_y == y) ? (press_x < x) : (press_y < y)); return; } else if (press_x >= Currentbuf->rootX) { Buffer *buf = Currentbuf; int cx = Currentbuf->cursorX, cy = Currentbuf->cursorY; t = posTab(x, y); if (t == NULL) return; if (t == NO_TABBUFFER) t = NULL; /* open new tab */ cursorXY(Currentbuf, press_x - Currentbuf->rootX, press_y - Currentbuf->rootY); if (Currentbuf->cursorY == press_y - Currentbuf->rootY && (Currentbuf->cursorX == press_x - Currentbuf->rootX #ifdef USE_M17N || (WcOption.use_wide && Currentbuf->currentLine != NULL && (CharType(Currentbuf->currentLine-> propBuf[Currentbuf->pos]) == PC_KANJI1) && Currentbuf->cursorX == press_x - Currentbuf->rootX - 1) #endif )) { displayBuffer(Currentbuf, B_NORMAL); followTab(t); } if (buf == Currentbuf) cursorXY(Currentbuf, cx, cy); } return; } else { delta_x = x - press_x; delta_y = y - press_y; if (abs(delta_x) < abs(delta_y) / 3) delta_x = 0; if (abs(delta_y) < abs(delta_x) / 3) delta_y = 0; if (reverse_mouse) { delta_y = -delta_y; delta_x = -delta_x; } if (delta_y > 0) { prec_num = delta_y; ldown1(); } else if (delta_y < 0) { prec_num = -delta_y; lup1(); } if (delta_x > 0) { prec_num = delta_x; col1L(); } else if (delta_x < 0) { prec_num = -delta_x; col1R(); } } break; case MOUSE_BTN2_DOWN: case MOUSE_BTN3_DOWN: if (press_y == y && press_x == x) do_mouse_action(press_btn, x, y); break; case MOUSE_BTN4_DOWN_RXVT: for (i = 0; i < mouse_scroll_line(); i++) ldown1(); break; case MOUSE_BTN5_DOWN_RXVT: for (i = 0; i < mouse_scroll_line(); i++) lup1(); break; } } else if (btn == MOUSE_BTN4_DOWN_XTERM) { for (i = 0; i < mouse_scroll_line(); i++) ldown1(); } else if (btn == MOUSE_BTN5_DOWN_XTERM) { for (i = 0; i < mouse_scroll_line(); i++) lup1(); } if (btn != MOUSE_BTN4_DOWN_RXVT || press_btn == MOUSE_BTN_RESET) { press_btn = btn; press_x = x; press_y = y; } else { press_btn = MOUSE_BTN_RESET; } } DEFUN(msToggle, MOUSE_TOGGLE, "Toggle mouse support") { if (use_mouse) { use_mouse = FALSE; } else { use_mouse = TRUE; } displayBuffer(Currentbuf, B_FORCE_REDRAW); } DEFUN(mouse, MOUSE, "mouse operation") { int btn, x, y; btn = (unsigned char)getch() - 32; #if defined(__CYGWIN__) && CYGWIN_VERSION_DLL_MAJOR < 1005 if (cygwin_mouse_btn_swapped) { if (btn == MOUSE_BTN2_DOWN) btn = MOUSE_BTN3_DOWN; else if (btn == MOUSE_BTN3_DOWN) btn = MOUSE_BTN2_DOWN; } #endif x = (unsigned char)getch() - 33; if (x < 0) x += 0x100; y = (unsigned char)getch() - 33; if (y < 0) y += 0x100; if (x < 0 || x >= COLS || y < 0 || y > LASTLINE) return; process_mouse(btn, x, y); } DEFUN(sgrmouse, SGRMOUSE, "SGR 1006 mouse operation") { int btn = 0, x = 0, y = 0; unsigned char c; do { c = getch(); if (IS_DIGIT(c)) btn = btn * 10 + c - '0'; else if (c == ';') break; else return; } while (1); #if defined(__CYGWIN__) && CYGWIN_VERSION_DLL_MAJOR < 1005 if (cygwin_mouse_btn_swapped) { if (btn == MOUSE_BTN2_DOWN) btn = MOUSE_BTN3_DOWN; else if (btn == MOUSE_BTN3_DOWN) btn = MOUSE_BTN2_DOWN; }; #endif do { c = getch(); if (IS_DIGIT(c)) x = x * 10 + c - '0'; else if (c == ';') break; else return; } while (1); if (x>0) x--; do { c = getch(); if (IS_DIGIT(c)) y = y * 10 + c - '0'; else if (c == 'M') break; else if (c == 'm') { btn |= 3; break; } else return; } while (1); if (y>0) y--; if (x < 0 || x >= COLS || y < 0 || y > LASTLINE) return; process_mouse(btn, x, y); } #ifdef USE_GPM int gpm_process_mouse(Gpm_Event * event, void *data) { int btn = MOUSE_BTN_RESET, x, y; if (event->type & GPM_UP) btn = MOUSE_BTN_UP; else if (event->type & GPM_DOWN) { switch (event->buttons) { case GPM_B_LEFT: btn = MOUSE_BTN1_DOWN; break; case GPM_B_MIDDLE: btn = MOUSE_BTN2_DOWN; break; case GPM_B_RIGHT: btn = MOUSE_BTN3_DOWN; break; } } else { GPM_DRAWPOINTER(event); return 0; } x = event->x; y = event->y; process_mouse(btn, x - 1, y - 1); return 0; } #endif /* USE_GPM */ #ifdef USE_SYSMOUSE int sysm_process_mouse(int x, int y, int nbs, int obs) { int btn; int bits; if (obs & ~nbs) btn = MOUSE_BTN_UP; else if (nbs & ~obs) { bits = nbs & ~obs; btn = bits & 0x1 ? MOUSE_BTN1_DOWN : (bits & 0x2 ? MOUSE_BTN2_DOWN : (bits & 0x4 ? MOUSE_BTN3_DOWN : 0)); } else /* nbs == obs */ return 0; process_mouse(btn, x, y); return 0; } #endif /* USE_SYSMOUSE */ DEFUN(movMs, MOVE_MOUSE, "Move cursor to mouse pointer") { if (!mouse_action.in_action) return; if ((nTab > 1 || mouse_action.menu_str) && mouse_action.cursorY < LastTab->y + 1) return; else if (mouse_action.cursorX >= Currentbuf->rootX && mouse_action.cursorY < LASTLINE) { cursorXY(Currentbuf, mouse_action.cursorX - Currentbuf->rootX, mouse_action.cursorY - Currentbuf->rootY); } displayBuffer(Currentbuf, B_NORMAL); } #ifdef USE_MENU #ifdef KANJI_SYMBOLS #define FRAME_WIDTH 2 #else #define FRAME_WIDTH 1 #endif DEFUN(menuMs, MENU_MOUSE, "Pop up menu at mouse pointer") { if (!mouse_action.in_action) return; if ((nTab > 1 || mouse_action.menu_str) && mouse_action.cursorY < LastTab->y + 1) mouse_action.cursorX -= FRAME_WIDTH + 1; else if (mouse_action.cursorX >= Currentbuf->rootX && mouse_action.cursorY < LASTLINE) { cursorXY(Currentbuf, mouse_action.cursorX - Currentbuf->rootX, mouse_action.cursorY - Currentbuf->rootY); displayBuffer(Currentbuf, B_NORMAL); } mainMn(); } #endif DEFUN(tabMs, TAB_MOUSE, "Select tab by mouse action") { TabBuffer *tab; if (!mouse_action.in_action) return; tab = posTab(mouse_action.cursorX, mouse_action.cursorY); if (!tab || tab == NO_TABBUFFER) return; CurrentTab = tab; displayBuffer(Currentbuf, B_FORCE_REDRAW); } DEFUN(closeTMs, CLOSE_TAB_MOUSE, "Close tab at mouse pointer") { TabBuffer *tab; if (!mouse_action.in_action) return; tab = posTab(mouse_action.cursorX, mouse_action.cursorY); if (!tab || tab == NO_TABBUFFER) return; deleteTab(tab); displayBuffer(Currentbuf, B_FORCE_REDRAW); } #endif /* USE_MOUSE */ DEFUN(dispVer, VERSION, "Display the version of w3m") { disp_message(Sprintf("w3m version %s", w3m_version)->ptr, TRUE); } DEFUN(wrapToggle, WRAP_TOGGLE, "Toggle wrapping mode in searches") { if (WrapSearch) { WrapSearch = FALSE; /* FIXME: gettextize? */ disp_message("Wrap search off", TRUE); } else { WrapSearch = TRUE; /* FIXME: gettextize? */ disp_message("Wrap search on", TRUE); } } static char * getCurWord(Buffer *buf, int *spos, int *epos) { char *p; Line *l = buf->currentLine; int b, e; *spos = 0; *epos = 0; if (l == NULL) return NULL; p = l->lineBuf; e = buf->pos; while (e > 0 && !is_wordchar(getChar(&p[e]))) prevChar(e, l); if (!is_wordchar(getChar(&p[e]))) return NULL; b = e; while (b > 0) { int tmp = b; prevChar(tmp, l); if (!is_wordchar(getChar(&p[tmp]))) break; b = tmp; } while (e < l->len && is_wordchar(getChar(&p[e]))) nextChar(e, l); *spos = b; *epos = e; return &p[b]; } static char * GetWord(Buffer *buf) { int b, e; char *p; if ((p = getCurWord(buf, &b, &e)) != NULL) { return Strnew_charp_n(p, e - b)->ptr; } return NULL; } #ifdef USE_DICT static void execdict(char *word) { char *w, *dictcmd; Buffer *buf; if (!UseDictCommand || word == NULL || *word == '\0') { displayBuffer(Currentbuf, B_NORMAL); return; } w = conv_to_system(word); if (*w == '\0') { displayBuffer(Currentbuf, B_NORMAL); return; } dictcmd = Sprintf("%s?%s", DictCommand, Str_form_quote(Strnew_charp(w))->ptr)->ptr; buf = loadGeneralFile(dictcmd, NULL, NO_REFERER, 0, NULL); if (buf == NULL) { disp_message("Execution failed", TRUE); return; } else if (buf != NO_BUFFER) { buf->filename = w; buf->buffername = Sprintf("%s %s", DICTBUFFERNAME, word)->ptr; if (buf->type == NULL) buf->type = "text/plain"; pushBuffer(buf); } displayBuffer(Currentbuf, B_FORCE_REDRAW); } DEFUN(dictword, DICT_WORD, "Execute dictionary command (see README.dict)") { execdict(inputStr("(dictionary)!", "")); } DEFUN(dictwordat, DICT_WORD_AT, "Execute dictionary command for word at cursor") { execdict(GetWord(Currentbuf)); } #endif /* USE_DICT */ void set_buffer_environ(Buffer *buf) { static Buffer *prev_buf = NULL; static Line *prev_line = NULL; static int prev_pos = -1; Line *l; if (buf == NULL) return; if (buf != prev_buf) { set_environ("W3M_SOURCEFILE", buf->sourcefile); set_environ("W3M_FILENAME", buf->filename); set_environ("W3M_TITLE", buf->buffername); set_environ("W3M_URL", parsedURL2Str(&buf->currentURL)->ptr); set_environ("W3M_TYPE", buf->real_type ? buf->real_type : "unknown"); #ifdef USE_M17N set_environ("W3M_CHARSET", wc_ces_to_charset(buf->document_charset)); #endif } l = buf->currentLine; if (l && (buf != prev_buf || l != prev_line || buf->pos != prev_pos)) { Anchor *a; ParsedURL pu; char *s = GetWord(buf); set_environ("W3M_CURRENT_WORD", s ? s : ""); a = retrieveCurrentAnchor(buf); if (a) { parseURL2(a->url, &pu, baseURL(buf)); set_environ("W3M_CURRENT_LINK", parsedURL2Str(&pu)->ptr); } else set_environ("W3M_CURRENT_LINK", ""); a = retrieveCurrentImg(buf); if (a) { parseURL2(a->url, &pu, baseURL(buf)); set_environ("W3M_CURRENT_IMG", parsedURL2Str(&pu)->ptr); } else set_environ("W3M_CURRENT_IMG", ""); a = retrieveCurrentForm(buf); if (a) set_environ("W3M_CURRENT_FORM", form2str((FormItemList *)a->url)); else set_environ("W3M_CURRENT_FORM", ""); set_environ("W3M_CURRENT_LINE", Sprintf("%ld", l->real_linenumber)->ptr); set_environ("W3M_CURRENT_COLUMN", Sprintf("%d", buf->currentColumn + buf->cursorX + 1)->ptr); } else if (!l) { set_environ("W3M_CURRENT_WORD", ""); set_environ("W3M_CURRENT_LINK", ""); set_environ("W3M_CURRENT_IMG", ""); set_environ("W3M_CURRENT_FORM", ""); set_environ("W3M_CURRENT_LINE", "0"); set_environ("W3M_CURRENT_COLUMN", "0"); } prev_buf = buf; prev_line = l; prev_pos = buf->pos; } char * searchKeyData(void) { char *data = NULL; if (CurrentKeyData != NULL && *CurrentKeyData != '\0') data = CurrentKeyData; else if (CurrentCmdData != NULL && *CurrentCmdData != '\0') data = CurrentCmdData; else if (CurrentKey >= 0) data = getKeyData(CurrentKey); CurrentKeyData = NULL; CurrentCmdData = NULL; if (data == NULL || *data == '\0') return NULL; return allocStr(data, -1); } static int searchKeyNum(void) { char *d; int n = 1; d = searchKeyData(); if (d != NULL) n = atoi(d); return n * PREC_NUM; } #ifdef __EMX__ #ifdef USE_M17N static char * getCodePage(void) { unsigned long CpList[8], CpSize; if (!getenv("WINDOWID") && !DosQueryCp(sizeof(CpList), CpList, &CpSize)) return Sprintf("CP%d", *CpList)->ptr; return NULL; } #endif #endif void deleteFiles() { Buffer *buf; char *f; for (CurrentTab = FirstTab; CurrentTab; CurrentTab = CurrentTab->nextTab) { while (Firstbuf && Firstbuf != NO_BUFFER) { buf = Firstbuf->nextBuffer; discardBuffer(Firstbuf); Firstbuf = buf; } } while ((f = popText(fileToDelete)) != NULL) { unlink(f); if (enable_inline_image == 2 && strcmp(f+strlen(f)-4, ".gif") == 0) { Str firstframe = Strnew_charp(f); Strcat_charp(firstframe, "-1"); unlink(firstframe->ptr); } } } void w3m_exit(int i) { #ifdef USE_MIGEMO init_migemo(); /* close pipe to migemo */ #endif stopDownload(); deleteFiles(); #ifdef USE_SSL free_ssl_ctx(); #endif disconnectFTP(); #ifdef USE_NNTP disconnectNews(); #endif #ifdef __MINGW32_VERSION WSACleanup(); #endif #ifdef HAVE_MKDTEMP if (no_rc_dir && tmp_dir != rc_dir) if (rmdir(tmp_dir) != 0) { fprintf(stderr, "Can't remove temporary directory (%s)!\n", tmp_dir); exit(1); } #endif exit(i); } DEFUN(execCmd, COMMAND, "Invoke w3m function(s)") { char *data, *p; int cmd; CurrentKeyData = NULL; /* not allowed in w3m-control: */ data = searchKeyData(); if (data == NULL || *data == '\0') { data = inputStrHist("command [; ...]: ", "", TextHist); if (data == NULL) { displayBuffer(Currentbuf, B_NORMAL); return; } } /* data: FUNC [DATA] [; FUNC [DATA] ...] */ while (*data) { SKIP_BLANKS(data); if (*data == ';') { data++; continue; } p = getWord(&data); cmd = getFuncList(p); if (cmd < 0) break; p = getQWord(&data); CurrentKey = -1; CurrentKeyData = NULL; CurrentCmdData = *p ? p : NULL; #ifdef USE_MOUSE if (use_mouse) mouse_inactive(); #endif w3mFuncList[cmd].func(); #ifdef USE_MOUSE if (use_mouse) mouse_active(); #endif CurrentCmdData = NULL; } displayBuffer(Currentbuf, B_NORMAL); } #ifdef USE_ALARM static MySignalHandler SigAlarm(SIGNAL_ARG) { char *data; if (CurrentAlarm->sec > 0) { CurrentKey = -1; CurrentKeyData = NULL; CurrentCmdData = data = (char *)CurrentAlarm->data; #ifdef USE_MOUSE if (use_mouse) mouse_inactive(); #endif w3mFuncList[CurrentAlarm->cmd].func(); #ifdef USE_MOUSE if (use_mouse) mouse_active(); #endif CurrentCmdData = NULL; if (CurrentAlarm->status == AL_IMPLICIT_ONCE) { CurrentAlarm->sec = 0; CurrentAlarm->status = AL_UNSET; } if (Currentbuf->event) { if (Currentbuf->event->status != AL_UNSET) CurrentAlarm = Currentbuf->event; else Currentbuf->event = NULL; } if (!Currentbuf->event) CurrentAlarm = &DefaultAlarm; if (CurrentAlarm->sec > 0) { mySignal(SIGALRM, SigAlarm); alarm(CurrentAlarm->sec); } } SIGNAL_RETURN; } DEFUN(setAlarm, ALARM, "Set alarm") { char *data; int sec = 0, cmd = -1; CurrentKeyData = NULL; /* not allowed in w3m-control: */ data = searchKeyData(); if (data == NULL || *data == '\0') { data = inputStrHist("(Alarm)sec command: ", "", TextHist); if (data == NULL) { displayBuffer(Currentbuf, B_NORMAL); return; } } if (*data != '\0') { sec = atoi(getWord(&data)); if (sec > 0) cmd = getFuncList(getWord(&data)); } if (cmd >= 0) { data = getQWord(&data); setAlarmEvent(&DefaultAlarm, sec, AL_EXPLICIT, cmd, data); disp_message_nsec(Sprintf("%dsec %s %s", sec, w3mFuncList[cmd].id, data)->ptr, FALSE, 1, FALSE, TRUE); } else { setAlarmEvent(&DefaultAlarm, 0, AL_UNSET, FUNCNAME_nulcmd, NULL); } displayBuffer(Currentbuf, B_NORMAL); } AlarmEvent * setAlarmEvent(AlarmEvent * event, int sec, short status, int cmd, void *data) { if (event == NULL) event = New(AlarmEvent); event->sec = sec; event->status = status; event->cmd = cmd; event->data = data; return event; } #endif DEFUN(reinit, REINIT, "Reload configuration file") { char *resource = searchKeyData(); if (resource == NULL) { init_rc(); sync_with_option(); #ifdef USE_COOKIE initCookie(); #endif displayBuffer(Currentbuf, B_REDRAW_IMAGE); return; } if (!strcasecmp(resource, "CONFIG") || !strcasecmp(resource, "RC")) { init_rc(); sync_with_option(); displayBuffer(Currentbuf, B_REDRAW_IMAGE); return; } #ifdef USE_COOKIE if (!strcasecmp(resource, "COOKIE")) { initCookie(); return; } #endif if (!strcasecmp(resource, "KEYMAP")) { initKeymap(TRUE); return; } if (!strcasecmp(resource, "MAILCAP")) { initMailcap(); return; } #ifdef USE_MOUSE if (!strcasecmp(resource, "MOUSE")) { initMouseAction(); displayBuffer(Currentbuf, B_REDRAW_IMAGE); return; } #endif #ifdef USE_MENU if (!strcasecmp(resource, "MENU")) { initMenu(); return; } #endif if (!strcasecmp(resource, "MIMETYPES")) { initMimeTypes(); return; } #ifdef USE_EXTERNAL_URI_LOADER if (!strcasecmp(resource, "URIMETHODS")) { initURIMethods(); return; } #endif disp_err_message(Sprintf("Don't know how to reinitialize '%s'", resource)-> ptr, FALSE); } DEFUN(defKey, DEFINE_KEY, "Define a binding between a key stroke combination and a command") { char *data; CurrentKeyData = NULL; /* not allowed in w3m-control: */ data = searchKeyData(); if (data == NULL || *data == '\0') { data = inputStrHist("Key definition: ", "", TextHist); if (data == NULL || *data == '\0') { displayBuffer(Currentbuf, B_NORMAL); return; } } setKeymap(allocStr(data, -1), -1, TRUE); displayBuffer(Currentbuf, B_NORMAL); } TabBuffer * newTab(void) { TabBuffer *n; n = New(TabBuffer); if (n == NULL) return NULL; n->nextTab = NULL; n->currentBuffer = NULL; n->firstBuffer = NULL; return n; } static void _newT(void) { TabBuffer *tag; Buffer *buf; int i; tag = newTab(); if (!tag) return; buf = newBuffer(Currentbuf->width); copyBuffer(buf, Currentbuf); buf->nextBuffer = NULL; for (i = 0; i < MAX_LB; i++) buf->linkBuffer[i] = NULL; (*buf->clone)++; tag->firstBuffer = tag->currentBuffer = buf; tag->nextTab = CurrentTab->nextTab; tag->prevTab = CurrentTab; if (CurrentTab->nextTab) CurrentTab->nextTab->prevTab = tag; else LastTab = tag; CurrentTab->nextTab = tag; CurrentTab = tag; nTab++; } DEFUN(newT, NEW_TAB, "Open a new tab (with current document)") { _newT(); displayBuffer(Currentbuf, B_REDRAW_IMAGE); } static TabBuffer * numTab(int n) { TabBuffer *tab; int i; if (n == 0) return CurrentTab; if (n == 1) return FirstTab; if (nTab <= 1) return NULL; for (tab = FirstTab, i = 1; tab && i < n; tab = tab->nextTab, i++) ; return tab; } void calcTabPos(void) { TabBuffer *tab; #if 0 int lcol = 0, rcol = 2, col; #else int lcol = 0, rcol = 0, col; #endif int n1, n2, na, nx, ny, ix, iy; #ifdef USE_MOUSE lcol = mouse_action.menu_str ? mouse_action.menu_width : 0; #endif if (nTab <= 0) return; n1 = (COLS - rcol - lcol) / TabCols; if (n1 >= nTab) { n2 = 1; ny = 1; } else { if (n1 < 0) n1 = 0; n2 = COLS / TabCols; if (n2 == 0) n2 = 1; ny = (nTab - n1 - 1) / n2 + 2; } na = n1 + n2 * (ny - 1); n1 -= (na - nTab) / ny; if (n1 < 0) n1 = 0; na = n1 + n2 * (ny - 1); tab = FirstTab; for (iy = 0; iy < ny && tab; iy++) { if (iy == 0) { nx = n1; col = COLS - rcol - lcol; } else { nx = n2 - (na - nTab + (iy - 1)) / (ny - 1); col = COLS; } for (ix = 0; ix < nx && tab; ix++, tab = tab->nextTab) { tab->x1 = col * ix / nx; tab->x2 = col * (ix + 1) / nx - 1; tab->y = iy; if (iy == 0) { tab->x1 += lcol; tab->x2 += lcol; } } } } TabBuffer * deleteTab(TabBuffer * tab) { Buffer *buf, *next; if (nTab <= 1) return FirstTab; if (tab->prevTab) { if (tab->nextTab) tab->nextTab->prevTab = tab->prevTab; else LastTab = tab->prevTab; tab->prevTab->nextTab = tab->nextTab; if (tab == CurrentTab) CurrentTab = tab->prevTab; } else { /* tab == FirstTab */ tab->nextTab->prevTab = NULL; FirstTab = tab->nextTab; if (tab == CurrentTab) CurrentTab = tab->nextTab; } nTab--; buf = tab->firstBuffer; while (buf && buf != NO_BUFFER) { next = buf->nextBuffer; discardBuffer(buf); buf = next; } return FirstTab; } DEFUN(closeT, CLOSE_TAB, "Close tab") { TabBuffer *tab; if (nTab <= 1) return; if (prec_num) tab = numTab(PREC_NUM); else tab = CurrentTab; if (tab) deleteTab(tab); displayBuffer(Currentbuf, B_REDRAW_IMAGE); } DEFUN(nextT, NEXT_TAB, "Switch to the next tab") { int i; if (nTab <= 1) return; for (i = 0; i < PREC_NUM; i++) { if (CurrentTab->nextTab) CurrentTab = CurrentTab->nextTab; else CurrentTab = FirstTab; } displayBuffer(Currentbuf, B_REDRAW_IMAGE); } DEFUN(prevT, PREV_TAB, "Switch to the previous tab") { int i; if (nTab <= 1) return; for (i = 0; i < PREC_NUM; i++) { if (CurrentTab->prevTab) CurrentTab = CurrentTab->prevTab; else CurrentTab = LastTab; } displayBuffer(Currentbuf, B_REDRAW_IMAGE); } static void followTab(TabBuffer * tab) { Buffer *buf; Anchor *a; #ifdef USE_IMAGE a = retrieveCurrentImg(Currentbuf); if (!(a && a->image && a->image->map)) #endif a = retrieveCurrentAnchor(Currentbuf); if (a == NULL) return; if (tab == CurrentTab) { check_target = FALSE; followA(); check_target = TRUE; return; } _newT(); buf = Currentbuf; check_target = FALSE; followA(); check_target = TRUE; if (tab == NULL) { if (buf != Currentbuf) delBuffer(buf); else deleteTab(CurrentTab); } else if (buf != Currentbuf) { /* buf <- p <- ... <- Currentbuf = c */ Buffer *c, *p; c = Currentbuf; p = prevBuffer(c, buf); p->nextBuffer = NULL; Firstbuf = buf; deleteTab(CurrentTab); CurrentTab = tab; for (buf = p; buf; buf = p) { p = prevBuffer(c, buf); pushBuffer(buf); } } displayBuffer(Currentbuf, B_FORCE_REDRAW); } DEFUN(tabA, TAB_LINK, "Follow current hyperlink in a new tab") { followTab(prec_num ? numTab(PREC_NUM) : NULL); } static void tabURL0(TabBuffer * tab, char *prompt, int relative) { Buffer *buf; if (tab == CurrentTab) { goURL0(prompt, relative); return; } _newT(); buf = Currentbuf; goURL0(prompt, relative); if (tab == NULL) { if (buf != Currentbuf) delBuffer(buf); else deleteTab(CurrentTab); } else if (buf != Currentbuf) { /* buf <- p <- ... <- Currentbuf = c */ Buffer *c, *p; c = Currentbuf; p = prevBuffer(c, buf); p->nextBuffer = NULL; Firstbuf = buf; deleteTab(CurrentTab); CurrentTab = tab; for (buf = p; buf; buf = p) { p = prevBuffer(c, buf); pushBuffer(buf); } } displayBuffer(Currentbuf, B_FORCE_REDRAW); } DEFUN(tabURL, TAB_GOTO, "Open specified document in a new tab") { tabURL0(prec_num ? numTab(PREC_NUM) : NULL, "Goto URL on new tab: ", FALSE); } DEFUN(tabrURL, TAB_GOTO_RELATIVE, "Open relative address in a new tab") { tabURL0(prec_num ? numTab(PREC_NUM) : NULL, "Goto relative URL on new tab: ", TRUE); } static void moveTab(TabBuffer * t, TabBuffer * t2, int right) { if (t2 == NO_TABBUFFER) t2 = FirstTab; if (!t || !t2 || t == t2 || t == NO_TABBUFFER) return; if (t->prevTab) { if (t->nextTab) t->nextTab->prevTab = t->prevTab; else LastTab = t->prevTab; t->prevTab->nextTab = t->nextTab; } else { t->nextTab->prevTab = NULL; FirstTab = t->nextTab; } if (right) { t->nextTab = t2->nextTab; t->prevTab = t2; if (t2->nextTab) t2->nextTab->prevTab = t; else LastTab = t; t2->nextTab = t; } else { t->prevTab = t2->prevTab; t->nextTab = t2; if (t2->prevTab) t2->prevTab->nextTab = t; else FirstTab = t; t2->prevTab = t; } displayBuffer(Currentbuf, B_FORCE_REDRAW); } DEFUN(tabR, TAB_RIGHT, "Move right along the tab bar") { TabBuffer *tab; int i; for (tab = CurrentTab, i = 0; tab && i < PREC_NUM; tab = tab->nextTab, i++) ; moveTab(CurrentTab, tab ? tab : LastTab, TRUE); } DEFUN(tabL, TAB_LEFT, "Move left along the tab bar") { TabBuffer *tab; int i; for (tab = CurrentTab, i = 0; tab && i < PREC_NUM; tab = tab->prevTab, i++) ; moveTab(CurrentTab, tab ? tab : FirstTab, FALSE); } void addDownloadList(pid_t pid, char *url, char *save, char *lock, clen_t size) { DownloadList *d; d = New(DownloadList); d->pid = pid; d->url = url; if (save[0] != '/' && save[0] != '~') save = Strnew_m_charp(CurrentDir, "/", save, NULL)->ptr; d->save = expandPath(save); d->lock = lock; d->size = size; d->time = time(0); d->running = TRUE; d->err = 0; d->next = NULL; d->prev = LastDL; if (LastDL) LastDL->next = d; else FirstDL = d; LastDL = d; add_download_list = TRUE; } int checkDownloadList(void) { DownloadList *d; struct stat st; if (!FirstDL) return FALSE; for (d = FirstDL; d != NULL; d = d->next) { if (d->running && !lstat(d->lock, &st)) return TRUE; } return FALSE; } static char * convert_size3(clen_t size) { Str tmp = Strnew(); int n; do { n = size % 1000; size /= 1000; tmp = Sprintf(size ? ",%.3d%s" : "%d%s", n, tmp->ptr); } while (size); return tmp->ptr; } static Buffer * DownloadListBuffer(void) { DownloadList *d; Str src = NULL; struct stat st; time_t cur_time; int duration, rate, eta; size_t size; if (!FirstDL) return NULL; cur_time = time(0); /* FIXME: gettextize? */ src = Strnew_charp("<html><head><title>" DOWNLOAD_LIST_TITLE "</title></head>\n<body><h1 align=center>" DOWNLOAD_LIST_TITLE "</h1>\n" "<form method=internal action=download><hr>\n"); for (d = LastDL; d != NULL; d = d->prev) { if (lstat(d->lock, &st)) d->running = FALSE; Strcat_charp(src, "<pre>\n"); Strcat(src, Sprintf("%s\n --&gt; %s\n ", html_quote(d->url), html_quote(conv_from_system(d->save)))); duration = cur_time - d->time; if (!stat(d->save, &st)) { size = st.st_size; if (!d->running) { if (!d->err) d->size = size; duration = st.st_mtime - d->time; } } else size = 0; if (d->size) { int i, l = COLS - 6; if (size < d->size) i = 1.0 * l * size / d->size; else i = l; l -= i; while (i-- > 0) Strcat_char(src, '#'); while (l-- > 0) Strcat_char(src, '_'); Strcat_char(src, '\n'); } if ((d->running || d->err) && size < d->size) Strcat(src, Sprintf(" %s / %s bytes (%d%%)", convert_size3(size), convert_size3(d->size), (int)(100.0 * size / d->size))); else Strcat(src, Sprintf(" %s bytes loaded", convert_size3(size))); if (duration > 0) { rate = size / duration; Strcat(src, Sprintf(" %02d:%02d:%02d rate %s/sec", duration / (60 * 60), (duration / 60) % 60, duration % 60, convert_size(rate, 1))); if (d->running && size < d->size && rate) { eta = (d->size - size) / rate; Strcat(src, Sprintf(" eta %02d:%02d:%02d", eta / (60 * 60), (eta / 60) % 60, eta % 60)); } } Strcat_char(src, '\n'); if (!d->running) { Strcat(src, Sprintf("<input type=submit name=ok%d value=OK>", d->pid)); switch (d->err) { case 0: if (size < d->size) Strcat_charp(src, " Download ended but probably not complete"); else Strcat_charp(src, " Download complete"); break; case 1: Strcat_charp(src, " Error: could not open destination file"); break; case 2: Strcat_charp(src, " Error: could not write to file (disk full)"); break; default: Strcat_charp(src, " Error: unknown reason"); } } else Strcat(src, Sprintf("<input type=submit name=stop%d value=STOP>", d->pid)); Strcat_charp(src, "\n</pre><hr>\n"); } Strcat_charp(src, "</form></body></html>"); return loadHTMLString(src); } void download_action(struct parsed_tagarg *arg) { DownloadList *d; pid_t pid; for (; arg; arg = arg->next) { if (!strncmp(arg->arg, "stop", 4)) { pid = (pid_t) atoi(&arg->arg[4]); #ifndef __MINGW32_VERSION kill(pid, SIGKILL); #endif } else if (!strncmp(arg->arg, "ok", 2)) pid = (pid_t) atoi(&arg->arg[2]); else continue; for (d = FirstDL; d; d = d->next) { if (d->pid == pid) { unlink(d->lock); if (d->prev) d->prev->next = d->next; else FirstDL = d->next; if (d->next) d->next->prev = d->prev; else LastDL = d->prev; break; } } } ldDL(); } void stopDownload(void) { DownloadList *d; if (!FirstDL) return; for (d = FirstDL; d != NULL; d = d->next) { if (!d->running) continue; #ifndef __MINGW32_VERSION kill(d->pid, SIGKILL); #endif unlink(d->lock); } } /* download panel */ DEFUN(ldDL, DOWNLOAD_LIST, "Display downloads panel") { Buffer *buf; int replace = FALSE, new_tab = FALSE; #ifdef USE_ALARM int reload; #endif if (Currentbuf->bufferprop & BP_INTERNAL && !strcmp(Currentbuf->buffername, DOWNLOAD_LIST_TITLE)) replace = TRUE; if (!FirstDL) { if (replace) { if (Currentbuf == Firstbuf && Currentbuf->nextBuffer == NULL) { if (nTab > 1) deleteTab(CurrentTab); } else delBuffer(Currentbuf); displayBuffer(Currentbuf, B_FORCE_REDRAW); } return; } #ifdef USE_ALARM reload = checkDownloadList(); #endif buf = DownloadListBuffer(); if (!buf) { displayBuffer(Currentbuf, B_NORMAL); return; } buf->bufferprop |= (BP_INTERNAL | BP_NO_URL); if (replace) { COPY_BUFROOT(buf, Currentbuf); restorePosition(buf, Currentbuf); } if (!replace && open_tab_dl_list) { _newT(); new_tab = TRUE; } pushBuffer(buf); if (replace || new_tab) deletePrevBuf(); #ifdef USE_ALARM if (reload) Currentbuf->event = setAlarmEvent(Currentbuf->event, 1, AL_IMPLICIT, FUNCNAME_reload, NULL); #endif displayBuffer(Currentbuf, B_FORCE_REDRAW); } static void save_buffer_position(Buffer *buf) { BufferPos *b = buf->undo; if (!buf->firstLine) return; if (b && b->top_linenumber == TOP_LINENUMBER(buf) && b->cur_linenumber == CUR_LINENUMBER(buf) && b->currentColumn == buf->currentColumn && b->pos == buf->pos) return; b = New(BufferPos); b->top_linenumber = TOP_LINENUMBER(buf); b->cur_linenumber = CUR_LINENUMBER(buf); b->currentColumn = buf->currentColumn; b->pos = buf->pos; b->bpos = buf->currentLine ? buf->currentLine->bpos : 0; b->next = NULL; b->prev = buf->undo; if (buf->undo) buf->undo->next = b; buf->undo = b; } static void resetPos(BufferPos * b) { Buffer buf; Line top, cur; top.linenumber = b->top_linenumber; cur.linenumber = b->cur_linenumber; cur.bpos = b->bpos; buf.topLine = &top; buf.currentLine = &cur; buf.pos = b->pos; buf.currentColumn = b->currentColumn; restorePosition(Currentbuf, &buf); Currentbuf->undo = b; displayBuffer(Currentbuf, B_FORCE_REDRAW); } DEFUN(undoPos, UNDO, "Cancel the last cursor movement") { BufferPos *b = Currentbuf->undo; int i; if (!Currentbuf->firstLine) return; if (!b || !b->prev) return; for (i = 0; i < PREC_NUM && b->prev; i++, b = b->prev) ; resetPos(b); } DEFUN(redoPos, REDO, "Cancel the last undo") { BufferPos *b = Currentbuf->undo; int i; if (!Currentbuf->firstLine) return; if (!b || !b->next) return; for (i = 0; i < PREC_NUM && b->next; i++, b = b->next) ; resetPos(b); }
./CrossVul/dataset_final_sorted/CWE-59/c/good_589_4
crossvul-cpp_data_bad_3272_0
/** \ingroup payload * \file lib/fsm.c * File state machine to handle a payload from a package. */ #include "system.h" #include <utime.h> #include <errno.h> #if WITH_CAP #include <sys/capability.h> #endif #include <rpm/rpmte.h> #include <rpm/rpmts.h> #include <rpm/rpmlog.h> #include <rpm/rpmmacro.h> #include "rpmio/rpmio_internal.h" /* fdInit/FiniDigest */ #include "lib/fsm.h" #include "lib/rpmte_internal.h" /* XXX rpmfs */ #include "lib/rpmplugins.h" /* rpm plugins hooks */ #include "lib/rpmug.h" #include "debug.h" #define _FSM_DEBUG 0 int _fsm_debug = _FSM_DEBUG; /* XXX Failure to remove is not (yet) cause for failure. */ static int strict_erasures = 0; #define SUFFIX_RPMORIG ".rpmorig" #define SUFFIX_RPMSAVE ".rpmsave" #define SUFFIX_RPMNEW ".rpmnew" /* Default directory and file permissions if not mapped */ #define _dirPerms 0755 #define _filePerms 0644 /* * XXX Forward declarations for previously exported functions to avoid moving * things around needlessly */ static const char * fileActionString(rpmFileAction a); /** \ingroup payload * Build path to file from file info, optionally ornamented with suffix. * @param fi file info iterator * @param suffix suffix to use (NULL disables) * @retval path to file (malloced) */ static char * fsmFsPath(rpmfi fi, const char * suffix) { return rstrscat(NULL, rpmfiDN(fi), rpmfiBN(fi), suffix ? suffix : "", NULL); } /** \ingroup payload * Directory name iterator. */ typedef struct dnli_s { rpmfiles fi; char * active; int reverse; int isave; int i; } * DNLI_t; /** \ingroup payload * Destroy directory name iterator. * @param dnli directory name iterator * @retval NULL always */ static DNLI_t dnlFreeIterator(DNLI_t dnli) { if (dnli) { if (dnli->active) free(dnli->active); free(dnli); } return NULL; } /** \ingroup payload * Create directory name iterator. * @param fi file info set * @param fs file state set * @param reverse traverse directory names in reverse order? * @return directory name iterator */ static DNLI_t dnlInitIterator(rpmfiles fi, rpmfs fs, int reverse) { DNLI_t dnli; int i, j; int dc; if (fi == NULL) return NULL; dc = rpmfilesDC(fi); dnli = xcalloc(1, sizeof(*dnli)); dnli->fi = fi; dnli->reverse = reverse; dnli->i = (reverse ? dc : 0); if (dc) { dnli->active = xcalloc(dc, sizeof(*dnli->active)); int fc = rpmfilesFC(fi); /* Identify parent directories not skipped. */ for (i = 0; i < fc; i++) if (!XFA_SKIPPING(rpmfsGetAction(fs, i))) dnli->active[rpmfilesDI(fi, i)] = 1; /* Exclude parent directories that are explicitly included. */ for (i = 0; i < fc; i++) { int dil; size_t dnlen, bnlen; if (!S_ISDIR(rpmfilesFMode(fi, i))) continue; dil = rpmfilesDI(fi, i); dnlen = strlen(rpmfilesDN(fi, dil)); bnlen = strlen(rpmfilesBN(fi, i)); for (j = 0; j < dc; j++) { const char * dnl; size_t jlen; if (!dnli->active[j] || j == dil) continue; dnl = rpmfilesDN(fi, j); jlen = strlen(dnl); if (jlen != (dnlen+bnlen+1)) continue; if (!rstreqn(dnl, rpmfilesDN(fi, dil), dnlen)) continue; if (!rstreqn(dnl+dnlen, rpmfilesBN(fi, i), bnlen)) continue; if (dnl[dnlen+bnlen] != '/' || dnl[dnlen+bnlen+1] != '\0') continue; /* This directory is included in the package. */ dnli->active[j] = 0; break; } } /* Print only once per package. */ if (!reverse) { j = 0; for (i = 0; i < dc; i++) { if (!dnli->active[i]) continue; if (j == 0) { j = 1; rpmlog(RPMLOG_DEBUG, "========== Directories not explicitly included in package:\n"); } rpmlog(RPMLOG_DEBUG, "%10d %s\n", i, rpmfilesDN(fi, i)); } if (j) rpmlog(RPMLOG_DEBUG, "==========\n"); } } return dnli; } /** \ingroup payload * Return next directory name (from file info). * @param dnli directory name iterator * @return next directory name */ static const char * dnlNextIterator(DNLI_t dnli) { const char * dn = NULL; if (dnli) { rpmfiles fi = dnli->fi; int dc = rpmfilesDC(fi); int i = -1; if (dnli->active) do { i = (!dnli->reverse ? dnli->i++ : --dnli->i); } while (i >= 0 && i < dc && !dnli->active[i]); if (i >= 0 && i < dc) dn = rpmfilesDN(fi, i); else i = -1; dnli->isave = i; } return dn; } static int fsmSetFCaps(const char *path, const char *captxt) { int rc = 0; #if WITH_CAP if (captxt && *captxt != '\0') { cap_t fcaps = cap_from_text(captxt); if (fcaps == NULL || cap_set_file(path, fcaps) != 0) { rc = RPMERR_SETCAP_FAILED; } cap_free(fcaps); } #endif return rc; } /* Check dest is the same, empty and regular file with writeonly permissions */ static int linkSane(FD_t wfd, const char *dest) { struct stat sb, lsb; return (fstat(Fileno(wfd), &sb) == 0 && sb.st_size == 0 && (sb.st_mode & ~S_IFMT) == S_IWUSR && lstat(dest, &lsb) == 0 && S_ISREG(lsb.st_mode) && sb.st_dev == lsb.st_dev && sb.st_ino == lsb.st_ino); } /** \ingroup payload * Create file from payload stream. * @return 0 on success */ static int expandRegular(rpmfi fi, const char *dest, rpmpsm psm, int exclusive, int nodigest, int nocontent) { FD_t wfd = NULL; int rc = 0; /* Create the file with 0200 permissions (write by owner). */ { mode_t old_umask = umask(0577); wfd = Fopen(dest, exclusive ? "wx.ufdio" : "a.ufdio"); umask(old_umask); /* If reopening, make sure the file is what we expect */ if (!exclusive && wfd != NULL && !linkSane(wfd, dest)) { rc = RPMERR_OPEN_FAILED; goto exit; } } if (Ferror(wfd)) { rc = RPMERR_OPEN_FAILED; goto exit; } if (!nocontent) rc = rpmfiArchiveReadToFilePsm(fi, wfd, nodigest, psm); exit: if (wfd) { int myerrno = errno; static int oneshot = 0; static int flush_io = 0; if (!oneshot) { flush_io = rpmExpandNumeric("%{?_flush_io}"); oneshot = 1; } if (flush_io) { int fdno = Fileno(wfd); fsync(fdno); } Fclose(wfd); errno = myerrno; } return rc; } static int fsmMkfile(rpmfi fi, const char *dest, rpmfiles files, rpmpsm psm, int nodigest, int *setmeta, int * firsthardlink) { int rc = 0; int numHardlinks = rpmfiFNlink(fi); if (numHardlinks > 1) { /* Create first hardlinked file empty */ if (*firsthardlink < 0) { *firsthardlink = rpmfiFX(fi); rc = expandRegular(fi, dest, psm, 1, nodigest, 1); } else { /* Create hard links for others */ char *fn = rpmfilesFN(files, *firsthardlink); rc = link(fn, dest); if (rc < 0) { rc = RPMERR_LINK_FAILED; } free(fn); } } /* Write normal files or fill the last hardlinked (already existing) file with content */ if (numHardlinks<=1) { if (!rc) rc = expandRegular(fi, dest, psm, 1, nodigest, 0); } else if (rpmfiArchiveHasContent(fi)) { if (!rc) rc = expandRegular(fi, dest, psm, 0, nodigest, 0); *firsthardlink = -1; } else { *setmeta = 0; } return rc; } static int fsmReadLink(const char *path, char *buf, size_t bufsize, size_t *linklen) { ssize_t llen = readlink(path, buf, bufsize - 1); int rc = RPMERR_READLINK_FAILED; if (_fsm_debug) { rpmlog(RPMLOG_DEBUG, " %8s (%s, buf, %d) %s\n", __func__, path, (int)(bufsize -1), (llen < 0 ? strerror(errno) : "")); } if (llen >= 0) { buf[llen] = '\0'; rc = 0; *linklen = llen; } return rc; } static int fsmStat(const char *path, int dolstat, struct stat *sb) { int rc; if (dolstat){ rc = lstat(path, sb); } else { rc = stat(path, sb); } if (_fsm_debug && rc && errno != ENOENT) rpmlog(RPMLOG_DEBUG, " %8s (%s, ost) %s\n", __func__, path, (rc < 0 ? strerror(errno) : "")); if (rc < 0) { rc = (errno == ENOENT ? RPMERR_ENOENT : RPMERR_LSTAT_FAILED); /* Ensure consistent struct content on failure */ memset(sb, 0, sizeof(*sb)); } return rc; } static int fsmRmdir(const char *path) { int rc = rmdir(path); if (_fsm_debug) rpmlog(RPMLOG_DEBUG, " %8s (%s) %s\n", __func__, path, (rc < 0 ? strerror(errno) : "")); if (rc < 0) switch (errno) { case ENOENT: rc = RPMERR_ENOENT; break; case ENOTEMPTY: rc = RPMERR_ENOTEMPTY; break; default: rc = RPMERR_RMDIR_FAILED; break; } return rc; } static int fsmMkdir(const char *path, mode_t mode) { int rc = mkdir(path, (mode & 07777)); if (_fsm_debug) rpmlog(RPMLOG_DEBUG, " %8s (%s, 0%04o) %s\n", __func__, path, (unsigned)(mode & 07777), (rc < 0 ? strerror(errno) : "")); if (rc < 0) rc = RPMERR_MKDIR_FAILED; return rc; } static int fsmMkfifo(const char *path, mode_t mode) { int rc = mkfifo(path, (mode & 07777)); if (_fsm_debug) { rpmlog(RPMLOG_DEBUG, " %8s (%s, 0%04o) %s\n", __func__, path, (unsigned)(mode & 07777), (rc < 0 ? strerror(errno) : "")); } if (rc < 0) rc = RPMERR_MKFIFO_FAILED; return rc; } static int fsmMknod(const char *path, mode_t mode, dev_t dev) { /* FIX: check S_IFIFO or dev != 0 */ int rc = mknod(path, (mode & ~07777), dev); if (_fsm_debug) { rpmlog(RPMLOG_DEBUG, " %8s (%s, 0%o, 0x%x) %s\n", __func__, path, (unsigned)(mode & ~07777), (unsigned)dev, (rc < 0 ? strerror(errno) : "")); } if (rc < 0) rc = RPMERR_MKNOD_FAILED; return rc; } /** * Create (if necessary) directories not explicitly included in package. * @param files file data * @param fs file states * @param plugins rpm plugins handle * @return 0 on success */ static int fsmMkdirs(rpmfiles files, rpmfs fs, rpmPlugins plugins) { DNLI_t dnli = dnlInitIterator(files, fs, 0); struct stat sb; const char *dpath; int dc = rpmfilesDC(files); int rc = 0; int i; int ldnlen = 0; int ldnalloc = 0; char * ldn = NULL; short * dnlx = NULL; dnlx = (dc ? xcalloc(dc, sizeof(*dnlx)) : NULL); if (dnlx != NULL) while ((dpath = dnlNextIterator(dnli)) != NULL) { size_t dnlen = strlen(dpath); char * te, dn[dnlen+1]; dc = dnli->isave; if (dc < 0) continue; dnlx[dc] = dnlen; if (dnlen <= 1) continue; if (dnlen <= ldnlen && rstreq(dpath, ldn)) continue; /* Copy as we need to modify the string */ (void) stpcpy(dn, dpath); /* Assume '/' directory exists, "mkdir -p" for others if non-existent */ for (i = 1, te = dn + 1; *te != '\0'; te++, i++) { if (*te != '/') continue; *te = '\0'; /* Already validated? */ if (i < ldnlen && (ldn[i] == '/' || ldn[i] == '\0') && rstreqn(dn, ldn, i)) { *te = '/'; /* Move pre-existing path marker forward. */ dnlx[dc] = (te - dn); continue; } /* Validate next component of path. */ rc = fsmStat(dn, 1, &sb); /* lstat */ *te = '/'; /* Directory already exists? */ if (rc == 0 && S_ISDIR(sb.st_mode)) { /* Move pre-existing path marker forward. */ dnlx[dc] = (te - dn); } else if (rc == RPMERR_ENOENT) { *te = '\0'; mode_t mode = S_IFDIR | (_dirPerms & 07777); rpmFsmOp op = (FA_CREATE|FAF_UNOWNED); /* Run fsm file pre hook for all plugins */ rc = rpmpluginsCallFsmFilePre(plugins, NULL, dn, mode, op); if (!rc) rc = fsmMkdir(dn, mode); if (!rc) { rc = rpmpluginsCallFsmFilePrepare(plugins, NULL, dn, dn, mode, op); } /* Run fsm file post hook for all plugins */ rpmpluginsCallFsmFilePost(plugins, NULL, dn, mode, op, rc); if (!rc) { rpmlog(RPMLOG_DEBUG, "%s directory created with perms %04o\n", dn, (unsigned)(mode & 07777)); } *te = '/'; } if (rc) break; } if (rc) break; /* Save last validated path. */ if (ldnalloc < (dnlen + 1)) { ldnalloc = dnlen + 100; ldn = xrealloc(ldn, ldnalloc); } if (ldn != NULL) { /* XXX can't happen */ strcpy(ldn, dn); ldnlen = dnlen; } } free(dnlx); free(ldn); dnlFreeIterator(dnli); return rc; } static void removeSBITS(const char *path) { struct stat stb; if (lstat(path, &stb) == 0 && S_ISREG(stb.st_mode)) { if ((stb.st_mode & 06000) != 0) { (void) chmod(path, stb.st_mode & 0777); } #if WITH_CAP if (stb.st_mode & (S_IXUSR|S_IXGRP|S_IXOTH)) { (void) cap_set_file(path, NULL); } #endif } } static void fsmDebug(const char *fpath, rpmFileAction action, const struct stat *st) { rpmlog(RPMLOG_DEBUG, "%-10s %06o%3d (%4d,%4d)%6d %s\n", fileActionString(action), (int)st->st_mode, (int)st->st_nlink, (int)st->st_uid, (int)st->st_gid, (int)st->st_size, (fpath ? fpath : "")); } static int fsmSymlink(const char *opath, const char *path) { int rc = symlink(opath, path); if (_fsm_debug) { rpmlog(RPMLOG_DEBUG, " %8s (%s, %s) %s\n", __func__, opath, path, (rc < 0 ? strerror(errno) : "")); } if (rc < 0) rc = RPMERR_SYMLINK_FAILED; return rc; } static int fsmUnlink(const char *path) { int rc = 0; removeSBITS(path); rc = unlink(path); if (_fsm_debug) rpmlog(RPMLOG_DEBUG, " %8s (%s) %s\n", __func__, path, (rc < 0 ? strerror(errno) : "")); if (rc < 0) rc = (errno == ENOENT ? RPMERR_ENOENT : RPMERR_UNLINK_FAILED); return rc; } static int fsmRename(const char *opath, const char *path) { removeSBITS(path); int rc = rename(opath, path); #if defined(ETXTBSY) && defined(__HPUX__) /* XXX HP-UX (and other os'es) don't permit rename to busy files. */ if (rc && errno == ETXTBSY) { char *rmpath = NULL; rstrscat(&rmpath, path, "-RPMDELETE", NULL); rc = rename(path, rmpath); if (!rc) rc = rename(opath, path); free(rmpath); } #endif if (_fsm_debug) rpmlog(RPMLOG_DEBUG, " %8s (%s, %s) %s\n", __func__, opath, path, (rc < 0 ? strerror(errno) : "")); if (rc < 0) rc = (errno == EISDIR ? RPMERR_EXIST_AS_DIR : RPMERR_RENAME_FAILED); return rc; } static int fsmRemove(const char *path, mode_t mode) { return S_ISDIR(mode) ? fsmRmdir(path) : fsmUnlink(path); } static int fsmChown(const char *path, mode_t mode, uid_t uid, gid_t gid) { int rc = S_ISLNK(mode) ? lchown(path, uid, gid) : chown(path, uid, gid); if (rc < 0) { struct stat st; if (lstat(path, &st) == 0 && st.st_uid == uid && st.st_gid == gid) rc = 0; } if (_fsm_debug) rpmlog(RPMLOG_DEBUG, " %8s (%s, %d, %d) %s\n", __func__, path, (int)uid, (int)gid, (rc < 0 ? strerror(errno) : "")); if (rc < 0) rc = RPMERR_CHOWN_FAILED; return rc; } static int fsmChmod(const char *path, mode_t mode) { int rc = chmod(path, (mode & 07777)); if (rc < 0) { struct stat st; if (lstat(path, &st) == 0 && (st.st_mode & 07777) == (mode & 07777)) rc = 0; } if (_fsm_debug) rpmlog(RPMLOG_DEBUG, " %8s (%s, 0%04o) %s\n", __func__, path, (unsigned)(mode & 07777), (rc < 0 ? strerror(errno) : "")); if (rc < 0) rc = RPMERR_CHMOD_FAILED; return rc; } static int fsmUtime(const char *path, mode_t mode, time_t mtime) { int rc = 0; struct timeval stamps[2] = { { .tv_sec = mtime, .tv_usec = 0 }, { .tv_sec = mtime, .tv_usec = 0 }, }; #if HAVE_LUTIMES rc = lutimes(path, stamps); #else if (!S_ISLNK(mode)) rc = utimes(path, stamps); #endif if (_fsm_debug) rpmlog(RPMLOG_DEBUG, " %8s (%s, 0x%x) %s\n", __func__, path, (unsigned)mtime, (rc < 0 ? strerror(errno) : "")); if (rc < 0) rc = RPMERR_UTIME_FAILED; /* ...but utime error is not critical for directories */ if (rc && S_ISDIR(mode)) rc = 0; return rc; } static int fsmVerify(const char *path, rpmfi fi) { int rc; int saveerrno = errno; struct stat dsb; mode_t mode = rpmfiFMode(fi); rc = fsmStat(path, 1, &dsb); if (rc) return rc; if (S_ISREG(mode)) { /* HP-UX (and other os'es) don't permit unlink on busy files. */ char *rmpath = rstrscat(NULL, path, "-RPMDELETE", NULL); rc = fsmRename(path, rmpath); /* XXX shouldn't we take unlink return code here? */ if (!rc) (void) fsmUnlink(rmpath); else rc = RPMERR_UNLINK_FAILED; free(rmpath); return (rc ? rc : RPMERR_ENOENT); /* XXX HACK */ } else if (S_ISDIR(mode)) { if (S_ISDIR(dsb.st_mode)) return 0; if (S_ISLNK(dsb.st_mode)) { rc = fsmStat(path, 0, &dsb); if (rc == RPMERR_ENOENT) rc = 0; if (rc) return rc; errno = saveerrno; if (S_ISDIR(dsb.st_mode)) return 0; } } else if (S_ISLNK(mode)) { if (S_ISLNK(dsb.st_mode)) { char buf[8 * BUFSIZ]; size_t len; rc = fsmReadLink(path, buf, 8 * BUFSIZ, &len); errno = saveerrno; if (rc) return rc; if (rstreq(rpmfiFLink(fi), buf)) return 0; } } else if (S_ISFIFO(mode)) { if (S_ISFIFO(dsb.st_mode)) return 0; } else if (S_ISCHR(mode) || S_ISBLK(mode)) { if ((S_ISCHR(dsb.st_mode) || S_ISBLK(dsb.st_mode)) && (dsb.st_rdev == rpmfiFRdev(fi))) return 0; } else if (S_ISSOCK(mode)) { if (S_ISSOCK(dsb.st_mode)) return 0; } /* XXX shouldn't do this with commit/undo. */ rc = fsmUnlink(path); if (rc == 0) rc = RPMERR_ENOENT; return (rc ? rc : RPMERR_ENOENT); /* XXX HACK */ } #define IS_DEV_LOG(_x) \ ((_x) != NULL && strlen(_x) >= (sizeof("/dev/log")-1) && \ rstreqn((_x), "/dev/log", sizeof("/dev/log")-1) && \ ((_x)[sizeof("/dev/log")-1] == '\0' || \ (_x)[sizeof("/dev/log")-1] == ';')) /* Rename pre-existing modified or unmanaged file. */ static int fsmBackup(rpmfi fi, rpmFileAction action) { int rc = 0; const char *suffix = NULL; if (!(rpmfiFFlags(fi) & RPMFILE_GHOST)) { switch (action) { case FA_SAVE: suffix = SUFFIX_RPMSAVE; break; case FA_BACKUP: suffix = SUFFIX_RPMORIG; break; default: break; } } if (suffix) { char * opath = fsmFsPath(fi, NULL); char * path = fsmFsPath(fi, suffix); rc = fsmRename(opath, path); if (!rc) { rpmlog(RPMLOG_WARNING, _("%s saved as %s\n"), opath, path); } free(path); free(opath); } return rc; } static int fsmSetmeta(const char *path, rpmfi fi, rpmPlugins plugins, rpmFileAction action, const struct stat * st, int nofcaps) { int rc = 0; const char *dest = rpmfiFN(fi); if (!rc && !getuid()) { rc = fsmChown(path, st->st_mode, st->st_uid, st->st_gid); } if (!rc && !S_ISLNK(st->st_mode)) { rc = fsmChmod(path, st->st_mode); } /* Set file capabilities (if enabled) */ if (!rc && !nofcaps && S_ISREG(st->st_mode) && !getuid()) { rc = fsmSetFCaps(path, rpmfiFCaps(fi)); } if (!rc) { rc = fsmUtime(path, st->st_mode, rpmfiFMtime(fi)); } if (!rc) { rc = rpmpluginsCallFsmFilePrepare(plugins, fi, path, dest, st->st_mode, action); } return rc; } static int fsmCommit(char **path, rpmfi fi, rpmFileAction action, const char *suffix) { int rc = 0; /* XXX Special case /dev/log, which shouldn't be packaged anyways */ if (!(S_ISSOCK(rpmfiFMode(fi)) && IS_DEV_LOG(*path))) { const char *nsuffix = (action == FA_ALTNAME) ? SUFFIX_RPMNEW : NULL; char *dest = *path; /* Construct final destination path (nsuffix is usually NULL) */ if (suffix) dest = fsmFsPath(fi, nsuffix); /* Rename temporary to final file name if needed. */ if (dest != *path) { rc = fsmRename(*path, dest); if (!rc && nsuffix) { char * opath = fsmFsPath(fi, NULL); rpmlog(RPMLOG_WARNING, _("%s created as %s\n"), opath, dest); free(opath); } free(*path); *path = dest; } } return rc; } /** * Return formatted string representation of file disposition. * @param a file disposition * @return formatted string */ static const char * fileActionString(rpmFileAction a) { switch (a) { case FA_UNKNOWN: return "unknown"; case FA_CREATE: return "create"; case FA_BACKUP: return "backup"; case FA_SAVE: return "save"; case FA_SKIP: return "skip"; case FA_ALTNAME: return "altname"; case FA_ERASE: return "erase"; case FA_SKIPNSTATE: return "skipnstate"; case FA_SKIPNETSHARED: return "skipnetshared"; case FA_SKIPCOLOR: return "skipcolor"; case FA_TOUCH: return "touch"; default: return "???"; } } /* Remember any non-regular file state for recording in the rpmdb */ static void setFileState(rpmfs fs, int i) { switch (rpmfsGetAction(fs, i)) { case FA_SKIPNSTATE: rpmfsSetState(fs, i, RPMFILE_STATE_NOTINSTALLED); break; case FA_SKIPNETSHARED: rpmfsSetState(fs, i, RPMFILE_STATE_NETSHARED); break; case FA_SKIPCOLOR: rpmfsSetState(fs, i, RPMFILE_STATE_WRONGCOLOR); break; case FA_TOUCH: rpmfsSetState(fs, i, RPMFILE_STATE_NORMAL); break; default: break; } } int rpmPackageFilesInstall(rpmts ts, rpmte te, rpmfiles files, rpmpsm psm, char ** failedFile) { FD_t payload = rpmtePayload(te); rpmfi fi = rpmfiNewArchiveReader(payload, files, RPMFI_ITER_READ_ARCHIVE); rpmfs fs = rpmteGetFileStates(te); rpmPlugins plugins = rpmtsPlugins(ts); struct stat sb; int saveerrno = errno; int rc = 0; int nodigest = (rpmtsFlags(ts) & RPMTRANS_FLAG_NOFILEDIGEST) ? 1 : 0; int nofcaps = (rpmtsFlags(ts) & RPMTRANS_FLAG_NOCAPS) ? 1 : 0; int firsthardlink = -1; int skip; rpmFileAction action; char *tid = NULL; const char *suffix; char *fpath = NULL; if (fi == NULL) { rc = RPMERR_BAD_MAGIC; goto exit; } /* transaction id used for temporary path suffix while installing */ rasprintf(&tid, ";%08x", (unsigned)rpmtsGetTid(ts)); /* Detect and create directories not explicitly in package. */ rc = fsmMkdirs(files, fs, plugins); while (!rc) { /* Read next payload header. */ rc = rpmfiNext(fi); if (rc < 0) { if (rc == RPMERR_ITER_END) rc = 0; break; } action = rpmfsGetAction(fs, rpmfiFX(fi)); skip = XFA_SKIPPING(action); suffix = S_ISDIR(rpmfiFMode(fi)) ? NULL : tid; if (action != FA_TOUCH) { fpath = fsmFsPath(fi, suffix); } else { fpath = fsmFsPath(fi, ""); } /* Remap file perms, owner, and group. */ rc = rpmfiStat(fi, 1, &sb); fsmDebug(fpath, action, &sb); /* Exit on error. */ if (rc) break; /* Run fsm file pre hook for all plugins */ rc = rpmpluginsCallFsmFilePre(plugins, fi, fpath, sb.st_mode, action); if (rc) { skip = 1; } else { setFileState(fs, rpmfiFX(fi)); } if (!skip) { int setmeta = 1; /* Directories replacing something need early backup */ if (!suffix) { rc = fsmBackup(fi, action); } /* Assume file does't exist when tmp suffix is in use */ if (!suffix) { rc = fsmVerify(fpath, fi); } else { rc = (action == FA_TOUCH) ? 0 : RPMERR_ENOENT; } if (S_ISREG(sb.st_mode)) { if (rc == RPMERR_ENOENT) { rc = fsmMkfile(fi, fpath, files, psm, nodigest, &setmeta, &firsthardlink); } } else if (S_ISDIR(sb.st_mode)) { if (rc == RPMERR_ENOENT) { mode_t mode = sb.st_mode; mode &= ~07777; mode |= 00700; rc = fsmMkdir(fpath, mode); } } else if (S_ISLNK(sb.st_mode)) { if (rc == RPMERR_ENOENT) { rc = fsmSymlink(rpmfiFLink(fi), fpath); } } else if (S_ISFIFO(sb.st_mode)) { /* This mimics cpio S_ISSOCK() behavior but probably isn't right */ if (rc == RPMERR_ENOENT) { rc = fsmMkfifo(fpath, 0000); } } else if (S_ISCHR(sb.st_mode) || S_ISBLK(sb.st_mode) || S_ISSOCK(sb.st_mode)) { if (rc == RPMERR_ENOENT) { rc = fsmMknod(fpath, sb.st_mode, sb.st_rdev); } } else { /* XXX Special case /dev/log, which shouldn't be packaged anyways */ if (!IS_DEV_LOG(fpath)) rc = RPMERR_UNKNOWN_FILETYPE; } /* Set permissions, timestamps etc for non-hardlink entries */ if (!rc && setmeta) { rc = fsmSetmeta(fpath, fi, plugins, action, &sb, nofcaps); } } else if (firsthardlink >= 0 && rpmfiArchiveHasContent(fi)) { /* we skip the hard linked file containing the content */ /* write the content to the first used instead */ char *fn = rpmfilesFN(files, firsthardlink); rc = expandRegular(fi, fn, psm, 0, nodigest, 0); firsthardlink = -1; free(fn); } if (rc) { if (!skip) { /* XXX only erase if temp fn w suffix is in use */ if (suffix && (action != FA_TOUCH)) { (void) fsmRemove(fpath, sb.st_mode); } errno = saveerrno; } } else { /* Notify on success. */ rpmpsmNotify(psm, RPMCALLBACK_INST_PROGRESS, rpmfiArchiveTell(fi)); if (!skip) { /* Backup file if needed. Directories are handled earlier */ if (suffix) rc = fsmBackup(fi, action); if (!rc) rc = fsmCommit(&fpath, fi, action, suffix); } } if (rc) *failedFile = xstrdup(fpath); /* Run fsm file post hook for all plugins */ rpmpluginsCallFsmFilePost(plugins, fi, fpath, sb.st_mode, action, rc); fpath = _free(fpath); } rpmswAdd(rpmtsOp(ts, RPMTS_OP_UNCOMPRESS), fdOp(payload, FDSTAT_READ)); rpmswAdd(rpmtsOp(ts, RPMTS_OP_DIGEST), fdOp(payload, FDSTAT_DIGEST)); exit: /* No need to bother with close errors on read */ rpmfiArchiveClose(fi); rpmfiFree(fi); Fclose(payload); free(tid); free(fpath); return rc; } int rpmPackageFilesRemove(rpmts ts, rpmte te, rpmfiles files, rpmpsm psm, char ** failedFile) { rpmfi fi = rpmfilesIter(files, RPMFI_ITER_BACK); rpmfs fs = rpmteGetFileStates(te); rpmPlugins plugins = rpmtsPlugins(ts); struct stat sb; int rc = 0; char *fpath = NULL; while (!rc && rpmfiNext(fi) >= 0) { rpmFileAction action = rpmfsGetAction(fs, rpmfiFX(fi)); fpath = fsmFsPath(fi, NULL); rc = fsmStat(fpath, 1, &sb); fsmDebug(fpath, action, &sb); /* Run fsm file pre hook for all plugins */ rc = rpmpluginsCallFsmFilePre(plugins, fi, fpath, sb.st_mode, action); if (!XFA_SKIPPING(action)) rc = fsmBackup(fi, action); /* Remove erased files. */ if (action == FA_ERASE) { int missingok = (rpmfiFFlags(fi) & (RPMFILE_MISSINGOK | RPMFILE_GHOST)); rc = fsmRemove(fpath, sb.st_mode); /* * Missing %ghost or %missingok entries are not errors. * XXX: Are non-existent files ever an actual error here? Afterall * that's exactly what we're trying to accomplish here, * and complaining about job already done seems like kinderkarten * level "But it was MY turn!" whining... */ if (rc == RPMERR_ENOENT && missingok) { rc = 0; } /* * Dont whine on non-empty directories for now. We might be able * to track at least some of the expected failures though, * such as when we knowingly left config file backups etc behind. */ if (rc == RPMERR_ENOTEMPTY) { rc = 0; } if (rc) { int lvl = strict_erasures ? RPMLOG_ERR : RPMLOG_WARNING; rpmlog(lvl, _("%s %s: remove failed: %s\n"), S_ISDIR(sb.st_mode) ? _("directory") : _("file"), fpath, strerror(errno)); } } /* Run fsm file post hook for all plugins */ rpmpluginsCallFsmFilePost(plugins, fi, fpath, sb.st_mode, action, rc); /* XXX Failure to remove is not (yet) cause for failure. */ if (!strict_erasures) rc = 0; if (rc) *failedFile = xstrdup(fpath); if (rc == 0) { /* Notify on success. */ /* On erase we're iterating backwards, fixup for progress */ rpm_loff_t amount = rpmfiFC(fi) - rpmfiFX(fi); rpmpsmNotify(psm, RPMCALLBACK_UNINST_PROGRESS, amount); } fpath = _free(fpath); } free(fpath); rpmfiFree(fi); return rc; }
./CrossVul/dataset_final_sorted/CWE-59/c/bad_3272_0
crossvul-cpp_data_good_1506_0
/* Copyright (C) 2010 ABRT team This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "problem_api.h" #include "libabrt.h" /* Maximal length of backtrace. */ #define MAX_BACKTRACE_SIZE (1024*1024) /* Amount of data received from one client for a message before reporting error. */ #define MAX_MESSAGE_SIZE (4*MAX_BACKTRACE_SIZE) /* Maximal number of characters read from socket at once. */ #define INPUT_BUFFER_SIZE (8*1024) /* We exit after this many seconds */ #define TIMEOUT 10 /* Unix socket in ABRT daemon for creating new dump directories. Why to use socket for creating dump dirs? Security. When a Python script throws unexpected exception, ABRT handler catches it, running as a part of that broken Python application. The application is running with certain SELinux privileges, for example it can not execute other programs, or to create files in /var/cache or anything else required to properly fill a problem directory. Adding these privileges to every application would weaken the security. The most suitable solution is for the Python application to open a socket where ABRT daemon is listening, write all relevant data to that socket, and close it. ABRT daemon handles the rest. ** Protocol Initializing new dump: open /var/run/abrt.socket Providing dump data (hook writes to the socket): MANDATORY ITEMS: -> "PID=" number 0 - PID_MAX (/proc/sys/kernel/pid_max) \0 -> "EXECUTABLE=" string \0 -> "BACKTRACE=" string \0 -> "ANALYZER=" string \0 -> "BASENAME=" string (no slashes) \0 -> "REASON=" string \0 You can send more messages using the same KEY=value format. */ static unsigned total_bytes_read = 0; static uid_t client_uid = (uid_t)-1L; /* Remove dump dir */ static int delete_path(const char *dump_dir_name) { /* If doesn't start with "g_settings_dump_location/"... */ if (!dir_is_in_dump_location(dump_dir_name)) { /* Then refuse to operate on it (someone is attacking us??) */ error_msg("Bad problem directory name '%s', should start with: '%s'", dump_dir_name, g_settings_dump_location); return 400; /* Bad Request */ } if (!dir_has_correct_permissions(dump_dir_name)) { error_msg("Problem directory '%s' isn't owned by root:abrt or others are not restricted from access", dump_dir_name); return 400; /* */ } int dir_fd = dd_openfd(dump_dir_name); if (dir_fd < 0) { perror_msg("Can't open problem directory '%s'", dump_dir_name); return 400; } if (!fdump_dir_accessible_by_uid(dir_fd, client_uid)) { close(dir_fd); if (errno == ENOTDIR) { error_msg("Path '%s' isn't problem directory", dump_dir_name); return 404; /* Not Found */ } error_msg("Problem directory '%s' can't be accessed by user with uid %ld", dump_dir_name, (long)client_uid); return 403; /* Forbidden */ } struct dump_dir *dd = dd_fdopendir(dir_fd, dump_dir_name, /*flags:*/ 0); if (dd) { if (dd_delete(dd) != 0) { error_msg("Failed to delete problem directory '%s'", dump_dir_name); dd_close(dd); return 400; } } return 0; /* success */ } static pid_t spawn_event_handler_child(const char *dump_dir_name, const char *event_name, int *fdp) { char *args[7]; args[0] = (char *) LIBEXEC_DIR"/abrt-handle-event"; /* Do not forward ASK_* messages to parent*/ args[1] = (char *) "-i"; args[2] = (char *) "-e"; args[3] = (char *) event_name; args[4] = (char *) "--"; args[5] = (char *) dump_dir_name; args[6] = NULL; int pipeout[2]; int flags = EXECFLG_INPUT_NUL | EXECFLG_OUTPUT | EXECFLG_QUIET | EXECFLG_ERR2OUT; VERB1 flags &= ~EXECFLG_QUIET; char *env_vec[2]; /* Intercept ASK_* messages in Client API -> don't wait for user response */ env_vec[0] = xstrdup("REPORT_CLIENT_NONINTERACTIVE=1"); env_vec[1] = NULL; pid_t child = fork_execv_on_steroids(flags, args, pipeout, env_vec, /*dir:*/ NULL, /*uid(unused):*/ 0); if (fdp) *fdp = pipeout[0]; return child; } static int run_post_create(const char *dirname) { /* If doesn't start with "g_settings_dump_location/"... */ if (!dir_is_in_dump_location(dirname)) { /* Then refuse to operate on it (someone is attacking us??) */ error_msg("Bad problem directory name '%s', should start with: '%s'", dirname, g_settings_dump_location); return 400; /* Bad Request */ } if (!dir_has_correct_permissions(dirname)) { error_msg("Problem directory '%s' isn't owned by root:abrt or others are not restricted from access", dirname); return 400; /* */ } if (g_settings_privatereports) { struct dump_dir *dd = dd_opendir(dirname, DD_OPEN_READONLY); const bool complete = dd && problem_dump_dir_is_complete(dd); dd_close(dd); if (complete) { error_msg("Problem directory '%s' has already been processed", dirname); return 403; } } int child_stdout_fd; int child_pid = spawn_event_handler_child(dirname, "post-create", &child_stdout_fd); char *dup_of_dir = NULL; struct strbuf *cmd_output = strbuf_new(); bool child_is_post_create = 1; /* else it is a notify child */ read_child_output: //log("Reading from event fd %d", child_stdout_fd); /* Read streamed data and split lines */ for (;;) { char buf[250]; /* usually we get one line, no need to have big buf */ errno = 0; int r = safe_read(child_stdout_fd, buf, sizeof(buf) - 1); if (r <= 0) break; buf[r] = '\0'; /* split lines in the current buffer */ char *raw = buf; char *newline; while ((newline = strchr(raw, '\n')) != NULL) { *newline = '\0'; strbuf_append_str(cmd_output, raw); char *msg = cmd_output->buf; /* Hmm, DUP_OF_DIR: ends up in syslog. move log() into 'else'? */ log("%s", msg); if (child_is_post_create && prefixcmp(msg, "DUP_OF_DIR: ") == 0 ) { free(dup_of_dir); dup_of_dir = xstrdup(msg + strlen("DUP_OF_DIR: ")); } strbuf_clear(cmd_output); /* jump to next line */ raw = newline + 1; } /* beginning of next line. the line continues by next read */ strbuf_append_str(cmd_output, raw); } /* EOF/error */ /* Wait for child to actually exit, collect status */ int status = 0; if (safe_waitpid(child_pid, &status, 0) <= 0) /* should not happen */ perror_msg("waitpid(%d)", child_pid); /* If it was a "notify[-dup]" event, then we're done */ if (!child_is_post_create) goto ret; /* exit 0 means "this is a good, non-dup dir" */ /* exit with 1 + "DUP_OF_DIR: dir" string => dup */ if (status != 0) { if (WIFSIGNALED(status)) { log("'post-create' on '%s' killed by signal %d", dirname, WTERMSIG(status)); goto delete_bad_dir; } /* else: it is WIFEXITED(status) */ if (!dup_of_dir) { log("'post-create' on '%s' exited with %d", dirname, WEXITSTATUS(status)); goto delete_bad_dir; } } const char *work_dir = (dup_of_dir ? dup_of_dir : dirname); /* Load problem_data (from the *first dir* if this one is a dup) */ struct dump_dir *dd = dd_opendir(work_dir, /*flags:*/ 0); if (!dd) /* dd_opendir already emitted error msg */ goto delete_bad_dir; /* Update count */ char *count_str = dd_load_text_ext(dd, FILENAME_COUNT, DD_FAIL_QUIETLY_ENOENT); unsigned long count = strtoul(count_str, NULL, 10); /* Don't increase crash count if we are working with newly uploaded * directory (remote crash) which already has its crash count set. */ if ((status != 0 && dup_of_dir) || count == 0) { count++; char new_count_str[sizeof(long)*3 + 2]; sprintf(new_count_str, "%lu", count); dd_save_text(dd, FILENAME_COUNT, new_count_str); /* This condition can be simplified to either * (status * != 0 && * dup_of_dir) or (count == 1). But the * chosen form is much more reliable and safe. We must not call * dd_opendir() to locked dd otherwise we go into a deadlock. */ if (strcmp(dd->dd_dirname, dirname) != 0) { /* Update the last occurrence file by the time file of the new problem */ struct dump_dir *new_dd = dd_opendir(dirname, DD_OPEN_READONLY); char *last_ocr = NULL; if (new_dd) { /* TIME must exists in a valid dump directory but we don't want to die * due to broken duplicated dump directory */ last_ocr = dd_load_text_ext(new_dd, FILENAME_TIME, DD_LOAD_TEXT_RETURN_NULL_ON_FAILURE | DD_FAIL_QUIETLY_ENOENT); dd_close(new_dd); } else { /* dd_opendir() already produced a message with good information about failure */ error_msg("Can't read the last occurrence file from the new dump directory."); } if (!last_ocr) { /* the new dump directory may lie in the dump location for some time */ log("Using current time for the last occurrence file which may be incorrect."); time_t t = time(NULL); last_ocr = xasprintf("%lu", (long)t); } dd_save_text(dd, FILENAME_LAST_OCCURRENCE, last_ocr); free(last_ocr); } } /* Reset mode/uig/gid to correct values for all files created by event run */ dd_sanitize_mode_and_owner(dd); dd_close(dd); if (!dup_of_dir) log_notice("New problem directory %s, processing", work_dir); else { log_warning("Deleting problem directory %s (dup of %s)", strrchr(dirname, '/') + 1, strrchr(dup_of_dir, '/') + 1); delete_dump_dir(dirname); } /* Run "notify[-dup]" event */ int fd; child_pid = spawn_event_handler_child( work_dir, (dup_of_dir ? "notify-dup" : "notify"), &fd ); //log("Started notify, fd %d -> %d", fd, child_stdout_fd); xmove_fd(fd, child_stdout_fd); child_is_post_create = 0; strbuf_clear(cmd_output); free(dup_of_dir); dup_of_dir = NULL; goto read_child_output; delete_bad_dir: log_warning("Deleting problem directory '%s'", dirname); delete_dump_dir(dirname); ret: strbuf_free(cmd_output); free(dup_of_dir); close(child_stdout_fd); return 0; } /* Create a new problem directory from client session. * Caller must ensure that all fields in struct client * are properly filled. */ static int create_problem_dir(GHashTable *problem_info, unsigned pid) { /* Exit if free space is less than 1/4 of MaxCrashReportsSize */ if (g_settings_nMaxCrashReportsSize > 0) { if (low_free_space(g_settings_nMaxCrashReportsSize, g_settings_dump_location)) exit(1); } /* Create temp directory with the problem data. * This directory is renamed to final directory name after * all files have been stored into it. */ gchar *dir_basename = g_hash_table_lookup(problem_info, "basename"); if (!dir_basename) dir_basename = g_hash_table_lookup(problem_info, FILENAME_TYPE); char *path = xasprintf("%s/%s-%s-%u.new", g_settings_dump_location, dir_basename, iso_date_string(NULL), pid); /* This item is useless, don't save it */ g_hash_table_remove(problem_info, "basename"); /* No need to check the path length, as all variables used are limited, * and dd_create() fails if the path is too long. */ struct dump_dir *dd = dd_create(path, g_settings_privatereports ? 0 : client_uid, DEFAULT_DUMP_DIR_MODE); if (!dd) { error_msg_and_die("Error creating problem directory '%s'", path); } dd_create_basic_files(dd, client_uid, NULL); dd_save_text(dd, FILENAME_ABRT_VERSION, VERSION); gpointer gpkey = g_hash_table_lookup(problem_info, FILENAME_CMDLINE); if (!gpkey) { /* Obtain and save the command line. */ char *cmdline = get_cmdline(pid); if (cmdline) { dd_save_text(dd, FILENAME_CMDLINE, cmdline); free(cmdline); } } /* Store id of the user whose application crashed. */ char uid_str[sizeof(long) * 3 + 2]; sprintf(uid_str, "%lu", (long)client_uid); dd_save_text(dd, FILENAME_UID, uid_str); GHashTableIter iter; gpointer gpvalue; g_hash_table_iter_init(&iter, problem_info); while (g_hash_table_iter_next(&iter, &gpkey, &gpvalue)) { dd_save_text(dd, (gchar *) gpkey, (gchar *) gpvalue); } dd_close(dd); /* Not needing it anymore */ g_hash_table_destroy(problem_info); /* Move the completely created problem directory * to final directory. */ char *newpath = xstrndup(path, strlen(path) - strlen(".new")); if (rename(path, newpath) == 0) strcpy(path, newpath); free(newpath); log_notice("Saved problem directory of pid %u to '%s'", pid, path); /* We let the peer know that problem dir was created successfully * _before_ we run potentially long-running post-create. */ printf("HTTP/1.1 201 Created\r\n\r\n"); fflush(NULL); close(STDOUT_FILENO); xdup2(STDERR_FILENO, STDOUT_FILENO); /* paranoia: don't leave stdout fd closed */ /* Trim old problem directories if necessary */ if (g_settings_nMaxCrashReportsSize > 0) { trim_problem_dirs(g_settings_dump_location, g_settings_nMaxCrashReportsSize * (double)(1024*1024), path); } run_post_create(path); /* free(path); */ exit(0); } static gboolean key_value_ok(gchar *key, gchar *value) { char *i; /* check key, it has to be valid filename and will end up in the * bugzilla */ for (i = key; *i != 0; i++) { if (!isalpha(*i) && (*i != '-') && (*i != '_') && (*i != ' ')) return FALSE; } /* check value of 'basename', it has to be valid non-hidden directory * name */ if (strcmp(key, "basename") == 0 || strcmp(key, FILENAME_TYPE) == 0 ) { if (!str_is_correct_filename(value)) { error_msg("Value of '%s' ('%s') is not a valid directory name", key, value); return FALSE; } } return allowed_new_user_problem_entry(client_uid, key, value); } /* Handles a message received from client over socket. */ static void process_message(GHashTable *problem_info, char *message) { gchar *key, *value; value = strchr(message, '='); if (value) { key = g_ascii_strdown(message, value - message); /* result is malloced */ //TODO: is it ok? it uses g_malloc, not malloc! value++; if (key_value_ok(key, value)) { if (strcmp(key, FILENAME_UID) == 0) { error_msg("Ignoring value of %s, will be determined later", FILENAME_UID); } else { g_hash_table_insert(problem_info, key, xstrdup(value)); /* Compat, delete when FILENAME_ANALYZER is replaced by FILENAME_TYPE: */ if (strcmp(key, FILENAME_TYPE) == 0) g_hash_table_insert(problem_info, xstrdup(FILENAME_ANALYZER), xstrdup(value)); /* Prevent freeing key later: */ key = NULL; } } else { /* should use error_msg_and_die() here? */ error_msg("Invalid key or value format: %s", message); } free(key); } else { /* should use error_msg_and_die() here? */ error_msg("Invalid message format: '%s'", message); } } static void die_if_data_is_missing(GHashTable *problem_info) { gboolean missing_data = FALSE; gchar **pstring; static const gchar *const needed[] = { FILENAME_TYPE, FILENAME_REASON, /* FILENAME_BACKTRACE, - ECC errors have no such elements */ /* FILENAME_EXECUTABLE, */ NULL }; for (pstring = (gchar**) needed; *pstring; pstring++) { if (!g_hash_table_lookup(problem_info, *pstring)) { error_msg("Element '%s' is missing", *pstring); missing_data = TRUE; } } if (missing_data) error_msg_and_die("Some data is missing, aborting"); } /* * Takes hash table, looks for key FILENAME_PID and tries to convert its value * to int. */ unsigned convert_pid(GHashTable *problem_info) { long ret; gchar *pid_str = (gchar *) g_hash_table_lookup(problem_info, FILENAME_PID); char *err_pos; if (!pid_str) error_msg_and_die("PID data is missing, aborting"); errno = 0; ret = strtol(pid_str, &err_pos, 10); if (errno || pid_str == err_pos || *err_pos != '\0' || ret > UINT_MAX || ret < 1) error_msg_and_die("Malformed or out-of-range PID number: '%s'", pid_str); return (unsigned) ret; } static int perform_http_xact(void) { /* use free instead of g_free so that we can use xstr* functions from * libreport/lib/xfuncs.c */ GHashTable *problem_info = g_hash_table_new_full(g_str_hash, g_str_equal, free, free); /* Read header */ char *body_start = NULL; char *messagebuf_data = NULL; unsigned messagebuf_len = 0; /* Loop until EOF/error/timeout/end_of_header */ while (1) { messagebuf_data = xrealloc(messagebuf_data, messagebuf_len + INPUT_BUFFER_SIZE); char *p = messagebuf_data + messagebuf_len; int rd = read(STDIN_FILENO, p, INPUT_BUFFER_SIZE); if (rd < 0) { if (errno == EINTR) /* SIGALRM? */ error_msg_and_die("Timed out"); perror_msg_and_die("read"); } if (rd == 0) break; log_debug("Received %u bytes of data", rd); messagebuf_len += rd; total_bytes_read += rd; if (total_bytes_read > MAX_MESSAGE_SIZE) error_msg_and_die("Message is too long, aborting"); /* Check whether we see end of header */ /* Note: we support both [\r]\n\r\n and \n\n */ char *past_end = messagebuf_data + messagebuf_len; if (p > messagebuf_data+1) p -= 2; /* start search from two last bytes in last read - they might be '\n\r' */ while (p < past_end) { p = memchr(p, '\n', past_end - p); if (!p) break; p++; if (p >= past_end) break; if (*p == '\n' || (*p == '\r' && p+1 < past_end && p[1] == '\n') ) { body_start = p + 1 + (*p == '\r'); *p = '\0'; goto found_end_of_header; } } } /* while (read) */ found_end_of_header: ; log_debug("Request: %s", messagebuf_data); /* Sanitize and analyze header. * Header now is in messagebuf_data, NUL terminated string, * with last empty line deleted (by placement of NUL). * \r\n are not (yet) converted to \n, multi-line headers also * not converted. */ /* First line must be "op<space>[http://host]/path<space>HTTP/n.n". * <space> is exactly one space char. */ if (prefixcmp(messagebuf_data, "DELETE ") == 0) { messagebuf_data += strlen("DELETE "); char *space = strchr(messagebuf_data, ' '); if (!space || prefixcmp(space+1, "HTTP/") != 0) return 400; /* Bad Request */ *space = '\0'; //decode_url(messagebuf_data); %20 => ' ' alarm(0); return delete_path(messagebuf_data); } /* We erroneously used "PUT /" to create new problems. * POST is the correct request in this case: * "PUT /" implies creation or replace of resource named "/"! * Delete PUT in 2014. */ if (prefixcmp(messagebuf_data, "PUT ") != 0 && prefixcmp(messagebuf_data, "POST ") != 0 ) { return 400; /* Bad Request */ } enum { CREATION_NOTIFICATION, CREATION_REQUEST, }; int url_type; char *url = skip_non_whitespace(messagebuf_data) + 1; /* skip "POST " */ if (prefixcmp(url, "/creation_notification ") == 0) url_type = CREATION_NOTIFICATION; else if (prefixcmp(url, "/ ") == 0) url_type = CREATION_REQUEST; else return 400; /* Bad Request */ /* Read body */ if (!body_start) { log_warning("Premature EOF detected, exiting"); return 400; /* Bad Request */ } messagebuf_len -= (body_start - messagebuf_data); memmove(messagebuf_data, body_start, messagebuf_len); log_debug("Body so far: %u bytes, '%s'", messagebuf_len, messagebuf_data); /* Loop until EOF/error/timeout */ while (1) { if (url_type == CREATION_REQUEST) { while (1) { unsigned len = strnlen(messagebuf_data, messagebuf_len); if (len >= messagebuf_len) break; /* messagebuf has at least one NUL - process the line */ process_message(problem_info, messagebuf_data); messagebuf_len -= (len + 1); memmove(messagebuf_data, messagebuf_data + len + 1, messagebuf_len); } } messagebuf_data = xrealloc(messagebuf_data, messagebuf_len + INPUT_BUFFER_SIZE + 1); int rd = read(STDIN_FILENO, messagebuf_data + messagebuf_len, INPUT_BUFFER_SIZE); if (rd < 0) { if (errno == EINTR) /* SIGALRM? */ error_msg_and_die("Timed out"); perror_msg_and_die("read"); } if (rd == 0) break; log_debug("Received %u bytes of data", rd); messagebuf_len += rd; total_bytes_read += rd; if (total_bytes_read > MAX_MESSAGE_SIZE) error_msg_and_die("Message is too long, aborting"); } /* Body received, EOF was seen. Don't let alarm to interrupt after this. */ alarm(0); int ret = 0; if (url_type == CREATION_NOTIFICATION) { if (client_uid != 0) { error_msg("UID=%ld is not authorized to trigger post-create processing", (long)client_uid); ret = 403; /* Forbidden */ goto out; } messagebuf_data[messagebuf_len] = '\0'; return run_post_create(messagebuf_data); } /* Save problem dir */ unsigned pid = convert_pid(problem_info); die_if_data_is_missing(problem_info); char *executable = g_hash_table_lookup(problem_info, FILENAME_EXECUTABLE); if (executable) { char *last_file = concat_path_file(g_settings_dump_location, "last-via-server"); int repeating_crash = check_recent_crash_file(last_file, executable); free(last_file); if (repeating_crash) /* Only pretend that we saved it */ goto out; /* ret is 0: "success" */ } #if 0 //TODO: /* At least it should generate local problem identifier UUID */ problem_data_add_basics(problem_info); //...the problem being that problem_info here is not a problem_data_t! #endif create_problem_dir(problem_info, pid); /* does not return */ out: g_hash_table_destroy(problem_info); return ret; /* Used as HTTP response code */ } static void dummy_handler(int sig_unused) {} int main(int argc, char **argv) { /* I18n */ setlocale(LC_ALL, ""); #if ENABLE_NLS bindtextdomain(PACKAGE, LOCALEDIR); textdomain(PACKAGE); #endif abrt_init(argv); /* Can't keep these strings/structs static: _() doesn't support that */ const char *program_usage_string = _( "& [options]" ); enum { OPT_v = 1 << 0, OPT_u = 1 << 1, OPT_s = 1 << 2, OPT_p = 1 << 3, }; /* Keep enum above and order of options below in sync! */ struct options program_options[] = { OPT__VERBOSE(&g_verbose), OPT_INTEGER('u', NULL, &client_uid, _("Use NUM as client uid")), OPT_BOOL( 's', NULL, NULL , _("Log to syslog")), OPT_BOOL( 'p', NULL, NULL , _("Add program names to log")), OPT_END() }; unsigned opts = parse_opts(argc, argv, program_options, program_usage_string); export_abrt_envvars(opts & OPT_p); msg_prefix = xasprintf("%s[%u]", g_progname, getpid()); if (opts & OPT_s) { logmode = LOGMODE_JOURNAL; } /* Set up timeout handling */ /* Part 1 - need this to make SIGALRM interrupt syscalls * (as opposed to restarting them): I want read syscall to be interrupted */ struct sigaction sa; /* sa.sa_flags.SA_RESTART bit is clear: make signal interrupt syscalls */ memset(&sa, 0, sizeof(sa)); sa.sa_handler = dummy_handler; /* pity, SIG_DFL won't do */ sigaction(SIGALRM, &sa, NULL); /* Part 2 - set the timeout per se */ alarm(TIMEOUT); if (client_uid == (uid_t)-1L) { /* Get uid of the connected client */ struct ucred cr; socklen_t crlen = sizeof(cr); if (0 != getsockopt(STDIN_FILENO, SOL_SOCKET, SO_PEERCRED, &cr, &crlen)) perror_msg_and_die("getsockopt(SO_PEERCRED)"); if (crlen != sizeof(cr)) error_msg_and_die("%s: bad crlen %d", "getsockopt(SO_PEERCRED)", (int)crlen); client_uid = cr.uid; } load_abrt_conf(); int r = perform_http_xact(); if (r == 0) r = 200; free_abrt_conf_data(); printf("HTTP/1.1 %u \r\n\r\n", r); return (r >= 400); /* Error if 400+ */ } #if 0 // TODO: example of SSLed connection #include <openssl/ssl.h> #include <openssl/err.h> if (flags & OPT_SSL) { /* load key and cert files */ SSL_CTX *ctx; SSL *ssl; ctx = init_ssl_context(); if (SSL_CTX_use_certificate_file(ctx, cert_path, SSL_FILETYPE_PEM) <= 0 || SSL_CTX_use_PrivateKey_file(ctx, key_path, SSL_FILETYPE_PEM) <= 0 ) { ERR_print_errors_fp(stderr); error_msg_and_die("SSL certificates err\n"); } if (!SSL_CTX_check_private_key(ctx)) { error_msg_and_die("Private key does not match public key\n"); } (void)SSL_CTX_set_mode(ctx, SSL_MODE_AUTO_RETRY); //TODO more errors? ssl = SSL_new(ctx); SSL_set_fd(ssl, sockfd_in); //SSL_set_accept_state(ssl); if (SSL_accept(ssl) == 1) { //while whatever serve while (serve(ssl, flags)) continue; //TODO errors SSL_shutdown(ssl); } SSL_free(ssl); SSL_CTX_free(ctx); } else { while (serve(&sockfd_in, flags)) continue; } err = (flags & OPT_SSL) ? SSL_read(sock, buffer, READ_BUF-1): read(*(int*)sock, buffer, READ_BUF-1); if ( err < 0 ) { //TODO handle errno || SSL_get_error(ssl,err); break; } if ( err == 0 ) break; if (!head) { buffer[err] = '\0'; clean[i%2] = delete_cr(buffer); cut = g_strstr_len(buffer, -1, "\n\n"); if ( cut == NULL ) { g_string_append(headers, buffer); } else { g_string_append_len(headers, buffer, cut-buffer); } } /* end of header section? */ if ( !head && ( cut != NULL || (clean[(i+1)%2] && buffer[0]=='\n') ) ) { parse_head(&request, headers); head = TRUE; c_len = has_body(&request); if ( c_len ) { //if we want to read body some day - this will be the right place to begin //malloc body append rest of the (fixed) buffer at the beginning of a body //if clean buffer[1]; } else { break; } break; //because we don't support body yet } else if ( head == TRUE ) { /* body-reading stuff * read body, check content-len * save body to request */ break; } else { // count header size len += err; if ( len > READ_BUF-1 ) { //TODO header is too long break; } } i++; } g_string_free(headers, true); //because we allocated it rt = generate_response(&request, &response); /* write headers */ if ( flags & OPT_SSL ) { //TODO err err = SSL_write(sock, response.response_line, strlen(response.response_line)); err = SSL_write(sock, response.head->str , strlen(response.head->str)); err = SSL_write(sock, "\r\n", 2); } else { //TODO err err = write(*(int*)sock, response.response_line, strlen(response.response_line)); err = write(*(int*)sock, response.head->str , strlen(response.head->str)); err = write(*(int*)sock, "\r\n", 2); } #endif
./CrossVul/dataset_final_sorted/CWE-59/c/good_1506_0
crossvul-cpp_data_good_1468_0
/* liblxcapi * * Copyright © 2012 Serge Hallyn <serge.hallyn@ubuntu.com>. * Copyright © 2012 Canonical Ltd. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #define _GNU_SOURCE #include "lxclock.h" #include <malloc.h> #include <stdio.h> #include <errno.h> #include <unistd.h> #include <fcntl.h> #include <stdlib.h> #include <pthread.h> #include <lxc/lxccontainer.h> #include "utils.h" #include "log.h" #ifdef MUTEX_DEBUGGING #include <execinfo.h> #endif #define MAX_STACKDEPTH 25 #define OFLAG (O_CREAT | O_RDWR) #define SEMMODE 0660 #define SEMVALUE 1 #define SEMVALUE_LOCKED 0 lxc_log_define(lxc_lock, lxc); #ifdef MUTEX_DEBUGGING static pthread_mutex_t thread_mutex = PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP; static inline void dump_stacktrace(void) { void *array[MAX_STACKDEPTH]; size_t size; char **strings; size_t i; size = backtrace(array, MAX_STACKDEPTH); strings = backtrace_symbols(array, size); // Using fprintf here as our logging module is not thread safe fprintf(stderr, "\tObtained %zd stack frames.\n", size); for (i = 0; i < size; i++) fprintf(stderr, "\t\t%s\n", strings[i]); free (strings); } #else static pthread_mutex_t thread_mutex = PTHREAD_MUTEX_INITIALIZER; static inline void dump_stacktrace(void) {;} #endif static void lock_mutex(pthread_mutex_t *l) { int ret; if ((ret = pthread_mutex_lock(l)) != 0) { fprintf(stderr, "pthread_mutex_lock returned:%d %s\n", ret, strerror(ret)); dump_stacktrace(); exit(1); } } static void unlock_mutex(pthread_mutex_t *l) { int ret; if ((ret = pthread_mutex_unlock(l)) != 0) { fprintf(stderr, "pthread_mutex_unlock returned:%d %s\n", ret, strerror(ret)); dump_stacktrace(); exit(1); } } static char *lxclock_name(const char *p, const char *n) { int ret; int len; char *dest; char *rundir; /* lockfile will be: * "/run" + "/lxc/lock/$lxcpath/$lxcname + '\0' if root * or * $XDG_RUNTIME_DIR + "/lxc/lock/$lxcpath/$lxcname + '\0' if non-root */ /* length of "/lxc/lock/" + $lxcpath + "/" + "." + $lxcname + '\0' */ len = strlen("/lxc/lock/") + strlen(n) + strlen(p) + 3; rundir = get_rundir(); if (!rundir) return NULL; len += strlen(rundir); if ((dest = malloc(len)) == NULL) { free(rundir); return NULL; } ret = snprintf(dest, len, "%s/lxc/lock/%s", rundir, p); if (ret < 0 || ret >= len) { free(dest); free(rundir); return NULL; } ret = mkdir_p(dest, 0755); if (ret < 0) { free(dest); free(rundir); return NULL; } ret = snprintf(dest, len, "%s/lxc/lock/%s/.%s", rundir, p, n); free(rundir); if (ret < 0 || ret >= len) { free(dest); return NULL; } return dest; } static sem_t *lxc_new_unnamed_sem(void) { sem_t *s; int ret; s = malloc(sizeof(*s)); if (!s) return NULL; ret = sem_init(s, 0, 1); if (ret) { free(s); return NULL; } return s; } struct lxc_lock *lxc_newlock(const char *lxcpath, const char *name) { struct lxc_lock *l; l = malloc(sizeof(*l)); if (!l) goto out; if (!name) { l->type = LXC_LOCK_ANON_SEM; l->u.sem = lxc_new_unnamed_sem(); if (!l->u.sem) { free(l); l = NULL; } goto out; } l->type = LXC_LOCK_FLOCK; l->u.f.fname = lxclock_name(lxcpath, name); if (!l->u.f.fname) { free(l); l = NULL; goto out; } l->u.f.fd = -1; out: return l; } int lxclock(struct lxc_lock *l, int timeout) { int ret = -1, saved_errno = errno; struct flock lk; switch(l->type) { case LXC_LOCK_ANON_SEM: if (!timeout) { ret = sem_wait(l->u.sem); if (ret == -1) saved_errno = errno; } else { struct timespec ts; if (clock_gettime(CLOCK_REALTIME, &ts) == -1) { ret = -2; goto out; } ts.tv_sec += timeout; ret = sem_timedwait(l->u.sem, &ts); if (ret == -1) saved_errno = errno; } break; case LXC_LOCK_FLOCK: ret = -2; if (timeout) { ERROR("Error: timeout not supported with flock"); ret = -2; goto out; } if (!l->u.f.fname) { ERROR("Error: filename not set for flock"); ret = -2; goto out; } if (l->u.f.fd == -1) { l->u.f.fd = open(l->u.f.fname, O_RDWR|O_CREAT, S_IWUSR | S_IRUSR); if (l->u.f.fd == -1) { ERROR("Error opening %s", l->u.f.fname); goto out; } } lk.l_type = F_WRLCK; lk.l_whence = SEEK_SET; lk.l_start = 0; lk.l_len = 0; ret = fcntl(l->u.f.fd, F_SETLKW, &lk); if (ret == -1) saved_errno = errno; break; } out: errno = saved_errno; return ret; } int lxcunlock(struct lxc_lock *l) { int ret = 0, saved_errno = errno; struct flock lk; switch(l->type) { case LXC_LOCK_ANON_SEM: if (!l->u.sem) ret = -2; else { ret = sem_post(l->u.sem); saved_errno = errno; } break; case LXC_LOCK_FLOCK: if (l->u.f.fd != -1) { lk.l_type = F_UNLCK; lk.l_whence = SEEK_SET; lk.l_start = 0; lk.l_len = 0; ret = fcntl(l->u.f.fd, F_SETLK, &lk); if (ret < 0) saved_errno = errno; close(l->u.f.fd); l->u.f.fd = -1; } else ret = -2; break; } errno = saved_errno; return ret; } /* * lxc_putlock() is only called when a container_new() fails, * or during container_put(), which is already guaranteed to * only be done by one task. * So the only exclusion we need to provide here is for regular * thread safety (i.e. file descriptor table changes). */ void lxc_putlock(struct lxc_lock *l) { if (!l) return; switch(l->type) { case LXC_LOCK_ANON_SEM: if (l->u.sem) { sem_destroy(l->u.sem); free(l->u.sem); l->u.sem = NULL; } break; case LXC_LOCK_FLOCK: if (l->u.f.fd != -1) { close(l->u.f.fd); l->u.f.fd = -1; } free(l->u.f.fname); l->u.f.fname = NULL; break; } free(l); } void process_lock(void) { lock_mutex(&thread_mutex); } void process_unlock(void) { unlock_mutex(&thread_mutex); } /* One thread can do fork() while another one is holding a mutex. * There is only one thread in child just after the fork(), so no one will ever release that mutex. * We setup a "child" fork handler to unlock the mutex just after the fork(). * For several mutex types, unlocking an unlocked mutex can lead to undefined behavior. * One way to deal with it is to setup "prepare" fork handler * to lock the mutex before fork() and both "parent" and "child" fork handlers * to unlock the mutex. * This forbids doing fork() while explicitly holding the lock. */ #ifdef HAVE_PTHREAD_ATFORK __attribute__((constructor)) static void process_lock_setup_atfork(void) { pthread_atfork(process_lock, process_unlock, process_unlock); } #endif int container_mem_lock(struct lxc_container *c) { return lxclock(c->privlock, 0); } void container_mem_unlock(struct lxc_container *c) { lxcunlock(c->privlock); } int container_disk_lock(struct lxc_container *c) { int ret; if ((ret = lxclock(c->privlock, 0))) return ret; if ((ret = lxclock(c->slock, 0))) { lxcunlock(c->privlock); return ret; } return 0; } void container_disk_unlock(struct lxc_container *c) { lxcunlock(c->slock); lxcunlock(c->privlock); }
./CrossVul/dataset_final_sorted/CWE-59/c/good_1468_0
crossvul-cpp_data_bad_3271_0
/** \ingroup rpmcli * \file lib/verify.c * Verify installed payload files from package metadata. */ #include "system.h" #include <errno.h> #if WITH_CAP #include <sys/capability.h> #endif #if WITH_ACL #include <acl/libacl.h> #endif #include <rpm/rpmcli.h> #include <rpm/header.h> #include <rpm/rpmlog.h> #include <rpm/rpmfi.h> #include <rpm/rpmts.h> #include <rpm/rpmdb.h> #include <rpm/rpmfileutil.h> #include "lib/misc.h" #include "lib/rpmchroot.h" #include "lib/rpmte_internal.h" /* rpmteProcess() */ #include "lib/rpmug.h" #include "debug.h" #define S_ISDEV(m) (S_ISBLK((m)) || S_ISCHR((m))) /* If cap_compare() (Linux extension) not available, do it the hard way */ #if WITH_CAP && !defined(HAVE_CAP_COMPARE) static int cap_compare(cap_t acap, cap_t bcap) { int rc = 0; size_t asize = cap_size(acap); size_t bsize = cap_size(bcap); if (asize != bsize) { rc = 1; } else { char *abuf = xcalloc(asize, sizeof(*abuf)); char *bbuf = xcalloc(bsize, sizeof(*bbuf)); cap_copy_ext(abuf, acap, asize); cap_copy_ext(bbuf, bcap, bsize); rc = memcmp(abuf, bbuf, asize); free(abuf); free(bbuf); } return rc; } #endif rpmVerifyAttrs rpmfilesVerify(rpmfiles fi, int ix, rpmVerifyAttrs omitMask) { rpm_mode_t fmode = rpmfilesFMode(fi, ix); rpmfileAttrs fileAttrs = rpmfilesFFlags(fi, ix); rpmVerifyAttrs flags = rpmfilesVFlags(fi, ix); const char * fn = rpmfilesFN(fi, ix); struct stat sb; rpmVerifyAttrs vfy = RPMVERIFY_NONE; /* * Check to see if the file was installed - if not pretend all is OK. */ switch (rpmfilesFState(fi, ix)) { case RPMFILE_STATE_NETSHARED: case RPMFILE_STATE_NOTINSTALLED: goto exit; break; case RPMFILE_STATE_REPLACED: /* For replaced files we can only verify if it exists at all */ flags = RPMVERIFY_LSTATFAIL; break; case RPMFILE_STATE_WRONGCOLOR: /* * Files with wrong color are supposed to share some attributes * with the actually installed file - verify what we can. */ flags &= ~(RPMVERIFY_FILEDIGEST | RPMVERIFY_FILESIZE | RPMVERIFY_MTIME | RPMVERIFY_RDEV); break; case RPMFILE_STATE_NORMAL: /* File from a non-installed package, try to verify nevertheless */ case RPMFILE_STATE_MISSING: break; } if (fn == NULL || lstat(fn, &sb) != 0) { vfy |= RPMVERIFY_LSTATFAIL; goto exit; } /* If we expected a directory but got a symlink to one, follow the link */ if (S_ISDIR(fmode) && S_ISLNK(sb.st_mode) && stat(fn, &sb) != 0) { vfy |= RPMVERIFY_LSTATFAIL; goto exit; } /* Links have no mode, other types have no linkto */ if (S_ISLNK(sb.st_mode)) flags &= ~(RPMVERIFY_MODE); else flags &= ~(RPMVERIFY_LINKTO); /* Not all attributes of non-regular files can be verified */ if (!S_ISREG(sb.st_mode)) flags &= ~(RPMVERIFY_FILEDIGEST | RPMVERIFY_FILESIZE | RPMVERIFY_MTIME | RPMVERIFY_CAPS); /* Content checks of %ghost files are meaningless. */ if (fileAttrs & RPMFILE_GHOST) flags &= ~(RPMVERIFY_FILEDIGEST | RPMVERIFY_FILESIZE | RPMVERIFY_MTIME | RPMVERIFY_LINKTO); /* Don't verify any features in omitMask. */ flags &= ~(omitMask | RPMVERIFY_FAILURES); if (flags & RPMVERIFY_FILEDIGEST) { const unsigned char *digest; int algo; size_t diglen; /* XXX If --nomd5, then prelinked library sizes are not corrected. */ if ((digest = rpmfilesFDigest(fi, ix, &algo, &diglen))) { unsigned char fdigest[diglen]; rpm_loff_t fsize; if (rpmDoDigest(algo, fn, 0, fdigest, &fsize)) { vfy |= (RPMVERIFY_READFAIL|RPMVERIFY_FILEDIGEST); } else { sb.st_size = fsize; if (memcmp(fdigest, digest, diglen)) vfy |= RPMVERIFY_FILEDIGEST; } } else { vfy |= RPMVERIFY_FILEDIGEST; } } if (flags & RPMVERIFY_LINKTO) { char linkto[1024+1]; int size = 0; if ((size = readlink(fn, linkto, sizeof(linkto)-1)) == -1) vfy |= (RPMVERIFY_READLINKFAIL|RPMVERIFY_LINKTO); else { const char * flink = rpmfilesFLink(fi, ix); linkto[size] = '\0'; if (flink == NULL || !rstreq(linkto, flink)) vfy |= RPMVERIFY_LINKTO; } } if (flags & RPMVERIFY_FILESIZE) { if (sb.st_size != rpmfilesFSize(fi, ix)) vfy |= RPMVERIFY_FILESIZE; } if (flags & RPMVERIFY_MODE) { rpm_mode_t metamode = fmode; rpm_mode_t filemode; /* * Platforms (like AIX) where sizeof(rpm_mode_t) != sizeof(mode_t) * need the (rpm_mode_t) cast here. */ filemode = (rpm_mode_t)sb.st_mode; /* * Comparing the type of %ghost files is meaningless, but perms are OK. */ if (fileAttrs & RPMFILE_GHOST) { metamode &= ~0xf000; filemode &= ~0xf000; } if (metamode != filemode) vfy |= RPMVERIFY_MODE; #if WITH_ACL /* * For now, any non-default acl's on a file is a difference as rpm * cannot have set them. */ acl_t facl = acl_get_file(fn, ACL_TYPE_ACCESS); if (facl) { if (acl_equiv_mode(facl, NULL) == 1) { vfy |= RPMVERIFY_MODE; } acl_free(facl); } #endif } if (flags & RPMVERIFY_RDEV) { if (S_ISCHR(fmode) != S_ISCHR(sb.st_mode) || S_ISBLK(fmode) != S_ISBLK(sb.st_mode)) { vfy |= RPMVERIFY_RDEV; } else if (S_ISDEV(fmode) && S_ISDEV(sb.st_mode)) { rpm_rdev_t st_rdev = (sb.st_rdev & 0xffff); rpm_rdev_t frdev = (rpmfilesFRdev(fi, ix) & 0xffff); if (st_rdev != frdev) vfy |= RPMVERIFY_RDEV; } } #if WITH_CAP if (flags & RPMVERIFY_CAPS) { /* * Empty capability set ("=") is not exactly the same as no * capabilities at all but suffices for now... */ cap_t cap, fcap; cap = cap_from_text(rpmfilesFCaps(fi, ix)); if (!cap) { cap = cap_from_text("="); } fcap = cap_get_file(fn); if (!fcap) { fcap = cap_from_text("="); } if (cap_compare(cap, fcap) != 0) vfy |= RPMVERIFY_CAPS; cap_free(fcap); cap_free(cap); } #endif if ((flags & RPMVERIFY_MTIME) && (sb.st_mtime != rpmfilesFMtime(fi, ix))) { vfy |= RPMVERIFY_MTIME; } if (flags & RPMVERIFY_USER) { const char * name = rpmugUname(sb.st_uid); const char * fuser = rpmfilesFUser(fi, ix); uid_t uid; int namematch = 0; int idmatch = 0; if (name && fuser) namematch = rstreq(name, fuser); if (fuser && rpmugUid(fuser, &uid) == 0) idmatch = (uid == sb.st_uid); if (namematch != idmatch) { rpmlog(RPMLOG_WARNING, _("Duplicate username or UID for user %s\n"), fuser); } if (!(namematch || idmatch)) vfy |= RPMVERIFY_USER; } if (flags & RPMVERIFY_GROUP) { const char * name = rpmugGname(sb.st_gid); const char * fgroup = rpmfilesFGroup(fi, ix); gid_t gid; int namematch = 0; int idmatch = 0; if (name && fgroup) namematch = rstreq(name, fgroup); if (fgroup && rpmugGid(fgroup, &gid) == 0) idmatch = (gid == sb.st_gid); if (namematch != idmatch) { rpmlog(RPMLOG_WARNING, _("Duplicate groupname or GID for group %s\n"), fgroup); } if (!(namematch || idmatch)) vfy |= RPMVERIFY_GROUP; } exit: return vfy; } int rpmVerifyFile(const rpmts ts, const rpmfi fi, rpmVerifyAttrs * res, rpmVerifyAttrs omitMask) { rpmVerifyAttrs vfy = rpmfiVerify(fi, omitMask); if (res) *res = vfy; return (vfy & RPMVERIFY_LSTATFAIL) ? 1 : 0; } /** * Return exit code from running verify script from header. * @param ts transaction set * @param h header * @return 0 on success */ static int rpmVerifyScript(rpmts ts, Header h) { int rc = 0; if (headerIsEntry(h, RPMTAG_VERIFYSCRIPT)) { /* fake up a erasure transaction element */ rpmte p = rpmteNew(ts, h, TR_REMOVED, NULL, NULL); if (p != NULL) { rpmteSetHeader(p, h); rc = (rpmpsmRun(ts, p, PKG_VERIFY) != RPMRC_OK); /* clean up our fake transaction bits */ rpmteFree(p); } else { rc = RPMRC_FAIL; } } return rc; } #define unknown "?" #define _verify(_RPMVERIFY_F, _C, _pad) \ ((verifyResult & _RPMVERIFY_F) ? _C : _pad) #define _verifylink(_RPMVERIFY_F, _C, _pad) \ ((verifyResult & RPMVERIFY_READLINKFAIL) ? unknown : \ (verifyResult & _RPMVERIFY_F) ? _C : _pad) #define _verifyfile(_RPMVERIFY_F, _C, _pad) \ ((verifyResult & RPMVERIFY_READFAIL) ? unknown : \ (verifyResult & _RPMVERIFY_F) ? _C : _pad) char * rpmVerifyString(uint32_t verifyResult, const char *pad) { char *fmt = NULL; rasprintf(&fmt, "%s%s%s%s%s%s%s%s%s", _verify(RPMVERIFY_FILESIZE, "S", pad), _verify(RPMVERIFY_MODE, "M", pad), _verifyfile(RPMVERIFY_FILEDIGEST, "5", pad), _verify(RPMVERIFY_RDEV, "D", pad), _verifylink(RPMVERIFY_LINKTO, "L", pad), _verify(RPMVERIFY_USER, "U", pad), _verify(RPMVERIFY_GROUP, "G", pad), _verify(RPMVERIFY_MTIME, "T", pad), _verify(RPMVERIFY_CAPS, "P", pad)); return fmt; } #undef _verifyfile #undef _verifylink #undef _verify #undef aok #undef unknown char * rpmFFlagsString(uint32_t fflags, const char *pad) { char *fmt = NULL; rasprintf(&fmt, "%s%s%s%s%s%s%s%s", (fflags & RPMFILE_DOC) ? "d" : pad, (fflags & RPMFILE_CONFIG) ? "c" : pad, (fflags & RPMFILE_SPECFILE) ? "s" : pad, (fflags & RPMFILE_MISSINGOK) ? "m" : pad, (fflags & RPMFILE_NOREPLACE) ? "n" : pad, (fflags & RPMFILE_GHOST) ? "g" : pad, (fflags & RPMFILE_LICENSE) ? "l" : pad, (fflags & RPMFILE_README) ? "r" : pad); return fmt; } static const char * stateStr(rpmfileState fstate) { switch (fstate) { case RPMFILE_STATE_NORMAL: return NULL; case RPMFILE_STATE_NOTINSTALLED: return rpmIsVerbose() ? _("not installed") : NULL; case RPMFILE_STATE_NETSHARED: return rpmIsVerbose() ? _("net shared") : NULL; case RPMFILE_STATE_WRONGCOLOR: return rpmIsVerbose() ? _("wrong color") : NULL; case RPMFILE_STATE_REPLACED: return _("replaced"); case RPMFILE_STATE_MISSING: return _("no state"); } return _("unknown state"); } /** * Check file info from header against what's actually installed. * @param ts transaction set * @param h header to verify * @param omitMask bits to disable verify checks * @param skipAttr skip files with these attrs (eg %ghost) * @return 0 no problems, 1 problems found */ static int verifyHeader(rpmts ts, Header h, rpmVerifyAttrs omitMask, rpmfileAttrs skipAttrs) { rpmVerifyAttrs verifyResult = 0; rpmVerifyAttrs verifyAll = 0; /* assume no problems */ rpmfi fi = rpmfiNew(ts, h, RPMTAG_BASENAMES, RPMFI_FLAGS_VERIFY); if (fi == NULL) return 1; rpmfiInit(fi, 0); while (rpmfiNext(fi) >= 0) { rpmfileAttrs fileAttrs = rpmfiFFlags(fi); char *buf = NULL, *attrFormat; const char *fstate = NULL; char ac; /* Skip on attributes (eg from --noghost) */ if (skipAttrs & fileAttrs) continue; verifyResult = rpmfiVerify(fi, omitMask); /* Filter out timestamp differences of shared files */ if (verifyResult & RPMVERIFY_MTIME) { rpmdbMatchIterator mi; mi = rpmtsInitIterator(ts, RPMDBI_BASENAMES, rpmfiFN(fi), 0); if (rpmdbGetIteratorCount(mi) > 1) verifyResult &= ~RPMVERIFY_MTIME; rpmdbFreeIterator(mi); } /* State is only meaningful for installed packages */ if (headerGetInstance(h)) fstate = stateStr(rpmfiFState(fi)); attrFormat = rpmFFlagsString(fileAttrs, ""); ac = rstreq(attrFormat, "") ? ' ' : attrFormat[0]; if (verifyResult & RPMVERIFY_LSTATFAIL) { if (!(fileAttrs & (RPMFILE_MISSINGOK|RPMFILE_GHOST)) || rpmIsVerbose()) { rasprintf(&buf, _("missing %c %s"), ac, rpmfiFN(fi)); if ((verifyResult & RPMVERIFY_LSTATFAIL) != 0 && errno != ENOENT) { char *app; rasprintf(&app, " (%s)", strerror(errno)); rstrcat(&buf, app); free(app); } } } else if (verifyResult || fstate || rpmIsVerbose()) { char *verifyFormat = rpmVerifyString(verifyResult, "."); rasprintf(&buf, "%s %c %s", verifyFormat, ac, rpmfiFN(fi)); free(verifyFormat); } free(attrFormat); if (buf) { if (fstate) buf = rstrscat(&buf, " (", fstate, ")", NULL); rpmlog(RPMLOG_NOTICE, "%s\n", buf); buf = _free(buf); } verifyAll |= verifyResult; } rpmfiFree(fi); return (verifyAll != 0) ? 1 : 0; } /** * Check installed package dependencies for problems. * @param ts transaction set * @param h header * @return number of problems found (0 for no problems) */ static int verifyDependencies(rpmts ts, Header h) { rpmps ps; rpmte te; int rc; rpmtsEmpty(ts); (void) rpmtsAddInstallElement(ts, h, NULL, 0, NULL); (void) rpmtsCheck(ts); te = rpmtsElement(ts, 0); ps = rpmteProblems(te); rc = rpmpsNumProblems(ps); if (rc > 0) { rpmlog(RPMLOG_NOTICE, _("Unsatisfied dependencies for %s:\n"), rpmteNEVRA(te)); rpmpsi psi = rpmpsInitIterator(ps); rpmProblem p; while ((p = rpmpsiNext(psi)) != NULL) { char * ps = rpmProblemString(p); rpmlog(RPMLOG_NOTICE, "\t%s\n", ps); free(ps); } rpmpsFreeIterator(psi); } rpmpsFree(ps); rpmtsEmpty(ts); return rc; } int showVerifyPackage(QVA_t qva, rpmts ts, Header h) { rpmVerifyAttrs omitMask = ((qva->qva_flags & VERIFY_ATTRS) ^ VERIFY_ATTRS); int ec = 0; int rc; if (qva->qva_flags & VERIFY_DEPS) { if ((rc = verifyDependencies(ts, h)) != 0) ec = rc; } if (qva->qva_flags & VERIFY_FILES) { if ((rc = verifyHeader(ts, h, omitMask, qva->qva_fflags)) != 0) ec = rc; } if (qva->qva_flags & VERIFY_SCRIPT) { if ((rc = rpmVerifyScript(ts, h)) != 0) ec = rc; } return ec; } int rpmcliVerify(rpmts ts, QVA_t qva, char * const * argv) { rpmVSFlags vsflags, ovsflags; int ec = 0; FD_t scriptFd = fdDup(STDOUT_FILENO); /* * Open the DB + indices explicitly before possible chroot, * otherwises BDB is going to be unhappy... */ rpmtsOpenDB(ts, O_RDONLY); rpmdbOpenAll(rpmtsGetRdb(ts)); if (rpmChrootSet(rpmtsRootDir(ts)) || rpmChrootIn()) { ec = 1; goto exit; } if (qva->qva_showPackage == NULL) qva->qva_showPackage = showVerifyPackage; vsflags = rpmExpandNumeric("%{?_vsflags_verify}"); if (rpmcliQueryFlags & VERIFY_DIGEST) vsflags |= _RPMVSF_NODIGESTS; if (rpmcliQueryFlags & VERIFY_SIGNATURE) vsflags |= _RPMVSF_NOSIGNATURES; if (rpmcliQueryFlags & VERIFY_HDRCHK) vsflags |= RPMVSF_NOHDRCHK; vsflags &= ~RPMVSF_NEEDPAYLOAD; rpmtsSetScriptFd(ts, scriptFd); ovsflags = rpmtsSetVSFlags(ts, vsflags); ec = rpmcliArgIter(ts, qva, argv); rpmtsSetVSFlags(ts, ovsflags); rpmtsSetScriptFd(ts, NULL); if (qva->qva_showPackage == showVerifyPackage) qva->qva_showPackage = NULL; rpmtsEmpty(ts); if (rpmChrootOut() || rpmChrootSet(NULL)) ec = 1; exit: Fclose(scriptFd); return ec; }
./CrossVul/dataset_final_sorted/CWE-59/c/bad_3271_0
crossvul-cpp_data_bad_1670_1
/* Copyright (C) 2011 ABRT Team Copyright (C) 2011 RedHat inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "libabrt.h" #define EXECUTABLE "abrt-action-install-debuginfo" #define IGNORE_RESULT(func_call) do { if (func_call) /* nothing */; } while (0) /* A binary wrapper is needed around python scripts if we want * to run them in sgid/suid mode. * * This is such a wrapper. */ int main(int argc, char **argv) { /* I18n */ setlocale(LC_ALL, ""); #if ENABLE_NLS bindtextdomain(PACKAGE, LOCALEDIR); textdomain(PACKAGE); #endif abrt_init(argv); /* Can't keep these strings/structs static: _() doesn't support that */ const char *program_usage_string = _( "& [-y] [-i BUILD_IDS_FILE|-i -] [-e PATH[:PATH]...]\n" "\t[-r REPO]\n" "\n" "Installs debuginfo packages for all build-ids listed in BUILD_IDS_FILE to\n" "ABRT system cache." ); enum { OPT_v = 1 << 0, OPT_y = 1 << 1, OPT_i = 1 << 2, OPT_e = 1 << 3, OPT_r = 1 << 4, OPT_s = 1 << 5, }; const char *build_ids = "build_ids"; const char *exact = NULL; const char *repo = NULL; const char *size_mb = NULL; struct options program_options[] = { OPT__VERBOSE(&g_verbose), OPT_BOOL ('y', "yes", NULL, _("Noninteractive, assume 'Yes' to all questions")), OPT_STRING('i', "ids", &build_ids, "BUILD_IDS_FILE", _("- means STDIN, default: build_ids")), OPT_STRING('e', "exact", &exact, "EXACT", _("Download only specified files")), OPT_STRING('r', "repo", &repo, "REPO", _("Pattern to use when searching for repos, default: *debug*")), OPT_STRING('s', "size_mb", &size_mb, "SIZE_MB", _("Ignored option")), OPT_END() }; const unsigned opts = parse_opts(argc, argv, program_options, program_usage_string); const gid_t egid = getegid(); const gid_t rgid = getgid(); const uid_t euid = geteuid(); const gid_t ruid = getuid(); /* We need to open the build ids file under the caller's UID/GID to avoid * information disclosures when reading files with changed UID. * Unfortunately, we cannot replace STDIN with the new fd because ABRT uses * STDIN to communicate with the caller. So, the following code opens a * dummy file descriptor to the build ids file and passes the new fd's proc * path to the wrapped program in the ids argument. * The new fd remains opened, the OS will close it for us. */ char *build_ids_self_fd = NULL; if (strcmp("-", build_ids) != 0) { if (setregid(egid, rgid) < 0) perror_msg_and_die("setregid(egid, rgid)"); if (setreuid(euid, ruid) < 0) perror_msg_and_die("setreuid(euid, ruid)"); const int build_ids_fd = open(build_ids, O_RDONLY); if (setregid(rgid, egid) < 0) perror_msg_and_die("setregid(rgid, egid)"); if (setreuid(ruid, euid) < 0 ) perror_msg_and_die("setreuid(ruid, euid)"); if (build_ids_fd < 0) perror_msg_and_die("Failed to open file '%s'", build_ids); /* We are not going to free this memory. There is no place to do so. */ build_ids_self_fd = xasprintf("/proc/self/fd/%d", build_ids_fd); } /* name, -v, --ids, -, -y, -e, EXACT, -r, REPO, --, NULL */ const char *args[11]; { const char *verbs[] = { "", "-v", "-vv", "-vvv" }; unsigned i = 0; args[i++] = EXECUTABLE; args[i++] = "--ids"; args[i++] = (build_ids_self_fd != NULL) ? build_ids_self_fd : "-"; if (g_verbose > 0) args[i++] = verbs[g_verbose <= 3 ? g_verbose : 3]; if ((opts & OPT_y)) args[i++] = "-y"; if ((opts & OPT_e)) { args[i++] = "--exact"; args[i++] = exact; } if ((opts & OPT_r)) { args[i++] = "--repo"; args[i++] = repo; } args[i++] = "--"; args[i] = NULL; } /* Switch real user/group to effective ones. * Otherwise yum library gets confused - gets EPERM (why??). */ /* do setregid only if we have to, to not upset selinux needlessly */ if (egid != rgid) IGNORE_RESULT(setregid(egid, egid)); if (euid != ruid) { IGNORE_RESULT(setreuid(euid, euid)); /* We are suid'ed! */ /* Prevent malicious user from messing up with suid'ed process: */ #if 1 // We forgot to sanitize PYTHONPATH. And who knows what else we forgot // (especially considering *future* new variables of this kind). // We switched to clearing entire environment instead: // However since we communicate through environment variables // we have to keep a whitelist of variables to keep. static const char *whitelist[] = { "REPORT_CLIENT_SLAVE", // Check if the app is being run as a slave "LANG", }; const size_t wlsize = sizeof(whitelist)/sizeof(char*); char *setlist[sizeof(whitelist)/sizeof(char*)] = { 0 }; char *p = NULL; for (size_t i = 0; i < wlsize; i++) if ((p = getenv(whitelist[i])) != NULL) setlist[i] = xstrdup(p); // Now we can clear the environment clearenv(); // And once again set whitelisted variables for (size_t i = 0; i < wlsize; i++) if (setlist[i] != NULL) { xsetenv(whitelist[i], setlist[i]); free(setlist[i]); } #else /* Clear dangerous stuff from env */ static const char forbid[] = "LD_LIBRARY_PATH" "\0" "LD_PRELOAD" "\0" "LD_TRACE_LOADED_OBJECTS" "\0" "LD_BIND_NOW" "\0" "LD_AOUT_LIBRARY_PATH" "\0" "LD_AOUT_PRELOAD" "\0" "LD_NOWARN" "\0" "LD_KEEPDIR" "\0" ; const char *p = forbid; do { unsetenv(p); p += strlen(p) + 1; } while (*p); #endif /* Set safe PATH */ // Adding configure --bindir and --sbindir to the PATH so that // abrt-action-install-debuginfo doesn't fail when spawning // abrt-action-trim-files char path_env[] = "PATH=/usr/sbin:/sbin:/usr/bin:/bin:"BIN_DIR":"SBIN_DIR; if (euid != 0) strcpy(path_env, "PATH=/usr/bin:/bin:"BIN_DIR); putenv(path_env); /* Use safe umask */ umask(0022); } execvp(EXECUTABLE, (char **)args); error_msg_and_die("Can't execute %s", EXECUTABLE); }
./CrossVul/dataset_final_sorted/CWE-59/c/bad_1670_1
crossvul-cpp_data_good_1471_1
/* * lxc: linux Container library * * (C) Copyright IBM Corp. 2007, 2008 * * Authors: * Daniel Lezcano <daniel.lezcano at free.fr> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "config.h" #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <unistd.h> #include <string.h> #include <dirent.h> #include <fcntl.h> #include <ctype.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/param.h> #include <sys/inotify.h> #include <sys/mount.h> #include <netinet/in.h> #include <net/if.h> #include "error.h" #include "commands.h" #include "list.h" #include "conf.h" #include "utils.h" #include "bdev.h" #include "log.h" #include "cgroup.h" #include "start.h" #include "state.h" #if IS_BIONIC #include <../include/lxcmntent.h> #else #include <mntent.h> #endif struct cgroup_hierarchy; struct cgroup_meta_data; struct cgroup_mount_point; /* * cgroup_meta_data: the metadata about the cgroup infrastructure on this * host */ struct cgroup_meta_data { ptrdiff_t ref; /* simple refcount */ struct cgroup_hierarchy **hierarchies; struct cgroup_mount_point **mount_points; int maximum_hierarchy; }; /* * cgroup_hierarchy: describes a single cgroup hierarchy * (may have multiple mount points) */ struct cgroup_hierarchy { int index; bool used; /* false if the hierarchy should be ignored by lxc */ char **subsystems; struct cgroup_mount_point *rw_absolute_mount_point; struct cgroup_mount_point *ro_absolute_mount_point; struct cgroup_mount_point **all_mount_points; size_t all_mount_point_capacity; }; /* * cgroup_mount_point: a mount point to where a hierarchy * is mounted to */ struct cgroup_mount_point { struct cgroup_hierarchy *hierarchy; char *mount_point; char *mount_prefix; bool read_only; bool need_cpuset_init; }; /* * cgroup_process_info: describes the membership of a * process to the different cgroup * hierarchies * * Note this is the per-process info tracked by the cgfs_ops. * This is not used with cgmanager. */ struct cgroup_process_info { struct cgroup_process_info *next; struct cgroup_meta_data *meta_ref; struct cgroup_hierarchy *hierarchy; char *cgroup_path; char *cgroup_path_sub; char **created_paths; size_t created_paths_capacity; size_t created_paths_count; struct cgroup_mount_point *designated_mount_point; }; struct cgfs_data { char *name; const char *cgroup_pattern; struct cgroup_meta_data *meta; struct cgroup_process_info *info; }; lxc_log_define(lxc_cgfs, lxc); static struct cgroup_process_info *lxc_cgroup_process_info_getx(const char *proc_pid_cgroup_str, struct cgroup_meta_data *meta); static char **subsystems_from_mount_options(const char *mount_options, char **kernel_list); static void lxc_cgroup_mount_point_free(struct cgroup_mount_point *mp); static void lxc_cgroup_hierarchy_free(struct cgroup_hierarchy *h); static bool is_valid_cgroup(const char *name); static int create_cgroup(struct cgroup_mount_point *mp, const char *path); static int remove_cgroup(struct cgroup_mount_point *mp, const char *path, bool recurse); static char *cgroup_to_absolute_path(struct cgroup_mount_point *mp, const char *path, const char *suffix); static struct cgroup_process_info *find_info_for_subsystem(struct cgroup_process_info *info, const char *subsystem); static int do_cgroup_get(const char *cgroup_path, const char *sub_filename, char *value, size_t len); static int do_cgroup_set(const char *cgroup_path, const char *sub_filename, const char *value); static bool cgroup_devices_has_allow_or_deny(struct cgfs_data *d, char *v, bool for_allow); static int do_setup_cgroup_limits(struct cgfs_data *d, struct lxc_list *cgroup_settings, bool do_devices); static int cgroup_recursive_task_count(const char *cgroup_path); static int count_lines(const char *fn); static int handle_cgroup_settings(struct cgroup_mount_point *mp, char *cgroup_path); static bool init_cpuset_if_needed(struct cgroup_mount_point *mp, const char *path); static struct cgroup_meta_data *lxc_cgroup_load_meta2(const char **subsystem_whitelist); static struct cgroup_meta_data *lxc_cgroup_get_meta(struct cgroup_meta_data *meta_data); static struct cgroup_meta_data *lxc_cgroup_put_meta(struct cgroup_meta_data *meta_data); /* free process membership information */ static void lxc_cgroup_process_info_free(struct cgroup_process_info *info); static void lxc_cgroup_process_info_free_and_remove(struct cgroup_process_info *info); static struct cgroup_ops cgfs_ops; static int cgroup_rmdir(char *dirname) { struct dirent dirent, *direntp; int saved_errno = 0; DIR *dir; int ret, failed=0; char pathname[MAXPATHLEN]; dir = opendir(dirname); if (!dir) { ERROR("%s: failed to open %s", __func__, dirname); return -1; } while (!readdir_r(dir, &dirent, &direntp)) { struct stat mystat; int rc; if (!direntp) break; if (!strcmp(direntp->d_name, ".") || !strcmp(direntp->d_name, "..")) continue; rc = snprintf(pathname, MAXPATHLEN, "%s/%s", dirname, direntp->d_name); if (rc < 0 || rc >= MAXPATHLEN) { ERROR("pathname too long"); failed=1; if (!saved_errno) saved_errno = -ENOMEM; continue; } ret = lstat(pathname, &mystat); if (ret) { SYSERROR("%s: failed to stat %s", __func__, pathname); failed=1; if (!saved_errno) saved_errno = errno; continue; } if (S_ISDIR(mystat.st_mode)) { if (cgroup_rmdir(pathname) < 0) { if (!saved_errno) saved_errno = errno; failed=1; } } } if (rmdir(dirname) < 0) { SYSERROR("%s: failed to delete %s", __func__, dirname); if (!saved_errno) saved_errno = errno; failed=1; } ret = closedir(dir); if (ret) { SYSERROR("%s: failed to close directory %s", __func__, dirname); if (!saved_errno) saved_errno = errno; failed=1; } errno = saved_errno; return failed ? -1 : 0; } static struct cgroup_meta_data *lxc_cgroup_load_meta() { const char *cgroup_use = NULL; char **cgroup_use_list = NULL; struct cgroup_meta_data *md = NULL; int saved_errno; errno = 0; cgroup_use = lxc_global_config_value("lxc.cgroup.use"); if (!cgroup_use && errno != 0) return NULL; if (cgroup_use) { cgroup_use_list = lxc_string_split_and_trim(cgroup_use, ','); if (!cgroup_use_list) return NULL; } md = lxc_cgroup_load_meta2((const char **)cgroup_use_list); saved_errno = errno; lxc_free_array((void **)cgroup_use_list, free); errno = saved_errno; return md; } /* Step 1: determine all kernel subsystems */ static bool find_cgroup_subsystems(char ***kernel_subsystems) { FILE *proc_cgroups; bool bret = false; char *line = NULL; size_t sz = 0; size_t kernel_subsystems_count = 0; size_t kernel_subsystems_capacity = 0; int r; proc_cgroups = fopen_cloexec("/proc/cgroups", "r"); if (!proc_cgroups) return false; while (getline(&line, &sz, proc_cgroups) != -1) { char *tab1; char *tab2; int hierarchy_number; if (line[0] == '#') continue; if (!line[0]) continue; tab1 = strchr(line, '\t'); if (!tab1) continue; *tab1++ = '\0'; tab2 = strchr(tab1, '\t'); if (!tab2) continue; *tab2 = '\0'; tab2 = NULL; hierarchy_number = strtoul(tab1, &tab2, 10); if (!tab2 || *tab2) continue; (void)hierarchy_number; r = lxc_grow_array((void ***)kernel_subsystems, &kernel_subsystems_capacity, kernel_subsystems_count + 1, 12); if (r < 0) goto out; (*kernel_subsystems)[kernel_subsystems_count] = strdup(line); if (!(*kernel_subsystems)[kernel_subsystems_count]) goto out; kernel_subsystems_count++; } bret = true; out: fclose(proc_cgroups); free(line); return bret; } /* Step 2: determine all hierarchies (by reading /proc/self/cgroup), * since mount points don't specify hierarchy number and * /proc/cgroups does not contain named hierarchies */ static bool find_cgroup_hierarchies(struct cgroup_meta_data *meta_data, bool all_kernel_subsystems, bool all_named_subsystems, const char **subsystem_whitelist) { FILE *proc_self_cgroup; char *line = NULL; size_t sz = 0; int r; bool bret = false; size_t hierarchy_capacity = 0; proc_self_cgroup = fopen_cloexec("/proc/self/cgroup", "r"); /* if for some reason (because of setns() and pid namespace for example), * /proc/self is not valid, we try /proc/1/cgroup... */ if (!proc_self_cgroup) proc_self_cgroup = fopen_cloexec("/proc/1/cgroup", "r"); if (!proc_self_cgroup) return false; while (getline(&line, &sz, proc_self_cgroup) != -1) { /* file format: hierarchy:subsystems:group, * we only extract hierarchy and subsystems * here */ char *colon1; char *colon2; int hierarchy_number; struct cgroup_hierarchy *h = NULL; char **p; if (!line[0]) continue; colon1 = strchr(line, ':'); if (!colon1) continue; *colon1++ = '\0'; colon2 = strchr(colon1, ':'); if (!colon2) continue; *colon2 = '\0'; colon2 = NULL; hierarchy_number = strtoul(line, &colon2, 10); if (!colon2 || *colon2) continue; if (hierarchy_number > meta_data->maximum_hierarchy) { /* lxc_grow_array will never shrink, so even if we find a lower * hierarchy number here, the array will never be smaller */ r = lxc_grow_array((void ***)&meta_data->hierarchies, &hierarchy_capacity, hierarchy_number + 1, 12); if (r < 0) goto out; meta_data->maximum_hierarchy = hierarchy_number; } /* this shouldn't happen, we had this already */ if (meta_data->hierarchies[hierarchy_number]) goto out; h = calloc(1, sizeof(struct cgroup_hierarchy)); if (!h) goto out; meta_data->hierarchies[hierarchy_number] = h; h->index = hierarchy_number; h->subsystems = lxc_string_split_and_trim(colon1, ','); if (!h->subsystems) goto out; /* see if this hierarchy should be considered */ if (!all_kernel_subsystems || !all_named_subsystems) { for (p = h->subsystems; *p; p++) { if (!strncmp(*p, "name=", 5)) { if (all_named_subsystems || (subsystem_whitelist && lxc_string_in_array(*p, subsystem_whitelist))) { h->used = true; break; } } else { if (all_kernel_subsystems || (subsystem_whitelist && lxc_string_in_array(*p, subsystem_whitelist))) { h->used = true; break; } } } } else { /* we want all hierarchy anyway */ h->used = true; } } bret = true; out: fclose(proc_self_cgroup); free(line); return bret; } /* Step 3: determine all mount points of each hierarchy */ static bool find_hierarchy_mountpts( struct cgroup_meta_data *meta_data, char **kernel_subsystems) { bool bret = false; FILE *proc_self_mountinfo; char *line = NULL; size_t sz = 0; char **tokens = NULL; size_t mount_point_count = 0; size_t mount_point_capacity = 0; size_t token_capacity = 0; int r; proc_self_mountinfo = fopen_cloexec("/proc/self/mountinfo", "r"); /* if for some reason (because of setns() and pid namespace for example), * /proc/self is not valid, we try /proc/1/cgroup... */ if (!proc_self_mountinfo) proc_self_mountinfo = fopen_cloexec("/proc/1/mountinfo", "r"); if (!proc_self_mountinfo) return false; while (getline(&line, &sz, proc_self_mountinfo) != -1) { char *token, *line_tok, *saveptr = NULL; size_t i, j, k; struct cgroup_mount_point *mount_point; struct cgroup_hierarchy *h; char **subsystems; if (line[0] && line[strlen(line) - 1] == '\n') line[strlen(line) - 1] = '\0'; for (i = 0, line_tok = line; (token = strtok_r(line_tok, " ", &saveptr)); line_tok = NULL) { r = lxc_grow_array((void ***)&tokens, &token_capacity, i + 1, 64); if (r < 0) goto out; tokens[i++] = token; } /* layout of /proc/self/mountinfo: * 0: id * 1: parent id * 2: device major:minor * 3: mount prefix * 4: mount point * 5: per-mount options * [optional X]: additional data * X+7: "-" * X+8: type * X+9: source * X+10: per-superblock options */ for (j = 6; j < i && tokens[j]; j++) if (!strcmp(tokens[j], "-")) break; /* could not find separator */ if (j >= i || !tokens[j]) continue; /* there should be exactly three fields after * the separator */ if (i != j + 4) continue; /* not a cgroup filesystem */ if (strcmp(tokens[j + 1], "cgroup") != 0) continue; subsystems = subsystems_from_mount_options(tokens[j + 3], kernel_subsystems); if (!subsystems) goto out; h = NULL; for (k = 1; k <= meta_data->maximum_hierarchy; k++) { if (meta_data->hierarchies[k] && meta_data->hierarchies[k]->subsystems[0] && lxc_string_in_array(meta_data->hierarchies[k]->subsystems[0], (const char **)subsystems)) { /* TODO: we could also check if the lists really match completely, * just to have an additional sanity check */ h = meta_data->hierarchies[k]; break; } } lxc_free_array((void **)subsystems, free); r = lxc_grow_array((void ***)&meta_data->mount_points, &mount_point_capacity, mount_point_count + 1, 12); if (r < 0) goto out; /* create mount point object */ mount_point = calloc(1, sizeof(*mount_point)); if (!mount_point) goto out; meta_data->mount_points[mount_point_count++] = mount_point; mount_point->hierarchy = h; mount_point->mount_point = strdup(tokens[4]); mount_point->mount_prefix = strdup(tokens[3]); if (!mount_point->mount_point || !mount_point->mount_prefix) goto out; mount_point->read_only = !lxc_string_in_list("rw", tokens[5], ','); if (!strcmp(mount_point->mount_prefix, "/")) { if (mount_point->read_only) { if (!h->ro_absolute_mount_point) h->ro_absolute_mount_point = mount_point; } else { if (!h->rw_absolute_mount_point) h->rw_absolute_mount_point = mount_point; } } k = lxc_array_len((void **)h->all_mount_points); r = lxc_grow_array((void ***)&h->all_mount_points, &h->all_mount_point_capacity, k + 1, 4); if (r < 0) goto out; h->all_mount_points[k] = mount_point; } bret = true; out: fclose(proc_self_mountinfo); free(tokens); free(line); return bret; } static struct cgroup_meta_data *lxc_cgroup_load_meta2(const char **subsystem_whitelist) { bool all_kernel_subsystems = true; bool all_named_subsystems = false; struct cgroup_meta_data *meta_data = NULL; char **kernel_subsystems = NULL; int saved_errno = 0; /* if the subsystem whitelist is not specified, include all * hierarchies that contain kernel subsystems by default but * no hierarchies that only contain named subsystems * * if it is specified, the specifier @all will select all * hierarchies, @kernel will select all hierarchies with * kernel subsystems and @named will select all named * hierarchies */ all_kernel_subsystems = subsystem_whitelist ? (lxc_string_in_array("@kernel", subsystem_whitelist) || lxc_string_in_array("@all", subsystem_whitelist)) : true; all_named_subsystems = subsystem_whitelist ? (lxc_string_in_array("@named", subsystem_whitelist) || lxc_string_in_array("@all", subsystem_whitelist)) : false; meta_data = calloc(1, sizeof(struct cgroup_meta_data)); if (!meta_data) return NULL; meta_data->ref = 1; if (!find_cgroup_subsystems(&kernel_subsystems)) goto out_error; if (!find_cgroup_hierarchies(meta_data, all_kernel_subsystems, all_named_subsystems, subsystem_whitelist)) goto out_error; if (!find_hierarchy_mountpts(meta_data, kernel_subsystems)) goto out_error; /* oops, we couldn't find anything */ if (!meta_data->hierarchies || !meta_data->mount_points) { errno = EINVAL; goto out_error; } lxc_free_array((void **)kernel_subsystems, free); return meta_data; out_error: saved_errno = errno; lxc_free_array((void **)kernel_subsystems, free); lxc_cgroup_put_meta(meta_data); errno = saved_errno; return NULL; } static struct cgroup_meta_data *lxc_cgroup_get_meta(struct cgroup_meta_data *meta_data) { meta_data->ref++; return meta_data; } static struct cgroup_meta_data *lxc_cgroup_put_meta(struct cgroup_meta_data *meta_data) { size_t i; if (!meta_data) return NULL; if (--meta_data->ref > 0) return meta_data; lxc_free_array((void **)meta_data->mount_points, (lxc_free_fn)lxc_cgroup_mount_point_free); if (meta_data->hierarchies) { for (i = 0; i <= meta_data->maximum_hierarchy; i++) lxc_cgroup_hierarchy_free(meta_data->hierarchies[i]); } free(meta_data->hierarchies); free(meta_data); return NULL; } static struct cgroup_hierarchy *lxc_cgroup_find_hierarchy(struct cgroup_meta_data *meta_data, const char *subsystem) { size_t i; for (i = 0; i <= meta_data->maximum_hierarchy; i++) { struct cgroup_hierarchy *h = meta_data->hierarchies[i]; if (h && lxc_string_in_array(subsystem, (const char **)h->subsystems)) return h; } return NULL; } static struct cgroup_mount_point *lxc_cgroup_find_mount_point(struct cgroup_hierarchy *hierarchy, const char *group, bool should_be_writable) { struct cgroup_mount_point **mps; struct cgroup_mount_point *current_result = NULL; ssize_t quality = -1; /* trivial case */ if (hierarchy->rw_absolute_mount_point) return hierarchy->rw_absolute_mount_point; if (!should_be_writable && hierarchy->ro_absolute_mount_point) return hierarchy->ro_absolute_mount_point; for (mps = hierarchy->all_mount_points; mps && *mps; mps++) { struct cgroup_mount_point *mp = *mps; size_t prefix_len = mp->mount_prefix ? strlen(mp->mount_prefix) : 0; if (prefix_len == 1 && mp->mount_prefix[0] == '/') prefix_len = 0; if (should_be_writable && mp->read_only) continue; if (!prefix_len || (strncmp(group, mp->mount_prefix, prefix_len) == 0 && (group[prefix_len] == '\0' || group[prefix_len] == '/'))) { /* search for the best quality match, i.e. the match with the * shortest prefix where this group is still contained */ if (quality == -1 || prefix_len < quality) { current_result = mp; quality = prefix_len; } } } if (!current_result) errno = ENOENT; return current_result; } static char *lxc_cgroup_find_abs_path(const char *subsystem, const char *group, bool should_be_writable, const char *suffix) { struct cgroup_meta_data *meta_data; struct cgroup_hierarchy *h; struct cgroup_mount_point *mp; char *result; int saved_errno; meta_data = lxc_cgroup_load_meta(); if (!meta_data) return NULL; h = lxc_cgroup_find_hierarchy(meta_data, subsystem); if (!h) goto out_error; mp = lxc_cgroup_find_mount_point(h, group, should_be_writable); if (!mp) goto out_error; result = cgroup_to_absolute_path(mp, group, suffix); if (!result) goto out_error; lxc_cgroup_put_meta(meta_data); return result; out_error: saved_errno = errno; lxc_cgroup_put_meta(meta_data); errno = saved_errno; return NULL; } static struct cgroup_process_info *lxc_cgroup_process_info_get(pid_t pid, struct cgroup_meta_data *meta) { char pid_buf[32]; snprintf(pid_buf, 32, "/proc/%lu/cgroup", (unsigned long)pid); return lxc_cgroup_process_info_getx(pid_buf, meta); } static struct cgroup_process_info *lxc_cgroup_process_info_get_init(struct cgroup_meta_data *meta) { return lxc_cgroup_process_info_get(1, meta); } static struct cgroup_process_info *lxc_cgroup_process_info_get_self(struct cgroup_meta_data *meta) { struct cgroup_process_info *i; i = lxc_cgroup_process_info_getx("/proc/self/cgroup", meta); if (!i) i = lxc_cgroup_process_info_get(getpid(), meta); return i; } /* * If a controller has ns cgroup mounted, then in that cgroup the handler->pid * is already in a new cgroup named after the pid. 'mnt' is passed in as * the full current cgroup. Say that is /sys/fs/cgroup/lxc/2975 and the container * name is c1. . We want to rename the cgroup directory to /sys/fs/cgroup/lxc/c1, * and return the string /sys/fs/cgroup/lxc/c1. */ static char *cgroup_rename_nsgroup(const char *mountpath, const char *oldname, pid_t pid, const char *name) { char *dir, *fulloldpath; char *newname, *fullnewpath; int len, newlen, ret; /* * if cgroup is mounted at /cgroup and task is in cgroup /ab/, pid 2375 and * name is c1, * dir: /ab * fulloldpath = /cgroup/ab/2375 * fullnewpath = /cgroup/ab/c1 * newname = /ab/c1 */ dir = alloca(strlen(oldname) + 1); strcpy(dir, oldname); len = strlen(oldname) + strlen(mountpath) + 22; fulloldpath = alloca(len); ret = snprintf(fulloldpath, len, "%s/%s/%ld", mountpath, oldname, (unsigned long)pid); if (ret < 0 || ret >= len) return NULL; len = strlen(dir) + strlen(name) + 2; newname = malloc(len); if (!newname) { SYSERROR("Out of memory"); return NULL; } ret = snprintf(newname, len, "%s/%s", dir, name); if (ret < 0 || ret >= len) { free(newname); return NULL; } newlen = strlen(mountpath) + len + 2; fullnewpath = alloca(newlen); ret = snprintf(fullnewpath, newlen, "%s/%s", mountpath, newname); if (ret < 0 || ret >= newlen) { free(newname); return NULL; } if (access(fullnewpath, F_OK) == 0) { if (rmdir(fullnewpath) != 0) { SYSERROR("container cgroup %s already exists.", fullnewpath); free(newname); return NULL; } } if (rename(fulloldpath, fullnewpath)) { SYSERROR("failed to rename cgroup %s->%s", fulloldpath, fullnewpath); free(newname); return NULL; } DEBUG("'%s' renamed to '%s'", oldname, newname); return newname; } /* create a new cgroup */ static struct cgroup_process_info *lxc_cgroupfs_create(const char *name, const char *path_pattern, struct cgroup_meta_data *meta_data, const char *sub_pattern) { char **cgroup_path_components = NULL; char **p = NULL; char *path_so_far = NULL; char **new_cgroup_paths = NULL; char **new_cgroup_paths_sub = NULL; struct cgroup_mount_point *mp; struct cgroup_hierarchy *h; struct cgroup_process_info *base_info = NULL; struct cgroup_process_info *info_ptr; int saved_errno; int r; unsigned suffix = 0; bool had_sub_pattern = false; size_t i; if (!is_valid_cgroup(name)) { ERROR("Invalid cgroup name: '%s'", name); errno = EINVAL; return NULL; } if (!strstr(path_pattern, "%n")) { ERROR("Invalid cgroup path pattern: '%s'; contains no %%n for specifying container name", path_pattern); errno = EINVAL; return NULL; } /* we will modify the result of this operation directly, * so we don't have to copy the data structure */ base_info = (path_pattern[0] == '/') ? lxc_cgroup_process_info_get_init(meta_data) : lxc_cgroup_process_info_get_self(meta_data); if (!base_info) return NULL; new_cgroup_paths = calloc(meta_data->maximum_hierarchy + 1, sizeof(char *)); if (!new_cgroup_paths) goto out_initial_error; new_cgroup_paths_sub = calloc(meta_data->maximum_hierarchy + 1, sizeof(char *)); if (!new_cgroup_paths_sub) goto out_initial_error; /* find mount points we can use */ for (info_ptr = base_info; info_ptr; info_ptr = info_ptr->next) { h = info_ptr->hierarchy; mp = lxc_cgroup_find_mount_point(h, info_ptr->cgroup_path, true); if (!mp) { ERROR("Could not find writable mount point for cgroup hierarchy %d while trying to create cgroup.", h->index); goto out_initial_error; } info_ptr->designated_mount_point = mp; if (lxc_string_in_array("ns", (const char **)h->subsystems)) continue; if (handle_cgroup_settings(mp, info_ptr->cgroup_path) < 0) { ERROR("Could not set clone_children to 1 for cpuset hierarchy in parent cgroup."); goto out_initial_error; } } /* normalize the path */ cgroup_path_components = lxc_normalize_path(path_pattern); if (!cgroup_path_components) goto out_initial_error; /* go through the path components to see if we can create them */ for (p = cgroup_path_components; *p || (sub_pattern && !had_sub_pattern); p++) { /* we only want to create the same component with -1, -2, etc. * if the component contains the container name itself, otherwise * it's not an error if it already exists */ char *p_eff = *p ? *p : (char *)sub_pattern; bool contains_name = strstr(p_eff, "%n"); char *current_component = NULL; char *current_subpath = NULL; char *current_entire_path = NULL; char *parts[3]; size_t j = 0; i = 0; /* if we are processing the subpattern, we want to make sure * loop is ended the next time around */ if (!*p) { had_sub_pattern = true; p--; } goto find_name_on_this_level; cleanup_name_on_this_level: /* This is reached if we found a name clash. * In that case, remove the cgroup from all previous hierarchies */ for (j = 0, info_ptr = base_info; j < i && info_ptr; info_ptr = info_ptr->next, j++) { r = remove_cgroup(info_ptr->designated_mount_point, info_ptr->created_paths[info_ptr->created_paths_count - 1], false); if (r < 0) WARN("could not clean up cgroup we created when trying to create container"); free(info_ptr->created_paths[info_ptr->created_paths_count - 1]); info_ptr->created_paths[--info_ptr->created_paths_count] = NULL; } if (current_component != current_subpath) free(current_subpath); if (current_component != p_eff) free(current_component); current_component = current_subpath = NULL; /* try again with another suffix */ ++suffix; find_name_on_this_level: /* determine name of the path component we should create */ if (contains_name && suffix > 0) { char *buf = calloc(strlen(name) + 32, 1); if (!buf) goto out_initial_error; snprintf(buf, strlen(name) + 32, "%s-%u", name, suffix); current_component = lxc_string_replace("%n", buf, p_eff); free(buf); } else { current_component = contains_name ? lxc_string_replace("%n", name, p_eff) : p_eff; } parts[0] = path_so_far; parts[1] = current_component; parts[2] = NULL; current_subpath = path_so_far ? lxc_string_join("/", (const char **)parts, false) : current_component; /* Now go through each hierarchy and try to create the * corresponding cgroup */ for (i = 0, info_ptr = base_info; info_ptr; info_ptr = info_ptr->next, i++) { char *parts2[3]; if (lxc_string_in_array("ns", (const char **)info_ptr->hierarchy->subsystems)) continue; current_entire_path = NULL; parts2[0] = !strcmp(info_ptr->cgroup_path, "/") ? "" : info_ptr->cgroup_path; parts2[1] = current_subpath; parts2[2] = NULL; current_entire_path = lxc_string_join("/", (const char **)parts2, false); if (!*p) { /* we are processing the subpath, so only update that one */ free(new_cgroup_paths_sub[i]); new_cgroup_paths_sub[i] = strdup(current_entire_path); if (!new_cgroup_paths_sub[i]) goto cleanup_from_error; } else { /* remember which path was used on this controller */ free(new_cgroup_paths[i]); new_cgroup_paths[i] = strdup(current_entire_path); if (!new_cgroup_paths[i]) goto cleanup_from_error; } r = create_cgroup(info_ptr->designated_mount_point, current_entire_path); if (r < 0 && errno == EEXIST && contains_name) { /* name clash => try new name with new suffix */ free(current_entire_path); current_entire_path = NULL; goto cleanup_name_on_this_level; } else if (r < 0 && errno != EEXIST) { SYSERROR("Could not create cgroup '%s' in '%s'.", current_entire_path, info_ptr->designated_mount_point->mount_point); goto cleanup_from_error; } else if (r == 0) { /* successfully created */ r = lxc_grow_array((void ***)&info_ptr->created_paths, &info_ptr->created_paths_capacity, info_ptr->created_paths_count + 1, 8); if (r < 0) goto cleanup_from_error; if (!init_cpuset_if_needed(info_ptr->designated_mount_point, current_entire_path)) { ERROR("Failed to initialize cpuset for '%s' in '%s'.", current_entire_path, info_ptr->designated_mount_point->mount_point); goto cleanup_from_error; } info_ptr->created_paths[info_ptr->created_paths_count++] = current_entire_path; } else { /* if we didn't create the cgroup, then we have to make sure that * further cgroups will be created properly */ if (handle_cgroup_settings(info_ptr->designated_mount_point, info_ptr->cgroup_path) < 0) { ERROR("Could not set clone_children to 1 for cpuset hierarchy in pre-existing cgroup."); goto cleanup_from_error; } if (!init_cpuset_if_needed(info_ptr->designated_mount_point, info_ptr->cgroup_path)) { ERROR("Failed to initialize cpuset in pre-existing '%s'.", info_ptr->cgroup_path); goto cleanup_from_error; } /* already existed but path component of pattern didn't contain '%n', * so this is not an error; but then we don't need current_entire_path * anymore... */ free(current_entire_path); current_entire_path = NULL; } } /* save path so far */ free(path_so_far); path_so_far = strdup(current_subpath); if (!path_so_far) goto cleanup_from_error; /* cleanup */ if (current_component != current_subpath) free(current_subpath); if (current_component != p_eff) free(current_component); current_component = current_subpath = NULL; continue; cleanup_from_error: /* called if an error occurred in the loop, so we * do some additional cleanup here */ saved_errno = errno; if (current_component != current_subpath) free(current_subpath); if (current_component != p_eff) free(current_component); free(current_entire_path); errno = saved_errno; goto out_initial_error; } /* we're done, now update the paths */ for (i = 0, info_ptr = base_info; info_ptr; info_ptr = info_ptr->next, i++) { /* ignore legacy 'ns' subsystem here, lxc_cgroup_create_legacy * will take care of it * Since we do a continue in above loop, new_cgroup_paths[i] is * unset anyway, as is new_cgroup_paths_sub[i] */ if (lxc_string_in_array("ns", (const char **)info_ptr->hierarchy->subsystems)) continue; free(info_ptr->cgroup_path); info_ptr->cgroup_path = new_cgroup_paths[i]; info_ptr->cgroup_path_sub = new_cgroup_paths_sub[i]; } /* don't use lxc_free_array since we used the array members * to store them in our result... */ free(new_cgroup_paths); free(new_cgroup_paths_sub); free(path_so_far); lxc_free_array((void **)cgroup_path_components, free); return base_info; out_initial_error: saved_errno = errno; free(path_so_far); lxc_cgroup_process_info_free_and_remove(base_info); lxc_free_array((void **)new_cgroup_paths, free); lxc_free_array((void **)new_cgroup_paths_sub, free); lxc_free_array((void **)cgroup_path_components, free); errno = saved_errno; return NULL; } static int lxc_cgroup_create_legacy(struct cgroup_process_info *base_info, const char *name, pid_t pid) { struct cgroup_process_info *info_ptr; int r; for (info_ptr = base_info; info_ptr; info_ptr = info_ptr->next) { if (!lxc_string_in_array("ns", (const char **)info_ptr->hierarchy->subsystems)) continue; /* * For any path which has ns cgroup mounted, handler->pid is already * moved into a container called '%d % (handler->pid)'. Rename it to * the cgroup name and record that. */ char *tmp = cgroup_rename_nsgroup((const char *)info_ptr->designated_mount_point->mount_point, info_ptr->cgroup_path, pid, name); if (!tmp) return -1; free(info_ptr->cgroup_path); info_ptr->cgroup_path = tmp; r = lxc_grow_array((void ***)&info_ptr->created_paths, &info_ptr->created_paths_capacity, info_ptr->created_paths_count + 1, 8); if (r < 0) return -1; tmp = strdup(tmp); if (!tmp) return -1; info_ptr->created_paths[info_ptr->created_paths_count++] = tmp; } return 0; } /* get the cgroup membership of a given container */ static struct cgroup_process_info *lxc_cgroup_get_container_info(const char *name, const char *lxcpath, struct cgroup_meta_data *meta_data) { struct cgroup_process_info *result = NULL; int saved_errno = 0; size_t i; struct cgroup_process_info **cptr = &result; struct cgroup_process_info *entry = NULL; char *path = NULL; for (i = 0; i <= meta_data->maximum_hierarchy; i++) { struct cgroup_hierarchy *h = meta_data->hierarchies[i]; if (!h || !h->used) continue; /* use the command interface to look for the cgroup */ path = lxc_cmd_get_cgroup_path(name, lxcpath, h->subsystems[0]); if (!path) { h->used = false; WARN("Not attaching to cgroup %s unknown to %s %s", h->subsystems[0], lxcpath, name); continue; } entry = calloc(1, sizeof(struct cgroup_process_info)); if (!entry) goto out_error; entry->meta_ref = lxc_cgroup_get_meta(meta_data); entry->hierarchy = h; entry->cgroup_path = path; path = NULL; /* it is not an error if we don't find anything here, * it is up to the caller to decide what to do in that * case */ entry->designated_mount_point = lxc_cgroup_find_mount_point(h, entry->cgroup_path, true); *cptr = entry; cptr = &entry->next; entry = NULL; } return result; out_error: saved_errno = errno; free(path); lxc_cgroup_process_info_free(result); lxc_cgroup_process_info_free(entry); errno = saved_errno; return NULL; } /* move a processs to the cgroups specified by the membership */ static int lxc_cgroupfs_enter(struct cgroup_process_info *info, pid_t pid, bool enter_sub) { char pid_buf[32]; char *cgroup_tasks_fn; int r; struct cgroup_process_info *info_ptr; snprintf(pid_buf, 32, "%lu", (unsigned long)pid); for (info_ptr = info; info_ptr; info_ptr = info_ptr->next) { char *cgroup_path = (enter_sub && info_ptr->cgroup_path_sub) ? info_ptr->cgroup_path_sub : info_ptr->cgroup_path; if (!info_ptr->designated_mount_point) { info_ptr->designated_mount_point = lxc_cgroup_find_mount_point(info_ptr->hierarchy, cgroup_path, true); if (!info_ptr->designated_mount_point) { SYSERROR("Could not add pid %lu to cgroup %s: internal error (couldn't find any writable mountpoint to cgroup filesystem)", (unsigned long)pid, cgroup_path); return -1; } } cgroup_tasks_fn = cgroup_to_absolute_path(info_ptr->designated_mount_point, cgroup_path, "/tasks"); if (!cgroup_tasks_fn) { SYSERROR("Could not add pid %lu to cgroup %s: internal error", (unsigned long)pid, cgroup_path); return -1; } r = lxc_write_to_file(cgroup_tasks_fn, pid_buf, strlen(pid_buf), false); free(cgroup_tasks_fn); if (r < 0) { SYSERROR("Could not add pid %lu to cgroup %s: internal error", (unsigned long)pid, cgroup_path); return -1; } } return 0; } /* free process membership information */ void lxc_cgroup_process_info_free(struct cgroup_process_info *info) { struct cgroup_process_info *next; if (!info) return; next = info->next; lxc_cgroup_put_meta(info->meta_ref); free(info->cgroup_path); free(info->cgroup_path_sub); lxc_free_array((void **)info->created_paths, free); free(info); lxc_cgroup_process_info_free(next); } /* free process membership information and remove cgroups that were created */ void lxc_cgroup_process_info_free_and_remove(struct cgroup_process_info *info) { struct cgroup_process_info *next; char **pp; if (!info) return; next = info->next; { struct cgroup_mount_point *mp = info->designated_mount_point; if (!mp) mp = lxc_cgroup_find_mount_point(info->hierarchy, info->cgroup_path, true); if (mp) /* ignore return value here, perhaps we created the * '/lxc' cgroup in this container but another container * is still running (for example) */ (void)remove_cgroup(mp, info->cgroup_path, true); } for (pp = info->created_paths; pp && *pp; pp++); for ((void)(pp && --pp); info->created_paths && pp >= info->created_paths; --pp) { free(*pp); } free(info->created_paths); lxc_cgroup_put_meta(info->meta_ref); free(info->cgroup_path); free(info->cgroup_path_sub); free(info); lxc_cgroup_process_info_free_and_remove(next); } static char *lxc_cgroup_get_hierarchy_path_data(const char *subsystem, struct cgfs_data *d) { struct cgroup_process_info *info = d->info; info = find_info_for_subsystem(info, subsystem); if (!info) return NULL; return info->cgroup_path; } static char *lxc_cgroup_get_hierarchy_abs_path_data(const char *subsystem, struct cgfs_data *d) { struct cgroup_process_info *info = d->info; struct cgroup_mount_point *mp = NULL; info = find_info_for_subsystem(info, subsystem); if (!info) return NULL; if (info->designated_mount_point) { mp = info->designated_mount_point; } else { mp = lxc_cgroup_find_mount_point(info->hierarchy, info->cgroup_path, true); if (!mp) return NULL; } return cgroup_to_absolute_path(mp, info->cgroup_path, NULL); } static char *lxc_cgroup_get_hierarchy_abs_path(const char *subsystem, const char *name, const char *lxcpath) { struct cgroup_meta_data *meta; struct cgroup_process_info *base_info, *info; struct cgroup_mount_point *mp; char *result = NULL; meta = lxc_cgroup_load_meta(); if (!meta) return NULL; base_info = lxc_cgroup_get_container_info(name, lxcpath, meta); if (!base_info) goto out1; info = find_info_for_subsystem(base_info, subsystem); if (!info) goto out2; if (info->designated_mount_point) { mp = info->designated_mount_point; } else { mp = lxc_cgroup_find_mount_point(info->hierarchy, info->cgroup_path, true); if (!mp) goto out3; } result = cgroup_to_absolute_path(mp, info->cgroup_path, NULL); out3: out2: lxc_cgroup_process_info_free(base_info); out1: lxc_cgroup_put_meta(meta); return result; } static int lxc_cgroup_set_data(const char *filename, const char *value, struct cgfs_data *d) { char *subsystem = NULL, *p, *path; int ret = -1; subsystem = alloca(strlen(filename) + 1); strcpy(subsystem, filename); if ((p = strchr(subsystem, '.')) != NULL) *p = '\0'; path = lxc_cgroup_get_hierarchy_abs_path_data(subsystem, d); if (path) { ret = do_cgroup_set(path, filename, value); free(path); } return ret; } static int lxc_cgroupfs_set(const char *filename, const char *value, const char *name, const char *lxcpath) { char *subsystem = NULL, *p, *path; int ret = -1; subsystem = alloca(strlen(filename) + 1); strcpy(subsystem, filename); if ((p = strchr(subsystem, '.')) != NULL) *p = '\0'; path = lxc_cgroup_get_hierarchy_abs_path(subsystem, name, lxcpath); if (path) { ret = do_cgroup_set(path, filename, value); free(path); } return ret; } static int lxc_cgroupfs_get(const char *filename, char *value, size_t len, const char *name, const char *lxcpath) { char *subsystem = NULL, *p, *path; int ret = -1; subsystem = alloca(strlen(filename) + 1); strcpy(subsystem, filename); if ((p = strchr(subsystem, '.')) != NULL) *p = '\0'; path = lxc_cgroup_get_hierarchy_abs_path(subsystem, name, lxcpath); if (path) { ret = do_cgroup_get(path, filename, value, len); free(path); } return ret; } static bool cgroupfs_mount_cgroup(void *hdata, const char *root, int type) { size_t bufsz = strlen(root) + sizeof("/sys/fs/cgroup"); char *path = NULL; char **parts = NULL; char *dirname = NULL; char *abs_path = NULL; char *abs_path2 = NULL; struct cgfs_data *cgfs_d; struct cgroup_process_info *info, *base_info; int r, saved_errno = 0; cgfs_d = hdata; if (!cgfs_d) return false; base_info = cgfs_d->info; /* If we get passed the _NOSPEC types, we default to _MIXED, since we don't * have access to the lxc_conf object at this point. It really should be up * to the caller to fix this, but this doesn't really hurt. */ if (type == LXC_AUTO_CGROUP_FULL_NOSPEC) type = LXC_AUTO_CGROUP_FULL_MIXED; else if (type == LXC_AUTO_CGROUP_NOSPEC) type = LXC_AUTO_CGROUP_MIXED; if (type < LXC_AUTO_CGROUP_RO || type > LXC_AUTO_CGROUP_FULL_MIXED) { ERROR("could not mount cgroups into container: invalid type specified internally"); errno = EINVAL; return false; } path = calloc(1, bufsz); if (!path) return false; snprintf(path, bufsz, "%s/sys/fs/cgroup", root); r = safe_mount("cgroup_root", path, "tmpfs", MS_NOSUID|MS_NODEV|MS_NOEXEC|MS_RELATIME, "size=10240k,mode=755", root); if (r < 0) { SYSERROR("could not mount tmpfs to /sys/fs/cgroup in the container"); return false; } /* now mount all the hierarchies we care about */ for (info = base_info; info; info = info->next) { size_t subsystem_count, i; struct cgroup_mount_point *mp = info->designated_mount_point; if (!mp) mp = lxc_cgroup_find_mount_point(info->hierarchy, info->cgroup_path, true); if (!mp) { SYSERROR("could not find original mount point for cgroup hierarchy while trying to mount cgroup filesystem"); goto out_error; } subsystem_count = lxc_array_len((void **)info->hierarchy->subsystems); parts = calloc(subsystem_count + 1, sizeof(char *)); if (!parts) goto out_error; for (i = 0; i < subsystem_count; i++) { if (!strncmp(info->hierarchy->subsystems[i], "name=", 5)) parts[i] = info->hierarchy->subsystems[i] + 5; else parts[i] = info->hierarchy->subsystems[i]; } dirname = lxc_string_join(",", (const char **)parts, false); if (!dirname) goto out_error; /* create subsystem directory */ abs_path = lxc_append_paths(path, dirname); if (!abs_path) goto out_error; r = mkdir_p(abs_path, 0755); if (r < 0 && errno != EEXIST) { SYSERROR("could not create cgroup subsystem directory /sys/fs/cgroup/%s", dirname); goto out_error; } abs_path2 = lxc_append_paths(abs_path, info->cgroup_path); if (!abs_path2) goto out_error; if (type == LXC_AUTO_CGROUP_FULL_RO || type == LXC_AUTO_CGROUP_FULL_RW || type == LXC_AUTO_CGROUP_FULL_MIXED) { /* bind-mount the cgroup entire filesystem there */ if (strcmp(mp->mount_prefix, "/") != 0) { /* FIXME: maybe we should just try to remount the entire hierarchy * with a regular mount command? may that works? */ ERROR("could not automatically mount cgroup-full to /sys/fs/cgroup/%s: host has no mount point for this cgroup filesystem that has access to the root cgroup", dirname); goto out_error; } r = mount(mp->mount_point, abs_path, "none", MS_BIND, 0); if (r < 0) { SYSERROR("error bind-mounting %s to %s", mp->mount_point, abs_path); goto out_error; } /* main cgroup path should be read-only */ if (type == LXC_AUTO_CGROUP_FULL_RO || type == LXC_AUTO_CGROUP_FULL_MIXED) { r = mount(NULL, abs_path, NULL, MS_REMOUNT|MS_BIND|MS_RDONLY, NULL); if (r < 0) { SYSERROR("error re-mounting %s readonly", abs_path); goto out_error; } } /* own cgroup should be read-write */ if (type == LXC_AUTO_CGROUP_FULL_MIXED) { r = mount(abs_path2, abs_path2, NULL, MS_BIND, NULL); if (r < 0) { SYSERROR("error bind-mounting %s onto itself", abs_path2); goto out_error; } r = mount(NULL, abs_path2, NULL, MS_REMOUNT|MS_BIND, NULL); if (r < 0) { SYSERROR("error re-mounting %s readwrite", abs_path2); goto out_error; } } } else { /* create path for container's cgroup */ r = mkdir_p(abs_path2, 0755); if (r < 0 && errno != EEXIST) { SYSERROR("could not create cgroup directory /sys/fs/cgroup/%s%s", dirname, info->cgroup_path); goto out_error; } /* for read-only and mixed cases, we have to bind-mount the tmpfs directory * that points to the hierarchy itself (i.e. /sys/fs/cgroup/cpu etc.) onto * itself and then bind-mount it read-only, since we keep the tmpfs itself * read-write (see comment below) */ if (type == LXC_AUTO_CGROUP_MIXED || type == LXC_AUTO_CGROUP_RO) { r = mount(abs_path, abs_path, NULL, MS_BIND, NULL); if (r < 0) { SYSERROR("error bind-mounting %s onto itself", abs_path); goto out_error; } r = mount(NULL, abs_path, NULL, MS_REMOUNT|MS_BIND|MS_RDONLY, NULL); if (r < 0) { SYSERROR("error re-mounting %s readonly", abs_path); goto out_error; } } free(abs_path); abs_path = NULL; /* bind-mount container's cgroup to that directory */ abs_path = cgroup_to_absolute_path(mp, info->cgroup_path, NULL); if (!abs_path) goto out_error; r = mount(abs_path, abs_path2, "none", MS_BIND, 0); if (r < 0) { SYSERROR("error bind-mounting %s to %s", abs_path, abs_path2); goto out_error; } if (type == LXC_AUTO_CGROUP_RO) { r = mount(NULL, abs_path2, NULL, MS_REMOUNT|MS_BIND|MS_RDONLY, NULL); if (r < 0) { SYSERROR("error re-mounting %s readonly", abs_path2); goto out_error; } } } free(abs_path); free(abs_path2); abs_path = NULL; abs_path2 = NULL; /* add symlinks for every single subsystem */ if (subsystem_count > 1) { for (i = 0; i < subsystem_count; i++) { abs_path = lxc_append_paths(path, parts[i]); if (!abs_path) goto out_error; r = symlink(dirname, abs_path); if (r < 0) WARN("could not create symlink %s -> %s in /sys/fs/cgroup of container", parts[i], dirname); free(abs_path); abs_path = NULL; } } free(dirname); free(parts); dirname = NULL; parts = NULL; } /* We used to remount the entire tmpfs readonly if any :ro or * :mixed mode was specified. However, Ubuntu's mountall has the * unfortunate behavior to block bootup if /sys/fs/cgroup is * mounted read-only and cannot be remounted read-write. * (mountall reads /lib/init/fstab and tries to (re-)mount all of * these if they are not already mounted with the right options; * it contains an entry for /sys/fs/cgroup. In case it can't do * that, it prompts for the user to either manually fix it or * boot anyway. But without user input, booting of the container * hangs.) * * Instead of remounting the entire tmpfs readonly, we only * remount the paths readonly that are part of the cgroup * hierarchy. */ free(path); return true; out_error: saved_errno = errno; free(path); free(dirname); free(parts); free(abs_path); free(abs_path2); errno = saved_errno; return false; } static int cgfs_nrtasks(void *hdata) { struct cgfs_data *d = hdata; struct cgroup_process_info *info; struct cgroup_mount_point *mp = NULL; char *abs_path = NULL; int ret; if (!d) { errno = ENOENT; return -1; } info = d->info; if (!info) { errno = ENOENT; return -1; } if (info->designated_mount_point) { mp = info->designated_mount_point; } else { mp = lxc_cgroup_find_mount_point(info->hierarchy, info->cgroup_path, false); if (!mp) return -1; } abs_path = cgroup_to_absolute_path(mp, info->cgroup_path, NULL); if (!abs_path) return -1; ret = cgroup_recursive_task_count(abs_path); free(abs_path); return ret; } static struct cgroup_process_info * lxc_cgroup_process_info_getx(const char *proc_pid_cgroup_str, struct cgroup_meta_data *meta) { struct cgroup_process_info *result = NULL; FILE *proc_pid_cgroup = NULL; char *line = NULL; size_t sz = 0; int saved_errno = 0; struct cgroup_process_info **cptr = &result; struct cgroup_process_info *entry = NULL; proc_pid_cgroup = fopen_cloexec(proc_pid_cgroup_str, "r"); if (!proc_pid_cgroup) return NULL; while (getline(&line, &sz, proc_pid_cgroup) != -1) { /* file format: hierarchy:subsystems:group */ char *colon1; char *colon2; char *endptr; int hierarchy_number; struct cgroup_hierarchy *h = NULL; if (!line[0]) continue; if (line[strlen(line) - 1] == '\n') line[strlen(line) - 1] = '\0'; colon1 = strchr(line, ':'); if (!colon1) continue; *colon1++ = '\0'; colon2 = strchr(colon1, ':'); if (!colon2) continue; *colon2++ = '\0'; endptr = NULL; hierarchy_number = strtoul(line, &endptr, 10); if (!endptr || *endptr) continue; if (hierarchy_number > meta->maximum_hierarchy) { /* we encountered a hierarchy we didn't have before, * so probably somebody remounted some stuff in the * mean time... */ errno = EAGAIN; goto out_error; } h = meta->hierarchies[hierarchy_number]; if (!h) { /* we encountered a hierarchy that was thought to be * dead before, so probably somebody remounted some * stuff in the mean time... */ errno = EAGAIN; goto out_error; } /* we are told that we should ignore this hierarchy */ if (!h->used) continue; entry = calloc(1, sizeof(struct cgroup_process_info)); if (!entry) goto out_error; entry->meta_ref = lxc_cgroup_get_meta(meta); entry->hierarchy = h; entry->cgroup_path = strdup(colon2); if (!entry->cgroup_path) goto out_error; *cptr = entry; cptr = &entry->next; entry = NULL; } fclose(proc_pid_cgroup); free(line); return result; out_error: saved_errno = errno; if (proc_pid_cgroup) fclose(proc_pid_cgroup); lxc_cgroup_process_info_free(result); lxc_cgroup_process_info_free(entry); free(line); errno = saved_errno; return NULL; } static char **subsystems_from_mount_options(const char *mount_options, char **kernel_list) { char *token, *str, *saveptr = NULL; char **result = NULL; size_t result_capacity = 0; size_t result_count = 0; int saved_errno; int r; str = alloca(strlen(mount_options)+1); strcpy(str, mount_options); for (; (token = strtok_r(str, ",", &saveptr)); str = NULL) { /* we have a subsystem if it's either in the list of * subsystems provided by the kernel OR if it starts * with name= for named hierarchies */ if (!strncmp(token, "name=", 5) || lxc_string_in_array(token, (const char **)kernel_list)) { r = lxc_grow_array((void ***)&result, &result_capacity, result_count + 1, 12); if (r < 0) goto out_free; result[result_count + 1] = NULL; result[result_count] = strdup(token); if (!result[result_count]) goto out_free; result_count++; } } return result; out_free: saved_errno = errno; lxc_free_array((void**)result, free); errno = saved_errno; return NULL; } static void lxc_cgroup_mount_point_free(struct cgroup_mount_point *mp) { if (!mp) return; free(mp->mount_point); free(mp->mount_prefix); free(mp); } static void lxc_cgroup_hierarchy_free(struct cgroup_hierarchy *h) { if (!h) return; lxc_free_array((void **)h->subsystems, free); free(h->all_mount_points); free(h); } static bool is_valid_cgroup(const char *name) { const char *p; for (p = name; *p; p++) { /* Use the ASCII printable characters range(32 - 127) * is reasonable, we kick out 32(SPACE) because it'll * break legacy lxc-ls */ if (*p <= 32 || *p >= 127 || *p == '/') return false; } return strcmp(name, ".") != 0 && strcmp(name, "..") != 0; } static int create_or_remove_cgroup(bool do_remove, struct cgroup_mount_point *mp, const char *path, int recurse) { int r, saved_errno = 0; char *buf = cgroup_to_absolute_path(mp, path, NULL); if (!buf) return -1; /* create or remove directory */ if (do_remove) { if (recurse) r = cgroup_rmdir(buf); else r = rmdir(buf); } else r = mkdir(buf, 0777); saved_errno = errno; free(buf); errno = saved_errno; return r; } static int create_cgroup(struct cgroup_mount_point *mp, const char *path) { return create_or_remove_cgroup(false, mp, path, false); } static int remove_cgroup(struct cgroup_mount_point *mp, const char *path, bool recurse) { return create_or_remove_cgroup(true, mp, path, recurse); } static char *cgroup_to_absolute_path(struct cgroup_mount_point *mp, const char *path, const char *suffix) { /* first we have to make sure we subtract the mount point's prefix */ char *prefix = mp->mount_prefix; char *buf; ssize_t len, rv; /* we want to make sure only absolute paths to cgroups are passed to us */ if (path[0] != '/') { errno = EINVAL; return NULL; } if (prefix && !strcmp(prefix, "/")) prefix = NULL; /* prefix doesn't match */ if (prefix && strncmp(prefix, path, strlen(prefix)) != 0) { errno = EINVAL; return NULL; } /* if prefix is /foo and path is /foobar */ if (prefix && path[strlen(prefix)] != '/' && path[strlen(prefix)] != '\0') { errno = EINVAL; return NULL; } /* remove prefix from path */ path += prefix ? strlen(prefix) : 0; len = strlen(mp->mount_point) + strlen(path) + (suffix ? strlen(suffix) : 0); buf = calloc(len + 1, 1); if (!buf) return NULL; rv = snprintf(buf, len + 1, "%s%s%s", mp->mount_point, path, suffix ? suffix : ""); if (rv > len) { free(buf); errno = ENOMEM; return NULL; } return buf; } static struct cgroup_process_info * find_info_for_subsystem(struct cgroup_process_info *info, const char *subsystem) { struct cgroup_process_info *info_ptr; for (info_ptr = info; info_ptr; info_ptr = info_ptr->next) { struct cgroup_hierarchy *h = info_ptr->hierarchy; if (lxc_string_in_array(subsystem, (const char **)h->subsystems)) return info_ptr; } errno = ENOENT; return NULL; } static int do_cgroup_get(const char *cgroup_path, const char *sub_filename, char *value, size_t len) { const char *parts[3] = { cgroup_path, sub_filename, NULL }; char *filename; int ret, saved_errno; filename = lxc_string_join("/", parts, false); if (!filename) return -1; ret = lxc_read_from_file(filename, value, len); saved_errno = errno; free(filename); errno = saved_errno; return ret; } static int do_cgroup_set(const char *cgroup_path, const char *sub_filename, const char *value) { const char *parts[3] = { cgroup_path, sub_filename, NULL }; char *filename; int ret, saved_errno; filename = lxc_string_join("/", parts, false); if (!filename) return -1; ret = lxc_write_to_file(filename, value, strlen(value), false); saved_errno = errno; free(filename); errno = saved_errno; return ret; } static int do_setup_cgroup_limits(struct cgfs_data *d, struct lxc_list *cgroup_settings, bool do_devices) { struct lxc_list *iterator, *sorted_cgroup_settings, *next; struct lxc_cgroup *cg; int ret = -1; if (lxc_list_empty(cgroup_settings)) return 0; sorted_cgroup_settings = sort_cgroup_settings(cgroup_settings); if (!sorted_cgroup_settings) { return -1; } lxc_list_for_each(iterator, sorted_cgroup_settings) { cg = iterator->elem; if (do_devices == !strncmp("devices", cg->subsystem, 7)) { if (strcmp(cg->subsystem, "devices.deny") == 0 && cgroup_devices_has_allow_or_deny(d, cg->value, false)) continue; if (strcmp(cg->subsystem, "devices.allow") == 0 && cgroup_devices_has_allow_or_deny(d, cg->value, true)) continue; if (lxc_cgroup_set_data(cg->subsystem, cg->value, d)) { ERROR("Error setting %s to %s for %s", cg->subsystem, cg->value, d->name); goto out; } } DEBUG("cgroup '%s' set to '%s'", cg->subsystem, cg->value); } ret = 0; INFO("cgroup has been setup"); out: lxc_list_for_each_safe(iterator, sorted_cgroup_settings, next) { lxc_list_del(iterator); free(iterator); } free(sorted_cgroup_settings); return ret; } static bool cgroup_devices_has_allow_or_deny(struct cgfs_data *d, char *v, bool for_allow) { char *path; FILE *devices_list; char *line = NULL; size_t sz = 0; bool ret = !for_allow; const char *parts[3] = { NULL, "devices.list", NULL }; // XXX FIXME if users could use something other than 'lxc.devices.deny = a'. // not sure they ever do, but they *could* // right now, I'm assuming they do NOT if (!for_allow && strcmp(v, "a") != 0 && strcmp(v, "a *:* rwm") != 0) return false; parts[0] = (const char *)lxc_cgroup_get_hierarchy_abs_path_data("devices", d); if (!parts[0]) return false; path = lxc_string_join("/", parts, false); if (!path) { free((void *)parts[0]); return false; } devices_list = fopen_cloexec(path, "r"); if (!devices_list) { free(path); return false; } while (getline(&line, &sz, devices_list) != -1) { size_t len = strlen(line); if (len > 0 && line[len-1] == '\n') line[len-1] = '\0'; if (strcmp(line, "a *:* rwm") == 0) { ret = for_allow; goto out; } else if (for_allow && strcmp(line, v) == 0) { ret = true; goto out; } } out: fclose(devices_list); free(line); free(path); return ret; } static int cgroup_recursive_task_count(const char *cgroup_path) { DIR *d; struct dirent *dent_buf; struct dirent *dent; ssize_t name_max; int n = 0, r; /* see man readdir_r(3) */ name_max = pathconf(cgroup_path, _PC_NAME_MAX); if (name_max <= 0) name_max = 255; dent_buf = malloc(offsetof(struct dirent, d_name) + name_max + 1); if (!dent_buf) return -1; d = opendir(cgroup_path); if (!d) { free(dent_buf); return 0; } while (readdir_r(d, dent_buf, &dent) == 0 && dent) { const char *parts[3] = { cgroup_path, dent->d_name, NULL }; char *sub_path; struct stat st; if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, "..")) continue; sub_path = lxc_string_join("/", parts, false); if (!sub_path) { closedir(d); free(dent_buf); return -1; } r = stat(sub_path, &st); if (r < 0) { closedir(d); free(dent_buf); free(sub_path); return -1; } if (S_ISDIR(st.st_mode)) { r = cgroup_recursive_task_count(sub_path); if (r >= 0) n += r; } else if (!strcmp(dent->d_name, "tasks")) { r = count_lines(sub_path); if (r >= 0) n += r; } free(sub_path); } closedir(d); free(dent_buf); return n; } static int count_lines(const char *fn) { FILE *f; char *line = NULL; size_t sz = 0; int n = 0; f = fopen_cloexec(fn, "r"); if (!f) return -1; while (getline(&line, &sz, f) != -1) { n++; } free(line); fclose(f); return n; } static int handle_cgroup_settings(struct cgroup_mount_point *mp, char *cgroup_path) { int r, saved_errno = 0; char buf[2]; mp->need_cpuset_init = false; /* If this is the memory cgroup, we want to enforce hierarchy. * But don't fail if for some reason we can't. */ if (lxc_string_in_array("memory", (const char **)mp->hierarchy->subsystems)) { char *cc_path = cgroup_to_absolute_path(mp, cgroup_path, "/memory.use_hierarchy"); if (cc_path) { r = lxc_read_from_file(cc_path, buf, 1); if (r < 1 || buf[0] != '1') { r = lxc_write_to_file(cc_path, "1", 1, false); if (r < 0) SYSERROR("failed to set memory.use_hierarchy to 1; continuing"); } free(cc_path); } } /* if this is a cpuset hierarchy, we have to set cgroup.clone_children in * the base cgroup, otherwise containers will start with an empty cpuset.mems * and cpuset.cpus and then */ if (lxc_string_in_array("cpuset", (const char **)mp->hierarchy->subsystems)) { char *cc_path = cgroup_to_absolute_path(mp, cgroup_path, "/cgroup.clone_children"); struct stat sb; if (!cc_path) return -1; /* cgroup.clone_children is not available when running under * older kernel versions; in this case, we'll initialize * cpuset.cpus and cpuset.mems later, after the new cgroup * was created */ if (stat(cc_path, &sb) != 0 && errno == ENOENT) { mp->need_cpuset_init = true; free(cc_path); return 0; } r = lxc_read_from_file(cc_path, buf, 1); if (r == 1 && buf[0] == '1') { free(cc_path); return 0; } r = lxc_write_to_file(cc_path, "1", 1, false); saved_errno = errno; free(cc_path); errno = saved_errno; return r < 0 ? -1 : 0; } return 0; } static int cgroup_read_from_file(const char *fn, char buf[], size_t bufsize) { int ret = lxc_read_from_file(fn, buf, bufsize); if (ret < 0) { SYSERROR("failed to read %s", fn); return ret; } if (ret == bufsize) { if (bufsize > 0) { /* obviously this wasn't empty */ buf[bufsize-1] = '\0'; return ret; } /* Callers don't do this, but regression/sanity check */ ERROR("%s: was not expecting 0 bufsize", __func__); return -1; } buf[ret] = '\0'; return ret; } static bool do_init_cpuset_file(struct cgroup_mount_point *mp, const char *path, const char *name) { char value[1024]; char *childfile, *parentfile = NULL, *tmp; int ret; bool ok = false; childfile = cgroup_to_absolute_path(mp, path, name); if (!childfile) return false; /* don't overwrite a non-empty value in the file */ ret = cgroup_read_from_file(childfile, value, sizeof(value)); if (ret < 0) goto out; if (value[0] != '\0' && value[0] != '\n') { ok = true; goto out; } /* path to the same name in the parent cgroup */ parentfile = strdup(path); if (!parentfile) goto out; tmp = strrchr(parentfile, '/'); if (!tmp) goto out; if (tmp == parentfile) tmp++; /* keep the '/' at the start */ *tmp = '\0'; tmp = parentfile; parentfile = cgroup_to_absolute_path(mp, tmp, name); free(tmp); if (!parentfile) goto out; /* copy from parent to child cgroup */ ret = cgroup_read_from_file(parentfile, value, sizeof(value)); if (ret < 0) goto out; if (ret == sizeof(value)) { /* If anyone actually sees this error, we can address it */ ERROR("parent cpuset value too long"); goto out; } ok = (lxc_write_to_file(childfile, value, strlen(value), false) >= 0); if (!ok) SYSERROR("failed writing %s", childfile); out: free(parentfile); free(childfile); return ok; } static bool init_cpuset_if_needed(struct cgroup_mount_point *mp, const char *path) { /* the files we have to handle here are only in cpuset hierarchies */ if (!lxc_string_in_array("cpuset", (const char **)mp->hierarchy->subsystems)) return true; if (!mp->need_cpuset_init) return true; return (do_init_cpuset_file(mp, path, "/cpuset.cpus") && do_init_cpuset_file(mp, path, "/cpuset.mems") ); } struct cgroup_ops *cgfs_ops_init(void) { return &cgfs_ops; } static void *cgfs_init(const char *name) { struct cgfs_data *d; d = malloc(sizeof(*d)); if (!d) return NULL; memset(d, 0, sizeof(*d)); d->name = strdup(name); if (!d->name) goto err1; d->cgroup_pattern = lxc_global_config_value("lxc.cgroup.pattern"); d->meta = lxc_cgroup_load_meta(); if (!d->meta) { ERROR("cgroupfs failed to detect cgroup metadata"); goto err2; } return d; err2: free(d->name); err1: free(d); return NULL; } static void cgfs_destroy(void *hdata) { struct cgfs_data *d = hdata; if (!d) return; free(d->name); lxc_cgroup_process_info_free_and_remove(d->info); lxc_cgroup_put_meta(d->meta); free(d); } static inline bool cgfs_create(void *hdata) { struct cgfs_data *d = hdata; struct cgroup_process_info *i; struct cgroup_meta_data *md; if (!d) return false; md = d->meta; i = lxc_cgroupfs_create(d->name, d->cgroup_pattern, md, NULL); if (!i) return false; d->info = i; return true; } static inline bool cgfs_enter(void *hdata, pid_t pid) { struct cgfs_data *d = hdata; struct cgroup_process_info *i; int ret; if (!d) return false; i = d->info; ret = lxc_cgroupfs_enter(i, pid, false); return ret == 0; } static inline bool cgfs_create_legacy(void *hdata, pid_t pid) { struct cgfs_data *d = hdata; struct cgroup_process_info *i; if (!d) return false; i = d->info; if (lxc_cgroup_create_legacy(i, d->name, pid) < 0) { ERROR("failed to create legacy ns cgroups for '%s'", d->name); return false; } return true; } static const char *cgfs_get_cgroup(void *hdata, const char *subsystem) { struct cgfs_data *d = hdata; if (!d) return NULL; return lxc_cgroup_get_hierarchy_path_data(subsystem, d); } static const char *cgfs_canonical_path(void *hdata) { struct cgfs_data *d = hdata; struct cgroup_process_info *info_ptr; char *path = NULL; if (!d) return NULL; for (info_ptr = d->info; info_ptr; info_ptr = info_ptr->next) { if (!path) path = info_ptr->cgroup_path; else if (strcmp(path, info_ptr->cgroup_path) != 0) { ERROR("not all paths match %s, %s has path %s", path, info_ptr->hierarchy->subsystems[0], info_ptr->cgroup_path); return NULL; } } return path; } static bool cgfs_unfreeze(void *hdata) { struct cgfs_data *d = hdata; char *cgabspath, *cgrelpath; int ret; if (!d) return false; cgrelpath = lxc_cgroup_get_hierarchy_path_data("freezer", d); cgabspath = lxc_cgroup_find_abs_path("freezer", cgrelpath, true, NULL); if (!cgabspath) return false; ret = do_cgroup_set(cgabspath, "freezer.state", "THAWED"); free(cgabspath); return ret == 0; } static bool cgroupfs_setup_limits(void *hdata, struct lxc_list *cgroup_conf, bool with_devices) { struct cgfs_data *d = hdata; if (!d) return false; return do_setup_cgroup_limits(d, cgroup_conf, with_devices) == 0; } static bool lxc_cgroupfs_attach(const char *name, const char *lxcpath, pid_t pid) { struct cgroup_meta_data *meta_data; struct cgroup_process_info *container_info; int ret; meta_data = lxc_cgroup_load_meta(); if (!meta_data) { ERROR("could not move attached process %d to cgroup of container", pid); return false; } container_info = lxc_cgroup_get_container_info(name, lxcpath, meta_data); lxc_cgroup_put_meta(meta_data); if (!container_info) { ERROR("could not move attached process %d to cgroup of container", pid); return false; } ret = lxc_cgroupfs_enter(container_info, pid, false); lxc_cgroup_process_info_free(container_info); if (ret < 0) { ERROR("could not move attached process %d to cgroup of container", pid); return false; } return true; } static struct cgroup_ops cgfs_ops = { .init = cgfs_init, .destroy = cgfs_destroy, .create = cgfs_create, .enter = cgfs_enter, .create_legacy = cgfs_create_legacy, .get_cgroup = cgfs_get_cgroup, .canonical_path = cgfs_canonical_path, .get = lxc_cgroupfs_get, .set = lxc_cgroupfs_set, .unfreeze = cgfs_unfreeze, .setup_limits = cgroupfs_setup_limits, .name = "cgroupfs", .attach = lxc_cgroupfs_attach, .chown = NULL, .mount_cgroup = cgroupfs_mount_cgroup, .nrtasks = cgfs_nrtasks, .driver = CGFS, };
./CrossVul/dataset_final_sorted/CWE-59/c/good_1471_1
crossvul-cpp_data_bad_1471_3
404: Not Found
./CrossVul/dataset_final_sorted/CWE-59/c/bad_1471_3
crossvul-cpp_data_bad_589_5
/* $Id: rc.c,v 1.116 2010/08/20 09:47:09 htrb Exp $ */ /* * Initialization file etc. */ #include "fm.h" #include "myctype.h" #include "proto.h" #include <stdio.h> #include <errno.h> #include "parsetag.h" #include "local.h" #include "regex.h" #include <stdlib.h> #include <stddef.h> struct param_ptr { char *name; int type; int inputtype; void *varptr; char *comment; void *select; }; struct param_section { char *name; struct param_ptr *params; }; struct rc_search_table { struct param_ptr *param; short uniq_pos; }; static struct rc_search_table *RC_search_table; static int RC_table_size; #define P_INT 0 #define P_SHORT 1 #define P_CHARINT 2 #define P_CHAR 3 #define P_STRING 4 #if defined(USE_SSL) && defined(USE_SSL_VERIFY) #define P_SSLPATH 5 #endif #ifdef USE_COLOR #define P_COLOR 6 #endif #ifdef USE_M17N #define P_CODE 7 #endif #define P_PIXELS 8 #define P_NZINT 9 #define P_SCALE 10 /* FIXME: gettextize here */ #ifdef USE_M17N static wc_ces OptionCharset = WC_CES_US_ASCII; /* FIXME: charset of source code */ static int OptionEncode = FALSE; #endif #define CMT_HELPER N_("External Viewer Setup") #define CMT_TABSTOP N_("Tab width in characters") #define CMT_INDENT_INCR N_("Indent for HTML rendering") #define CMT_PIXEL_PER_CHAR N_("Number of pixels per character (4.0...32.0)") #define CMT_PIXEL_PER_LINE N_("Number of pixels per line (4.0...64.0)") #define CMT_PAGERLINE N_("Number of remembered lines when used as a pager") #define CMT_HISTORY N_("Use URL history") #define CMT_HISTSIZE N_("Number of remembered URL") #define CMT_SAVEHIST N_("Save URL history") #define CMT_FRAME N_("Render frames automatically") #define CMT_ARGV_IS_URL N_("Treat argument without scheme as URL") #define CMT_TSELF N_("Use _self as default target") #define CMT_OPEN_TAB_BLANK N_("Open link on new tab if target is _blank or _new") #define CMT_OPEN_TAB_DL_LIST N_("Open download list panel on new tab") #define CMT_DISPLINK N_("Display link URL automatically") #define CMT_DISPLINKNUMBER N_("Display link numbers") #define CMT_DECODE_URL N_("Display decoded URL") #define CMT_DISPLINEINFO N_("Display current line number") #define CMT_DISP_IMAGE N_("Display inline images") #define CMT_PSEUDO_INLINES N_("Display pseudo-ALTs for inline images with no ALT or TITLE string") #ifdef USE_IMAGE #define CMT_AUTO_IMAGE N_("Load inline images automatically") #define CMT_MAX_LOAD_IMAGE N_("Maximum processes for parallel image loading") #define CMT_EXT_IMAGE_VIEWER N_("Use external image viewer") #define CMT_IMAGE_SCALE N_("Scale of image (%)") #define CMT_IMGDISPLAY N_("External command to display image") #define CMT_IMAGE_MAP_LIST N_("Use link list of image map") #endif #define CMT_MULTICOL N_("Display file names in multi-column format") #define CMT_ALT_ENTITY N_("Use ASCII equivalents to display entities") #define CMT_GRAPHIC_CHAR N_("Character type for border of table and menu") #define CMT_DISP_BORDERS N_("Display table borders, ignore value of BORDER") #define CMT_FOLD_TEXTAREA N_("Fold lines in TEXTAREA") #define CMT_DISP_INS_DEL N_("Display INS, DEL, S and STRIKE element") #define CMT_COLOR N_("Display with color") #define CMT_B_COLOR N_("Color of normal character") #define CMT_A_COLOR N_("Color of anchor") #define CMT_I_COLOR N_("Color of image link") #define CMT_F_COLOR N_("Color of form") #define CMT_ACTIVE_STYLE N_("Enable coloring of active link") #define CMT_C_COLOR N_("Color of currently active link") #define CMT_VISITED_ANCHOR N_("Use visited link color") #define CMT_V_COLOR N_("Color of visited link") #define CMT_BG_COLOR N_("Color of background") #define CMT_MARK_COLOR N_("Color of mark") #define CMT_USE_PROXY N_("Use proxy") #define CMT_HTTP_PROXY N_("URL of HTTP proxy host") #ifdef USE_SSL #define CMT_HTTPS_PROXY N_("URL of HTTPS proxy host") #endif /* USE_SSL */ #ifdef USE_GOPHER #define CMT_GOPHER_PROXY N_("URL of GOPHER proxy host") #endif /* USE_GOPHER */ #define CMT_FTP_PROXY N_("URL of FTP proxy host") #define CMT_NO_PROXY N_("Domains to be accessed directly (no proxy)") #define CMT_NOPROXY_NETADDR N_("Check noproxy by network address") #define CMT_NO_CACHE N_("Disable cache") #ifdef USE_NNTP #define CMT_NNTP_SERVER N_("News server") #define CMT_NNTP_MODE N_("Mode of news server") #define CMT_MAX_NEWS N_("Number of news messages") #endif #define CMT_DNS_ORDER N_("Order of name resolution") #define CMT_DROOT N_("Directory corresponding to / (document root)") #define CMT_PDROOT N_("Directory corresponding to /~user") #define CMT_CGIBIN N_("Directory corresponding to /cgi-bin") #define CMT_CONFIRM_QQ N_("Confirm when quitting with q") #define CMT_CLOSE_TAB_BACK N_("Close tab if buffer is last when back") #ifdef USE_MARK #define CMT_USE_MARK N_("Enable mark operations") #endif #define CMT_EMACS_LIKE_LINEEDIT N_("Enable Emacs-style line editing") #define CMT_VI_PREC_NUM N_("Enable vi-like numeric prefix") #define CMT_LABEL_TOPLINE N_("Move cursor to top line when going to label") #define CMT_NEXTPAGE_TOPLINE N_("Move cursor to top line when moving to next page") #define CMT_FOLD_LINE N_("Fold lines of plain text file") #define CMT_SHOW_NUM N_("Show line numbers") #define CMT_SHOW_SRCH_STR N_("Show search string") #define CMT_MIMETYPES N_("List of mime.types files") #define CMT_MAILCAP N_("List of mailcap files") #define CMT_URIMETHODMAP N_("List of urimethodmap files") #define CMT_EDITOR N_("Editor") #define CMT_MAILER N_("Mailer") #define CMT_MAILTO_OPTIONS N_("How to call Mailer for mailto URLs with options") #define CMT_EXTBRZ N_("External browser") #define CMT_EXTBRZ2 N_("2nd external browser") #define CMT_EXTBRZ3 N_("3rd external browser") #define CMT_EXTBRZ4 N_("4th external browser") #define CMT_EXTBRZ5 N_("5th external browser") #define CMT_EXTBRZ6 N_("6th external browser") #define CMT_EXTBRZ7 N_("7th external browser") #define CMT_EXTBRZ8 N_("8th external browser") #define CMT_EXTBRZ9 N_("9th external browser") #define CMT_DISABLE_SECRET_SECURITY_CHECK N_("Disable secret file security check") #define CMT_PASSWDFILE N_("Password file") #define CMT_PRE_FORM_FILE N_("File for setting form on loading") #define CMT_SITECONF_FILE N_("File for preferences for each site") #define CMT_FTPPASS N_("Password for anonymous FTP (your mail address)") #define CMT_FTPPASS_HOSTNAMEGEN N_("Generate domain part of password for FTP") #define CMT_USERAGENT N_("User-Agent identification string") #define CMT_ACCEPTENCODING N_("Accept-Encoding header") #define CMT_ACCEPTMEDIA N_("Accept header") #define CMT_ACCEPTLANG N_("Accept-Language header") #define CMT_MARK_ALL_PAGES N_("Treat URL-like strings as links in all pages") #define CMT_WRAP N_("Wrap search") #define CMT_VIEW_UNSEENOBJECTS N_("Display unseen objects (e.g. bgimage tag)") #define CMT_AUTO_UNCOMPRESS N_("Uncompress compressed data automatically when downloading") #ifdef __EMX__ #define CMT_BGEXTVIEW N_("Run external viewer in a separate session") #else #define CMT_BGEXTVIEW N_("Run external viewer in the background") #endif #define CMT_EXT_DIRLIST N_("Use external program for directory listing") #define CMT_DIRLIST_CMD N_("URL of directory listing command") #ifdef USE_DICT #define CMT_USE_DICTCOMMAND N_("Enable dictionary lookup through CGI") #define CMT_DICTCOMMAND N_("URL of dictionary lookup command") #endif /* USE_DICT */ #define CMT_IGNORE_NULL_IMG_ALT N_("Display link name for images lacking ALT") #define CMT_IFILE N_("Index file for directories") #define CMT_RETRY_HTTP N_("Prepend http:// to URL automatically") #define CMT_DEFAULT_URL N_("Default value for open-URL command") #define CMT_DECODE_CTE N_("Decode Content-Transfer-Encoding when saving") #define CMT_PRESERVE_TIMESTAMP N_("Preserve timestamp when saving") #ifdef USE_MOUSE #define CMT_MOUSE N_("Enable mouse") #define CMT_REVERSE_MOUSE N_("Scroll in reverse direction of mouse drag") #define CMT_RELATIVE_WHEEL_SCROLL N_("Behavior of wheel scroll speed") #define CMT_RELATIVE_WHEEL_SCROLL_RATIO N_("(A only)Scroll by # (%) of screen") #define CMT_FIXED_WHEEL_SCROLL_COUNT N_("(B only)Scroll by # lines") #endif /* USE_MOUSE */ #define CMT_CLEAR_BUF N_("Free memory of undisplayed buffers") #define CMT_NOSENDREFERER N_("Suppress `Referer:' header") #define CMT_IGNORE_CASE N_("Search case-insensitively") #define CMT_USE_LESSOPEN N_("Use LESSOPEN") #ifdef USE_SSL #ifdef USE_SSL_VERIFY #define CMT_SSL_VERIFY_SERVER N_("Perform SSL server verification") #define CMT_SSL_CERT_FILE N_("PEM encoded certificate file of client") #define CMT_SSL_KEY_FILE N_("PEM encoded private key file of client") #define CMT_SSL_CA_PATH N_("Path to directory for PEM encoded certificates of CAs") #define CMT_SSL_CA_FILE N_("File consisting of PEM encoded certificates of CAs") #endif /* USE_SSL_VERIFY */ #define CMT_SSL_FORBID_METHOD N_("List of forbidden SSL methods (2: SSLv2, 3: SSLv3, t: TLSv1.0, 5: TLSv1.1)") #endif /* USE_SSL */ #ifdef USE_COOKIE #define CMT_USECOOKIE N_("Enable cookie processing") #define CMT_SHOWCOOKIE N_("Print a message when receiving a cookie") #define CMT_ACCEPTCOOKIE N_("Accept cookies") #define CMT_ACCEPTBADCOOKIE N_("Action to be taken on invalid cookie") #define CMT_COOKIE_REJECT_DOMAINS N_("Domains to reject cookies from") #define CMT_COOKIE_ACCEPT_DOMAINS N_("Domains to accept cookies from") #define CMT_COOKIE_AVOID_WONG_NUMBER_OF_DOTS N_("Domains to avoid [wrong number of dots]") #endif #define CMT_FOLLOW_REDIRECTION N_("Number of redirections to follow") #define CMT_META_REFRESH N_("Enable processing of meta-refresh tag") #ifdef USE_MIGEMO #define CMT_USE_MIGEMO N_("Enable Migemo (Roma-ji search)") #define CMT_MIGEMO_COMMAND N_("Migemo command") #endif /* USE_MIGEMO */ #ifdef USE_M17N #define CMT_DISPLAY_CHARSET N_("Display charset") #define CMT_DOCUMENT_CHARSET N_("Default document charset") #define CMT_AUTO_DETECT N_("Automatic charset detect when loading") #define CMT_SYSTEM_CHARSET N_("System charset") #define CMT_FOLLOW_LOCALE N_("System charset follows locale(LC_CTYPE)") #define CMT_EXT_HALFDUMP N_("Output halfdump with display charset") #define CMT_USE_WIDE N_("Use multi column characters") #define CMT_USE_COMBINING N_("Use combining characters") #define CMT_EAST_ASIAN_WIDTH N_("Use double width for some Unicode characters") #define CMT_USE_LANGUAGE_TAG N_("Use Unicode language tags") #define CMT_UCS_CONV N_("Charset conversion using Unicode map") #define CMT_PRE_CONV N_("Charset conversion when loading") #define CMT_SEARCH_CONV N_("Adjust search string for document charset") #define CMT_FIX_WIDTH_CONV N_("Fix character width when conversion") #define CMT_USE_GB12345_MAP N_("Use GB 12345 Unicode map instead of GB 2312's") #define CMT_USE_JISX0201 N_("Use JIS X 0201 Roman for ISO-2022-JP") #define CMT_USE_JISC6226 N_("Use JIS C 6226:1978 for ISO-2022-JP") #define CMT_USE_JISX0201K N_("Use JIS X 0201 Katakana") #define CMT_USE_JISX0212 N_("Use JIS X 0212:1990 (Supplemental Kanji)") #define CMT_USE_JISX0213 N_("Use JIS X 0213:2000 (2000JIS)") #define CMT_STRICT_ISO2022 N_("Strict ISO-2022-JP/KR/CN") #define CMT_GB18030_AS_UCS N_("Treat 4 bytes char. of GB18030 as Unicode") #define CMT_SIMPLE_PRESERVE_SPACE N_("Simple Preserve space") #endif #define CMT_KEYMAP_FILE N_("keymap file") #define PI_TEXT 0 #define PI_ONOFF 1 #define PI_SEL_C 2 #ifdef USE_M17N #define PI_CODE 3 #endif struct sel_c { int value; char *cvalue; char *text; }; #ifdef USE_COLOR static struct sel_c colorstr[] = { {0, "black", N_("black")}, {1, "red", N_("red")}, {2, "green", N_("green")}, {3, "yellow", N_("yellow")}, {4, "blue", N_("blue")}, {5, "magenta", N_("magenta")}, {6, "cyan", N_("cyan")}, {7, "white", N_("white")}, {8, "terminal", N_("terminal")}, {0, NULL, NULL} }; #endif /* USE_COLOR */ #if 1 /* ANSI-C ? */ #define N_STR(x) #x #define N_S(x) (x), N_STR(x) #else /* for traditional cpp? */ static char n_s[][2] = { {'0', 0}, {'1', 0}, {'2', 0}, }; #define N_S(x) (x), n_s[(x)] #endif static struct sel_c defaulturls[] = { {N_S(DEFAULT_URL_EMPTY), N_("none")}, {N_S(DEFAULT_URL_CURRENT), N_("current URL")}, {N_S(DEFAULT_URL_LINK), N_("link URL")}, {0, NULL, NULL} }; static struct sel_c displayinsdel[] = { {N_S(DISPLAY_INS_DEL_SIMPLE), N_("simple")}, {N_S(DISPLAY_INS_DEL_NORMAL), N_("use tag")}, {N_S(DISPLAY_INS_DEL_FONTIFY), N_("fontify")}, {0, NULL, NULL} }; #ifdef USE_MOUSE static struct sel_c wheelmode[] = { {TRUE, "1", N_("A:relative to screen height")}, {FALSE, "0", N_("B:fixed speed")}, {0, NULL, NULL} }; #endif /* MOUSE */ #ifdef INET6 static struct sel_c dnsorders[] = { {N_S(DNS_ORDER_UNSPEC), N_("unspecified")}, {N_S(DNS_ORDER_INET_INET6), N_("inet inet6")}, {N_S(DNS_ORDER_INET6_INET), N_("inet6 inet")}, {N_S(DNS_ORDER_INET_ONLY), N_("inet only")}, {N_S(DNS_ORDER_INET6_ONLY), N_("inet6 only")}, {0, NULL, NULL} }; #endif /* INET6 */ #ifdef USE_COOKIE static struct sel_c badcookiestr[] = { {N_S(ACCEPT_BAD_COOKIE_DISCARD), N_("discard")}, #if 0 {N_S(ACCEPT_BAD_COOKIE_ACCEPT), N_("accept")}, #endif {N_S(ACCEPT_BAD_COOKIE_ASK), N_("ask")}, {0, NULL, NULL} }; #endif /* USE_COOKIE */ static struct sel_c mailtooptionsstr[] = { #ifdef USE_W3MMAILER {N_S(MAILTO_OPTIONS_USE_W3MMAILER), N_("use internal mailer instead")}, #endif {N_S(MAILTO_OPTIONS_IGNORE), N_("ignore options and use only the address")}, {N_S(MAILTO_OPTIONS_USE_MAILTO_URL), N_("use full mailto URL")}, {0, NULL, NULL} }; #ifdef USE_M17N static wc_ces_list *display_charset_str = NULL; static wc_ces_list *document_charset_str = NULL; static wc_ces_list *system_charset_str = NULL; static struct sel_c auto_detect_str[] = { {N_S(WC_OPT_DETECT_OFF), N_("OFF")}, {N_S(WC_OPT_DETECT_ISO_2022), N_("Only ISO 2022")}, {N_S(WC_OPT_DETECT_ON), N_("ON")}, {0, NULL, NULL} }; #endif static struct sel_c graphic_char_str[] = { {N_S(GRAPHIC_CHAR_ASCII), N_("ASCII")}, {N_S(GRAPHIC_CHAR_CHARSET), N_("charset specific")}, {N_S(GRAPHIC_CHAR_DEC), N_("DEC special graphics")}, {0, NULL, NULL} }; struct param_ptr params1[] = { {"tabstop", P_NZINT, PI_TEXT, (void *)&Tabstop, CMT_TABSTOP, NULL}, {"indent_incr", P_NZINT, PI_TEXT, (void *)&IndentIncr, CMT_INDENT_INCR, NULL}, {"pixel_per_char", P_PIXELS, PI_TEXT, (void *)&pixel_per_char, CMT_PIXEL_PER_CHAR, NULL}, #ifdef USE_IMAGE {"pixel_per_line", P_PIXELS, PI_TEXT, (void *)&pixel_per_line, CMT_PIXEL_PER_LINE, NULL}, #endif {"frame", P_CHARINT, PI_ONOFF, (void *)&RenderFrame, CMT_FRAME, NULL}, {"target_self", P_CHARINT, PI_ONOFF, (void *)&TargetSelf, CMT_TSELF, NULL}, {"open_tab_blank", P_INT, PI_ONOFF, (void *)&open_tab_blank, CMT_OPEN_TAB_BLANK, NULL}, {"open_tab_dl_list", P_INT, PI_ONOFF, (void *)&open_tab_dl_list, CMT_OPEN_TAB_DL_LIST, NULL}, {"display_link", P_INT, PI_ONOFF, (void *)&displayLink, CMT_DISPLINK, NULL}, {"display_link_number", P_INT, PI_ONOFF, (void *)&displayLinkNumber, CMT_DISPLINKNUMBER, NULL}, {"decode_url", P_INT, PI_ONOFF, (void *)&DecodeURL, CMT_DECODE_URL, NULL}, {"display_lineinfo", P_INT, PI_ONOFF, (void *)&displayLineInfo, CMT_DISPLINEINFO, NULL}, {"ext_dirlist", P_INT, PI_ONOFF, (void *)&UseExternalDirBuffer, CMT_EXT_DIRLIST, NULL}, {"dirlist_cmd", P_STRING, PI_TEXT, (void *)&DirBufferCommand, CMT_DIRLIST_CMD, NULL}, #ifdef USE_DICT {"use_dictcommand", P_INT, PI_ONOFF, (void *)&UseDictCommand, CMT_USE_DICTCOMMAND, NULL}, {"dictcommand", P_STRING, PI_TEXT, (void *)&DictCommand, CMT_DICTCOMMAND, NULL}, #endif /* USE_DICT */ {"multicol", P_INT, PI_ONOFF, (void *)&multicolList, CMT_MULTICOL, NULL}, {"alt_entity", P_CHARINT, PI_ONOFF, (void *)&UseAltEntity, CMT_ALT_ENTITY, NULL}, {"graphic_char", P_CHARINT, PI_SEL_C, (void *)&UseGraphicChar, CMT_GRAPHIC_CHAR, (void *)graphic_char_str}, {"display_borders", P_CHARINT, PI_ONOFF, (void *)&DisplayBorders, CMT_DISP_BORDERS, NULL}, {"fold_textarea", P_CHARINT, PI_ONOFF, (void *)&FoldTextarea, CMT_FOLD_TEXTAREA, NULL}, {"display_ins_del", P_INT, PI_SEL_C, (void *)&displayInsDel, CMT_DISP_INS_DEL, displayinsdel}, {"ignore_null_img_alt", P_INT, PI_ONOFF, (void *)&ignore_null_img_alt, CMT_IGNORE_NULL_IMG_ALT, NULL}, {"view_unseenobject", P_INT, PI_ONOFF, (void *)&view_unseenobject, CMT_VIEW_UNSEENOBJECTS, NULL}, /* XXX: emacs-w3m force to off display_image even if image options off */ {"display_image", P_INT, PI_ONOFF, (void *)&displayImage, CMT_DISP_IMAGE, NULL}, {"pseudo_inlines", P_INT, PI_ONOFF, (void *)&pseudoInlines, CMT_PSEUDO_INLINES, NULL}, #ifdef USE_IMAGE {"auto_image", P_INT, PI_ONOFF, (void *)&autoImage, CMT_AUTO_IMAGE, NULL}, {"max_load_image", P_INT, PI_TEXT, (void *)&maxLoadImage, CMT_MAX_LOAD_IMAGE, NULL}, {"ext_image_viewer", P_INT, PI_ONOFF, (void *)&useExtImageViewer, CMT_EXT_IMAGE_VIEWER, NULL}, {"image_scale", P_SCALE, PI_TEXT, (void *)&image_scale, CMT_IMAGE_SCALE, NULL}, {"imgdisplay", P_STRING, PI_TEXT, (void *)&Imgdisplay, CMT_IMGDISPLAY, NULL}, {"image_map_list", P_INT, PI_ONOFF, (void *)&image_map_list, CMT_IMAGE_MAP_LIST, NULL}, #endif {"fold_line", P_INT, PI_ONOFF, (void *)&FoldLine, CMT_FOLD_LINE, NULL}, {"show_lnum", P_INT, PI_ONOFF, (void *)&showLineNum, CMT_SHOW_NUM, NULL}, {"show_srch_str", P_INT, PI_ONOFF, (void *)&show_srch_str, CMT_SHOW_SRCH_STR, NULL}, {"label_topline", P_INT, PI_ONOFF, (void *)&label_topline, CMT_LABEL_TOPLINE, NULL}, {"nextpage_topline", P_INT, PI_ONOFF, (void *)&nextpage_topline, CMT_NEXTPAGE_TOPLINE, NULL}, {NULL, 0, 0, NULL, NULL, NULL}, }; #ifdef USE_COLOR struct param_ptr params2[] = { {"color", P_INT, PI_ONOFF, (void *)&useColor, CMT_COLOR, NULL}, {"basic_color", P_COLOR, PI_SEL_C, (void *)&basic_color, CMT_B_COLOR, (void *)colorstr}, {"anchor_color", P_COLOR, PI_SEL_C, (void *)&anchor_color, CMT_A_COLOR, (void *)colorstr}, {"image_color", P_COLOR, PI_SEL_C, (void *)&image_color, CMT_I_COLOR, (void *)colorstr}, {"form_color", P_COLOR, PI_SEL_C, (void *)&form_color, CMT_F_COLOR, (void *)colorstr}, #ifdef USE_BG_COLOR {"mark_color", P_COLOR, PI_SEL_C, (void *)&mark_color, CMT_MARK_COLOR, (void *)colorstr}, {"bg_color", P_COLOR, PI_SEL_C, (void *)&bg_color, CMT_BG_COLOR, (void *)colorstr}, #endif /* USE_BG_COLOR */ {"active_style", P_INT, PI_ONOFF, (void *)&useActiveColor, CMT_ACTIVE_STYLE, NULL}, {"active_color", P_COLOR, PI_SEL_C, (void *)&active_color, CMT_C_COLOR, (void *)colorstr}, {"visited_anchor", P_INT, PI_ONOFF, (void *)&useVisitedColor, CMT_VISITED_ANCHOR, NULL}, {"visited_color", P_COLOR, PI_SEL_C, (void *)&visited_color, CMT_V_COLOR, (void *)colorstr}, {NULL, 0, 0, NULL, NULL, NULL}, }; #endif /* USE_COLOR */ struct param_ptr params3[] = { {"pagerline", P_NZINT, PI_TEXT, (void *)&PagerMax, CMT_PAGERLINE, NULL}, #ifdef USE_HISTORY {"use_history", P_INT, PI_ONOFF, (void *)&UseHistory, CMT_HISTORY, NULL}, {"history", P_INT, PI_TEXT, (void *)&URLHistSize, CMT_HISTSIZE, NULL}, {"save_hist", P_INT, PI_ONOFF, (void *)&SaveURLHist, CMT_SAVEHIST, NULL}, #endif /* USE_HISTORY */ {"confirm_qq", P_INT, PI_ONOFF, (void *)&confirm_on_quit, CMT_CONFIRM_QQ, NULL}, {"close_tab_back", P_INT, PI_ONOFF, (void *)&close_tab_back, CMT_CLOSE_TAB_BACK, NULL}, #ifdef USE_MARK {"mark", P_INT, PI_ONOFF, (void *)&use_mark, CMT_USE_MARK, NULL}, #endif {"emacs_like_lineedit", P_INT, PI_ONOFF, (void *)&emacs_like_lineedit, CMT_EMACS_LIKE_LINEEDIT, NULL}, {"vi_prec_num", P_INT, PI_ONOFF, (void *)&vi_prec_num, CMT_VI_PREC_NUM, NULL}, {"mark_all_pages", P_INT, PI_ONOFF, (void *)&MarkAllPages, CMT_MARK_ALL_PAGES, NULL}, {"wrap_search", P_INT, PI_ONOFF, (void *)&WrapDefault, CMT_WRAP, NULL}, {"ignorecase_search", P_INT, PI_ONOFF, (void *)&IgnoreCase, CMT_IGNORE_CASE, NULL}, #ifdef USE_MIGEMO {"use_migemo", P_INT, PI_ONOFF, (void *)&use_migemo, CMT_USE_MIGEMO, NULL}, {"migemo_command", P_STRING, PI_TEXT, (void *)&migemo_command, CMT_MIGEMO_COMMAND, NULL}, #endif /* USE_MIGEMO */ #ifdef USE_MOUSE {"use_mouse", P_INT, PI_ONOFF, (void *)&use_mouse, CMT_MOUSE, NULL}, {"reverse_mouse", P_INT, PI_ONOFF, (void *)&reverse_mouse, CMT_REVERSE_MOUSE, NULL}, {"relative_wheel_scroll", P_INT, PI_SEL_C, (void *)&relative_wheel_scroll, CMT_RELATIVE_WHEEL_SCROLL, (void *)wheelmode}, {"relative_wheel_scroll_ratio", P_INT, PI_TEXT, (void *)&relative_wheel_scroll_ratio, CMT_RELATIVE_WHEEL_SCROLL_RATIO, NULL}, {"fixed_wheel_scroll_count", P_INT, PI_TEXT, (void *)&fixed_wheel_scroll_count, CMT_FIXED_WHEEL_SCROLL_COUNT, NULL}, #endif /* USE_MOUSE */ {"clear_buffer", P_INT, PI_ONOFF, (void *)&clear_buffer, CMT_CLEAR_BUF, NULL}, {"decode_cte", P_CHARINT, PI_ONOFF, (void *)&DecodeCTE, CMT_DECODE_CTE, NULL}, {"auto_uncompress", P_CHARINT, PI_ONOFF, (void *)&AutoUncompress, CMT_AUTO_UNCOMPRESS, NULL}, {"preserve_timestamp", P_CHARINT, PI_ONOFF, (void *)&PreserveTimestamp, CMT_PRESERVE_TIMESTAMP, NULL}, {"keymap_file", P_STRING, PI_TEXT, (void *)&keymap_file, CMT_KEYMAP_FILE, NULL}, {NULL, 0, 0, NULL, NULL, NULL}, }; struct param_ptr params4[] = { {"use_proxy", P_CHARINT, PI_ONOFF, (void *)&use_proxy, CMT_USE_PROXY, NULL}, {"http_proxy", P_STRING, PI_TEXT, (void *)&HTTP_proxy, CMT_HTTP_PROXY, NULL}, #ifdef USE_SSL {"https_proxy", P_STRING, PI_TEXT, (void *)&HTTPS_proxy, CMT_HTTPS_PROXY, NULL}, #endif /* USE_SSL */ #ifdef USE_GOPHER {"gopher_proxy", P_STRING, PI_TEXT, (void *)&GOPHER_proxy, CMT_GOPHER_PROXY, NULL}, #endif /* USE_GOPHER */ {"ftp_proxy", P_STRING, PI_TEXT, (void *)&FTP_proxy, CMT_FTP_PROXY, NULL}, {"no_proxy", P_STRING, PI_TEXT, (void *)&NO_proxy, CMT_NO_PROXY, NULL}, {"noproxy_netaddr", P_INT, PI_ONOFF, (void *)&NOproxy_netaddr, CMT_NOPROXY_NETADDR, NULL}, {"no_cache", P_CHARINT, PI_ONOFF, (void *)&NoCache, CMT_NO_CACHE, NULL}, {NULL, 0, 0, NULL, NULL, NULL}, }; struct param_ptr params5[] = { {"document_root", P_STRING, PI_TEXT, (void *)&document_root, CMT_DROOT, NULL}, {"personal_document_root", P_STRING, PI_TEXT, (void *)&personal_document_root, CMT_PDROOT, NULL}, {"cgi_bin", P_STRING, PI_TEXT, (void *)&cgi_bin, CMT_CGIBIN, NULL}, {"index_file", P_STRING, PI_TEXT, (void *)&index_file, CMT_IFILE, NULL}, {NULL, 0, 0, NULL, NULL, NULL}, }; struct param_ptr params6[] = { {"mime_types", P_STRING, PI_TEXT, (void *)&mimetypes_files, CMT_MIMETYPES, NULL}, {"mailcap", P_STRING, PI_TEXT, (void *)&mailcap_files, CMT_MAILCAP, NULL}, #ifdef USE_EXTERNAL_URI_LOADER {"urimethodmap", P_STRING, PI_TEXT, (void *)&urimethodmap_files, CMT_URIMETHODMAP, NULL}, #endif {"editor", P_STRING, PI_TEXT, (void *)&Editor, CMT_EDITOR, NULL}, {"mailto_options", P_INT, PI_SEL_C, (void *)&MailtoOptions, CMT_MAILTO_OPTIONS, (void *)mailtooptionsstr}, {"mailer", P_STRING, PI_TEXT, (void *)&Mailer, CMT_MAILER, NULL}, {"extbrowser", P_STRING, PI_TEXT, (void *)&ExtBrowser, CMT_EXTBRZ, NULL}, {"extbrowser2", P_STRING, PI_TEXT, (void *)&ExtBrowser2, CMT_EXTBRZ2, NULL}, {"extbrowser3", P_STRING, PI_TEXT, (void *)&ExtBrowser3, CMT_EXTBRZ3, NULL}, {"extbrowser4", P_STRING, PI_TEXT, (void *)&ExtBrowser4, CMT_EXTBRZ4, NULL}, {"extbrowser5", P_STRING, PI_TEXT, (void *)&ExtBrowser5, CMT_EXTBRZ5, NULL}, {"extbrowser6", P_STRING, PI_TEXT, (void *)&ExtBrowser6, CMT_EXTBRZ6, NULL}, {"extbrowser7", P_STRING, PI_TEXT, (void *)&ExtBrowser7, CMT_EXTBRZ7, NULL}, {"extbrowser8", P_STRING, PI_TEXT, (void *)&ExtBrowser8, CMT_EXTBRZ8, NULL}, {"extbrowser9", P_STRING, PI_TEXT, (void *)&ExtBrowser9, CMT_EXTBRZ9, NULL}, {"bgextviewer", P_INT, PI_ONOFF, (void *)&BackgroundExtViewer, CMT_BGEXTVIEW, NULL}, {"use_lessopen", P_INT, PI_ONOFF, (void *)&use_lessopen, CMT_USE_LESSOPEN, NULL}, {NULL, 0, 0, NULL, NULL, NULL}, }; #ifdef USE_SSL struct param_ptr params7[] = { {"ssl_forbid_method", P_STRING, PI_TEXT, (void *)&ssl_forbid_method, CMT_SSL_FORBID_METHOD, NULL}, #ifdef USE_SSL_VERIFY {"ssl_verify_server", P_INT, PI_ONOFF, (void *)&ssl_verify_server, CMT_SSL_VERIFY_SERVER, NULL}, {"ssl_cert_file", P_SSLPATH, PI_TEXT, (void *)&ssl_cert_file, CMT_SSL_CERT_FILE, NULL}, {"ssl_key_file", P_SSLPATH, PI_TEXT, (void *)&ssl_key_file, CMT_SSL_KEY_FILE, NULL}, {"ssl_ca_path", P_SSLPATH, PI_TEXT, (void *)&ssl_ca_path, CMT_SSL_CA_PATH, NULL}, {"ssl_ca_file", P_SSLPATH, PI_TEXT, (void *)&ssl_ca_file, CMT_SSL_CA_FILE, NULL}, #endif /* USE_SSL_VERIFY */ {NULL, 0, 0, NULL, NULL, NULL}, }; #endif /* USE_SSL */ #ifdef USE_COOKIE struct param_ptr params8[] = { {"use_cookie", P_INT, PI_ONOFF, (void *)&use_cookie, CMT_USECOOKIE, NULL}, {"show_cookie", P_INT, PI_ONOFF, (void *)&show_cookie, CMT_SHOWCOOKIE, NULL}, {"accept_cookie", P_INT, PI_ONOFF, (void *)&accept_cookie, CMT_ACCEPTCOOKIE, NULL}, {"accept_bad_cookie", P_INT, PI_SEL_C, (void *)&accept_bad_cookie, CMT_ACCEPTBADCOOKIE, (void *)badcookiestr}, {"cookie_reject_domains", P_STRING, PI_TEXT, (void *)&cookie_reject_domains, CMT_COOKIE_REJECT_DOMAINS, NULL}, {"cookie_accept_domains", P_STRING, PI_TEXT, (void *)&cookie_accept_domains, CMT_COOKIE_ACCEPT_DOMAINS, NULL}, {"cookie_avoid_wrong_number_of_dots", P_STRING, PI_TEXT, (void *)&cookie_avoid_wrong_number_of_dots, CMT_COOKIE_AVOID_WONG_NUMBER_OF_DOTS, NULL}, {NULL, 0, 0, NULL, NULL, NULL}, }; #endif struct param_ptr params9[] = { {"passwd_file", P_STRING, PI_TEXT, (void *)&passwd_file, CMT_PASSWDFILE, NULL}, {"disable_secret_security_check", P_INT, PI_ONOFF, (void *)&disable_secret_security_check, CMT_DISABLE_SECRET_SECURITY_CHECK, NULL}, {"ftppasswd", P_STRING, PI_TEXT, (void *)&ftppasswd, CMT_FTPPASS, NULL}, {"ftppass_hostnamegen", P_INT, PI_ONOFF, (void *)&ftppass_hostnamegen, CMT_FTPPASS_HOSTNAMEGEN, NULL}, {"pre_form_file", P_STRING, PI_TEXT, (void *)&pre_form_file, CMT_PRE_FORM_FILE, NULL}, {"siteconf_file", P_STRING, PI_TEXT, (void *)&siteconf_file, CMT_SITECONF_FILE, NULL}, {"user_agent", P_STRING, PI_TEXT, (void *)&UserAgent, CMT_USERAGENT, NULL}, {"no_referer", P_INT, PI_ONOFF, (void *)&NoSendReferer, CMT_NOSENDREFERER, NULL}, {"accept_language", P_STRING, PI_TEXT, (void *)&AcceptLang, CMT_ACCEPTLANG, NULL}, {"accept_encoding", P_STRING, PI_TEXT, (void *)&AcceptEncoding, CMT_ACCEPTENCODING, NULL}, {"accept_media", P_STRING, PI_TEXT, (void *)&AcceptMedia, CMT_ACCEPTMEDIA, NULL}, {"argv_is_url", P_CHARINT, PI_ONOFF, (void *)&ArgvIsURL, CMT_ARGV_IS_URL, NULL}, {"retry_http", P_INT, PI_ONOFF, (void *)&retryAsHttp, CMT_RETRY_HTTP, NULL}, {"default_url", P_INT, PI_SEL_C, (void *)&DefaultURLString, CMT_DEFAULT_URL, (void *)defaulturls}, {"follow_redirection", P_INT, PI_TEXT, &FollowRedirection, CMT_FOLLOW_REDIRECTION, NULL}, {"meta_refresh", P_CHARINT, PI_ONOFF, (void *)&MetaRefresh, CMT_META_REFRESH, NULL}, #ifdef INET6 {"dns_order", P_INT, PI_SEL_C, (void *)&DNS_order, CMT_DNS_ORDER, (void *)dnsorders}, #endif /* INET6 */ #ifdef USE_NNTP {"nntpserver", P_STRING, PI_TEXT, (void *)&NNTP_server, CMT_NNTP_SERVER, NULL}, {"nntpmode", P_STRING, PI_TEXT, (void *)&NNTP_mode, CMT_NNTP_MODE, NULL}, {"max_news", P_INT, PI_TEXT, (void *)&MaxNewsMessage, CMT_MAX_NEWS, NULL}, #endif {NULL, 0, 0, NULL, NULL, NULL}, }; #ifdef USE_M17N struct param_ptr params10[] = { {"display_charset", P_CODE, PI_CODE, (void *)&DisplayCharset, CMT_DISPLAY_CHARSET, (void *)&display_charset_str}, {"document_charset", P_CODE, PI_CODE, (void *)&DocumentCharset, CMT_DOCUMENT_CHARSET, (void *)&document_charset_str}, {"auto_detect", P_CHARINT, PI_SEL_C, (void *)&WcOption.auto_detect, CMT_AUTO_DETECT, (void *)auto_detect_str}, {"system_charset", P_CODE, PI_CODE, (void *)&SystemCharset, CMT_SYSTEM_CHARSET, (void *)&system_charset_str}, {"follow_locale", P_CHARINT, PI_ONOFF, (void *)&FollowLocale, CMT_FOLLOW_LOCALE, NULL}, {"ext_halfdump", P_CHARINT, PI_ONOFF, (void *)&ExtHalfdump, CMT_EXT_HALFDUMP, NULL}, {"use_wide", P_CHARINT, PI_ONOFF, (void *)&WcOption.use_wide, CMT_USE_WIDE, NULL}, {"use_combining", P_CHARINT, PI_ONOFF, (void *)&WcOption.use_combining, CMT_USE_COMBINING, NULL}, #ifdef USE_UNICODE {"east_asian_width", P_CHARINT, PI_ONOFF, (void *)&WcOption.east_asian_width, CMT_EAST_ASIAN_WIDTH, NULL}, {"use_language_tag", P_CHARINT, PI_ONOFF, (void *)&WcOption.use_language_tag, CMT_USE_LANGUAGE_TAG, NULL}, {"ucs_conv", P_CHARINT, PI_ONOFF, (void *)&WcOption.ucs_conv, CMT_UCS_CONV, NULL}, #endif {"pre_conv", P_CHARINT, PI_ONOFF, (void *)&WcOption.pre_conv, CMT_PRE_CONV, NULL}, {"search_conv", P_CHARINT, PI_ONOFF, (void *)&SearchConv, CMT_SEARCH_CONV, NULL}, {"fix_width_conv", P_CHARINT, PI_ONOFF, (void *)&WcOption.fix_width_conv, CMT_FIX_WIDTH_CONV, NULL}, #ifdef USE_UNICODE {"use_gb12345_map", P_CHARINT, PI_ONOFF, (void *)&WcOption.use_gb12345_map, CMT_USE_GB12345_MAP, NULL}, #endif {"use_jisx0201", P_CHARINT, PI_ONOFF, (void *)&WcOption.use_jisx0201, CMT_USE_JISX0201, NULL}, {"use_jisc6226", P_CHARINT, PI_ONOFF, (void *)&WcOption.use_jisc6226, CMT_USE_JISC6226, NULL}, {"use_jisx0201k", P_CHARINT, PI_ONOFF, (void *)&WcOption.use_jisx0201k, CMT_USE_JISX0201K, NULL}, {"use_jisx0212", P_CHARINT, PI_ONOFF, (void *)&WcOption.use_jisx0212, CMT_USE_JISX0212, NULL}, {"use_jisx0213", P_CHARINT, PI_ONOFF, (void *)&WcOption.use_jisx0213, CMT_USE_JISX0213, NULL}, {"strict_iso2022", P_CHARINT, PI_ONOFF, (void *)&WcOption.strict_iso2022, CMT_STRICT_ISO2022, NULL}, #ifdef USE_UNICODE {"gb18030_as_ucs", P_CHARINT, PI_ONOFF, (void *)&WcOption.gb18030_as_ucs, CMT_GB18030_AS_UCS, NULL}, #endif {"simple_preserve_space", P_CHARINT, PI_ONOFF, (void *)&SimplePreserveSpace, CMT_SIMPLE_PRESERVE_SPACE, NULL}, {NULL, 0, 0, NULL, NULL, NULL}, }; #endif struct param_section sections[] = { {N_("Display Settings"), params1}, #ifdef USE_COLOR {N_("Color Settings"), params2}, #endif /* USE_COLOR */ {N_("Miscellaneous Settings"), params3}, {N_("Directory Settings"), params5}, {N_("External Program Settings"), params6}, {N_("Network Settings"), params9}, {N_("Proxy Settings"), params4}, #ifdef USE_SSL {N_("SSL Settings"), params7}, #endif #ifdef USE_COOKIE {N_("Cookie Settings"), params8}, #endif #ifdef USE_M17N {N_("Charset Settings"), params10}, #endif {NULL, NULL} }; static Str to_str(struct param_ptr *p); static int compare_table(struct rc_search_table *a, struct rc_search_table *b) { return strcmp(a->param->name, b->param->name); } static void create_option_search_table() { int i, j, k; int diff1, diff2; char *p, *q; /* count table size */ RC_table_size = 0; for (j = 0; sections[j].name != NULL; j++) { i = 0; while (sections[j].params[i].name) { i++; RC_table_size++; } } RC_search_table = New_N(struct rc_search_table, RC_table_size); k = 0; for (j = 0; sections[j].name != NULL; j++) { i = 0; while (sections[j].params[i].name) { RC_search_table[k].param = &sections[j].params[i]; k++; i++; } } qsort(RC_search_table, RC_table_size, sizeof(struct rc_search_table), (int (*)(const void *, const void *))compare_table); diff2 = 0; for (i = 0; i < RC_table_size - 1; i++) { p = RC_search_table[i].param->name; q = RC_search_table[i + 1].param->name; for (j = 0; p[j] != '\0' && q[j] != '\0' && p[j] == q[j]; j++) ; diff1 = j; if (diff1 > diff2) RC_search_table[i].uniq_pos = diff1 + 1; else RC_search_table[i].uniq_pos = diff2 + 1; diff2 = diff1; } } struct param_ptr * search_param(char *name) { size_t b, e, i; int cmp; int len = strlen(name); for (b = 0, e = RC_table_size - 1; b <= e;) { i = (b + e) / 2; cmp = strncmp(name, RC_search_table[i].param->name, len); if (!cmp) { if (len >= RC_search_table[i].uniq_pos) { return RC_search_table[i].param; } else { while ((cmp = strcmp(name, RC_search_table[i].param->name)) <= 0) if (!cmp) return RC_search_table[i].param; else if (i == 0) return NULL; else i--; /* ambiguous */ return NULL; } } else if (cmp < 0) { if (i == 0) return NULL; e = i - 1; } else b = i + 1; } return NULL; } /* show parameter with bad options invokation */ void show_params(FILE * fp) { int i, j, l; const char *t = ""; char *cmt; #ifdef USE_M17N #ifdef ENABLE_NLS OptionCharset = SystemCharset; /* FIXME */ #endif #endif fputs("\nconfiguration parameters\n", fp); for (j = 0; sections[j].name != NULL; j++) { #ifdef USE_M17N if (!OptionEncode) cmt = wc_conv(_(sections[j].name), OptionCharset, InnerCharset)->ptr; else #endif cmt = sections[j].name; fprintf(fp, " section[%d]: %s\n", j, conv_to_system(cmt)); i = 0; while (sections[j].params[i].name) { switch (sections[j].params[i].type) { case P_INT: case P_SHORT: case P_CHARINT: case P_NZINT: t = (sections[j].params[i].inputtype == PI_ONOFF) ? "bool" : "number"; break; case P_CHAR: t = "char"; break; case P_STRING: t = "string"; break; #if defined(USE_SSL) && defined(USE_SSL_VERIFY) case P_SSLPATH: t = "path"; break; #endif #ifdef USE_COLOR case P_COLOR: t = "color"; break; #endif #ifdef USE_M17N case P_CODE: t = "charset"; break; #endif case P_PIXELS: t = "number"; break; case P_SCALE: t = "percent"; break; } #ifdef USE_M17N if (!OptionEncode) cmt = wc_conv(_(sections[j].params[i].comment), OptionCharset, InnerCharset)->ptr; else #endif cmt = sections[j].params[i].comment; l = 30 - (strlen(sections[j].params[i].name) + strlen(t)); if (l < 0) l = 1; fprintf(fp, " -o %s=<%s>%*s%s\n", sections[j].params[i].name, t, l, " ", conv_to_system(cmt)); i++; } } } int str_to_bool(char *value, int old) { if (value == NULL) return 1; switch (TOLOWER(*value)) { case '0': case 'f': /* false */ case 'n': /* no */ case 'u': /* undef */ return 0; case 'o': if (TOLOWER(value[1]) == 'f') /* off */ return 0; return 1; /* on */ case 't': if (TOLOWER(value[1]) == 'o') /* toggle */ return !old; return 1; /* true */ case '!': case 'r': /* reverse */ case 'x': /* exchange */ return !old; } return 1; } #ifdef USE_COLOR static int str_to_color(char *value) { if (value == NULL) return 8; /* terminal */ switch (TOLOWER(*value)) { case '0': return 0; /* black */ case '1': case 'r': return 1; /* red */ case '2': case 'g': return 2; /* green */ case '3': case 'y': return 3; /* yellow */ case '4': return 4; /* blue */ case '5': case 'm': return 5; /* magenta */ case '6': case 'c': return 6; /* cyan */ case '7': case 'w': return 7; /* white */ case '8': case 't': return 8; /* terminal */ case 'b': if (!strncasecmp(value, "blu", 3)) return 4; /* blue */ else return 0; /* black */ } return 8; /* terminal */ } #endif static int set_param(char *name, char *value) { struct param_ptr *p; double ppc; if (value == NULL) return 0; p = search_param(name); if (p == NULL) return 0; switch (p->type) { case P_INT: if (atoi(value) >= 0) *(int *)p->varptr = (p->inputtype == PI_ONOFF) ? str_to_bool(value, *(int *)p->varptr) : atoi(value); break; case P_NZINT: if (atoi(value) > 0) *(int *)p->varptr = atoi(value); break; case P_SHORT: *(short *)p->varptr = (p->inputtype == PI_ONOFF) ? str_to_bool(value, *(short *)p->varptr) : atoi(value); break; case P_CHARINT: *(char *)p->varptr = (p->inputtype == PI_ONOFF) ? str_to_bool(value, *(char *)p->varptr) : atoi(value); break; case P_CHAR: *(char *)p->varptr = value[0]; break; case P_STRING: *(char **)p->varptr = value; break; #if defined(USE_SSL) && defined(USE_SSL_VERIFY) case P_SSLPATH: if (value != NULL && value[0] != '\0') *(char **)p->varptr = rcFile(value); else *(char **)p->varptr = NULL; ssl_path_modified = 1; break; #endif #ifdef USE_COLOR case P_COLOR: *(int *)p->varptr = str_to_color(value); break; #endif #ifdef USE_M17N case P_CODE: *(wc_ces *) p->varptr = wc_guess_charset_short(value, *(wc_ces *) p->varptr); break; #endif case P_PIXELS: ppc = atof(value); if (ppc >= MINIMUM_PIXEL_PER_CHAR && ppc <= MAXIMUM_PIXEL_PER_CHAR * 2) *(double *)p->varptr = ppc; break; case P_SCALE: ppc = atof(value); if (ppc >= 10 && ppc <= 1000) *(double *)p->varptr = ppc; break; } return 1; } int set_param_option(char *option) { Str tmp = Strnew(); char *p = option, *q; while (*p && !IS_SPACE(*p) && *p != '=') Strcat_char(tmp, *p++); while (*p && IS_SPACE(*p)) p++; if (*p == '=') { p++; while (*p && IS_SPACE(*p)) p++; } Strlower(tmp); if (set_param(tmp->ptr, p)) goto option_assigned; q = tmp->ptr; if (!strncmp(q, "no", 2)) { /* -o noxxx, -o no-xxx, -o no_xxx */ q += 2; if (*q == '-' || *q == '_') q++; } else if (tmp->ptr[0] == '-') /* -o -xxx */ q++; else return 0; if (set_param(q, "0")) goto option_assigned; return 0; option_assigned: return 1; } char * get_param_option(char *name) { struct param_ptr *p; p = search_param(name); return p ? to_str(p)->ptr : NULL; } static void interpret_rc(FILE * f) { Str line; Str tmp; char *p; for (;;) { line = Strfgets(f); if (line->length == 0) /* end of file */ break; Strchop(line); if (line->length == 0) /* blank line */ continue; Strremovefirstspaces(line); if (line->ptr[0] == '#') /* comment */ continue; tmp = Strnew(); p = line->ptr; while (*p && !IS_SPACE(*p)) Strcat_char(tmp, *p++); while (*p && IS_SPACE(*p)) p++; Strlower(tmp); set_param(tmp->ptr, p); } } void parse_proxy() { if (non_null(HTTP_proxy)) parseURL(HTTP_proxy, &HTTP_proxy_parsed, NULL); #ifdef USE_SSL if (non_null(HTTPS_proxy)) parseURL(HTTPS_proxy, &HTTPS_proxy_parsed, NULL); #endif /* USE_SSL */ #ifdef USE_GOPHER if (non_null(GOPHER_proxy)) parseURL(GOPHER_proxy, &GOPHER_proxy_parsed, NULL); #endif if (non_null(FTP_proxy)) parseURL(FTP_proxy, &FTP_proxy_parsed, NULL); if (non_null(NO_proxy)) set_no_proxy(NO_proxy); } #ifdef USE_COOKIE void parse_cookie() { if (non_null(cookie_reject_domains)) Cookie_reject_domains = make_domain_list(cookie_reject_domains); if (non_null(cookie_accept_domains)) Cookie_accept_domains = make_domain_list(cookie_accept_domains); if (non_null(cookie_avoid_wrong_number_of_dots)) Cookie_avoid_wrong_number_of_dots_domains = make_domain_list(cookie_avoid_wrong_number_of_dots); } #endif #ifdef __EMX__ static int do_mkdir(const char *dir, long mode) { char *r, abs[_MAX_PATH]; size_t n; _abspath(abs, rc_dir, _MAX_PATH); /* Translate '\\' to '/' */ if (!(n = strlen(abs))) return -1; if (*(r = abs + n - 1) == '/') /* Ignore tailing slash if it is */ *r = 0; return mkdir(abs, mode); } #else /* not __EMX__ */ #ifdef __MINGW32_VERSION #define do_mkdir(dir,mode) mkdir(dir) #else #define do_mkdir(dir,mode) mkdir(dir,mode) #endif /* not __MINW32_VERSION */ #endif /* not __EMX__ */ static void loadSiteconf(void); void sync_with_option(void) { if (PagerMax < LINES) PagerMax = LINES; WrapSearch = WrapDefault; parse_proxy(); #ifdef USE_COOKIE parse_cookie(); #endif initMailcap(); initMimeTypes(); #ifdef USE_EXTERNAL_URI_LOADER initURIMethods(); #endif #ifdef USE_MIGEMO init_migemo(); #endif #ifdef USE_IMAGE if (fmInitialized && displayImage) initImage(); #else displayImage = FALSE; /* XXX */ #endif loadPasswd(); loadPreForm(); loadSiteconf(); if (AcceptLang == NULL || *AcceptLang == '\0') { /* TRANSLATORS: * AcceptLang default: this is used in Accept-Language: HTTP request * header. For example, ja.po should translate it as * "ja;q=1.0, en;q=0.5" like that. */ AcceptLang = _("en;q=1.0"); } if (AcceptEncoding == NULL || *AcceptEncoding == '\0') AcceptEncoding = acceptableEncoding(); if (AcceptMedia == NULL || *AcceptMedia == '\0') AcceptMedia = acceptableMimeTypes(); #ifdef USE_UNICODE update_utf8_symbol(); #endif if (fmInitialized) { initKeymap(FALSE); #ifdef USE_MOUSE initMouseAction(); #endif /* MOUSE */ #ifdef USE_MENU initMenu(); #endif /* MENU */ } } void init_rc(void) { int i; struct stat st; FILE *f; if (rc_dir != NULL) goto open_rc; rc_dir = expandPath(RC_DIR); i = strlen(rc_dir); if (i > 1 && rc_dir[i - 1] == '/') rc_dir[i - 1] = '\0'; #ifdef USE_M17N display_charset_str = wc_get_ces_list(); document_charset_str = display_charset_str; system_charset_str = display_charset_str; #endif if (stat(rc_dir, &st) < 0) { if (errno == ENOENT) { /* no directory */ if (do_mkdir(rc_dir, 0700) < 0) { /* fprintf(stderr, "Can't create config directory (%s)!\n", rc_dir); */ goto rc_dir_err; } else { stat(rc_dir, &st); } } else { /* fprintf(stderr, "Can't open config directory (%s)!\n", rc_dir); */ goto rc_dir_err; } } if (!S_ISDIR(st.st_mode)) { /* not a directory */ /* fprintf(stderr, "%s is not a directory!\n", rc_dir); */ goto rc_dir_err; } if (!(st.st_mode & S_IWUSR)) { /* fprintf(stderr, "%s is not writable!\n", rc_dir); */ goto rc_dir_err; } no_rc_dir = FALSE; tmp_dir = rc_dir; if (config_file == NULL) config_file = rcFile(CONFIG_FILE); create_option_search_table(); open_rc: /* open config file */ if ((f = fopen(etcFile(W3MCONFIG), "rt")) != NULL) { interpret_rc(f); fclose(f); } if ((f = fopen(confFile(CONFIG_FILE), "rt")) != NULL) { interpret_rc(f); fclose(f); } if (config_file && (f = fopen(config_file, "rt")) != NULL) { interpret_rc(f); fclose(f); } return; rc_dir_err: no_rc_dir = TRUE; if (((tmp_dir = getenv("TMPDIR")) == NULL || *tmp_dir == '\0') && ((tmp_dir = getenv("TMP")) == NULL || *tmp_dir == '\0') && ((tmp_dir = getenv("TEMP")) == NULL || *tmp_dir == '\0')) tmp_dir = "/tmp"; create_option_search_table(); goto open_rc; } static char optionpanel_src1[] = "<html><head><title>Option Setting Panel</title></head><body>\ <h1 align=center>Option Setting Panel<br>(w3m version %s)</b></h1>\ <form method=post action=\"file:///$LIB/" W3MHELPERPANEL_CMDNAME "\">\ <input type=hidden name=mode value=panel>\ <input type=hidden name=cookie value=\"%s\">\ <input type=submit value=\"%s\">\ </form><br>\ <form method=internal action=option>"; static Str optionpanel_str = NULL; static Str to_str(struct param_ptr *p) { switch (p->type) { case P_INT: #ifdef USE_COLOR case P_COLOR: #endif #ifdef USE_M17N case P_CODE: return Sprintf("%d", (int)(*(wc_ces *) p->varptr)); #endif case P_NZINT: return Sprintf("%d", *(int *)p->varptr); case P_SHORT: return Sprintf("%d", *(short *)p->varptr); case P_CHARINT: return Sprintf("%d", *(char *)p->varptr); case P_CHAR: return Sprintf("%c", *(char *)p->varptr); case P_STRING: #if defined(USE_SSL) && defined(USE_SSL_VERIFY) case P_SSLPATH: #endif /* SystemCharset -> InnerCharset */ return Strnew_charp(conv_from_system(*(char **)p->varptr)); case P_PIXELS: case P_SCALE: return Sprintf("%g", *(double *)p->varptr); } /* not reached */ return NULL; } Buffer * load_option_panel(void) { Str src; struct param_ptr *p; struct sel_c *s; #ifdef USE_M17N wc_ces_list *c; #endif int x, i; Str tmp; Buffer *buf; if (optionpanel_str == NULL) optionpanel_str = Sprintf(optionpanel_src1, w3m_version, html_quote(localCookie()->ptr), _(CMT_HELPER)); #ifdef USE_M17N #ifdef ENABLE_NLS OptionCharset = SystemCharset; /* FIXME */ #endif if (!OptionEncode) { optionpanel_str = wc_Str_conv(optionpanel_str, OptionCharset, InnerCharset); for (i = 0; sections[i].name != NULL; i++) { sections[i].name = wc_conv(_(sections[i].name), OptionCharset, InnerCharset)->ptr; for (p = sections[i].params; p->name; p++) { p->comment = wc_conv(_(p->comment), OptionCharset, InnerCharset)->ptr; if (p->inputtype == PI_SEL_C #ifdef USE_COLOR && p->select != colorstr #endif ) { for (s = (struct sel_c *)p->select; s->text != NULL; s++) { s->text = wc_conv(_(s->text), OptionCharset, InnerCharset)->ptr; } } } } #ifdef USE_COLOR for (s = colorstr; s->text; s++) s->text = wc_conv(_(s->text), OptionCharset, InnerCharset)->ptr; #endif OptionEncode = TRUE; } #endif src = Strdup(optionpanel_str); Strcat_charp(src, "<table><tr><td>"); for (i = 0; sections[i].name != NULL; i++) { Strcat_m_charp(src, "<h1>", sections[i].name, "</h1>", NULL); p = sections[i].params; Strcat_charp(src, "<table width=100% cellpadding=0>"); while (p->name) { Strcat_m_charp(src, "<tr><td>", p->comment, NULL); Strcat(src, Sprintf("</td><td width=%d>", (int)(28 * pixel_per_char))); switch (p->inputtype) { case PI_TEXT: Strcat_m_charp(src, "<input type=text name=", p->name, " value=\"", html_quote(to_str(p)->ptr), "\">", NULL); break; case PI_ONOFF: x = atoi(to_str(p)->ptr); Strcat_m_charp(src, "<input type=radio name=", p->name, " value=1", (x ? " checked" : ""), ">YES&nbsp;&nbsp;<input type=radio name=", p->name, " value=0", (x ? "" : " checked"), ">NO", NULL); break; case PI_SEL_C: tmp = to_str(p); Strcat_m_charp(src, "<select name=", p->name, ">", NULL); for (s = (struct sel_c *)p->select; s->text != NULL; s++) { Strcat_charp(src, "<option value="); Strcat(src, Sprintf("%s\n", s->cvalue)); if ((p->type != P_CHAR && s->value == atoi(tmp->ptr)) || (p->type == P_CHAR && (char)s->value == *(tmp->ptr))) Strcat_charp(src, " selected"); Strcat_char(src, '>'); Strcat_charp(src, s->text); } Strcat_charp(src, "</select>"); break; #ifdef USE_M17N case PI_CODE: tmp = to_str(p); Strcat_m_charp(src, "<select name=", p->name, ">", NULL); for (c = *(wc_ces_list **) p->select; c->desc != NULL; c++) { Strcat_charp(src, "<option value="); Strcat(src, Sprintf("%s\n", c->name)); if (c->id == atoi(tmp->ptr)) Strcat_charp(src, " selected"); Strcat_char(src, '>'); Strcat_charp(src, c->desc); } Strcat_charp(src, "</select>"); break; #endif } Strcat_charp(src, "</td></tr>\n"); p++; } Strcat_charp(src, "<tr><td></td><td><p><input type=submit value=\"OK\"></td></tr>"); Strcat_charp(src, "</table><hr width=50%>"); } Strcat_charp(src, "</table></form></body></html>"); buf = loadHTMLString(src); #ifdef USE_M17N if (buf) buf->document_charset = OptionCharset; #endif return buf; } void panel_set_option(struct parsed_tagarg *arg) { FILE *f = NULL; char *p; Str s = Strnew(), tmp; if (config_file == NULL) { disp_message("There's no config file... config not saved", FALSE); } else { f = fopen(config_file, "wt"); if (f == NULL) { disp_message("Can't write option!", FALSE); } } while (arg) { /* InnerCharset -> SystemCharset */ if (arg->value) { p = conv_to_system(arg->value); if (set_param(arg->arg, p)) { tmp = Sprintf("%s %s\n", arg->arg, p); Strcat(tmp, s); s = tmp; } } arg = arg->next; } if (f) { fputs(s->ptr, f); fclose(f); } sync_with_option(); backBf(); } char * rcFile(char *base) { if (base && (base[0] == '/' || (base[0] == '.' && (base[1] == '/' || (base[1] == '.' && base[2] == '/'))) || (base[0] == '~' && base[1] == '/'))) /* /file, ./file, ../file, ~/file */ return expandPath(base); return expandPath(Strnew_m_charp(rc_dir, "/", base, NULL)->ptr); } char * auxbinFile(char *base) { return expandPath(Strnew_m_charp(w3m_auxbin_dir(), "/", base, NULL)->ptr); } #if 0 /* not used */ char * libFile(char *base) { return expandPath(Strnew_m_charp(w3m_lib_dir(), "/", base, NULL)->ptr); } #endif char * etcFile(char *base) { return expandPath(Strnew_m_charp(w3m_etc_dir(), "/", base, NULL)->ptr); } char * confFile(char *base) { return expandPath(Strnew_m_charp(w3m_conf_dir(), "/", base, NULL)->ptr); } #ifndef USE_HELP_CGI char * helpFile(char *base) { return expandPath(Strnew_m_charp(w3m_help_dir(), "/", base, NULL)->ptr); } #endif /* siteconf */ /* * url "<url>"|/<re-url>/|m@<re-url>@i [exact] * substitute_url "<destination-url>" * url_charset <charset> * no_referer_from on|off * no_referer_to on|off * * The last match wins. */ struct siteconf_rec { struct siteconf_rec *next; char *url; Regex *re_url; int url_exact; unsigned char mask[(SCONF_N_FIELD + 7) >> 3]; char *substitute_url; #ifdef USE_M17N wc_ces url_charset; #endif int no_referer_from; int no_referer_to; }; #define SCONF_TEST(ent, f) ((ent)->mask[(f)>>3] & (1U<<((f)&7))) #define SCONF_SET(ent, f) ((ent)->mask[(f)>>3] |= (1U<<((f)&7))) #define SCONF_CLEAR(ent, f) ((ent)->mask[(f)>>3] &= ~(1U<<((f)&7))) static struct siteconf_rec *siteconf_head = NULL; static struct siteconf_rec *newSiteconfRec(void); static struct siteconf_rec * newSiteconfRec(void) { struct siteconf_rec *ent; ent = New(struct siteconf_rec); ent->next = NULL; ent->url = NULL; ent->re_url = NULL; ent->url_exact = FALSE; memset(ent->mask, 0, sizeof(ent->mask)); ent->substitute_url = NULL; #ifdef USE_M17N ent->url_charset = 0; #endif return ent; } static void loadSiteconf(void) { char *efname; FILE *fp; Str line; struct siteconf_rec *ent = NULL; siteconf_head = NULL; if (!siteconf_file) return; if ((efname = expandPath(siteconf_file)) == NULL) return; fp = fopen(efname, "r"); if (fp == NULL) return; while (line = Strfgets(fp), line->length > 0) { char *p, *s; Strchop(line); p = line->ptr; SKIP_BLANKS(p); if (*p == '#' || *p == '\0') continue; s = getWord(&p); /* The "url" begins a new record. */ if (strcmp(s, "url") == 0) { char *url, *opt; struct siteconf_rec *newent; /* First, register the current record. */ if (ent) { ent->next = siteconf_head; siteconf_head = ent; ent = NULL; } /* Second, create a new record. */ newent = newSiteconfRec(); url = getRegexWord((const char **)&p, &newent->re_url); opt = getWord(&p); SKIP_BLANKS(p); if (!newent->re_url) { ParsedURL pu; if (!url || !*url) continue; parseURL2(url, &pu, NULL); newent->url = parsedURL2Str(&pu)->ptr; } /* If we have an extra or unknown option, ignore this record * for future extensions. */ if (strcmp(opt, "exact") == 0) { newent->url_exact = TRUE; } else if (*opt != 0) continue; if (*p) continue; ent = newent; continue; } /* If the current record is broken, skip to the next "url". */ if (!ent) continue; /* Fill the new record. */ if (strcmp(s, "substitute_url") == 0) { ent->substitute_url = getQWord(&p); SCONF_SET(ent, SCONF_SUBSTITUTE_URL); } #ifdef USE_M17N else if (strcmp(s, "url_charset") == 0) { char *charset = getWord(&p); ent->url_charset = (charset && *charset) ? wc_charset_to_ces(charset) : 0; SCONF_SET(ent, SCONF_URL_CHARSET); } #endif /* USE_M17N */ else if (strcmp(s, "no_referer_from") == 0) { ent->no_referer_from = str_to_bool(getWord(&p), 0); SCONF_SET(ent, SCONF_NO_REFERER_FROM); } else if (strcmp(s, "no_referer_to") == 0) { ent->no_referer_to = str_to_bool(getWord(&p), 0); SCONF_SET(ent, SCONF_NO_REFERER_TO); } } if (ent) { ent->next = siteconf_head; siteconf_head = ent; ent = NULL; } fclose(fp); } const void * querySiteconf(const ParsedURL *query_pu, int field) { const struct siteconf_rec *ent; Str u; char *firstp, *lastp; if (field < 0 || field >= SCONF_N_FIELD) return NULL; if (!query_pu || IS_EMPTY_PARSED_URL(query_pu)) return NULL; u = parsedURL2Str((ParsedURL *)query_pu); if (u->length == 0) return NULL; for (ent = siteconf_head; ent; ent = ent->next) { if (!SCONF_TEST(ent, field)) continue; if (ent->re_url) { if (RegexMatch(ent->re_url, u->ptr, u->length, 1)) { MatchedPosition(ent->re_url, &firstp, &lastp); if (!ent->url_exact) goto url_found; if (firstp != u->ptr || lastp == firstp) continue; if (*lastp == 0 || *lastp == '?' || *(lastp - 1) == '?' || *lastp == '#' || *(lastp - 1) == '#') goto url_found; } } else { int matchlen = strmatchlen(ent->url, u->ptr, u->length); if (matchlen == 0 || ent->url[matchlen] != 0) continue; firstp = u->ptr; lastp = u->ptr + matchlen; if (*lastp == 0 || *lastp == '?' || *(lastp - 1) == '?' || *lastp == '#' || *(lastp - 1) == '#') goto url_found; if (!ent->url_exact && (*lastp == '/' || *(lastp - 1) == '/')) goto url_found; } } return NULL; url_found: switch (field) { case SCONF_SUBSTITUTE_URL: if (ent->substitute_url && *ent->substitute_url) { Str tmp = Strnew_charp_n(u->ptr, firstp - u->ptr); Strcat_charp(tmp, ent->substitute_url); Strcat_charp(tmp, lastp); return tmp->ptr; } return NULL; #ifdef USE_M17N case SCONF_URL_CHARSET: return &ent->url_charset; #endif case SCONF_NO_REFERER_FROM: return &ent->no_referer_from; case SCONF_NO_REFERER_TO: return &ent->no_referer_to; } return NULL; }
./CrossVul/dataset_final_sorted/CWE-59/c/bad_589_5
crossvul-cpp_data_good_3263_0
/* * ProFTPD - FTP server daemon * Copyright (c) 1997, 1998 Public Flood Software * Copyright (c) 1999, 2000 MacGyver aka Habeeb J. Dihu <macgyver@tos.net> * Copyright (c) 2001-2017 The ProFTPD Project team * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Suite 500, Boston, MA 02110-1335, USA. * * As a special exemption, Public Flood Software/MacGyver aka Habeeb J. Dihu * and other respective copyright holders give permission to link this program * with OpenSSL, and distribute the resulting executable, without including * the source code for OpenSSL in the source distribution. */ /* Authentication module for ProFTPD */ #include "conf.h" #include "privs.h" #ifdef HAVE_USERSEC_H # include <usersec.h> #endif #ifdef HAVE_SYS_AUDIT_H # include <sys/audit.h> #endif extern pid_t mpid; module auth_module; #ifdef PR_USE_LASTLOG static unsigned char lastlog = FALSE; #endif /* PR_USE_LASTLOG */ static unsigned char mkhome = FALSE; static unsigned char authenticated_without_pass = FALSE; static int TimeoutLogin = PR_TUNABLE_TIMEOUTLOGIN; static int logged_in = FALSE; static int auth_anon_allow_robots = FALSE; static int auth_anon_allow_robots_enabled = FALSE; static int auth_client_connected = FALSE; static unsigned int auth_tries = 0; static char *auth_pass_resp_code = R_230; static pr_fh_t *displaylogin_fh = NULL; static int TimeoutSession = 0; static int saw_first_user_cmd = FALSE; static const char *timing_channel = "timing"; static int auth_count_scoreboard(cmd_rec *, const char *); static int auth_scan_scoreboard(void); static int auth_sess_init(void); /* auth_cmd_chk_cb() is hooked into the main server's auth_hook function, * so that we can deny all commands until authentication is complete. * * Note: Once this function returns true (i.e. client has authenticated), * it will ALWAYS return true. At least until REIN is implemented. Thus * we have a flag for such a situation, to save on redundant lookups for * the "authenticated" record. */ static int auth_have_authenticated = FALSE; static int auth_cmd_chk_cb(cmd_rec *cmd) { if (auth_have_authenticated == FALSE) { unsigned char *authd; authd = get_param_ptr(cmd->server->conf, "authenticated", FALSE); if (authd == NULL || *authd == FALSE) { pr_response_send(R_530, _("Please login with USER and PASS")); return FALSE; } auth_have_authenticated = TRUE; } return TRUE; } static int auth_login_timeout_cb(CALLBACK_FRAME) { pr_response_send_async(R_421, _("Login timeout (%d %s): closing control connection"), TimeoutLogin, TimeoutLogin != 1 ? "seconds" : "second"); /* It's possible that any listeners of this event might terminate the * session process themselves (e.g. mod_ban). So write out that the * TimeoutLogin has been exceeded to the log here, in addition to the * scheduled session exit message. */ pr_log_pri(PR_LOG_INFO, "%s", "Login timeout exceeded, disconnected"); pr_event_generate("core.timeout-login", NULL); pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_TIMEOUT, "TimeoutLogin"); /* Do not restart the timer (should never be reached). */ return 0; } static int auth_session_timeout_cb(CALLBACK_FRAME) { pr_event_generate("core.timeout-session", NULL); pr_response_send_async(R_421, _("Session Timeout (%d seconds): closing control connection"), TimeoutSession); pr_log_pri(PR_LOG_INFO, "%s", "FTP session timed out, disconnected"); pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_TIMEOUT, "TimeoutSession"); /* no need to restart the timer -- session's over */ return 0; } /* Event listeners */ static void auth_exit_ev(const void *event_data, void *user_data) { pr_auth_cache_clear(); /* Close the scoreboard descriptor that we opened. */ (void) pr_close_scoreboard(FALSE); } static void auth_sess_reinit_ev(const void *event_data, void *user_data) { int res; /* A HOST command changed the main_server pointer, reinitialize ourselves. */ pr_event_unregister(&auth_module, "core.exit", auth_exit_ev); pr_event_unregister(&auth_module, "core.session-reinit", auth_sess_reinit_ev); pr_timer_remove(PR_TIMER_LOGIN, &auth_module); /* Reset the CreateHome setting. */ mkhome = FALSE; /* Reset any MaxPasswordSize setting. */ (void) pr_auth_set_max_password_len(session.pool, 0); #if defined(PR_USE_LASTLOG) lastlog = FALSE; #endif /* PR_USE_LASTLOG */ mkhome = FALSE; res = auth_sess_init(); if (res < 0) { pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_SESSION_INIT_FAILED, NULL); } } /* Initialization functions */ static int auth_init(void) { /* Add the commands handled by this module to the HELP list. */ pr_help_add(C_USER, _("<sp> username"), TRUE); pr_help_add(C_PASS, _("<sp> password"), TRUE); pr_help_add(C_ACCT, _("is not implemented"), FALSE); pr_help_add(C_REIN, _("is not implemented"), FALSE); /* By default, enable auth checking */ set_auth_check(auth_cmd_chk_cb); return 0; } static int auth_sess_init(void) { config_rec *c = NULL; unsigned char *tmp = NULL; pr_event_register(&auth_module, "core.session-reinit", auth_sess_reinit_ev, NULL); /* Check for any MaxPasswordSize. */ c = find_config(main_server->conf, CONF_PARAM, "MaxPasswordSize", FALSE); if (c != NULL) { size_t len; len = *((size_t *) c->argv[0]); (void) pr_auth_set_max_password_len(session.pool, len); } /* Check for a server-specific TimeoutLogin */ c = find_config(main_server->conf, CONF_PARAM, "TimeoutLogin", FALSE); if (c != NULL) { TimeoutLogin = *((int *) c->argv[0]); } /* Start the login timer */ if (TimeoutLogin) { pr_timer_remove(PR_TIMER_LOGIN, &auth_module); pr_timer_add(TimeoutLogin, PR_TIMER_LOGIN, &auth_module, auth_login_timeout_cb, "TimeoutLogin"); } if (auth_client_connected == FALSE) { int res = 0; PRIVS_ROOT res = pr_open_scoreboard(O_RDWR); PRIVS_RELINQUISH if (res < 0) { switch (res) { case PR_SCORE_ERR_BAD_MAGIC: pr_log_debug(DEBUG0, "error opening scoreboard: bad/corrupted file"); break; case PR_SCORE_ERR_OLDER_VERSION: pr_log_debug(DEBUG0, "error opening scoreboard: bad version (too old)"); break; case PR_SCORE_ERR_NEWER_VERSION: pr_log_debug(DEBUG0, "error opening scoreboard: bad version (too new)"); break; default: pr_log_debug(DEBUG0, "error opening scoreboard: %s", strerror(errno)); break; } } } pr_event_register(&auth_module, "core.exit", auth_exit_ev, NULL); if (auth_client_connected == FALSE) { /* Create an entry in the scoreboard for this session, if we don't already * have one. */ if (pr_scoreboard_entry_get(PR_SCORE_CLIENT_ADDR) == NULL) { if (pr_scoreboard_entry_add() < 0) { pr_log_pri(PR_LOG_NOTICE, "notice: unable to add scoreboard entry: %s", strerror(errno)); } pr_scoreboard_entry_update(session.pid, PR_SCORE_USER, "(none)", PR_SCORE_SERVER_PORT, main_server->ServerPort, PR_SCORE_SERVER_ADDR, session.c->local_addr, session.c->local_port, PR_SCORE_SERVER_LABEL, main_server->ServerName, PR_SCORE_CLIENT_ADDR, session.c->remote_addr, PR_SCORE_CLIENT_NAME, session.c->remote_name, PR_SCORE_CLASS, session.conn_class ? session.conn_class->cls_name : "", PR_SCORE_PROTOCOL, "ftp", PR_SCORE_BEGIN_SESSION, time(NULL), NULL); } } else { /* We're probably handling a HOST comand, and the server changed; just * update the SERVER_LABEL field. */ pr_scoreboard_entry_update(session.pid, PR_SCORE_SERVER_LABEL, main_server->ServerName, NULL); } /* Should we create the home for a user, if they don't have one? */ tmp = get_param_ptr(main_server->conf, "CreateHome", FALSE); if (tmp != NULL && *tmp == TRUE) { mkhome = TRUE; } else { mkhome = FALSE; } #ifdef PR_USE_LASTLOG /* Use the lastlog file, if supported and requested. */ tmp = get_param_ptr(main_server->conf, "UseLastlog", FALSE); if (tmp && *tmp == TRUE) { lastlog = TRUE; } else { lastlog = FALSE; } #endif /* PR_USE_LASTLOG */ /* Scan the scoreboard now, in order to tally up certain values for * substituting in any of the Display* file variables. This function * also performs the MaxConnectionsPerHost enforcement. */ auth_scan_scoreboard(); auth_client_connected = TRUE; return 0; } static int do_auth(pool *p, xaset_t *conf, const char *u, char *pw) { char *cpw = NULL; config_rec *c; if (conf != NULL) { c = find_config(conf, CONF_PARAM, "UserPassword", FALSE); while (c != NULL) { pr_signals_handle(); if (strcmp(c->argv[0], u) == 0) { cpw = (char *) c->argv[1]; break; } c = find_config_next(c, c->next, CONF_PARAM, "UserPassword", FALSE); } } if (cpw != NULL) { if (pr_auth_getpwnam(p, u) == NULL) { int xerrno = errno; if (xerrno == ENOENT) { pr_log_pri(PR_LOG_NOTICE, "no such user '%s'", u); } errno = xerrno; return PR_AUTH_NOPWD; } return pr_auth_check(p, cpw, u, pw); } return pr_auth_authenticate(p, u, pw); } /* Command handlers */ static void login_failed(pool *p, const char *user) { #ifdef HAVE_LOGINFAILED const char *host, *sess_ttyname; int res, xerrno; host = pr_netaddr_get_dnsstr(session.c->remote_addr); sess_ttyname = pr_session_get_ttyname(p); PRIVS_ROOT res = loginfailed((char *) user, (char *) host, (char *) sess_ttyname, AUDIT_FAIL); xerrno = errno; PRIVS_RELINQUISH if (res < 0) { pr_trace_msg("auth", 3, "AIX loginfailed() error for user '%s', " "host '%s', tty '%s', reason %d: %s", user, host, sess_ttyname, AUDIT_FAIL, strerror(errno)); } #endif /* HAVE_LOGINFAILED */ } MODRET auth_err_pass(cmd_rec *cmd) { const char *user; user = pr_table_get(session.notes, "mod_auth.orig-user", NULL); if (user != NULL) { login_failed(cmd->tmp_pool, user); } /* Remove the stashed original USER name here in a LOG_CMD_ERR handler, so * that other modules, who may want to lookup the original USER parameter on * a failed login in an earlier command handler phase, have a chance to do * so. This removal of the USER parameter on failure was happening directly * in the CMD handler previously, thus preventing POST_CMD_ERR handlers from * using USER. */ pr_table_remove(session.notes, "mod_auth.orig-user", NULL); return PR_HANDLED(cmd); } MODRET auth_log_pass(cmd_rec *cmd) { /* Only log, to the syslog, that the login has succeeded here, where we * know that the login has definitely succeeded. */ pr_log_auth(PR_LOG_INFO, "%s %s: Login successful.", (session.anon_config != NULL) ? "ANON" : C_USER, session.user); if (cmd->arg != NULL) { size_t passwd_len; /* And scrub the memory holding the password sent by the client, for * safety/security. */ passwd_len = strlen(cmd->arg); pr_memscrub(cmd->arg, passwd_len); } return PR_DECLINED(cmd); } static void login_succeeded(pool *p, const char *user) { #ifdef HAVE_LOGINSUCCESS const char *host, *sess_ttyname; char *msg = NULL; int res, xerrno; host = pr_netaddr_get_dnsstr(session.c->remote_addr); sess_ttyname = pr_session_get_ttyname(p); PRIVS_ROOT res = loginsuccess((char *) user, (char *) host, (char *) sess_ttyname, &msg); xerrno = errno; PRIVS_RELINQUISH if (res == 0) { if (msg != NULL) { pr_trace_msg("auth", 14, "AIX loginsuccess() report: %s", msg); } } else { pr_trace_msg("auth", 3, "AIX loginsuccess() error for user '%s', " "host '%s', tty '%s': %s", user, host, sess_ttyname, strerror(errno)); } if (msg != NULL) { free(msg); } #endif /* HAVE_LOGINSUCCESS */ } MODRET auth_post_pass(cmd_rec *cmd) { config_rec *c = NULL; const char *grantmsg = NULL, *user; unsigned int ctxt_precedence = 0; unsigned char have_user_timeout, have_group_timeout, have_class_timeout, have_all_timeout, *root_revoke = NULL, *authenticated; struct stat st; /* Was there a precending USER command? Was the client successfully * authenticated? */ authenticated = get_param_ptr(cmd->server->conf, "authenticated", FALSE); /* Clear the list of auth-only modules. */ pr_auth_clear_auth_only_modules(); if (authenticated != NULL && *authenticated == TRUE) { /* At this point, we can look up the Protocols config if the client * has been authenticated, which may have been tweaked via mod_ifsession's * user/group/class-specific sections. */ c = find_config(main_server->conf, CONF_PARAM, "Protocols", FALSE); if (c != NULL) { register unsigned int i; array_header *protocols; char **elts; const char *protocol; protocols = c->argv[0]; elts = protocols->elts; protocol = pr_session_get_protocol(PR_SESS_PROTO_FL_LOGOUT); /* We only want to check for 'ftp' in the configured Protocols list * if a) a RFC2228 mechanism (e.g. SSL or GSS) is not in use, and * b) an SSH protocol is not in use. */ if (session.rfc2228_mech == NULL && strncmp(protocol, "SSH2", 5) != 0) { int allow_ftp = FALSE; for (i = 0; i < protocols->nelts; i++) { char *proto; proto = elts[i]; if (proto != NULL) { if (strncasecmp(proto, "ftp", 4) == 0) { allow_ftp = TRUE; break; } } } if (!allow_ftp) { pr_log_debug(DEBUG0, "%s", "ftp protocol denied by Protocols config"); pr_response_send(R_530, "%s", _("Login incorrect.")); pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_CONFIG_ACL, "Denied by Protocols setting"); } } } } user = pr_table_get(session.notes, "mod_auth.orig-user", NULL); /* Count up various quantities in the scoreboard, checking them against * the Max* limits to see if the session should be barred from going * any further. */ auth_count_scoreboard(cmd, session.user); /* Check for dynamic configuration. This check needs to be after the * setting of any possible anon_config, as that context may be allowed * or denied .ftpaccess-parsing separately from the containing server. */ if (pr_fsio_stat(session.cwd, &st) != -1) build_dyn_config(cmd->tmp_pool, session.cwd, &st, TRUE); have_user_timeout = have_group_timeout = have_class_timeout = have_all_timeout = FALSE; c = find_config(TOPLEVEL_CONF, CONF_PARAM, "TimeoutSession", FALSE); while (c != NULL) { pr_signals_handle(); if (c->argc == 3) { if (strncmp(c->argv[1], "user", 5) == 0) { if (pr_expr_eval_user_or((char **) &c->argv[2]) == TRUE) { if (*((unsigned int *) c->argv[1]) > ctxt_precedence) { /* Set the context precedence. */ ctxt_precedence = *((unsigned int *) c->argv[1]); TimeoutSession = *((int *) c->argv[0]); have_group_timeout = have_class_timeout = have_all_timeout = FALSE; have_user_timeout = TRUE; } } } else if (strncmp(c->argv[1], "group", 6) == 0) { if (pr_expr_eval_group_and((char **) &c->argv[2]) == TRUE) { if (*((unsigned int *) c->argv[1]) > ctxt_precedence) { /* Set the context precedence. */ ctxt_precedence = *((unsigned int *) c->argv[1]); TimeoutSession = *((int *) c->argv[0]); have_user_timeout = have_class_timeout = have_all_timeout = FALSE; have_group_timeout = TRUE; } } } else if (strncmp(c->argv[1], "class", 6) == 0) { if (session.conn_class != NULL && strcmp(session.conn_class->cls_name, c->argv[2]) == 0) { if (*((unsigned int *) c->argv[1]) > ctxt_precedence) { /* Set the context precedence. */ ctxt_precedence = *((unsigned int *) c->argv[1]); TimeoutSession = *((int *) c->argv[0]); have_user_timeout = have_group_timeout = have_all_timeout = FALSE; have_class_timeout = TRUE; } } } } else { if (*((unsigned int *) c->argv[1]) > ctxt_precedence) { /* Set the context precedence. */ ctxt_precedence = *((unsigned int *) c->argv[1]); TimeoutSession = *((int *) c->argv[0]); have_user_timeout = have_group_timeout = have_class_timeout = FALSE; have_all_timeout = TRUE; } } c = find_config_next(c, c->next, CONF_PARAM, "TimeoutSession", FALSE); } /* If configured, start a session timer. The timer ID value for * session timers will not be #defined, as I think that is a bad approach. * A better mechanism would be to use the random timer ID generation, and * store the returned ID in order to later remove the timer. */ if (have_user_timeout || have_group_timeout || have_class_timeout || have_all_timeout) { pr_log_debug(DEBUG4, "setting TimeoutSession of %d seconds for current %s", TimeoutSession, have_user_timeout ? "user" : have_group_timeout ? "group" : have_class_timeout ? "class" : "all"); pr_timer_add(TimeoutSession, PR_TIMER_SESSION, &auth_module, auth_session_timeout_cb, "TimeoutSession"); } /* Handle a DisplayLogin file. */ if (displaylogin_fh) { if (!(session.sf_flags & SF_ANON)) { if (pr_display_fh(displaylogin_fh, NULL, auth_pass_resp_code, 0) < 0) { pr_log_debug(DEBUG6, "unable to display DisplayLogin file '%s': %s", displaylogin_fh->fh_path, strerror(errno)); } pr_fsio_close(displaylogin_fh); displaylogin_fh = NULL; } else { /* We're an <Anonymous> login, but there was a previous DisplayLogin * configured which was picked up earlier. Close that filehandle, * and look for a new one. */ char *displaylogin; pr_fsio_close(displaylogin_fh); displaylogin_fh = NULL; displaylogin = get_param_ptr(TOPLEVEL_CONF, "DisplayLogin", FALSE); if (displaylogin) { if (pr_display_file(displaylogin, NULL, auth_pass_resp_code, 0) < 0) { pr_log_debug(DEBUG6, "unable to display DisplayLogin file '%s': %s", displaylogin, strerror(errno)); } } } } else { char *displaylogin = get_param_ptr(TOPLEVEL_CONF, "DisplayLogin", FALSE); if (displaylogin) { if (pr_display_file(displaylogin, NULL, auth_pass_resp_code, 0) < 0) { pr_log_debug(DEBUG6, "unable to display DisplayLogin file '%s': %s", displaylogin, strerror(errno)); } } } grantmsg = get_param_ptr(TOPLEVEL_CONF, "AccessGrantMsg", FALSE); if (grantmsg == NULL) { /* Append the final greeting lines. */ if (session.sf_flags & SF_ANON) { pr_response_add(auth_pass_resp_code, "%s", _("Anonymous access granted, restrictions apply")); } else { pr_response_add(auth_pass_resp_code, _("User %s logged in"), user); } } else { /* Handle any AccessGrantMsg directive. */ grantmsg = sreplace(cmd->tmp_pool, grantmsg, "%u", user, NULL); pr_response_add(auth_pass_resp_code, "%s", grantmsg); } login_succeeded(cmd->tmp_pool, user); /* A RootRevoke value of 0 indicates 'false', 1 indicates 'true', and * 2 indicates 'NonCompliantActiveTransfer'. We will drop root privs for any * RootRevoke value greater than 0. */ root_revoke = get_param_ptr(TOPLEVEL_CONF, "RootRevoke", FALSE); if (root_revoke != NULL && *root_revoke > 0) { pr_signals_block(); PRIVS_ROOT PRIVS_REVOKE pr_signals_unblock(); /* Disable future attempts at UID/GID manipulation. */ session.disable_id_switching = TRUE; if (*root_revoke == 1) { /* If the server's listening port is less than 1024, block PORT * commands (effectively allowing only passive connections, which is * not necessarily a Bad Thing). Only log this here -- the blocking * will need to occur in mod_core's handling of the PORT/EPRT commands. */ if (session.c->local_port < 1024) { pr_log_debug(DEBUG0, "RootRevoke in effect, active data transfers may not succeed"); } } pr_log_debug(DEBUG0, "RootRevoke in effect, dropped root privs"); } c = find_config(TOPLEVEL_CONF, CONF_PARAM, "AnonAllowRobots", FALSE); if (c != NULL) { auth_anon_allow_robots = *((int *) c->argv[0]); } return PR_DECLINED(cmd); } /* Handle group based authentication, only checked if pw based fails. */ static config_rec *auth_group(pool *p, const char *user, char **group, char **ournamep, char **anonnamep, char *pass) { config_rec *c; char *ourname = NULL, *anonname = NULL; char **grmem; struct group *grp; ourname = get_param_ptr(main_server->conf, "UserName", FALSE); if (ournamep != NULL && ourname != NULL) { *ournamep = ourname; } c = find_config(main_server->conf, CONF_PARAM, "GroupPassword", TRUE); if (c) do { grp = pr_auth_getgrnam(p, c->argv[0]); if (grp == NULL) { continue; } for (grmem = grp->gr_mem; *grmem; grmem++) { if (strcmp(*grmem, user) == 0) { if (pr_auth_check(p, c->argv[1], user, pass) == 0) { break; } } } if (*grmem) { if (group != NULL) { *group = c->argv[0]; } if (c->parent != NULL) { c = c->parent; } if (c->config_type == CONF_ANON) { anonname = get_param_ptr(c->subset, "UserName", FALSE); } if (anonnamep != NULL) { *anonnamep = anonname; } if (anonnamep != NULL && !anonname && ourname != NULL) { *anonnamep = ourname; } break; } } while((c = find_config_next(c, c->next, CONF_PARAM, "GroupPassword", TRUE)) != NULL); return c; } /* Determine any applicable chdirs. */ static const char *get_default_chdir(pool *p, xaset_t *conf) { config_rec *c; const char *dir = NULL; c = find_config(conf, CONF_PARAM, "DefaultChdir", FALSE); while (c != NULL) { int res; pr_signals_handle(); /* Check the groups acl */ if (c->argc < 2) { dir = c->argv[0]; break; } res = pr_expr_eval_group_and(((char **) c->argv)+1); if (res) { dir = c->argv[0]; break; } c = find_config_next(c, c->next, CONF_PARAM, "DefaultChdir", FALSE); } /* If the directory is relative, concatenate w/ session.cwd. */ if (dir != NULL && *dir != '/' && *dir != '~') { dir = pdircat(p, session.cwd, dir, NULL); } /* Check for any expandable variables. */ if (dir != NULL) { dir = path_subst_uservar(p, &dir); } return dir; } static int is_symlink_path(pool *p, const char *path, size_t pathlen) { int res, xerrno = 0; struct stat st; char *ptr; if (pathlen == 0) { return 0; } pr_fs_clear_cache2(path); res = pr_fsio_lstat(path, &st); if (res < 0) { xerrno = errno; pr_log_pri(PR_LOG_WARNING, "error: unable to check %s: %s", path, strerror(xerrno)); errno = xerrno; return -1; } if (S_ISLNK(st.st_mode)) { errno = EPERM; return -1; } /* To handle the case where a component further up the path might be a * symlink (which lstat(2) will NOT handle), we walk the path backwards, * calling ourselves recursively. */ ptr = strrchr(path, '/'); if (ptr != NULL) { char *new_path; size_t new_pathlen; pr_signals_handle(); new_pathlen = ptr - path; new_path = pstrndup(p, path, new_pathlen); pr_log_debug(DEBUG10, "AllowChrootSymlink: path '%s' not a symlink, checking '%s'", path, new_path); res = is_symlink_path(p, new_path, new_pathlen); if (res < 0) { return -1; } } return 0; } /* Determine if the user (non-anon) needs a default root dir other than /. */ static int get_default_root(pool *p, int allow_symlinks, const char **root) { config_rec *c = NULL; const char *dir = NULL; int res; c = find_config(main_server->conf, CONF_PARAM, "DefaultRoot", FALSE); while (c != NULL) { pr_signals_handle(); /* Check the groups acl */ if (c->argc < 2) { dir = c->argv[0]; break; } res = pr_expr_eval_group_and(((char **) c->argv)+1); if (res) { dir = c->argv[0]; break; } c = find_config_next(c, c->next, CONF_PARAM, "DefaultRoot", FALSE); } if (dir != NULL) { const char *new_dir; /* Check for any expandable variables. */ new_dir = path_subst_uservar(p, &dir); if (new_dir != NULL) { dir = new_dir; } if (strncmp(dir, "/", 2) == 0) { dir = NULL; } else { char *realdir; int xerrno = 0; if (allow_symlinks == FALSE) { char *path, target_path[PR_TUNABLE_PATH_MAX + 1]; size_t pathlen; /* First, deal with any possible interpolation. dir_realpath() will * do this for us, but dir_realpath() ALSO automatically follows * symlinks, which is what we do NOT want to do here. */ path = pstrdup(p, dir); if (*path != '/') { if (*path == '~') { if (pr_fs_interpolate(dir, target_path, sizeof(target_path)-1) < 0) { return -1; } path = target_path; } } /* Note: lstat(2) is sensitive to the presence of a trailing slash on * the path, particularly in the case of a symlink to a directory. * Thus to get the correct test, we need to remove any trailing slash * that might be present. Subtle. */ pathlen = strlen(path); if (pathlen > 1 && path[pathlen-1] == '/') { path[pathlen-1] = '\0'; } res = is_symlink_path(p, path, pathlen); if (res < 0) { if (errno == EPERM) { pr_log_pri(PR_LOG_WARNING, "error: DefaultRoot %s is a symlink " "(denied by AllowChrootSymlinks config)", path); } errno = EPERM; return -1; } } /* We need to be the final user here so that if the user has their home * directory with a mode the user proftpd is running (i.e. the User * directive) as can not traverse down, we can still have the default * root. */ pr_fs_clear_cache2(dir); PRIVS_USER realdir = dir_realpath(p, dir); xerrno = errno; PRIVS_RELINQUISH if (realdir) { dir = realdir; } else { /* Try to provide a more informative message. */ char interp_dir[PR_TUNABLE_PATH_MAX + 1]; memset(interp_dir, '\0', sizeof(interp_dir)); (void) pr_fs_interpolate(dir, interp_dir, sizeof(interp_dir)-1); pr_log_pri(PR_LOG_NOTICE, "notice: unable to use DefaultRoot '%s' [resolved to '%s']: %s", dir, interp_dir, strerror(xerrno)); errno = xerrno; } } } *root = dir; return 0; } static struct passwd *passwd_dup(pool *p, struct passwd *pw) { struct passwd *npw; npw = pcalloc(p, sizeof(struct passwd)); npw->pw_name = pstrdup(p, pw->pw_name); npw->pw_passwd = pstrdup(p, pw->pw_passwd); npw->pw_uid = pw->pw_uid; npw->pw_gid = pw->pw_gid; npw->pw_gecos = pstrdup(p, pw->pw_gecos); npw->pw_dir = pstrdup(p, pw->pw_dir); npw->pw_shell = pstrdup(p, pw->pw_shell); return npw; } static void ensure_open_passwd(pool *p) { /* Make sure pass/group is open. */ pr_auth_setpwent(p); pr_auth_setgrent(p); /* On some unices the following is necessary to ensure the files * are open (BSDI 3.1) */ pr_auth_getpwent(p); pr_auth_getgrent(p); /* Per Debian bug report: * https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=717235 * we might want to do another set{pw,gr}ent(), to play better with * some NSS modules. */ pr_auth_setpwent(p); pr_auth_setgrent(p); } /* Next function (the biggie) handles all authentication, setting * up chroot() jail, etc. */ static int setup_env(pool *p, cmd_rec *cmd, const char *user, char *pass) { struct passwd *pw; config_rec *c, *tmpc; const char *defchdir = NULL, *defroot = NULL, *origuser, *sess_ttyname; char *ourname = NULL, *anonname = NULL, *anongroup = NULL, *ugroup = NULL; char *xferlog = NULL; int aclp, i, res = 0, allow_chroot_symlinks = TRUE, showsymlinks; unsigned char *wtmp_log = NULL, *anon_require_passwd = NULL; /********************* Authenticate the user here *********************/ session.hide_password = TRUE; origuser = user; c = pr_auth_get_anon_config(p, &user, &ourname, &anonname); if (c != NULL) { session.anon_config = c; } if (user == NULL) { pr_log_auth(PR_LOG_NOTICE, "USER %s: user is not a UserAlias from %s [%s] " "to %s:%i", origuser, session.c->remote_name, pr_netaddr_get_ipstr(session.c->remote_addr), pr_netaddr_get_ipstr(session.c->local_addr), session.c->local_port); goto auth_failure; } pw = pr_auth_getpwnam(p, user); if (pw == NULL && c != NULL && ourname != NULL) { /* If the client is authenticating using an alias (e.g. "AuthAliasOnly on"), * then we need to try checking using the real username, too (Bug#4255). */ pr_trace_msg("auth", 16, "no user entry found for <Anonymous> alias '%s', using '%s'", user, ourname); pw = pr_auth_getpwnam(p, ourname); } if (pw == NULL) { int auth_code = PR_AUTH_NOPWD; pr_log_auth(PR_LOG_NOTICE, "USER %s: no such user found from %s [%s] to %s:%i", user, session.c->remote_name, pr_netaddr_get_ipstr(session.c->remote_addr), pr_netaddr_get_ipstr(session.c->local_addr), session.c->local_port); pr_event_generate("mod_auth.authentication-code", &auth_code); goto auth_failure; } /* Security: other functions perform pw lookups, thus we need to make * a local copy of the user just looked up. */ pw = passwd_dup(p, pw); if (pw->pw_uid == PR_ROOT_UID) { unsigned char *root_allow = NULL; pr_event_generate("mod_auth.root-login", NULL); /* If RootLogin is set to true, we allow this... even though we * still log a warning. :) */ if ((root_allow = get_param_ptr(c ? c->subset : main_server->conf, "RootLogin", FALSE)) == NULL || *root_allow != TRUE) { if (pass) { pr_memscrub(pass, strlen(pass)); } pr_log_auth(PR_LOG_NOTICE, "SECURITY VIOLATION: Root login attempted"); return 0; } } session.user = pstrdup(p, pw->pw_name); session.group = pstrdup(p, pr_auth_gid2name(p, pw->pw_gid)); /* Set the login_uid and login_uid */ session.login_uid = pw->pw_uid; session.login_gid = pw->pw_gid; /* Check for any expandable variables in session.cwd. */ pw->pw_dir = (char *) path_subst_uservar(p, (const char **) &pw->pw_dir); /* Before we check for supplemental groups, check to see if the locally * resolved name of the user, returned via auth_getpwnam(), is different * from the USER argument sent by the client. The name can change, since * auth modules can play all sorts of neat tricks on us. * * If the names differ, assume that any cached data in the session.gids * and session.groups lists are stale, and clear them out. */ if (strcmp(pw->pw_name, user) != 0) { pr_trace_msg("auth", 10, "local user name '%s' differs from client-sent " "user name '%s', clearing cached group data", pw->pw_name, user); session.gids = NULL; session.groups = NULL; } if (!session.gids && !session.groups) { /* Get the supplemental groups. Note that we only look up the * supplemental group credentials if we have not cached the group * credentials before, in session.gids and session.groups. * * Those credentials may have already been retrieved, as part of the * pr_auth_get_anon_config() call. */ res = pr_auth_getgroups(p, pw->pw_name, &session.gids, &session.groups); if (res < 1) { pr_log_debug(DEBUG5, "no supplemental groups found for user '%s'", pw->pw_name); } } tmpc = find_config(main_server->conf, CONF_PARAM, "AllowChrootSymlinks", FALSE); if (tmpc != NULL) { allow_chroot_symlinks = *((int *) tmpc->argv[0]); } /* If c != NULL from this point on, we have an anonymous login */ aclp = login_check_limits(main_server->conf, FALSE, TRUE, &i); if (c != NULL) { anongroup = get_param_ptr(c->subset, "GroupName", FALSE); if (anongroup == NULL) { anongroup = get_param_ptr(main_server->conf, "GroupName",FALSE); } #ifdef PR_USE_REGEX /* Check for configured AnonRejectPasswords regex here, and fail the login * if the given password matches the regex. */ tmpc = find_config(c->subset, CONF_PARAM, "AnonRejectPasswords", FALSE); if (tmpc != NULL) { int re_notmatch; pr_regex_t *pw_regex; pw_regex = (pr_regex_t *) tmpc->argv[0]; re_notmatch = *((int *) tmpc->argv[1]); if (pw_regex != NULL && pass != NULL) { int re_res; re_res = pr_regexp_exec(pw_regex, pass, 0, NULL, 0, 0, 0); if (re_res == 0 || (re_res != 0 && re_notmatch == TRUE)) { char errstr[200] = {'\0'}; pr_regexp_error(re_res, pw_regex, errstr, sizeof(errstr)); pr_log_auth(PR_LOG_NOTICE, "ANON %s: AnonRejectPasswords denies login", origuser); pr_event_generate("mod_auth.anon-reject-passwords", session.c); goto auth_failure; } } } #endif if (!login_check_limits(c->subset, FALSE, TRUE, &i) || (!aclp && !i) ){ pr_log_auth(PR_LOG_NOTICE, "ANON %s (Login failed): Limit access denies " "login", origuser); goto auth_failure; } } if (c == NULL && aclp == 0) { pr_log_auth(PR_LOG_NOTICE, "USER %s (Login failed): Limit access denies login", origuser); goto auth_failure; } if (c != NULL) { anon_require_passwd = get_param_ptr(c->subset, "AnonRequirePassword", FALSE); } if (c == NULL || (anon_require_passwd != NULL && *anon_require_passwd == TRUE)) { int auth_code; const char *user_name = user; if (c != NULL && origuser != NULL && strcasecmp(user, origuser) != 0) { unsigned char *auth_using_alias; auth_using_alias = get_param_ptr(c->subset, "AuthUsingAlias", FALSE); /* If 'AuthUsingAlias' set and we're logging in under an alias, * then auth using that alias. */ if (auth_using_alias && *auth_using_alias == TRUE) { user_name = origuser; pr_log_auth(PR_LOG_INFO, "ANON AUTH: User %s, authenticating using alias %s", user, user_name); } } /* It is possible for the user to have already been authenticated during * the handling of the USER command, as by an RFC2228 mechanism. If * that had happened, we won't need to call do_auth() here. */ if (!authenticated_without_pass) { auth_code = do_auth(p, c ? c->subset : main_server->conf, user_name, pass); } else { auth_code = PR_AUTH_OK_NO_PASS; } pr_event_generate("mod_auth.authentication-code", &auth_code); if (auth_code < 0) { /* Normal authentication has failed, see if group authentication * passes */ c = auth_group(p, user, &anongroup, &ourname, &anonname, pass); if (c != NULL) { if (c->config_type != CONF_ANON) { c = NULL; ugroup = anongroup; anongroup = NULL; } auth_code = PR_AUTH_OK; } } if (pass) pr_memscrub(pass, strlen(pass)); if (session.auth_mech) pr_log_debug(DEBUG2, "user '%s' authenticated by %s", user, session.auth_mech); switch (auth_code) { case PR_AUTH_OK_NO_PASS: auth_pass_resp_code = R_232; break; case PR_AUTH_OK: auth_pass_resp_code = R_230; break; case PR_AUTH_NOPWD: pr_log_auth(PR_LOG_NOTICE, "USER %s (Login failed): No such user found", user); goto auth_failure; case PR_AUTH_BADPWD: pr_log_auth(PR_LOG_NOTICE, "USER %s (Login failed): Incorrect password", origuser); goto auth_failure; case PR_AUTH_AGEPWD: pr_log_auth(PR_LOG_NOTICE, "USER %s (Login failed): Password expired", user); goto auth_failure; case PR_AUTH_DISABLEDPWD: pr_log_auth(PR_LOG_NOTICE, "USER %s (Login failed): Account disabled", user); goto auth_failure; case PR_AUTH_CRED_INSUFFICIENT: pr_log_auth(PR_LOG_NOTICE, "USER %s (Login failed): Insufficient credentials", user); goto auth_failure; case PR_AUTH_CRED_UNAVAIL: pr_log_auth(PR_LOG_NOTICE, "USER %s (Login failed): Unavailable credentials", user); goto auth_failure; case PR_AUTH_CRED_ERROR: pr_log_auth(PR_LOG_NOTICE, "USER %s (Login failed): Failure setting credentials", user); goto auth_failure; case PR_AUTH_INFO_UNAVAIL: pr_log_auth(PR_LOG_NOTICE, "USER %s (Login failed): Unavailable authentication service", user); goto auth_failure; case PR_AUTH_MAX_ATTEMPTS_EXCEEDED: pr_log_auth(PR_LOG_NOTICE, "USER %s (Login failed): Max authentication service attempts reached", user); goto auth_failure; case PR_AUTH_INIT_ERROR: pr_log_auth(PR_LOG_NOTICE, "USER %s (Login failed): Failed initializing authentication service", user); goto auth_failure; case PR_AUTH_NEW_TOKEN_REQUIRED: pr_log_auth(PR_LOG_NOTICE, "USER %s (Login failed): New authentication token required", user); goto auth_failure; default: break; }; /* Catch the case where we forgot to handle a bad auth code above. */ if (auth_code < 0) goto auth_failure; if (pw->pw_uid == PR_ROOT_UID) { pr_log_auth(PR_LOG_WARNING, "ROOT FTP login successful"); } } else if (c && (!anon_require_passwd || *anon_require_passwd == FALSE)) { session.hide_password = FALSE; } pr_auth_setgrent(p); res = pr_auth_is_valid_shell(c ? c->subset : main_server->conf, pw->pw_shell); if (res == FALSE) { pr_log_auth(PR_LOG_NOTICE, "USER %s (Login failed): Invalid shell: '%s'", user, pw->pw_shell); goto auth_failure; } res = pr_auth_banned_by_ftpusers(c ? c->subset : main_server->conf, pw->pw_name); if (res == TRUE) { pr_log_auth(PR_LOG_NOTICE, "USER %s (Login failed): User in " PR_FTPUSERS_PATH, user); goto auth_failure; } if (c) { struct group *grp = NULL; unsigned char *add_userdir = NULL; const char *u; char *chroot_dir; u = pr_table_get(session.notes, "mod_auth.orig-user", NULL); add_userdir = get_param_ptr(c->subset, "UserDirRoot", FALSE); /* If resolving an <Anonymous> user, make sure that user's groups * are set properly for the check of the home directory path (which * depend on those supplemental group memberships). Additionally, * temporarily switch to the new user's uid. */ pr_signals_block(); PRIVS_ROOT res = set_groups(p, pw->pw_gid, session.gids); if (res < 0) { if (errno != ENOSYS) { pr_log_pri(PR_LOG_WARNING, "error: unable to set groups: %s", strerror(errno)); } } #ifndef PR_DEVEL_COREDUMP # ifdef __hpux if (setresuid(0, 0, 0) < 0) { pr_log_pri(PR_LOG_ERR, "unable to setresuid(): %s", strerror(errno)); } if (setresgid(0, 0, 0) < 0) { pr_log_pri(PR_LOG_ERR, "unable to setresgid(): %s", strerror(errno)); } # else if (setuid(PR_ROOT_UID) < 0) { pr_log_pri(PR_LOG_ERR, "unable to setuid(): %s", strerror(errno)); } if (setgid(PR_ROOT_GID) < 0) { pr_log_pri(PR_LOG_ERR, "unable to setgid(): %s", strerror(errno)); } # endif /* __hpux */ #endif /* PR_DEVEL_COREDUMP */ PRIVS_SETUP(pw->pw_uid, pw->pw_gid) if ((add_userdir && *add_userdir == TRUE) && strcmp(u, user) != 0) { chroot_dir = pdircat(p, c->name, u, NULL); } else { chroot_dir = c->name; } if (allow_chroot_symlinks == FALSE) { char *chroot_path, target_path[PR_TUNABLE_PATH_MAX+1]; struct stat st; chroot_path = chroot_dir; if (chroot_path[0] != '/') { if (chroot_path[0] == '~') { if (pr_fs_interpolate(chroot_path, target_path, sizeof(target_path)-1) == 0) { chroot_path = target_path; } else { chroot_path = NULL; } } } if (chroot_path != NULL) { size_t chroot_pathlen; /* Note: lstat(2) is sensitive to the presence of a trailing slash on * the path, particularly in the case of a symlink to a directory. * Thus to get the correct test, we need to remove any trailing slash * that might be present. Subtle. */ chroot_pathlen = strlen(chroot_path); if (chroot_pathlen > 1 && chroot_path[chroot_pathlen-1] == '/') { chroot_path[chroot_pathlen-1] = '\0'; } pr_fs_clear_cache2(chroot_path); res = pr_fsio_lstat(chroot_path, &st); if (res < 0) { int xerrno = errno; pr_log_pri(PR_LOG_WARNING, "error: unable to check %s: %s", chroot_path, strerror(xerrno)); errno = xerrno; chroot_path = NULL; } else { if (S_ISLNK(st.st_mode)) { pr_log_pri(PR_LOG_WARNING, "error: <Anonymous %s> is a symlink (denied by " "AllowChrootSymlinks config)", chroot_path); errno = EPERM; chroot_path = NULL; } } } if (chroot_path != NULL) { session.chroot_path = dir_realpath(p, chroot_dir); } else { session.chroot_path = NULL; } if (session.chroot_path == NULL) { pr_log_debug(DEBUG8, "error resolving '%s': %s", chroot_dir, strerror(errno)); } } else { session.chroot_path = dir_realpath(p, chroot_dir); if (session.chroot_path == NULL) { pr_log_debug(DEBUG8, "error resolving '%s': %s", chroot_dir, strerror(errno)); } } if (session.chroot_path && pr_fsio_access(session.chroot_path, X_OK, session.uid, session.gid, session.gids) != 0) { session.chroot_path = NULL; } else { session.chroot_path = pstrdup(session.pool, session.chroot_path); } /* Return all privileges back to that of the daemon, for now. */ PRIVS_ROOT res = set_groups(p, daemon_gid, daemon_gids); if (res < 0) { if (errno != ENOSYS) { pr_log_pri(PR_LOG_ERR, "error: unable to set groups: %s", strerror(errno)); } } #ifndef PR_DEVEL_COREDUMP # ifdef __hpux if (setresuid(0, 0, 0) < 0) { pr_log_pri(PR_LOG_ERR, "unable to setresuid(): %s", strerror(errno)); } if (setresgid(0, 0, 0) < 0) { pr_log_pri(PR_LOG_ERR, "unable to setresgid(): %s", strerror(errno)); } # else if (setuid(PR_ROOT_UID) < 0) { pr_log_pri(PR_LOG_ERR, "unable to setuid(): %s", strerror(errno)); } if (setgid(PR_ROOT_GID) < 0) { pr_log_pri(PR_LOG_ERR, "unable to setgid(): %s", strerror(errno)); } # endif /* __hpux */ #endif /* PR_DEVEL_COREDUMP */ PRIVS_SETUP(daemon_uid, daemon_gid) pr_signals_unblock(); /* Sanity check, make sure we have daemon_uid and daemon_gid back */ #ifdef HAVE_GETEUID if (getegid() != daemon_gid || geteuid() != daemon_uid) { PRIVS_RELINQUISH pr_log_pri(PR_LOG_WARNING, "switching IDs from user %s back to daemon uid/gid failed: %s", session.user, strerror(errno)); pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_BY_APPLICATION, NULL); } #endif /* HAVE_GETEUID */ if (anon_require_passwd && *anon_require_passwd == TRUE) { session.anon_user = pstrdup(session.pool, origuser); } else { session.anon_user = pstrdup(session.pool, pass); } if (!session.chroot_path) { pr_log_pri(PR_LOG_NOTICE, "%s: Directory %s is not accessible", session.user, c->name); pr_response_add_err(R_530, _("Unable to set anonymous privileges.")); goto auth_failure; } sstrncpy(session.cwd, "/", sizeof(session.cwd)); xferlog = get_param_ptr(c->subset, "TransferLog", FALSE); if (anongroup) { grp = pr_auth_getgrnam(p, anongroup); if (grp) { pw->pw_gid = grp->gr_gid; session.group = pstrdup(p, grp->gr_name); } } } else { struct group *grp; char *homedir; if (ugroup) { grp = pr_auth_getgrnam(p, ugroup); if (grp) { pw->pw_gid = grp->gr_gid; session.group = pstrdup(p, grp->gr_name); } } /* Attempt to resolve any possible symlinks. */ PRIVS_USER homedir = dir_realpath(p, pw->pw_dir); PRIVS_RELINQUISH if (homedir) sstrncpy(session.cwd, homedir, sizeof(session.cwd)); else sstrncpy(session.cwd, pw->pw_dir, sizeof(session.cwd)); } /* Create the home directory, if need be. */ if (!c && mkhome) { if (create_home(p, session.cwd, origuser, pw->pw_uid, pw->pw_gid) < 0) { /* NOTE: should this cause the login to fail? */ goto auth_failure; } } /* Get default chdir (if any) */ defchdir = get_default_chdir(p, (c ? c->subset : main_server->conf)); if (defchdir != NULL) { sstrncpy(session.cwd, defchdir, sizeof(session.cwd)); } /* Check limits again to make sure deny/allow directives still permit * access. */ if (!login_check_limits((c ? c->subset : main_server->conf), FALSE, TRUE, &i)) { pr_log_auth(PR_LOG_NOTICE, "%s %s: Limit access denies login", (c != NULL) ? "ANON" : C_USER, origuser); goto auth_failure; } /* Perform a directory fixup. */ resolve_deferred_dirs(main_server); fixup_dirs(main_server, CF_DEFER); /* If running under an anonymous context, resolve all <Directory> * blocks inside it. */ if (c && c->subset) resolve_anonymous_dirs(c->subset); /* Write the login to wtmp. This must be done here because we won't * have access after we give up root. This can result in falsified * wtmp entries if an error kicks the user out before we get * through with the login process. Oh well. */ sess_ttyname = pr_session_get_ttyname(p); /* Perform wtmp logging only if not turned off in <Anonymous> * or the current server */ if (c) wtmp_log = get_param_ptr(c->subset, "WtmpLog", FALSE); if (wtmp_log == NULL) wtmp_log = get_param_ptr(main_server->conf, "WtmpLog", FALSE); /* As per Bug#3482, we need to disable WtmpLog for FreeBSD 9.0, as * an interim measure. * * The issue is that some platforms update multiple files for a single * pututxline(3) call; proftpd tries to update those files manually, * do to chroots (after which a pututxline(3) call will fail). A proper * solution requires a separate process, running with the correct * privileges, which would handle wtmp logging. The proftpd session * processes would send messages to this logging daemon (via Unix domain * socket, or FIFO, or TCP socket). * * Also note that this hack to disable WtmpLog may need to be extended * to other platforms in the future. */ #if defined(HAVE_UTMPX_H) && \ defined(__FreeBSD_version) && __FreeBSD_version >= 900007 if (wtmp_log == NULL || *wtmp_log == TRUE) { wtmp_log = pcalloc(p, sizeof(unsigned char)); *wtmp_log = FALSE; pr_log_debug(DEBUG5, "WtpmLog automatically disabled; see Bug#3482 for details"); } #endif PRIVS_ROOT if (wtmp_log == NULL || *wtmp_log == TRUE) { log_wtmp(sess_ttyname, session.user, session.c->remote_name, session.c->remote_addr); session.wtmp_log = TRUE; } #ifdef PR_USE_LASTLOG if (lastlog) { log_lastlog(pw->pw_uid, session.user, sess_ttyname, session.c->remote_addr); } #endif /* PR_USE_LASTLOG */ /* Open any TransferLogs */ if (!xferlog) { if (c) xferlog = get_param_ptr(c->subset, "TransferLog", FALSE); if (!xferlog) xferlog = get_param_ptr(main_server->conf, "TransferLog", FALSE); if (!xferlog) xferlog = PR_XFERLOG_PATH; } if (strcasecmp(xferlog, "NONE") == 0) { xferlog_open(NULL); } else { xferlog_open(xferlog); } res = set_groups(p, pw->pw_gid, session.gids); if (res < 0) { if (errno != ENOSYS) { pr_log_pri(PR_LOG_ERR, "error: unable to set groups: %s", strerror(errno)); } } PRIVS_RELINQUISH /* Now check to see if the user has an applicable DefaultRoot */ if (c == NULL) { if (get_default_root(session.pool, allow_chroot_symlinks, &defroot) < 0) { pr_log_pri(PR_LOG_NOTICE, "error: unable to determine DefaultRoot directory"); pr_response_send(R_530, _("Login incorrect.")); pr_session_end(0); } ensure_open_passwd(p); if (defroot != NULL) { if (pr_auth_chroot(defroot) == -1) { pr_log_pri(PR_LOG_NOTICE, "error: unable to set DefaultRoot directory"); pr_response_send(R_530, _("Login incorrect.")); pr_session_end(0); } /* Re-calc the new cwd based on this root dir. If not applicable * place the user in / (of defroot) */ if (strncmp(session.cwd, defroot, strlen(defroot)) == 0) { char *newcwd = &session.cwd[strlen(defroot)]; if (*newcwd == '/') newcwd++; session.cwd[0] = '/'; sstrncpy(&session.cwd[1], newcwd, sizeof(session.cwd)); } } } if (c) ensure_open_passwd(p); if (c && pr_auth_chroot(session.chroot_path) == -1) { pr_log_pri(PR_LOG_NOTICE, "error: unable to set anonymous privileges"); pr_response_send(R_530, _("Login incorrect.")); pr_session_end(0); } /* new in 1.1.x, I gave in and we don't give up root permanently.. * sigh. */ PRIVS_ROOT #ifndef PR_DEVEL_COREDUMP # ifdef __hpux if (setresuid(0, 0, 0) < 0) { pr_log_pri(PR_LOG_ERR, "unable to setresuid(): %s", strerror(errno)); } if (setresgid(0, 0, 0) < 0) { pr_log_pri(PR_LOG_ERR, "unable to setresgid(): %s", strerror(errno)); } # else if (setuid(PR_ROOT_UID) < 0) { pr_log_pri(PR_LOG_ERR, "unable to setuid(): %s", strerror(errno)); } if (setgid(PR_ROOT_GID) < 0) { pr_log_pri(PR_LOG_ERR, "unable to setgid(): %s", strerror(errno)); } # endif /* __hpux */ #endif /* PR_DEVEL_COREDUMP */ PRIVS_SETUP(pw->pw_uid, pw->pw_gid) #ifdef HAVE_GETEUID if (getegid() != pw->pw_gid || geteuid() != pw->pw_uid) { PRIVS_RELINQUISH pr_log_pri(PR_LOG_ERR, "error: %s setregid() or setreuid(): %s", session.user, strerror(errno)); pr_response_send(R_530, _("Login incorrect.")); pr_session_end(0); } #endif /* If the home directory is NULL or "", reject the login. */ if (pw->pw_dir == NULL || strncmp(pw->pw_dir, "", 1) == 0) { pr_log_pri(PR_LOG_WARNING, "error: user %s home directory is NULL or \"\"", session.user); pr_response_send(R_530, _("Login incorrect.")); pr_session_end(0); } { unsigned char *show_symlinks = get_param_ptr( c ? c->subset : main_server->conf, "ShowSymlinks", FALSE); if (!show_symlinks || *show_symlinks == TRUE) showsymlinks = TRUE; else showsymlinks = FALSE; } /* chdir to the proper directory, do this even if anonymous * to make sure we aren't outside our chrooted space. */ /* Attempt to change to the correct directory -- use session.cwd first. * This will contain the DefaultChdir directory, if configured... */ if (pr_fsio_chdir_canon(session.cwd, !showsymlinks) == -1) { /* if we've got DefaultRoot or anonymous login, ignore this error * and chdir to / */ if (session.chroot_path != NULL || defroot) { pr_log_debug(DEBUG2, "unable to chdir to %s (%s), defaulting to chroot " "directory %s", session.cwd, strerror(errno), (session.chroot_path ? session.chroot_path : defroot)); if (pr_fsio_chdir_canon("/", !showsymlinks) == -1) { pr_log_pri(PR_LOG_NOTICE, "%s chdir(\"/\") failed: %s", session.user, strerror(errno)); pr_response_send(R_530, _("Login incorrect.")); pr_session_end(0); } } else if (defchdir) { /* If we've got defchdir, failure is ok as well, simply switch to * user's homedir. */ pr_log_debug(DEBUG2, "unable to chdir to %s (%s), defaulting to home " "directory %s", session.cwd, strerror(errno), pw->pw_dir); if (pr_fsio_chdir_canon(pw->pw_dir, !showsymlinks) == -1) { pr_log_pri(PR_LOG_NOTICE, "%s chdir(\"%s\") failed: %s", session.user, session.cwd, strerror(errno)); pr_response_send(R_530, _("Login incorrect.")); pr_session_end(0); } } else { /* Unable to switch to user's real home directory, which is not * allowed. */ pr_log_pri(PR_LOG_NOTICE, "%s chdir(\"%s\") failed: %s", session.user, session.cwd, strerror(errno)); pr_response_send(R_530, _("Login incorrect.")); pr_session_end(0); } } sstrncpy(session.cwd, pr_fs_getcwd(), sizeof(session.cwd)); sstrncpy(session.vwd, pr_fs_getvwd(), sizeof(session.vwd)); /* Make sure directory config pointers are set correctly */ dir_check_full(p, cmd, G_NONE, session.cwd, NULL); if (c) { if (!session.hide_password) { session.proc_prefix = pstrcat(session.pool, session.c->remote_name, ": anonymous/", pass, NULL); } else { session.proc_prefix = pstrcat(session.pool, session.c->remote_name, ": anonymous", NULL); } session.sf_flags = SF_ANON; } else { session.proc_prefix = pstrdup(session.pool, session.c->remote_name); session.sf_flags = 0; } /* While closing the pointer to the password database would avoid any * potential attempt to hijack this information, it is unfortunately needed * in a chroot()ed environment. Otherwise, mappings from UIDs to names, * among other things, would fail. */ /* pr_auth_endpwent(p); */ /* Authentication complete, user logged in, now kill the login * timer. */ /* Update the scoreboard entry */ pr_scoreboard_entry_update(session.pid, PR_SCORE_USER, session.user, PR_SCORE_CWD, session.cwd, NULL); pr_session_set_idle(); pr_timer_remove(PR_TIMER_LOGIN, &auth_module); /* These copies are made from the session.pool, instead of the more * volatile pool used originally, in order that the copied data maintain * its integrity for the lifetime of the session. */ session.user = pstrdup(session.pool, session.user); if (session.group) session.group = pstrdup(session.pool, session.group); if (session.gids) session.gids = copy_array(session.pool, session.gids); /* session.groups is an array of strings, so we must copy the string data * as well as the pointers. */ session.groups = copy_array_str(session.pool, session.groups); /* Resolve any deferred-resolution paths in the FS layer */ pr_resolve_fs_map(); return 1; auth_failure: if (pass) pr_memscrub(pass, strlen(pass)); session.user = session.group = NULL; session.gids = session.groups = NULL; session.wtmp_log = FALSE; return 0; } /* This function counts the number of connected users. It only fills in the * Class-based counters and an estimate for the number of clients. The primary * purpose is to make it so that the %N/%y escapes work in a DisplayConnect * greeting. A secondary purpose is to enforce any configured * MaxConnectionsPerHost limit. */ static int auth_scan_scoreboard(void) { char *key; void *v; config_rec *c = NULL; pr_scoreboard_entry_t *score = NULL; unsigned int cur = 0, ccur = 0, hcur = 0; char curr_server_addr[80] = {'\0'}; const char *client_addr = pr_netaddr_get_ipstr(session.c->remote_addr); snprintf(curr_server_addr, sizeof(curr_server_addr), "%s:%d", pr_netaddr_get_ipstr(session.c->local_addr), main_server->ServerPort); curr_server_addr[sizeof(curr_server_addr)-1] = '\0'; /* Determine how many users are currently connected */ if (pr_rewind_scoreboard() < 0) { pr_log_pri(PR_LOG_NOTICE, "error rewinding scoreboard: %s", strerror(errno)); } while ((score = pr_scoreboard_entry_read()) != NULL) { pr_signals_handle(); /* Make sure it matches our current server */ if (strcmp(score->sce_server_addr, curr_server_addr) == 0) { cur++; if (strcmp(score->sce_client_addr, client_addr) == 0) hcur++; /* Only count up authenticated clients, as per the documentation. */ if (strncmp(score->sce_user, "(none)", 7) == 0) continue; /* Note: the class member of the scoreboard entry will never be * NULL. At most, it may be the empty string. */ if (session.conn_class != NULL && strcasecmp(score->sce_class, session.conn_class->cls_name) == 0) { ccur++; } } } pr_restore_scoreboard(); key = "client-count"; (void) pr_table_remove(session.notes, key, NULL); v = palloc(session.pool, sizeof(unsigned int)); *((unsigned int *) v) = cur; if (pr_table_add(session.notes, key, v, sizeof(unsigned int)) < 0) { if (errno != EEXIST) { pr_log_pri(PR_LOG_WARNING, "warning: error stashing '%s': %s", key, strerror(errno)); } } if (session.conn_class != NULL) { key = "class-client-count"; (void) pr_table_remove(session.notes, key, NULL); v = palloc(session.pool, sizeof(unsigned int)); *((unsigned int *) v) = ccur; if (pr_table_add(session.notes, key, v, sizeof(unsigned int)) < 0) { if (errno != EEXIST) { pr_log_pri(PR_LOG_WARNING, "warning: error stashing '%s': %s", key, strerror(errno)); } } } /* Lookup any configured MaxConnectionsPerHost. */ c = find_config(main_server->conf, CONF_PARAM, "MaxConnectionsPerHost", FALSE); if (c) { unsigned int *max = c->argv[0]; if (*max && hcur > *max) { char maxstr[20]; char *msg = "Sorry, the maximum number of connections (%m) for your host " "are already connected."; pr_event_generate("mod_auth.max-connections-per-host", session.c); if (c->argc == 2) msg = c->argv[1]; memset(maxstr, '\0', sizeof(maxstr)); snprintf(maxstr, sizeof(maxstr), "%u", *max); maxstr[sizeof(maxstr)-1] = '\0'; pr_response_send(R_530, "%s", sreplace(session.pool, msg, "%m", maxstr, NULL)); pr_log_auth(PR_LOG_NOTICE, "Connection refused (MaxConnectionsPerHost %u)", *max); pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_CONFIG_ACL, "Denied by MaxConnectionsPerHost"); } } return 0; } static int have_client_limits(cmd_rec *cmd) { if (find_config(TOPLEVEL_CONF, CONF_PARAM, "MaxClientsPerClass", FALSE) != NULL) { return TRUE; } if (find_config(TOPLEVEL_CONF, CONF_PARAM, "MaxClientsPerHost", FALSE) != NULL) { return TRUE; } if (find_config(TOPLEVEL_CONF, CONF_PARAM, "MaxClientsPerUser", FALSE) != NULL) { return TRUE; } if (find_config(TOPLEVEL_CONF, CONF_PARAM, "MaxClients", FALSE) != NULL) { return TRUE; } if (find_config(TOPLEVEL_CONF, CONF_PARAM, "MaxHostsPerUser", FALSE) != NULL) { return TRUE; } return FALSE; } static int auth_count_scoreboard(cmd_rec *cmd, const char *user) { char *key; void *v; pr_scoreboard_entry_t *score = NULL; long cur = 0, hcur = 0, ccur = 0, hostsperuser = 1, usersessions = 0; config_rec *c = NULL, *maxc = NULL; /* First, check to see which Max* directives are configured. If none * are configured, then there is no need for us to needlessly scan the * ScoreboardFile. */ if (have_client_limits(cmd) == FALSE) { return 0; } /* Determine how many users are currently connected. */ /* We use this call to get the possibly-changed user name. */ c = pr_auth_get_anon_config(cmd->tmp_pool, &user, NULL, NULL); /* Gather our statistics. */ if (user != NULL) { char curr_server_addr[80] = {'\0'}; snprintf(curr_server_addr, sizeof(curr_server_addr), "%s:%d", pr_netaddr_get_ipstr(session.c->local_addr), main_server->ServerPort); curr_server_addr[sizeof(curr_server_addr)-1] = '\0'; if (pr_rewind_scoreboard() < 0) { pr_log_pri(PR_LOG_NOTICE, "error rewinding scoreboard: %s", strerror(errno)); } while ((score = pr_scoreboard_entry_read()) != NULL) { unsigned char same_host = FALSE; pr_signals_handle(); /* Make sure it matches our current server. */ if (strcmp(score->sce_server_addr, curr_server_addr) == 0) { if ((c != NULL && c->config_type == CONF_ANON && !strcmp(score->sce_user, user)) || c == NULL) { /* This small hack makes sure that cur is incremented properly * when dealing with anonymous logins (the timing of anonymous * login updates to the scoreboard makes this...odd). */ if (c != NULL && c->config_type == CONF_ANON && cur == 0) { cur = 1; } /* Only count authenticated clients, as per the documentation. */ if (strncmp(score->sce_user, "(none)", 7) == 0) { continue; } cur++; /* Count up sessions on a per-host basis. */ if (!strcmp(score->sce_client_addr, pr_netaddr_get_ipstr(session.c->remote_addr))) { same_host = TRUE; /* This small hack makes sure that hcur is incremented properly * when dealing with anonymous logins (the timing of anonymous * login updates to the scoreboard makes this...odd). */ if (c != NULL && c->config_type == CONF_ANON && hcur == 0) { hcur = 1; } hcur++; } /* Take a per-user count of connections. */ if (strcmp(score->sce_user, user) == 0) { usersessions++; /* Count up unique hosts. */ if (!same_host) { hostsperuser++; } } } if (session.conn_class != NULL && strcasecmp(score->sce_class, session.conn_class->cls_name) == 0) { ccur++; } } } pr_restore_scoreboard(); PRIVS_RELINQUISH } key = "client-count"; (void) pr_table_remove(session.notes, key, NULL); v = palloc(session.pool, sizeof(unsigned int)); *((unsigned int *) v) = cur; if (pr_table_add(session.notes, key, v, sizeof(unsigned int)) < 0) { if (errno != EEXIST) { pr_log_pri(PR_LOG_WARNING, "warning: error stashing '%s': %s", key, strerror(errno)); } } if (session.conn_class != NULL) { key = "class-client-count"; (void) pr_table_remove(session.notes, key, NULL); v = palloc(session.pool, sizeof(unsigned int)); *((unsigned int *) v) = ccur; if (pr_table_add(session.notes, key, v, sizeof(unsigned int)) < 0) { if (errno != EEXIST) { pr_log_pri(PR_LOG_WARNING, "warning: error stashing '%s': %s", key, strerror(errno)); } } } /* Try to determine what MaxClients/MaxHosts limits apply to this session * (if any) and count through the runtime file to see if this limit would * be exceeded. */ maxc = find_config(cmd->server->conf, CONF_PARAM, "MaxClientsPerClass", FALSE); while (session.conn_class != NULL && maxc) { char *maxstr = "Sorry, the maximum number of clients (%m) from your class " "are already connected."; unsigned int *max = maxc->argv[1]; if (strcmp(maxc->argv[0], session.conn_class->cls_name) != 0) { maxc = find_config_next(maxc, maxc->next, CONF_PARAM, "MaxClientsPerClass", FALSE); continue; } if (maxc->argc > 2) { maxstr = maxc->argv[2]; } if (*max && ccur > *max) { char maxn[20] = {'\0'}; pr_event_generate("mod_auth.max-clients-per-class", session.conn_class->cls_name); snprintf(maxn, sizeof(maxn), "%u", *max); pr_response_send(R_530, "%s", sreplace(cmd->tmp_pool, maxstr, "%m", maxn, NULL)); (void) pr_cmd_dispatch_phase(cmd, LOG_CMD_ERR, 0); pr_log_auth(PR_LOG_NOTICE, "Connection refused (MaxClientsPerClass %s %u)", session.conn_class->cls_name, *max); pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_CONFIG_ACL, "Denied by MaxClientsPerClass"); } break; } maxc = find_config(TOPLEVEL_CONF, CONF_PARAM, "MaxClientsPerHost", FALSE); if (maxc) { char *maxstr = "Sorry, the maximum number of clients (%m) from your host " "are already connected."; unsigned int *max = maxc->argv[0]; if (maxc->argc > 1) { maxstr = maxc->argv[1]; } if (*max && hcur > *max) { char maxn[20] = {'\0'}; pr_event_generate("mod_auth.max-clients-per-host", session.c); snprintf(maxn, sizeof(maxn), "%u", *max); pr_response_send(R_530, "%s", sreplace(cmd->tmp_pool, maxstr, "%m", maxn, NULL)); (void) pr_cmd_dispatch_phase(cmd, LOG_CMD_ERR, 0); pr_log_auth(PR_LOG_NOTICE, "Connection refused (MaxClientsPerHost %u)", *max); pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_CONFIG_ACL, "Denied by MaxClientsPerHost"); } } /* Check for any configured MaxClientsPerUser. */ maxc = find_config(TOPLEVEL_CONF, CONF_PARAM, "MaxClientsPerUser", FALSE); if (maxc) { char *maxstr = "Sorry, the maximum number of clients (%m) for this user " "are already connected."; unsigned int *max = maxc->argv[0]; if (maxc->argc > 1) { maxstr = maxc->argv[1]; } if (*max && usersessions > *max) { char maxn[20] = {'\0'}; pr_event_generate("mod_auth.max-clients-per-user", user); snprintf(maxn, sizeof(maxn), "%u", *max); pr_response_send(R_530, "%s", sreplace(cmd->tmp_pool, maxstr, "%m", maxn, NULL)); (void) pr_cmd_dispatch_phase(cmd, LOG_CMD_ERR, 0); pr_log_auth(PR_LOG_NOTICE, "Connection refused (MaxClientsPerUser %u)", *max); pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_CONFIG_ACL, "Denied by MaxClientsPerUser"); } } maxc = find_config(TOPLEVEL_CONF, CONF_PARAM, "MaxClients", FALSE); if (maxc) { char *maxstr = "Sorry, the maximum number of allowed clients (%m) are " "already connected."; unsigned int *max = maxc->argv[0]; if (maxc->argc > 1) { maxstr = maxc->argv[1]; } if (*max && cur > *max) { char maxn[20] = {'\0'}; pr_event_generate("mod_auth.max-clients", NULL); snprintf(maxn, sizeof(maxn), "%u", *max); pr_response_send(R_530, "%s", sreplace(cmd->tmp_pool, maxstr, "%m", maxn, NULL)); (void) pr_cmd_dispatch_phase(cmd, LOG_CMD_ERR, 0); pr_log_auth(PR_LOG_NOTICE, "Connection refused (MaxClients %u)", *max); pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_CONFIG_ACL, "Denied by MaxClients"); } } maxc = find_config(TOPLEVEL_CONF, CONF_PARAM, "MaxHostsPerUser", FALSE); if (maxc) { char *maxstr = "Sorry, the maximum number of hosts (%m) for this user are " "already connected."; unsigned int *max = maxc->argv[0]; if (maxc->argc > 1) { maxstr = maxc->argv[1]; } if (*max && hostsperuser > *max) { char maxn[20] = {'\0'}; pr_event_generate("mod_auth.max-hosts-per-user", user); snprintf(maxn, sizeof(maxn), "%u", *max); pr_response_send(R_530, "%s", sreplace(cmd->tmp_pool, maxstr, "%m", maxn, NULL)); (void) pr_cmd_dispatch_phase(cmd, LOG_CMD_ERR, 0); pr_log_auth(PR_LOG_NOTICE, "Connection refused (MaxHostsPerUser %u)", *max); pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_CONFIG_ACL, "Denied by MaxHostsPerUser"); } } return 0; } MODRET auth_pre_user(cmd_rec *cmd) { if (saw_first_user_cmd == FALSE) { if (pr_trace_get_level(timing_channel)) { unsigned long elapsed_ms; uint64_t finish_ms; pr_gettimeofday_millis(&finish_ms); elapsed_ms = (unsigned long) (finish_ms - session.connect_time_ms); pr_trace_msg(timing_channel, 4, "Time before first USER: %lu ms", elapsed_ms); } saw_first_user_cmd = TRUE; } if (logged_in) { return PR_DECLINED(cmd); } /* Close the passwd and group databases, because libc won't let us see new * entries to these files without this (only in PersistentPasswd mode). */ pr_auth_endpwent(cmd->tmp_pool); pr_auth_endgrent(cmd->tmp_pool); /* Check for a user name that exceeds PR_TUNABLE_LOGIN_MAX. */ if (strlen(cmd->arg) > PR_TUNABLE_LOGIN_MAX) { pr_log_pri(PR_LOG_NOTICE, "USER %s (Login failed): " "maximum USER length exceeded", cmd->arg); pr_response_add_err(R_501, _("Login incorrect.")); pr_cmd_set_errno(cmd, EPERM); errno = EPERM; return PR_ERROR(cmd); } return PR_DECLINED(cmd); } MODRET auth_user(cmd_rec *cmd) { int nopass = FALSE; config_rec *c; const char *denymsg = NULL, *user, *origuser; int failnopwprompt = 0, aclp, i; unsigned char *anon_require_passwd = NULL, *login_passwd_prompt = NULL; if (cmd->argc < 2) { return PR_ERROR_MSG(cmd, R_500, _("USER: command requires a parameter")); } if (logged_in) { /* If the client has already authenticated, BUT the given USER command * here is for the exact same user name, then allow the command to * succeed (Bug#4217). */ origuser = pr_table_get(session.notes, "mod_auth.orig-user", NULL); if (origuser != NULL && strcmp(origuser, cmd->arg) == 0) { pr_response_add(R_230, _("User %s logged in"), origuser); return PR_HANDLED(cmd); } pr_response_add_err(R_501, "%s", _("Reauthentication not supported")); return PR_ERROR(cmd); } user = cmd->arg; (void) pr_table_remove(session.notes, "mod_auth.orig-user", NULL); (void) pr_table_remove(session.notes, "mod_auth.anon-passwd", NULL); if (pr_table_add_dup(session.notes, "mod_auth.orig-user", user, 0) < 0) { pr_log_debug(DEBUG3, "error stashing 'mod_auth.orig-user' in " "session.notes: %s", strerror(errno)); } origuser = user; c = pr_auth_get_anon_config(cmd->tmp_pool, &user, NULL, NULL); /* Check for AccessDenyMsg */ denymsg = get_param_ptr((c ? c->subset : cmd->server->conf), "AccessDenyMsg", FALSE); if (denymsg != NULL) { if (strstr(denymsg, "%u") != NULL) { denymsg = sreplace(cmd->tmp_pool, denymsg, "%u", user, NULL); } } login_passwd_prompt = get_param_ptr( (c && c->config_type == CONF_ANON) ? c->subset : main_server->conf, "LoginPasswordPrompt", FALSE); if (login_passwd_prompt && *login_passwd_prompt == FALSE) { failnopwprompt = TRUE; } else { failnopwprompt = FALSE; } if (failnopwprompt) { if (!user) { (void) pr_table_remove(session.notes, "mod_auth.orig-user", NULL); (void) pr_table_remove(session.notes, "mod_auth.anon-passwd", NULL); pr_log_pri(PR_LOG_NOTICE, "USER %s (Login failed): Not a UserAlias", origuser); if (denymsg) { pr_response_send(R_530, "%s", denymsg); } else { pr_response_send(R_530, _("Login incorrect.")); } pr_session_end(0); } aclp = login_check_limits(main_server->conf, FALSE, TRUE, &i); if (c && c->config_type != CONF_ANON) { c = (config_rec *) pcalloc(session.pool, sizeof(config_rec)); c->config_type = CONF_ANON; c->name = ""; /* don't really need this yet */ c->subset = main_server->conf; } if (c) { if (!login_check_limits(c->subset, FALSE, TRUE, &i) || (!aclp && !i) ) { (void) pr_table_remove(session.notes, "mod_auth.orig-user", NULL); (void) pr_table_remove(session.notes, "mod_auth.anon-passwd", NULL); pr_log_auth(PR_LOG_NOTICE, "ANON %s: Limit access denies login", origuser); if (denymsg) { pr_response_send(R_530, "%s", denymsg); } else { pr_response_send(R_530, _("Login incorrect.")); } pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_CONFIG_ACL, "Denied by <Limit LOGIN>"); } } if (c == NULL && aclp == 0) { (void) pr_table_remove(session.notes, "mod_auth.orig-user", NULL); (void) pr_table_remove(session.notes, "mod_auth.anon-passwd", NULL); pr_log_auth(PR_LOG_NOTICE, "USER %s: Limit access denies login", origuser); if (denymsg) { pr_response_send(R_530, "%s", denymsg); } else { pr_response_send(R_530, "%s", _("Login incorrect.")); } pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_CONFIG_ACL, "Denied by <Limit LOGIN>"); } } if (c) anon_require_passwd = get_param_ptr(c->subset, "AnonRequirePassword", FALSE); if (c && user && (!anon_require_passwd || *anon_require_passwd == FALSE)) nopass = TRUE; session.gids = NULL; session.groups = NULL; session.user = NULL; session.group = NULL; if (nopass) { pr_response_add(R_331, _("Anonymous login ok, send your complete email " "address as your password")); } else if (pr_auth_requires_pass(cmd->tmp_pool, user) == FALSE) { /* Check to see if a password from the client is required. In the * vast majority of cases, a password will be required. */ /* Act as if we received a PASS command from the client. */ cmd_rec *fakecmd = pr_cmd_alloc(cmd->pool, 2, NULL); /* We use pstrdup() here, rather than assigning C_PASS directly, since * code elsewhere will attempt to modify this buffer, and C_PASS is * a string literal. */ fakecmd->argv[0] = pstrdup(fakecmd->pool, C_PASS); fakecmd->argv[1] = NULL; fakecmd->arg = NULL; c = add_config_param_set(&cmd->server->conf, "authenticated", 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = TRUE; authenticated_without_pass = TRUE; pr_log_auth(PR_LOG_NOTICE, "USER %s: Authenticated without password", user); pr_cmd_dispatch(fakecmd); } else { pr_response_add(R_331, _("Password required for %s"), (char *) cmd->argv[1]); } return PR_HANDLED(cmd); } /* Close the passwd and group databases, similar to auth_pre_user(). */ MODRET auth_pre_pass(cmd_rec *cmd) { const char *user; char *displaylogin; pr_auth_endpwent(cmd->tmp_pool); pr_auth_endgrent(cmd->tmp_pool); /* Handle cases where PASS might be sent before USER. */ user = pr_table_get(session.notes, "mod_auth.orig-user", NULL); if (user != NULL) { config_rec *c; c = find_config(main_server->conf, CONF_PARAM, "AllowEmptyPasswords", FALSE); if (c == NULL) { const char *anon_user; config_rec *anon_config; /* Since we have not authenticated yet, we cannot use the TOPLEVEL_CONF * macro to handle <Anonymous> sections. So we do it manually. */ anon_user = pstrdup(cmd->tmp_pool, user); anon_config = pr_auth_get_anon_config(cmd->tmp_pool, &anon_user, NULL, NULL); if (anon_config != NULL) { c = find_config(anon_config->subset, CONF_PARAM, "AllowEmptyPasswords", FALSE); } } if (c != NULL) { int allow_empty_passwords; allow_empty_passwords = *((int *) c->argv[0]); if (allow_empty_passwords == FALSE) { size_t passwd_len = 0; if (cmd->argc > 1) { if (cmd->arg != NULL) { passwd_len = strlen(cmd->arg); } } /* Make sure to NOT enforce 'AllowEmptyPasswords off' if e.g. * the AllowDotLogin TLSOption is in effect. */ if (cmd->argc == 1 || passwd_len == 0) { if (session.auth_mech == NULL || strcmp(session.auth_mech, "mod_tls.c") != 0) { pr_log_debug(DEBUG5, "Refusing empty password from user '%s' (AllowEmptyPasswords " "false)", user); pr_log_auth(PR_LOG_NOTICE, "Refusing empty password from user '%s'", user); pr_event_generate("mod_auth.empty-password", user); pr_response_add_err(R_501, _("Login incorrect.")); return PR_ERROR(cmd); } pr_log_debug(DEBUG9, "%s", "'AllowEmptyPasswords off' in effect, " "BUT client authenticated via the AllowDotLogin TLSOption"); } } } } /* Look for a DisplayLogin file which has an absolute path. If we find one, * open a filehandle, such that that file can be displayed even if the * session is chrooted. DisplayLogin files with relative paths will be * handled after chroot, preserving the old behavior. */ displaylogin = get_param_ptr(TOPLEVEL_CONF, "DisplayLogin", FALSE); if (displaylogin && *displaylogin == '/') { struct stat st; displaylogin_fh = pr_fsio_open(displaylogin, O_RDONLY); if (displaylogin_fh == NULL) { pr_log_debug(DEBUG6, "unable to open DisplayLogin file '%s': %s", displaylogin, strerror(errno)); } else { if (pr_fsio_fstat(displaylogin_fh, &st) < 0) { pr_log_debug(DEBUG6, "unable to stat DisplayLogin file '%s': %s", displaylogin, strerror(errno)); pr_fsio_close(displaylogin_fh); displaylogin_fh = NULL; } else { if (S_ISDIR(st.st_mode)) { errno = EISDIR; pr_log_debug(DEBUG6, "unable to use DisplayLogin file '%s': %s", displaylogin, strerror(errno)); pr_fsio_close(displaylogin_fh); displaylogin_fh = NULL; } } } } return PR_DECLINED(cmd); } MODRET auth_pass(cmd_rec *cmd) { const char *user = NULL; int res = 0; if (logged_in) { return PR_ERROR_MSG(cmd, R_503, _("You are already logged in")); } user = pr_table_get(session.notes, "mod_auth.orig-user", NULL); if (user == NULL) { (void) pr_table_remove(session.notes, "mod_auth.orig-user", NULL); (void) pr_table_remove(session.notes, "mod_auth.anon-passwd", NULL); return PR_ERROR_MSG(cmd, R_503, _("Login with USER first")); } /* Clear any potentially cached directory config */ session.anon_config = NULL; session.dir_config = NULL; res = setup_env(cmd->tmp_pool, cmd, user, cmd->arg); if (res == 1) { config_rec *c = NULL; c = add_config_param_set(&cmd->server->conf, "authenticated", 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = TRUE; set_auth_check(NULL); (void) pr_table_remove(session.notes, "mod_auth.anon-passwd", NULL); if (session.sf_flags & SF_ANON) { if (pr_table_add_dup(session.notes, "mod_auth.anon-passwd", pr_fs_decode_path(cmd->server->pool, cmd->arg), 0) < 0) { pr_log_debug(DEBUG3, "error stashing anonymous password in session.notes: %s", strerror(errno)); } } logged_in = TRUE; if (pr_trace_get_level(timing_channel)) { unsigned long elapsed_ms; uint64_t finish_ms; pr_gettimeofday_millis(&finish_ms); elapsed_ms = (unsigned long) (finish_ms - session.connect_time_ms); pr_trace_msg(timing_channel, 4, "Time before successful login (via '%s'): %lu ms", session.auth_mech, elapsed_ms); } return PR_HANDLED(cmd); } (void) pr_table_remove(session.notes, "mod_auth.anon-passwd", NULL); if (res == 0) { unsigned int max_logins, *max = NULL; const char *denymsg = NULL; /* check for AccessDenyMsg */ if ((denymsg = get_param_ptr((session.anon_config ? session.anon_config->subset : cmd->server->conf), "AccessDenyMsg", FALSE)) != NULL) { if (strstr(denymsg, "%u") != NULL) { denymsg = sreplace(cmd->tmp_pool, denymsg, "%u", user, NULL); } } max = get_param_ptr(main_server->conf, "MaxLoginAttempts", FALSE); if (max != NULL) { max_logins = *max; } else { max_logins = 3; } if (max_logins > 0 && ++auth_tries >= max_logins) { if (denymsg) { pr_response_send(R_530, "%s", denymsg); } else { pr_response_send(R_530, "%s", _("Login incorrect.")); } pr_log_auth(PR_LOG_NOTICE, "Maximum login attempts (%u) exceeded, connection refused", max_logins); /* Generate an event about this limit being exceeded. */ pr_event_generate("mod_auth.max-login-attempts", session.c); pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_CONFIG_ACL, "Denied by MaxLoginAttempts"); } return PR_ERROR_MSG(cmd, R_530, denymsg ? denymsg : _("Login incorrect.")); } return PR_HANDLED(cmd); } MODRET auth_acct(cmd_rec *cmd) { pr_response_add(R_502, _("ACCT command not implemented")); return PR_HANDLED(cmd); } MODRET auth_rein(cmd_rec *cmd) { pr_response_add(R_502, _("REIN command not implemented")); return PR_HANDLED(cmd); } /* FSIO callbacks for providing a fake robots.txt file, for the AnonAllowRobots * functionality. */ #define AUTH_ROBOTS_TXT "User-agent: *\nDisallow: /\n" #define AUTH_ROBOTS_TXT_FD 6742 static int robots_fsio_stat(pr_fs_t *fs, const char *path, struct stat *st) { st->st_dev = (dev_t) 0; st->st_ino = (ino_t) 0; st->st_mode = (S_IFREG|S_IRUSR|S_IRGRP|S_IROTH); st->st_nlink = 0; st->st_uid = (uid_t) 0; st->st_gid = (gid_t) 0; st->st_atime = 0; st->st_mtime = 0; st->st_ctime = 0; st->st_size = strlen(AUTH_ROBOTS_TXT); st->st_blksize = 1024; st->st_blocks = 1; return 0; } static int robots_fsio_fstat(pr_fh_t *fh, int fd, struct stat *st) { if (fd != AUTH_ROBOTS_TXT_FD) { errno = EINVAL; return -1; } return robots_fsio_stat(NULL, NULL, st); } static int robots_fsio_lstat(pr_fs_t *fs, const char *path, struct stat *st) { return robots_fsio_stat(fs, path, st); } static int robots_fsio_unlink(pr_fs_t *fs, const char *path) { return 0; } static int robots_fsio_open(pr_fh_t *fh, const char *path, int flags) { if (flags != O_RDONLY) { errno = EINVAL; return -1; } return AUTH_ROBOTS_TXT_FD; } static int robots_fsio_close(pr_fh_t *fh, int fd) { if (fd != AUTH_ROBOTS_TXT_FD) { errno = EINVAL; return -1; } return 0; } static int robots_fsio_read(pr_fh_t *fh, int fd, char *buf, size_t bufsz) { size_t robots_len; if (fd != AUTH_ROBOTS_TXT_FD) { errno = EINVAL; return -1; } robots_len = strlen(AUTH_ROBOTS_TXT); if (bufsz < robots_len) { errno = EINVAL; return -1; } memcpy(buf, AUTH_ROBOTS_TXT, robots_len); return (int) robots_len; } static int robots_fsio_write(pr_fh_t *fh, int fd, const char *buf, size_t bufsz) { if (fd != AUTH_ROBOTS_TXT_FD) { errno = EINVAL; return -1; } return (int) bufsz; } static int robots_fsio_access(pr_fs_t *fs, const char *path, int mode, uid_t uid, gid_t gid, array_header *suppl_gids) { if (mode != R_OK) { errno = EACCES; return -1; } return 0; } static int robots_fsio_faccess(pr_fh_t *fh, int mode, uid_t uid, gid_t gid, array_header *suppl_gids) { if (fh->fh_fd != AUTH_ROBOTS_TXT_FD) { errno = EINVAL; return -1; } if (mode != R_OK) { errno = EACCES; return -1; } return 0; } MODRET auth_pre_retr(cmd_rec *cmd) { const char *path; pr_fs_t *curr_fs = NULL; struct stat st; /* Only apply this for <Anonymous> logins. */ if (session.anon_config == NULL) { return PR_DECLINED(cmd); } if (auth_anon_allow_robots == TRUE) { return PR_DECLINED(cmd); } auth_anon_allow_robots_enabled = FALSE; path = dir_canonical_path(cmd->tmp_pool, cmd->arg); if (strcasecmp(path, "/robots.txt") != 0) { return PR_DECLINED(cmd); } /* If a previous REST command, with a non-zero value, has been sent, then * do nothing. Ugh. */ if (session.restart_pos > 0) { pr_log_debug(DEBUG10, "'AnonAllowRobots off' in effect, but cannot " "support resumed download (REST %" PR_LU " previously sent by client)", (pr_off_t) session.restart_pos); return PR_DECLINED(cmd); } pr_fs_clear_cache2(path); if (pr_fsio_lstat(path, &st) == 0) { /* There's an existing REAL "robots.txt" file on disk; use that, and * preserve the principle of least surprise. */ pr_log_debug(DEBUG10, "'AnonAllowRobots off' in effect, but have " "real 'robots.txt' file on disk; using that"); return PR_DECLINED(cmd); } curr_fs = pr_get_fs(path, NULL); if (curr_fs != NULL) { pr_fs_t *robots_fs; robots_fs = pr_register_fs(cmd->pool, "robots", path); if (robots_fs == NULL) { pr_log_debug(DEBUG8, "'AnonAllowRobots off' in effect, but failed to " "register FS: %s", strerror(errno)); return PR_DECLINED(cmd); } /* Use enough of our own custom FSIO callbacks to be able to provide * a fake "robots.txt" file. */ robots_fs->stat = robots_fsio_stat; robots_fs->fstat = robots_fsio_fstat; robots_fs->lstat = robots_fsio_lstat; robots_fs->unlink = robots_fsio_unlink; robots_fs->open = robots_fsio_open; robots_fs->close = robots_fsio_close; robots_fs->read = robots_fsio_read; robots_fs->write = robots_fsio_write; robots_fs->access = robots_fsio_access; robots_fs->faccess = robots_fsio_faccess; /* For all other FSIO callbacks, use the underlying FS. */ robots_fs->rename = curr_fs->rename; robots_fs->lseek = curr_fs->lseek; robots_fs->link = curr_fs->link; robots_fs->readlink = curr_fs->readlink; robots_fs->symlink = curr_fs->symlink; robots_fs->ftruncate = curr_fs->ftruncate; robots_fs->truncate = curr_fs->truncate; robots_fs->chmod = curr_fs->chmod; robots_fs->fchmod = curr_fs->fchmod; robots_fs->chown = curr_fs->chown; robots_fs->fchown = curr_fs->fchown; robots_fs->lchown = curr_fs->lchown; robots_fs->utimes = curr_fs->utimes; robots_fs->futimes = curr_fs->futimes; robots_fs->fsync = curr_fs->fsync; pr_fs_clear_cache2(path); auth_anon_allow_robots_enabled = TRUE; } return PR_DECLINED(cmd); } MODRET auth_post_retr(cmd_rec *cmd) { if (auth_anon_allow_robots == TRUE) { return PR_DECLINED(cmd); } if (auth_anon_allow_robots_enabled == TRUE) { int res; res = pr_unregister_fs("/robots.txt"); if (res < 0) { pr_log_debug(DEBUG9, "error removing 'robots' FS for '/robots.txt': %s", strerror(errno)); } auth_anon_allow_robots_enabled = FALSE; } return PR_DECLINED(cmd); } /* Configuration handlers */ MODRET set_accessdenymsg(cmd_rec *cmd) { config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); c = add_config_param_str(cmd->argv[0], 1, cmd->argv[1]); c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } MODRET set_accessgrantmsg(cmd_rec *cmd) { config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); c = add_config_param_str(cmd->argv[0], 1, cmd->argv[1]); c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } /* usage: AllowChrootSymlinks on|off */ MODRET set_allowchrootsymlinks(cmd_rec *cmd) { int allow_chroot_symlinks = -1; config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL); allow_chroot_symlinks = get_boolean(cmd, 1); if (allow_chroot_symlinks == -1) { CONF_ERROR(cmd, "expected Boolean parameter"); } c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(int)); *((int *) c->argv[0]) = allow_chroot_symlinks; return PR_HANDLED(cmd); } /* usage: AllowEmptyPasswords on|off */ MODRET set_allowemptypasswords(cmd_rec *cmd) { int allow_empty_passwords = -1; config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); allow_empty_passwords = get_boolean(cmd, 1); if (allow_empty_passwords == -1) { CONF_ERROR(cmd, "expected Boolean parameter"); } c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(int)); *((int *) c->argv[0]) = allow_empty_passwords; c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } /* usage: AnonAllowRobots on|off */ MODRET set_anonallowrobots(cmd_rec *cmd) { int allow_robots = -1; config_rec *c; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ANON); allow_robots = get_boolean(cmd, 1); if (allow_robots == -1) { CONF_ERROR(cmd, "expected Boolean parameter"); } c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = palloc(c->pool, sizeof(int)); *((int *) c->argv[0]) = allow_robots; return PR_HANDLED(cmd); } MODRET set_anonrequirepassword(cmd_rec *cmd) { int bool = -1; config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ANON); bool = get_boolean(cmd, 1); if (bool == -1) CONF_ERROR(cmd, "expected Boolean parameter"); c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = bool; return PR_HANDLED(cmd); } /* usage: AnonRejectPasswords pattern [flags] */ MODRET set_anonrejectpasswords(cmd_rec *cmd) { #ifdef PR_USE_REGEX config_rec *c; pr_regex_t *pre = NULL; int notmatch = FALSE, regex_flags = REG_EXTENDED|REG_NOSUB, res = 0; char *pattern = NULL; if (cmd->argc-1 < 1 || cmd->argc-1 > 2) { CONF_ERROR(cmd, "bad number of parameters"); } CHECK_CONF(cmd, CONF_ANON); /* Make sure that, if present, the flags parameter is correctly formatted. */ if (cmd->argc-1 == 2) { int flags = 0; /* We need to parse the flags parameter here, to see if any flags which * affect the compilation of the regex (e.g. NC) are present. */ flags = pr_filter_parse_flags(cmd->tmp_pool, cmd->argv[2]); if (flags < 0) { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, ": badly formatted flags parameter: '", cmd->argv[2], "'", NULL)); } if (flags == 0) { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, ": unknown flags '", cmd->argv[2], "'", NULL)); } regex_flags |= flags; } pre = pr_regexp_alloc(&auth_module); pattern = cmd->argv[1]; if (*pattern == '!') { notmatch = TRUE; pattern++; } res = pr_regexp_compile(pre, pattern, regex_flags); if (res != 0) { char errstr[200] = {'\0'}; pr_regexp_error(res, pre, errstr, 200); pr_regexp_free(NULL, pre); CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "Unable to compile regex '", cmd->argv[1], "': ", errstr, NULL)); } c = add_config_param(cmd->argv[0], 2, pre, NULL); c->argv[1] = palloc(c->pool, sizeof(int)); *((int *) c->argv[1]) = notmatch; return PR_HANDLED(cmd); #else CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "The ", cmd->argv[0], " directive " "cannot be used on this system, as you do not have POSIX compliant " "regex support", NULL)); #endif } MODRET set_authaliasonly(cmd_rec *cmd) { int bool = -1; config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); bool = get_boolean(cmd, 1); if (bool == -1) CONF_ERROR(cmd, "expected Boolean parameter"); c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = bool; c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } MODRET set_authusingalias(cmd_rec *cmd) { int bool = -1; config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ANON); bool = get_boolean(cmd, 1); if (bool == -1) CONF_ERROR(cmd, "expected Boolean parameter"); c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = bool; return PR_HANDLED(cmd); } MODRET set_createhome(cmd_rec *cmd) { int bool = -1, start = 2; mode_t mode = (mode_t) 0700, dirmode = (mode_t) 0711; char *skel_path = NULL; config_rec *c = NULL; uid_t cuid = 0; gid_t cgid = 0, hgid = -1; unsigned long flags = 0UL; if (cmd->argc-1 < 1) { CONF_ERROR(cmd, "wrong number of parameters"); } CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL); bool = get_boolean(cmd, 1); if (bool == -1) { CONF_ERROR(cmd, "expected Boolean parameter"); } /* No need to process the rest if bool is FALSE. */ if (bool == FALSE) { c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = bool; return PR_HANDLED(cmd); } /* Check the mode parameter, if present */ if (cmd->argc-1 >= 2 && strcasecmp(cmd->argv[2], "dirmode") != 0 && strcasecmp(cmd->argv[2], "skel") != 0) { char *tmp = NULL; mode = strtol(cmd->argv[2], &tmp, 8); if (tmp && *tmp) CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, ": bad mode parameter: '", cmd->argv[2], "'", NULL)); start = 3; } if (cmd->argc-1 > 2) { register unsigned int i; /* Cycle through the rest of the parameters */ for (i = start; i < cmd->argc;) { if (strcasecmp(cmd->argv[i], "skel") == 0) { struct stat st; /* Check that the skel directory, if configured, meets the * requirements. */ skel_path = cmd->argv[++i]; if (*skel_path != '/') { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "skel path '", skel_path, "' is not a full path", NULL)); } if (pr_fsio_stat(skel_path, &st) < 0) { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "unable to stat '", skel_path, "': ", strerror(errno), NULL)); } if (!S_ISDIR(st.st_mode)) { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "'", skel_path, "' is not a directory", NULL)); } /* Must not be world-writable. */ if (st.st_mode & S_IWOTH) { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "'", skel_path, "' is world-writable", NULL)); } /* Move the index past the skel parameter */ i++; } else if (strcasecmp(cmd->argv[i], "dirmode") == 0) { char *tmp = NULL; dirmode = strtol(cmd->argv[++i], &tmp, 8); if (tmp && *tmp) CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "bad mode parameter: '", cmd->argv[i], "'", NULL)); /* Move the index past the dirmode parameter */ i++; } else if (strcasecmp(cmd->argv[i], "uid") == 0) { /* Check for a "~" parameter. */ if (strncmp(cmd->argv[i+1], "~", 2) != 0) { uid_t uid; if (pr_str2uid(cmd->argv[++i], &uid) < 0) { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "bad UID parameter: '", cmd->argv[i], "'", NULL)); } cuid = uid; } else { cuid = (uid_t) -1; i++; } /* Move the index past the uid parameter */ i++; } else if (strcasecmp(cmd->argv[i], "gid") == 0) { /* Check for a "~" parameter. */ if (strncmp(cmd->argv[i+1], "~", 2) != 0) { gid_t gid; if (pr_str2gid(cmd->argv[++i], &gid) < 0) { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "bad GID parameter: '", cmd->argv[i], "'", NULL)); } cgid = gid; } else { cgid = (gid_t) -1; i++; } /* Move the index past the gid parameter */ i++; } else if (strcasecmp(cmd->argv[i], "homegid") == 0) { char *tmp = NULL; gid_t gid; gid = strtol(cmd->argv[++i], &tmp, 10); if (tmp && *tmp) { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "bad GID parameter: '", cmd->argv[i], "'", NULL)); } hgid = gid; /* Move the index past the homegid parameter */ i++; } else if (strcasecmp(cmd->argv[i], "NoRootPrivs") == 0) { flags |= PR_MKHOME_FL_USE_USER_PRIVS; i++; } else { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "unknown parameter: '", cmd->argv[i], "'", NULL)); } } } c = add_config_param(cmd->argv[0], 8, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = bool; c->argv[1] = pcalloc(c->pool, sizeof(mode_t)); *((mode_t *) c->argv[1]) = mode; c->argv[2] = pcalloc(c->pool, sizeof(mode_t)); *((mode_t *) c->argv[2]) = dirmode; if (skel_path) { c->argv[3] = pstrdup(c->pool, skel_path); } c->argv[4] = pcalloc(c->pool, sizeof(uid_t)); *((uid_t *) c->argv[4]) = cuid; c->argv[5] = pcalloc(c->pool, sizeof(gid_t)); *((gid_t *) c->argv[5]) = cgid; c->argv[6] = pcalloc(c->pool, sizeof(gid_t)); *((gid_t *) c->argv[6]) = hgid; c->argv[7] = pcalloc(c->pool, sizeof(unsigned long)); *((unsigned long *) c->argv[7]) = flags; return PR_HANDLED(cmd); } MODRET add_defaultroot(cmd_rec *cmd) { config_rec *c; char *dir; unsigned int argc; void **argv; array_header *acl = NULL; CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL); if (cmd->argc < 2) { CONF_ERROR(cmd, "syntax: DefaultRoot <directory> [<group-expression>]"); } argc = cmd->argc - 2; argv = cmd->argv; dir = *++argv; /* dir must be / or ~. */ if (*dir != '/' && *dir != '~') { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "(", dir, ") absolute pathname " "required", NULL)); } if (strchr(dir, '*')) { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "(", dir, ") wildcards not allowed " "in pathname", NULL)); } if (*(dir + strlen(dir) - 1) != '/') { dir = pstrcat(cmd->tmp_pool, dir, "/", NULL); } acl = pr_expr_create(cmd->tmp_pool, &argc, (char **) argv); c = add_config_param(cmd->argv[0], 0); c->argc = argc + 1; c->argv = pcalloc(c->pool, (argc + 2) * sizeof(void *)); argv = c->argv; *argv++ = pstrdup(c->pool, dir); if (argc && acl) while(argc--) { *argv++ = pstrdup(c->pool, *((char **) acl->elts)); acl->elts = ((char **) acl->elts) + 1; } *argv = NULL; return PR_HANDLED(cmd); } MODRET add_defaultchdir(cmd_rec *cmd) { config_rec *c; char *dir; unsigned int argc; void **argv; array_header *acl = NULL; CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); if (cmd->argc < 2) { CONF_ERROR(cmd, "syntax: DefaultChdir <directory> [<group-expression>]"); } argc = cmd->argc - 2; argv = cmd->argv; dir = *++argv; if (strchr(dir, '*')) { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "(", dir, ") wildcards not allowed " "in pathname", NULL)); } if (*(dir + strlen(dir) - 1) != '/') { dir = pstrcat(cmd->tmp_pool, dir, "/", NULL); } acl = pr_expr_create(cmd->tmp_pool, &argc, (char **) argv); c = add_config_param(cmd->argv[0], 0); c->argc = argc + 1; c->argv = pcalloc(c->pool, (argc + 2) * sizeof(void *)); argv = c->argv; *argv++ = pstrdup(c->pool, dir); if (argc && acl) { while(argc--) { *argv++ = pstrdup(c->pool, *((char **) acl->elts)); acl->elts = ((char **) acl->elts) + 1; } } *argv = NULL; c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } MODRET set_displaylogin(cmd_rec *cmd) { config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); c = add_config_param_str(cmd->argv[0], 1, cmd->argv[1]); c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } MODRET set_grouppassword(cmd_rec *cmd) { config_rec *c = NULL; CHECK_ARGS(cmd, 2); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); c = add_config_param_str(cmd->argv[0], 2, cmd->argv[1], cmd->argv[2]); c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } MODRET set_loginpasswordprompt(cmd_rec *cmd) { int bool = -1; config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); bool = get_boolean(cmd, 1); if (bool == -1) CONF_ERROR(cmd, "expected Boolean parameter"); c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = bool; c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } /* usage: MaxClientsPerClass class max|"none" ["message"] */ MODRET set_maxclientsclass(cmd_rec *cmd) { int max; config_rec *c; CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL); if (strcasecmp(cmd->argv[2], "none") == 0) max = 0; else { char *endp = NULL; max = (int) strtol(cmd->argv[2], &endp, 10); if ((endp && *endp) || max < 1) CONF_ERROR(cmd, "max must be 'none' or a number greater than 0"); } if (cmd->argc == 4) { c = add_config_param(cmd->argv[0], 3, NULL, NULL, NULL); c->argv[0] = pstrdup(c->pool, cmd->argv[1]); c->argv[1] = pcalloc(c->pool, sizeof(unsigned int)); *((unsigned int *) c->argv[1]) = max; c->argv[2] = pstrdup(c->pool, cmd->argv[3]); } else { c = add_config_param(cmd->argv[0], 2, NULL, NULL); c->argv[0] = pstrdup(c->pool, cmd->argv[1]); c->argv[1] = pcalloc(c->pool, sizeof(unsigned int)); *((unsigned int *) c->argv[1]) = max; } return PR_HANDLED(cmd); } /* usage: MaxClients max|"none" ["message"] */ MODRET set_maxclients(cmd_rec *cmd) { int max; config_rec *c = NULL; if (cmd->argc < 2 || cmd->argc > 3) CONF_ERROR(cmd, "wrong number of parameters"); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); if (!strcasecmp(cmd->argv[1], "none")) max = 0; else { char *endp = NULL; max = (int) strtol(cmd->argv[1], &endp, 10); if ((endp && *endp) || max < 1) CONF_ERROR(cmd, "parameter must be 'none' or a number greater than 0"); } if (cmd->argc == 3) { c = add_config_param(cmd->argv[0], 2, NULL, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned int)); *((unsigned int *) c->argv[0]) = max; c->argv[1] = pstrdup(c->pool, cmd->argv[2]); } else { c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned int)); *((unsigned int *) c->argv[0]) = max; } c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } /* usage: MaxClientsPerHost max|"none" ["message"] */ MODRET set_maxhostclients(cmd_rec *cmd) { int max; config_rec *c = NULL; if (cmd->argc < 2 || cmd->argc > 3) CONF_ERROR(cmd, "wrong number of parameters"); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); if (!strcasecmp(cmd->argv[1], "none")) max = 0; else { char *endp = NULL; max = (int) strtol(cmd->argv[1], &endp, 10); if ((endp && *endp) || max < 1) CONF_ERROR(cmd, "parameter must be 'none' or a number greater than 0"); } if (cmd->argc == 3) { c = add_config_param(cmd->argv[0], 2, NULL, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned int)); *((unsigned int *) c->argv[0]) = max; c->argv[1] = pstrdup(c->pool, cmd->argv[2]); } else { c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned int)); *((unsigned int *) c->argv[0]) = max; } c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } /* usage: MaxClientsPerUser max|"none" ["message"] */ MODRET set_maxuserclients(cmd_rec *cmd) { int max; config_rec *c = NULL; if (cmd->argc < 2 || cmd->argc > 3) CONF_ERROR(cmd, "wrong number of parameters"); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); if (!strcasecmp(cmd->argv[1], "none")) max = 0; else { char *endp = NULL; max = (int) strtol(cmd->argv[1], &endp, 10); if ((endp && *endp) || max < 1) CONF_ERROR(cmd, "parameter must be 'none' or a number greater than 0"); } if (cmd->argc == 3) { c = add_config_param(cmd->argv[0], 2, NULL, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned int)); *((unsigned int *) c->argv[0]) = max; c->argv[1] = pstrdup(c->pool, cmd->argv[2]); } else { c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned int)); *((unsigned int *) c->argv[0]) = max; } c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } /* usage: MaxConnectionsPerHost max|"none" ["message"] */ MODRET set_maxconnectsperhost(cmd_rec *cmd) { int max; config_rec *c; if (cmd->argc < 2 || cmd->argc > 3) CONF_ERROR(cmd, "wrong number of parameters"); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL); if (strcasecmp(cmd->argv[1], "none") == 0) max = 0; else { char *tmp = NULL; max = (int) strtol(cmd->argv[1], &tmp, 10); if ((tmp && *tmp) || max < 1) CONF_ERROR(cmd, "parameter must be 'none' or a number greater than 0"); } if (cmd->argc == 3) { c = add_config_param(cmd->argv[0], 2, NULL, NULL); c->argv[1] = pstrdup(c->pool, cmd->argv[2]); } else c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned int)); *((unsigned int *) c->argv[0]) = max; return PR_HANDLED(cmd); } /* usage: MaxHostsPerUser max|"none" ["message"] */ MODRET set_maxhostsperuser(cmd_rec *cmd) { int max; config_rec *c = NULL; CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); if (cmd->argc < 2 || cmd->argc > 3) CONF_ERROR(cmd, "wrong number of parameters"); if (!strcasecmp(cmd->argv[1], "none")) max = 0; else { char *endp = NULL; max = (int) strtol(cmd->argv[1], &endp, 10); if ((endp && *endp) || max < 1) CONF_ERROR(cmd, "parameter must be 'none' or a number greater than 0"); } if (cmd->argc == 3) { c = add_config_param(cmd->argv[0], 2, NULL, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned int)); *((unsigned int *) c->argv[0]) = max; c->argv[1] = pstrdup(c->pool, cmd->argv[2]); } else { c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned int)); *((unsigned int *) c->argv[0]) = max; } c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } MODRET set_maxloginattempts(cmd_rec *cmd) { int max; config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL); if (strcasecmp(cmd->argv[1], "none") == 0) { max = 0; } else { char *endp = NULL; max = (int) strtol(cmd->argv[1], &endp, 10); if ((endp && *endp) || max < 1) CONF_ERROR(cmd, "parameter must be 'none' or a number greater than 0"); } c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned int)); *((unsigned int *) c->argv[0]) = max; return PR_HANDLED(cmd); } /* usage: MaxPasswordSize len */ MODRET set_maxpasswordsize(cmd_rec *cmd) { config_rec *c; size_t password_len; char *len, *ptr = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL); len = cmd->argv[1]; if (*len == '-') { CONF_ERROR(cmd, "badly formatted parameter"); } password_len = strtoul(len, &ptr, 10); if (ptr && *ptr) { CONF_ERROR(cmd, "badly formatted parameter"); } /* XXX Applies to the following modules, which use crypt(3): * * mod_ldap (ldap_auth_check; "check" authtab) * ldap_auth_auth ("auth" authtab) calls pr_auth_check() * mod_sql (sql_auth_crypt, via SQLAuthTypes; cmd_check "check" authtab dispatches here) * cmd_auth ("auth" authtab) calls pr_auth_check() * mod_auth_file (authfile_chkpass, "check" authtab) * authfile_auth ("auth" authtab) calls pr_auth_check() * mod_auth_unix (pw_check, "check" authtab) * pw_auth ("auth" authtab) calls pr_auth_check() * * mod_sftp uses pr_auth_authenticate(), which will dispatch into above * * mod_radius does NOT use either -- up to RADIUS server policy? * * Is there a common code path that all of the above go through? */ c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = palloc(c->pool, sizeof(size_t)); *((size_t *) c->argv[0]) = password_len; return PR_HANDLED(cmd); } MODRET set_requirevalidshell(cmd_rec *cmd) { int bool = -1; config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); bool = get_boolean(cmd, 1); if (bool == -1) CONF_ERROR(cmd, "expected Boolean parameter"); c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = bool; c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } /* usage: RewriteHome on|off */ MODRET set_rewritehome(cmd_rec *cmd) { int bool = -1; config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL); bool = get_boolean(cmd, 1); if (bool == -1) CONF_ERROR(cmd, "expected Boolean parameter"); c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(int)); *((int *) c->argv[0]) = bool; return PR_HANDLED(cmd); } MODRET set_rootlogin(cmd_rec *cmd) { int bool = -1; config_rec *c = NULL; CHECK_ARGS(cmd,1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); bool = get_boolean(cmd, 1); if (bool == -1) CONF_ERROR(cmd, "expected Boolean parameter"); c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = (unsigned char) bool; c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } /* usage: RootRevoke on|off|UseNonCompliantActiveTransfer */ MODRET set_rootrevoke(cmd_rec *cmd) { int root_revoke = -1; config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); /* A RootRevoke value of 0 indicates 'false', 1 indicates 'true', and * 2 indicates 'NonCompliantActiveTransfer'. */ root_revoke = get_boolean(cmd, 1); if (root_revoke == -1) { if (strcasecmp(cmd->argv[1], "UseNonCompliantActiveTransfer") != 0 && strcasecmp(cmd->argv[1], "UseNonCompliantActiveTransfers") != 0) { CONF_ERROR(cmd, "expected Boolean parameter"); } root_revoke = 2; } c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = (unsigned char) root_revoke; c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } MODRET set_timeoutlogin(cmd_rec *cmd) { int timeout = -1; config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL); if (pr_str_get_duration(cmd->argv[1], &timeout) < 0) { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "error parsing timeout value '", cmd->argv[1], "': ", strerror(errno), NULL)); } c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(int)); *((int *) c->argv[0]) = timeout; return PR_HANDLED(cmd); } MODRET set_timeoutsession(cmd_rec *cmd) { int timeout = 0, precedence = 0; config_rec *c = NULL; int ctxt = (cmd->config && cmd->config->config_type != CONF_PARAM ? cmd->config->config_type : cmd->server->config_type ? cmd->server->config_type : CONF_ROOT); /* this directive must have either 1 or 3 arguments */ if (cmd->argc-1 != 1 && cmd->argc-1 != 3) { CONF_ERROR(cmd, "missing parameters"); } CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); /* Set the precedence for this config_rec based on its configuration * context. */ if (ctxt & CONF_GLOBAL) { precedence = 1; /* These will never appear simultaneously */ } else if ((ctxt & CONF_ROOT) || (ctxt & CONF_VIRTUAL)) { precedence = 2; } else if (ctxt & CONF_ANON) { precedence = 3; } if (pr_str_get_duration(cmd->argv[1], &timeout) < 0) { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "error parsing timeout value '", cmd->argv[1], "': ", strerror(errno), NULL)); } if (timeout == 0) { /* do nothing */ return PR_HANDLED(cmd); } if (cmd->argc-1 == 3) { if (strncmp(cmd->argv[2], "user", 5) == 0 || strncmp(cmd->argv[2], "group", 6) == 0 || strncmp(cmd->argv[2], "class", 6) == 0) { /* no op */ } else { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, cmd->argv[0], ": unknown classifier used: '", cmd->argv[2], "'", NULL)); } } if (cmd->argc-1 == 1) { c = add_config_param(cmd->argv[0], 2, NULL); c->argv[0] = pcalloc(c->pool, sizeof(int)); *((int *) c->argv[0]) = timeout; c->argv[1] = pcalloc(c->pool, sizeof(unsigned int)); *((unsigned int *) c->argv[1]) = precedence; } else if (cmd->argc-1 == 3) { array_header *acl = NULL; unsigned int argc; void **argv; argc = cmd->argc - 3; argv = cmd->argv + 2; acl = pr_expr_create(cmd->tmp_pool, &argc, (char **) argv); c = add_config_param(cmd->argv[0], 0); c->argc = argc + 2; /* Add 3 to argc for the argv of the config_rec: one for the * seconds value, one for the precedence, one for the classifier, * and one for the terminating NULL. */ c->argv = pcalloc(c->pool, ((argc + 4) * sizeof(void *))); /* Capture the config_rec's argv pointer for doing the by-hand * population. */ argv = c->argv; /* Copy in the seconds. */ *argv = pcalloc(c->pool, sizeof(int)); *((int *) *argv++) = timeout; /* Copy in the precedence. */ *argv = pcalloc(c->pool, sizeof(unsigned int)); *((unsigned int *) *argv++) = precedence; /* Copy in the classifier. */ *argv++ = pstrdup(c->pool, cmd->argv[2]); /* now, copy in the expression arguments */ if (argc && acl) { while (argc--) { *argv++ = pstrdup(c->pool, *((char **) acl->elts)); acl->elts = ((char **) acl->elts) + 1; } } /* don't forget the terminating NULL */ *argv = NULL; } else { /* Should never reach here. */ CONF_ERROR(cmd, "wrong number of parameters"); } c->flags |= CF_MERGEDOWN_MULTI; return PR_HANDLED(cmd); } MODRET set_useftpusers(cmd_rec *cmd) { int bool = -1; config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); bool = get_boolean(cmd, 1); if (bool == -1) CONF_ERROR(cmd, "expected Boolean parameter"); c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = bool; c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } /* usage: UseLastlog on|off */ MODRET set_uselastlog(cmd_rec *cmd) { #ifdef PR_USE_LASTLOG int bool; config_rec *c; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL); bool = get_boolean(cmd, 1); if (bool == -1) CONF_ERROR(cmd, "expected Boolean parameter"); c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = bool; return PR_HANDLED(cmd); #else CONF_ERROR(cmd, "requires lastlog support (--with-lastlog)"); #endif /* PR_USE_LASTLOG */ } /* usage: UserAlias alias real-user */ MODRET set_useralias(cmd_rec *cmd) { config_rec *c = NULL; char *alias, *real_user; CHECK_ARGS(cmd, 2); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); /* Make sure that the given names differ. */ alias = cmd->argv[1]; real_user = cmd->argv[2]; if (strcmp(alias, real_user) == 0) { CONF_ERROR(cmd, "alias and real user names must differ"); } c = add_config_param_str(cmd->argv[0], 2, alias, real_user); /* Note: only merge this directive down if it is not appearing in an * <Anonymous> context. */ if (!check_context(cmd, CONF_ANON)) { c->flags |= CF_MERGEDOWN_MULTI; } return PR_HANDLED(cmd); } MODRET set_userdirroot(cmd_rec *cmd) { int bool = -1; config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ANON); bool = get_boolean(cmd, 1); if (bool == -1) CONF_ERROR(cmd, "expected Boolean parameter"); c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = bool; return PR_HANDLED(cmd); } MODRET set_userpassword(cmd_rec *cmd) { config_rec *c = NULL; CHECK_ARGS(cmd, 2); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); c = add_config_param_str(cmd->argv[0], 2, cmd->argv[1], cmd->argv[2]); c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } /* usage: WtmpLog on|off */ MODRET set_wtmplog(cmd_rec *cmd) { int use_wtmp = -1; config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); if (strcasecmp(cmd->argv[1], "NONE") == 0) { use_wtmp = FALSE; } else { use_wtmp = get_boolean(cmd, 1); if (use_wtmp == -1) { CONF_ERROR(cmd, "expected Boolean parameter"); } } c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = use_wtmp; c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } /* Module API tables */ static conftable auth_conftab[] = { { "AccessDenyMsg", set_accessdenymsg, NULL }, { "AccessGrantMsg", set_accessgrantmsg, NULL }, { "AllowChrootSymlinks", set_allowchrootsymlinks, NULL }, { "AllowEmptyPasswords", set_allowemptypasswords, NULL }, { "AnonAllowRobots", set_anonallowrobots, NULL }, { "AnonRequirePassword", set_anonrequirepassword, NULL }, { "AnonRejectPasswords", set_anonrejectpasswords, NULL }, { "AuthAliasOnly", set_authaliasonly, NULL }, { "AuthUsingAlias", set_authusingalias, NULL }, { "CreateHome", set_createhome, NULL }, { "DefaultChdir", add_defaultchdir, NULL }, { "DefaultRoot", add_defaultroot, NULL }, { "DisplayLogin", set_displaylogin, NULL }, { "GroupPassword", set_grouppassword, NULL }, { "LoginPasswordPrompt", set_loginpasswordprompt, NULL }, { "MaxClients", set_maxclients, NULL }, { "MaxClientsPerClass", set_maxclientsclass, NULL }, { "MaxClientsPerHost", set_maxhostclients, NULL }, { "MaxClientsPerUser", set_maxuserclients, NULL }, { "MaxConnectionsPerHost", set_maxconnectsperhost, NULL }, { "MaxHostsPerUser", set_maxhostsperuser, NULL }, { "MaxLoginAttempts", set_maxloginattempts, NULL }, { "MaxPasswordSize", set_maxpasswordsize, NULL }, { "RequireValidShell", set_requirevalidshell, NULL }, { "RewriteHome", set_rewritehome, NULL }, { "RootLogin", set_rootlogin, NULL }, { "RootRevoke", set_rootrevoke, NULL }, { "TimeoutLogin", set_timeoutlogin, NULL }, { "TimeoutSession", set_timeoutsession, NULL }, { "UseFtpUsers", set_useftpusers, NULL }, { "UseLastlog", set_uselastlog, NULL }, { "UserAlias", set_useralias, NULL }, { "UserDirRoot", set_userdirroot, NULL }, { "UserPassword", set_userpassword, NULL }, { "WtmpLog", set_wtmplog, NULL }, { NULL, NULL, NULL } }; static cmdtable auth_cmdtab[] = { { PRE_CMD, C_USER, G_NONE, auth_pre_user, FALSE, FALSE, CL_AUTH }, { CMD, C_USER, G_NONE, auth_user, FALSE, FALSE, CL_AUTH }, { PRE_CMD, C_PASS, G_NONE, auth_pre_pass, FALSE, FALSE, CL_AUTH }, { CMD, C_PASS, G_NONE, auth_pass, FALSE, FALSE, CL_AUTH }, { POST_CMD, C_PASS, G_NONE, auth_post_pass, FALSE, FALSE, CL_AUTH }, { LOG_CMD, C_PASS, G_NONE, auth_log_pass, FALSE, FALSE }, { LOG_CMD_ERR,C_PASS, G_NONE, auth_err_pass, FALSE, FALSE }, { CMD, C_ACCT, G_NONE, auth_acct, FALSE, FALSE, CL_AUTH }, { CMD, C_REIN, G_NONE, auth_rein, FALSE, FALSE, CL_AUTH }, /* For the automatic robots.txt handling */ { PRE_CMD, C_RETR, G_NONE, auth_pre_retr, FALSE, FALSE }, { POST_CMD, C_RETR, G_NONE, auth_post_retr, FALSE, FALSE }, { POST_CMD_ERR,C_RETR,G_NONE, auth_post_retr, FALSE, FALSE }, { 0, NULL } }; /* Module interface */ module auth_module = { NULL, NULL, /* Module API version */ 0x20, /* Module name */ "auth", /* Module configuration directive table */ auth_conftab, /* Module command handler table */ auth_cmdtab, /* Module authentication handler table */ NULL, /* Module initialization function */ auth_init, /* Session initialization function */ auth_sess_init };
./CrossVul/dataset_final_sorted/CWE-59/c/good_3263_0
crossvul-cpp_data_good_436_10
/* * Soft: Keepalived is a failover program for the LVS project * <www.linuxvirtualserver.org>. It monitor & manipulate * a loadbalanced server pool using multi-layer checks. * * Part: Forked system call to launch an extra script. * * Author: Alexandre Cassen, <acassen@linux-vs.org> * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. * * Copyright (C) 2001-2017 Alexandre Cassen, <acassen@gmail.com> */ #include "config.h" #include <unistd.h> #include <stdlib.h> #include <fcntl.h> #include <errno.h> #include <signal.h> #include <grp.h> #include <string.h> #include <sys/stat.h> #include <pwd.h> #include <sys/resource.h> #include <limits.h> #include <sys/prctl.h> #include "notify.h" #include "signals.h" #include "logger.h" #include "utils.h" #include "process.h" #include "parser.h" #include "keepalived_magic.h" #include "scheduler.h" /* Default user/group for script execution */ uid_t default_script_uid; gid_t default_script_gid; /* Have we got a default user OK? */ static bool default_script_uid_set = false; static bool default_user_fail = false; /* Set if failed to set default user, unless it defaults to root */ /* Script security enabled */ bool script_security = false; /* Buffer length needed for getpwnam_r/getgrname_r */ static size_t getpwnam_buf_len; static char *path; static bool path_is_malloced; /* The priority this process is running at */ static int cur_prio = INT_MAX; /* Buffer for expanding notify script commands */ static char cmd_str_buf[MAXBUF]; static bool set_privileges(uid_t uid, gid_t gid) { int retval; /* Ensure we receive SIGTERM if our parent process dies */ prctl(PR_SET_PDEATHSIG, SIGTERM); /* If we have increased our priority, set it to default for the script */ if (cur_prio != INT_MAX) cur_prio = getpriority(PRIO_PROCESS, 0); if (cur_prio < 0) setpriority(PRIO_PROCESS, 0, 0); /* Drop our privileges if configured */ if (gid) { retval = setgid(gid); if (retval < 0) { log_message(LOG_ALERT, "Couldn't setgid: %d (%m)", gid); return true; } /* Clear any extra supplementary groups */ retval = setgroups(1, &gid); if (retval < 0) { log_message(LOG_ALERT, "Couldn't setgroups: %d (%m)", gid); return true; } } if (uid) { retval = setuid(uid); if (retval < 0) { log_message(LOG_ALERT, "Couldn't setuid: %d (%m)", uid); return true; } } /* Prepare for invoking process/script */ signal_handler_script(); set_std_fd(false); return false; } char * cmd_str_r(const notify_script_t *script, char *buf, size_t len) { char *str_p; int i; size_t str_len; str_p = buf; for (i = 0; i < script->num_args; i++) { /* Check there is enough room for the next word */ str_len = strlen(script->args[i]); if (str_p + str_len + 2 + (i ? 1 : 0) >= buf + len) return NULL; if (i) *str_p++ = ' '; *str_p++ = '\''; strcpy(str_p, script->args[i]); str_p += str_len; *str_p++ = '\''; } *str_p = '\0'; return buf; } char * cmd_str(const notify_script_t *script) { size_t len; int i; for (i = 0, len = 0; i < script->num_args; i++) len += strlen(script->args[i]) + 3; /* Add two ', and trailing space (or null for last arg) */ if (len > sizeof cmd_str_buf) return NULL; return cmd_str_r(script, cmd_str_buf, sizeof cmd_str_buf); } /* Execute external script/program to process FIFO */ static pid_t notify_fifo_exec(thread_master_t *m, int (*func) (thread_t *), void *arg, notify_script_t *script) { pid_t pid; int retval; char *scr; pid = local_fork(); /* In case of fork is error. */ if (pid < 0) { log_message(LOG_INFO, "Failed fork process"); return -1; } /* In case of this is parent process */ if (pid) { thread_add_child(m, func, arg, pid, TIMER_NEVER); return 0; } #ifdef _MEM_CHECK_ skip_mem_dump(); #endif setpgid(0, 0); set_privileges(script->uid, script->gid); if (script->flags | SC_EXECABLE) { /* If keepalived dies, we want the script to die */ prctl(PR_SET_PDEATHSIG, SIGTERM); execve(script->args[0], script->args, environ); if (errno == EACCES) log_message(LOG_INFO, "FIFO notify script %s is not executable", script->args[0]); else log_message(LOG_INFO, "Unable to execute FIFO notify script %s - errno %d - %m", script->args[0], errno); } else { retval = system(scr = cmd_str(script)); if (retval == 127) { /* couldn't exec command */ log_message(LOG_ALERT, "Couldn't exec FIFO command: %s", scr); } else if (retval == -1) log_message(LOG_ALERT, "Error exec-ing FIFO command: %s", scr); exit(0); } /* unreached unless error */ exit(0); } static void fifo_open(notify_fifo_t* fifo, int (*script_exit)(thread_t *), const char *type) { int ret; int sav_errno; if (fifo->name) { sav_errno = 0; if (!(ret = mkfifo(fifo->name, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH))) fifo->created_fifo = true; else { sav_errno = errno; if (sav_errno != EEXIST) log_message(LOG_INFO, "Unable to create %snotify fifo %s", type, fifo->name); } if (!sav_errno || sav_errno == EEXIST) { /* Run the notify script if there is one */ if (fifo->script) notify_fifo_exec(master, script_exit, fifo, fifo->script); /* Now open the fifo */ if ((fifo->fd = open(fifo->name, O_RDWR | O_CLOEXEC | O_NONBLOCK | O_NOFOLLOW)) == -1) { log_message(LOG_INFO, "Unable to open %snotify fifo %s - errno %d", type, fifo->name, errno); if (fifo->created_fifo) { unlink(fifo->name); fifo->created_fifo = false; } } } if (fifo->fd == -1) { FREE(fifo->name); fifo->name = NULL; } } } void notify_fifo_open(notify_fifo_t* global_fifo, notify_fifo_t* fifo, int (*script_exit)(thread_t *), const char *type) { /* Open the global FIFO if specified */ if (global_fifo->name) fifo_open(global_fifo, script_exit, ""); /* Now the specific FIFO */ if (fifo->name) fifo_open(fifo, script_exit, type); } static void fifo_close(notify_fifo_t* fifo) { if (fifo->fd != -1) { close(fifo->fd); fifo->fd = -1; } if (fifo->created_fifo) unlink(fifo->name); } void notify_fifo_close(notify_fifo_t* global_fifo, notify_fifo_t* fifo) { if (global_fifo->fd != -1) fifo_close(global_fifo); fifo_close(fifo); } /* perform a system call */ static void system_call(const notify_script_t *) __attribute__ ((noreturn)); static void system_call(const notify_script_t* script) { char *command_line = NULL; char *str; int retval; if (set_privileges(script->uid, script->gid)) exit(0); /* Move us into our own process group, so if the script needs to be killed * all its child processes will also be killed. */ setpgid(0, 0); if (script->flags & SC_EXECABLE) { /* If keepalived dies, we want the script to die */ prctl(PR_SET_PDEATHSIG, SIGTERM); execve(script->args[0], script->args, environ); /* error */ log_message(LOG_ALERT, "Error exec-ing command '%s', error %d: %m", script->args[0], errno); } else { retval = system(str = cmd_str(script)); if (retval == -1) log_message(LOG_ALERT, "Error exec-ing command: %s", str); else if (WIFEXITED(retval)) { if (WEXITSTATUS(retval) == 127) { /* couldn't find command */ log_message(LOG_ALERT, "Couldn't find command: %s", str); } else if (WEXITSTATUS(retval) == 126) { /* couldn't find command */ log_message(LOG_ALERT, "Couldn't execute command: %s", str); } } if (command_line) FREE(command_line); if (retval == -1 || (WIFEXITED(retval) && (WEXITSTATUS(retval) == 126 || WEXITSTATUS(retval) == 127))) exit(0); if (WIFEXITED(retval)) exit(WEXITSTATUS(retval)); if (WIFSIGNALED(retval)) kill(getpid(), WTERMSIG(retval)); exit(0); } exit(0); } /* Execute external script/program */ int notify_exec(const notify_script_t *script) { pid_t pid; if (log_file_name) flush_log_file(); pid = local_fork(); if (pid < 0) { /* fork error */ log_message(LOG_INFO, "Failed fork process"); return -1; } if (pid) { /* parent process */ return 0; } #ifdef _MEM_CHECK_ skip_mem_dump(); #endif system_call(script); /* We should never get here */ exit(0); } int system_call_script(thread_master_t *m, int (*func) (thread_t *), void * arg, unsigned long timer, notify_script_t* script) { pid_t pid; /* Daemonization to not degrade our scheduling timer */ if (log_file_name) flush_log_file(); pid = local_fork(); if (pid < 0) { /* fork error */ log_message(LOG_INFO, "Failed fork process"); return -1; } if (pid) { /* parent process */ thread_add_child(m, func, arg, pid, timer); return 0; } /* Child process */ #ifdef _MEM_CHECK_ skip_mem_dump(); #endif system_call(script); exit(0); /* Script errors aren't server errors */ } int child_killed_thread(thread_t *thread) { thread_master_t *m = thread->master; /* If the child didn't die, then force it */ if (thread->type == THREAD_CHILD_TIMEOUT) kill(-getpgid(thread->u.c.pid), SIGKILL); /* If all children have died, we can now complete the * termination process */ if (!&m->child.rb_root.rb_node && !m->shutdown_timer_running) thread_add_terminate_event(m); return 0; } void script_killall(thread_master_t *m, int signo, bool requeue) { thread_t *thread; pid_t p_pgid, c_pgid; #ifndef HAVE_SIGNALFD sigset_t old_set, child_wait; sigmask_func(0, NULL, &old_set); if (!sigismember(&old_set, SIGCHLD)) { sigemptyset(&child_wait); sigaddset(&child_wait, SIGCHLD); sigmask_func(SIG_BLOCK, &child_wait, NULL); } #endif p_pgid = getpgid(0); rb_for_each_entry_cached(thread, &m->child, n) { c_pgid = getpgid(thread->u.c.pid); if (c_pgid != p_pgid) kill(-c_pgid, signo); else { log_message(LOG_INFO, "Child process %d in our process group %d", c_pgid, p_pgid); kill(thread->u.c.pid, signo); } } /* We want to timeout the killed children in 1 second */ if (requeue && signo != SIGKILL) thread_children_reschedule(m, child_killed_thread, TIMER_HZ); #ifndef HAVE_SIGNALFD if (!sigismember(&old_set, SIGCHLD)) sigmask_func(SIG_UNBLOCK, &child_wait, NULL); #endif } static bool is_executable(struct stat *buf, uid_t uid, gid_t gid) { return (uid == 0 && buf->st_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) || (uid == buf->st_uid && buf->st_mode & S_IXUSR) || (uid != buf->st_uid && ((gid == buf->st_gid && buf->st_mode & S_IXGRP) || (gid != buf->st_gid && buf->st_mode & S_IXOTH))); } static void replace_cmd_name(notify_script_t *script, char *new_path) { size_t len; char **wp = &script->args[1]; size_t num_words = 1; char **params; char **word_ptrs; char *words; len = strlen(new_path) + 1; while (*wp) len += strlen(*wp++) + 1; num_words = ((char **)script->args[0] - &script->args[0]) - 1; params = word_ptrs = MALLOC((num_words + 1) * sizeof(char *) + len); words = (char *)&params[num_words + 1]; strcpy(words, new_path); *(word_ptrs++) = words; words += strlen(words) + 1; wp = &script->args[1]; while (*wp) { strcpy(words, *wp); *(word_ptrs++) = words; words += strlen(*wp) + 1; wp++; } *word_ptrs = NULL; FREE(script->args); script->args = params; } /* The following function is essentially __execve() from glibc */ static int find_path(notify_script_t *script) { size_t filename_len; size_t file_len; size_t path_len; char *file = script->args[0]; struct stat buf; int ret; int ret_val = ENOENT; int sgid_num; gid_t *sgid_list = NULL; const char *subp; bool got_eacces = false; const char *p; /* We check the simple case first. */ if (*file == '\0') return ENOENT; filename_len = strlen(file); if (filename_len >= PATH_MAX) { ret_val = ENAMETOOLONG; goto exit1; } /* Don't search when it contains a slash. */ if (strchr (file, '/') != NULL) { ret_val = 0; goto exit1; } /* Get the path if we haven't already done so, and if that doesn't * exist, use CS_PATH */ if (!path) { path = getenv ("PATH"); if (!path) { size_t cs_path_len; path = MALLOC(cs_path_len = confstr(_CS_PATH, NULL, 0)); confstr(_CS_PATH, path, cs_path_len); path_is_malloced = true; } } /* Although GLIBC does not enforce NAME_MAX, we set it as the maximum size to avoid unbounded stack allocation. Same applies for PATH_MAX. */ file_len = strnlen (file, NAME_MAX + 1); path_len = strnlen (path, PATH_MAX - 1) + 1; if (file_len > NAME_MAX) { ret_val = ENAMETOOLONG; goto exit1; } /* Set file access to the relevant uid/gid */ if (script->gid) { if (setegid(script->gid)) { log_message(LOG_INFO, "Unable to set egid to %d (%m)", script->gid); ret_val = EACCES; goto exit1; } /* Get our supplementary groups */ sgid_num = getgroups(0, NULL); sgid_list = MALLOC(((size_t)sgid_num + 1) * sizeof(gid_t)); sgid_num = getgroups(sgid_num, sgid_list); sgid_list[sgid_num++] = 0; /* Clear the supplementary group list */ if (setgroups(1, &script->gid)) { log_message(LOG_INFO, "Unable to set supplementary gids (%m)"); ret_val = EACCES; goto exit; } } if (script->uid && seteuid(script->uid)) { log_message(LOG_INFO, "Unable to set euid to %d (%m)", script->uid); ret_val = EACCES; goto exit; } for (p = path; ; p = subp) { char buffer[path_len + file_len + 1]; subp = strchrnul (p, ':'); /* PATH is larger than PATH_MAX and thus potentially larger than the stack allocation. */ if (subp >= p + path_len) { /* There are no more paths, bail out. */ if (*subp == '\0') { ret_val = ENOENT; goto exit; } /* Otherwise skip to next one. */ continue; } /* Use the current path entry, plus a '/' if nonempty, plus the file to execute. */ char *pend = mempcpy (buffer, p, (size_t)(subp - p)); *pend = '/'; memcpy (pend + (p < subp), file, file_len + 1); ret = stat (buffer, &buf); if (!ret) { if (!S_ISREG(buf.st_mode)) errno = EACCES; else if (!is_executable(&buf, script->uid, script->gid)) { errno = EACCES; } else { /* Success */ log_message(LOG_INFO, "WARNING - script `%s` resolved by path search to `%s`. Please specify full path.", script->args[0], buffer); /* Copy the found file name, and any parameters */ replace_cmd_name(script, buffer); ret_val = 0; got_eacces = false; goto exit; } } switch (errno) { case ENOEXEC: case EACCES: /* Record that we got a 'Permission denied' error. If we end up finding no executable we can use, we want to diagnose that we did find one but were denied access. */ if (!ret) got_eacces = true; case ENOENT: case ESTALE: case ENOTDIR: /* Those errors indicate the file is missing or not executable by us, in which case we want to just try the next path directory. */ case ENODEV: case ETIMEDOUT: /* Some strange filesystems like AFS return even stranger error numbers. They cannot reasonably mean anything else so ignore those, too. */ break; default: /* Some other error means we found an executable file, but something went wrong accessing it; return the error to our caller. */ ret_val = -1; goto exit; } if (*subp++ == '\0') break; } exit: /* Restore root euid/egid */ if (script->uid && seteuid(0)) log_message(LOG_INFO, "Unable to restore euid after script search (%m)"); if (script->gid) { if (setegid(0)) log_message(LOG_INFO, "Unable to restore egid after script search (%m)"); /* restore supplementary groups */ if (sgid_list) { if (setgroups((size_t)sgid_num, sgid_list)) log_message(LOG_INFO, "Unable to restore supplementary groups after script search (%m)"); FREE(sgid_list); } } exit1: /* We tried every element and none of them worked. */ if (got_eacces) { /* At least one failure was due to permissions, so report that error. */ return EACCES; } return ret_val; } static int check_security(char *filename, bool script_security) { char *next; char *slash; char sav; int ret; struct stat buf; int flags = 0; next = filename; while (next) { slash = strchrnul(next, '/'); if (*slash) next = slash + 1; else { slash = NULL; next = NULL; } if (slash) { /* We want to check '/' for first time around */ if (slash == filename) slash++; sav = *slash; *slash = 0; } ret = fstatat(0, filename, &buf, AT_SYMLINK_NOFOLLOW); /* Restore the full path name */ if (slash) *slash = sav; if (ret) { if (errno == EACCES || errno == ELOOP || errno == ENOENT || errno == ENOTDIR) log_message(LOG_INFO, "check_script_secure could not find script '%s' - disabling", filename); else log_message(LOG_INFO, "check_script_secure('%s') returned errno %d - %s - disabling", filename, errno, strerror(errno)); return flags | SC_NOTFOUND; } /* If it is not the last item, it must be a directory. If it is the last item * it must be a file or a symbolic link. */ if ((slash && !S_ISDIR(buf.st_mode)) || (!slash && !S_ISREG(buf.st_mode) && !S_ISLNK(buf.st_mode))) { log_message(LOG_INFO, "Wrong file type found in script path '%s'.", filename); return flags | SC_INHIBIT; } if (buf.st_uid || /* Owner is not root */ (((S_ISDIR(buf.st_mode) && /* A directory without the sticky bit set */ !(buf.st_mode & S_ISVTX)) || S_ISREG(buf.st_mode)) && /* This is a file */ ((buf.st_gid && buf.st_mode & S_IWGRP) || /* Group is not root and group write permission */ buf.st_mode & S_IWOTH))) { /* World has write permission */ log_message(LOG_INFO, "Unsafe permissions found for script '%s'%s.", filename, script_security ? " - disabling" : ""); flags |= SC_INSECURE; return flags | (script_security ? SC_INHIBIT : 0); } } return flags; } int check_script_secure(notify_script_t *script, #ifndef _HAVE_LIBMAGIC_ __attribute__((unused)) #endif magic_t magic) { int flags; int ret, ret_real, ret_new; struct stat file_buf, real_buf; bool need_script_protection = false; uid_t old_uid = 0; gid_t old_gid = 0; char *new_path; int sav_errno; char *real_file_path; char *orig_file_part, *new_file_part; if (!script) return 0; /* If the script starts "</" (possibly with white space between * the '<' and '/'), it is checking for a file being openable, * so it won't be executed */ if (script->args[0][0] == '<' && script->args[0][strspn(script->args[0] + 1, " \t") + 1] == '/') return SC_SYSTEM; if (!strchr(script->args[0], '/')) { /* It is a bare file name, so do a path search */ if ((ret = find_path(script))) { if (ret == EACCES) log_message(LOG_INFO, "Permissions failure for script %s in path - disabling", script->args[0]); else log_message(LOG_INFO, "Cannot find script %s in path - disabling", script->args[0]); return SC_NOTFOUND; } } /* Check script accessible by the user running it */ if (script->uid) old_uid = geteuid(); if (script->gid) old_gid = getegid(); if ((script->gid && setegid(script->gid)) || (script->uid && seteuid(script->uid))) { log_message(LOG_INFO, "Unable to set uid:gid %d:%d for script %s - disabling", script->uid, script->gid, script->args[0]); if ((script->uid && seteuid(old_uid)) || (script->gid && setegid(old_gid))) log_message(LOG_INFO, "Unable to restore uid:gid %d:%d after script %s", script->uid, script->gid, script->args[0]); return SC_INHIBIT; } /* Remove /./, /../, multiple /'s, and resolve symbolic links */ new_path = realpath(script->args[0], NULL); sav_errno = errno; if ((script->gid && setegid(old_gid)) || (script->uid && seteuid(old_uid))) log_message(LOG_INFO, "Unable to restore uid:gid %d:%d after checking script %s", script->uid, script->gid, script->args[0]); if (!new_path) { log_message(LOG_INFO, "Script %s cannot be accessed - %s", script->args[0], strerror(sav_errno)); return SC_NOTFOUND; } real_file_path = NULL; orig_file_part = strrchr(script->args[0], '/'); new_file_part = strrchr(new_path, '/'); if (strcmp(script->args[0], new_path)) { /* The path name is different */ /* If the file name parts don't match, we need to be careful to * ensure that we preserve the file name part since some executables * alter their behaviour based on what they are called */ if (strcmp(orig_file_part + 1, new_file_part + 1)) { real_file_path = new_path; new_path = MALLOC(new_file_part - real_file_path + 1 + strlen(orig_file_part + 1) + 1); strncpy(new_path, real_file_path, new_file_part + 1 - real_file_path); strcpy(new_path + (new_file_part + 1 - real_file_path), orig_file_part + 1); /* Now check this is the same file */ ret_real = stat(real_file_path, &real_buf); ret_new = stat(new_path, &file_buf); if (!ret_real && (ret_new || real_buf.st_dev != file_buf.st_dev || real_buf.st_ino != file_buf.st_ino)) { /* It doesn't resolve to the same file */ FREE(new_path); new_path = real_file_path; real_file_path = NULL; } } if (strcmp(script->args[0], new_path)) { /* We need to set up all the args again */ replace_cmd_name(script, new_path); } } if (!real_file_path) free(new_path); else FREE(new_path); /* Get the permissions for the file itself */ if (stat(real_file_path ? real_file_path : script->args[0], &file_buf)) { log_message(LOG_INFO, "Unable to access script `%s` - disabling", script->args[0]); return SC_NOTFOUND; } flags = SC_ISSCRIPT; /* We have the final file. Check if root is executing it, or it is set uid/gid root. */ if (is_executable(&file_buf, script->uid, script->gid)) { flags |= SC_EXECUTABLE; if (script->uid == 0 || script->gid == 0 || (file_buf.st_uid == 0 && (file_buf.st_mode & S_IXUSR) && (file_buf.st_mode & S_ISUID)) || (file_buf.st_gid == 0 && (file_buf.st_mode & S_IXGRP) && (file_buf.st_mode & S_ISGID))) need_script_protection = true; } else log_message(LOG_INFO, "WARNING - script '%s' is not executable for uid:gid %d:%d - disabling.", script->args[0], script->uid, script->gid); /* Default to execable */ script->flags |= SC_EXECABLE; #ifdef _HAVE_LIBMAGIC_ if (magic && flags & SC_EXECUTABLE) { const char *magic_desc = magic_file(magic, real_file_path ? real_file_path : script->args[0]); if (!strstr(magic_desc, " executable") && !strstr(magic_desc, " shared object")) { log_message(LOG_INFO, "Please add a #! shebang to script %s", script->args[0]); script->flags &= ~SC_EXECABLE; } } #endif if (!need_script_protection) { if (real_file_path) free(real_file_path); return flags; } /* Make sure that all parts of the path are not non-root writable */ flags |= check_security(script->args[0], script_security); if (real_file_path) { flags |= check_security(real_file_path, script_security); free(real_file_path); } return flags; } int check_notify_script_secure(notify_script_t **script_p, magic_t magic) { int flags; notify_script_t *script = *script_p; if (!script) return 0; flags = check_script_secure(script, magic); /* Mark not to run if needs inhibiting */ if ((flags & (SC_INHIBIT | SC_NOTFOUND)) || !(flags & SC_EXECUTABLE)) free_notify_script(script_p); return flags; } static void set_pwnam_buf_len(void) { long buf_len; /* Get buffer length needed for getpwnam_r/getgrnam_r */ if ((buf_len = sysconf(_SC_GETPW_R_SIZE_MAX)) == -1) getpwnam_buf_len = 1024; /* A safe default if no value is returned */ else getpwnam_buf_len = (size_t)buf_len; if ((buf_len = sysconf(_SC_GETGR_R_SIZE_MAX)) != -1 && (size_t)buf_len > getpwnam_buf_len) getpwnam_buf_len = (size_t)buf_len; } bool set_uid_gid(const char *username, const char *groupname, uid_t *uid_p, gid_t *gid_p, bool default_user) { uid_t uid; gid_t gid; struct passwd pwd; struct passwd *pwd_p; struct group grp; struct group *grp_p; int ret; bool using_default_default_user = false; if (!getpwnam_buf_len) set_pwnam_buf_len(); { char buf[getpwnam_buf_len]; if (default_user && !username) { using_default_default_user = true; username = "keepalived_script"; } if ((ret = getpwnam_r(username, &pwd, buf, sizeof(buf), &pwd_p))) { log_message(LOG_INFO, "Unable to resolve %sscript username '%s' - ignoring", default_user ? "default " : "", username); return true; } if (!pwd_p) { if (using_default_default_user) log_message(LOG_INFO, "WARNING - default user '%s' for script execution does not exist - please create.", username); else log_message(LOG_INFO, "%script user '%s' does not exist", default_user ? "Default s" : "S", username); return true; } uid = pwd.pw_uid; gid = pwd.pw_gid; if (groupname) { if ((ret = getgrnam_r(groupname, &grp, buf, sizeof(buf), &grp_p))) { log_message(LOG_INFO, "Unable to resolve %sscript group name '%s' - ignoring", default_user ? "default " : "", groupname); return true; } if (!grp_p) { log_message(LOG_INFO, "%script group '%s' does not exist", default_user ? "Default s" : "S", groupname); return true; } gid = grp.gr_gid; } *uid_p = uid; *gid_p = gid; } return false; } /* The default script user/group is keepalived_script if it exists, or root otherwise */ bool set_default_script_user(const char *username, const char *groupname) { if (!default_script_uid_set || username) { /* Even if we fail to set it, there is no point in trying again */ default_script_uid_set = true; if (set_uid_gid(username, groupname, &default_script_uid, &default_script_gid, true)) { if (username || script_security) default_user_fail = true; } else default_user_fail = false; } return default_user_fail; } bool set_script_uid_gid(vector_t *strvec, unsigned keyword_offset, uid_t *uid_p, gid_t *gid_p) { char *username; char *groupname; username = strvec_slot(strvec, keyword_offset); if (vector_size(strvec) > keyword_offset + 1) groupname = strvec_slot(strvec, keyword_offset + 1); else groupname = NULL; return set_uid_gid(username, groupname, uid_p, gid_p, false); } void set_script_params_array(vector_t *strvec, notify_script_t *script, unsigned extra_params) { unsigned num_words = 0; size_t len = 0; char **word_ptrs; char *words; vector_t *strvec_qe = NULL; unsigned i; /* Count the number of words, and total string length */ if (vector_size(strvec) >= 2) strvec_qe = alloc_strvec_quoted_escaped(strvec_slot(strvec, 1)); if (!strvec_qe) return; num_words = vector_size(strvec_qe); for (i = 0; i < num_words; i++) len += strlen(strvec_slot(strvec_qe, i)) + 1; /* Allocate memory for pointers to words and words themselves */ script->args = word_ptrs = MALLOC((num_words + extra_params + 1) * sizeof(char *) + len); words = (char *)word_ptrs + (num_words + extra_params + 1) * sizeof(char *); /* Set up pointers to words, and copy the words */ for (i = 0; i < num_words; i++) { strcpy(words, strvec_slot(strvec_qe, i)); *(word_ptrs++) = words; words += strlen(words) + 1; } *word_ptrs = NULL; script->num_args = num_words; free_strvec(strvec_qe); } notify_script_t* notify_script_init(int extra_params, const char *type) { notify_script_t *script = MALLOC(sizeof(notify_script_t)); vector_t *strvec_qe; /* We need to reparse the command line, allowing for quoted and escaped strings */ strvec_qe = alloc_strvec_quoted_escaped(NULL); if (!strvec_qe) { log_message(LOG_INFO, "Unable to parse notify script"); FREE(script); return NULL; } set_script_params_array(strvec_qe, script, extra_params); if (!script->args) { log_message(LOG_INFO, "Unable to parse script '%s' - ignoring", FMT_STR_VSLOT(strvec_qe, 1)); FREE(script); free_strvec(strvec_qe); return NULL; } script->flags = 0; if (vector_size(strvec_qe) > 2) { if (set_script_uid_gid(strvec_qe, 2, &script->uid, &script->gid)) { log_message(LOG_INFO, "Invalid user/group for %s script %s - ignoring", type, script->args[0]); FREE(script->args); FREE(script); free_strvec(strvec_qe); return NULL; } } else { if (set_default_script_user(NULL, NULL)) { log_message(LOG_INFO, "Failed to set default user for %s script %s - ignoring", type, script->args[0]); FREE(script->args); FREE(script); free_strvec(strvec_qe); return NULL; } script->uid = default_script_uid; script->gid = default_script_gid; } free_strvec(strvec_qe); return script; } void add_script_param(notify_script_t *script, char *param) { /* We store the args as an array of pointers to the args, terminated * by a NULL pointer, followed by the null terminated strings themselves */ if (script->args[script->num_args + 1]) { log_message(LOG_INFO, "notify_fifo_script %s no room to add parameter %s", script->args[0], param); return; } /* Add the extra parameter in the pre-reserved slot at the end */ script->args[script->num_args++] = param; } void notify_resource_release(void) { if (path_is_malloced) { FREE(path); path_is_malloced = false; path = NULL; } } bool notify_script_compare(notify_script_t *a, notify_script_t *b) { int i; if (a->num_args != b->num_args) return false; for (i = 0; i < a->num_args; i++) { if (strcmp(a->args[i], b->args[i])) return false; } return true; } #ifdef THREAD_DUMP void register_notify_addresses(void) { register_thread_address("child_killed_thread", child_killed_thread); } #endif
./CrossVul/dataset_final_sorted/CWE-59/c/good_436_10
crossvul-cpp_data_bad_436_8
/* * Soft: Keepalived is a failover program for the LVS project * <www.linuxvirtualserver.org>. It monitor & manipulate * a loadbalanced server pool using multi-layer checks. * * Part: logging facility. * * Author: Alexandre Cassen, <acassen@linux-vs.org> * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. * * Copyright (C) 2001-2017 Alexandre Cassen, <acassen@gmail.com> */ #include "config.h" #include <stdio.h> #include <stdbool.h> #include <time.h> #include <unistd.h> #include <fcntl.h> #include <string.h> #include <memory.h> #include "logger.h" #include "bitops.h" #include "utils.h" /* Boolean flag - send messages to console as well as syslog */ static bool log_console = false; /* File to write log messages to */ char *log_file_name; static FILE *log_file; bool always_flush_log_file; void enable_console_log(void) { log_console = true; } void set_flush_log_file(void) { always_flush_log_file = true; } void close_log_file(void) { if (log_file) { fclose(log_file); log_file = NULL; } } void open_log_file(const char *name, const char *prog, const char *namespace, const char *instance) { char *file_name; if (log_file) { fclose(log_file); log_file = NULL; } if (!name) return; file_name = make_file_name(name, prog, namespace, instance); log_file = fopen(file_name, "a"); if (log_file) { int n = fileno(log_file); fcntl(n, F_SETFD, FD_CLOEXEC | fcntl(n, F_GETFD)); fcntl(n, F_SETFL, O_NONBLOCK | fcntl(n, F_GETFL)); } FREE(file_name); } void flush_log_file(void) { if (log_file) fflush(log_file); } void vlog_message(const int facility, const char* format, va_list args) { #if !HAVE_VSYSLOG char buf[MAX_LOG_MSG+1]; vsnprintf(buf, sizeof(buf), format, args); #endif /* Don't write syslog if testing configuration */ if (__test_bit(CONFIG_TEST_BIT, &debug)) return; if (log_file || (__test_bit(DONT_FORK_BIT, &debug) && log_console)) { #if HAVE_VSYSLOG va_list args1; char buf[2 * MAX_LOG_MSG + 1]; va_copy(args1, args); vsnprintf(buf, sizeof(buf), format, args1); va_end(args1); #endif /* timestamp setup */ time_t t = time(NULL); struct tm tm; localtime_r(&t, &tm); char timestamp[64]; strftime(timestamp, sizeof(timestamp), "%c", &tm); if (log_console && __test_bit(DONT_FORK_BIT, &debug)) fprintf(stderr, "%s: %s\n", timestamp, buf); if (log_file) { fprintf(log_file, "%s: %s\n", timestamp, buf); if (always_flush_log_file) fflush(log_file); } } if (!__test_bit(NO_SYSLOG_BIT, &debug)) #if HAVE_VSYSLOG vsyslog(facility, format, args); #else syslog(facility, "%s", buf); #endif } void log_message(const int facility, const char *format, ...) { va_list args; va_start(args, format); vlog_message(facility, format, args); va_end(args); } void conf_write(FILE *fp, const char *format, ...) { va_list args; va_start(args, format); if (fp) { vfprintf(fp, format, args); fprintf(fp, "\n"); } else vlog_message(LOG_INFO, format, args); va_end(args); }
./CrossVul/dataset_final_sorted/CWE-59/c/bad_436_8
crossvul-cpp_data_bad_3576_3
/* * transform.c: support for building and running transformers * * Copyright (C) 2007-2011 David Lutterkort * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: David Lutterkort <dlutter@redhat.com> */ #include <config.h> #include <fnmatch.h> #include <glob.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <selinux/selinux.h> #include <stdbool.h> #include "internal.h" #include "memory.h" #include "augeas.h" #include "syntax.h" #include "transform.h" #include "errcode.h" static const int fnm_flags = FNM_PATHNAME; static const int glob_flags = GLOB_NOSORT; /* Extension for newly created files */ #define EXT_AUGNEW ".augnew" /* Extension for backup files */ #define EXT_AUGSAVE ".augsave" /* Loaded files are tracked underneath METATREE. When a file with name * FNAME is loaded, certain entries are made under METATREE / FNAME: * path : path where tree for FNAME is put * mtime : time of last modification of the file as reported by stat(2) * lens/info : information about where the applied lens was loaded from * lens/id : unique hexadecimal id of the lens * error : indication of errors during processing FNAME, or NULL * if processing succeeded * error/pos : position in file where error occured (for get errors) * error/path: path to tree node where error occurred (for put errors) * error/message : human-readable error message */ static const char *const s_path = "path"; static const char *const s_lens = "lens"; static const char *const s_info = "info"; static const char *const s_mtime = "mtime"; static const char *const s_error = "error"; /* These are all put underneath "error" */ static const char *const s_pos = "pos"; static const char *const s_message = "message"; static const char *const s_line = "line"; static const char *const s_char = "char"; /* * Filters */ struct filter *make_filter(struct string *glb, unsigned int include) { struct filter *f; make_ref(f); f->glob = glb; f->include = include; return f; } void free_filter(struct filter *f) { if (f == NULL) return; assert(f->ref == 0); unref(f->next, filter); unref(f->glob, string); free(f); } static const char *pathbase(const char *path) { const char *p = strrchr(path, SEP); return (p == NULL) ? path : p + 1; } static bool is_excl(struct tree *f) { return streqv(f->label, "excl") && f->value != NULL; } static bool is_incl(struct tree *f) { return streqv(f->label, "incl") && f->value != NULL; } static bool is_regular_file(const char *path) { int r; struct stat st; r = stat(path, &st); if (r < 0) return false; return S_ISREG(st.st_mode); } static char *mtime_as_string(struct augeas *aug, const char *fname) { int r; struct stat st; char *result = NULL; if (fname == NULL) { result = strdup("0"); ERR_NOMEM(result == NULL, aug); goto done; } r = stat(fname, &st); if (r < 0) { /* If we fail to stat, silently ignore the error * and report an impossible mtime */ result = strdup("0"); ERR_NOMEM(result == NULL, aug); } else { r = xasprintf(&result, "%ld", (long) st.st_mtime); ERR_NOMEM(r < 0, aug); } done: return result; error: FREE(result); return NULL; } static bool file_current(struct augeas *aug, const char *fname, struct tree *finfo) { struct tree *mtime = tree_child(finfo, s_mtime); struct tree *file = NULL, *path = NULL; int r; struct stat st; int64_t mtime_i; if (mtime == NULL || mtime->value == NULL) return false; r = xstrtoint64(mtime->value, 10, &mtime_i); if (r < 0) { /* Ignore silently and err on the side of caution */ return false; } r = stat(fname, &st); if (r < 0) return false; if (mtime_i != (int64_t) st.st_mtime) return false; path = tree_child(finfo, s_path); if (path == NULL) return false; file = tree_find(aug, path->value); return (file != NULL && ! file->dirty); } static int filter_generate(struct tree *xfm, const char *root, int *nmatches, char ***matches) { glob_t globbuf; int gl_flags = glob_flags; int r; int ret = 0; char **pathv = NULL; int pathc = 0; int root_prefix = strlen(root) - 1; *nmatches = 0; *matches = NULL; MEMZERO(&globbuf, 1); list_for_each(f, xfm->children) { char *globpat = NULL; if (! is_incl(f)) continue; pathjoin(&globpat, 2, root, f->value); r = glob(globpat, gl_flags, NULL, &globbuf); free(globpat); if (r != 0 && r != GLOB_NOMATCH) { ret = -1; goto error; } gl_flags |= GLOB_APPEND; } pathc = globbuf.gl_pathc; int pathind = 0; if (ALLOC_N(pathv, pathc) < 0) goto error; for (int i=0; i < pathc; i++) { const char *path = globbuf.gl_pathv[i] + root_prefix; bool include = true; list_for_each(e, xfm->children) { if (! is_excl(e)) continue; if (strchr(e->value, SEP) == NULL) path = pathbase(path); if ((r = fnmatch(e->value, path, fnm_flags)) == 0) { include = false; } } if (include) include = is_regular_file(globbuf.gl_pathv[i]); if (include) { pathv[pathind] = strdup(globbuf.gl_pathv[i]); if (pathv[pathind] == NULL) goto error; pathind += 1; } } pathc = pathind; if (REALLOC_N(pathv, pathc) == -1) goto error; *matches = pathv; *nmatches = pathc; done: globfree(&globbuf); return ret; error: if (pathv != NULL) for (int i=0; i < pathc; i++) free(pathv[i]); free(pathv); ret = -1; goto done; } static int filter_matches(struct tree *xfm, const char *path) { int found = 0; list_for_each(f, xfm->children) { if (is_incl(f) && fnmatch(f->value, path, fnm_flags) == 0) { found = 1; break; } } if (! found) return 0; list_for_each(f, xfm->children) { if (is_excl(f) && (fnmatch(f->value, path, fnm_flags) == 0)) return 0; } return 1; } /* * Transformers */ struct transform *make_transform(struct lens *lens, struct filter *filter) { struct transform *xform; make_ref(xform); xform->lens = lens; xform->filter = filter; return xform; } void free_transform(struct transform *xform) { if (xform == NULL) return; assert(xform->ref == 0); unref(xform->lens, lens); unref(xform->filter, filter); free(xform); } static char *err_path(const char *filename) { char *result = NULL; if (filename == NULL) pathjoin(&result, 2, AUGEAS_META_FILES, s_error); else pathjoin(&result, 3, AUGEAS_META_FILES, filename, s_error); return result; } ATTRIBUTE_FORMAT(printf, 4, 5) static void err_set(struct augeas *aug, struct tree *err_info, const char *sub, const char *format, ...) { int r; va_list ap; char *value = NULL; struct tree *tree = NULL; va_start(ap, format); r = vasprintf(&value, format, ap); va_end(ap); if (r < 0) value = NULL; ERR_NOMEM(r < 0, aug); tree = tree_child_cr(err_info, sub); ERR_NOMEM(tree == NULL, aug); r = tree_set_value(tree, value); ERR_NOMEM(r < 0, aug); error: free(value); } /* Record an error in the tree. The error will show up underneath * /augeas/FILENAME/error if filename is not NULL, and underneath * /augeas/text/PATH otherwise. PATH is the path to the toplevel node in * the tree where the lens application happened. When STATUS is NULL, just * clear any error associated with FILENAME in the tree. */ static int store_error(struct augeas *aug, const char *filename, const char *path, const char *status, int errnum, const struct lns_error *err, const char *text) { struct tree *err_info = NULL, *finfo = NULL; char *fip = NULL; int r; int result = -1; if (filename != NULL) { r = pathjoin(&fip, 2, AUGEAS_META_FILES, filename); } else { r = pathjoin(&fip, 2, AUGEAS_META_TEXT, path); } ERR_NOMEM(r < 0, aug); finfo = tree_find_cr(aug, fip); ERR_BAIL(aug); if (status != NULL) { err_info = tree_child_cr(finfo, s_error); ERR_NOMEM(err_info == NULL, aug); r = tree_set_value(err_info, status); ERR_NOMEM(r < 0, aug); /* Errors from err_set are ignored on purpose. We try * to report as much as we can */ if (err != NULL) { if (err->pos >= 0) { size_t line, ofs; err_set(aug, err_info, s_pos, "%d", err->pos); if (text != NULL) { calc_line_ofs(text, err->pos, &line, &ofs); err_set(aug, err_info, s_line, "%zd", line); err_set(aug, err_info, s_char, "%zd", ofs); } } if (err->path != NULL) { err_set(aug, err_info, s_path, "%s%s", path, err->path); } if (err->lens != NULL) { char *fi = format_info(err->lens->info); if (fi != NULL) { err_set(aug, err_info, s_lens, "%s", fi); free(fi); } } err_set(aug, err_info, s_message, "%s", err->message); } else if (errnum != 0) { const char *msg = strerror(errnum); err_set(aug, err_info, s_message, "%s", msg); } } else { /* No error, nuke the error node if it exists */ err_info = tree_child(finfo, s_error); if (err_info != NULL) { tree_unlink_children(aug, err_info); pathx_symtab_remove_descendants(aug->symtab, err_info); tree_unlink(err_info); } } tree_clean(finfo); result = 0; error: free(fip); return result; } /* Set up the file information in the /augeas tree. * * NODE must be the path to the file contents, and start with /files. * LENS is the lens used to transform the file. * Create entries under /augeas/NODE with some metadata about the file. * * Returns 0 on success, -1 on error */ static int add_file_info(struct augeas *aug, const char *node, struct lens *lens, const char *lens_name, const char *filename, bool force_reload) { struct tree *file, *tree; char *tmp = NULL; int r; char *path = NULL; int result = -1; if (lens == NULL) return -1; r = pathjoin(&path, 2, AUGEAS_META_TREE, node); ERR_NOMEM(r < 0, aug); file = tree_find_cr(aug, path); ERR_BAIL(aug); /* Set 'path' */ tree = tree_child_cr(file, s_path); ERR_NOMEM(tree == NULL, aug); r = tree_set_value(tree, node); ERR_NOMEM(r < 0, aug); /* Set 'mtime' */ if (force_reload) { tmp = strdup("0"); ERR_NOMEM(tmp == NULL, aug); } else { tmp = mtime_as_string(aug, filename); ERR_BAIL(aug); } tree = tree_child_cr(file, s_mtime); ERR_NOMEM(tree == NULL, aug); tree_store_value(tree, &tmp); /* Set 'lens/info' */ tmp = format_info(lens->info); ERR_NOMEM(tmp == NULL, aug); tree = tree_path_cr(file, 2, s_lens, s_info); ERR_NOMEM(tree == NULL, aug); r = tree_set_value(tree, tmp); ERR_NOMEM(r < 0, aug); FREE(tmp); /* Set 'lens' */ tree = tree->parent; r = tree_set_value(tree, lens_name); ERR_NOMEM(r < 0, aug); tree_clean(file); result = 0; error: free(path); free(tmp); return result; } static char *append_newline(char *text, size_t len) { /* Try to append a newline; this is a big hack to work */ /* around the fact that lenses generally break if the */ /* file does not end with a newline. */ if (len == 0 || text[len-1] != '\n') { if (REALLOC_N(text, len+2) == 0) { text[len] = '\n'; text[len+1] = '\0'; } } return text; } /* Turn the file name FNAME, which starts with aug->root, into * a path in the tree underneath /files */ static char *file_name_path(struct augeas *aug, const char *fname) { char *path = NULL; pathjoin(&path, 2, AUGEAS_FILES_TREE, fname + strlen(aug->root) - 1); return path; } static int load_file(struct augeas *aug, struct lens *lens, const char *lens_name, char *filename) { char *text = NULL; const char *err_status = NULL; struct tree *tree = NULL; char *path = NULL; struct lns_error *err = NULL; struct span *span = NULL; int result = -1, r, text_len = 0; path = file_name_path(aug, filename); ERR_NOMEM(path == NULL, aug); r = add_file_info(aug, path, lens, lens_name, filename, false); if (r < 0) goto done; text = xread_file(filename); if (text == NULL) { err_status = "read_failed"; goto done; } text_len = strlen(text); text = append_newline(text, text_len); struct info *info; make_ref(info); make_ref(info->filename); info->filename->str = strdup(filename); info->error = aug->error; info->flags = aug->flags; info->first_line = 1; if (aug->flags & AUG_ENABLE_SPAN) { span = make_span(info); ERR_NOMEM(span == NULL, info); } tree = lns_get(info, lens, text, &err); unref(info, info); if (err != NULL) { err_status = "parse_failed"; goto done; } tree_replace(aug, path, tree); /* top level node span entire file length */ if (span != NULL && tree != NULL) { tree->parent->span = span; tree->parent->span->span_start = 0; tree->parent->span->span_end = text_len; } tree = NULL; result = 0; done: store_error(aug, filename + strlen(aug->root) - 1, path, err_status, errno, err, text); error: free_lns_error(err); free(path); free_tree(tree); free(text); return result; } /* The lens for a transform can be referred to in one of two ways: * either by a fully qualified name "Module.lens" or by the special * syntax "@Module"; the latter means we should take the lens from the * autoload transform for Module */ static struct lens *lens_from_name(struct augeas *aug, const char *name) { struct lens *result = NULL; if (name[0] == '@') { struct module *modl = NULL; for (modl = aug->modules; modl != NULL && !streqv(modl->name, name + 1); modl = modl->next); ERR_THROW(modl == NULL, aug, AUG_ENOLENS, "Could not find module %s", name + 1); ERR_THROW(modl->autoload == NULL, aug, AUG_ENOLENS, "No autoloaded lens in module %s", name + 1); result = modl->autoload->lens; } else { result = lens_lookup(aug, name); } ERR_THROW(result == NULL, aug, AUG_ENOLENS, "Can not find lens %s", name); return result; error: return NULL; } int text_store(struct augeas *aug, const char *lens_path, const char *path, const char *text) { struct info *info = NULL; struct lns_error *err = NULL; struct tree *tree = NULL; struct span *span = NULL; int result = -1; const char *err_status = NULL; struct lens *lens = NULL; lens = lens_from_name(aug, lens_path); if (lens == NULL) { goto done; } make_ref(info); info->first_line = 1; info->last_line = 1; info->first_column = 1; info->last_column = strlen(text); tree = lns_get(info, lens, text, &err); if (err != NULL) { err_status = "parse_failed"; goto done; } unref(info, info); tree_replace(aug, path, tree); /* top level node span entire file length */ if (span != NULL && tree != NULL) { tree->parent->span = span; tree->parent->span->span_start = 0; tree->parent->span->span_end = strlen(text); } tree = NULL; result = 0; done: store_error(aug, NULL, path, err_status, errno, err, text); free_tree(tree); free_lns_error(err); return result; } const char *xfm_lens_name(struct tree *xfm) { struct tree *l = tree_child(xfm, s_lens); if (l == NULL) return "(unknown)"; if (l->value == NULL) return "(noname)"; return l->value; } static struct lens *xfm_lens(struct augeas *aug, struct tree *xfm, const char **lens_name) { struct tree *l = NULL; for (l = xfm->children; l != NULL && !streqv("lens", l->label); l = l->next); if (l == NULL || l->value == NULL) return NULL; *lens_name = l->value; return lens_from_name(aug, l->value); } static void xfm_error(struct tree *xfm, const char *msg) { char *v = strdup(msg); char *l = strdup("error"); if (l == NULL || v == NULL) return; tree_append(xfm, l, v); } int transform_validate(struct augeas *aug, struct tree *xfm) { struct tree *l = NULL; for (struct tree *t = xfm->children; t != NULL; ) { if (streqv(t->label, "lens")) { l = t; } else if ((is_incl(t) || (is_excl(t) && strchr(t->value, SEP) != NULL)) && t->value[0] != SEP) { /* Normalize relative paths to absolute ones */ int r; r = REALLOC_N(t->value, strlen(t->value) + 2); ERR_NOMEM(r < 0, aug); memmove(t->value + 1, t->value, strlen(t->value) + 1); t->value[0] = SEP; } if (streqv(t->label, "error")) { struct tree *del = t; t = del->next; tree_unlink(del); } else { t = t->next; } } if (l == NULL) { xfm_error(xfm, "missing a child with label 'lens'"); return -1; } if (l->value == NULL) { xfm_error(xfm, "the 'lens' node does not contain a lens name"); return -1; } lens_from_name(aug, l->value); ERR_BAIL(aug); return 0; error: xfm_error(xfm, aug->error->details); return -1; } void transform_file_error(struct augeas *aug, const char *status, const char *filename, const char *format, ...) { char *ep = err_path(filename); struct tree *err; char *msg; va_list ap; int r; err = tree_find_cr(aug, ep); if (err == NULL) return; tree_unlink_children(aug, err); tree_set_value(err, status); err = tree_child_cr(err, s_message); if (err == NULL) return; va_start(ap, format); r = vasprintf(&msg, format, ap); va_end(ap); if (r < 0) return; tree_set_value(err, msg); free(msg); } static struct tree *file_info(struct augeas *aug, const char *fname) { char *path = NULL; struct tree *result = NULL; int r; r = pathjoin(&path, 2, AUGEAS_META_FILES, fname); ERR_NOMEM(r < 0, aug); result = tree_find(aug, path); ERR_BAIL(aug); error: free(path); return result; } int transform_load(struct augeas *aug, struct tree *xfm) { int nmatches = 0; char **matches; const char *lens_name; struct lens *lens = xfm_lens(aug, xfm, &lens_name); int r; if (lens == NULL) { // FIXME: Record an error and return 0 return -1; } r = filter_generate(xfm, aug->root, &nmatches, &matches); if (r == -1) return -1; for (int i=0; i < nmatches; i++) { const char *filename = matches[i] + strlen(aug->root) - 1; struct tree *finfo = file_info(aug, filename); if (finfo != NULL && !finfo->dirty && tree_child(finfo, s_lens) != NULL) { const char *s = xfm_lens_name(finfo); char *fpath = file_name_path(aug, matches[i]); transform_file_error(aug, "mxfm_load", filename, "Lenses %s and %s could be used to load this file", s, lens_name); aug_rm(aug, fpath); free(fpath); } else if (!file_current(aug, matches[i], finfo)) { load_file(aug, lens, lens_name, matches[i]); } if (finfo != NULL) finfo->dirty = 0; FREE(matches[i]); } lens_release(lens); free(matches); return 0; } int transform_applies(struct tree *xfm, const char *path) { if (STRNEQLEN(path, AUGEAS_FILES_TREE, strlen(AUGEAS_FILES_TREE)) || path[strlen(AUGEAS_FILES_TREE)] != SEP) return 0; return filter_matches(xfm, path + strlen(AUGEAS_FILES_TREE)); } static int transfer_file_attrs(const char *from, const char *to, const char **err_status) { struct stat st; int ret = 0; int selinux_enabled = (is_selinux_enabled() > 0); security_context_t con = NULL; ret = lstat(from, &st); if (ret < 0) { *err_status = "replace_stat"; return -1; } if (selinux_enabled) { if (lgetfilecon(from, &con) < 0 && errno != ENOTSUP) { *err_status = "replace_getfilecon"; return -1; } } if (lchown(to, st.st_uid, st.st_gid) < 0) { *err_status = "replace_chown"; return -1; } if (chmod(to, st.st_mode) < 0) { *err_status = "replace_chmod"; return -1; } if (selinux_enabled && con != NULL) { if (lsetfilecon(to, con) < 0 && errno != ENOTSUP) { *err_status = "replace_setfilecon"; return -1; } freecon(con); } return 0; } /* Try to rename FROM to TO. If that fails with an error other than EXDEV * or EBUSY, return -1. If the failure is EXDEV or EBUSY (which we assume * means that FROM or TO is a bindmounted file), and COPY_IF_RENAME_FAILS * is true, copy the contents of FROM into TO and delete FROM. * * Return 0 on success (either rename succeeded or we copied the contents * over successfully), -1 on failure. */ static int clone_file(const char *from, const char *to, const char **err_status, int copy_if_rename_fails) { FILE *from_fp = NULL, *to_fp = NULL; char buf[BUFSIZ]; size_t len; int result = -1; if (rename(from, to) == 0) return 0; if ((errno != EXDEV && errno != EBUSY) || !copy_if_rename_fails) { *err_status = "rename"; return -1; } /* rename not possible, copy file contents */ if (!(from_fp = fopen(from, "r"))) { *err_status = "clone_open_src"; goto done; } if (!(to_fp = fopen(to, "w"))) { *err_status = "clone_open_dst"; goto done; } if (transfer_file_attrs(from, to, err_status) < 0) goto done; while ((len = fread(buf, 1, BUFSIZ, from_fp)) > 0) { if (fwrite(buf, 1, len, to_fp) != len) { *err_status = "clone_write"; goto done; } } if (ferror(from_fp)) { *err_status = "clone_read"; goto done; } if (fflush(to_fp) != 0) { *err_status = "clone_flush"; goto done; } if (fsync(fileno(to_fp)) < 0) { *err_status = "clone_sync"; goto done; } result = 0; done: if (from_fp != NULL) fclose(from_fp); if (to_fp != NULL && fclose(to_fp) != 0) result = -1; if (result != 0) unlink(to); if (result == 0) unlink(from); return result; } static char *strappend(const char *s1, const char *s2) { size_t len = strlen(s1) + strlen(s2); char *result = NULL, *p; if (ALLOC_N(result, len + 1) < 0) return NULL; p = stpcpy(result, s1); stpcpy(p, s2); return result; } static int file_saved_event(struct augeas *aug, const char *path) { const char *saved = strrchr(AUGEAS_EVENTS_SAVED, SEP) + 1; struct pathx *px; struct tree *dummy; int r; px = pathx_aug_parse(aug, aug->origin, NULL, AUGEAS_EVENTS_SAVED "[last()]", true); ERR_BAIL(aug); if (pathx_find_one(px, &dummy) == 1) { r = tree_insert(px, saved, 0); if (r < 0) goto error; } if (! tree_set(px, path)) goto error; free_pathx(px); return 0; error: free_pathx(px); return -1; } /* * Save TREE->CHILDREN into the file PATH using the lens from XFORM. Errors * are noted in the /augeas/files hierarchy in AUG->ORIGIN under * PATH/error. * * Writing the file happens by first writing into PATH.augnew, transferring * all file attributes of PATH to PATH.augnew, and then renaming * PATH.augnew to PATH. If the rename fails, and the entry * AUGEAS_COPY_IF_FAILURE exists in AUG->ORIGIN, PATH is overwritten by * copying file contents * * Return 0 on success, -1 on failure. */ int transform_save(struct augeas *aug, struct tree *xfm, const char *path, struct tree *tree) { FILE *fp = NULL; char *augnew = NULL, *augorig = NULL, *augsave = NULL; char *augorig_canon = NULL; int augorig_exists; int copy_if_rename_fails = 0; char *text = NULL; const char *filename = path + strlen(AUGEAS_FILES_TREE) + 1; const char *err_status = NULL; char *dyn_err_status = NULL; struct lns_error *err = NULL; const char *lens_name; struct lens *lens = xfm_lens(aug, xfm, &lens_name); int result = -1, r; bool force_reload; errno = 0; if (lens == NULL) { err_status = "lens_name"; goto done; } copy_if_rename_fails = aug_get(aug, AUGEAS_COPY_IF_RENAME_FAILS, NULL) == 1; if (asprintf(&augorig, "%s%s", aug->root, filename) == -1) { augorig = NULL; goto done; } if (access(augorig, R_OK) == 0) { text = xread_file(augorig); } else { text = strdup(""); } if (text == NULL) { err_status = "put_read"; goto done; } text = append_newline(text, strlen(text)); augorig_canon = canonicalize_file_name(augorig); augorig_exists = 1; if (augorig_canon == NULL) { if (errno == ENOENT) { augorig_canon = augorig; augorig_exists = 0; } else { err_status = "canon_augorig"; goto done; } } /* Figure out where to put the .augnew file. If we need to rename it later on, put it next to augorig_canon */ if (aug->flags & AUG_SAVE_NEWFILE) { if (xasprintf(&augnew, "%s" EXT_AUGNEW, augorig) < 0) { err_status = "augnew_oom"; goto done; } } else { if (xasprintf(&augnew, "%s" EXT_AUGNEW, augorig_canon) < 0) { err_status = "augnew_oom"; goto done; } } // FIXME: We might have to create intermediate directories // to be able to write augnew, but we have no idea what permissions // etc. they should get. Just the process default ? fp = fopen(augnew, "w"); if (fp == NULL) { err_status = "open_augnew"; goto done; } if (augorig_exists) { if (transfer_file_attrs(augorig_canon, augnew, &err_status) != 0) { err_status = "xfer_attrs"; goto done; } } if (tree != NULL) lns_put(fp, lens, tree->children, text, &err); if (ferror(fp)) { err_status = "error_augnew"; goto done; } if (fflush(fp) != 0) { err_status = "flush_augnew"; goto done; } if (fsync(fileno(fp)) < 0) { err_status = "sync_augnew"; goto done; } if (fclose(fp) != 0) { err_status = "close_augnew"; fp = NULL; goto done; } fp = NULL; if (err != NULL) { err_status = err->pos >= 0 ? "parse_skel_failed" : "put_failed"; unlink(augnew); goto done; } { char *new_text = xread_file(augnew); int same = 0; if (new_text == NULL) { err_status = "read_augnew"; goto done; } same = STREQ(text, new_text); FREE(new_text); if (same) { result = 0; unlink(augnew); goto done; } else if (aug->flags & AUG_SAVE_NOOP) { result = 1; unlink(augnew); goto done; } } if (!(aug->flags & AUG_SAVE_NEWFILE)) { if (augorig_exists && (aug->flags & AUG_SAVE_BACKUP)) { r = asprintf(&augsave, "%s%s" EXT_AUGSAVE, aug->root, filename); if (r == -1) { augsave = NULL; goto done; } r = clone_file(augorig_canon, augsave, &err_status, 1); if (r != 0) { dyn_err_status = strappend(err_status, "_augsave"); goto done; } } r = clone_file(augnew, augorig_canon, &err_status, copy_if_rename_fails); if (r != 0) { dyn_err_status = strappend(err_status, "_augnew"); goto done; } } result = 1; done: force_reload = aug->flags & AUG_SAVE_NEWFILE; r = add_file_info(aug, path, lens, lens_name, augorig, force_reload); if (r < 0) { err_status = "file_info"; result = -1; } if (result > 0) { r = file_saved_event(aug, path); if (r < 0) { err_status = "saved_event"; result = -1; } } { const char *emsg = dyn_err_status == NULL ? err_status : dyn_err_status; store_error(aug, filename, path, emsg, errno, err, text); } free(dyn_err_status); lens_release(lens); free(text); free(augnew); if (augorig_canon != augorig) free(augorig_canon); free(augorig); free(augsave); free_lns_error(err); if (fp != NULL) fclose(fp); return result; } int text_retrieve(struct augeas *aug, const char *lens_name, const char *path, struct tree *tree, const char *text_in, char **text_out) { struct memstream ms; bool ms_open; const char *err_status = NULL; char *dyn_err_status = NULL; struct lns_error *err = NULL; struct lens *lens = NULL; int result = -1, r; MEMZERO(&ms, 1); errno = 0; lens = lens_from_name(aug, lens_name); if (lens == NULL) { err_status = "lens_name"; goto done; } r = init_memstream(&ms); if (r < 0) { err_status = "init_memstream"; goto done; } ms_open = true; if (tree != NULL) lns_put(ms.stream, lens, tree->children, text_in, &err); r = close_memstream(&ms); ms_open = false; if (r < 0) { err_status = "close_memstream"; goto done; } *text_out = ms.buf; ms.buf = NULL; if (err != NULL) { err_status = err->pos >= 0 ? "parse_skel_failed" : "put_failed"; goto done; } result = 0; done: { const char *emsg = dyn_err_status == NULL ? err_status : dyn_err_status; store_error(aug, NULL, path, emsg, errno, err, text_in); } free(dyn_err_status); lens_release(lens); if (result < 0) { free(*text_out); *text_out = NULL; } free_lns_error(err); if (ms_open) close_memstream(&ms); return result; } int remove_file(struct augeas *aug, struct tree *tree) { char *path = NULL; const char *filename = NULL; const char *err_status = NULL; char *dyn_err_status = NULL; char *augsave = NULL, *augorig = NULL, *augorig_canon = NULL; int r; path = path_of_tree(tree); if (path == NULL) { err_status = "path_of_tree"; goto error; } filename = path + strlen(AUGEAS_META_FILES); if ((augorig = strappend(aug->root, filename + 1)) == NULL) { err_status = "root_file"; goto error; } augorig_canon = canonicalize_file_name(augorig); if (augorig_canon == NULL) { if (errno == ENOENT) { goto done; } else { err_status = "canon_augorig"; goto error; } } r = file_saved_event(aug, path + strlen(AUGEAS_META_TREE)); if (r < 0) { err_status = "saved_event"; goto error; } if (aug->flags & AUG_SAVE_NOOP) goto done; if (aug->flags & AUG_SAVE_BACKUP) { /* Move file to one with extension .augsave */ r = asprintf(&augsave, "%s" EXT_AUGSAVE, augorig_canon); if (r == -1) { augsave = NULL; goto error; } r = clone_file(augorig_canon, augsave, &err_status, 1); if (r != 0) { dyn_err_status = strappend(err_status, "_augsave"); goto error; } } else { /* Unlink file */ r = unlink(augorig_canon); if (r < 0) { err_status = "unlink_orig"; goto error; } } tree_unlink(tree); done: free(path); free(augorig); free(augorig_canon); free(augsave); return 0; error: { const char *emsg = dyn_err_status == NULL ? err_status : dyn_err_status; store_error(aug, filename, path, emsg, errno, NULL, NULL); } free(path); free(augorig); free(augorig_canon); free(augsave); free(dyn_err_status); return -1; } /* * Local variables: * indent-tabs-mode: nil * c-indent-level: 4 * c-basic-offset: 4 * tab-width: 4 * End: */
./CrossVul/dataset_final_sorted/CWE-59/c/bad_3576_3
crossvul-cpp_data_bad_4226_3
/* * mib.c * * $Id$ * * Update: 1998-07-17 <jhy@gsu.edu> * Added print_oid_report* functions. * */ /* Portions of this file are subject to the following copyrights. See * the Net-SNMP's COPYING file for more details and other copyrights * that may apply: */ /********************************************************************** Copyright 1988, 1989, 1991, 1992 by Carnegie Mellon University All Rights Reserved Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation, and that the name of CMU not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. CMU DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL CMU BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ******************************************************************/ /* * Copyright � 2003 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms specified in the COPYING file * distributed with the Net-SNMP package. * * Portions of this file are copyrighted by: * Copyright (c) 2016 VMware, Inc. All rights reserved. * Use is subject to license terms specified in the COPYING file * distributed with the Net-SNMP package. */ #include <net-snmp/net-snmp-config.h> #include <net-snmp/net-snmp-features.h> #include <stdio.h> #include <ctype.h> #include <sys/types.h> #if HAVE_DIRENT_H # include <dirent.h> # define NAMLEN(dirent) strlen((dirent)->d_name) #else # define dirent direct # define NAMLEN(dirent) (dirent)->d_namlen # if HAVE_SYS_NDIR_H # include <sys/ndir.h> # endif # if HAVE_SYS_DIR_H # include <sys/dir.h> # endif # if HAVE_NDIR_H # include <ndir.h> # endif #endif #ifdef HAVE_INTTYPES_H #include <inttypes.h> #endif #if HAVE_NETINET_IN_H #include <netinet/in.h> #endif #if TIME_WITH_SYS_TIME # include <sys/time.h> # include <time.h> #else # if HAVE_SYS_TIME_H # include <sys/time.h> # else # include <time.h> # endif #endif #if HAVE_STRING_H #include <string.h> #else #include <strings.h> #endif #if HAVE_STDLIB_H #include <stdlib.h> #endif #if HAVE_SYS_SELECT_H #include <sys/select.h> #endif #if HAVE_UNISTD_H #include <unistd.h> #endif #if HAVE_DMALLOC_H #include <dmalloc.h> #endif #include <net-snmp/types.h> #include <net-snmp/output_api.h> #include <net-snmp/config_api.h> #include <net-snmp/utilities.h> #include <net-snmp/library/asn1.h> #include <net-snmp/library/snmp_api.h> #include <net-snmp/library/mib.h> #include <net-snmp/library/parse.h> #include <net-snmp/library/int64.h> #include <net-snmp/library/snmp_client.h> netsnmp_feature_child_of(mib_api, libnetsnmp) netsnmp_feature_child_of(mib_strings_all, mib_api) netsnmp_feature_child_of(mib_snprint, mib_strings_all) netsnmp_feature_child_of(mib_snprint_description, mib_strings_all) netsnmp_feature_child_of(mib_snprint_variable, mib_strings_all) netsnmp_feature_child_of(mib_string_conversions, mib_strings_all) netsnmp_feature_child_of(print_mib, mib_strings_all) netsnmp_feature_child_of(snprint_objid, mib_strings_all) netsnmp_feature_child_of(snprint_value, mib_strings_all) netsnmp_feature_child_of(mib_to_asn_type, mib_api) /** @defgroup mib_utilities mib parsing and datatype manipulation routines. * @ingroup library * * @{ */ static char *uptimeString(u_long, char *, size_t); #ifndef NETSNMP_DISABLE_MIB_LOADING static struct tree *_get_realloc_symbol(const oid * objid, size_t objidlen, struct tree *subtree, u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, int *buf_overflow, struct index_list *in_dices, size_t * end_of_known); static int print_tree_node(u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, struct tree *tp, int width); static void handle_mibdirs_conf(const char *token, char *line); static void handle_mibs_conf(const char *token, char *line); static void handle_mibfile_conf(const char *token, char *line); #endif /*NETSNMP_DISABLE_MIB_LOADING */ static void _oid_finish_printing(const oid * objid, size_t objidlen, u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, int *buf_overflow); /* * helper functions for get_module_node */ #ifndef NETSNMP_DISABLE_MIB_LOADING static int node_to_oid(struct tree *, oid *, size_t *); static int _add_strings_to_oid(struct tree *, char *, oid *, size_t *, size_t); #else static int _add_strings_to_oid(void *, char *, oid *, size_t *, size_t); #endif /* NETSNMP_DISABLE_MIB_LOADING */ #ifndef NETSNMP_DISABLE_MIB_LOADING NETSNMP_IMPORT struct tree *tree_head; static struct tree *tree_top; NETSNMP_IMPORT struct tree *Mib; struct tree *Mib; /* Backwards compatibility */ #endif /* NETSNMP_DISABLE_MIB_LOADING */ static char Standard_Prefix[] = ".1.3.6.1.2.1"; /* * Set default here as some uses of read_objid require valid pointer. */ #ifndef NETSNMP_DISABLE_MIB_LOADING static char *Prefix = &Standard_Prefix[0]; #endif /* NETSNMP_DISABLE_MIB_LOADING */ typedef struct _PrefixList { const char *str; int len; } *PrefixListPtr, PrefixList; /* * Here are the prefix strings. * Note that the first one finds the value of Prefix or Standard_Prefix. * Any of these MAY start with period; all will NOT end with period. * Period is added where needed. See use of Prefix in this module. */ PrefixList mib_prefixes[] = { {&Standard_Prefix[0]}, /* placeholder for Prefix data */ {".iso.org.dod.internet.mgmt.mib-2"}, {".iso.org.dod.internet.experimental"}, {".iso.org.dod.internet.private"}, {".iso.org.dod.internet.snmpParties"}, {".iso.org.dod.internet.snmpSecrets"}, {NULL, 0} /* end of list */ }; enum inet_address_type { IPV4 = 1, IPV6 = 2, IPV4Z = 3, IPV6Z = 4, DNS = 16 }; /** * @internal * Converts timeticks to hours, minutes, seconds string. * * @param timeticks The timeticks to convert. * @param buf Buffer to write to, has to be at * least 40 Bytes large. * * @return The buffer. */ static char * uptimeString(u_long timeticks, char *buf, size_t buflen) { int centisecs, seconds, minutes, hours, days; if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_NUMERIC_TIMETICKS)) { snprintf(buf, buflen, "%lu", timeticks); return buf; } centisecs = timeticks % 100; timeticks /= 100; days = timeticks / (60 * 60 * 24); timeticks %= (60 * 60 * 24); hours = timeticks / (60 * 60); timeticks %= (60 * 60); minutes = timeticks / 60; seconds = timeticks % 60; if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT)) snprintf(buf, buflen, "%d:%d:%02d:%02d.%02d", days, hours, minutes, seconds, centisecs); else { if (days == 0) { snprintf(buf, buflen, "%d:%02d:%02d.%02d", hours, minutes, seconds, centisecs); } else if (days == 1) { snprintf(buf, buflen, "%d day, %d:%02d:%02d.%02d", days, hours, minutes, seconds, centisecs); } else { snprintf(buf, buflen, "%d days, %d:%02d:%02d.%02d", days, hours, minutes, seconds, centisecs); } } return buf; } /** * @internal * Prints the character pointed to if in human-readable ASCII range, * otherwise prints a dot. * * @param buf Buffer to print the character to. * @param ch Character to print. */ static void sprint_char(char *buf, const u_char ch) { if (isprint(ch) || isspace(ch)) { sprintf(buf, "%c", (int) ch); } else { sprintf(buf, "."); } } /** * Prints a hexadecimal string into a buffer. * * The characters pointed by *cp are encoded as hexadecimal string. * * If allow_realloc is true the buffer will be (re)allocated to fit in the * needed size. (Note: *buf may change due to this.) * * @param buf address of the buffer to print to. * @param buf_len address to an integer containing the size of buf. * @param out_len incremented by the number of characters printed. * @param allow_realloc if not zero reallocate the buffer to fit the * needed size. * @param cp the array of characters to encode. * @param line_len the array length of cp. * * @return 1 on success, or 0 on failure (out of memory, or buffer to * small when not allowed to realloc.) */ int _sprint_hexstring_line(u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, const u_char * cp, size_t line_len) { const u_char *tp; const u_char *cp2 = cp; size_t lenleft = line_len; /* * Make sure there's enough room for the hex output.... */ while ((*out_len + line_len*3+1) >= *buf_len) { if (!(allow_realloc && snmp_realloc(buf, buf_len))) { return 0; } } /* * .... and display the hex values themselves.... */ for (; lenleft >= 8; lenleft-=8) { sprintf((char *) (*buf + *out_len), "%02X %02X %02X %02X %02X %02X %02X %02X ", cp[0], cp[1], cp[2], cp[3], cp[4], cp[5], cp[6], cp[7]); *out_len += strlen((char *) (*buf + *out_len)); cp += 8; } for (; lenleft > 0; lenleft--) { sprintf((char *) (*buf + *out_len), "%02X ", *cp++); *out_len += strlen((char *) (*buf + *out_len)); } /* * .... plus (optionally) do the same for the ASCII equivalent. */ if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PRINT_HEX_TEXT)) { while ((*out_len + line_len+5) >= *buf_len) { if (!(allow_realloc && snmp_realloc(buf, buf_len))) { return 0; } } sprintf((char *) (*buf + *out_len), " ["); *out_len += strlen((char *) (*buf + *out_len)); for (tp = cp2; tp < cp; tp++) { sprint_char((char *) (*buf + *out_len), *tp); (*out_len)++; } sprintf((char *) (*buf + *out_len), "]"); *out_len += strlen((char *) (*buf + *out_len)); } return 1; } int sprint_realloc_hexstring(u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, const u_char * cp, size_t len) { int line_len = netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_HEX_OUTPUT_LENGTH); if (line_len <= 0) line_len = len; for (; (int)len > line_len; len -= line_len) { if(!_sprint_hexstring_line(buf, buf_len, out_len, allow_realloc, cp, line_len)) return 0; *(*buf + (*out_len)++) = '\n'; *(*buf + *out_len) = 0; cp += line_len; } if(!_sprint_hexstring_line(buf, buf_len, out_len, allow_realloc, cp, len)) return 0; *(*buf + *out_len) = 0; return 1; } /** * Prints an ascii string into a buffer. * * The characters pointed by *cp are encoded as an ascii string. * * If allow_realloc is true the buffer will be (re)allocated to fit in the * needed size. (Note: *buf may change due to this.) * * @param buf address of the buffer to print to. * @param buf_len address to an integer containing the size of buf. * @param out_len incremented by the number of characters printed. * @param allow_realloc if not zero reallocate the buffer to fit the * needed size. * @param cp the array of characters to encode. * @param len the array length of cp. * * @return 1 on success, or 0 on failure (out of memory, or buffer to * small when not allowed to realloc.) */ int sprint_realloc_asciistring(u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, const u_char * cp, size_t len) { int i; for (i = 0; i < (int) len; i++) { if (isprint(*cp) || isspace(*cp)) { if (*cp == '\\' || *cp == '"') { if ((*out_len >= *buf_len) && !(allow_realloc && snmp_realloc(buf, buf_len))) { return 0; } *(*buf + (*out_len)++) = '\\'; } if ((*out_len >= *buf_len) && !(allow_realloc && snmp_realloc(buf, buf_len))) { return 0; } *(*buf + (*out_len)++) = *cp++; } else { if ((*out_len >= *buf_len) && !(allow_realloc && snmp_realloc(buf, buf_len))) { return 0; } *(*buf + (*out_len)++) = '.'; cp++; } } if ((*out_len >= *buf_len) && !(allow_realloc && snmp_realloc(buf, buf_len))) { return 0; } *(*buf + *out_len) = '\0'; return 1; } /** * Prints an octet string into a buffer. * * The variable var is encoded as octet string. * * If allow_realloc is true the buffer will be (re)allocated to fit in the * needed size. (Note: *buf may change due to this.) * * @param buf Address of the buffer to print to. * @param buf_len Address to an integer containing the size of buf. * @param out_len Incremented by the number of characters printed. * @param allow_realloc if not zero reallocate the buffer to fit the * needed size. * @param var The variable to encode. * @param enums The enumeration ff this variable is enumerated. may be NULL. * @param hint Contents of the DISPLAY-HINT clause of the MIB. * See RFC 1903 Section 3.1 for details. may be NULL. * @param units Contents of the UNITS clause of the MIB. may be NULL. * * @return 1 on success, or 0 on failure (out of memory, or buffer to * small when not allowed to realloc.) */ int sprint_realloc_octet_string(u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, const netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { size_t saved_out_len = *out_len; const char *saved_hint = hint; int hex = 0, x = 0; u_char *cp; int output_format, cnt; if (var->type != ASN_OCTET_STR) { if (!netsnmp_ds_get_boolean( NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICKE_PRINT)) { const char str[] = "Wrong Type (should be OCTET STRING): "; if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, str)) return 0; } return sprint_realloc_by_type(buf, buf_len, out_len, allow_realloc, var, NULL, NULL, NULL); } if (hint) { int repeat, width = 1; long value; char code = 'd', separ = 0, term = 0, ch, intbuf[32]; #define HEX2DIGIT_NEED_INIT 3 char hex2digit = HEX2DIGIT_NEED_INIT; u_char *ecp; if (!netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT)) { if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, "STRING: ")) { return 0; } } cp = var->val.string; ecp = cp + var->val_len; while (cp < ecp) { repeat = 1; if (*hint) { if (*hint == '*') { repeat = *cp++; hint++; } width = 0; while ('0' <= *hint && *hint <= '9') width = (width * 10) + (*hint++ - '0'); code = *hint++; if ((ch = *hint) && ch != '*' && (ch < '0' || ch > '9') && (width != 0 || (ch != 'x' && ch != 'd' && ch != 'o'))) separ = *hint++; else separ = 0; if ((ch = *hint) && ch != '*' && (ch < '0' || ch > '9') && (width != 0 || (ch != 'x' && ch != 'd' && ch != 'o'))) term = *hint++; else term = 0; if (width == 0) /* Handle malformed hint strings */ width = 1; } while (repeat && cp < ecp) { value = 0; if (code != 'a' && code != 't') { for (x = 0; x < width; x++) { value = value * 256 + *cp++; } } switch (code) { case 'x': if (HEX2DIGIT_NEED_INIT == hex2digit) hex2digit = netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_2DIGIT_HEX_OUTPUT); /* * if value is < 16, it will be a single hex digit. If the * width is 1 (we are outputting a byte at a time), pat it * to 2 digits if NETSNMP_DS_LIB_2DIGIT_HEX_OUTPUT is set * or all of the following are true: * - we do not have a separation character * - there is no hint left (or there never was a hint) * * e.g. for the data 0xAA01BB, would anyone really ever * want the string "AA1BB"?? */ if (((value < 16) && (1 == width)) && (hex2digit || ((0 == separ) && (0 == *hint)))) { sprintf(intbuf, "0%lx", value); } else { sprintf(intbuf, "%lx", value); } if (!snmp_cstrcat (buf, buf_len, out_len, allow_realloc, intbuf)) { return 0; } break; case 'd': sprintf(intbuf, "%ld", value); if (!snmp_cstrcat (buf, buf_len, out_len, allow_realloc, intbuf)) { return 0; } break; case 'o': sprintf(intbuf, "%lo", value); if (!snmp_cstrcat (buf, buf_len, out_len, allow_realloc, intbuf)) { return 0; } break; case 't': /* new in rfc 3411 */ case 'a': /* A string hint gives the max size - we may not need this much */ cnt = SNMP_MIN(width, ecp - cp); while ((*out_len + cnt + 1) > *buf_len) { if (!allow_realloc || !snmp_realloc(buf, buf_len)) return 0; } if (memchr(cp, '\0', cnt) == NULL) { /* No embedded '\0' - use memcpy() to preserve UTF-8 */ memcpy(*buf + *out_len, cp, cnt); *out_len += cnt; *(*buf + *out_len) = '\0'; } else if (!sprint_realloc_asciistring(buf, buf_len, out_len, allow_realloc, cp, cnt)) { return 0; } cp += cnt; break; default: *out_len = saved_out_len; if (snmp_cstrcat(buf, buf_len, out_len, allow_realloc, "(Bad hint ignored: ") && snmp_cstrcat(buf, buf_len, out_len, allow_realloc, saved_hint) && snmp_cstrcat(buf, buf_len, out_len, allow_realloc, ") ")) { return sprint_realloc_octet_string(buf, buf_len, out_len, allow_realloc, var, enums, NULL, NULL); } else { return 0; } } if (cp < ecp && separ) { while ((*out_len + 1) >= *buf_len) { if (!(allow_realloc && snmp_realloc(buf, buf_len))) { return 0; } } *(*buf + *out_len) = separ; (*out_len)++; *(*buf + *out_len) = '\0'; } repeat--; } if (term && cp < ecp) { while ((*out_len + 1) >= *buf_len) { if (!(allow_realloc && snmp_realloc(buf, buf_len))) { return 0; } } *(*buf + *out_len) = term; (*out_len)++; *(*buf + *out_len) = '\0'; } } if (units) { return (snmp_cstrcat (buf, buf_len, out_len, allow_realloc, " ") && snmp_cstrcat(buf, buf_len, out_len, allow_realloc, units)); } if ((*out_len >= *buf_len) && !(allow_realloc && snmp_realloc(buf, buf_len))) { return 0; } *(*buf + *out_len) = '\0'; return 1; } output_format = netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_STRING_OUTPUT_FORMAT); if (0 == output_format) { output_format = NETSNMP_STRING_OUTPUT_GUESS; } switch (output_format) { case NETSNMP_STRING_OUTPUT_GUESS: hex = 0; for (cp = var->val.string, x = 0; x < (int) var->val_len; x++, cp++) { if (!isprint(*cp) && !isspace(*cp)) { hex = 1; } } break; case NETSNMP_STRING_OUTPUT_ASCII: hex = 0; break; case NETSNMP_STRING_OUTPUT_HEX: hex = 1; break; } if (var->val_len == 0) { return snmp_cstrcat(buf, buf_len, out_len, allow_realloc, "\"\""); } if (hex) { if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT)) { if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, "\"")) { return 0; } } else { if (!snmp_cstrcat (buf, buf_len, out_len, allow_realloc, "Hex-STRING: ")) { return 0; } } if (!sprint_realloc_hexstring(buf, buf_len, out_len, allow_realloc, var->val.string, var->val_len)) { return 0; } if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT)) { if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, "\"")) { return 0; } } } else { if (!netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT)) { if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, "STRING: ")) { return 0; } } if (!snmp_cstrcat (buf, buf_len, out_len, allow_realloc, "\"")) { return 0; } if (!sprint_realloc_asciistring (buf, buf_len, out_len, allow_realloc, var->val.string, var->val_len)) { return 0; } if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, "\"")) { return 0; } } if (units) { return (snmp_cstrcat(buf, buf_len, out_len, allow_realloc, " ") && snmp_cstrcat(buf, buf_len, out_len, allow_realloc, units)); } return 1; } #ifdef NETSNMP_WITH_OPAQUE_SPECIAL_TYPES /** * Prints a float into a buffer. * * The variable var is encoded as a floating point value. * * If allow_realloc is true the buffer will be (re)allocated to fit in the * needed size. (Note: *buf may change due to this.) * * @param buf Address of the buffer to print to. * @param buf_len Address to an integer containing the size of buf. * @param out_len Incremented by the number of characters printed. * @param allow_realloc if not zero reallocate the buffer to fit the * needed size. * @param var The variable to encode. * @param enums The enumeration ff this variable is enumerated. may be NULL. * @param hint Contents of the DISPLAY-HINT clause of the MIB. * See RFC 1903 Section 3.1 for details. may be NULL. * @param units Contents of the UNITS clause of the MIB. may be NULL. * * @return 1 on success, or 0 on failure (out of memory, or buffer to * small when not allowed to realloc.) */ int sprint_realloc_float(u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, const netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { char *printf_format_string = NULL; if (var->type != ASN_OPAQUE_FLOAT) { if (!netsnmp_ds_get_boolean( NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICKE_PRINT)) { u_char str[] = "Wrong Type (should be Float): "; if (!snmp_strcat(buf, buf_len, out_len, allow_realloc, str)) return 0; } return sprint_realloc_by_type(buf, buf_len, out_len, allow_realloc, var, NULL, NULL, NULL); } if (!netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT)) { if (!snmp_cstrcat (buf, buf_len, out_len, allow_realloc, "Opaque: Float: ")) { return 0; } } /* * How much space needed for max. length float? 128 is overkill. */ while ((*out_len + 128 + 1) >= *buf_len) { if (!(allow_realloc && snmp_realloc(buf, buf_len))) { return 0; } } printf_format_string = make_printf_format_string("%f"); if (!printf_format_string) { return 0; } snprintf((char *)(*buf + *out_len), 128, printf_format_string, *var->val.floatVal); free(printf_format_string); *out_len += strlen((char *) (*buf + *out_len)); if (units) { return (snmp_cstrcat(buf, buf_len, out_len, allow_realloc, " ") && snmp_cstrcat(buf, buf_len, out_len, allow_realloc, units)); } return 1; } /** * Prints a double into a buffer. * * The variable var is encoded as a double precision floating point value. * * If allow_realloc is true the buffer will be (re)allocated to fit in the * needed size. (Note: *buf may change due to this.) * * @param buf Address of the buffer to print to. * @param buf_len Address to an integer containing the size of buf. * @param out_len Incremented by the number of characters printed. * @param allow_realloc if not zero reallocate the buffer to fit the * needed size. * @param var The variable to encode. * @param enums The enumeration ff this variable is enumerated. may be NULL. * @param hint Contents of the DISPLAY-HINT clause of the MIB. * See RFC 1903 Section 3.1 for details. may be NULL. * @param units Contents of the UNITS clause of the MIB. may be NULL. * * @return 1 on success, or 0 on failure (out of memory, or buffer to * small when not allowed to realloc.) */ int sprint_realloc_double(u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, const netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { char *printf_format_string = NULL; if (var->type != ASN_OPAQUE_DOUBLE) { if (!netsnmp_ds_get_boolean( NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICKE_PRINT)) { u_char str[] = "Wrong Type (should be Double): "; if (!snmp_strcat(buf, buf_len, out_len, allow_realloc, str)) return 0; } return sprint_realloc_by_type(buf, buf_len, out_len, allow_realloc, var, NULL, NULL, NULL); } if (!netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT)) { if (!snmp_cstrcat (buf, buf_len, out_len, allow_realloc, "Opaque: Float: ")) { return 0; } } /* * How much space needed for max. length double? 128 is overkill. */ while ((*out_len + 128 + 1) >= *buf_len) { if (!(allow_realloc && snmp_realloc(buf, buf_len))) { return 0; } } printf_format_string = make_printf_format_string("%f"); if (!printf_format_string) { return 0; } snprintf((char *)(*buf + *out_len), 128, printf_format_string, *var->val.doubleVal); free(printf_format_string); *out_len += strlen((char *) (*buf + *out_len)); if (units) { return (snmp_cstrcat (buf, buf_len, out_len, allow_realloc, " ") && snmp_cstrcat(buf, buf_len, out_len, allow_realloc, units)); } return 1; } #endif /* NETSNMP_WITH_OPAQUE_SPECIAL_TYPES */ /** * Prints a counter into a buffer. * * The variable var is encoded as a counter value. * * If allow_realloc is true the buffer will be (re)allocated to fit in the * needed size. (Note: *buf may change due to this.) * * @param buf Address of the buffer to print to. * @param buf_len Address to an integer containing the size of buf. * @param out_len Incremented by the number of characters printed. * @param allow_realloc if not zero reallocate the buffer to fit the * needed size. * @param var The variable to encode. * @param enums The enumeration ff this variable is enumerated. may be NULL. * @param hint Contents of the DISPLAY-HINT clause of the MIB. * See RFC 1903 Section 3.1 for details. may be NULL. * @param units Contents of the UNITS clause of the MIB. may be NULL. * * @return 1 on success, or 0 on failure (out of memory, or buffer to * small when not allowed to realloc.) */ int sprint_realloc_counter64(u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, const netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { char a64buf[I64CHARSZ + 1]; if (var->type != ASN_COUNTER64 #ifdef NETSNMP_WITH_OPAQUE_SPECIAL_TYPES && var->type != ASN_OPAQUE_COUNTER64 && var->type != ASN_OPAQUE_I64 && var->type != ASN_OPAQUE_U64 #endif ) { if (!netsnmp_ds_get_boolean( NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICKE_PRINT)) { u_char str[] = "Wrong Type (should be Counter64): "; if (!snmp_strcat(buf, buf_len, out_len, allow_realloc, str)) return 0; } return sprint_realloc_by_type(buf, buf_len, out_len, allow_realloc, var, NULL, NULL, NULL); } if (!netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT)) { #ifdef NETSNMP_WITH_OPAQUE_SPECIAL_TYPES if (var->type != ASN_COUNTER64) { if (!snmp_cstrcat (buf, buf_len, out_len, allow_realloc, "Opaque: ")) { return 0; } } #endif #ifdef NETSNMP_WITH_OPAQUE_SPECIAL_TYPES switch (var->type) { case ASN_OPAQUE_U64: if (!snmp_cstrcat (buf, buf_len, out_len, allow_realloc, "UInt64: ")) { return 0; } break; case ASN_OPAQUE_I64: if (!snmp_cstrcat (buf, buf_len, out_len, allow_realloc, "Int64: ")) { return 0; } break; case ASN_COUNTER64: case ASN_OPAQUE_COUNTER64: #endif if (!snmp_cstrcat (buf, buf_len, out_len, allow_realloc, "Counter64: ")) { return 0; } #ifdef NETSNMP_WITH_OPAQUE_SPECIAL_TYPES } #endif } #ifdef NETSNMP_WITH_OPAQUE_SPECIAL_TYPES if (var->type == ASN_OPAQUE_I64) { printI64(a64buf, var->val.counter64); if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, a64buf)) { return 0; } } else { #endif printU64(a64buf, var->val.counter64); if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, a64buf)) { return 0; } #ifdef NETSNMP_WITH_OPAQUE_SPECIAL_TYPES } #endif if (units) { return (snmp_cstrcat(buf, buf_len, out_len, allow_realloc, " ") && snmp_cstrcat(buf, buf_len, out_len, allow_realloc, units)); } return 1; } /** * Prints an object identifier into a buffer. * * If allow_realloc is true the buffer will be (re)allocated to fit in the * needed size. (Note: *buf may change due to this.) * * @param buf Address of the buffer to print to. * @param buf_len Address to an integer containing the size of buf. * @param out_len Incremented by the number of characters printed. * @param allow_realloc if not zero reallocate the buffer to fit the * needed size. * @param var The variable to encode. * @param enums The enumeration ff this variable is enumerated. may be NULL. * @param hint Contents of the DISPLAY-HINT clause of the MIB. * See RFC 1903 Section 3.1 for details. may be NULL. * @param units Contents of the UNITS clause of the MIB. may be NULL. * * @return 1 on success, or 0 on failure (out of memory, or buffer to * small when not allowed to realloc.) */ int sprint_realloc_opaque(u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, const netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { if (var->type != ASN_OPAQUE #ifdef NETSNMP_WITH_OPAQUE_SPECIAL_TYPES && var->type != ASN_OPAQUE_COUNTER64 && var->type != ASN_OPAQUE_U64 && var->type != ASN_OPAQUE_I64 && var->type != ASN_OPAQUE_FLOAT && var->type != ASN_OPAQUE_DOUBLE #endif /* NETSNMP_WITH_OPAQUE_SPECIAL_TYPES */ ) { if (!netsnmp_ds_get_boolean( NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICKE_PRINT)) { u_char str[] = "Wrong Type (should be Opaque): "; if (!snmp_strcat(buf, buf_len, out_len, allow_realloc, str)) return 0; } return sprint_realloc_by_type(buf, buf_len, out_len, allow_realloc, var, NULL, NULL, NULL); } #ifdef NETSNMP_WITH_OPAQUE_SPECIAL_TYPES switch (var->type) { case ASN_OPAQUE_COUNTER64: case ASN_OPAQUE_U64: case ASN_OPAQUE_I64: return sprint_realloc_counter64(buf, buf_len, out_len, allow_realloc, var, enums, hint, units); break; case ASN_OPAQUE_FLOAT: return sprint_realloc_float(buf, buf_len, out_len, allow_realloc, var, enums, hint, units); break; case ASN_OPAQUE_DOUBLE: return sprint_realloc_double(buf, buf_len, out_len, allow_realloc, var, enums, hint, units); break; case ASN_OPAQUE: #endif if (!netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT)) { u_char str[] = "OPAQUE: "; if (!snmp_strcat(buf, buf_len, out_len, allow_realloc, str)) { return 0; } } if (!sprint_realloc_hexstring(buf, buf_len, out_len, allow_realloc, var->val.string, var->val_len)) { return 0; } #ifdef NETSNMP_WITH_OPAQUE_SPECIAL_TYPES } #endif if (units) { return (snmp_strcat (buf, buf_len, out_len, allow_realloc, (const u_char *) " ") && snmp_strcat(buf, buf_len, out_len, allow_realloc, (const u_char *) units)); } return 1; } /** * Prints an object identifier into a buffer. * * If allow_realloc is true the buffer will be (re)allocated to fit in the * needed size. (Note: *buf may change due to this.) * * @param buf Address of the buffer to print to. * @param buf_len Address to an integer containing the size of buf. * @param out_len Incremented by the number of characters printed. * @param allow_realloc if not zero reallocate the buffer to fit the * needed size. * @param var The variable to encode. * @param enums The enumeration ff this variable is enumerated. may be NULL. * @param hint Contents of the DISPLAY-HINT clause of the MIB. * See RFC 1903 Section 3.1 for details. may be NULL. * @param units Contents of the UNITS clause of the MIB. may be NULL. * * @return 1 on success, or 0 on failure (out of memory, or buffer to * small when not allowed to realloc.) */ int sprint_realloc_object_identifier(u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, const netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { int buf_overflow = 0; if (var->type != ASN_OBJECT_ID) { if (!netsnmp_ds_get_boolean( NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICKE_PRINT)) { u_char str[] = "Wrong Type (should be OBJECT IDENTIFIER): "; if (!snmp_strcat(buf, buf_len, out_len, allow_realloc, str)) return 0; } return sprint_realloc_by_type(buf, buf_len, out_len, allow_realloc, var, NULL, NULL, NULL); } if (!netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT)) { u_char str[] = "OID: "; if (!snmp_strcat(buf, buf_len, out_len, allow_realloc, str)) { return 0; } } netsnmp_sprint_realloc_objid_tree(buf, buf_len, out_len, allow_realloc, &buf_overflow, (oid *) (var->val.objid), var->val_len / sizeof(oid)); if (buf_overflow) { return 0; } if (units) { return (snmp_strcat (buf, buf_len, out_len, allow_realloc, (const u_char *) " ") && snmp_strcat(buf, buf_len, out_len, allow_realloc, (const u_char *) units)); } return 1; } /** * Prints a timetick variable into a buffer. * * If allow_realloc is true the buffer will be (re)allocated to fit in the * needed size. (Note: *buf may change due to this.) * * @param buf Address of the buffer to print to. * @param buf_len Address to an integer containing the size of buf. * @param out_len Incremented by the number of characters printed. * @param allow_realloc if not zero reallocate the buffer to fit the * needed size. * @param var The variable to encode. * @param enums The enumeration ff this variable is enumerated. may be NULL. * @param hint Contents of the DISPLAY-HINT clause of the MIB. * See RFC 1903 Section 3.1 for details. may be NULL. * @param units Contents of the UNITS clause of the MIB. may be NULL. * * @return 1 on success, or 0 on failure (out of memory, or buffer to * small when not allowed to realloc.) */ int sprint_realloc_timeticks(u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, const netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { char timebuf[40]; if (var->type != ASN_TIMETICKS) { if (!netsnmp_ds_get_boolean( NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICKE_PRINT)) { u_char str[] = "Wrong Type (should be Timeticks): "; if (!snmp_strcat(buf, buf_len, out_len, allow_realloc, str)) return 0; } return sprint_realloc_by_type(buf, buf_len, out_len, allow_realloc, var, NULL, NULL, NULL); } if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_NUMERIC_TIMETICKS)) { char str[32]; sprintf(str, "%lu", *(u_long *) var->val.integer); if (!snmp_strcat (buf, buf_len, out_len, allow_realloc, (const u_char *) str)) { return 0; } return 1; } if (!netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT)) { char str[32]; sprintf(str, "Timeticks: (%lu) ", *(u_long *) var->val.integer); if (!snmp_strcat (buf, buf_len, out_len, allow_realloc, (const u_char *) str)) { return 0; } } uptimeString(*(u_long *) (var->val.integer), timebuf, sizeof(timebuf)); if (!snmp_strcat (buf, buf_len, out_len, allow_realloc, (const u_char *) timebuf)) { return 0; } if (units) { return (snmp_strcat (buf, buf_len, out_len, allow_realloc, (const u_char *) " ") && snmp_strcat(buf, buf_len, out_len, allow_realloc, (const u_char *) units)); } return 1; } /** * Prints an integer according to the hint into a buffer. * * If allow_realloc is true the buffer will be (re)allocated to fit in the * needed size. (Note: *buf may change due to this.) * * @param buf Address of the buffer to print to. * @param buf_len Address to an integer containing the size of buf. * @param out_len Incremented by the number of characters printed. * @param allow_realloc if not zero reallocate the buffer to fit the * needed size. * @param val The variable to encode. * @param decimaltype 'd' or 'u' depending on integer type * @param hint Contents of the DISPLAY-HINT clause of the MIB. * See RFC 1903 Section 3.1 for details. may _NOT_ be NULL. * @param units Contents of the UNITS clause of the MIB. may be NULL. * * @return 1 on success, or 0 on failure (out of memory, or buffer to * small when not allowed to realloc.) */ int sprint_realloc_hinted_integer(u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, long val, const char decimaltype, const char *hint, const char *units) { char fmt[10] = "%l@", tmp[256]; int shift = 0, len, negative = 0; if (hint[0] == 'd') { /* * We might *actually* want a 'u' here. */ if (hint[1] == '-') shift = atoi(hint + 2); fmt[2] = decimaltype; if (val < 0) { negative = 1; val = -val; } } else { /* * DISPLAY-HINT character is 'b', 'o', or 'x'. */ fmt[2] = hint[0]; } if (hint[0] == 'b') { unsigned long int bit = 0x80000000LU; char *bp = tmp; while (bit) { *bp++ = val & bit ? '1' : '0'; bit >>= 1; } *bp = 0; } else sprintf(tmp, fmt, val); if (shift != 0) { len = strlen(tmp); if (shift <= len) { tmp[len + 1] = 0; while (shift--) { tmp[len] = tmp[len - 1]; len--; } tmp[len] = '.'; } else { tmp[shift + 1] = 0; while (shift) { if (len-- > 0) { tmp[shift] = tmp[len]; } else { tmp[shift] = '0'; } shift--; } tmp[0] = '.'; } } if (negative) { len = strlen(tmp)+1; while (len) { tmp[len] = tmp[len-1]; len--; } tmp[0] = '-'; } return snmp_strcat(buf, buf_len, out_len, allow_realloc, (u_char *)tmp); } /** * Prints an integer into a buffer. * * If allow_realloc is true the buffer will be (re)allocated to fit in the * needed size. (Note: *buf may change due to this.) * * @param buf Address of the buffer to print to. * @param buf_len Address to an integer containing the size of buf. * @param out_len Incremented by the number of characters printed. * @param allow_realloc if not zero reallocate the buffer to fit the * needed size. * @param var The variable to encode. * @param enums The enumeration ff this variable is enumerated. may be NULL. * @param hint Contents of the DISPLAY-HINT clause of the MIB. * See RFC 1903 Section 3.1 for details. may be NULL. * @param units Contents of the UNITS clause of the MIB. may be NULL. * * @return 1 on success, or 0 on failure (out of memory, or buffer to * small when not allowed to realloc.) */ int sprint_realloc_integer(u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, const netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { char *enum_string = NULL; if (var->type != ASN_INTEGER) { if (!netsnmp_ds_get_boolean( NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICKE_PRINT)) { u_char str[] = "Wrong Type (should be INTEGER): "; if (!snmp_strcat(buf, buf_len, out_len, allow_realloc, str)) return 0; } return sprint_realloc_by_type(buf, buf_len, out_len, allow_realloc, var, NULL, NULL, NULL); } for (; enums; enums = enums->next) { if (enums->value == *var->val.integer) { enum_string = enums->label; break; } } if (!netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT)) { if (!snmp_strcat(buf, buf_len, out_len, allow_realloc, (const u_char *) "INTEGER: ")) { return 0; } } if (enum_string == NULL || netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PRINT_NUMERIC_ENUM)) { if (hint) { if (!(sprint_realloc_hinted_integer(buf, buf_len, out_len, allow_realloc, *var->val.integer, 'd', hint, units))) { return 0; } } else { char str[32]; sprintf(str, "%ld", *var->val.integer); if (!snmp_strcat (buf, buf_len, out_len, allow_realloc, (const u_char *) str)) { return 0; } } } else if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT)) { if (!snmp_strcat (buf, buf_len, out_len, allow_realloc, (const u_char *) enum_string)) { return 0; } } else { char str[32]; sprintf(str, "(%ld)", *var->val.integer); if (!snmp_strcat (buf, buf_len, out_len, allow_realloc, (const u_char *) enum_string)) { return 0; } if (!snmp_strcat (buf, buf_len, out_len, allow_realloc, (const u_char *) str)) { return 0; } } if (units) { return (snmp_strcat (buf, buf_len, out_len, allow_realloc, (const u_char *) " ") && snmp_strcat(buf, buf_len, out_len, allow_realloc, (const u_char *) units)); } return 1; } /** * Prints an unsigned integer into a buffer. * * If allow_realloc is true the buffer will be (re)allocated to fit in the * needed size. (Note: *buf may change due to this.) * * @param buf Address of the buffer to print to. * @param buf_len Address to an integer containing the size of buf. * @param out_len Incremented by the number of characters printed. * @param allow_realloc if not zero reallocate the buffer to fit the * needed size. * @param var The variable to encode. * @param enums The enumeration ff this variable is enumerated. may be NULL. * @param hint Contents of the DISPLAY-HINT clause of the MIB. * See RFC 1903 Section 3.1 for details. may be NULL. * @param units Contents of the UNITS clause of the MIB. may be NULL. * * @return 1 on success, or 0 on failure (out of memory, or buffer to * small when not allowed to realloc.) */ int sprint_realloc_uinteger(u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, const netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { char *enum_string = NULL; if (var->type != ASN_UINTEGER) { if (!netsnmp_ds_get_boolean( NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICKE_PRINT)) { u_char str[] = "Wrong Type (should be UInteger32): "; if (!snmp_strcat(buf, buf_len, out_len, allow_realloc, str)) return 0; } return sprint_realloc_by_type(buf, buf_len, out_len, allow_realloc, var, NULL, NULL, NULL); } for (; enums; enums = enums->next) { if (enums->value == *var->val.integer) { enum_string = enums->label; break; } } if (enum_string == NULL || netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PRINT_NUMERIC_ENUM)) { if (hint) { if (!(sprint_realloc_hinted_integer(buf, buf_len, out_len, allow_realloc, *var->val.integer, 'u', hint, units))) { return 0; } } else { char str[32]; sprintf(str, "%lu", *var->val.integer); if (!snmp_strcat (buf, buf_len, out_len, allow_realloc, (const u_char *) str)) { return 0; } } } else if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT)) { if (!snmp_strcat (buf, buf_len, out_len, allow_realloc, (const u_char *) enum_string)) { return 0; } } else { char str[32]; sprintf(str, "(%lu)", *var->val.integer); if (!snmp_strcat (buf, buf_len, out_len, allow_realloc, (const u_char *) enum_string)) { return 0; } if (!snmp_strcat (buf, buf_len, out_len, allow_realloc, (const u_char *) str)) { return 0; } } if (units) { return (snmp_strcat (buf, buf_len, out_len, allow_realloc, (const u_char *) " ") && snmp_strcat(buf, buf_len, out_len, allow_realloc, (const u_char *) units)); } return 1; } /** * Prints a gauge value into a buffer. * * If allow_realloc is true the buffer will be (re)allocated to fit in the * needed size. (Note: *buf may change due to this.) * * @param buf Address of the buffer to print to. * @param buf_len Address to an integer containing the size of buf. * @param out_len Incremented by the number of characters printed. * @param allow_realloc if not zero reallocate the buffer to fit the * needed size. * @param var The variable to encode. * @param enums The enumeration ff this variable is enumerated. may be NULL. * @param hint Contents of the DISPLAY-HINT clause of the MIB. * See RFC 1903 Section 3.1 for details. may be NULL. * @param units Contents of the UNITS clause of the MIB. may be NULL. * * @return 1 on success, or 0 on failure (out of memory, or buffer to * small when not allowed to realloc.) */ int sprint_realloc_gauge(u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, const netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { char tmp[32]; if (var->type != ASN_GAUGE) { if (!netsnmp_ds_get_boolean( NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICKE_PRINT)) { u_char str[] = "Wrong Type (should be Gauge32 or Unsigned32): "; if (!snmp_strcat(buf, buf_len, out_len, allow_realloc, str)) return 0; } return sprint_realloc_by_type(buf, buf_len, out_len, allow_realloc, var, NULL, NULL, NULL); } if (!netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT)) { u_char str[] = "Gauge32: "; if (!snmp_strcat(buf, buf_len, out_len, allow_realloc, str)) { return 0; } } if (hint) { if (!sprint_realloc_hinted_integer(buf, buf_len, out_len, allow_realloc, *var->val.integer, 'u', hint, units)) { return 0; } } else { sprintf(tmp, "%u", (unsigned int)(*var->val.integer & 0xffffffff)); if (!snmp_strcat (buf, buf_len, out_len, allow_realloc, (const u_char *) tmp)) { return 0; } } if (units) { return (snmp_strcat (buf, buf_len, out_len, allow_realloc, (const u_char *) " ") && snmp_strcat(buf, buf_len, out_len, allow_realloc, (const u_char *) units)); } return 1; } /** * Prints a counter value into a buffer. * * If allow_realloc is true the buffer will be (re)allocated to fit in the * needed size. (Note: *buf may change due to this.) * * @param buf Address of the buffer to print to. * @param buf_len Address to an integer containing the size of buf. * @param out_len Incremented by the number of characters printed. * @param allow_realloc if not zero reallocate the buffer to fit the * needed size. * @param var The variable to encode. * @param enums The enumeration ff this variable is enumerated. may be NULL. * @param hint Contents of the DISPLAY-HINT clause of the MIB. * See RFC 1903 Section 3.1 for details. may be NULL. * @param units Contents of the UNITS clause of the MIB. may be NULL. * * @return 1 on success, or 0 on failure (out of memory, or buffer to * small when not allowed to realloc.) */ int sprint_realloc_counter(u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, const netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { char tmp[32]; if (var->type != ASN_COUNTER) { if (!netsnmp_ds_get_boolean( NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICKE_PRINT)) { u_char str[] = "Wrong Type (should be Counter32): "; if (!snmp_strcat(buf, buf_len, out_len, allow_realloc, str)) return 0; } return sprint_realloc_by_type(buf, buf_len, out_len, allow_realloc, var, NULL, NULL, NULL); } if (!netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT)) { u_char str[] = "Counter32: "; if (!snmp_strcat(buf, buf_len, out_len, allow_realloc, str)) { return 0; } } sprintf(tmp, "%u", (unsigned int)(*var->val.integer & 0xffffffff)); if (!snmp_strcat (buf, buf_len, out_len, allow_realloc, (const u_char *) tmp)) { return 0; } if (units) { return (snmp_strcat (buf, buf_len, out_len, allow_realloc, (const u_char *) " ") && snmp_strcat(buf, buf_len, out_len, allow_realloc, (const u_char *) units)); } return 1; } /** * Prints a network address into a buffer. * * If allow_realloc is true the buffer will be (re)allocated to fit in the * needed size. (Note: *buf may change due to this.) * * @param buf Address of the buffer to print to. * @param buf_len Address to an integer containing the size of buf. * @param out_len Incremented by the number of characters printed. * @param allow_realloc if not zero reallocate the buffer to fit the * needed size. * @param var The variable to encode. * @param enums The enumeration ff this variable is enumerated. may be NULL. * @param hint Contents of the DISPLAY-HINT clause of the MIB. * See RFC 1903 Section 3.1 for details. may be NULL. * @param units Contents of the UNITS clause of the MIB. may be NULL. * * @return 1 on success, or 0 on failure (out of memory, or buffer to * small when not allowed to realloc.) */ int sprint_realloc_networkaddress(u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, const netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { size_t i; if (var->type != ASN_IPADDRESS) { if (!netsnmp_ds_get_boolean( NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICKE_PRINT)) { u_char str[] = "Wrong Type (should be NetworkAddress): "; if (!snmp_strcat(buf, buf_len, out_len, allow_realloc, str)) return 0; } return sprint_realloc_by_type(buf, buf_len, out_len, allow_realloc, var, NULL, NULL, NULL); } if (!netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT)) { u_char str[] = "Network Address: "; if (!snmp_strcat(buf, buf_len, out_len, allow_realloc, str)) { return 0; } } while ((*out_len + (var->val_len * 3) + 2) >= *buf_len) { if (!(allow_realloc && snmp_realloc(buf, buf_len))) { return 0; } } for (i = 0; i < var->val_len; i++) { sprintf((char *) (*buf + *out_len), "%02X", var->val.string[i]); *out_len += 2; if (i < var->val_len - 1) { *(*buf + *out_len) = ':'; (*out_len)++; } } return 1; } /** * Prints an ip-address into a buffer. * * If allow_realloc is true the buffer will be (re)allocated to fit in the * needed size. (Note: *buf may change due to this.) * * @param buf Address of the buffer to print to. * @param buf_len Address to an integer containing the size of buf. * @param out_len Incremented by the number of characters printed. * @param allow_realloc if not zero reallocate the buffer to fit the * needed size. * @param var The variable to encode. * @param enums The enumeration ff this variable is enumerated. may be NULL. * @param hint Contents of the DISPLAY-HINT clause of the MIB. * See RFC 1903 Section 3.1 for details. may be NULL. * @param units Contents of the UNITS clause of the MIB. may be NULL. * * @return 1 on success, or 0 on failure (out of memory, or buffer to * small when not allowed to realloc.) */ int sprint_realloc_ipaddress(u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, const netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { u_char *ip = var->val.string; if (var->type != ASN_IPADDRESS) { if (!netsnmp_ds_get_boolean( NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICKE_PRINT)) { u_char str[] = "Wrong Type (should be IpAddress): "; if (!snmp_strcat(buf, buf_len, out_len, allow_realloc, str)) return 0; } return sprint_realloc_by_type(buf, buf_len, out_len, allow_realloc, var, NULL, NULL, NULL); } if (!netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT)) { u_char str[] = "IpAddress: "; if (!snmp_strcat(buf, buf_len, out_len, allow_realloc, str)) { return 0; } } while ((*out_len + 17) >= *buf_len) { if (!(allow_realloc && snmp_realloc(buf, buf_len))) { return 0; } } if (ip) sprintf((char *) (*buf + *out_len), "%d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]); *out_len += strlen((char *) (*buf + *out_len)); return 1; } /** * Prints a null value into a buffer. * * If allow_realloc is true the buffer will be (re)allocated to fit in the * needed size. (Note: *buf may change due to this.) * * @param buf Address of the buffer to print to. * @param buf_len Address to an integer containing the size of buf. * @param out_len Incremented by the number of characters printed. * @param allow_realloc if not zero reallocate the buffer to fit the * needed size. * @param var The variable to encode. * @param enums The enumeration ff this variable is enumerated. may be NULL. * @param hint Contents of the DISPLAY-HINT clause of the MIB. * See RFC 1903 Section 3.1 for details. may be NULL. * @param units Contents of the UNITS clause of the MIB. may be NULL. * * @return 1 on success, or 0 on failure (out of memory, or buffer to * small when not allowed to realloc.) */ int sprint_realloc_null(u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, const netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { u_char str[] = "NULL"; if (var->type != ASN_NULL) { if (!netsnmp_ds_get_boolean( NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICKE_PRINT)) { u_char str[] = "Wrong Type (should be NULL): "; if (!snmp_strcat(buf, buf_len, out_len, allow_realloc, str)) return 0; } return sprint_realloc_by_type(buf, buf_len, out_len, allow_realloc, var, NULL, NULL, NULL); } return snmp_strcat(buf, buf_len, out_len, allow_realloc, str); } /** * Prints a bit string into a buffer. * * If allow_realloc is true the buffer will be (re)allocated to fit in the * needed size. (Note: *buf may change due to this.) * * @param buf Address of the buffer to print to. * @param buf_len Address to an integer containing the size of buf. * @param out_len Incremented by the number of characters printed. * @param allow_realloc if not zero reallocate the buffer to fit the * needed size. * @param var The variable to encode. * @param enums The enumeration ff this variable is enumerated. may be NULL. * @param hint Contents of the DISPLAY-HINT clause of the MIB. * See RFC 1903 Section 3.1 for details. may be NULL. * @param units Contents of the UNITS clause of the MIB. may be NULL. * * @return 1 on success, or 0 on failure (out of memory, or buffer to * small when not allowed to realloc.) */ int sprint_realloc_bitstring(u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, const netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { int len, bit; u_char *cp; char *enum_string; if (var->type != ASN_BIT_STR && var->type != ASN_OCTET_STR) { if (!netsnmp_ds_get_boolean( NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICKE_PRINT)) { u_char str[] = "Wrong Type (should be BITS): "; if (!snmp_strcat(buf, buf_len, out_len, allow_realloc, str)) return 0; } return sprint_realloc_by_type(buf, buf_len, out_len, allow_realloc, var, NULL, NULL, NULL); } if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT)) { u_char str[] = "\""; if (!snmp_strcat(buf, buf_len, out_len, allow_realloc, str)) { return 0; } } else { u_char str[] = "BITS: "; if (!snmp_strcat(buf, buf_len, out_len, allow_realloc, str)) { return 0; } } if (!sprint_realloc_hexstring(buf, buf_len, out_len, allow_realloc, var->val.bitstring, var->val_len)) { return 0; } if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT)) { u_char str[] = "\""; if (!snmp_strcat(buf, buf_len, out_len, allow_realloc, str)) { return 0; } } else { cp = var->val.bitstring; for (len = 0; len < (int) var->val_len; len++) { for (bit = 0; bit < 8; bit++) { if (*cp & (0x80 >> bit)) { enum_string = NULL; for (; enums; enums = enums->next) { if (enums->value == (len * 8) + bit) { enum_string = enums->label; break; } } if (enum_string == NULL || netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PRINT_NUMERIC_ENUM)) { char str[32]; sprintf(str, "%d ", (len * 8) + bit); if (!snmp_strcat (buf, buf_len, out_len, allow_realloc, (const u_char *) str)) { return 0; } } else { char str[32]; sprintf(str, "(%d) ", (len * 8) + bit); if (!snmp_strcat (buf, buf_len, out_len, allow_realloc, (const u_char *) enum_string)) { return 0; } if (!snmp_strcat (buf, buf_len, out_len, allow_realloc, (const u_char *) str)) { return 0; } } } } cp++; } } return 1; } int sprint_realloc_nsapaddress(u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, const netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { if (var->type != ASN_NSAP) { if (!netsnmp_ds_get_boolean( NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICKE_PRINT)) { u_char str[] = "Wrong Type (should be NsapAddress): "; if (!snmp_strcat(buf, buf_len, out_len, allow_realloc, str)) return 0; } return sprint_realloc_by_type(buf, buf_len, out_len, allow_realloc, var, NULL, NULL, NULL); } if (!netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT)) { u_char str[] = "NsapAddress: "; if (!snmp_strcat(buf, buf_len, out_len, allow_realloc, str)) { return 0; } } return sprint_realloc_hexstring(buf, buf_len, out_len, allow_realloc, var->val.string, var->val_len); } /** * Fallback routine for a bad type, prints "Variable has bad type" into a buffer. * * If allow_realloc is true the buffer will be (re)allocated to fit in the * needed size. (Note: *buf may change due to this.) * * @param buf Address of the buffer to print to. * @param buf_len Address to an integer containing the size of buf. * @param out_len Incremented by the number of characters printed. * @param allow_realloc if not zero reallocate the buffer to fit the * needed size. * @param var The variable to encode. * @param enums The enumeration ff this variable is enumerated. may be NULL. * @param hint Contents of the DISPLAY-HINT clause of the MIB. * See RFC 1903 Section 3.1 for details. may be NULL. * @param units Contents of the UNITS clause of the MIB. may be NULL. * * @return 1 on success, or 0 on failure (out of memory, or buffer to * small when not allowed to realloc.) */ int sprint_realloc_badtype(u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, const netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { u_char str[] = "Variable has bad type"; return snmp_strcat(buf, buf_len, out_len, allow_realloc, str); } /** * Universal print routine, prints a variable into a buffer according to the variable * type. * * If allow_realloc is true the buffer will be (re)allocated to fit in the * needed size. (Note: *buf may change due to this.) * * @param buf Address of the buffer to print to. * @param buf_len Address to an integer containing the size of buf. * @param out_len Incremented by the number of characters printed. * @param allow_realloc if not zero reallocate the buffer to fit the * needed size. * @param var The variable to encode. * @param enums The enumeration ff this variable is enumerated. may be NULL. * @param hint Contents of the DISPLAY-HINT clause of the MIB. * See RFC 1903 Section 3.1 for details. may be NULL. * @param units Contents of the UNITS clause of the MIB. may be NULL. * * @return 1 on success, or 0 on failure (out of memory, or buffer to * small when not allowed to realloc.) */ int sprint_realloc_by_type(u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, const netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { DEBUGMSGTL(("output", "sprint_by_type, type %d\n", var->type)); switch (var->type) { case ASN_INTEGER: return sprint_realloc_integer(buf, buf_len, out_len, allow_realloc, var, enums, hint, units); case ASN_OCTET_STR: return sprint_realloc_octet_string(buf, buf_len, out_len, allow_realloc, var, enums, hint, units); case ASN_BIT_STR: return sprint_realloc_bitstring(buf, buf_len, out_len, allow_realloc, var, enums, hint, units); case ASN_OPAQUE: return sprint_realloc_opaque(buf, buf_len, out_len, allow_realloc, var, enums, hint, units); case ASN_OBJECT_ID: return sprint_realloc_object_identifier(buf, buf_len, out_len, allow_realloc, var, enums, hint, units); case ASN_TIMETICKS: return sprint_realloc_timeticks(buf, buf_len, out_len, allow_realloc, var, enums, hint, units); case ASN_GAUGE: return sprint_realloc_gauge(buf, buf_len, out_len, allow_realloc, var, enums, hint, units); case ASN_COUNTER: return sprint_realloc_counter(buf, buf_len, out_len, allow_realloc, var, enums, hint, units); case ASN_IPADDRESS: return sprint_realloc_ipaddress(buf, buf_len, out_len, allow_realloc, var, enums, hint, units); case ASN_NULL: return sprint_realloc_null(buf, buf_len, out_len, allow_realloc, var, enums, hint, units); case ASN_UINTEGER: return sprint_realloc_uinteger(buf, buf_len, out_len, allow_realloc, var, enums, hint, units); case ASN_COUNTER64: #ifdef NETSNMP_WITH_OPAQUE_SPECIAL_TYPES case ASN_OPAQUE_U64: case ASN_OPAQUE_I64: case ASN_OPAQUE_COUNTER64: #endif /* NETSNMP_WITH_OPAQUE_SPECIAL_TYPES */ return sprint_realloc_counter64(buf, buf_len, out_len, allow_realloc, var, enums, hint, units); #ifdef NETSNMP_WITH_OPAQUE_SPECIAL_TYPES case ASN_OPAQUE_FLOAT: return sprint_realloc_float(buf, buf_len, out_len, allow_realloc, var, enums, hint, units); case ASN_OPAQUE_DOUBLE: return sprint_realloc_double(buf, buf_len, out_len, allow_realloc, var, enums, hint, units); #endif /* NETSNMP_WITH_OPAQUE_SPECIAL_TYPES */ default: DEBUGMSGTL(("sprint_by_type", "bad type: %d\n", var->type)); return sprint_realloc_badtype(buf, buf_len, out_len, allow_realloc, var, enums, hint, units); } } /** * Generates a prinf format string. * * The original format string is combined with the optional * NETSNMP_DS_LIB_OUTPUT_PRECISION string (the -Op parameter). * * Example: * If the original format string is "%f", and the NETSNMP_DS_LIB_OUTPUT_PRECISION * is "5.2", the returned format string will be "%5.2f". * * The PRECISION string is inserted after the '%' of the original format string. * To prevent buffer overflow if NETSNMP_DS_LIB_OUTPUT_PRECISION is set to an * illegal size (e.g. with -Op 10000) snprintf should be used to prevent buffer * overflow. * * @param printf_format_default The format string used by the original printf. * * @return The address of of the new allocated format string (which must be freed * if no longer used), or NULL if any error (malloc). */ char * make_printf_format_string(const char *printf_format_default) { const char *cp_printf_format_default; const char *printf_precision; const char *cp_printf_precision; char *printf_format_string; char *cp_out; char c; printf_precision = netsnmp_ds_get_string(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OUTPUT_PRECISION); if (!printf_precision) { printf_precision = ""; } /* reserve new format string buffer */ printf_format_string = (char *) malloc(strlen(printf_format_default)+strlen(printf_precision)+1); if (!printf_format_string) { DEBUGMSGTL(("make_printf_format_string", "malloc failed\n")); return NULL; } /* copy default format string, including the '%' */ cp_out = printf_format_string; cp_printf_format_default = printf_format_default; while((c = *cp_printf_format_default) != '\0') { *cp_out++ = c; cp_printf_format_default++; if (c == '%') break; } /* insert the precision string */ cp_printf_precision = printf_precision; while ((c = *cp_printf_precision++) != '\0') { *cp_out++ = c; } /* copy the remaining default format string, including the terminating '\0' */ strcpy(cp_out, cp_printf_format_default); DEBUGMSGTL(("make_printf_format_string", "\"%s\"+\"%s\"->\"%s\"\n", printf_format_default, printf_precision, printf_format_string)); return printf_format_string; } #ifndef NETSNMP_DISABLE_MIB_LOADING /** * Retrieves the tree head. * * @return the tree head. */ struct tree * get_tree_head(void) { return (tree_head); } static char *confmibdir = NULL; static char *confmibs = NULL; static void handle_mibdirs_conf(const char *token, char *line) { char *ctmp; if (confmibdir) { if ((*line == '+') || (*line == '-')) { ctmp = (char *) malloc(strlen(confmibdir) + strlen(line) + 2); if (!ctmp) { DEBUGMSGTL(("read_config:initmib", "mibdir conf malloc failed")); return; } if(*line++ == '+') sprintf(ctmp, "%s%c%s", confmibdir, ENV_SEPARATOR_CHAR, line); else sprintf(ctmp, "%s%c%s", line, ENV_SEPARATOR_CHAR, confmibdir); } else { ctmp = strdup(line); if (!ctmp) { DEBUGMSGTL(("read_config:initmib", "mibs conf malloc failed")); return; } } SNMP_FREE(confmibdir); } else { ctmp = strdup(line); if (!ctmp) { DEBUGMSGTL(("read_config:initmib", "mibs conf malloc failed")); return; } } confmibdir = ctmp; DEBUGMSGTL(("read_config:initmib", "using mibdirs: %s\n", confmibdir)); } static void handle_mibs_conf(const char *token, char *line) { char *ctmp; if (confmibs) { if ((*line == '+') || (*line == '-')) { ctmp = (char *) malloc(strlen(confmibs) + strlen(line) + 2); if (!ctmp) { DEBUGMSGTL(("read_config:initmib", "mibs conf malloc failed")); return; } if(*line++ == '+') sprintf(ctmp, "%s%c%s", confmibs, ENV_SEPARATOR_CHAR, line); else sprintf(ctmp, "%s%c%s", line, ENV_SEPARATOR_CHAR, confmibdir); } else { ctmp = strdup(line); if (!ctmp) { DEBUGMSGTL(("read_config:initmib", "mibs conf malloc failed")); return; } } SNMP_FREE(confmibs); } else { ctmp = strdup(line); if (!ctmp) { DEBUGMSGTL(("read_config:initmib", "mibs conf malloc failed")); return; } } confmibs = ctmp; DEBUGMSGTL(("read_config:initmib", "using mibs: %s\n", confmibs)); } static void handle_mibfile_conf(const char *token, char *line) { DEBUGMSGTL(("read_config:initmib", "reading mibfile: %s\n", line)); read_mib(line); } #endif static void handle_print_numeric(const char *token, char *line) { const char *value; char *st; value = strtok_r(line, " \t\n", &st); if (value && ( (strcasecmp(value, "yes") == 0) || (strcasecmp(value, "true") == 0) || (*value == '1') )) { netsnmp_ds_set_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OID_OUTPUT_FORMAT, NETSNMP_OID_OUTPUT_NUMERIC); } } char * snmp_out_options(char *options, int argc, char *const *argv) { while (*options) { switch (*options++) { case '0': netsnmp_ds_toggle_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_2DIGIT_HEX_OUTPUT); break; case 'a': netsnmp_ds_set_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_STRING_OUTPUT_FORMAT, NETSNMP_STRING_OUTPUT_ASCII); break; case 'b': netsnmp_ds_toggle_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_DONT_BREAKDOWN_OIDS); break; case 'e': netsnmp_ds_toggle_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PRINT_NUMERIC_ENUM); break; case 'E': netsnmp_ds_toggle_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_ESCAPE_QUOTES); break; case 'f': netsnmp_ds_set_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OID_OUTPUT_FORMAT, NETSNMP_OID_OUTPUT_FULL); break; case 'n': netsnmp_ds_set_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OID_OUTPUT_FORMAT, NETSNMP_OID_OUTPUT_NUMERIC); break; case 'p': /* What if argc/argv are null ? */ if (!*(options)) { options = argv[optind++]; } netsnmp_ds_set_string(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OUTPUT_PRECISION, options); return NULL; /* -Op... is a standalone option, so we're done here */ case 'q': netsnmp_ds_toggle_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT); break; case 'Q': netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICKE_PRINT, 1); netsnmp_ds_toggle_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT); break; case 's': netsnmp_ds_set_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OID_OUTPUT_FORMAT, NETSNMP_OID_OUTPUT_SUFFIX); break; case 'S': netsnmp_ds_set_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OID_OUTPUT_FORMAT, NETSNMP_OID_OUTPUT_MODULE); break; case 't': netsnmp_ds_toggle_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_NUMERIC_TIMETICKS); break; case 'T': netsnmp_ds_toggle_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PRINT_HEX_TEXT); break; case 'u': netsnmp_ds_set_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OID_OUTPUT_FORMAT, NETSNMP_OID_OUTPUT_UCD); break; case 'U': netsnmp_ds_toggle_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_DONT_PRINT_UNITS); break; case 'v': netsnmp_ds_toggle_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PRINT_BARE_VALUE); break; case 'x': netsnmp_ds_set_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_STRING_OUTPUT_FORMAT, NETSNMP_STRING_OUTPUT_HEX); break; case 'X': netsnmp_ds_toggle_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_EXTENDED_INDEX); break; default: return options - 1; } } return NULL; } char * snmp_out_toggle_options(char *options) { return snmp_out_options( options, 0, NULL ); } void snmp_out_toggle_options_usage(const char *lead, FILE * outf) { fprintf(outf, "%s0: print leading 0 for single-digit hex characters\n", lead); fprintf(outf, "%sa: print all strings in ascii format\n", lead); fprintf(outf, "%sb: do not break OID indexes down\n", lead); fprintf(outf, "%se: print enums numerically\n", lead); fprintf(outf, "%sE: escape quotes in string indices\n", lead); fprintf(outf, "%sf: print full OIDs on output\n", lead); fprintf(outf, "%sn: print OIDs numerically\n", lead); fprintf(outf, "%sp PRECISION: display floating point values with specified PRECISION (printf format string)\n", lead); fprintf(outf, "%sq: quick print for easier parsing\n", lead); fprintf(outf, "%sQ: quick print with equal-signs\n", lead); /* @@JDW */ fprintf(outf, "%ss: print only last symbolic element of OID\n", lead); fprintf(outf, "%sS: print MIB module-id plus last element\n", lead); fprintf(outf, "%st: print timeticks unparsed as numeric integers\n", lead); fprintf(outf, "%sT: print human-readable text along with hex strings\n", lead); fprintf(outf, "%su: print OIDs using UCD-style prefix suppression\n", lead); fprintf(outf, "%sU: don't print units\n", lead); fprintf(outf, "%sv: print values only (not OID = value)\n", lead); fprintf(outf, "%sx: print all strings in hex format\n", lead); fprintf(outf, "%sX: extended index format\n", lead); } char * snmp_in_options(char *optarg, int argc, char *const *argv) { char *cp; for (cp = optarg; *cp; cp++) { switch (*cp) { case 'b': netsnmp_ds_toggle_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_REGEX_ACCESS); break; case 'R': netsnmp_ds_toggle_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_RANDOM_ACCESS); break; case 'r': netsnmp_ds_toggle_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_DONT_CHECK_RANGE); break; case 'h': netsnmp_ds_toggle_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_NO_DISPLAY_HINT); break; case 'u': netsnmp_ds_toggle_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_READ_UCD_STYLE_OID); break; case 's': /* What if argc/argv are null ? */ if (!*(++cp)) cp = argv[optind++]; netsnmp_ds_set_string(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OIDSUFFIX, cp); return NULL; /* -Is... is a standalone option, so we're done here */ case 'S': /* What if argc/argv are null ? */ if (!*(++cp)) cp = argv[optind++]; netsnmp_ds_set_string(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OIDPREFIX, cp); return NULL; /* -IS... is a standalone option, so we're done here */ default: /* * Here? Or in snmp_parse_args? snmp_log(LOG_ERR, "Unknown input option passed to -I: %c.\n", *cp); */ return cp; } } return NULL; } char * snmp_in_toggle_options(char *options) { return snmp_in_options( options, 0, NULL ); } /** * Prints out a help usage for the in* toggle options. * * @param lead The lead to print for every line. * @param outf The file descriptor to write to. * */ void snmp_in_toggle_options_usage(const char *lead, FILE * outf) { fprintf(outf, "%sb: do best/regex matching to find a MIB node\n", lead); fprintf(outf, "%sh: don't apply DISPLAY-HINTs\n", lead); fprintf(outf, "%sr: do not check values for range/type legality\n", lead); fprintf(outf, "%sR: do random access to OID labels\n", lead); fprintf(outf, "%su: top-level OIDs must have '.' prefix (UCD-style)\n", lead); fprintf(outf, "%ss SUFFIX: Append all textual OIDs with SUFFIX before parsing\n", lead); fprintf(outf, "%sS PREFIX: Prepend all textual OIDs with PREFIX before parsing\n", lead); } /*** * */ void register_mib_handlers(void) { #ifndef NETSNMP_DISABLE_MIB_LOADING register_prenetsnmp_mib_handler("snmp", "mibdirs", handle_mibdirs_conf, NULL, "[mib-dirs|+mib-dirs|-mib-dirs]"); register_prenetsnmp_mib_handler("snmp", "mibs", handle_mibs_conf, NULL, "[mib-tokens|+mib-tokens]"); register_config_handler("snmp", "mibfile", handle_mibfile_conf, NULL, "mibfile-to-read"); /* * register the snmp.conf configuration handlers for default * parsing behaviour */ netsnmp_ds_register_premib(ASN_BOOLEAN, "snmp", "showMibErrors", NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_ERRORS); netsnmp_ds_register_premib(ASN_BOOLEAN, "snmp", "commentToEOL", /* Describes actual behaviour */ NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_COMMENT_TERM); netsnmp_ds_register_premib(ASN_BOOLEAN, "snmp", "strictCommentTerm", /* Backward compatibility */ NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_COMMENT_TERM); netsnmp_ds_register_premib(ASN_BOOLEAN, "snmp", "mibAllowUnderline", NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_PARSE_LABEL); netsnmp_ds_register_premib(ASN_INTEGER, "snmp", "mibWarningLevel", NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_WARNINGS); netsnmp_ds_register_premib(ASN_BOOLEAN, "snmp", "mibReplaceWithLatest", NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIB_REPLACE); #endif netsnmp_ds_register_premib(ASN_BOOLEAN, "snmp", "printNumericEnums", NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PRINT_NUMERIC_ENUM); register_prenetsnmp_mib_handler("snmp", "printNumericOids", handle_print_numeric, NULL, "(1|yes|true|0|no|false)"); netsnmp_ds_register_premib(ASN_BOOLEAN, "snmp", "escapeQuotes", NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_ESCAPE_QUOTES); netsnmp_ds_register_premib(ASN_BOOLEAN, "snmp", "dontBreakdownOids", NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_DONT_BREAKDOWN_OIDS); netsnmp_ds_register_premib(ASN_BOOLEAN, "snmp", "quickPrinting", NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT); netsnmp_ds_register_premib(ASN_BOOLEAN, "snmp", "numericTimeticks", NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_NUMERIC_TIMETICKS); netsnmp_ds_register_premib(ASN_INTEGER, "snmp", "oidOutputFormat", NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OID_OUTPUT_FORMAT); netsnmp_ds_register_premib(ASN_INTEGER, "snmp", "suffixPrinting", NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OID_OUTPUT_FORMAT); netsnmp_ds_register_premib(ASN_BOOLEAN, "snmp", "extendedIndex", NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_EXTENDED_INDEX); netsnmp_ds_register_premib(ASN_BOOLEAN, "snmp", "printHexText", NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PRINT_HEX_TEXT); netsnmp_ds_register_premib(ASN_BOOLEAN, "snmp", "printValueOnly", NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PRINT_BARE_VALUE); netsnmp_ds_register_premib(ASN_BOOLEAN, "snmp", "dontPrintUnits", NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_DONT_PRINT_UNITS); netsnmp_ds_register_premib(ASN_INTEGER, "snmp", "hexOutputLength", NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_HEX_OUTPUT_LENGTH); } #ifndef NETSNMP_DISABLE_MIB_LOADING /* * function : netsnmp_set_mib_directory * - This function sets the string of the directories * from which the MIB modules will be searched or * loaded. * arguments: const char *dir, which are the directories * from which the MIB modules will be searched or * loaded. * returns : - */ void netsnmp_set_mib_directory(const char *dir) { const char *newdir; char *olddir, *tmpdir = NULL; DEBUGTRACE; if (NULL == dir) { return; } olddir = netsnmp_ds_get_string(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIBDIRS); if (olddir) { if ((*dir == '+') || (*dir == '-')) { /** New dir starts with '+', thus we add it. */ tmpdir = (char *)malloc(strlen(dir) + strlen(olddir) + 2); if (!tmpdir) { DEBUGMSGTL(("read_config:initmib", "set mibdir malloc failed")); return; } if (*dir++ == '+') sprintf(tmpdir, "%s%c%s", olddir, ENV_SEPARATOR_CHAR, dir); else sprintf(tmpdir, "%s%c%s", dir, ENV_SEPARATOR_CHAR, olddir); newdir = tmpdir; } else { newdir = dir; } } else { /** If dir starts with '+' skip '+' it. */ newdir = ((*dir == '+') ? ++dir : dir); } netsnmp_ds_set_string(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIBDIRS, newdir); /** set_string calls strdup, so if we allocated memory, free it */ if (tmpdir == newdir) { SNMP_FREE(tmpdir); } } /* * function : netsnmp_get_mib_directory * - This function returns a string of the directories * from which the MIB modules will be searched or * loaded. * If the value still does not exists, it will be made * from the evironment variable 'MIBDIRS' and/or the * default. * arguments: - * returns : char * of the directories in which the MIB modules * will be searched/loaded. */ char * netsnmp_get_mib_directory(void) { char *dir; DEBUGTRACE; dir = netsnmp_ds_get_string(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIBDIRS); if (dir == NULL) { DEBUGMSGTL(("get_mib_directory", "no mib directories set\n")); /** Check if the environment variable is set */ dir = netsnmp_getenv("MIBDIRS"); if (dir == NULL) { DEBUGMSGTL(("get_mib_directory", "no mib directories set by environment\n")); /** Not set use hard coded path */ if (confmibdir == NULL) { DEBUGMSGTL(("get_mib_directory", "no mib directories set by config\n")); netsnmp_set_mib_directory(NETSNMP_DEFAULT_MIBDIRS); } else if ((*confmibdir == '+') || (*confmibdir == '-')) { DEBUGMSGTL(("get_mib_directory", "mib directories set by config (but added)\n")); netsnmp_set_mib_directory(NETSNMP_DEFAULT_MIBDIRS); netsnmp_set_mib_directory(confmibdir); } else { DEBUGMSGTL(("get_mib_directory", "mib directories set by config\n")); netsnmp_set_mib_directory(confmibdir); } } else if ((*dir == '+') || (*dir == '-')) { DEBUGMSGTL(("get_mib_directory", "mib directories set by environment (but added)\n")); netsnmp_set_mib_directory(NETSNMP_DEFAULT_MIBDIRS); netsnmp_set_mib_directory(dir); } else { DEBUGMSGTL(("get_mib_directory", "mib directories set by environment\n")); netsnmp_set_mib_directory(dir); } dir = netsnmp_ds_get_string(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_MIBDIRS); } DEBUGMSGTL(("get_mib_directory", "mib directories set '%s'\n", dir)); return(dir); } /* * function : netsnmp_fixup_mib_directory * arguments: - * returns : - */ void netsnmp_fixup_mib_directory(void) { char *homepath = netsnmp_getenv("HOME"); char *mibpath = netsnmp_get_mib_directory(); char *oldmibpath = NULL; char *ptr_home; char *new_mibpath; DEBUGTRACE; if (homepath && mibpath) { DEBUGMSGTL(("fixup_mib_directory", "mib directories '%s'\n", mibpath)); while ((ptr_home = strstr(mibpath, "$HOME"))) { new_mibpath = (char *)malloc(strlen(mibpath) - strlen("$HOME") + strlen(homepath)+1); if (new_mibpath) { *ptr_home = 0; /* null out the spot where we stop copying */ sprintf(new_mibpath, "%s%s%s", mibpath, homepath, ptr_home + strlen("$HOME")); /** swap in the new value and repeat */ mibpath = new_mibpath; if (oldmibpath != NULL) { SNMP_FREE(oldmibpath); } oldmibpath = new_mibpath; } else { break; } } netsnmp_set_mib_directory(mibpath); /* The above copies the mibpath for us, so... */ if (oldmibpath != NULL) { SNMP_FREE(oldmibpath); } } } /** * Initialises the mib reader. * * Reads in all settings from the environment. */ void netsnmp_init_mib(void) { const char *prefix; char *env_var, *entry; PrefixListPtr pp = &mib_prefixes[0]; char *st = NULL; if (Mib) return; netsnmp_init_mib_internals(); /* * Initialise the MIB directory/ies */ netsnmp_fixup_mib_directory(); env_var = strdup(netsnmp_get_mib_directory()); if (!env_var) return; netsnmp_mibindex_load(); DEBUGMSGTL(("init_mib", "Seen MIBDIRS: Looking in '%s' for mib dirs ...\n", env_var)); entry = strtok_r(env_var, ENV_SEPARATOR, &st); while (entry) { add_mibdir(entry); entry = strtok_r(NULL, ENV_SEPARATOR, &st); } SNMP_FREE(env_var); env_var = netsnmp_getenv("MIBFILES"); if (env_var != NULL) { if (*env_var == '+') entry = strtok_r(env_var+1, ENV_SEPARATOR, &st); else entry = strtok_r(env_var, ENV_SEPARATOR, &st); while (entry) { add_mibfile(entry, NULL, NULL); entry = strtok_r(NULL, ENV_SEPARATOR, &st); } } netsnmp_init_mib_internals(); /* * Read in any modules or mibs requested */ env_var = netsnmp_getenv("MIBS"); if (env_var == NULL) { if (confmibs != NULL) env_var = strdup(confmibs); else env_var = strdup(NETSNMP_DEFAULT_MIBS); } else { env_var = strdup(env_var); } if (env_var && ((*env_var == '+') || (*env_var == '-'))) { entry = (char *) malloc(strlen(NETSNMP_DEFAULT_MIBS) + strlen(env_var) + 2); if (!entry) { DEBUGMSGTL(("init_mib", "env mibs malloc failed")); SNMP_FREE(env_var); return; } else { if (*env_var == '+') sprintf(entry, "%s%c%s", NETSNMP_DEFAULT_MIBS, ENV_SEPARATOR_CHAR, env_var+1); else sprintf(entry, "%s%c%s", env_var+1, ENV_SEPARATOR_CHAR, NETSNMP_DEFAULT_MIBS ); } SNMP_FREE(env_var); env_var = entry; } DEBUGMSGTL(("init_mib", "Seen MIBS: Looking in '%s' for mib files ...\n", env_var)); entry = strtok_r(env_var, ENV_SEPARATOR, &st); while (entry) { if (strcasecmp(entry, DEBUG_ALWAYS_TOKEN) == 0) { read_all_mibs(); } else if (strstr(entry, "/") != NULL) { read_mib(entry); } else { netsnmp_read_module(entry); } entry = strtok_r(NULL, ENV_SEPARATOR, &st); } adopt_orphans(); SNMP_FREE(env_var); env_var = netsnmp_getenv("MIBFILES"); if (env_var != NULL) { if ((*env_var == '+') || (*env_var == '-')) { #ifdef NETSNMP_DEFAULT_MIBFILES entry = (char *) malloc(strlen(NETSNMP_DEFAULT_MIBFILES) + strlen(env_var) + 2); if (!entry) { DEBUGMSGTL(("init_mib", "env mibfiles malloc failed")); } else { if (*env_var++ == '+') sprintf(entry, "%s%c%s", NETSNMP_DEFAULT_MIBFILES, ENV_SEPARATOR_CHAR, env_var ); else sprintf(entry, "%s%c%s", env_var, ENV_SEPARATOR_CHAR, NETSNMP_DEFAULT_MIBFILES ); } SNMP_FREE(env_var); env_var = entry; #else env_var = strdup(env_var + 1); #endif } else { env_var = strdup(env_var); } } else { #ifdef NETSNMP_DEFAULT_MIBFILES env_var = strdup(NETSNMP_DEFAULT_MIBFILES); #endif } if (env_var != NULL) { DEBUGMSGTL(("init_mib", "Seen MIBFILES: Looking in '%s' for mib files ...\n", env_var)); entry = strtok_r(env_var, ENV_SEPARATOR, &st); while (entry) { read_mib(entry); entry = strtok_r(NULL, ENV_SEPARATOR, &st); } SNMP_FREE(env_var); } prefix = netsnmp_getenv("PREFIX"); if (!prefix) prefix = Standard_Prefix; Prefix = (char *) malloc(strlen(prefix) + 2); if (!Prefix) DEBUGMSGTL(("init_mib", "Prefix malloc failed")); else strcpy(Prefix, prefix); DEBUGMSGTL(("init_mib", "Seen PREFIX: Looking in '%s' for prefix ...\n", Prefix)); /* * remove trailing dot */ if (Prefix) { env_var = &Prefix[strlen(Prefix) - 1]; if (*env_var == '.') *env_var = '\0'; } pp->str = Prefix; /* fixup first mib_prefix entry */ /* * now that the list of prefixes is built, save each string length. */ while (pp->str) { pp->len = strlen(pp->str); pp++; } Mib = tree_head; /* Backwards compatibility */ tree_top = (struct tree *) calloc(1, sizeof(struct tree)); /* * XX error check ? */ if (tree_top) { tree_top->label = strdup("(top)"); tree_top->child_list = tree_head; } } #ifndef NETSNMP_NO_LEGACY_DEFINITIONS void init_mib(void) { netsnmp_init_mib(); } #endif /* * Handle MIB indexes centrally */ static int _mibindex = 0; /* Last index in use */ static int _mibindex_max = 0; /* Size of index array */ char **_mibindexes = NULL; int _mibindex_add( const char *dirname, int i ); void netsnmp_mibindex_load( void ) { DIR *dir; struct dirent *file; FILE *fp; char tmpbuf[ 300]; char tmpbuf2[300]; int i; char *cp; /* * Open the MIB index directory, or create it (empty) */ snprintf( tmpbuf, sizeof(tmpbuf), "%s/mib_indexes", get_persistent_directory()); tmpbuf[sizeof(tmpbuf)-1] = 0; dir = opendir( tmpbuf ); if ( dir == NULL ) { DEBUGMSGTL(("mibindex", "load: (new)\n")); mkdirhier( tmpbuf, NETSNMP_AGENT_DIRECTORY_MODE, 0); return; } /* * Create a list of which directory each file refers to */ while ((file = readdir( dir ))) { if ( !isdigit((unsigned char)(file->d_name[0]))) continue; i = atoi( file->d_name ); snprintf( tmpbuf, sizeof(tmpbuf), "%s/mib_indexes/%d", get_persistent_directory(), i ); tmpbuf[sizeof(tmpbuf)-1] = 0; fp = fopen( tmpbuf, "r" ); if (!fp) continue; cp = fgets( tmpbuf2, sizeof(tmpbuf2), fp ); fclose( fp ); if ( !cp ) { DEBUGMSGTL(("mibindex", "Empty MIB index (%d)\n", i)); continue; } if ( strncmp( tmpbuf2, "DIR ", 4 ) != 0 ) { DEBUGMSGTL(("mibindex", "Malformed MIB index (%d)\n", i)); continue; } tmpbuf2[strlen(tmpbuf2)-1] = 0; DEBUGMSGTL(("mibindex", "load: (%d) %s\n", i, tmpbuf2)); (void)_mibindex_add( tmpbuf2+4, i ); /* Skip 'DIR ' */ } closedir( dir ); } char * netsnmp_mibindex_lookup( const char *dirname ) { int i; static char tmpbuf[300]; for (i=0; i<_mibindex; i++) { if ( _mibindexes[i] && strcmp( _mibindexes[i], dirname ) == 0) { snprintf(tmpbuf, sizeof(tmpbuf), "%s/mib_indexes/%d", get_persistent_directory(), i); tmpbuf[sizeof(tmpbuf)-1] = 0; DEBUGMSGTL(("mibindex", "lookup: %s (%d) %s\n", dirname, i, tmpbuf )); return tmpbuf; } } DEBUGMSGTL(("mibindex", "lookup: (none)\n")); return NULL; } int _mibindex_add( const char *dirname, int i ) { const int old_mibindex_max = _mibindex_max; DEBUGMSGTL(("mibindex", "add: %s (%d)\n", dirname, i )); if ( i == -1 ) i = _mibindex++; if ( i >= _mibindex_max ) { /* * If the index array is full (or non-existent) * then expand (or create) it */ _mibindex_max = i + 10; _mibindexes = realloc(_mibindexes, _mibindex_max * sizeof(_mibindexes[0])); netsnmp_assert(_mibindexes); memset(_mibindexes + old_mibindex_max, 0, (_mibindex_max - old_mibindex_max) * sizeof(_mibindexes[0])); } _mibindexes[ i ] = strdup( dirname ); if ( i >= _mibindex ) _mibindex = i+1; DEBUGMSGTL(("mibindex", "add: %d/%d/%d\n", i, _mibindex, _mibindex_max )); return i; } FILE * netsnmp_mibindex_new( const char *dirname ) { FILE *fp; char tmpbuf[300]; char *cp; int i; cp = netsnmp_mibindex_lookup( dirname ); if (!cp) { i = _mibindex_add( dirname, -1 ); snprintf( tmpbuf, sizeof(tmpbuf), "%s/mib_indexes/%d", get_persistent_directory(), i ); tmpbuf[sizeof(tmpbuf)-1] = 0; cp = tmpbuf; } DEBUGMSGTL(("mibindex", "new: %s (%s)\n", dirname, cp )); fp = fopen( cp, "w" ); if (fp) fprintf( fp, "DIR %s\n", dirname ); return fp; } /** * Unloads all mibs. */ void shutdown_mib(void) { unload_all_mibs(); if (tree_top) { if (tree_top->label) SNMP_FREE(tree_top->label); SNMP_FREE(tree_top); } tree_head = NULL; Mib = NULL; if (_mibindexes) { int i; for (i = 0; i < _mibindex; ++i) SNMP_FREE(_mibindexes[i]); free(_mibindexes); _mibindex = 0; _mibindex_max = 0; _mibindexes = NULL; } if (Prefix != NULL && Prefix != &Standard_Prefix[0]) SNMP_FREE(Prefix); if (Prefix) Prefix = NULL; SNMP_FREE(confmibs); SNMP_FREE(confmibdir); } /** * Prints the MIBs to the file fp. * * @param fp The file descriptor to print to. */ #ifndef NETSNMP_FEATURE_REMOVE_PRINT_MIB void print_mib(FILE * fp) { print_subtree(fp, tree_head, 0); } #endif /* NETSNMP_FEATURE_REMOVE_PRINT_MIB */ void print_ascii_dump(FILE * fp) { fprintf(fp, "dump DEFINITIONS ::= BEGIN\n"); print_ascii_dump_tree(fp, tree_head, 0); fprintf(fp, "END\n"); } /** * Set's the printing function printomat in a subtree according * it's type * * @param subtree The subtree to set. */ void set_function(struct tree *subtree) { subtree->printer = NULL; switch (subtree->type) { case TYPE_OBJID: subtree->printomat = sprint_realloc_object_identifier; break; case TYPE_OCTETSTR: subtree->printomat = sprint_realloc_octet_string; break; case TYPE_INTEGER: subtree->printomat = sprint_realloc_integer; break; case TYPE_INTEGER32: subtree->printomat = sprint_realloc_integer; break; case TYPE_NETADDR: subtree->printomat = sprint_realloc_networkaddress; break; case TYPE_IPADDR: subtree->printomat = sprint_realloc_ipaddress; break; case TYPE_COUNTER: subtree->printomat = sprint_realloc_counter; break; case TYPE_GAUGE: subtree->printomat = sprint_realloc_gauge; break; case TYPE_TIMETICKS: subtree->printomat = sprint_realloc_timeticks; break; case TYPE_OPAQUE: subtree->printomat = sprint_realloc_opaque; break; case TYPE_NULL: subtree->printomat = sprint_realloc_null; break; case TYPE_BITSTRING: subtree->printomat = sprint_realloc_bitstring; break; case TYPE_NSAPADDRESS: subtree->printomat = sprint_realloc_nsapaddress; break; case TYPE_COUNTER64: subtree->printomat = sprint_realloc_counter64; break; case TYPE_UINTEGER: subtree->printomat = sprint_realloc_uinteger; break; case TYPE_UNSIGNED32: subtree->printomat = sprint_realloc_gauge; break; case TYPE_OTHER: default: subtree->printomat = sprint_realloc_by_type; break; } } #endif /* NETSNMP_DISABLE_MIB_LOADING */ /** * Reads an object identifier from an input string into internal OID form. * * When called, out_len must hold the maximum length of the output array. * * @param input the input string. * @param output the oid wirte. * @param out_len number of subid's in output. * * @return 1 if successful. * * If an error occurs, this function returns 0 and MAY set snmp_errno. * snmp_errno is NOT set if SET_SNMP_ERROR evaluates to nothing. * This can make multi-threaded use a tiny bit more robust. */ int read_objid(const char *input, oid * output, size_t * out_len) { /* number of subid's in "output" */ #ifndef NETSNMP_DISABLE_MIB_LOADING struct tree *root = tree_top; char buf[SPRINT_MAX_LEN]; #endif /* NETSNMP_DISABLE_MIB_LOADING */ int ret, max_out_len; char *name, ch; const char *cp; cp = input; while ((ch = *cp)) { if (('0' <= ch && ch <= '9') || ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') || ch == '-') cp++; else break; } #ifndef NETSNMP_DISABLE_MIB_LOADING if (ch == ':') return get_node(input, output, out_len); #endif /* NETSNMP_DISABLE_MIB_LOADING */ if (*input == '.') input++; #ifndef NETSNMP_DISABLE_MIB_LOADING else if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_READ_UCD_STYLE_OID)) { /* * get past leading '.', append '.' to Prefix. */ if (*Prefix == '.') strlcpy(buf, Prefix + 1, sizeof(buf)); else strlcpy(buf, Prefix, sizeof(buf)); strlcat(buf, ".", sizeof(buf)); strlcat(buf, input, sizeof(buf)); input = buf; } #endif /* NETSNMP_DISABLE_MIB_LOADING */ #ifndef NETSNMP_DISABLE_MIB_LOADING if ((root == NULL) && (tree_head != NULL)) { root = tree_head; } else if (root == NULL) { SET_SNMP_ERROR(SNMPERR_NOMIB); *out_len = 0; return 0; } #endif /* NETSNMP_DISABLE_MIB_LOADING */ name = strdup(input); max_out_len = *out_len; *out_len = 0; #ifndef NETSNMP_DISABLE_MIB_LOADING if ((ret = _add_strings_to_oid(root, name, output, out_len, max_out_len)) <= 0) #else if ((ret = _add_strings_to_oid(NULL, name, output, out_len, max_out_len)) <= 0) #endif /* NETSNMP_DISABLE_MIB_LOADING */ { if (ret == 0) ret = SNMPERR_UNKNOWN_OBJID; SET_SNMP_ERROR(ret); SNMP_FREE(name); return 0; } SNMP_FREE(name); return 1; } /** * */ void netsnmp_sprint_realloc_objid(u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, int *buf_overflow, const oid * objid, size_t objidlen) { u_char *tbuf = NULL, *cp = NULL; size_t tbuf_len = 256, tout_len = 0; int tbuf_overflow = 0; int output_format; if ((tbuf = (u_char *) calloc(tbuf_len, 1)) == NULL) { tbuf_overflow = 1; } else { *tbuf = '.'; tout_len = 1; } _oid_finish_printing(objid, objidlen, &tbuf, &tbuf_len, &tout_len, allow_realloc, &tbuf_overflow); if (tbuf_overflow) { if (!*buf_overflow) { snmp_strcat(buf, buf_len, out_len, allow_realloc, tbuf); *buf_overflow = 1; } SNMP_FREE(tbuf); return; } output_format = netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OID_OUTPUT_FORMAT); if (0 == output_format) { output_format = NETSNMP_OID_OUTPUT_NUMERIC; } switch (output_format) { case NETSNMP_OID_OUTPUT_FULL: case NETSNMP_OID_OUTPUT_NUMERIC: case NETSNMP_OID_OUTPUT_SUFFIX: case NETSNMP_OID_OUTPUT_MODULE: cp = tbuf; break; case NETSNMP_OID_OUTPUT_NONE: default: cp = NULL; } if (!*buf_overflow && !snmp_strcat(buf, buf_len, out_len, allow_realloc, cp)) { *buf_overflow = 1; } SNMP_FREE(tbuf); } /** * */ #ifdef NETSNMP_DISABLE_MIB_LOADING void netsnmp_sprint_realloc_objid_tree(u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, int *buf_overflow, const oid * objid, size_t objidlen) { netsnmp_sprint_realloc_objid(buf, buf_len, out_len, allow_realloc, buf_overflow, objid, objidlen); } #else struct tree * netsnmp_sprint_realloc_objid_tree(u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, int *buf_overflow, const oid * objid, size_t objidlen) { u_char *tbuf = NULL, *cp = NULL; size_t tbuf_len = 512, tout_len = 0; struct tree *subtree = tree_head; size_t midpoint_offset = 0; int tbuf_overflow = 0; int output_format; if ((tbuf = (u_char *) calloc(tbuf_len, 1)) == NULL) { tbuf_overflow = 1; } else { *tbuf = '.'; tout_len = 1; } subtree = _get_realloc_symbol(objid, objidlen, subtree, &tbuf, &tbuf_len, &tout_len, allow_realloc, &tbuf_overflow, NULL, &midpoint_offset); if (tbuf_overflow) { if (!*buf_overflow) { snmp_strcat(buf, buf_len, out_len, allow_realloc, tbuf); *buf_overflow = 1; } SNMP_FREE(tbuf); return subtree; } output_format = netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OID_OUTPUT_FORMAT); if (0 == output_format) { output_format = NETSNMP_OID_OUTPUT_MODULE; } switch (output_format) { case NETSNMP_OID_OUTPUT_FULL: case NETSNMP_OID_OUTPUT_NUMERIC: cp = tbuf; break; case NETSNMP_OID_OUTPUT_SUFFIX: case NETSNMP_OID_OUTPUT_MODULE: for (cp = tbuf; *cp; cp++); if (midpoint_offset != 0) { cp = tbuf + midpoint_offset - 2; /* beyond the '.' */ } else { while (cp >= tbuf) { if (isalpha(*cp)) { break; } cp--; } } while (cp >= tbuf) { if (*cp == '.') { break; } cp--; } cp++; if ((NETSNMP_OID_OUTPUT_MODULE == output_format) && cp > tbuf) { char modbuf[256] = { 0 }, *mod = module_name(subtree->modid, modbuf); /* * Don't add the module ID if it's just numeric (i.e. we couldn't look * it up properly. */ if (!*buf_overflow && modbuf[0] != '#') { if (!snmp_strcat (buf, buf_len, out_len, allow_realloc, (const u_char *) mod) || !snmp_strcat(buf, buf_len, out_len, allow_realloc, (const u_char *) "::")) { *buf_overflow = 1; } } } break; case NETSNMP_OID_OUTPUT_UCD: { PrefixListPtr pp = &mib_prefixes[0]; size_t ilen, tlen; const char *testcp; cp = tbuf; tlen = strlen((char *) tbuf); while (pp->str) { ilen = pp->len; testcp = pp->str; if ((tlen > ilen) && memcmp(tbuf, testcp, ilen) == 0) { cp += (ilen + 1); break; } pp++; } break; } case NETSNMP_OID_OUTPUT_NONE: default: cp = NULL; } if (!*buf_overflow && !snmp_strcat(buf, buf_len, out_len, allow_realloc, cp)) { *buf_overflow = 1; } SNMP_FREE(tbuf); return subtree; } #endif /* NETSNMP_DISABLE_MIB_LOADING */ int sprint_realloc_objid(u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, const oid * objid, size_t objidlen) { int buf_overflow = 0; netsnmp_sprint_realloc_objid_tree(buf, buf_len, out_len, allow_realloc, &buf_overflow, objid, objidlen); return !buf_overflow; } #ifndef NETSNMP_FEATURE_REMOVE_SPRINT_OBJID int snprint_objid(char *buf, size_t buf_len, const oid * objid, size_t objidlen) { size_t out_len = 0; if (sprint_realloc_objid((u_char **) & buf, &buf_len, &out_len, 0, objid, objidlen)) { return (int) out_len; } else { return -1; } } #endif /* NETSNMP_FEATURE_REMOVE_SPRINT_OBJID */ /** * Prints an oid to stdout. * * @param objid The oid to print * @param objidlen The length of oidid. */ void print_objid(const oid * objid, size_t objidlen) { /* number of subidentifiers */ fprint_objid(stdout, objid, objidlen); } /** * Prints an oid to a file descriptor. * * @param f The file descriptor to print to. * @param objid The oid to print * @param objidlen The length of oidid. */ void fprint_objid(FILE * f, const oid * objid, size_t objidlen) { /* number of subidentifiers */ u_char *buf = NULL; size_t buf_len = 256, out_len = 0; int buf_overflow = 0; if ((buf = (u_char *) calloc(buf_len, 1)) == NULL) { fprintf(f, "[TRUNCATED]\n"); return; } else { netsnmp_sprint_realloc_objid_tree(&buf, &buf_len, &out_len, 1, &buf_overflow, objid, objidlen); if (buf_overflow) { fprintf(f, "%s [TRUNCATED]\n", buf); } else { fprintf(f, "%s\n", buf); } } SNMP_FREE(buf); } int sprint_realloc_variable(u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, const oid * objid, size_t objidlen, const netsnmp_variable_list * variable) { int buf_overflow = 0; #ifndef NETSNMP_DISABLE_MIB_LOADING struct tree *subtree = tree_head; subtree = #endif /* NETSNMP_DISABLE_MIB_LOADING */ netsnmp_sprint_realloc_objid_tree(buf, buf_len, out_len, allow_realloc, &buf_overflow, objid, objidlen); if (buf_overflow) { return 0; } if (!netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PRINT_BARE_VALUE)) { if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICKE_PRINT)) { if (!snmp_strcat (buf, buf_len, out_len, allow_realloc, (const u_char *) " = ")) { return 0; } } else { if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT)) { if (!snmp_strcat (buf, buf_len, out_len, allow_realloc, (const u_char *) " ")) { return 0; } } else { if (!snmp_strcat (buf, buf_len, out_len, allow_realloc, (const u_char *) " = ")) { return 0; } } /* end if-else NETSNMP_DS_LIB_QUICK_PRINT */ } /* end if-else NETSNMP_DS_LIB_QUICKE_PRINT */ } else { *out_len = 0; } if (variable->type == SNMP_NOSUCHOBJECT) { return snmp_strcat(buf, buf_len, out_len, allow_realloc, (const u_char *) "No Such Object available on this agent at this OID"); } else if (variable->type == SNMP_NOSUCHINSTANCE) { return snmp_strcat(buf, buf_len, out_len, allow_realloc, (const u_char *) "No Such Instance currently exists at this OID"); } else if (variable->type == SNMP_ENDOFMIBVIEW) { return snmp_strcat(buf, buf_len, out_len, allow_realloc, (const u_char *) "No more variables left in this MIB View (It is past the end of the MIB tree)"); #ifndef NETSNMP_DISABLE_MIB_LOADING } else if (subtree) { const char *units = NULL; const char *hint = NULL; if (!netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_DONT_PRINT_UNITS)) { units = subtree->units; } if (!netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_NO_DISPLAY_HINT)) { hint = subtree->hint; } if (subtree->printomat) { return (*subtree->printomat) (buf, buf_len, out_len, allow_realloc, variable, subtree->enums, hint, units); } else { return sprint_realloc_by_type(buf, buf_len, out_len, allow_realloc, variable, subtree->enums, hint, units); } #endif /* NETSNMP_DISABLE_MIB_LOADING */ } else { /* * Handle rare case where tree is empty. */ return sprint_realloc_by_type(buf, buf_len, out_len, allow_realloc, variable, NULL, NULL, NULL); } } #ifndef NETSNMP_FEATURE_REMOVE_SNPRINT_VARABLE int snprint_variable(char *buf, size_t buf_len, const oid * objid, size_t objidlen, const netsnmp_variable_list * variable) { size_t out_len = 0; if (sprint_realloc_variable((u_char **) & buf, &buf_len, &out_len, 0, objid, objidlen, variable)) { return (int) out_len; } else { return -1; } } #endif /* NETSNMP_FEATURE_REMOVE_SNPRINT_VARABLE */ /** * Prints a variable to stdout. * * @param objid The object id. * @param objidlen The length of teh object id. * @param variable The variable to print. */ void print_variable(const oid * objid, size_t objidlen, const netsnmp_variable_list * variable) { fprint_variable(stdout, objid, objidlen, variable); } /** * Prints a variable to a file descriptor. * * @param f The file descriptor to print to. * @param objid The object id. * @param objidlen The length of teh object id. * @param variable The variable to print. */ void fprint_variable(FILE * f, const oid * objid, size_t objidlen, const netsnmp_variable_list * variable) { u_char *buf = NULL; size_t buf_len = 256, out_len = 0; if ((buf = (u_char *) calloc(buf_len, 1)) == NULL) { fprintf(f, "[TRUNCATED]\n"); return; } else { if (sprint_realloc_variable(&buf, &buf_len, &out_len, 1, objid, objidlen, variable)) { fprintf(f, "%s\n", buf); } else { fprintf(f, "%s [TRUNCATED]\n", buf); } } SNMP_FREE(buf); } int sprint_realloc_value(u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, const oid * objid, size_t objidlen, const netsnmp_variable_list * variable) { if (variable->type == SNMP_NOSUCHOBJECT) { return snmp_strcat(buf, buf_len, out_len, allow_realloc, (const u_char *) "No Such Object available on this agent at this OID"); } else if (variable->type == SNMP_NOSUCHINSTANCE) { return snmp_strcat(buf, buf_len, out_len, allow_realloc, (const u_char *) "No Such Instance currently exists at this OID"); } else if (variable->type == SNMP_ENDOFMIBVIEW) { return snmp_strcat(buf, buf_len, out_len, allow_realloc, (const u_char *) "No more variables left in this MIB View (It is past the end of the MIB tree)"); } else { #ifndef NETSNMP_DISABLE_MIB_LOADING const char *units = NULL; struct tree *subtree = tree_head; subtree = get_tree(objid, objidlen, subtree); if (subtree && !netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_DONT_PRINT_UNITS)) { units = subtree->units; } if (subtree) { if(subtree->printomat) { return (*subtree->printomat) (buf, buf_len, out_len, allow_realloc, variable, subtree->enums, subtree->hint, units); } else { return sprint_realloc_by_type(buf, buf_len, out_len, allow_realloc, variable, subtree->enums, subtree->hint, units); } } #endif /* NETSNMP_DISABLE_MIB_LOADING */ return sprint_realloc_by_type(buf, buf_len, out_len, allow_realloc, variable, NULL, NULL, NULL); } } #ifndef NETSNMP_FEATURE_REMOVE_SNPRINT_VALUE /* used in the perl module */ int snprint_value(char *buf, size_t buf_len, const oid * objid, size_t objidlen, const netsnmp_variable_list * variable) { size_t out_len = 0; if (sprint_realloc_value((u_char **) & buf, &buf_len, &out_len, 0, objid, objidlen, variable)) { return (int) out_len; } else { return -1; } } #endif /* NETSNMP_FEATURE_REMOVE_SNPRINT_VALUE */ void print_value(const oid * objid, size_t objidlen, const netsnmp_variable_list * variable) { fprint_value(stdout, objid, objidlen, variable); } void fprint_value(FILE * f, const oid * objid, size_t objidlen, const netsnmp_variable_list * variable) { u_char *buf = NULL; size_t buf_len = 256, out_len = 0; if ((buf = (u_char *) calloc(buf_len, 1)) == NULL) { fprintf(f, "[TRUNCATED]\n"); return; } else { if (sprint_realloc_value(&buf, &buf_len, &out_len, 1, objid, objidlen, variable)) { fprintf(f, "%s\n", buf); } else { fprintf(f, "%s [TRUNCATED]\n", buf); } } SNMP_FREE(buf); } /** * Takes the value in VAR and turns it into an OID segment in var->name. * * @param var The variable. * * @return SNMPERR_SUCCESS or SNMPERR_GENERR */ int build_oid_segment(netsnmp_variable_list * var) { int i; uint32_t ipaddr; if (var->name && var->name != var->name_loc) SNMP_FREE(var->name); switch (var->type) { case ASN_INTEGER: case ASN_COUNTER: case ASN_GAUGE: case ASN_TIMETICKS: var->name_length = 1; var->name = var->name_loc; var->name[0] = *(var->val.integer); break; case ASN_IPADDRESS: var->name_length = 4; var->name = var->name_loc; memcpy(&ipaddr, var->val.string, sizeof(ipaddr)); var->name[0] = (ipaddr >> 24) & 0xff; var->name[1] = (ipaddr >> 16) & 0xff; var->name[2] = (ipaddr >> 8) & 0xff; var->name[3] = (ipaddr >> 0) & 0xff; break; case ASN_PRIV_IMPLIED_OBJECT_ID: var->name_length = var->val_len / sizeof(oid); if (var->name_length > (sizeof(var->name_loc) / sizeof(oid))) var->name = (oid *) malloc(sizeof(oid) * (var->name_length)); else var->name = var->name_loc; if (var->name == NULL) return SNMPERR_GENERR; for (i = 0; i < (int) var->name_length; i++) var->name[i] = var->val.objid[i]; break; case ASN_OBJECT_ID: var->name_length = var->val_len / sizeof(oid) + 1; if (var->name_length > (sizeof(var->name_loc) / sizeof(oid))) var->name = (oid *) malloc(sizeof(oid) * (var->name_length)); else var->name = var->name_loc; if (var->name == NULL) return SNMPERR_GENERR; var->name[0] = var->name_length - 1; for (i = 0; i < (int) var->name_length - 1; i++) var->name[i + 1] = var->val.objid[i]; break; case ASN_PRIV_IMPLIED_OCTET_STR: var->name_length = var->val_len; if (var->name_length > (sizeof(var->name_loc) / sizeof(oid))) var->name = (oid *) malloc(sizeof(oid) * (var->name_length)); else var->name = var->name_loc; if (var->name == NULL) return SNMPERR_GENERR; for (i = 0; i < (int) var->val_len; i++) var->name[i] = (oid) var->val.string[i]; break; case ASN_OPAQUE: case ASN_OCTET_STR: var->name_length = var->val_len + 1; if (var->name_length > (sizeof(var->name_loc) / sizeof(oid))) var->name = (oid *) malloc(sizeof(oid) * (var->name_length)); else var->name = var->name_loc; if (var->name == NULL) return SNMPERR_GENERR; var->name[0] = (oid) var->val_len; for (i = 0; i < (int) var->val_len; i++) var->name[i + 1] = (oid) var->val.string[i]; break; default: DEBUGMSGTL(("build_oid_segment", "invalid asn type: %d\n", var->type)); return SNMPERR_GENERR; } if (var->name_length > MAX_OID_LEN) { DEBUGMSGTL(("build_oid_segment", "Something terribly wrong, namelen = %lu\n", (unsigned long)var->name_length)); return SNMPERR_GENERR; } return SNMPERR_SUCCESS; } int build_oid_noalloc(oid * in, size_t in_len, size_t * out_len, oid * prefix, size_t prefix_len, netsnmp_variable_list * indexes) { netsnmp_variable_list *var; if (prefix) { if (in_len < prefix_len) return SNMPERR_GENERR; memcpy(in, prefix, prefix_len * sizeof(oid)); *out_len = prefix_len; } else { *out_len = 0; } for (var = indexes; var != NULL; var = var->next_variable) { if (build_oid_segment(var) != SNMPERR_SUCCESS) return SNMPERR_GENERR; if (var->name_length + *out_len <= in_len) { memcpy(&(in[*out_len]), var->name, sizeof(oid) * var->name_length); *out_len += var->name_length; } else { return SNMPERR_GENERR; } } DEBUGMSGTL(("build_oid_noalloc", "generated: ")); DEBUGMSGOID(("build_oid_noalloc", in, *out_len)); DEBUGMSG(("build_oid_noalloc", "\n")); return SNMPERR_SUCCESS; } int build_oid(oid ** out, size_t * out_len, oid * prefix, size_t prefix_len, netsnmp_variable_list * indexes) { oid tmpout[MAX_OID_LEN]; /* * xxx-rks: inefficent. try only building segments to find index len: * for (var = indexes; var != NULL; var = var->next_variable) { * if (build_oid_segment(var) != SNMPERR_SUCCESS) * return SNMPERR_GENERR; * *out_len += var->name_length; * * then see if it fits in existing buffer, or realloc buffer. */ if (build_oid_noalloc(tmpout, sizeof(tmpout), out_len, prefix, prefix_len, indexes) != SNMPERR_SUCCESS) return SNMPERR_GENERR; /** xxx-rks: should free previous value? */ snmp_clone_mem((void **) out, (void *) tmpout, *out_len * sizeof(oid)); return SNMPERR_SUCCESS; } /* * vblist_out must contain a pre-allocated string of variables into * which indexes can be extracted based on the previously existing * types in the variable chain * returns: * SNMPERR_GENERR on error * SNMPERR_SUCCESS on success */ int parse_oid_indexes(oid * oidIndex, size_t oidLen, netsnmp_variable_list * data) { netsnmp_variable_list *var = data; while (var && oidLen > 0) { if (parse_one_oid_index(&oidIndex, &oidLen, var, 0) != SNMPERR_SUCCESS) break; var = var->next_variable; } if (var != NULL || oidLen != 0) return SNMPERR_GENERR; return SNMPERR_SUCCESS; } int parse_one_oid_index(oid ** oidStart, size_t * oidLen, netsnmp_variable_list * data, int complete) { netsnmp_variable_list *var = data; oid tmpout[MAX_OID_LEN]; unsigned int i; unsigned int uitmp = 0; oid *oidIndex = *oidStart; if (var == NULL || ((*oidLen == 0) && (complete == 0))) return SNMPERR_GENERR; else { switch (var->type) { case ASN_INTEGER: case ASN_COUNTER: case ASN_GAUGE: case ASN_TIMETICKS: if (*oidLen) { snmp_set_var_value(var, (u_char *) oidIndex++, sizeof(oid)); --(*oidLen); } else { snmp_set_var_value(var, (u_char *) oidLen, sizeof(long)); } DEBUGMSGTL(("parse_oid_indexes", "Parsed int(%d): %ld\n", var->type, *var->val.integer)); break; case ASN_IPADDRESS: if ((4 > *oidLen) && (complete == 0)) return SNMPERR_GENERR; for (i = 0; i < 4 && i < *oidLen; ++i) { if (oidIndex[i] > 255) { DEBUGMSGTL(("parse_oid_indexes", "illegal oid in index: %" NETSNMP_PRIo "d\n", oidIndex[0])); return SNMPERR_GENERR; /* sub-identifier too large */ } uitmp = uitmp + (oidIndex[i] << (8*(3-i))); } if (4 > (int) (*oidLen)) { oidIndex += *oidLen; (*oidLen) = 0; } else { oidIndex += 4; (*oidLen) -= 4; } uitmp = htonl(uitmp); /* put it in proper order for byte copies */ uitmp = snmp_set_var_value(var, (u_char *) &uitmp, 4); DEBUGMSGTL(("parse_oid_indexes", "Parsed ipaddr(%d): %d.%d.%d.%d\n", var->type, var->val.string[0], var->val.string[1], var->val.string[2], var->val.string[3])); break; case ASN_OBJECT_ID: case ASN_PRIV_IMPLIED_OBJECT_ID: if (var->type == ASN_PRIV_IMPLIED_OBJECT_ID) { /* * might not be implied, might be fixed len. check if * caller set up val len, and use it if they did. */ if (0 == var->val_len) uitmp = *oidLen; else { DEBUGMSGTL(("parse_oid_indexes:fix", "fixed len oid\n")); uitmp = var->val_len; } } else { if (*oidLen) { uitmp = *oidIndex++; --(*oidLen); } else { uitmp = 0; } if ((uitmp > *oidLen) && (complete == 0)) return SNMPERR_GENERR; } if (uitmp > MAX_OID_LEN) return SNMPERR_GENERR; /* too big and illegal */ if (uitmp > *oidLen) { memcpy(tmpout, oidIndex, sizeof(oid) * (*oidLen)); memset(&tmpout[*oidLen], 0x00, sizeof(oid) * (uitmp - *oidLen)); snmp_set_var_value(var, (u_char *) tmpout, sizeof(oid) * uitmp); oidIndex += *oidLen; (*oidLen) = 0; } else { snmp_set_var_value(var, (u_char *) oidIndex, sizeof(oid) * uitmp); oidIndex += uitmp; (*oidLen) -= uitmp; } DEBUGMSGTL(("parse_oid_indexes", "Parsed oid: ")); DEBUGMSGOID(("parse_oid_indexes", var->val.objid, var->val_len / sizeof(oid))); DEBUGMSG(("parse_oid_indexes", "\n")); break; case ASN_OPAQUE: case ASN_OCTET_STR: case ASN_PRIV_IMPLIED_OCTET_STR: if (var->type == ASN_PRIV_IMPLIED_OCTET_STR) { /* * might not be implied, might be fixed len. check if * caller set up val len, and use it if they did. */ if (0 == var->val_len) uitmp = *oidLen; else { DEBUGMSGTL(("parse_oid_indexes:fix", "fixed len str\n")); uitmp = var->val_len; } } else { if (*oidLen) { uitmp = *oidIndex++; --(*oidLen); } else { uitmp = 0; } if ((uitmp > *oidLen) && (complete == 0)) return SNMPERR_GENERR; } /* * we handle this one ourselves since we don't have * pre-allocated memory to copy from using * snmp_set_var_value() */ if (uitmp == 0) break; /* zero length strings shouldn't malloc */ if (uitmp > MAX_OID_LEN) return SNMPERR_GENERR; /* too big and illegal */ /* * malloc by size+1 to allow a null to be appended. */ var->val_len = uitmp; var->val.string = (u_char *) calloc(1, uitmp + 1); if (var->val.string == NULL) return SNMPERR_GENERR; if ((size_t)uitmp > (*oidLen)) { for (i = 0; i < *oidLen; ++i) var->val.string[i] = (u_char) * oidIndex++; for (i = *oidLen; i < uitmp; ++i) var->val.string[i] = '\0'; (*oidLen) = 0; } else { for (i = 0; i < uitmp; ++i) var->val.string[i] = (u_char) * oidIndex++; (*oidLen) -= uitmp; } var->val.string[uitmp] = '\0'; DEBUGMSGTL(("parse_oid_indexes", "Parsed str(%d): %s\n", var->type, var->val.string)); break; default: DEBUGMSGTL(("parse_oid_indexes", "invalid asn type: %d\n", var->type)); return SNMPERR_GENERR; } } (*oidStart) = oidIndex; return SNMPERR_SUCCESS; } /* * dump_realloc_oid_to_inetaddress: * return 0 for failure, * return 1 for success, * return 2 for not handled */ int dump_realloc_oid_to_inetaddress(const int addr_type, const oid * objid, size_t objidlen, u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, char quotechar) { int i, len; char intbuf[64], *p; char *const end = intbuf + sizeof(intbuf); unsigned char *zc; unsigned long zone; if (!buf) return 1; for (i = 0; i < objidlen; i++) if (objid[i] < 0 || objid[i] > 255) return 2; p = intbuf; *p++ = quotechar; switch (addr_type) { case IPV4: case IPV4Z: if ((addr_type == IPV4 && objidlen != 4) || (addr_type == IPV4Z && objidlen != 8)) return 2; len = snprintf(p, end - p, "%" NETSNMP_PRIo "u.%" NETSNMP_PRIo "u." "%" NETSNMP_PRIo "u.%" NETSNMP_PRIo "u", objid[0], objid[1], objid[2], objid[3]); p += len; if (p >= end) return 2; if (addr_type == IPV4Z) { zc = (unsigned char*)&zone; zc[0] = objid[4]; zc[1] = objid[5]; zc[2] = objid[6]; zc[3] = objid[7]; zone = ntohl(zone); len = snprintf(p, end - p, "%%%lu", zone); p += len; if (p >= end) return 2; } break; case IPV6: case IPV6Z: if ((addr_type == IPV6 && objidlen != 16) || (addr_type == IPV6Z && objidlen != 20)) return 2; len = 0; for (i = 0; i < 16; i ++) { len = snprintf(p, end - p, "%s%02" NETSNMP_PRIo "x", i ? ":" : "", objid[i]); p += len; if (p >= end) return 2; } if (addr_type == IPV6Z) { zc = (unsigned char*)&zone; zc[0] = objid[16]; zc[1] = objid[17]; zc[2] = objid[18]; zc[3] = objid[19]; zone = ntohl(zone); len = snprintf(p, end - p, "%%%lu", zone); p += len; if (p >= end) return 2; } break; case DNS: default: /* DNS can just be handled by dump_realloc_oid_to_string() */ return 2; } *p++ = quotechar; if (p >= end) return 2; *p++ = '\0'; if (p >= end) return 2; return snmp_cstrcat(buf, buf_len, out_len, allow_realloc, intbuf); } int dump_realloc_oid_to_string(const oid * objid, size_t objidlen, u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, char quotechar) { if (buf) { int i, alen; for (i = 0, alen = 0; i < (int) objidlen; i++) { oid tst = objid[i]; if ((tst > 254) || (!isprint(tst))) { tst = (oid) '.'; } if (alen == 0) { if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_ESCAPE_QUOTES)) { while ((*out_len + 2) >= *buf_len) { if (!(allow_realloc && snmp_realloc(buf, buf_len))) { return 0; } } *(*buf + *out_len) = '\\'; (*out_len)++; } while ((*out_len + 2) >= *buf_len) { if (!(allow_realloc && snmp_realloc(buf, buf_len))) { return 0; } } *(*buf + *out_len) = quotechar; (*out_len)++; } while ((*out_len + 2) >= *buf_len) { if (!(allow_realloc && snmp_realloc(buf, buf_len))) { return 0; } } *(*buf + *out_len) = (char) tst; (*out_len)++; alen++; } if (alen) { if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_ESCAPE_QUOTES)) { while ((*out_len + 2) >= *buf_len) { if (!(allow_realloc && snmp_realloc(buf, buf_len))) { return 0; } } *(*buf + *out_len) = '\\'; (*out_len)++; } while ((*out_len + 2) >= *buf_len) { if (!(allow_realloc && snmp_realloc(buf, buf_len))) { return 0; } } *(*buf + *out_len) = quotechar; (*out_len)++; } *(*buf + *out_len) = '\0'; } return 1; } void _oid_finish_printing(const oid * objid, size_t objidlen, u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, int *buf_overflow) { char intbuf[64]; if (*buf != NULL && *(*buf + *out_len - 1) != '.') { if (!*buf_overflow && !snmp_strcat(buf, buf_len, out_len, allow_realloc, (const u_char *) ".")) { *buf_overflow = 1; } } while (objidlen-- > 0) { /* output rest of name, uninterpreted */ sprintf(intbuf, "%" NETSNMP_PRIo "u.", *objid++); if (!*buf_overflow && !snmp_strcat(buf, buf_len, out_len, allow_realloc, (const u_char *) intbuf)) { *buf_overflow = 1; } } if (*buf != NULL) { *(*buf + *out_len - 1) = '\0'; /* remove trailing dot */ *out_len = *out_len - 1; } } #ifndef NETSNMP_DISABLE_MIB_LOADING static void _get_realloc_symbol_octet_string(size_t numids, const oid * objid, u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, int *buf_overflow, struct tree* tp) { netsnmp_variable_list var = { 0 }; u_char buffer[1024]; size_t i; for (i = 0; i < numids; i++) buffer[i] = (u_char) objid[i]; var.type = ASN_OCTET_STR; var.val.string = buffer; var.val_len = numids; if (!*buf_overflow) { if (!sprint_realloc_octet_string(buf, buf_len, out_len, allow_realloc, &var, NULL, tp->hint, NULL)) { *buf_overflow = 1; } } } static struct tree * _get_realloc_symbol(const oid * objid, size_t objidlen, struct tree *subtree, u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, int *buf_overflow, struct index_list *in_dices, size_t * end_of_known) { struct tree *return_tree = NULL; int extended_index = netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_EXTENDED_INDEX); int output_format = netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OID_OUTPUT_FORMAT); char intbuf[64]; struct tree *orgtree = subtree; if (!objid || !buf) { return NULL; } for (; subtree; subtree = subtree->next_peer) { if (*objid == subtree->subid) { while (subtree->next_peer && subtree->next_peer->subid == *objid) subtree = subtree->next_peer; if (subtree->indexes) { in_dices = subtree->indexes; } else if (subtree->augments) { struct tree *tp2 = find_tree_node(subtree->augments, -1); if (tp2) { in_dices = tp2->indexes; } } if (!strncmp(subtree->label, ANON, ANON_LEN) || (NETSNMP_OID_OUTPUT_NUMERIC == output_format)) { sprintf(intbuf, "%lu", subtree->subid); if (!*buf_overflow && !snmp_strcat(buf, buf_len, out_len, allow_realloc, (const u_char *) intbuf)) { *buf_overflow = 1; } } else { if (!*buf_overflow && !snmp_strcat(buf, buf_len, out_len, allow_realloc, (const u_char *) subtree->label)) { *buf_overflow = 1; } } if (objidlen > 1) { if (!*buf_overflow && !snmp_strcat(buf, buf_len, out_len, allow_realloc, (const u_char *) ".")) { *buf_overflow = 1; } return_tree = _get_realloc_symbol(objid + 1, objidlen - 1, subtree->child_list, buf, buf_len, out_len, allow_realloc, buf_overflow, in_dices, end_of_known); } if (return_tree != NULL) { return return_tree; } else { return subtree; } } } if (end_of_known) { *end_of_known = *out_len; } /* * Subtree not found. */ if (orgtree && in_dices && objidlen > 0) { sprintf(intbuf, "%" NETSNMP_PRIo "u.", *objid); if (!*buf_overflow && !snmp_strcat(buf, buf_len, out_len, allow_realloc, (const u_char *) intbuf)) { *buf_overflow = 1; } objid++; objidlen--; } while (in_dices && (objidlen > 0) && (NETSNMP_OID_OUTPUT_NUMERIC != output_format) && !netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_DONT_BREAKDOWN_OIDS)) { size_t numids; struct tree *tp; tp = find_tree_node(in_dices->ilabel, -1); if (!tp) { /* * Can't find an index in the mib tree. Bail. */ goto finish_it; } if (extended_index) { if (*buf != NULL && *(*buf + *out_len - 1) == '.') { (*out_len)--; } if (!*buf_overflow && !snmp_strcat(buf, buf_len, out_len, allow_realloc, (const u_char *) "[")) { *buf_overflow = 1; } } switch (tp->type) { case TYPE_OCTETSTR: if (extended_index && tp->hint) { if (in_dices->isimplied) { numids = objidlen; if (numids > objidlen) goto finish_it; } else if (tp->ranges && !tp->ranges->next && tp->ranges->low == tp->ranges->high) { numids = tp->ranges->low; if (numids > objidlen) goto finish_it; } else { numids = *objid; if (numids >= objidlen) goto finish_it; objid++; objidlen--; } if (numids > objidlen) goto finish_it; _get_realloc_symbol_octet_string(numids, objid, buf, buf_len, out_len, allow_realloc, buf_overflow, tp); } else if (in_dices->isimplied) { numids = objidlen; if (numids > objidlen) goto finish_it; if (!*buf_overflow) { if (!dump_realloc_oid_to_string (objid, numids, buf, buf_len, out_len, allow_realloc, '\'')) { *buf_overflow = 1; } } } else if (tp->ranges && !tp->ranges->next && tp->ranges->low == tp->ranges->high) { /* * a fixed-length octet string */ numids = tp->ranges->low; if (numids > objidlen) goto finish_it; if (!*buf_overflow) { if (!dump_realloc_oid_to_string (objid, numids, buf, buf_len, out_len, allow_realloc, '\'')) { *buf_overflow = 1; } } } else { numids = (size_t) * objid + 1; if (numids > objidlen) goto finish_it; if (numids == 1) { if (netsnmp_ds_get_boolean (NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_ESCAPE_QUOTES)) { if (!*buf_overflow && !snmp_strcat(buf, buf_len, out_len, allow_realloc, (const u_char *) "\\")) { *buf_overflow = 1; } } if (!*buf_overflow && !snmp_strcat(buf, buf_len, out_len, allow_realloc, (const u_char *) "\"")) { *buf_overflow = 1; } if (netsnmp_ds_get_boolean (NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_ESCAPE_QUOTES)) { if (!*buf_overflow && !snmp_strcat(buf, buf_len, out_len, allow_realloc, (const u_char *) "\\")) { *buf_overflow = 1; } } if (!*buf_overflow && !snmp_strcat(buf, buf_len, out_len, allow_realloc, (const u_char *) "\"")) { *buf_overflow = 1; } } else { if (!*buf_overflow) { struct tree * next_peer; int normal_handling = 1; if (tp->next_peer) { next_peer = tp->next_peer; } /* Try handling the InetAddress in the OID, in case of failure, * use the normal_handling. */ if (tp->next_peer && tp->tc_index != -1 && next_peer->tc_index != -1 && strcmp(get_tc_descriptor(tp->tc_index), "InetAddress") == 0 && strcmp(get_tc_descriptor(next_peer->tc_index), "InetAddressType") == 0 ) { int ret; int addr_type = *(objid - 1); ret = dump_realloc_oid_to_inetaddress(addr_type, objid + 1, numids - 1, buf, buf_len, out_len, allow_realloc, '"'); if (ret != 2) { normal_handling = 0; if (ret == 0) { *buf_overflow = 1; } } } if (normal_handling && !dump_realloc_oid_to_string (objid + 1, numids - 1, buf, buf_len, out_len, allow_realloc, '"')) { *buf_overflow = 1; } } } } objid += numids; objidlen -= numids; break; case TYPE_INTEGER32: case TYPE_UINTEGER: case TYPE_UNSIGNED32: case TYPE_GAUGE: case TYPE_INTEGER: if (tp->enums) { struct enum_list *ep = tp->enums; while (ep && ep->value != (int) (*objid)) { ep = ep->next; } if (ep) { if (!*buf_overflow && !snmp_strcat(buf, buf_len, out_len, allow_realloc, (const u_char *) ep->label)) { *buf_overflow = 1; } } else { sprintf(intbuf, "%" NETSNMP_PRIo "u", *objid); if (!*buf_overflow && !snmp_strcat(buf, buf_len, out_len, allow_realloc, (const u_char *) intbuf)) { *buf_overflow = 1; } } } else { sprintf(intbuf, "%" NETSNMP_PRIo "u", *objid); if (!*buf_overflow && !snmp_strcat(buf, buf_len, out_len, allow_realloc, (const u_char *) intbuf)) { *buf_overflow = 1; } } objid++; objidlen--; break; case TYPE_TIMETICKS: /* In an index, this is probably a timefilter */ if (extended_index) { uptimeString( *objid, intbuf, sizeof( intbuf ) ); } else { sprintf(intbuf, "%" NETSNMP_PRIo "u", *objid); } if (!*buf_overflow && !snmp_strcat(buf, buf_len, out_len, allow_realloc, (const u_char *) intbuf)) { *buf_overflow = 1; } objid++; objidlen--; break; case TYPE_OBJID: if (in_dices->isimplied) { numids = objidlen; } else { numids = (size_t) * objid + 1; } if (numids > objidlen) goto finish_it; if (extended_index) { if (in_dices->isimplied) { if (!*buf_overflow && !netsnmp_sprint_realloc_objid_tree(buf, buf_len, out_len, allow_realloc, buf_overflow, objid, numids)) { *buf_overflow = 1; } } else { if (!*buf_overflow && !netsnmp_sprint_realloc_objid_tree(buf, buf_len, out_len, allow_realloc, buf_overflow, objid + 1, numids - 1)) { *buf_overflow = 1; } } } else { _get_realloc_symbol(objid, numids, NULL, buf, buf_len, out_len, allow_realloc, buf_overflow, NULL, NULL); } objid += (numids); objidlen -= (numids); break; case TYPE_IPADDR: if (objidlen < 4) goto finish_it; sprintf(intbuf, "%" NETSNMP_PRIo "u.%" NETSNMP_PRIo "u." "%" NETSNMP_PRIo "u.%" NETSNMP_PRIo "u", objid[0], objid[1], objid[2], objid[3]); objid += 4; objidlen -= 4; if (!*buf_overflow && !snmp_strcat(buf, buf_len, out_len, allow_realloc, (const u_char *) intbuf)) { *buf_overflow = 1; } break; case TYPE_NETADDR:{ oid ntype = *objid++; objidlen--; sprintf(intbuf, "%" NETSNMP_PRIo "u.", ntype); if (!*buf_overflow && !snmp_strcat(buf, buf_len, out_len, allow_realloc, (const u_char *) intbuf)) { *buf_overflow = 1; } if (ntype == 1 && objidlen >= 4) { sprintf(intbuf, "%" NETSNMP_PRIo "u.%" NETSNMP_PRIo "u." "%" NETSNMP_PRIo "u.%" NETSNMP_PRIo "u", objid[0], objid[1], objid[2], objid[3]); if (!*buf_overflow && !snmp_strcat(buf, buf_len, out_len, allow_realloc, (const u_char *) intbuf)) { *buf_overflow = 1; } objid += 4; objidlen -= 4; } else { goto finish_it; } } break; case TYPE_NSAPADDRESS: default: goto finish_it; break; } if (extended_index) { if (!*buf_overflow && !snmp_strcat(buf, buf_len, out_len, allow_realloc, (const u_char *) "]")) { *buf_overflow = 1; } } else { if (!*buf_overflow && !snmp_strcat(buf, buf_len, out_len, allow_realloc, (const u_char *) ".")) { *buf_overflow = 1; } } in_dices = in_dices->next; } finish_it: _oid_finish_printing(objid, objidlen, buf, buf_len, out_len, allow_realloc, buf_overflow); return NULL; } struct tree * get_tree(const oid * objid, size_t objidlen, struct tree *subtree) { struct tree *return_tree = NULL; for (; subtree; subtree = subtree->next_peer) { if (*objid == subtree->subid) goto found; } return NULL; found: while (subtree->next_peer && subtree->next_peer->subid == *objid) subtree = subtree->next_peer; if (objidlen > 1) return_tree = get_tree(objid + 1, objidlen - 1, subtree->child_list); if (return_tree != NULL) return return_tree; else return subtree; } /** * Prints on oid description on stdout. * * @see fprint_description */ void print_description(oid * objid, size_t objidlen, /* number of subidentifiers */ int width) { fprint_description(stdout, objid, objidlen, width); } /** * Prints on oid description into a file descriptor. * * @param f The file descriptor to print to. * @param objid The object identifier. * @param objidlen The object id length. * @param width Number of subidentifiers. */ void fprint_description(FILE * f, oid * objid, size_t objidlen, int width) { u_char *buf = NULL; size_t buf_len = 256, out_len = 0; if ((buf = (u_char *) calloc(buf_len, 1)) == NULL) { fprintf(f, "[TRUNCATED]\n"); return; } else { if (!sprint_realloc_description(&buf, &buf_len, &out_len, 1, objid, objidlen, width)) { fprintf(f, "%s [TRUNCATED]\n", buf); } else { fprintf(f, "%s\n", buf); } } SNMP_FREE(buf); } #ifndef NETSNMP_FEATURE_REMOVE_MIB_SNPRINT_DESCRIPTION int snprint_description(char *buf, size_t buf_len, oid * objid, size_t objidlen, int width) { size_t out_len = 0; if (sprint_realloc_description((u_char **) & buf, &buf_len, &out_len, 0, objid, objidlen, width)) { return (int) out_len; } else { return -1; } } #endif /* NETSNMP_FEATURE_REMOVE_MIB_SNPRINT_DESCRIPTION */ int sprint_realloc_description(u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, oid * objid, size_t objidlen, int width) { struct tree *tp = get_tree(objid, objidlen, tree_head); struct tree *subtree = tree_head; int pos, len; char tmpbuf[128]; const char *cp; if (NULL == tp) return 0; if (tp->type <= TYPE_SIMPLE_LAST) cp = " OBJECT-TYPE"; else switch (tp->type) { case TYPE_TRAPTYPE: cp = " TRAP-TYPE"; break; case TYPE_NOTIFTYPE: cp = " NOTIFICATION-TYPE"; break; case TYPE_OBJGROUP: cp = " OBJECT-GROUP"; break; case TYPE_AGENTCAP: cp = " AGENT-CAPABILITIES"; break; case TYPE_MODID: cp = " MODULE-IDENTITY"; break; case TYPE_OBJIDENTITY: cp = " OBJECT-IDENTITY"; break; case TYPE_MODCOMP: cp = " MODULE-COMPLIANCE"; break; default: sprintf(tmpbuf, " type_%d", tp->type); cp = tmpbuf; } if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, tp->label) || !snmp_cstrcat(buf, buf_len, out_len, allow_realloc, cp) || !snmp_cstrcat(buf, buf_len, out_len, allow_realloc, "\n")) { return 0; } if (!print_tree_node(buf, buf_len, out_len, allow_realloc, tp, width)) return 0; if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, "::= {")) return 0; pos = 5; while (objidlen > 1) { for (; subtree; subtree = subtree->next_peer) { if (*objid == subtree->subid) { while (subtree->next_peer && subtree->next_peer->subid == *objid) subtree = subtree->next_peer; if (strncmp(subtree->label, ANON, ANON_LEN)) { snprintf(tmpbuf, sizeof(tmpbuf), " %s(%lu)", subtree->label, subtree->subid); tmpbuf[ sizeof(tmpbuf)-1 ] = 0; } else sprintf(tmpbuf, " %lu", subtree->subid); len = strlen(tmpbuf); if (pos + len + 2 > width) { if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, "\n ")) return 0; pos = 5; } if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, tmpbuf)) return 0; pos += len; objid++; objidlen--; break; } } if (subtree) subtree = subtree->child_list; else break; } while (objidlen > 1) { sprintf(tmpbuf, " %" NETSNMP_PRIo "u", *objid); len = strlen(tmpbuf); if (pos + len + 2 > width) { if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, "\n ")) return 0; pos = 5; } if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, tmpbuf)) return 0; pos += len; objid++; objidlen--; } sprintf(tmpbuf, " %" NETSNMP_PRIo "u }", *objid); len = strlen(tmpbuf); if (pos + len + 2 > width) { if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, "\n ")) return 0; pos = 5; } if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, tmpbuf)) return 0; return 1; } static int print_tree_node(u_char ** buf, size_t * buf_len, size_t * out_len, int allow_realloc, struct tree *tp, int width) { const char *cp; char str[MAXTOKEN]; int i, prevmod, pos, len; if (tp) { module_name(tp->modid, str); if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, " -- FROM\t") || !snmp_cstrcat(buf, buf_len, out_len, allow_realloc, str)) return 0; pos = 16+strlen(str); for (i = 1, prevmod = tp->modid; i < tp->number_modules; i++) { if (prevmod != tp->module_list[i]) { module_name(tp->module_list[i], str); len = strlen(str); if (pos + len + 2 > width) { if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, ",\n --\t\t")) return 0; pos = 16; } else { if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, ", ")) return 0; pos += 2; } if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, str)) return 0; pos += len; } prevmod = tp->module_list[i]; } if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, "\n")) return 0; if (tp->tc_index != -1) { if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, " -- TEXTUAL CONVENTION ") || !snmp_cstrcat(buf, buf_len, out_len, allow_realloc, get_tc_descriptor(tp->tc_index)) || !snmp_cstrcat(buf, buf_len, out_len, allow_realloc, "\n")) return 0; } switch (tp->type) { case TYPE_OBJID: cp = "OBJECT IDENTIFIER"; break; case TYPE_OCTETSTR: cp = "OCTET STRING"; break; case TYPE_INTEGER: cp = "INTEGER"; break; case TYPE_NETADDR: cp = "NetworkAddress"; break; case TYPE_IPADDR: cp = "IpAddress"; break; case TYPE_COUNTER: cp = "Counter32"; break; case TYPE_GAUGE: cp = "Gauge32"; break; case TYPE_TIMETICKS: cp = "TimeTicks"; break; case TYPE_OPAQUE: cp = "Opaque"; break; case TYPE_NULL: cp = "NULL"; break; case TYPE_COUNTER64: cp = "Counter64"; break; case TYPE_BITSTRING: cp = "BITS"; break; case TYPE_NSAPADDRESS: cp = "NsapAddress"; break; case TYPE_UINTEGER: cp = "UInteger32"; break; case TYPE_UNSIGNED32: cp = "Unsigned32"; break; case TYPE_INTEGER32: cp = "Integer32"; break; default: cp = NULL; break; } #if NETSNMP_ENABLE_TESTING_CODE if (!cp && (tp->ranges || tp->enums)) { /* ranges without type ? */ sprintf(str, "?0 with %s %s ?", tp->ranges ? "Range" : "", tp->enums ? "Enum" : ""); cp = str; } #endif /* NETSNMP_ENABLE_TESTING_CODE */ if (cp) if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, " SYNTAX\t") || !snmp_cstrcat(buf, buf_len, out_len, allow_realloc, cp)) return 0; if (tp->ranges) { struct range_list *rp = tp->ranges; int first = 1; if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, " (")) return 0; while (rp) { switch (tp->type) { case TYPE_INTEGER: case TYPE_INTEGER32: if (rp->low == rp->high) sprintf(str, "%s%d", (first ? "" : " | "), rp->low ); else sprintf(str, "%s%d..%d", (first ? "" : " | "), rp->low, rp->high); break; case TYPE_UNSIGNED32: case TYPE_OCTETSTR: case TYPE_GAUGE: case TYPE_UINTEGER: if (rp->low == rp->high) sprintf(str, "%s%u", (first ? "" : " | "), (unsigned)rp->low ); else sprintf(str, "%s%u..%u", (first ? "" : " | "), (unsigned)rp->low, (unsigned)rp->high); break; default: /* No other range types allowed */ break; } if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, str)) return 0; if (first) first = 0; rp = rp->next; } if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, ") ")) return 0; } if (tp->enums) { struct enum_list *ep = tp->enums; int first = 1; if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, " {")) return 0; pos = 16 + strlen(cp) + 2; while (ep) { if (first) first = 0; else if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, ", ")) return 0; snprintf(str, sizeof(str), "%s(%d)", ep->label, ep->value); str[ sizeof(str)-1 ] = 0; len = strlen(str); if (pos + len + 2 > width) { if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, "\n\t\t ")) return 0; pos = 18; } if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, str)) return 0; pos += len + 2; ep = ep->next; } if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, "} ")) return 0; } if (cp) if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, "\n")) return 0; if (tp->hint) if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, " DISPLAY-HINT\t\"") || !snmp_cstrcat(buf, buf_len, out_len, allow_realloc, tp->hint) || !snmp_cstrcat(buf, buf_len, out_len, allow_realloc, "\"\n")) return 0; if (tp->units) if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, " UNITS\t\t\"") || !snmp_cstrcat(buf, buf_len, out_len, allow_realloc, tp->units) || !snmp_cstrcat(buf, buf_len, out_len, allow_realloc, "\"\n")) return 0; switch (tp->access) { case MIB_ACCESS_READONLY: cp = "read-only"; break; case MIB_ACCESS_READWRITE: cp = "read-write"; break; case MIB_ACCESS_WRITEONLY: cp = "write-only"; break; case MIB_ACCESS_NOACCESS: cp = "not-accessible"; break; case MIB_ACCESS_NOTIFY: cp = "accessible-for-notify"; break; case MIB_ACCESS_CREATE: cp = "read-create"; break; case 0: cp = NULL; break; default: sprintf(str, "access_%d", tp->access); cp = str; } if (cp) if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, " MAX-ACCESS\t") || !snmp_cstrcat(buf, buf_len, out_len, allow_realloc, cp) || !snmp_cstrcat(buf, buf_len, out_len, allow_realloc, "\n")) return 0; switch (tp->status) { case MIB_STATUS_MANDATORY: cp = "mandatory"; break; case MIB_STATUS_OPTIONAL: cp = "optional"; break; case MIB_STATUS_OBSOLETE: cp = "obsolete"; break; case MIB_STATUS_DEPRECATED: cp = "deprecated"; break; case MIB_STATUS_CURRENT: cp = "current"; break; case 0: cp = NULL; break; default: sprintf(str, "status_%d", tp->status); cp = str; } #if NETSNMP_ENABLE_TESTING_CODE if (!cp && (tp->indexes)) { /* index without status ? */ sprintf(str, "?0 with %s ?", tp->indexes ? "Index" : ""); cp = str; } #endif /* NETSNMP_ENABLE_TESTING_CODE */ if (cp) if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, " STATUS\t") || !snmp_cstrcat(buf, buf_len, out_len, allow_realloc, cp) || !snmp_cstrcat(buf, buf_len, out_len, allow_realloc, "\n")) return 0; if (tp->augments) if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, " AUGMENTS\t{ ") || !snmp_cstrcat(buf, buf_len, out_len, allow_realloc, tp->augments) || !snmp_cstrcat(buf, buf_len, out_len, allow_realloc, " }\n")) return 0; if (tp->indexes) { struct index_list *ip = tp->indexes; int first = 1; if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, " INDEX\t\t{ ")) return 0; pos = 16 + 2; while (ip) { if (first) first = 0; else if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, ", ")) return 0; snprintf(str, sizeof(str), "%s%s", ip->isimplied ? "IMPLIED " : "", ip->ilabel); str[ sizeof(str)-1 ] = 0; len = strlen(str); if (pos + len + 2 > width) { if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, "\n\t\t ")) return 0; pos = 16 + 2; } if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, str)) return 0; pos += len + 2; ip = ip->next; } if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, " }\n")) return 0; } if (tp->varbinds) { struct varbind_list *vp = tp->varbinds; int first = 1; if (tp->type == TYPE_TRAPTYPE) { if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, " VARIABLES\t{ ")) return 0; } else { if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, " OBJECTS\t{ ")) return 0; } pos = 16 + 2; while (vp) { if (first) first = 0; else if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, ", ")) return 0; strlcpy(str, vp->vblabel, sizeof(str)); len = strlen(str); if (pos + len + 2 > width) { if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, "\n\t\t ")) return 0; pos = 16 + 2; } if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, str)) return 0; pos += len + 2; vp = vp->next; } if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, " }\n")) return 0; } if (tp->description) if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, " DESCRIPTION\t\"") || !snmp_cstrcat(buf, buf_len, out_len, allow_realloc, tp->description) || !snmp_cstrcat(buf, buf_len, out_len, allow_realloc, "\"\n")) return 0; if (tp->defaultValue) if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, " DEFVAL\t{ ") || !snmp_cstrcat(buf, buf_len, out_len, allow_realloc, tp->defaultValue) || !snmp_cstrcat(buf, buf_len, out_len, allow_realloc, " }\n")) return 0; } else if (!snmp_cstrcat(buf, buf_len, out_len, allow_realloc, "No description\n")) return 0; return 1; } int get_module_node(const char *fname, const char *module, oid * objid, size_t * objidlen) { int modid, rc = 0; struct tree *tp; char *name, *cp; if (!strcmp(module, "ANY")) modid = -1; else { netsnmp_read_module(module); modid = which_module(module); if (modid == -1) return 0; } /* * Isolate the first component of the name ... */ name = strdup(fname); cp = strchr(name, '.'); if (cp != NULL) { *cp = '\0'; cp++; } /* * ... and locate it in the tree. */ tp = find_tree_node(name, modid); if (tp) { size_t maxlen = *objidlen; /* * Set the first element of the object ID */ if (node_to_oid(tp, objid, objidlen)) { rc = 1; /* * If the name requested was more than one element, * tag on the rest of the components */ if (cp != NULL) rc = _add_strings_to_oid(tp, cp, objid, objidlen, maxlen); } } SNMP_FREE(name); return (rc); } /** * @internal * * Populates the object identifier from a node in the MIB hierarchy. * Builds up the object ID, working backwards, * starting from the end of the objid buffer. * When the top of the MIB tree is reached, the buffer is adjusted. * * The buffer length is set to the number of subidentifiers * for the object identifier associated with the MIB node. * * @return the number of subidentifiers copied. * * If 0 is returned, the objid buffer is too small, * and the buffer contents are indeterminate. * The buffer length can be used to create a larger buffer. */ static int node_to_oid(struct tree *tp, oid * objid, size_t * objidlen) { int numids, lenids; oid *op; if (!tp || !objid || !objidlen) return 0; lenids = (int) *objidlen; op = objid + lenids; /* points after the last element */ for (numids = 0; tp; tp = tp->parent, numids++) { if (numids >= lenids) continue; --op; *op = tp->subid; } *objidlen = (size_t) numids; if (numids > lenids) { return 0; } if (numids < lenids) memmove(objid, op, numids * sizeof(oid)); return (numids); } /* * Replace \x with x stop at eos_marker * return NULL if eos_marker not found */ static char *_apply_escapes(char *src, char eos_marker) { char *dst; int backslash = 0; dst = src; while (*src) { if (backslash) { backslash = 0; *dst++ = *src; } else { if (eos_marker == *src) break; if ('\\' == *src) { backslash = 1; } else { *dst++ = *src; } } src++; } if (!*src) { /* never found eos_marker */ return NULL; } else { *dst = 0; return src; } } #endif /* NETSNMP_DISABLE_MIB_LOADING */ static int #ifndef NETSNMP_DISABLE_MIB_LOADING _add_strings_to_oid(struct tree *tp, char *cp, oid * objid, size_t * objidlen, size_t maxlen) #else _add_strings_to_oid(void *tp, char *cp, oid * objid, size_t * objidlen, size_t maxlen) #endif /* NETSNMP_DISABLE_MIB_LOADING */ { oid subid; char *fcp, *ecp, *cp2 = NULL; char doingquote; int len = -1; #ifndef NETSNMP_DISABLE_MIB_LOADING struct tree *tp2 = NULL; struct index_list *in_dices = NULL; int pos = -1; int check = !netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_DONT_CHECK_RANGE); int do_hint = !netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_NO_DISPLAY_HINT); int len_index = 1000000; while (cp && tp && tp->child_list) { fcp = cp; tp2 = tp->child_list; /* * Isolate the next entry */ cp2 = strchr(cp, '.'); if (cp2) *cp2++ = '\0'; /* * Search for the appropriate child */ if (isdigit((unsigned char)(*cp))) { subid = strtoul(cp, &ecp, 0); if (*ecp) goto bad_id; while (tp2 && tp2->subid != subid) tp2 = tp2->next_peer; } else { while (tp2 && strcmp(tp2->label, fcp)) tp2 = tp2->next_peer; if (!tp2) goto bad_id; subid = tp2->subid; } if (*objidlen >= maxlen) goto bad_id; while (tp2 && tp2->next_peer && tp2->next_peer->subid == subid) tp2 = tp2->next_peer; objid[*objidlen] = subid; (*objidlen)++; cp = cp2; if (!tp2) break; tp = tp2; } if (tp && !tp->child_list) { if ((tp2 = tp->parent)) { if (tp2->indexes) in_dices = tp2->indexes; else if (tp2->augments) { tp2 = find_tree_node(tp2->augments, -1); if (tp2) in_dices = tp2->indexes; } } tp = NULL; } while (cp && in_dices) { fcp = cp; tp = find_tree_node(in_dices->ilabel, -1); if (!tp) break; switch (tp->type) { case TYPE_INTEGER: case TYPE_INTEGER32: case TYPE_UINTEGER: case TYPE_UNSIGNED32: case TYPE_TIMETICKS: /* * Isolate the next entry */ cp2 = strchr(cp, '.'); if (cp2) *cp2++ = '\0'; if (isdigit((unsigned char)(*cp))) { subid = strtoul(cp, &ecp, 0); if (*ecp) goto bad_id; } else { if (tp->enums) { struct enum_list *ep = tp->enums; while (ep && strcmp(ep->label, cp)) ep = ep->next; if (!ep) goto bad_id; subid = ep->value; } else goto bad_id; } if (check && tp->ranges) { struct range_list *rp = tp->ranges; int ok = 0; if (tp->type == TYPE_INTEGER || tp->type == TYPE_INTEGER32) { while (!ok && rp) { if ((rp->low <= (int) subid) && ((int) subid <= rp->high)) ok = 1; else rp = rp->next; } } else { /* check unsigned range */ while (!ok && rp) { if (((unsigned int)rp->low <= subid) && (subid <= (unsigned int)rp->high)) ok = 1; else rp = rp->next; } } if (!ok) goto bad_id; } if (*objidlen >= maxlen) goto bad_id; objid[*objidlen] = subid; (*objidlen)++; break; case TYPE_IPADDR: if (*objidlen + 4 > maxlen) goto bad_id; for (subid = 0; cp && subid < 4; subid++) { fcp = cp; cp2 = strchr(cp, '.'); if (cp2) *cp2++ = 0; objid[*objidlen] = strtoul(cp, &ecp, 0); if (*ecp) goto bad_id; if (check && objid[*objidlen] > 255) goto bad_id; (*objidlen)++; cp = cp2; } break; case TYPE_OCTETSTR: if (tp->ranges && !tp->ranges->next && tp->ranges->low == tp->ranges->high) len = tp->ranges->low; else len = -1; pos = 0; if (*cp == '"' || *cp == '\'') { doingquote = *cp++; /* * insert length if requested */ if (!in_dices->isimplied && len == -1) { if (doingquote == '\'') { snmp_set_detail ("'-quote is for fixed length strings"); return 0; } if (*objidlen >= maxlen) goto bad_id; len_index = *objidlen; (*objidlen)++; } else if (doingquote == '"') { snmp_set_detail ("\"-quote is for variable length strings"); return 0; } cp2 = _apply_escapes(cp, doingquote); if (!cp2) goto bad_id; else { unsigned char *new_val; int new_val_len; int parsed_hint = 0; const char *parsed_value; if (do_hint && tp->hint) { parsed_value = parse_octet_hint(tp->hint, cp, &new_val, &new_val_len); parsed_hint = parsed_value == NULL; } if (parsed_hint) { int i; for (i = 0; i < new_val_len; i++) { if (*objidlen >= maxlen) goto bad_id; objid[ *objidlen ] = new_val[i]; (*objidlen)++; pos++; } SNMP_FREE(new_val); } else { while(*cp) { if (*objidlen >= maxlen) goto bad_id; objid[ *objidlen ] = *cp++; (*objidlen)++; pos++; } } } cp2++; if (!*cp2) cp2 = NULL; else if (*cp2 != '.') goto bad_id; else cp2++; if (check) { if (len == -1) { struct range_list *rp = tp->ranges; int ok = 0; while (rp && !ok) if (rp->low <= pos && pos <= rp->high) ok = 1; else rp = rp->next; if (!ok) goto bad_id; if (!in_dices->isimplied) objid[len_index] = pos; } else if (pos != len) goto bad_id; } else if (len == -1 && !in_dices->isimplied) objid[len_index] = pos; } else { if (!in_dices->isimplied && len == -1) { fcp = cp; cp2 = strchr(cp, '.'); if (cp2) *cp2++ = 0; len = strtoul(cp, &ecp, 0); if (*ecp) goto bad_id; if (*objidlen + len + 1 >= maxlen) goto bad_id; objid[*objidlen] = len; (*objidlen)++; cp = cp2; } while (len && cp) { fcp = cp; cp2 = strchr(cp, '.'); if (cp2) *cp2++ = 0; objid[*objidlen] = strtoul(cp, &ecp, 0); if (*ecp) goto bad_id; if (check && objid[*objidlen] > 255) goto bad_id; (*objidlen)++; len--; cp = cp2; } } break; case TYPE_OBJID: in_dices = NULL; cp2 = cp; break; case TYPE_NETADDR: fcp = cp; cp2 = strchr(cp, '.'); if (cp2) *cp2++ = 0; subid = strtoul(cp, &ecp, 0); if (*ecp) goto bad_id; if (*objidlen + 1 >= maxlen) goto bad_id; objid[*objidlen] = subid; (*objidlen)++; cp = cp2; if (subid == 1) { for (len = 0; cp && len < 4; len++) { fcp = cp; cp2 = strchr(cp, '.'); if (cp2) *cp2++ = 0; subid = strtoul(cp, &ecp, 0); if (*ecp) goto bad_id; if (*objidlen + 1 >= maxlen) goto bad_id; if (check && subid > 255) goto bad_id; objid[*objidlen] = subid; (*objidlen)++; cp = cp2; } } else { in_dices = NULL; } break; default: snmp_log(LOG_ERR, "Unexpected index type: %d %s %s\n", tp->type, in_dices->ilabel, cp); in_dices = NULL; cp2 = cp; break; } cp = cp2; if (in_dices) in_dices = in_dices->next; } #endif /* NETSNMP_DISABLE_MIB_LOADING */ while (cp) { fcp = cp; switch (*cp) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': cp2 = strchr(cp, '.'); if (cp2) *cp2++ = 0; subid = strtoul(cp, &ecp, 0); if (*ecp) goto bad_id; if (*objidlen >= maxlen) goto bad_id; objid[*objidlen] = subid; (*objidlen)++; break; case '"': case '\'': doingquote = *cp++; /* * insert length if requested */ if (doingquote == '"') { if (*objidlen >= maxlen) goto bad_id; objid[*objidlen] = len = strchr(cp, doingquote) - cp; (*objidlen)++; } while (*cp && *cp != doingquote) { if (*objidlen >= maxlen) goto bad_id; objid[*objidlen] = *cp++; (*objidlen)++; } cp2 = cp + 1; if (!*cp2) cp2 = NULL; else if (*cp2 == '.') cp2++; else goto bad_id; break; default: goto bad_id; } cp = cp2; } return 1; bad_id: { char buf[256]; #ifndef NETSNMP_DISABLE_MIB_LOADING if (in_dices) snprintf(buf, sizeof(buf), "Index out of range: %s (%s)", fcp, in_dices->ilabel); else if (tp) snprintf(buf, sizeof(buf), "Sub-id not found: %s -> %s", tp->label, fcp); else #endif /* NETSNMP_DISABLE_MIB_LOADING */ snprintf(buf, sizeof(buf), "%s", fcp); buf[ sizeof(buf)-1 ] = 0; snmp_set_detail(buf); } return 0; } #ifndef NETSNMP_DISABLE_MIB_LOADING /** * @see comments on find_best_tree_node for usage after first time. */ int get_wild_node(const char *name, oid * objid, size_t * objidlen) { struct tree *tp = find_best_tree_node(name, tree_head, NULL); if (!tp) return 0; return get_node(tp->label, objid, objidlen); } int get_node(const char *name, oid * objid, size_t * objidlen) { const char *cp; char ch; int res; cp = name; while ((ch = *cp)) if (('0' <= ch && ch <= '9') || ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') || ch == '-') cp++; else break; if (ch != ':') if (*name == '.') res = get_module_node(name + 1, "ANY", objid, objidlen); else res = get_module_node(name, "ANY", objid, objidlen); else { char *module; /* * requested name is of the form * "module:subidentifier" */ module = (char *) malloc((size_t) (cp - name + 1)); if (!module) return SNMPERR_GENERR; sprintf(module, "%.*s", (int) (cp - name), name); cp++; /* cp now point to the subidentifier */ if (*cp == ':') cp++; /* * 'cp' and 'name' *do* go that way round! */ res = get_module_node(cp, module, objid, objidlen); SNMP_FREE(module); } if (res == 0) { SET_SNMP_ERROR(SNMPERR_UNKNOWN_OBJID); } return res; } #endif /* NETSNMP_DISABLE_MIB_LOADING */ #ifdef testing main(int argc, char *argv[]) { oid objid[MAX_OID_LEN]; int objidlen = MAX_OID_LEN; int count; netsnmp_variable_list variable; netsnmp_init_mib(); if (argc < 2) print_subtree(stdout, tree_head, 0); variable.type = ASN_INTEGER; variable.val.integer = 3; variable.val_len = 4; for (argc--; argc; argc--, argv++) { objidlen = MAX_OID_LEN; printf("read_objid(%s) = %d\n", argv[1], read_objid(argv[1], objid, &objidlen)); for (count = 0; count < objidlen; count++) printf("%d.", objid[count]); printf("\n"); print_variable(objid, objidlen, &variable); } } #endif /* testing */ #ifndef NETSNMP_DISABLE_MIB_LOADING /* * initialize: no peers included in the report. */ void clear_tree_flags(register struct tree *tp) { for (; tp; tp = tp->next_peer) { tp->reported = 0; if (tp->child_list) clear_tree_flags(tp->child_list); /*RECURSE*/} } /* * Update: 1998-07-17 <jhy@gsu.edu> * Added print_oid_report* functions. */ static int print_subtree_oid_report_labeledoid = 0; static int print_subtree_oid_report_oid = 0; static int print_subtree_oid_report_symbolic = 0; static int print_subtree_oid_report_mibchildoid = 0; static int print_subtree_oid_report_suffix = 0; /* * These methods recurse. */ static void print_parent_labeledoid(FILE *, struct tree *); static void print_parent_oid(FILE *, struct tree *); static void print_parent_mibchildoid(FILE *, struct tree *); static void print_parent_label(FILE *, struct tree *); static void print_subtree_oid_report(FILE *, struct tree *, int); void print_oid_report(FILE * fp) { struct tree *tp; clear_tree_flags(tree_head); for (tp = tree_head; tp; tp = tp->next_peer) print_subtree_oid_report(fp, tp, 0); } void print_oid_report_enable_labeledoid(void) { print_subtree_oid_report_labeledoid = 1; } void print_oid_report_enable_oid(void) { print_subtree_oid_report_oid = 1; } void print_oid_report_enable_suffix(void) { print_subtree_oid_report_suffix = 1; } void print_oid_report_enable_symbolic(void) { print_subtree_oid_report_symbolic = 1; } void print_oid_report_enable_mibchildoid(void) { print_subtree_oid_report_mibchildoid = 1; } /* * helper methods for print_subtree_oid_report() * each one traverses back up the node tree * until there is no parent. Then, the label combination * is output, such that the parent is displayed first. * * Warning: these methods are all recursive. */ static void print_parent_labeledoid(FILE * f, struct tree *tp) { if (tp) { if (tp->parent) { print_parent_labeledoid(f, tp->parent); /*RECURSE*/} fprintf(f, ".%s(%lu)", tp->label, tp->subid); } } static void print_parent_oid(FILE * f, struct tree *tp) { if (tp) { if (tp->parent) { print_parent_oid(f, tp->parent); /*RECURSE*/} fprintf(f, ".%lu", tp->subid); } } static void print_parent_mibchildoid(FILE * f, struct tree *tp) { static struct tree *temp; unsigned long elems[100]; int elem_cnt = 0; int i = 0; temp = tp; if (temp) { while (temp->parent) { elems[elem_cnt++] = temp->subid; temp = temp->parent; } elems[elem_cnt++] = temp->subid; } for (i = elem_cnt - 1; i >= 0; i--) { if (i == elem_cnt - 1) { fprintf(f, "%lu", elems[i]); } else { fprintf(f, ".%lu", elems[i]); } } } static void print_parent_label(FILE * f, struct tree *tp) { if (tp) { if (tp->parent) { print_parent_label(f, tp->parent); /*RECURSE*/} fprintf(f, ".%s", tp->label); } } /** * @internal * This methods generates variations on the original print_subtree() report. * Traverse the tree depth first, from least to greatest sub-identifier. * Warning: this methods recurses and calls methods that recurse. * * @param f File descriptor to print to. * @param tree ??? * @param count ??? */ static void print_subtree_oid_report(FILE * f, struct tree *tree, int count) { struct tree *tp; count++; /* * sanity check */ if (!tree) { return; } /* * find the not reported peer with the lowest sub-identifier. * if no more, break the loop and cleanup. * set "reported" flag, and create report for this peer. * recurse using the children of this peer, if any. */ while (1) { register struct tree *ntp; tp = NULL; for (ntp = tree->child_list; ntp; ntp = ntp->next_peer) { if (ntp->reported) continue; if (!tp || (tp->subid > ntp->subid)) tp = ntp; } if (!tp) break; tp->reported = 1; if (print_subtree_oid_report_labeledoid) { print_parent_labeledoid(f, tp); fprintf(f, "\n"); } if (print_subtree_oid_report_oid) { print_parent_oid(f, tp); fprintf(f, "\n"); } if (print_subtree_oid_report_symbolic) { print_parent_label(f, tp); fprintf(f, "\n"); } if (print_subtree_oid_report_mibchildoid) { fprintf(f, "\"%s\"\t", tp->label); fprintf(f, "\t\t\""); print_parent_mibchildoid(f, tp); fprintf(f, "\"\n"); } if (print_subtree_oid_report_suffix) { int i; for (i = 0; i < count; i++) fprintf(f, " "); fprintf(f, "%s(%ld) type=%d", tp->label, tp->subid, tp->type); if (tp->tc_index != -1) fprintf(f, " tc=%d", tp->tc_index); if (tp->hint) fprintf(f, " hint=%s", tp->hint); if (tp->units) fprintf(f, " units=%s", tp->units); fprintf(f, "\n"); } print_subtree_oid_report(f, tp, count); /*RECURSE*/} } #endif /* NETSNMP_DISABLE_MIB_LOADING */ /** * Converts timeticks to hours, minutes, seconds string. * * @param timeticks The timeticks to convert. * @param buf Buffer to write to, has to be at * least 40 Bytes large. * * @return The buffer * * @see uptimeString */ char * uptime_string(u_long timeticks, char *buf) { return uptime_string_n( timeticks, buf, 40); } char * uptime_string_n(u_long timeticks, char *buf, size_t buflen) { uptimeString(timeticks, buf, buflen); return buf; } /** * Given a string, parses an oid out of it (if possible). * It will try to parse it based on predetermined configuration if * present or by every method possible otherwise. * If a suffix has been registered using NETSNMP_DS_LIB_OIDSUFFIX, it * will be appended to the input string before processing. * * @param argv The OID to string parse * @param root An OID array where the results are stored. * @param rootlen The max length of the array going in and the data * length coming out. * * @return The root oid pointer if successful, or NULL otherwise. */ oid * snmp_parse_oid(const char *argv, oid * root, size_t * rootlen) { #ifndef NETSNMP_DISABLE_MIB_LOADING size_t savlen = *rootlen; #endif /* NETSNMP_DISABLE_MIB_LOADING */ static size_t tmpbuf_len = 0; static char *tmpbuf = NULL; const char *suffix, *prefix; suffix = netsnmp_ds_get_string(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OIDSUFFIX); prefix = netsnmp_ds_get_string(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OIDPREFIX); if ((suffix && suffix[0]) || (prefix && prefix[0])) { if (!suffix) suffix = ""; if (!prefix) prefix = ""; if ((strlen(suffix) + strlen(prefix) + strlen(argv) + 2) > tmpbuf_len) { tmpbuf_len = strlen(suffix) + strlen(argv) + strlen(prefix) + 2; tmpbuf = malloc(tmpbuf_len); } snprintf(tmpbuf, tmpbuf_len, "%s%s%s%s", prefix, argv, ((suffix[0] == '.' || suffix[0] == '\0') ? "" : "."), suffix); argv = tmpbuf; DEBUGMSGTL(("snmp_parse_oid","Parsing: %s\n",argv)); } #ifndef NETSNMP_DISABLE_MIB_LOADING if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_RANDOM_ACCESS) || strchr(argv, ':')) { if (get_node(argv, root, rootlen)) { free(tmpbuf); return root; } } else if (netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_REGEX_ACCESS)) { clear_tree_flags(tree_head); if (get_wild_node(argv, root, rootlen)) { free(tmpbuf); return root; } } else { #endif /* NETSNMP_DISABLE_MIB_LOADING */ if (read_objid(argv, root, rootlen)) { free(tmpbuf); return root; } #ifndef NETSNMP_DISABLE_MIB_LOADING *rootlen = savlen; if (get_node(argv, root, rootlen)) { free(tmpbuf); return root; } *rootlen = savlen; DEBUGMSGTL(("parse_oid", "wildly parsing\n")); clear_tree_flags(tree_head); if (get_wild_node(argv, root, rootlen)) { free(tmpbuf); return root; } } #endif /* NETSNMP_DISABLE_MIB_LOADING */ free(tmpbuf); return NULL; } #ifndef NETSNMP_DISABLE_MIB_LOADING /* * Use DISPLAY-HINT to parse a value into an octet string. * * note that "1d1d", "11" could have come from an octet string that * looked like { 1, 1 } or an octet string that looked like { 11 } * because of this, it's doubtful that anyone would use such a display * string. Therefore, the parser ignores this case. */ struct parse_hints { int length; int repeat; int format; int separator; int terminator; unsigned char *result; int result_max; int result_len; }; static void parse_hints_reset(struct parse_hints *ph) { ph->length = 0; ph->repeat = 0; ph->format = 0; ph->separator = 0; ph->terminator = 0; } static void parse_hints_ctor(struct parse_hints *ph) { parse_hints_reset(ph); ph->result = NULL; ph->result_max = 0; ph->result_len = 0; } static int parse_hints_add_result_octet(struct parse_hints *ph, unsigned char octet) { if (!(ph->result_len < ph->result_max)) { ph->result_max = ph->result_len + 32; if (!ph->result) { ph->result = (unsigned char *)malloc(ph->result_max); } else { ph->result = (unsigned char *)realloc(ph->result, ph->result_max); } } if (!ph->result) { return 0; /* failed */ } ph->result[ph->result_len++] = octet; return 1; /* success */ } static int parse_hints_parse(struct parse_hints *ph, const char **v_in_out) { const char *v = *v_in_out; char *nv; int base; int repeats = 0; int repeat_fixup = ph->result_len; if (ph->repeat) { if (!parse_hints_add_result_octet(ph, 0)) { return 0; } } do { base = 0; switch (ph->format) { case 'x': base += 6; /* fall through */ case 'd': base += 2; /* fall through */ case 'o': base += 8; /* fall through */ { int i; unsigned long number = strtol(v, &nv, base); if (nv == v) return 0; v = nv; for (i = 0; i < ph->length; i++) { int shift = 8 * (ph->length - 1 - i); if (!parse_hints_add_result_octet(ph, (u_char)(number >> shift) )) { return 0; /* failed */ } } } break; case 'a': { int i; for (i = 0; i < ph->length && *v; i++) { if (!parse_hints_add_result_octet(ph, *v++)) { return 0; /* failed */ } } } break; } repeats++; if (ph->separator && *v) { if (*v == ph->separator) { v++; } else { return 0; /* failed */ } } if (ph->terminator) { if (*v == ph->terminator) { v++; break; } } } while (ph->repeat && *v); if (ph->repeat) { ph->result[repeat_fixup] = repeats; } *v_in_out = v; return 1; } static void parse_hints_length_add_digit(struct parse_hints *ph, int digit) { ph->length *= 10; ph->length += digit - '0'; } const char *parse_octet_hint(const char *hint, const char *value, unsigned char **new_val, int *new_val_len) { const char *h = hint; const char *v = value; struct parse_hints ph; int retval = 1; /* See RFC 1443 */ enum { HINT_1_2, HINT_2_3, HINT_1_2_4, HINT_1_2_5 } state = HINT_1_2; parse_hints_ctor(&ph); while (*h && *v && retval) { switch (state) { case HINT_1_2: if ('*' == *h) { ph.repeat = 1; state = HINT_2_3; } else if (isdigit((unsigned char)(*h))) { parse_hints_length_add_digit(&ph, *h); state = HINT_2_3; } else { return v; /* failed */ } break; case HINT_2_3: if (isdigit((unsigned char)(*h))) { parse_hints_length_add_digit(&ph, *h); /* state = HINT_2_3 */ } else if ('x' == *h || 'd' == *h || 'o' == *h || 'a' == *h) { ph.format = *h; state = HINT_1_2_4; } else { return v; /* failed */ } break; case HINT_1_2_4: if ('*' == *h) { retval = parse_hints_parse(&ph, &v); parse_hints_reset(&ph); ph.repeat = 1; state = HINT_2_3; } else if (isdigit((unsigned char)(*h))) { retval = parse_hints_parse(&ph, &v); parse_hints_reset(&ph); parse_hints_length_add_digit(&ph, *h); state = HINT_2_3; } else { ph.separator = *h; state = HINT_1_2_5; } break; case HINT_1_2_5: if ('*' == *h) { retval = parse_hints_parse(&ph, &v); parse_hints_reset(&ph); ph.repeat = 1; state = HINT_2_3; } else if (isdigit((unsigned char)(*h))) { retval = parse_hints_parse(&ph, &v); parse_hints_reset(&ph); parse_hints_length_add_digit(&ph, *h); state = HINT_2_3; } else { ph.terminator = *h; retval = parse_hints_parse(&ph, &v); parse_hints_reset(&ph); state = HINT_1_2; } break; } h++; } while (*v && retval) { retval = parse_hints_parse(&ph, &v); } if (retval) { *new_val = ph.result; *new_val_len = ph.result_len; } else { if (ph.result) { SNMP_FREE(ph.result); } *new_val = NULL; *new_val_len = 0; } return retval ? NULL : v; } #endif /* NETSNMP_DISABLE_MIB_LOADING */ #ifdef test_display_hint int main(int argc, const char **argv) { const char *hint; const char *value; unsigned char *new_val; int new_val_len; char *r; if (argc < 3) { fprintf(stderr, "usage: dh <hint> <value>\n"); exit(2); } hint = argv[1]; value = argv[2]; r = parse_octet_hint(hint, value, &new_val, &new_val_len); printf("{\"%s\", \"%s\"}: \n\t", hint, value); if (r) { *r = 0; printf("returned failed\n"); printf("value syntax error at: %s\n", value); } else { int i; printf("returned success\n"); for (i = 0; i < new_val_len; i++) { int c = new_val[i] & 0xFF; printf("%02X(%c) ", c, isprint(c) ? c : ' '); } SNMP_FREE(new_val); } printf("\n"); exit(0); } #endif /* test_display_hint */ #ifndef NETSNMP_FEATURE_REMOVE_MIB_TO_ASN_TYPE u_char mib_to_asn_type(int mib_type) { switch (mib_type) { case TYPE_OBJID: return ASN_OBJECT_ID; case TYPE_OCTETSTR: return ASN_OCTET_STR; case TYPE_NETADDR: case TYPE_IPADDR: return ASN_IPADDRESS; case TYPE_INTEGER32: case TYPE_INTEGER: return ASN_INTEGER; case TYPE_COUNTER: return ASN_COUNTER; case TYPE_GAUGE: return ASN_GAUGE; case TYPE_TIMETICKS: return ASN_TIMETICKS; case TYPE_OPAQUE: return ASN_OPAQUE; case TYPE_NULL: return ASN_NULL; case TYPE_COUNTER64: return ASN_COUNTER64; case TYPE_BITSTRING: return ASN_BIT_STR; case TYPE_UINTEGER: case TYPE_UNSIGNED32: return ASN_UNSIGNED; case TYPE_NSAPADDRESS: return ASN_NSAP; } return -1; } #endif /* NETSNMP_FEATURE_REMOVE_MIB_TO_ASN_TYPE */ /** * Converts a string to its OID form. * in example "hello" = 5 . 'h' . 'e' . 'l' . 'l' . 'o' * * @param S The string. * @param O The oid. * @param L The length of the oid. * * @return 0 on Sucess, 1 on failure. */ #ifndef NETSNMP_FEATURE_REMOVE_MIB_STRING_CONVERSIONS int netsnmp_str2oid(const char *S, oid * O, int L) { const char *c = S; oid *o = &O[1]; --L; /* leave room for length prefix */ for (; *c && L; --L, ++o, ++c) *o = *c; /* * make sure we got to the end of the string */ if (*c != 0) return 1; /* * set the length of the oid */ *O = c - S; return 0; } /** * Converts an OID to its character form. * in example 5 . 1 . 2 . 3 . 4 . 5 = 12345 * * @param C The character buffer. * @param L The length of the buffer. * @param O The oid. * * @return 0 on Sucess, 1 on failure. */ int netsnmp_oid2chars(char *C, int L, const oid * O) { char *c = C; const oid *o = &O[1]; if (L < (int)*O) return 1; L = *O; /** length */ for (; L; --L, ++o, ++c) { if (*o > 0xFF) return 1; *c = (char)*o; } return 0; } /** * Converts an OID to its string form. * in example 5 . 'h' . 'e' . 'l' . 'l' . 'o' = "hello\0" (null terminated) * * @param S The character string buffer. * @param L The length of the string buffer. * @param O The oid. * * @return 0 on Sucess, 1 on failure. */ int netsnmp_oid2str(char *S, int L, oid * O) { int rc; if (L <= (int)*O) return 1; rc = netsnmp_oid2chars(S, L, O); if (rc) return 1; S[ *O ] = 0; return 0; } #endif /* NETSNMP_FEATURE_REMOVE_MIB_STRING_CONVERSIONS */ #ifndef NETSNMP_FEATURE_REMOVE_MIB_SNPRINT int snprint_by_type(char *buf, size_t buf_len, netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { size_t out_len = 0; if (sprint_realloc_by_type((u_char **) & buf, &buf_len, &out_len, 0, var, enums, hint, units)) return (int) out_len; else return -1; } int snprint_hexstring(char *buf, size_t buf_len, const u_char * cp, size_t len) { size_t out_len = 0; if (sprint_realloc_hexstring((u_char **) & buf, &buf_len, &out_len, 0, cp, len)) return (int) out_len; else return -1; } int snprint_asciistring(char *buf, size_t buf_len, const u_char * cp, size_t len) { size_t out_len = 0; if (sprint_realloc_asciistring ((u_char **) & buf, &buf_len, &out_len, 0, cp, len)) return (int) out_len; else return -1; } int snprint_octet_string(char *buf, size_t buf_len, const netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { size_t out_len = 0; if (sprint_realloc_octet_string ((u_char **) & buf, &buf_len, &out_len, 0, var, enums, hint, units)) return (int) out_len; else return -1; } int snprint_opaque(char *buf, size_t buf_len, const netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { size_t out_len = 0; if (sprint_realloc_opaque((u_char **) & buf, &buf_len, &out_len, 0, var, enums, hint, units)) return (int) out_len; else return -1; } int snprint_object_identifier(char *buf, size_t buf_len, const netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { size_t out_len = 0; if (sprint_realloc_object_identifier ((u_char **) & buf, &buf_len, &out_len, 0, var, enums, hint, units)) return (int) out_len; else return -1; } int snprint_timeticks(char *buf, size_t buf_len, const netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { size_t out_len = 0; if (sprint_realloc_timeticks((u_char **) & buf, &buf_len, &out_len, 0, var, enums, hint, units)) return (int) out_len; else return -1; } int snprint_hinted_integer(char *buf, size_t buf_len, long val, const char *hint, const char *units) { size_t out_len = 0; if (sprint_realloc_hinted_integer ((u_char **) & buf, &buf_len, &out_len, 0, val, 'd', hint, units)) return (int) out_len; else return -1; } int snprint_integer(char *buf, size_t buf_len, const netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { size_t out_len = 0; if (sprint_realloc_integer((u_char **) & buf, &buf_len, &out_len, 0, var, enums, hint, units)) return (int) out_len; else return -1; } int snprint_uinteger(char *buf, size_t buf_len, const netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { size_t out_len = 0; if (sprint_realloc_uinteger((u_char **) & buf, &buf_len, &out_len, 0, var, enums, hint, units)) return (int) out_len; else return -1; } int snprint_gauge(char *buf, size_t buf_len, const netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { size_t out_len = 0; if (sprint_realloc_gauge((u_char **) & buf, &buf_len, &out_len, 0, var, enums, hint, units)) return (int) out_len; else return -1; } int snprint_counter(char *buf, size_t buf_len, const netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { size_t out_len = 0; if (sprint_realloc_counter((u_char **) & buf, &buf_len, &out_len, 0, var, enums, hint, units)) return (int) out_len; else return -1; } int snprint_networkaddress(char *buf, size_t buf_len, const netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { size_t out_len = 0; if (sprint_realloc_networkaddress ((u_char **) & buf, &buf_len, &out_len, 0, var, enums, hint, units)) return (int) out_len; else return -1; } int snprint_ipaddress(char *buf, size_t buf_len, const netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { size_t out_len = 0; if (sprint_realloc_ipaddress((u_char **) & buf, &buf_len, &out_len, 0, var, enums, hint, units)) return (int) out_len; else return -1; } int snprint_null(char *buf, size_t buf_len, const netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { size_t out_len = 0; if (sprint_realloc_null((u_char **) & buf, &buf_len, &out_len, 0, var, enums, hint, units)) return (int) out_len; else return -1; } int snprint_bitstring(char *buf, size_t buf_len, const netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { size_t out_len = 0; if (sprint_realloc_bitstring((u_char **) & buf, &buf_len, &out_len, 0, var, enums, hint, units)) return (int) out_len; else return -1; } int snprint_nsapaddress(char *buf, size_t buf_len, const netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { size_t out_len = 0; if (sprint_realloc_nsapaddress ((u_char **) & buf, &buf_len, &out_len, 0, var, enums, hint, units)) return (int) out_len; else return -1; } int snprint_counter64(char *buf, size_t buf_len, const netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { size_t out_len = 0; if (sprint_realloc_counter64((u_char **) & buf, &buf_len, &out_len, 0, var, enums, hint, units)) return (int) out_len; else return -1; } int snprint_badtype(char *buf, size_t buf_len, const netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { size_t out_len = 0; if (sprint_realloc_badtype((u_char **) & buf, &buf_len, &out_len, 0, var, enums, hint, units)) return (int) out_len; else return -1; } #ifdef NETSNMP_WITH_OPAQUE_SPECIAL_TYPES int snprint_float(char *buf, size_t buf_len, const netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { size_t out_len = 0; if (sprint_realloc_float((u_char **) & buf, &buf_len, &out_len, 0, var, enums, hint, units)) return (int) out_len; else return -1; } int snprint_double(char *buf, size_t buf_len, const netsnmp_variable_list * var, const struct enum_list *enums, const char *hint, const char *units) { size_t out_len = 0; if (sprint_realloc_double((u_char **) & buf, &buf_len, &out_len, 0, var, enums, hint, units)) return (int) out_len; else return -1; } #endif #endif /* NETSNMP_FEATURE_REMOVE_MIB_SNPRINT */ /** @} */
./CrossVul/dataset_final_sorted/CWE-59/c/bad_4226_3
crossvul-cpp_data_good_1590_0
/* abrt-hook-ccpp.cpp - the hook for C/C++ crashing program Copyright (C) 2009 Zdenek Prikryl (zprikryl@redhat.com) Copyright (C) 2009 RedHat inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <sys/utsname.h> #include "libabrt.h" #define DUMP_SUID_UNSAFE 1 #define DUMP_SUID_SAFE 2 /* I want to use -Werror, but gcc-4.4 throws a curveball: * "warning: ignoring return value of 'ftruncate', declared with attribute warn_unused_result" * and (void) cast is not enough to shut it up! Oh God... */ #define IGNORE_RESULT(func_call) do { if (func_call) /* nothing */; } while (0) static char* malloc_readlink(const char *linkname) { char buf[PATH_MAX + 1]; int len; len = readlink(linkname, buf, sizeof(buf)-1); if (len >= 0) { buf[len] = '\0'; return xstrdup(buf); } return NULL; } /* Custom version of copyfd_xyz, * one which is able to write into two descriptors at once. */ #define CONFIG_FEATURE_COPYBUF_KB 4 static off_t copyfd_sparse(int src_fd, int dst_fd1, int dst_fd2, off_t size2) { off_t total = 0; int last_was_seek = 0; #if CONFIG_FEATURE_COPYBUF_KB <= 4 char buffer[CONFIG_FEATURE_COPYBUF_KB * 1024]; enum { buffer_size = sizeof(buffer) }; #else char *buffer; int buffer_size; /* We want page-aligned buffer, just in case kernel is clever * and can do page-aligned io more efficiently */ buffer = mmap(NULL, CONFIG_FEATURE_COPYBUF_KB * 1024, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, /* ignored: */ -1, 0); buffer_size = CONFIG_FEATURE_COPYBUF_KB * 1024; if (buffer == MAP_FAILED) { buffer = alloca(4 * 1024); buffer_size = 4 * 1024; } #endif while (1) { ssize_t rd = safe_read(src_fd, buffer, buffer_size); if (!rd) { /* eof */ if (last_was_seek) { if (lseek(dst_fd1, -1, SEEK_CUR) < 0 || safe_write(dst_fd1, "", 1) != 1 || (dst_fd2 >= 0 && (lseek(dst_fd2, -1, SEEK_CUR) < 0 || safe_write(dst_fd2, "", 1) != 1 ) ) ) { perror_msg("Write error"); total = -1; goto out; } } /* all done */ goto out; } if (rd < 0) { perror_msg("Read error"); total = -1; goto out; } /* checking sparseness */ ssize_t cnt = rd; while (--cnt >= 0) { if (buffer[cnt] != 0) { /* not sparse */ errno = 0; ssize_t wr1 = full_write(dst_fd1, buffer, rd); ssize_t wr2 = (dst_fd2 >= 0 ? full_write(dst_fd2, buffer, rd) : rd); if (wr1 < rd || wr2 < rd) { perror_msg("Write error"); total = -1; goto out; } last_was_seek = 0; goto adv; } } /* sparse */ xlseek(dst_fd1, rd, SEEK_CUR); if (dst_fd2 >= 0) xlseek(dst_fd2, rd, SEEK_CUR); last_was_seek = 1; adv: total += rd; size2 -= rd; if (size2 < 0) dst_fd2 = -1; //TODO: truncate to 0 or even delete the second file //(currently we delete the file later) } out: #if CONFIG_FEATURE_COPYBUF_KB > 4 if (buffer_size != 4 * 1024) munmap(buffer, buffer_size); #endif return total; } /* Global data */ static char *user_pwd; static char *proc_pid_status; static struct dump_dir *dd; static int user_core_fd = -1; /* * %s - signal number * %c - ulimit -c value * %p - pid * %u - uid * %g - gid * %t - UNIX time of dump * %e - executable filename * %h - hostname * %% - output one "%" */ /* Hook must be installed with exactly the same sequence of %c specifiers. * Last one, %h, may be omitted (we can find it out). */ static const char percent_specifiers[] = "%scpugteh"; static char *core_basename = (char*) "core"; /* * Used for error messages only. * It is either the same as core_basename if it is absolute, * or $PWD/core_basename. */ static char *full_core_basename; static char* get_executable(pid_t pid, int *fd_p) { char buf[sizeof("/proc/%lu/exe") + sizeof(long)*3]; sprintf(buf, "/proc/%lu/exe", (long)pid); if (fd_p) *fd_p = open(buf, O_RDONLY); /* might fail and return -1, it's ok */ char *executable = malloc_readlink(buf); if (!executable) return NULL; /* find and cut off " (deleted)" from the path */ char *deleted = executable + strlen(executable) - strlen(" (deleted)"); if (deleted > executable && strcmp(deleted, " (deleted)") == 0) { *deleted = '\0'; log("File '%s' seems to be deleted", executable); } /* find and cut off prelink suffixes from the path */ char *prelink = executable + strlen(executable) - strlen(".#prelink#.XXXXXX"); if (prelink > executable && strncmp(prelink, ".#prelink#.", strlen(".#prelink#.")) == 0) { log("File '%s' seems to be a prelink temporary file", executable); *prelink = '\0'; } return executable; } static char* get_cwd(pid_t pid) { char buf[sizeof("/proc/%lu/cwd") + sizeof(long)*3]; sprintf(buf, "/proc/%lu/cwd", (long)pid); return malloc_readlink(buf); } static char* get_rootdir(pid_t pid) { char buf[sizeof("/proc/%lu/root") + sizeof(long)*3]; sprintf(buf, "/proc/%lu/root", (long)pid); return malloc_readlink(buf); } static int get_fsuid(void) { int real, euid, saved; /* if we fail to parse the uid, then make it root only readable to be safe */ int fs_uid = 0; char *line = proc_pid_status; /* never NULL */ for (;;) { if (strncmp(line, "Uid", 3) == 0) { int n = sscanf(line, "Uid:\t%d\t%d\t%d\t%d\n", &real, &euid, &saved, &fs_uid); if (n != 4) { perror_msg_and_die("Can't parse Uid: line"); } break; } line = strchr(line, '\n'); if (!line) break; line++; } return fs_uid; } static int dump_suid_policy() { /* - values are: 0 - don't dump suided programs - in this case the hook is not called by kernel 1 - create coredump readable by fs_uid 2 - create coredump readable by root only */ int c; int suid_dump_policy = 0; const char *filename = "/proc/sys/fs/suid_dumpable"; FILE *f = fopen(filename, "r"); if (!f) { log("Can't open %s", filename); return suid_dump_policy; } c = fgetc(f); fclose(f); if (c != EOF) suid_dump_policy = c - '0'; //log("suid dump policy is: %i", suid_dump_policy); return suid_dump_policy; } static int open_user_core(uid_t uid, uid_t fsuid, pid_t pid, char **percent_values) { errno = 0; if (user_pwd == NULL || chdir(user_pwd) != 0 ) { perror_msg("Can't cd to '%s'", user_pwd); return -1; } struct passwd* pw = getpwuid(uid); gid_t gid = pw ? pw->pw_gid : uid; //log("setting uid: %i gid: %i", uid, gid); xsetegid(gid); xseteuid(fsuid); if (strcmp(core_basename, "core") == 0) { /* Mimic "core.PID" if requested */ char buf[] = "0\n"; int fd = open("/proc/sys/kernel/core_uses_pid", O_RDONLY); if (fd >= 0) { IGNORE_RESULT(read(fd, buf, sizeof(buf))); close(fd); } if (strcmp(buf, "1\n") == 0) { core_basename = xasprintf("%s.%lu", core_basename, (long)pid); } } else { /* Expand old core pattern, put expanded name in core_basename */ core_basename = xstrdup(core_basename); unsigned idx = 0; while (1) { char c = core_basename[idx]; if (!c) break; idx++; if (c != '%') continue; /* We just copied %, look at following char and expand %c */ c = core_basename[idx]; unsigned specifier_num = strchrnul(percent_specifiers, c) - percent_specifiers; if (percent_specifiers[specifier_num] != '\0') /* valid %c (might be %% too) */ { const char *val = "%"; if (specifier_num > 0) /* not %% */ val = percent_values[specifier_num - 1]; //log("c:'%c'", c); //log("val:'%s'", val); /* Replace %c at core_basename[idx] by its value */ idx--; char *old = core_basename; core_basename = xasprintf("%.*s%s%s", idx, core_basename, val, core_basename + idx + 2); //log("pos:'%*s|'", idx, ""); //log("new:'%s'", core_basename); //log("old:'%s'", old); free(old); idx += strlen(val); } /* else: invalid %c, % is already copied verbatim, * next loop iteration will copy c */ } } full_core_basename = core_basename; if (core_basename[0] != '/') core_basename = concat_path_file(user_pwd, core_basename); /* Open (create) compat core file. * man core: * There are various circumstances in which a core dump file * is not produced: * * [skipped obvious ones] * The process does not have permission to write the core file. * ...if a file with the same name exists and is not writable * or is not a regular file (e.g., it is a directory or a symbolic link). * * A file with the same name already exists, but there is more * than one hard link to that file. * * The file system where the core dump file would be created is full; * or has run out of inodes; or is mounted read-only; * or the user has reached their quota for the file system. * * The RLIMIT_CORE or RLIMIT_FSIZE resource limits for the process * are set to zero. * [we check RLIMIT_CORE, but how can we check RLIMIT_FSIZE?] * * The binary being executed by the process does not have * read permission enabled. [how we can check it here?] * * The process is executing a set-user-ID (set-group-ID) program * that is owned by a user (group) other than the real * user (group) ID of the process. [TODO?] * (However, see the description of the prctl(2) PR_SET_DUMPABLE operation, * and the description of the /proc/sys/fs/suid_dumpable file in proc(5).) */ struct stat sb; errno = 0; /* Do not O_TRUNC: if later checks fail, we do not want to have file already modified here */ int user_core_fd = open(core_basename, O_WRONLY | O_CREAT | O_NOFOLLOW, 0600); /* kernel makes 0600 too */ xsetegid(0); xseteuid(0); if (user_core_fd < 0 || fstat(user_core_fd, &sb) != 0 || !S_ISREG(sb.st_mode) || sb.st_nlink != 1 /* kernel internal dumper checks this too: if (inode->i_uid != current->fsuid) <fail>, need to mimic? */ ) { if (user_core_fd < 0) perror_msg("Can't open '%s'", full_core_basename); else perror_msg("'%s' is not a regular file with link count 1", full_core_basename); return -1; } if (ftruncate(user_core_fd, 0) != 0) { /* perror first, otherwise unlink may trash errno */ perror_msg("Can't truncate '%s' to size 0", full_core_basename); unlink(core_basename); return -1; } return user_core_fd; } static bool dump_fd_info(const char *dest_filename, char *source_filename, int source_base_ofs, uid_t uid, gid_t gid) { FILE *fp = fopen(dest_filename, "w"); if (!fp) return false; unsigned fd = 0; while (fd <= 99999) /* paranoia check */ { sprintf(source_filename + source_base_ofs, "fd/%u", fd); char *name = malloc_readlink(source_filename); if (!name) break; fprintf(fp, "%u:%s\n", fd, name); free(name); sprintf(source_filename + source_base_ofs, "fdinfo/%u", fd); fd++; FILE *in = fopen(source_filename, "r"); if (!in) continue; char buf[128]; while (fgets(buf, sizeof(buf)-1, in)) { /* in case the line is not terminated, terminate it */ char *eol = strchrnul(buf, '\n'); eol[0] = '\n'; eol[1] = '\0'; fputs(buf, fp); } fclose(in); } const int dest_fd = fileno(fp); if (fchown(dest_fd, uid, gid) < 0) { perror_msg("Can't change '%s' ownership to %lu:%lu", dest_filename, (long)uid, (long)gid); fclose(fp); unlink(dest_filename); return false; } fclose(fp); return true; } /* Like xopen, but on error, unlocks and deletes dd and user core */ static int create_or_die(const char *filename) { int fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, DEFAULT_DUMP_DIR_MODE); if (fd >= 0) { IGNORE_RESULT(fchown(fd, dd->dd_uid, dd->dd_gid)); return fd; } int sv_errno = errno; if (dd) dd_delete(dd); if (user_core_fd >= 0) { xchdir(user_pwd); unlink(core_basename); } errno = sv_errno; perror_msg_and_die("Can't open '%s'", filename); } int main(int argc, char** argv) { /* Kernel starts us with all fd's closed. * But it's dangerous: * fprintf(stderr) can dump messages into random fds, etc. * Ensure that if any of fd 0,1,2 is closed, we open it to /dev/null. */ int fd = xopen("/dev/null", O_RDWR); while (fd < 2) fd = xdup(fd); if (fd > 2) close(fd); if (argc < 8) { /* percent specifier: %s %c %p %u %g %t %e %h */ /* argv: [0] [1] [2] [3] [4] [5] [6] [7] [8]*/ error_msg_and_die("Usage: %s SIGNO CORE_SIZE_LIMIT PID UID GID TIME BINARY_NAME [HOSTNAME]", argv[0]); } /* Not needed on 2.6.30. * At least 2.6.18 has a bug where * argv[1] = "SIGNO CORE_SIZE_LIMIT PID ..." * argv[2] = "CORE_SIZE_LIMIT PID ..." * and so on. Fixing it: */ if (strchr(argv[1], ' ')) { int i; for (i = 1; argv[i]; i++) { strchrnul(argv[i], ' ')[0] = '\0'; } } logmode = LOGMODE_JOURNAL; /* Parse abrt.conf */ load_abrt_conf(); /* ... and plugins/CCpp.conf */ bool setting_MakeCompatCore; bool setting_SaveBinaryImage; { map_string_t *settings = new_map_string(); load_abrt_plugin_conf_file("CCpp.conf", settings); const char *value; value = get_map_string_item_or_NULL(settings, "MakeCompatCore"); setting_MakeCompatCore = value && string_to_bool(value); value = get_map_string_item_or_NULL(settings, "SaveBinaryImage"); setting_SaveBinaryImage = value && string_to_bool(value); value = get_map_string_item_or_NULL(settings, "VerboseLog"); if (value) g_verbose = xatoi_positive(value); free_map_string(settings); } errno = 0; const char* signal_str = argv[1]; int signal_no = xatoi_positive(signal_str); off_t ulimit_c = strtoull(argv[2], NULL, 10); if (ulimit_c < 0) /* unlimited? */ { /* set to max possible >0 value */ ulimit_c = ~((off_t)1 << (sizeof(off_t)*8-1)); } const char *pid_str = argv[3]; pid_t pid = xatoi_positive(argv[3]); uid_t uid = xatoi_positive(argv[4]); if (errno || pid <= 0) { perror_msg_and_die("PID '%s' or limit '%s' is bogus", argv[3], argv[2]); } { char *s = xmalloc_fopen_fgetline_fclose(VAR_RUN"/abrt/saved_core_pattern"); /* If we have a saved pattern and it's not a "|PROG ARGS" thing... */ if (s && s[0] != '|') core_basename = s; else free(s); } struct utsname uts; if (!argv[8]) /* no HOSTNAME? */ { uname(&uts); argv[8] = uts.nodename; } char path[PATH_MAX]; int src_fd_binary = -1; char *executable = get_executable(pid, setting_SaveBinaryImage ? &src_fd_binary : NULL); if (executable && strstr(executable, "/abrt-hook-ccpp")) { error_msg_and_die("PID %lu is '%s', not dumping it to avoid recursion", (long)pid, executable); } user_pwd = get_cwd(pid); /* may be NULL on error */ log_notice("user_pwd:'%s'", user_pwd); sprintf(path, "/proc/%lu/status", (long)pid); proc_pid_status = xmalloc_xopen_read_close(path, /*maxsz:*/ NULL); uid_t fsuid = uid; uid_t tmp_fsuid = get_fsuid(); int suid_policy = dump_suid_policy(); if (tmp_fsuid != uid) { /* use root for suided apps unless it's explicitly set to UNSAFE */ fsuid = 0; if (suid_policy == DUMP_SUID_UNSAFE) { fsuid = tmp_fsuid; } } /* Open a fd to compat coredump, if requested and is possible */ if (setting_MakeCompatCore && ulimit_c != 0) /* note: checks "user_pwd == NULL" inside; updates core_basename */ user_core_fd = open_user_core(uid, fsuid, pid, &argv[1]); if (executable == NULL) { /* readlink on /proc/$PID/exe failed, don't create abrt dump dir */ error_msg("Can't read /proc/%lu/exe link", (long)pid); goto create_user_core; } const char *signame = NULL; switch (signal_no) { case SIGILL : signame = "ILL" ; break; case SIGFPE : signame = "FPE" ; break; case SIGSEGV: signame = "SEGV"; break; case SIGBUS : signame = "BUS" ; break; //Bus error (bad memory access) case SIGABRT: signame = "ABRT"; break; //usually when abort() was called // We have real-world reports from users who see buggy programs // dying with SIGTRAP, uncommented it too: case SIGTRAP: signame = "TRAP"; break; //Trace/breakpoint trap // These usually aren't caused by bugs: //case SIGQUIT: signame = "QUIT"; break; //Quit from keyboard //case SIGSYS : signame = "SYS" ; break; //Bad argument to routine (SVr4) //case SIGXCPU: signame = "XCPU"; break; //CPU time limit exceeded (4.2BSD) //case SIGXFSZ: signame = "XFSZ"; break; //File size limit exceeded (4.2BSD) default: goto create_user_core; // not a signal we care about } if (!daemon_is_ok()) { /* not an error, exit with exit code 0 */ log("abrtd is not running. If it crashed, " "/proc/sys/kernel/core_pattern contains a stale value, " "consider resetting it to 'core'" ); goto create_user_core; } if (g_settings_nMaxCrashReportsSize > 0) { /* If free space is less than 1/4 of MaxCrashReportsSize... */ if (low_free_space(g_settings_nMaxCrashReportsSize, g_settings_dump_location)) goto create_user_core; } /* Check /var/tmp/abrt/last-ccpp marker, do not dump repeated crashes * if they happen too often. Else, write new marker value. */ snprintf(path, sizeof(path), "%s/last-ccpp", g_settings_dump_location); if (check_recent_crash_file(path, executable)) { /* It is a repeating crash */ goto create_user_core; } const char *last_slash = strrchr(executable, '/'); if (last_slash && strncmp(++last_slash, "abrt", 4) == 0) { /* If abrtd/abrt-foo crashes, we don't want to create a _directory_, * since that can make new copy of abrtd to process it, * and maybe crash again... * Unlike dirs, mere files are ignored by abrtd. */ snprintf(path, sizeof(path), "%s/%s-coredump", g_settings_dump_location, last_slash); int abrt_core_fd = xopen3(path, O_WRONLY | O_CREAT | O_TRUNC, 0600); off_t core_size = copyfd_eof(STDIN_FILENO, abrt_core_fd, COPYFD_SPARSE); if (core_size < 0 || fsync(abrt_core_fd) != 0) { unlink(path); /* copyfd_eof logs the error including errno string, * but it does not log file name */ error_msg_and_die("Error saving '%s'", path); } log("Saved core dump of pid %lu (%s) to %s (%llu bytes)", (long)pid, executable, path, (long long)core_size); return 0; } unsigned path_len = snprintf(path, sizeof(path), "%s/ccpp-%s-%lu.new", g_settings_dump_location, iso_date_string(NULL), (long)pid); if (path_len >= (sizeof(path) - sizeof("/"FILENAME_COREDUMP))) { goto create_user_core; } /* use fsuid instead of uid, so we don't expose any sensitive * information of suided app in /var/tmp/abrt */ dd = dd_create(path, fsuid, DEFAULT_DUMP_DIR_MODE); if (dd) { char *rootdir = get_rootdir(pid); dd_create_basic_files(dd, fsuid, (rootdir && strcmp(rootdir, "/") != 0) ? rootdir : NULL); char source_filename[sizeof("/proc/%lu/somewhat_long_name") + sizeof(long)*3]; int source_base_ofs = sprintf(source_filename, "/proc/%lu/smaps", (long)pid); source_base_ofs -= strlen("smaps"); char *dest_filename = concat_path_file(dd->dd_dirname, "also_somewhat_longish_name"); char *dest_base = strrchr(dest_filename, '/') + 1; // Disabled for now: /proc/PID/smaps tends to be BIG, // and not much more informative than /proc/PID/maps: //copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL); strcpy(source_filename + source_base_ofs, "maps"); strcpy(dest_base, FILENAME_MAPS); copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL); strcpy(source_filename + source_base_ofs, "limits"); strcpy(dest_base, FILENAME_LIMITS); copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL); strcpy(source_filename + source_base_ofs, "cgroup"); strcpy(dest_base, FILENAME_CGROUP); copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL); strcpy(dest_base, FILENAME_OPEN_FDS); dump_fd_info(dest_filename, source_filename, source_base_ofs, dd->dd_uid, dd->dd_gid); free(dest_filename); dd_save_text(dd, FILENAME_ANALYZER, "CCpp"); dd_save_text(dd, FILENAME_TYPE, "CCpp"); dd_save_text(dd, FILENAME_EXECUTABLE, executable); dd_save_text(dd, FILENAME_PID, pid_str); dd_save_text(dd, FILENAME_PROC_PID_STATUS, proc_pid_status); if (user_pwd) dd_save_text(dd, FILENAME_PWD, user_pwd); if (rootdir) { if (strcmp(rootdir, "/") != 0) dd_save_text(dd, FILENAME_ROOTDIR, rootdir); } char *reason = xasprintf("%s killed by SIG%s", last_slash, signame ? signame : signal_str); dd_save_text(dd, FILENAME_REASON, reason); free(reason); char *cmdline = get_cmdline(pid); dd_save_text(dd, FILENAME_CMDLINE, cmdline ? : ""); free(cmdline); char *environ = get_environ(pid); dd_save_text(dd, FILENAME_ENVIRON, environ ? : ""); free(environ); char *fips_enabled = xmalloc_fopen_fgetline_fclose("/proc/sys/crypto/fips_enabled"); if (fips_enabled) { if (strcmp(fips_enabled, "0") != 0) dd_save_text(dd, "fips_enabled", fips_enabled); free(fips_enabled); } dd_save_text(dd, FILENAME_ABRT_VERSION, VERSION); if (src_fd_binary > 0) { strcpy(path + path_len, "/"FILENAME_BINARY); int dst_fd = create_or_die(path); off_t sz = copyfd_eof(src_fd_binary, dst_fd, COPYFD_SPARSE); if (fsync(dst_fd) != 0 || close(dst_fd) != 0 || sz < 0) { dd_delete(dd); error_msg_and_die("Error saving '%s'", path); } close(src_fd_binary); } strcpy(path + path_len, "/"FILENAME_COREDUMP); int abrt_core_fd = create_or_die(path); /* We write both coredumps at once. * We can't write user coredump first, since it might be truncated * and thus can't be copied and used as abrt coredump; * and if we write abrt coredump first and then copy it as user one, * then we have a race when process exits but coredump does not exist yet: * $ echo -e '#include<signal.h>\nmain(){raise(SIGSEGV);}' | gcc -o test -x c - * $ rm -f core*; ulimit -c unlimited; ./test; ls -l core* * 21631 Segmentation fault (core dumped) ./test * ls: cannot access core*: No such file or directory <=== BAD */ off_t core_size = copyfd_sparse(STDIN_FILENO, abrt_core_fd, user_core_fd, ulimit_c); if (fsync(abrt_core_fd) != 0 || close(abrt_core_fd) != 0 || core_size < 0) { unlink(path); dd_delete(dd); if (user_core_fd >= 0) { xchdir(user_pwd); unlink(core_basename); } /* copyfd_sparse logs the error including errno string, * but it does not log file name */ error_msg_and_die("Error writing '%s'", path); } if (user_core_fd >= 0 /* error writing user coredump? */ && (fsync(user_core_fd) != 0 || close(user_core_fd) != 0 /* user coredump is too big? */ || (ulimit_c == 0 /* paranoia */ || core_size > ulimit_c) ) ) { /* nuke it (silently) */ xchdir(user_pwd); unlink(core_basename); } /* Because of #1211835 and #1126850 */ #if 0 /* Save JVM crash log if it exists. (JVM's coredump per se * is nearly useless for JVM developers) */ { char *java_log = xasprintf("/tmp/jvm-%lu/hs_error.log", (long)pid); int src_fd = open(java_log, O_RDONLY); free(java_log); /* If we couldn't open the error log in /tmp directory we can try to * read the log from the current directory. It may produce AVC, it * may produce some error log but all these are expected. */ if (src_fd < 0) { java_log = xasprintf("%s/hs_err_pid%lu.log", user_pwd, (long)pid); src_fd = open(java_log, O_RDONLY); free(java_log); } if (src_fd >= 0) { strcpy(path + path_len, "/hs_err.log"); int dst_fd = create_or_die(path); off_t sz = copyfd_eof(src_fd, dst_fd, COPYFD_SPARSE); if (close(dst_fd) != 0 || sz < 0) { dd_delete(dd); error_msg_and_die("Error saving '%s'", path); } close(src_fd); } } #endif /* We close dumpdir before we start catering for crash storm case. * Otherwise, delete_dump_dir's from other concurrent * CCpp's won't be able to delete our dump (their delete_dump_dir * will wait for us), and we won't be able to delete their dumps. * Classic deadlock. */ dd_close(dd); path[path_len] = '\0'; /* path now contains only directory name */ char *newpath = xstrndup(path, path_len - (sizeof(".new")-1)); if (rename(path, newpath) == 0) strcpy(path, newpath); free(newpath); log("Saved core dump of pid %lu (%s) to %s (%llu bytes)", (long)pid, executable, path, (long long)core_size); notify_new_path(path); /* rhbz#539551: "abrt going crazy when crashing process is respawned" */ if (g_settings_nMaxCrashReportsSize > 0) { /* x1.25 and round up to 64m: go a bit up, so that usual in-daemon trimming * kicks in first, and we don't "fight" with it: */ unsigned maxsize = g_settings_nMaxCrashReportsSize + g_settings_nMaxCrashReportsSize / 4; maxsize |= 63; trim_problem_dirs(g_settings_dump_location, maxsize * (double)(1024*1024), path); } free(rootdir); return 0; } /* We didn't create abrt dump, but may need to create compat coredump */ create_user_core: if (user_core_fd >= 0) { off_t core_size = copyfd_size(STDIN_FILENO, user_core_fd, ulimit_c, COPYFD_SPARSE); if (fsync(user_core_fd) != 0 || close(user_core_fd) != 0 || core_size < 0) { /* perror first, otherwise unlink may trash errno */ perror_msg("Error writing '%s'", full_core_basename); xchdir(user_pwd); unlink(core_basename); return 1; } if (ulimit_c == 0 || core_size > ulimit_c) { xchdir(user_pwd); unlink(core_basename); return 1; } log("Saved core dump of pid %lu to %s (%llu bytes)", (long)pid, full_core_basename, (long long)core_size); } return 0; }
./CrossVul/dataset_final_sorted/CWE-59/c/good_1590_0
crossvul-cpp_data_good_436_12
/* * Soft: Keepalived is a failover program for the LVS project * <www.linuxvirtualserver.org>. It monitor & manipulate * a loadbalanced server pool using multi-layer checks. * * Part: General program utils. * * Author: Alexandre Cassen, <acassen@linux-vs.org> * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. * * Copyright (C) 2001-2017 Alexandre Cassen, <acassen@gmail.com> */ #include "config.h" /* System includes */ #include <string.h> #include <unistd.h> #include <fcntl.h> #include <stdlib.h> #include <netdb.h> #include <arpa/inet.h> #include <sys/utsname.h> #include <stdint.h> #include <errno.h> #ifdef _WITH_PERF_ #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/epoll.h> #include <sys/inotify.h> #endif #if !defined _HAVE_LIBIPTC_ || defined _LIBIPTC_DYNAMIC_ #include <signal.h> #include <sys/wait.h> #endif #ifdef _WITH_STACKTRACE_ #include <sys/stat.h> #include <execinfo.h> #include <memory.h> #endif /* Local includes */ #include "utils.h" #include "memory.h" #include "utils.h" #include "signals.h" #include "bitops.h" #include "parser.h" #if !defined _HAVE_LIBIPTC_ || defined _LIBIPTC_DYNAMIC_ || defined _WITH_STACKTRACE_ || defined _WITH_PERF_ #include "logger.h" #endif #if !defined _HAVE_LIBIPTC_ || defined _LIBIPTC_DYNAMIC_ #include "process.h" #endif /* global vars */ unsigned long debug = 0; /* Display a buffer into a HEXA formated output */ void dump_buffer(char *buff, size_t count, FILE* fp, int indent) { size_t i, j, c; bool printnext = true; if (count % 16) c = count + (16 - count % 16); else c = count; for (i = 0; i < c; i++) { if (printnext) { printnext = false; fprintf(fp, "%*s%.4zu ", indent, "", i & 0xffff); } if (i < count) fprintf(fp, "%3.2x", buff[i] & 0xff); else fprintf(fp, " "); if (!((i + 1) % 8)) { if ((i + 1) % 16) fprintf(fp, " -"); else { fprintf(fp, " "); for (j = i - 15; j <= i; j++) if (j < count) { if ((buff[j] & 0xff) >= 0x20 && (buff[j] & 0xff) <= 0x7e) fprintf(fp, "%c", buff[j] & 0xff); else fprintf(fp, "."); } else fprintf(fp, " "); fprintf(fp, "\n"); printnext = true; } } } } #ifdef _WITH_STACKTRACE_ void write_stacktrace(const char *file_name, const char *str) { int fd; void *buffer[100]; int nptrs; int i; char **strs; nptrs = backtrace(buffer, 100); if (file_name) { fd = open(file_name, O_WRONLY | O_APPEND | O_CREAT | O_NOFOLLOW, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH); if (str) dprintf(fd, "%s\n", str); backtrace_symbols_fd(buffer, nptrs, fd); if (write(fd, "\n", 1) != 1) { /* We don't care, but this stops a warning on Ubuntu */ } close(fd); } else { if (str) log_message(LOG_INFO, "%s", str); strs = backtrace_symbols(buffer, nptrs); if (strs == NULL) { log_message(LOG_INFO, "Unable to get stack backtrace"); return; } /* We don't need the call to this function, or the first two entries on the stack */ for (i = 1; i < nptrs - 2; i++) log_message(LOG_INFO, " %s", strs[i]); free(strs); } } #endif char * make_file_name(const char *name, const char *prog, const char *namespace, const char *instance) { const char *extn_start; const char *dir_end; size_t len; char *file_name; if (!name) return NULL; len = strlen(name); if (prog) len += strlen(prog) + 1; if (namespace) len += strlen(namespace) + 1; if (instance) len += strlen(instance) + 1; file_name = MALLOC(len + 1); dir_end = strrchr(name, '/'); extn_start = strrchr(dir_end ? dir_end : name, '.'); strncpy(file_name, name, extn_start ? (size_t)(extn_start - name) : len); if (prog) { strcat(file_name, "_"); strcat(file_name, prog); } if (namespace) { strcat(file_name, "_"); strcat(file_name, namespace); } if (instance) { strcat(file_name, "_"); strcat(file_name, instance); } if (extn_start) strcat(file_name, extn_start); return file_name; } #ifdef _WITH_PERF_ void run_perf(const char *process, const char *network_namespace, const char *instance_name) { int ret; pid_t pid; char *orig_name = NULL; char *new_name; const char *perf_name = "perf.data"; int in = -1; int ep = -1; do { orig_name = MALLOC(PATH_MAX); if (!getcwd(orig_name, PATH_MAX)) { log_message(LOG_INFO, "Unable to get cwd"); break; } #ifdef IN_CLOEXEC in = inotify_init1(IN_CLOEXEC | IN_NONBLOCK); #else if ((in = inotify_init()) != -1) { fcntl(in, F_SETFD, FD_CLOEXEC | fcntl(n, F_GETFD)); fcntl(in, F_SETFL, O_NONBLOCK | fcntl(n, F_GETFL)); } #endif if (in == -1) { log_message(LOG_INFO, "inotify_init failed %d - %m", errno); break; } if (inotify_add_watch(in, orig_name, IN_CREATE) == -1) { log_message(LOG_INFO, "inotify_add_watch of %s failed %d - %m", orig_name, errno); break; } pid = fork(); if (pid == -1) { log_message(LOG_INFO, "fork() for perf failed"); break; } /* Child */ if (!pid) { char buf[9]; snprintf(buf, sizeof buf, "%d", getppid()); execlp("perf", "perf", "record", "-p", buf, "-q", "-g", "--call-graph", "fp", NULL); exit(0); } /* Parent */ char buf[sizeof(struct inotify_event) + NAME_MAX + 1]; struct inotify_event *ie = (struct inotify_event*)buf; struct epoll_event ee = { .events = EPOLLIN, .data.fd = in }; if ((ep = epoll_create(1)) == -1) { log_message(LOG_INFO, "perf epoll_create failed errno %d - %m", errno); break; } if (epoll_ctl(ep, EPOLL_CTL_ADD, in, &ee) == -1) { log_message(LOG_INFO, "perf epoll_ctl failed errno %d - %m", errno); break; } do { ret = epoll_wait(ep, &ee, 1, 1000); if (ret == 0) { log_message(LOG_INFO, "Timed out waiting for creation of %s", perf_name); break; } else if (ret == -1) { if (errno == EINTR) continue; log_message(LOG_INFO, "perf epoll returned errno %d - %m", errno); break; } ret = read(in, buf, sizeof(buf)); if (ret == -1) { if (errno == EINTR) continue; log_message(LOG_INFO, "perf inotify read returned errno %d %m", errno); break; } if (ret < (int)sizeof(*ie)) { log_message(LOG_INFO, "read returned %d", ret); break; } if (!(ie->mask & IN_CREATE)) { log_message(LOG_INFO, "mask is 0x%x", ie->mask); continue; } if (!ie->len) { log_message(LOG_INFO, "perf inotify read returned no len"); continue; } if (strcmp(ie->name, perf_name)) continue; /* Rename the /perf.data file */ strcat(orig_name, perf_name); new_name = make_file_name(orig_name, process, #if HAVE_DECL_CLONE_NEWNET network_namespace, #else NULL, #endif instance_name); if (rename(orig_name, new_name)) log_message(LOG_INFO, "Rename %s to %s failed - %m (%d)", orig_name, new_name, errno); FREE(new_name); } while (false); } while (false); if (ep != -1) close(ep); if (in != -1) close(in); if (orig_name) FREE(orig_name); } #endif /* Compute a checksum */ uint16_t in_csum(const uint16_t *addr, size_t len, uint32_t csum, uint32_t *acc) { register size_t nleft = len; const uint16_t *w = addr; register uint16_t answer; register uint32_t sum = csum; /* * Our algorithm is simple, using a 32 bit accumulator (sum), * we add sequential 16 bit words to it, and at the end, fold * back all the carry bits from the top 16 bits into the lower * 16 bits. */ while (nleft > 1) { sum += *w++; nleft -= 2; } /* mop up an odd byte, if necessary */ if (nleft == 1) sum += htons(*(u_char *) w << 8); if (acc) *acc = sum; /* * add back carry outs from top 16 bits to low 16 bits */ sum = (sum >> 16) + (sum & 0xffff); /* add hi 16 to low 16 */ sum += (sum >> 16); /* add carry */ answer = (~sum & 0xffff); /* truncate to 16 bits */ return (answer); } /* IP network to ascii representation */ char * inet_ntop2(uint32_t ip) { static char buf[16]; unsigned char *bytep; bytep = (unsigned char *) &(ip); sprintf(buf, "%d.%d.%d.%d", bytep[0], bytep[1], bytep[2], bytep[3]); return buf; } #ifdef _INCLUDE_UNUSED_CODE_ /* * IP network to ascii representation. To use * for multiple IP address convertion into the same call. */ char * inet_ntoa2(uint32_t ip, char *buf) { unsigned char *bytep; bytep = (unsigned char *) &(ip); sprintf(buf, "%d.%d.%d.%d", bytep[0], bytep[1], bytep[2], bytep[3]); return buf; } #endif /* IP string to network range representation. */ bool inet_stor(const char *addr, uint32_t *range_end) { const char *cp; char *endptr; unsigned long range; int family = strchr(addr, ':') ? AF_INET6 : AF_INET; char *warn = ""; #ifndef _STRICT_CONFIG_ if (!__test_bit(CONFIG_TEST_BIT, &debug)) warn = "WARNING - "; #endif /* Return UINT32_MAX to indicate no range */ if (!(cp = strchr(addr, '-'))) { *range_end = UINT32_MAX; return true; } errno = 0; range = strtoul(cp + 1, &endptr, family == AF_INET6 ? 16 : 10); *range_end = range; if (*endptr) report_config_error(CONFIG_INVALID_NUMBER, "%sVirtual server group range '%s' has extra characters at end '%s'", warn, addr, endptr); else if (errno == ERANGE || (family == AF_INET6 && range > 0xffff) || (family == AF_INET && range > 255)) { report_config_error(CONFIG_INVALID_NUMBER, "Virtual server group range '%s' end '%s' too large", addr, cp + 1); /* Indicate error */ return false; } else return true; #ifdef _STRICT_CONFIG_ return false; #else return !__test_bit(CONFIG_TEST_BIT, &debug); #endif } /* Domain to sockaddr_storage */ int domain_stosockaddr(const char *domain, const char *port, struct sockaddr_storage *addr) { struct addrinfo *res = NULL; unsigned port_num; if (port) { if (!read_unsigned(port, &port_num, 1, 65535, true)) { addr->ss_family = AF_UNSPEC; return -1; } } if (getaddrinfo(domain, NULL, NULL, &res) != 0 || !res) { addr->ss_family = AF_UNSPEC; return -1; } addr->ss_family = (sa_family_t)res->ai_family; if (addr->ss_family == AF_INET6) { struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)addr; *addr6 = *(struct sockaddr_in6 *)res->ai_addr; if (port) addr6->sin6_port = htons(port_num); } else { struct sockaddr_in *addr4 = (struct sockaddr_in *)addr; *addr4 = *(struct sockaddr_in *)res->ai_addr; if (port) addr4->sin_port = htons(port_num); } freeaddrinfo(res); return 0; } /* IP string to sockaddr_storage */ int inet_stosockaddr(char *ip, const char *port, struct sockaddr_storage *addr) { void *addr_ip; char *cp; char sav_cp; unsigned port_num; int res; addr->ss_family = (strchr(ip, ':')) ? AF_INET6 : AF_INET; if (port) { if (!read_unsigned(port, &port_num, 1, 65535, true)) { addr->ss_family = AF_UNSPEC; return -1; } } if (addr->ss_family == AF_INET6) { struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *) addr; if (port) addr6->sin6_port = htons(port_num); addr_ip = &addr6->sin6_addr; } else { struct sockaddr_in *addr4 = (struct sockaddr_in *) addr; if (port) addr4->sin_port = htons(port_num); addr_ip = &addr4->sin_addr; } /* remove range and mask stuff */ if ((cp = strchr(ip, '-')) || (cp = strchr(ip, '/'))) { sav_cp = *cp; *cp = 0; } res = inet_pton(addr->ss_family, ip, addr_ip); /* restore range and mask stuff */ if (cp) *cp = sav_cp; if (!res) { addr->ss_family = AF_UNSPEC; return -1; } return 0; } /* IPv4 to sockaddr_storage */ void inet_ip4tosockaddr(struct in_addr *sin_addr, struct sockaddr_storage *addr) { struct sockaddr_in *addr4 = (struct sockaddr_in *) addr; addr4->sin_family = AF_INET; addr4->sin_addr = *sin_addr; } /* IPv6 to sockaddr_storage */ void inet_ip6tosockaddr(struct in6_addr *sin_addr, struct sockaddr_storage *addr) { struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *) addr; addr6->sin6_family = AF_INET6; addr6->sin6_addr = *sin_addr; } /* IP network to string representation */ static char * inet_sockaddrtos2(struct sockaddr_storage *addr, char *addr_str) { void *addr_ip; if (addr->ss_family == AF_INET6) { struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *) addr; addr_ip = &addr6->sin6_addr; } else { struct sockaddr_in *addr4 = (struct sockaddr_in *) addr; addr_ip = &addr4->sin_addr; } if (!inet_ntop(addr->ss_family, addr_ip, addr_str, INET6_ADDRSTRLEN)) return NULL; return addr_str; } char * inet_sockaddrtos(struct sockaddr_storage *addr) { static char addr_str[INET6_ADDRSTRLEN]; inet_sockaddrtos2(addr, addr_str); return addr_str; } uint16_t inet_sockaddrport(struct sockaddr_storage *addr) { uint16_t port; if (addr->ss_family == AF_INET6) { struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *) addr; port = addr6->sin6_port; } else { /* Note: this might be AF_UNSPEC if it is the sequence number of * a virtual server in a virtual server group */ struct sockaddr_in *addr4 = (struct sockaddr_in *) addr; port = addr4->sin_port; } return port; } char * inet_sockaddrtopair(struct sockaddr_storage *addr) { char addr_str[INET6_ADDRSTRLEN]; static char ret[sizeof(addr_str) + 8]; /* '[' + addr_str + ']' + ':' + 'nnnnn' */ inet_sockaddrtos2(addr, addr_str); snprintf(ret, sizeof(ret), "[%s]:%d" , addr_str , ntohs(inet_sockaddrport(addr))); return ret; } char * inet_sockaddrtotrio(struct sockaddr_storage *addr, uint16_t proto) { char addr_str[INET6_ADDRSTRLEN]; static char ret[sizeof(addr_str) + 13]; /* '[' + addr_str + ']' + ':' + 'sctp' + ':' + 'nnnnn' */ char *proto_str = proto == IPPROTO_TCP ? "tcp" : proto == IPPROTO_UDP ? "udp" : proto == IPPROTO_SCTP ? "sctp" : proto == 0 ? "none" : "?"; inet_sockaddrtos2(addr, addr_str); snprintf(ret, sizeof(ret), "[%s]:%s:%d" ,addr_str, proto_str, ntohs(inet_sockaddrport(addr))); return ret; } uint32_t inet_sockaddrip4(struct sockaddr_storage *addr) { if (addr->ss_family != AF_INET) return 0xffffffff; return ((struct sockaddr_in *) addr)->sin_addr.s_addr; } int inet_sockaddrip6(struct sockaddr_storage *addr, struct in6_addr *ip6) { if (addr->ss_family != AF_INET6) return -1; *ip6 = ((struct sockaddr_in6 *) addr)->sin6_addr; return 0; } /* IPv6 address compare */ int inet_inaddrcmp(const int family, const void *a, const void *b) { int64_t addr_diff; if (family == AF_INET) { addr_diff = (int64_t)ntohl(*((const uint32_t *) a)) - (int64_t)ntohl(*((const uint32_t *) b)); if (addr_diff > 0) return 1; if (addr_diff < 0) return -1; return 0; } if (family == AF_INET6) { int i; for (i = 0; i < 4; i++ ) { addr_diff = (int64_t)ntohl(((const uint32_t *) (a))[i]) - (int64_t)ntohl(((const uint32_t *) (b))[i]); if (addr_diff > 0) return 1; if (addr_diff < 0) return -1; } return 0; } return -2; } int inet_sockaddrcmp(const struct sockaddr_storage *a, const struct sockaddr_storage *b) { if (a->ss_family != b->ss_family) return -2; if (a->ss_family == AF_INET) return inet_inaddrcmp(a->ss_family, &((struct sockaddr_in *) a)->sin_addr, &((struct sockaddr_in *) b)->sin_addr); if (a->ss_family == AF_INET6) return inet_inaddrcmp(a->ss_family, &((struct sockaddr_in6 *) a)->sin6_addr, &((struct sockaddr_in6 *) b)->sin6_addr); return 0; } #ifdef _INCLUDE_UNUSED_CODE_ /* * IP string to network representation * Highly inspired from Paul Vixie code. */ int inet_ston(const char *addr, uint32_t * dst) { static char digits[] = "0123456789"; int saw_digit, octets, ch; u_char tmp[INADDRSZ], *tp; saw_digit = 0; octets = 0; *(tp = tmp) = 0; while ((ch = *addr++) != '\0' && ch != '/' && ch != '-') { const char *pch; if ((pch = strchr(digits, ch)) != NULL) { u_int new = *tp * 10 + (pch - digits); if (new > 255) return 0; *tp = new; if (!saw_digit) { if (++octets > 4) return 0; saw_digit = 1; } } else if (ch == '.' && saw_digit) { if (octets == 4) return 0; *++tp = 0; saw_digit = 0; } else return 0; } if (octets < 4) return 0; memcpy(dst, tmp, INADDRSZ); return 1; } /* * Return broadcast address from network and netmask. */ uint32_t inet_broadcast(uint32_t network, uint32_t netmask) { return 0xffffffff - netmask + network; } /* * Convert CIDR netmask notation to long notation. */ uint32_t inet_cidrtomask(uint8_t cidr) { uint32_t mask = 0; int b; for (b = 0; b < cidr; b++) mask |= (1 << (31 - b)); return ntohl(mask); } #endif /* Getting localhost official canonical name */ char * get_local_name(void) { struct utsname name; struct addrinfo hints, *res = NULL; char *canonname = NULL; size_t len = 0; memset(&hints, 0, sizeof(struct addrinfo)); hints.ai_flags = AI_CANONNAME; if (uname(&name) < 0) return NULL; if (getaddrinfo(name.nodename, NULL, &hints, &res) != 0) return NULL; if (res && res->ai_canonname) { len = strlen(res->ai_canonname); canonname = MALLOC(len + 1); if (canonname) { memcpy(canonname, res->ai_canonname, len); } } freeaddrinfo(res); return canonname; } /* String compare with NULL string handling */ bool string_equal(const char *str1, const char *str2) { if (!str1 && !str2) return true; if (!str1 != !str2) return false; return !strcmp(str1, str2); } /* We need to use O_NOFOLLOW if opening a file for write, so that a non privileged user can't * create a symbolic link from the path to a system file and cause a system file to be overwritten. */ FILE *fopen_safe(const char *path, const char *mode) { int fd; FILE *file; int flags = O_NOFOLLOW | O_CREAT; if (mode[0] == 'r') return fopen(path, mode); if (mode[0] != 'a' && mode[0] != 'w') return NULL; if (mode[1] && (mode[1] != '+' || mode[2])) return NULL; if (mode[0] == 'w') flags |= O_TRUNC; else flags |= O_APPEND; if (mode[1]) flags |= O_RDWR; else flags |= O_WRONLY; fd = open(path, flags, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH); if (fd == -1) return NULL; file = fdopen (fd, "w"); if (!file) { close(fd); return NULL; } return file; } void set_std_fd(bool force) { int fd; if (force || __test_bit(DONT_FORK_BIT, &debug)) { fd = open("/dev/null", O_RDWR); if (fd != -1) { dup2(fd, STDIN_FILENO); dup2(fd, STDOUT_FILENO); dup2(fd, STDERR_FILENO); if (fd > STDERR_FILENO) close(fd); } } signal_fd_close(STDERR_FILENO+1); } void close_std_fd(void) { close(STDIN_FILENO); close(STDOUT_FILENO); close(STDERR_FILENO); } #if !defined _HAVE_LIBIPTC_ || defined _LIBIPTC_DYNAMIC_ int fork_exec(char **argv) { pid_t pid; int status; struct sigaction act, old_act; int res = 0; act.sa_handler = SIG_DFL; sigemptyset(&act.sa_mask); act.sa_flags = 0; sigaction(SIGCHLD, &act, &old_act); if (log_file_name) flush_log_file(); pid = local_fork(); if (pid < 0) res = -1; else if (pid == 0) { /* Child */ set_std_fd(false); signal_handler_script(); execvp(*argv, argv); exit(EXIT_FAILURE); } else { /* Parent */ while (waitpid(pid, &status, 0) != pid); if (!WIFEXITED(status) || WEXITSTATUS(status) != EXIT_SUCCESS) res = -1; } sigaction(SIGCHLD, &old_act, NULL); return res; } #endif #if defined _WITH_VRRP_ || defined _WITH_BFD_ int open_pipe(int pipe_arr[2]) { /* Open pipe */ #ifdef HAVE_PIPE2 if (pipe2(pipe_arr, O_CLOEXEC | O_NONBLOCK) == -1) #else if (pipe(pipe_arr) == -1) #endif return -1; #ifndef HAVE_PIPE2 fcntl(pipe_arr[0], F_SETFL, O_NONBLOCK | fcntl(pipe_arr[0], F_GETFL)); fcntl(pipe_arr[1], F_SETFL, O_NONBLOCK | fcntl(pipe_arr[1], F_GETFL)); fcntl(pipe_arr[0], F_SETFD, FD_CLOEXEC | fcntl(pipe_arr[0], F_GETFD)); fcntl(pipe_arr[1], F_SETFD, FD_CLOEXEC | fcntl(pipe_arr[1], F_GETFD)); #endif return 0; } #endif
./CrossVul/dataset_final_sorted/CWE-59/c/good_436_12
crossvul-cpp_data_bad_1506_1
#include <gio/gio.h> #include <stdlib.h> #include <sys/types.h> #include <pwd.h> #include <grp.h> #include "libabrt.h" #include "abrt-polkit.h" #include "abrt_glib.h" #include <libreport/dump_dir.h> #include "problem_api.h" static GMainLoop *loop; static guint g_timeout_source; /* default, settable with -t: */ static unsigned g_timeout_value = 120; /* ---------------------------------------------------------------------------------------------------- */ static GDBusNodeInfo *introspection_data = NULL; /* Introspection data for the service we are exporting */ static const gchar introspection_xml[] = "<node>" " <interface name='"ABRT_DBUS_IFACE"'>" " <method name='NewProblem'>" " <arg type='a{ss}' name='problem_data' direction='in'/>" " <arg type='s' name='problem_id' direction='out'/>" " </method>" " <method name='GetProblems'>" " <arg type='as' name='response' direction='out'/>" " </method>" " <method name='GetAllProblems'>" " <arg type='as' name='response' direction='out'/>" " </method>" " <method name='GetForeignProblems'>" " <arg type='as' name='response' direction='out'/>" " </method>" " <method name='GetInfo'>" " <arg type='s' name='problem_dir' direction='in'/>" " <arg type='as' name='element_names' direction='in'/>" " <arg type='a{ss}' name='response' direction='out'/>" " </method>" " <method name='SetElement'>" " <arg type='s' name='problem_dir' direction='in'/>" " <arg type='s' name='name' direction='in'/>" " <arg type='s' name='value' direction='in'/>" " </method>" " <method name='DeleteElement'>" " <arg type='s' name='problem_dir' direction='in'/>" " <arg type='s' name='name' direction='in'/>" " </method>" " <method name='ChownProblemDir'>" " <arg type='s' name='problem_dir' direction='in'/>" " </method>" " <method name='DeleteProblem'>" " <arg type='as' name='problem_dir' direction='in'/>" " </method>" " <method name='FindProblemByElementInTimeRange'>" " <arg type='s' name='element' direction='in'/>" " <arg type='s' name='value' direction='in'/>" " <arg type='x' name='timestamp_from' direction='in'/>" " <arg type='x' name='timestamp_to' direction='in'/>" " <arg type='b' name='all_users' direction='in'/>" " <arg type='as' name='response' direction='out'/>" " </method>" " <method name='Quit' />" " </interface>" "</node>"; /* ---------------------------------------------------------------------------------------------------- */ /* forward */ static gboolean on_timeout_cb(gpointer user_data); static void reset_timeout(void) { if (g_timeout_source > 0) { log_info("Removing timeout"); g_source_remove(g_timeout_source); } log_info("Setting a new timeout"); g_timeout_source = g_timeout_add_seconds(g_timeout_value, on_timeout_cb, NULL); } static uid_t get_caller_uid(GDBusConnection *connection, GDBusMethodInvocation *invocation, const char *caller) { GError *error = NULL; guint caller_uid; GDBusProxy * proxy = g_dbus_proxy_new_sync(connection, G_DBUS_PROXY_FLAGS_NONE, NULL, "org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", NULL, &error); GVariant *result = g_dbus_proxy_call_sync(proxy, "GetConnectionUnixUser", g_variant_new ("(s)", caller), G_DBUS_CALL_FLAGS_NONE, -1, NULL, &error); if (result == NULL) { /* we failed to get the uid, so return (uid_t) -1 to indicate the error */ if (error) { g_dbus_method_invocation_return_dbus_error(invocation, "org.freedesktop.problems.InvalidUser", error->message); g_error_free(error); } else { g_dbus_method_invocation_return_dbus_error(invocation, "org.freedesktop.problems.InvalidUser", _("Unknown error")); } return (uid_t) -1; } g_variant_get(result, "(u)", &caller_uid); g_variant_unref(result); log_info("Caller uid: %i", caller_uid); return caller_uid; } bool allowed_problem_dir(const char *dir_name) { if (!dir_is_in_dump_location(dir_name)) { error_msg("Bad problem directory name '%s', should start with: '%s'", dir_name, g_settings_dump_location); return false; } /* We cannot test correct permissions yet because we still need to chown * dump directories before reporting and Chowing changes the file owner to * the reporter, which causes this test to fail and prevents users from * getting problem data after reporting it. * * Fortunately, libreport has been hardened against hard link and symbolic * link attacks and refuses to work with such files, so this test isn't * really necessary, however, we will use it once we get rid of the * chowning files. * * abrt-server refuses to run post-create on directories that have * incorrect owner (not "root:(abrt|root)"), incorrect permissions (other * bits are not 0) and are complete (post-create finished). So, there is no * way to run security sensitive event scripts (post-create) on crafted * problem directories. */ #if 0 if (!dir_has_correct_permissions(dir_name)) { error_msg("Problem directory '%s' isn't owned by root:abrt or others are not restricted from access", dir_name); return false; } #endif return true; } static char *handle_new_problem(GVariant *problem_info, uid_t caller_uid, char **error) { problem_data_t *pd = problem_data_new(); GVariantIter *iter; g_variant_get(problem_info, "a{ss}", &iter); gchar *key, *value; while (g_variant_iter_loop(iter, "{ss}", &key, &value)) { problem_data_add_text_editable(pd, key, value); } if (caller_uid != 0 || problem_data_get_content_or_NULL(pd, FILENAME_UID) == NULL) { /* set uid field to caller's uid if caller is not root or root doesn't pass own uid */ log_info("Adding UID %d to problem data", caller_uid); char buf[sizeof(uid_t) * 3 + 2]; snprintf(buf, sizeof(buf), "%d", caller_uid); problem_data_add_text_noteditable(pd, FILENAME_UID, buf); } /* At least it should generate local problem identifier UUID */ problem_data_add_basics(pd); char *problem_id = problem_data_save(pd); if (problem_id) notify_new_path(problem_id); else if (error) *error = xasprintf("Cannot create a new problem"); problem_data_free(pd); return problem_id; } static void return_InvalidProblemDir_error(GDBusMethodInvocation *invocation, const char *dir_name) { char *msg = xasprintf(_("'%s' is not a valid problem directory"), dir_name); g_dbus_method_invocation_return_dbus_error(invocation, "org.freedesktop.problems.InvalidProblemDir", msg); free(msg); } /* * Checks element's rights and does not open directory if element is protected. * Checks problem's rights and does not open directory if user hasn't got * access to a problem. * * Returns a dump directory opend for writing or NULL. * * If any operation from the above listed fails, immediately returns D-Bus * error to a D-Bus caller. */ static struct dump_dir *open_directory_for_modification_of_element( GDBusMethodInvocation *invocation, uid_t caller_uid, const char *problem_id, const char *element) { static const char *const protected_elements[] = { FILENAME_TIME, FILENAME_UID, NULL, }; for (const char *const *protected = protected_elements; *protected; ++protected) { if (strcmp(*protected, element) == 0) { log_notice("'%s' element of '%s' can't be modified", element, problem_id); char *error = xasprintf(_("'%s' element can't be modified"), element); g_dbus_method_invocation_return_dbus_error(invocation, "org.freedesktop.problems.ProtectedElement", error); free(error); return NULL; } } int dir_fd = dd_openfd(problem_id); if (dir_fd < 0) { perror_msg("can't open problem directory '%s'", problem_id); return_InvalidProblemDir_error(invocation, problem_id); return NULL; } if (!fdump_dir_accessible_by_uid(dir_fd, caller_uid)) { if (errno == ENOTDIR) { log_notice("'%s' is not a valid problem directory", problem_id); return_InvalidProblemDir_error(invocation, problem_id); } else { log_notice("UID(%d) is not Authorized to access '%s'", caller_uid, problem_id); g_dbus_method_invocation_return_dbus_error(invocation, "org.freedesktop.problems.AuthFailure", _("Not Authorized")); } close(dir_fd); return NULL; } struct dump_dir *dd = dd_fdopendir(dir_fd, problem_id, /* flags : */ 0); if (!dd) { /* This should not happen because of the access check above */ log_notice("Can't access the problem '%s' for modification", problem_id); g_dbus_method_invocation_return_dbus_error(invocation, "org.freedesktop.problems.Failure", _("Can't access the problem for modification")); return NULL; } return dd; } /* * Lists problems which have given element and were seen in given time interval */ struct field_and_time_range { GList *list; const char *element; const char *value; unsigned long timestamp_from; unsigned long timestamp_to; }; static int add_dirname_to_GList_if_matches(struct dump_dir *dd, void *arg) { struct field_and_time_range *me = arg; char *field_data = dd_load_text(dd, me->element); int brk = (strcmp(field_data, me->value) != 0); free(field_data); if (brk) return 0; field_data = dd_load_text(dd, FILENAME_LAST_OCCURRENCE); long val = atol(field_data); free(field_data); if (val < me->timestamp_from || val > me->timestamp_to) return 0; me->list = g_list_prepend(me->list, xstrdup(dd->dd_dirname)); return 0; } static GList *get_problem_dirs_for_element_in_time(uid_t uid, const char *element, const char *value, unsigned long timestamp_from, unsigned long timestamp_to) { if (timestamp_to == 0) /* not sure this is possible, but... */ timestamp_to = time(NULL); struct field_and_time_range me = { .list = NULL, .element = element, .value = value, .timestamp_from = timestamp_from, .timestamp_to = timestamp_to, }; for_each_problem_in_dir(g_settings_dump_location, uid, add_dirname_to_GList_if_matches, &me); return g_list_reverse(me.list); } static void handle_method_call(GDBusConnection *connection, const gchar *caller, const gchar *object_path, const gchar *interface_name, const gchar *method_name, GVariant *parameters, GDBusMethodInvocation *invocation, gpointer user_data) { reset_timeout(); uid_t caller_uid; GVariant *response; caller_uid = get_caller_uid(connection, invocation, caller); log_notice("caller_uid:%ld method:'%s'", (long)caller_uid, method_name); if (caller_uid == (uid_t) -1) return; if (g_strcmp0(method_name, "NewProblem") == 0) { char *error = NULL; char *problem_id = handle_new_problem(g_variant_get_child_value(parameters, 0), caller_uid, &error); if (!problem_id) { g_dbus_method_invocation_return_dbus_error(invocation, "org.freedesktop.problems.Failure", error); free(error); return; } /* else */ response = g_variant_new("(s)", problem_id); g_dbus_method_invocation_return_value(invocation, response); free(problem_id); return; } if (g_strcmp0(method_name, "GetProblems") == 0) { GList *dirs = get_problem_dirs_for_uid(caller_uid, g_settings_dump_location); response = variant_from_string_list(dirs); list_free_with_free(dirs); g_dbus_method_invocation_return_value(invocation, response); //I was told that g_dbus_method frees the response //g_variant_unref(response); return; } if (g_strcmp0(method_name, "GetAllProblems") == 0) { /* - so, we have UID, - if it's 0, then we don't have to check anything and just return all directories - if uid != 0 then we want to ask for authorization */ if (caller_uid != 0) { if (polkit_check_authorization_dname(caller, "org.freedesktop.problems.getall") == PolkitYes) caller_uid = 0; } GList * dirs = get_problem_dirs_for_uid(caller_uid, g_settings_dump_location); response = variant_from_string_list(dirs); list_free_with_free(dirs); g_dbus_method_invocation_return_value(invocation, response); return; } if (g_strcmp0(method_name, "GetForeignProblems") == 0) { GList * dirs = get_problem_dirs_not_accessible_by_uid(caller_uid, g_settings_dump_location); response = variant_from_string_list(dirs); list_free_with_free(dirs); g_dbus_method_invocation_return_value(invocation, response); return; } if (g_strcmp0(method_name, "ChownProblemDir") == 0) { const gchar *problem_dir; g_variant_get(parameters, "(&s)", &problem_dir); log_notice("problem_dir:'%s'", problem_dir); if (!allowed_problem_dir(problem_dir)) { return_InvalidProblemDir_error(invocation, problem_dir); return; } int dir_fd = dd_openfd(problem_dir); if (dir_fd < 0) { perror_msg("can't open problem directory '%s'", problem_dir); return_InvalidProblemDir_error(invocation, problem_dir); return; } int ddstat = fdump_dir_stat_for_uid(dir_fd, caller_uid); if (ddstat < 0) { if (errno == ENOTDIR) { log_notice("requested directory does not exist '%s'", problem_dir); } else { perror_msg("can't get stat of '%s'", problem_dir); } return_InvalidProblemDir_error(invocation, problem_dir); close(dir_fd); return; } if (ddstat & DD_STAT_OWNED_BY_UID) { //caller seems to be in group with access to this dir, so no action needed log_notice("caller has access to the requested directory %s", problem_dir); g_dbus_method_invocation_return_value(invocation, NULL); close(dir_fd); return; } if ((ddstat & DD_STAT_ACCESSIBLE_BY_UID) == 0 && polkit_check_authorization_dname(caller, "org.freedesktop.problems.getall") != PolkitYes) { log_notice("not authorized"); g_dbus_method_invocation_return_dbus_error(invocation, "org.freedesktop.problems.AuthFailure", _("Not Authorized")); close(dir_fd); return; } struct dump_dir *dd = dd_fdopendir(dir_fd, problem_dir, DD_OPEN_READONLY | DD_FAIL_QUIETLY_EACCES); if (!dd) { return_InvalidProblemDir_error(invocation, problem_dir); return; } int chown_res = dd_chown(dd, caller_uid); if (chown_res != 0) g_dbus_method_invocation_return_dbus_error(invocation, "org.freedesktop.problems.ChownError", _("Chowning directory failed. Check system logs for more details.")); else g_dbus_method_invocation_return_value(invocation, NULL); dd_close(dd); return; } if (g_strcmp0(method_name, "GetInfo") == 0) { /* Parameter tuple is (sas) */ /* Get 1st param - problem dir name */ const gchar *problem_dir; g_variant_get_child(parameters, 0, "&s", &problem_dir); log_notice("problem_dir:'%s'", problem_dir); if (!allowed_problem_dir(problem_dir)) { return_InvalidProblemDir_error(invocation, problem_dir); return; } int dir_fd = dd_openfd(problem_dir); if (dir_fd < 0) { perror_msg("can't open problem directory '%s'", problem_dir); return_InvalidProblemDir_error(invocation, problem_dir); return; } if (!fdump_dir_accessible_by_uid(dir_fd, caller_uid)) { if (errno == ENOTDIR) { log_notice("Requested directory does not exist '%s'", problem_dir); return_InvalidProblemDir_error(invocation, problem_dir); close(dir_fd); return; } if (polkit_check_authorization_dname(caller, "org.freedesktop.problems.getall") != PolkitYes) { log_notice("not authorized"); g_dbus_method_invocation_return_dbus_error(invocation, "org.freedesktop.problems.AuthFailure", _("Not Authorized")); close(dir_fd); return; } } struct dump_dir *dd = dd_fdopendir(dir_fd, problem_dir, DD_OPEN_READONLY | DD_FAIL_QUIETLY_EACCES); if (!dd) { return_InvalidProblemDir_error(invocation, problem_dir); return; } /* Get 2nd param - vector of element names */ GVariant *array = g_variant_get_child_value(parameters, 1); GList *elements = string_list_from_variant(array); g_variant_unref(array); GVariantBuilder *builder = NULL; for (GList *l = elements; l; l = l->next) { const char *element_name = (const char*)l->data; char *value = dd_load_text_ext(dd, element_name, 0 | DD_LOAD_TEXT_RETURN_NULL_ON_FAILURE | DD_FAIL_QUIETLY_ENOENT | DD_FAIL_QUIETLY_EACCES); log_notice("element '%s' %s", element_name, value ? "fetched" : "not found"); if (value) { if (!builder) builder = g_variant_builder_new(G_VARIANT_TYPE_ARRAY); /* g_variant_builder_add makes a copy. No need to xstrdup here */ g_variant_builder_add(builder, "{ss}", element_name, value); free(value); } } list_free_with_free(elements); dd_close(dd); /* It is OK to call g_variant_new("(a{ss})", NULL) because */ /* G_VARIANT_TYPE_TUPLE allows NULL value */ GVariant *response = g_variant_new("(a{ss})", builder); if (builder) g_variant_builder_unref(builder); log_info("GetInfo: returning value for '%s'", problem_dir); g_dbus_method_invocation_return_value(invocation, response); return; } if (g_strcmp0(method_name, "SetElement") == 0) { const char *problem_id; const char *element; const char *value; g_variant_get(parameters, "(&s&s&s)", &problem_id, &element, &value); if (!str_is_correct_filename(element)) { log_notice("'%s' is not a valid element name of '%s'", element, problem_id); char *error = xasprintf(_("'%s' is not a valid element name"), element); g_dbus_method_invocation_return_dbus_error(invocation, "org.freedesktop.problems.InvalidElement", error); free(error); return; } struct dump_dir *dd = open_directory_for_modification_of_element( invocation, caller_uid, problem_id, element); if (!dd) /* Already logged from open_directory_for_modification_of_element() */ return; /* Is it good idea to make it static? Is it possible to change the max size while a single run? */ const double max_dir_size = g_settings_nMaxCrashReportsSize * (1024 * 1024); const long item_size = dd_get_item_size(dd, element); if (item_size < 0) { log_notice("Can't get size of '%s/%s'", problem_id, element); char *error = xasprintf(_("Can't get size of '%s'"), element); g_dbus_method_invocation_return_dbus_error(invocation, "org.freedesktop.problems.Failure", error); return; } const double requested_size = (double)strlen(value) - item_size; /* Don't want to check the size limit in case of reducing of size */ if (requested_size > 0 && requested_size > (max_dir_size - get_dirsize(g_settings_dump_location))) { log_notice("No problem space left in '%s' (requested Bytes %f)", problem_id, requested_size); g_dbus_method_invocation_return_dbus_error(invocation, "org.freedesktop.problems.Failure", _("No problem space left")); } else { dd_save_text(dd, element, value); g_dbus_method_invocation_return_value(invocation, NULL); } dd_close(dd); return; } if (g_strcmp0(method_name, "DeleteElement") == 0) { const char *problem_id; const char *element; g_variant_get(parameters, "(&s&s)", &problem_id, &element); if (!str_is_correct_filename(element)) { log_notice("'%s' is not a valid element name of '%s'", element, problem_id); char *error = xasprintf(_("'%s' is not a valid element name"), element); g_dbus_method_invocation_return_dbus_error(invocation, "org.freedesktop.problems.InvalidElement", error); free(error); return; } struct dump_dir *dd = open_directory_for_modification_of_element( invocation, caller_uid, problem_id, element); if (!dd) /* Already logged from open_directory_for_modification_of_element() */ return; const int res = dd_delete_item(dd, element); dd_close(dd); if (res != 0) { log_notice("Can't delete the element '%s' from the problem directory '%s'", element, problem_id); char *error = xasprintf(_("Can't delete the element '%s' from the problem directory '%s'"), element, problem_id); g_dbus_method_invocation_return_dbus_error(invocation, "org.freedesktop.problems.Failure", error); free(error); return; } g_dbus_method_invocation_return_value(invocation, NULL); return; } if (g_strcmp0(method_name, "DeleteProblem") == 0) { /* Dbus parameters are always tuples. * In this case, it's (as) - a tuple of one element (array of strings). * Need to fetch the array: */ GVariant *array = g_variant_get_child_value(parameters, 0); GList *problem_dirs = string_list_from_variant(array); g_variant_unref(array); for (GList *l = problem_dirs; l; l = l->next) { const char *dir_name = (const char*)l->data; log_notice("dir_name:'%s'", dir_name); if (!allowed_problem_dir(dir_name)) { return_InvalidProblemDir_error(invocation, dir_name); goto ret; } } for (GList *l = problem_dirs; l; l = l->next) { const char *dir_name = (const char*)l->data; int dir_fd = dd_openfd(dir_name); if (dir_fd < 0) { perror_msg("can't open problem directory '%s'", dir_name); return_InvalidProblemDir_error(invocation, dir_name); return; } if (!fdump_dir_accessible_by_uid(dir_fd, caller_uid)) { if (errno == ENOTDIR) { log_notice("Requested directory does not exist '%s'", dir_name); close(dir_fd); continue; } if (polkit_check_authorization_dname(caller, "org.freedesktop.problems.getall") != PolkitYes) { // if user didn't provide correct credentials, just move to the next dir close(dir_fd); continue; } } struct dump_dir *dd = dd_fdopendir(dir_fd, dir_name, /*flags:*/ 0); if (dd) { if (dd_delete(dd) != 0) { error_msg("Failed to delete problem directory '%s'", dir_name); dd_close(dd); } } } g_dbus_method_invocation_return_value(invocation, NULL); ret: list_free_with_free(problem_dirs); return; } if (g_strcmp0(method_name, "FindProblemByElementInTimeRange") == 0) { const gchar *element; const gchar *value; glong timestamp_from; glong timestamp_to; gboolean all; g_variant_get_child(parameters, 0, "&s", &element); g_variant_get_child(parameters, 1, "&s", &value); g_variant_get_child(parameters, 2, "x", &timestamp_from); g_variant_get_child(parameters, 3, "x", &timestamp_to); g_variant_get_child(parameters, 4, "b", &all); if (all && polkit_check_authorization_dname(caller, "org.freedesktop.problems.getall") == PolkitYes) caller_uid = 0; GList *dirs = get_problem_dirs_for_element_in_time(caller_uid, element, value, timestamp_from, timestamp_to); response = variant_from_string_list(dirs); list_free_with_free(dirs); g_dbus_method_invocation_return_value(invocation, response); return; } if (g_strcmp0(method_name, "Quit") == 0) { g_dbus_method_invocation_return_value(invocation, NULL); g_main_loop_quit(loop); return; } } static gboolean on_timeout_cb(gpointer user_data) { g_main_loop_quit(loop); return TRUE; } static const GDBusInterfaceVTable interface_vtable = { .method_call = handle_method_call, .get_property = NULL, .set_property = NULL, }; static void on_bus_acquired(GDBusConnection *connection, const gchar *name, gpointer user_data) { guint registration_id; registration_id = g_dbus_connection_register_object(connection, ABRT_DBUS_OBJECT, introspection_data->interfaces[0], &interface_vtable, NULL, /* user_data */ NULL, /* user_data_free_func */ NULL); /* GError** */ g_assert(registration_id > 0); reset_timeout(); } /* not used static void on_name_acquired (GDBusConnection *connection, const gchar *name, gpointer user_data) { } */ static void on_name_lost(GDBusConnection *connection, const gchar *name, gpointer user_data) { g_print(_("The name '%s' has been lost, please check if other " "service owning the name is not running.\n"), name); exit(1); } int main(int argc, char *argv[]) { /* I18n */ setlocale(LC_ALL, ""); #if ENABLE_NLS bindtextdomain(PACKAGE, LOCALEDIR); textdomain(PACKAGE); #endif guint owner_id; abrt_init(argv); const char *program_usage_string = _( "& [options]" ); enum { OPT_v = 1 << 0, OPT_t = 1 << 1, }; /* Keep enum above and order of options below in sync! */ struct options program_options[] = { OPT__VERBOSE(&g_verbose), OPT_INTEGER('t', NULL, &g_timeout_value, _("Exit after NUM seconds of inactivity")), OPT_END() }; /*unsigned opts =*/ parse_opts(argc, argv, program_options, program_usage_string); export_abrt_envvars(0); /* When dbus daemon starts us, it doesn't set PATH * (I saw it set only DBUS_STARTER_ADDRESS and DBUS_STARTER_BUS_TYPE). * In this case, set something sane: */ const char *env_path = getenv("PATH"); if (!env_path || !env_path[0]) putenv((char*)"PATH=/usr/sbin:/usr/bin:/sbin:/bin"); msg_prefix = "abrt-dbus"; /* for log(), error_msg() and such */ if (getuid() != 0) error_msg_and_die(_("This program must be run as root.")); glib_init(); /* We are lazy here - we don't want to manually provide * the introspection data structures - so we just build * them from XML. */ introspection_data = g_dbus_node_info_new_for_xml(introspection_xml, NULL); g_assert(introspection_data != NULL); owner_id = g_bus_own_name(G_BUS_TYPE_SYSTEM, ABRT_DBUS_NAME, G_BUS_NAME_OWNER_FLAGS_NONE, on_bus_acquired, NULL, on_name_lost, NULL, NULL); /* initialize the g_settings_dump_location */ load_abrt_conf(); loop = g_main_loop_new(NULL, FALSE); g_main_loop_run(loop); log_notice("Cleaning up"); g_bus_unown_name(owner_id); g_dbus_node_info_unref(introspection_data); free_abrt_conf_data(); return 0; }
./CrossVul/dataset_final_sorted/CWE-59/c/bad_1506_1
crossvul-cpp_data_bad_436_0
/* * Soft: Keepalived is a failover program for the LVS project * <www.linuxvirtualserver.org>. It monitor & manipulate * a loadbalanced server pool using multi-layer checks. * * Part: Main program structure. * * Author: Alexandre Cassen, <acassen@linux-vs.org> * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. * * Copyright (C) 2001-2017 Alexandre Cassen, <acassen@gmail.com> */ #include "config.h" #include <stdlib.h> #include <sys/utsname.h> #include <sys/resource.h> #include <stdbool.h> #ifdef HAVE_SIGNALFD #include <sys/signalfd.h> #endif #include <errno.h> #include <signal.h> #include <fcntl.h> #include <sys/wait.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <getopt.h> #include <linux/version.h> #include <ctype.h> #include "main.h" #include "global_data.h" #include "daemon.h" #include "config.h" #include "git-commit.h" #include "utils.h" #include "signals.h" #include "pidfile.h" #include "bitops.h" #include "logger.h" #include "parser.h" #include "notify.h" #include "utils.h" #ifdef _WITH_LVS_ #include "check_parser.h" #include "check_daemon.h" #endif #ifdef _WITH_VRRP_ #include "vrrp_daemon.h" #include "vrrp_parser.h" #include "vrrp_if.h" #ifdef _WITH_JSON_ #include "vrrp_json.h" #endif #endif #ifdef _WITH_BFD_ #include "bfd_daemon.h" #include "bfd_parser.h" #endif #include "global_parser.h" #if HAVE_DECL_CLONE_NEWNET #include "namespaces.h" #endif #include "scheduler.h" #include "keepalived_netlink.h" #include "git-commit.h" #if defined THREAD_DUMP || defined _EPOLL_DEBUG_ || defined _EPOLL_THREAD_DUMP_ #include "scheduler.h" #endif #include "process.h" #ifdef _TIMER_CHECK_ #include "timer.h" #endif #ifdef _SMTP_ALERT_DEBUG_ #include "smtp.h" #endif #if defined _REGEX_DEBUG_ || defined _WITH_REGEX_TIMERS_ #include "check_http.h" #endif #ifdef _TSM_DEBUG_ #include "vrrp_scheduler.h" #endif /* musl libc doesn't define the following */ #ifndef W_EXITCODE #define W_EXITCODE(ret, sig) ((ret) << 8 | (sig)) #endif #ifndef WCOREFLAG #define WCOREFLAG ((int32_t)WCOREDUMP(0xffffffff)) #endif #define VERSION_STRING PACKAGE_NAME " v" PACKAGE_VERSION " (" GIT_DATE ")" #define COPYRIGHT_STRING "Copyright(C) 2001-" GIT_YEAR " Alexandre Cassen, <acassen@gmail.com>" #define CHILD_WAIT_SECS 5 /* global var */ const char *version_string = VERSION_STRING; /* keepalived version */ char *conf_file = KEEPALIVED_CONFIG_FILE; /* Configuration file */ int log_facility = LOG_DAEMON; /* Optional logging facilities */ bool reload; /* Set during a reload */ char *main_pidfile; /* overrule default pidfile */ static bool free_main_pidfile; #ifdef _WITH_LVS_ pid_t checkers_child; /* Healthcheckers child process ID */ char *checkers_pidfile; /* overrule default pidfile */ static bool free_checkers_pidfile; #endif #ifdef _WITH_VRRP_ pid_t vrrp_child; /* VRRP child process ID */ char *vrrp_pidfile; /* overrule default pidfile */ static bool free_vrrp_pidfile; #endif #ifdef _WITH_BFD_ pid_t bfd_child; /* BFD child process ID */ char *bfd_pidfile; /* overrule default pidfile */ static bool free_bfd_pidfile; #endif unsigned long daemon_mode; /* VRRP/CHECK/BFD subsystem selection */ #ifdef _WITH_SNMP_ bool snmp; /* Enable SNMP support */ const char *snmp_socket; /* Socket to use for SNMP agent */ #endif static char *syslog_ident; /* syslog ident if not default */ bool use_pid_dir; /* Put pid files in /var/run/keepalived or @localstatedir@/run/keepalived */ unsigned os_major; /* Kernel version */ unsigned os_minor; unsigned os_release; char *hostname; /* Initial part of hostname */ #if HAVE_DECL_CLONE_NEWNET static char *override_namespace; /* If namespace specified on command line */ #endif unsigned child_wait_time = CHILD_WAIT_SECS; /* Time to wait for children to exit */ /* Log facility table */ static struct { int facility; } LOG_FACILITY[] = { {LOG_LOCAL0}, {LOG_LOCAL1}, {LOG_LOCAL2}, {LOG_LOCAL3}, {LOG_LOCAL4}, {LOG_LOCAL5}, {LOG_LOCAL6}, {LOG_LOCAL7} }; #define LOG_FACILITY_MAX ((sizeof(LOG_FACILITY) / sizeof(LOG_FACILITY[0])) - 1) /* umask settings */ bool umask_cmdline; static mode_t umask_val = S_IXUSR | S_IWGRP | S_IXGRP | S_IWOTH | S_IXOTH; /* Control producing core dumps */ static bool set_core_dump_pattern = false; static bool create_core_dump = false; static const char *core_dump_pattern = "core"; static char *orig_core_dump_pattern = NULL; /* debug flags */ #if defined _TIMER_CHECK_ || defined _SMTP_ALERT_DEBUG_ || defined _EPOLL_DEBUG_ || defined _EPOLL_THREAD_DUMP_ || defined _REGEX_DEBUG_ || defined _WITH_REGEX_TIMERS_ || defined _TSM_DEBUG_ || defined _VRRP_FD_DEBUG_ || defined _NETLINK_TIMERS_ #define WITH_DEBUG_OPTIONS 1 #endif #ifdef _TIMER_CHECK_ static char timer_debug; #endif #ifdef _SMTP_ALERT_DEBUG_ static char smtp_debug; #endif #ifdef _EPOLL_DEBUG_ static char epoll_debug; #endif #ifdef _EPOLL_THREAD_DUMP_ static char epoll_thread_debug; #endif #ifdef _REGEX_DEBUG_ static char regex_debug; #endif #ifdef _WITH_REGEX_TIMERS_ static char regex_timers; #endif #ifdef _TSM_DEBUG_ static char tsm_debug; #endif #ifdef _VRRP_FD_DEBUG_ static char vrrp_fd_debug; #endif #ifdef _NETLINK_TIMERS_ static char netlink_timer_debug; #endif void free_parent_mallocs_startup(bool am_child) { if (am_child) { #if HAVE_DECL_CLONE_NEWNET free_dirname(); #endif #ifndef _MEM_CHECK_LOG_ FREE_PTR(syslog_ident); #else free(syslog_ident); #endif syslog_ident = NULL; FREE_PTR(orig_core_dump_pattern); } if (free_main_pidfile) { FREE_PTR(main_pidfile); free_main_pidfile = false; } } void free_parent_mallocs_exit(void) { #ifdef _WITH_VRRP_ if (free_vrrp_pidfile) FREE_PTR(vrrp_pidfile); #endif #ifdef _WITH_LVS_ if (free_checkers_pidfile) FREE_PTR(checkers_pidfile); #endif #ifdef _WITH_BFD_ if (free_bfd_pidfile) FREE_PTR(bfd_pidfile); #endif FREE_PTR(config_id); } char * make_syslog_ident(const char* name) { size_t ident_len = strlen(name) + 1; char *ident; #if HAVE_DECL_CLONE_NEWNET if (global_data->network_namespace) ident_len += strlen(global_data->network_namespace) + 1; #endif if (global_data->instance_name) ident_len += strlen(global_data->instance_name) + 1; /* If we are writing MALLOC/FREE info to the log, we have * trouble FREEing the syslog_ident */ #ifndef _MEM_CHECK_LOG_ ident = MALLOC(ident_len); #else ident = malloc(ident_len); #endif if (!ident) return NULL; strcpy(ident, name); #if HAVE_DECL_CLONE_NEWNET if (global_data->network_namespace) { strcat(ident, "_"); strcat(ident, global_data->network_namespace); } #endif if (global_data->instance_name) { strcat(ident, "_"); strcat(ident, global_data->instance_name); } return ident; } static char * make_pidfile_name(const char* start, const char* instance, const char* extn) { size_t len; char *name; len = strlen(start) + 1; if (instance) len += strlen(instance) + 1; if (extn) len += strlen(extn); name = MALLOC(len); if (!name) { log_message(LOG_INFO, "Unable to make pidfile name for %s", start); return NULL; } strcpy(name, start); if (instance) { strcat(name, "_"); strcat(name, instance); } if (extn) strcat(name, extn); return name; } #ifdef _WITH_VRRP_ bool running_vrrp(void) { return (__test_bit(DAEMON_VRRP, &daemon_mode) && (global_data->have_vrrp_config || __test_bit(RUN_ALL_CHILDREN, &daemon_mode))); } #endif #ifdef _WITH_LVS_ bool running_checker(void) { return (__test_bit(DAEMON_CHECKERS, &daemon_mode) && (global_data->have_checker_config || __test_bit(RUN_ALL_CHILDREN, &daemon_mode))); } #endif #ifdef _WITH_BFD_ bool running_bfd(void) { return (__test_bit(DAEMON_BFD, &daemon_mode) && (global_data->have_bfd_config || __test_bit(RUN_ALL_CHILDREN, &daemon_mode))); } #endif static char const * find_keepalived_child_name(pid_t pid) { #ifdef _WITH_LVS_ if (pid == checkers_child) return PROG_CHECK; #endif #ifdef _WITH_VRRP_ if (pid == vrrp_child) return PROG_VRRP; #endif #ifdef _WITH_BFD_ if (pid == bfd_child) return PROG_BFD; #endif return NULL; } static vector_t * global_init_keywords(void) { /* global definitions mapping */ init_global_keywords(true); #ifdef _WITH_VRRP_ init_vrrp_keywords(false); #endif #ifdef _WITH_LVS_ init_check_keywords(false); #endif #ifdef _WITH_BFD_ init_bfd_keywords(false); #endif return keywords; } static void read_config_file(void) { init_data(conf_file, global_init_keywords); } /* Daemon stop sequence */ void stop_keepalived(void) { #ifndef _DEBUG_ /* Just cleanup memory & exit */ thread_destroy_master(master); #ifdef _WITH_VRRP_ if (__test_bit(DAEMON_VRRP, &daemon_mode)) pidfile_rm(vrrp_pidfile); #endif #ifdef _WITH_LVS_ if (__test_bit(DAEMON_CHECKERS, &daemon_mode)) pidfile_rm(checkers_pidfile); #endif #ifdef _WITH_BFD_ if (__test_bit(DAEMON_BFD, &daemon_mode)) pidfile_rm(bfd_pidfile); #endif pidfile_rm(main_pidfile); #endif } /* Daemon init sequence */ static int start_keepalived(void) { bool have_child = false; #ifdef _WITH_BFD_ /* must be opened before vrrp and bfd start */ open_bfd_pipes(); #endif #ifdef _WITH_LVS_ /* start healthchecker child */ if (running_checker()) { start_check_child(); have_child = true; } #endif #ifdef _WITH_VRRP_ /* start vrrp child */ if (running_vrrp()) { start_vrrp_child(); have_child = true; } #endif #ifdef _WITH_BFD_ /* start bfd child */ if (running_bfd()) { start_bfd_child(); have_child = true; } #endif return have_child; } static void validate_config(void) { #ifdef _WITH_VRRP_ kernel_netlink_read_interfaces(); #endif #ifdef _WITH_LVS_ /* validate healthchecker config */ #ifndef _DEBUG_ prog_type = PROG_TYPE_CHECKER; #endif check_validate_config(); #endif #ifdef _WITH_VRRP_ /* validate vrrp config */ #ifndef _DEBUG_ prog_type = PROG_TYPE_VRRP; #endif vrrp_validate_config(); #endif #ifdef _WITH_BFD_ /* validate bfd config */ #ifndef _DEBUG_ prog_type = PROG_TYPE_BFD; #endif bfd_validate_config(); #endif } static void config_test_exit(void) { config_err_t config_err = get_config_status(); switch (config_err) { case CONFIG_OK: exit(KEEPALIVED_EXIT_OK); case CONFIG_FILE_NOT_FOUND: case CONFIG_BAD_IF: case CONFIG_FATAL: exit(KEEPALIVED_EXIT_CONFIG); case CONFIG_SECURITY_ERROR: exit(KEEPALIVED_EXIT_CONFIG_TEST_SECURITY); default: exit(KEEPALIVED_EXIT_CONFIG_TEST); } } #ifndef _DEBUG_ static bool reload_config(void) { bool unsupported_change = false; log_message(LOG_INFO, "Reloading ..."); /* Make sure there isn't an attempt to change the network namespace or instance name */ old_global_data = global_data; global_data = NULL; global_data = alloc_global_data(); read_config_file(); init_global_data(global_data, old_global_data); #if HAVE_DECL_CLONE_NEWNET if (!!old_global_data->network_namespace != !!global_data->network_namespace || (global_data->network_namespace && strcmp(old_global_data->network_namespace, global_data->network_namespace))) { log_message(LOG_INFO, "Cannot change network namespace at a reload - please restart %s", PACKAGE); unsupported_change = true; } FREE_PTR(global_data->network_namespace); global_data->network_namespace = old_global_data->network_namespace; old_global_data->network_namespace = NULL; #endif if (!!old_global_data->instance_name != !!global_data->instance_name || (global_data->instance_name && strcmp(old_global_data->instance_name, global_data->instance_name))) { log_message(LOG_INFO, "Cannot change instance name at a reload - please restart %s", PACKAGE); unsupported_change = true; } FREE_PTR(global_data->instance_name); global_data->instance_name = old_global_data->instance_name; old_global_data->instance_name = NULL; if (unsupported_change) { /* We cannot reload the configuration, so continue with the old config */ free_global_data (global_data); global_data = old_global_data; } else free_global_data (old_global_data); return !unsupported_change; } /* SIGHUP/USR1/USR2 handler */ static void propagate_signal(__attribute__((unused)) void *v, int sig) { if (sig == SIGHUP) { if (!reload_config()) return; } /* Signal child processes */ #ifdef _WITH_VRRP_ if (vrrp_child > 0) kill(vrrp_child, sig); else if (sig == SIGHUP && running_vrrp()) start_vrrp_child(); #endif #ifdef _WITH_LVS_ if (sig == SIGHUP) { if (checkers_child > 0) kill(checkers_child, sig); else if (running_checker()) start_check_child(); } #endif #ifdef _WITH_BFD_ if (sig == SIGHUP) { if (bfd_child > 0) kill(bfd_child, sig); else if (running_bfd()) start_bfd_child(); } #endif } /* Terminate handler */ static void sigend(__attribute__((unused)) void *v, __attribute__((unused)) int sig) { int status; int ret; int wait_count = 0; struct timeval start_time, now; #ifdef HAVE_SIGNALFD struct timeval timeout = { .tv_sec = child_wait_time, .tv_usec = 0 }; int signal_fd = master->signal_fd; fd_set read_set; struct signalfd_siginfo siginfo; sigset_t sigmask; #else sigset_t old_set, child_wait; struct timespec timeout = { .tv_sec = child_wait_time, .tv_nsec = 0 }; #endif /* register the terminate thread */ thread_add_terminate_event(master); log_message(LOG_INFO, "Stopping"); #ifdef HAVE_SIGNALFD /* We only want to receive SIGCHLD now */ sigemptyset(&sigmask); sigaddset(&sigmask, SIGCHLD); signalfd(signal_fd, &sigmask, 0); FD_ZERO(&read_set); #else sigmask_func(0, NULL, &old_set); if (!sigismember(&old_set, SIGCHLD)) { sigemptyset(&child_wait); sigaddset(&child_wait, SIGCHLD); sigmask_func(SIG_BLOCK, &child_wait, NULL); } #endif #ifdef _WITH_VRRP_ if (vrrp_child > 0) { if (kill(vrrp_child, SIGTERM)) { /* ESRCH means no such process */ if (errno == ESRCH) vrrp_child = 0; } else wait_count++; } #endif #ifdef _WITH_LVS_ if (checkers_child > 0) { if (kill(checkers_child, SIGTERM)) { if (errno == ESRCH) checkers_child = 0; } else wait_count++; } #endif #ifdef _WITH_BFD_ if (bfd_child > 0) { if (kill(bfd_child, SIGTERM)) { if (errno == ESRCH) bfd_child = 0; } else wait_count++; } #endif gettimeofday(&start_time, NULL); while (wait_count) { #ifdef HAVE_SIGNALFD FD_SET(signal_fd, &read_set); ret = select(signal_fd + 1, &read_set, NULL, NULL, &timeout); if (ret == 0) break; if (ret == -1) { if (errno == EINTR) continue; log_message(LOG_INFO, "Terminating select returned errno %d", errno); break; } if (!FD_ISSET(signal_fd, &read_set)) { log_message(LOG_INFO, "Terminating select did not return select_fd"); continue; } if (read(signal_fd, &siginfo, sizeof(siginfo)) != sizeof(siginfo)) { log_message(LOG_INFO, "Terminating signal read did not read entire siginfo"); break; } status = siginfo.ssi_code == CLD_EXITED ? W_EXITCODE(siginfo.ssi_status, 0) : siginfo.ssi_code == CLD_KILLED ? W_EXITCODE(0, siginfo.ssi_status) : WCOREFLAG; #ifdef _WITH_VRRP_ if (vrrp_child > 0 && vrrp_child == (pid_t)siginfo.ssi_pid) { report_child_status(status, vrrp_child, PROG_VRRP); vrrp_child = 0; wait_count--; } #endif #ifdef _WITH_LVS_ if (checkers_child > 0 && checkers_child == (pid_t)siginfo.ssi_pid) { report_child_status(status, checkers_child, PROG_CHECK); checkers_child = 0; wait_count--; } #endif #ifdef _WITH_BFD_ if (bfd_child > 0 && bfd_child == (pid_t)siginfo.ssi_pid) { report_child_status(status, bfd_child, PROG_BFD); bfd_child = 0; wait_count--; } #endif #else ret = sigtimedwait(&child_wait, NULL, &timeout); if (ret == -1) { if (errno == EINTR) continue; if (errno == EAGAIN) break; } #ifdef _WITH_VRRP_ if (vrrp_child > 0 && vrrp_child == waitpid(vrrp_child, &status, WNOHANG)) { report_child_status(status, vrrp_child, PROG_VRRP); vrrp_child = 0; wait_count--; } #endif #ifdef _WITH_LVS_ if (checkers_child > 0 && checkers_child == waitpid(checkers_child, &status, WNOHANG)) { report_child_status(status, checkers_child, PROG_CHECK); checkers_child = 0; wait_count--; } #endif #ifdef _WITH_BFD_ if (bfd_child > 0 && bfd_child == waitpid(bfd_child, &status, WNOHANG)) { report_child_status(status, bfd_child, PROG_BFD); bfd_child = 0; wait_count--; } #endif #endif if (wait_count) { gettimeofday(&now, NULL); timeout.tv_sec = child_wait_time - (now.tv_sec - start_time.tv_sec); #ifdef HAVE_SIGNALFD timeout.tv_usec = (start_time.tv_usec - now.tv_usec); if (timeout.tv_usec < 0) { timeout.tv_usec += 1000000L; timeout.tv_sec--; } #else timeout.tv_nsec = (start_time.tv_usec - now.tv_usec) * 1000; if (timeout.tv_nsec < 0) { timeout.tv_nsec += 1000000000L; timeout.tv_sec--; } #endif if (timeout.tv_sec < 0) break; } } /* A child may not have terminated, so force its termination */ #ifdef _WITH_VRRP_ if (vrrp_child) { log_message(LOG_INFO, "vrrp process failed to die - forcing termination"); kill(vrrp_child, SIGKILL); } #endif #ifdef _WITH_LVS_ if (checkers_child) { log_message(LOG_INFO, "checker process failed to die - forcing termination"); kill(checkers_child, SIGKILL); } #endif #ifdef _WITH_BFD_ if (bfd_child) { log_message(LOG_INFO, "bfd process failed to die - forcing termination"); kill(bfd_child, SIGKILL); } #endif #ifndef HAVE_SIGNALFD if (!sigismember(&old_set, SIGCHLD)) sigmask_func(SIG_UNBLOCK, &child_wait, NULL); #endif } #endif /* Initialize signal handler */ static void signal_init(void) { #ifndef _DEBUG_ signal_set(SIGHUP, propagate_signal, NULL); signal_set(SIGUSR1, propagate_signal, NULL); signal_set(SIGUSR2, propagate_signal, NULL); #ifdef _WITH_JSON_ signal_set(SIGJSON, propagate_signal, NULL); #endif signal_set(SIGINT, sigend, NULL); signal_set(SIGTERM, sigend, NULL); #endif signal_ignore(SIGPIPE); } /* To create a core file when abrt is running (a RedHat distribution), * and keepalived isn't installed from an RPM package, edit the file * “/etc/abrt/abrt.conf”, and change the value of the field * “ProcessUnpackaged” to “yes”. * * Alternatively, use the -M command line option. */ static void update_core_dump_pattern(const char *pattern_str) { int fd; bool initialising = (orig_core_dump_pattern == NULL); /* CORENAME_MAX_SIZE in kernel source include/linux/binfmts.h defines * the maximum string length, * see core_pattern[CORENAME_MAX_SIZE] in * fs/coredump.c. Currently (Linux 4.10) defines it to be 128, but the * definition is not exposed to user-space. */ #define CORENAME_MAX_SIZE 128 if (initialising) orig_core_dump_pattern = MALLOC(CORENAME_MAX_SIZE); fd = open ("/proc/sys/kernel/core_pattern", O_RDWR); if (fd == -1 || (initialising && read(fd, orig_core_dump_pattern, CORENAME_MAX_SIZE - 1) == -1) || write(fd, pattern_str, strlen(pattern_str)) == -1) { log_message(LOG_INFO, "Unable to read/write core_pattern"); if (fd != -1) close(fd); FREE(orig_core_dump_pattern); return; } close(fd); if (!initialising) FREE_PTR(orig_core_dump_pattern); } static void core_dump_init(void) { struct rlimit orig_rlim, rlim; if (set_core_dump_pattern) { /* If we set the core_pattern here, we will attempt to restore it when we * exit. This will be fine if it is a child of ours that core dumps, * but if we ourself core dump, then the core_pattern will not be restored */ update_core_dump_pattern(core_dump_pattern); } if (create_core_dump) { rlim.rlim_cur = RLIM_INFINITY; rlim.rlim_max = RLIM_INFINITY; if (getrlimit(RLIMIT_CORE, &orig_rlim) == -1) log_message(LOG_INFO, "Failed to get core file size"); else if (setrlimit(RLIMIT_CORE, &rlim) == -1) log_message(LOG_INFO, "Failed to set core file size"); else set_child_rlimit(RLIMIT_CORE, &orig_rlim); } } static mode_t set_umask(const char *optarg) { long umask_long; mode_t umask_val; char *endptr; umask_long = strtoll(optarg, &endptr, 0); if (*endptr || umask_long < 0 || umask_long & ~0777L) { fprintf(stderr, "Invalid --umask option %s", optarg); return 0; } umask_val = umask_long & 0777; umask(umask_val); umask_cmdline = true; return umask_val; } void initialise_debug_options(void) { #if defined WITH_DEBUG_OPTIONS && !defined _DEBUG_ char mask = 0; if (prog_type == PROG_TYPE_PARENT) mask = 1 << PROG_TYPE_PARENT; #if _WITH_BFD_ else if (prog_type == PROG_TYPE_BFD) mask = 1 << PROG_TYPE_BFD; #endif #if _WITH_LVS_ else if (prog_type == PROG_TYPE_CHECKER) mask = 1 << PROG_TYPE_CHECKER; #endif #if _WITH_VRRP_ else if (prog_type == PROG_TYPE_VRRP) mask = 1 << PROG_TYPE_VRRP; #endif #ifdef _TIMER_CHECK_ do_timer_check = !!(timer_debug & mask); #endif #ifdef _SMTP_ALERT_DEBUG_ do_smtp_alert_debug = !!(smtp_debug & mask); #endif #ifdef _EPOLL_DEBUG_ do_epoll_debug = !!(epoll_debug & mask); #endif #ifdef _EPOLL_THREAD_DUMP_ do_epoll_thread_dump = !!(epoll_thread_debug & mask); #endif #ifdef _REGEX_DEBUG_ do_regex_debug = !!(regex_debug & mask); #endif #ifdef _WITH_REGEX_TIMERS_ do_regex_timers = !!(regex_timers & mask); #endif #ifdef _TSM_DEBUG_ do_tsm_debug = !!(tsm_debug & mask); #endif #ifdef _VRRP_FD_DEBUG_ do_vrrp_fd_debug = !!(vrrp_fd_debug & mask); #endif #ifdef _NETLINK_TIMERS_ do_netlink_timers = !!(netlink_timer_debug & mask); #endif #endif } #ifdef WITH_DEBUG_OPTIONS static void set_debug_options(const char *options) { char all_processes, processes; char opt; const char *opt_p = options; #ifdef _DEBUG_ all_processes = 1; #else all_processes = (1 << PROG_TYPE_PARENT); #if _WITH_BFD_ all_processes |= (1 << PROG_TYPE_BFD); #endif #if _WITH_LVS_ all_processes |= (1 << PROG_TYPE_CHECKER); #endif #if _WITH_VRRP_ all_processes |= (1 << PROG_TYPE_VRRP); #endif #endif if (!options) { #ifdef _TIMER_CHECK_ timer_debug = all_processes; #endif #ifdef _SMTP_ALERT_DEBUG_ smtp_debug = all_processes; #endif #ifdef _EPOLL_DEBUG_ epoll_debug = all_processes; #endif #ifdef _EPOLL_THREAD_DUMP_ epoll_thread_debug = all_processes; #endif #ifdef _REGEX_DEBUG_ regex_debug = all_processes; #endif #ifdef _WITH_REGEX_TIMERS_ regex_timers = all_processes; #endif #ifdef _TSM_DEBUG_ tsm_debug = all_processes; #endif #ifdef _VRRP_FD_DEBUG_ vrrp_fd_debug = all_processes; #endif #ifdef _NETLINK_TIMERS_ netlink_timer_debug = all_processes; #endif return; } opt_p = options; do { if (!isupper(*opt_p)) { fprintf(stderr, "Unknown debug option'%c' in '%s'\n", *opt_p, options); return; } opt = *opt_p++; #ifdef _DEBUG_ processes = all_processes; #else if (!*opt_p || isupper(*opt_p)) processes = all_processes; else { processes = 0; while (*opt_p && !isupper(*opt_p)) { switch (*opt_p) { case 'p': processes |= (1 << PROG_TYPE_PARENT); break; #if _WITH_BFD_ case 'b': processes |= (1 << PROG_TYPE_BFD); break; #endif #if _WITH_LVS_ case 'c': processes |= (1 << PROG_TYPE_CHECKER); break; #endif #if _WITH_VRRP_ case 'v': processes |= (1 << PROG_TYPE_VRRP); break; #endif default: fprintf(stderr, "Unknown debug process '%c' in '%s'\n", *opt_p, options); return; } opt_p++; } } #endif switch (opt) { #ifdef _TIMER_CHECK_ case 'T': timer_debug = processes; break; #endif #ifdef _SMTP_ALERT_DEBUG_ case 'M': smtp_debug = processes; break; #endif #ifdef _EPOLL_DEBUG_ case 'E': epoll_debug = processes; break; #endif #ifdef _EPOLL_THREAD_DUMP_ case 'D': epoll_thread_debug = processes; break; #endif #ifdef _REGEX_DEBUG_ case 'R': regex_debug = processes; break; #endif #ifdef _WITH_REGEX_TIMERS_ case 'X': regex_timers = processes; break; #endif #ifdef _TSM_DEBUG_ case 'S': tsm_debug = processes; break; #endif #ifdef _VRRP_FD_DEBUG_ case 'F': vrrp_fd_debug = processes; break; #endif #ifdef _NETLINK_TIMERS_ case 'N': netlink_timer_debug = processes; break; #endif default: fprintf(stderr, "Unknown debug type '%c' in '%s'\n", opt, options); return; } } while (opt_p && *opt_p); } #endif /* Usage function */ static void usage(const char *prog) { fprintf(stderr, "Usage: %s [OPTION...]\n", prog); fprintf(stderr, " -f, --use-file=FILE Use the specified configuration file\n"); #if defined _WITH_VRRP_ && defined _WITH_LVS_ fprintf(stderr, " -P, --vrrp Only run with VRRP subsystem\n"); fprintf(stderr, " -C, --check Only run with Health-checker subsystem\n"); #endif #ifdef _WITH_BFD_ fprintf(stderr, " -B, --no_bfd Don't run BFD subsystem\n"); #endif fprintf(stderr, " --all Force all child processes to run, even if have no configuration\n"); fprintf(stderr, " -l, --log-console Log messages to local console\n"); fprintf(stderr, " -D, --log-detail Detailed log messages\n"); fprintf(stderr, " -S, --log-facility=[0-7] Set syslog facility to LOG_LOCAL[0-7]\n"); fprintf(stderr, " -g, --log-file=FILE Also log to FILE (default /tmp/keepalived.log)\n"); fprintf(stderr, " --flush-log-file Flush log file on write\n"); fprintf(stderr, " -G, --no-syslog Don't log via syslog\n"); fprintf(stderr, " -u, --umask=MASK umask for file creation (in numeric form)\n"); #ifdef _WITH_VRRP_ fprintf(stderr, " -X, --release-vips Drop VIP on transition from signal.\n"); fprintf(stderr, " -V, --dont-release-vrrp Don't remove VRRP VIPs and VROUTEs on daemon stop\n"); #endif #ifdef _WITH_LVS_ fprintf(stderr, " -I, --dont-release-ipvs Don't remove IPVS topology on daemon stop\n"); #endif fprintf(stderr, " -R, --dont-respawn Don't respawn child processes\n"); fprintf(stderr, " -n, --dont-fork Don't fork the daemon process\n"); fprintf(stderr, " -d, --dump-conf Dump the configuration data\n"); fprintf(stderr, " -p, --pid=FILE Use specified pidfile for parent process\n"); #ifdef _WITH_VRRP_ fprintf(stderr, " -r, --vrrp_pid=FILE Use specified pidfile for VRRP child process\n"); #endif #ifdef _WITH_LVS_ fprintf(stderr, " -c, --checkers_pid=FILE Use specified pidfile for checkers child process\n"); fprintf(stderr, " -a, --address-monitoring Report all address additions/deletions notified via netlink\n"); #endif #ifdef _WITH_BFD_ fprintf(stderr, " -b, --bfd_pid=FILE Use specified pidfile for BFD child process\n"); #endif #ifdef _WITH_SNMP_ fprintf(stderr, " -x, --snmp Enable SNMP subsystem\n"); fprintf(stderr, " -A, --snmp-agent-socket=FILE Use the specified socket for master agent\n"); #endif #if HAVE_DECL_CLONE_NEWNET fprintf(stderr, " -s, --namespace=NAME Run in network namespace NAME (overrides config)\n"); #endif fprintf(stderr, " -m, --core-dump Produce core dump if terminate abnormally\n"); fprintf(stderr, " -M, --core-dump-pattern=PATN Also set /proc/sys/kernel/core_pattern to PATN (default 'core')\n"); #ifdef _MEM_CHECK_LOG_ fprintf(stderr, " -L, --mem-check-log Log malloc/frees to syslog\n"); #endif fprintf(stderr, " -i, --config-id id Skip any configuration lines beginning '@' that don't match id\n" " or any lines beginning @^ that do match.\n" " The config-id defaults to the node name if option not used\n"); fprintf(stderr, " --signum=SIGFUNC Return signal number for STOP, RELOAD, DATA, STATS" #ifdef _WITH_JSON_ ", JSON" #endif "\n"); fprintf(stderr, " -t, --config-test[=LOG_FILE] Check the configuration for obvious errors, output to\n" " stderr by default\n"); #ifdef _WITH_PERF_ fprintf(stderr, " --perf[=PERF_TYPE] Collect perf data, PERF_TYPE=all, run(default) or end\n"); #endif #ifdef WITH_DEBUG_OPTIONS fprintf(stderr, " --debug[=...] Enable debug options. p, b, c, v specify parent, bfd, checker and vrrp processes\n"); #ifdef _TIMER_CHECK_ fprintf(stderr, " T - timer debug\n"); #endif #ifdef _SMTP_ALERT_DEBUG_ fprintf(stderr, " M - email alert debug\n"); #endif #ifdef _EPOLL_DEBUG_ fprintf(stderr, " E - epoll debug\n"); #endif #ifdef _EPOLL_THREAD_DUMP_ fprintf(stderr, " D - epoll thread dump debug\n"); #endif #ifdef _VRRP_FD_DEBUG fprintf(stderr, " F - vrrp fd dump debug\n"); #endif #ifdef _REGEX_DEBUG_ fprintf(stderr, " R - regex debug\n"); #endif #ifdef _WITH_REGEX_TIMERS_ fprintf(stderr, " X - regex timers\n"); #endif #ifdef _TSM_DEBUG_ fprintf(stderr, " S - TSM debug\n"); #endif #ifdef _NETLINK_TIMERS_ fprintf(stderr, " N - netlink timer debug\n"); #endif fprintf(stderr, " Example --debug=TpMEvcp\n"); #endif fprintf(stderr, " -v, --version Display the version number\n"); fprintf(stderr, " -h, --help Display this help message\n"); } /* Command line parser */ static bool parse_cmdline(int argc, char **argv) { int c; bool reopen_log = false; int signum; struct utsname uname_buf; int longindex; int curind; bool bad_option = false; unsigned facility; mode_t new_umask_val; struct option long_options[] = { {"use-file", required_argument, NULL, 'f'}, #if defined _WITH_VRRP_ && defined _WITH_LVS_ {"vrrp", no_argument, NULL, 'P'}, {"check", no_argument, NULL, 'C'}, #endif #ifdef _WITH_BFD_ {"no_bfd", no_argument, NULL, 'B'}, #endif {"all", no_argument, NULL, 3 }, {"log-console", no_argument, NULL, 'l'}, {"log-detail", no_argument, NULL, 'D'}, {"log-facility", required_argument, NULL, 'S'}, {"log-file", optional_argument, NULL, 'g'}, {"flush-log-file", no_argument, NULL, 2 }, {"no-syslog", no_argument, NULL, 'G'}, {"umask", required_argument, NULL, 'u'}, #ifdef _WITH_VRRP_ {"release-vips", no_argument, NULL, 'X'}, {"dont-release-vrrp", no_argument, NULL, 'V'}, #endif #ifdef _WITH_LVS_ {"dont-release-ipvs", no_argument, NULL, 'I'}, #endif {"dont-respawn", no_argument, NULL, 'R'}, {"dont-fork", no_argument, NULL, 'n'}, {"dump-conf", no_argument, NULL, 'd'}, {"pid", required_argument, NULL, 'p'}, #ifdef _WITH_VRRP_ {"vrrp_pid", required_argument, NULL, 'r'}, #endif #ifdef _WITH_LVS_ {"checkers_pid", required_argument, NULL, 'c'}, {"address-monitoring", no_argument, NULL, 'a'}, #endif #ifdef _WITH_BFD_ {"bfd_pid", required_argument, NULL, 'b'}, #endif #ifdef _WITH_SNMP_ {"snmp", no_argument, NULL, 'x'}, {"snmp-agent-socket", required_argument, NULL, 'A'}, #endif {"core-dump", no_argument, NULL, 'm'}, {"core-dump-pattern", optional_argument, NULL, 'M'}, #ifdef _MEM_CHECK_LOG_ {"mem-check-log", no_argument, NULL, 'L'}, #endif #if HAVE_DECL_CLONE_NEWNET {"namespace", required_argument, NULL, 's'}, #endif {"config-id", required_argument, NULL, 'i'}, {"signum", required_argument, NULL, 4 }, {"config-test", optional_argument, NULL, 't'}, #ifdef _WITH_PERF_ {"perf", optional_argument, NULL, 5 }, #endif #ifdef WITH_DEBUG_OPTIONS {"debug", optional_argument, NULL, 6 }, #endif {"version", no_argument, NULL, 'v'}, {"help", no_argument, NULL, 'h'}, {NULL, 0, NULL, 0 } }; /* Unfortunately, if a short option is used, getopt_long() doesn't change the value * of longindex, so we need to ensure that before calling getopt_long(), longindex * is set to a known invalid value */ curind = optind; while (longindex = -1, (c = getopt_long(argc, argv, ":vhlndu:DRS:f:p:i:mM::g::Gt::" #if defined _WITH_VRRP_ && defined _WITH_LVS_ "PC" #endif #ifdef _WITH_VRRP_ "r:VX" #endif #ifdef _WITH_LVS_ "ac:I" #endif #ifdef _WITH_BFD_ "Bb:" #endif #ifdef _WITH_SNMP_ "xA:" #endif #ifdef _MEM_CHECK_LOG_ "L" #endif #if HAVE_DECL_CLONE_NEWNET "s:" #endif , long_options, &longindex)) != -1) { /* Check for an empty option argument. For example --use-file= returns * a 0 length option, which we don't want */ if (longindex >= 0 && long_options[longindex].has_arg == required_argument && optarg && !optarg[0]) { c = ':'; optarg = NULL; } switch (c) { case 'v': fprintf(stderr, "%s", version_string); #ifdef GIT_COMMIT fprintf(stderr, ", git commit %s", GIT_COMMIT); #endif fprintf(stderr, "\n\n%s\n\n", COPYRIGHT_STRING); fprintf(stderr, "Built with kernel headers for Linux %d.%d.%d\n", (LINUX_VERSION_CODE >> 16) & 0xff, (LINUX_VERSION_CODE >> 8) & 0xff, (LINUX_VERSION_CODE ) & 0xff); uname(&uname_buf); fprintf(stderr, "Running on %s %s %s\n\n", uname_buf.sysname, uname_buf.release, uname_buf.version); fprintf(stderr, "configure options: %s\n\n", KEEPALIVED_CONFIGURE_OPTIONS); fprintf(stderr, "Config options: %s\n\n", CONFIGURATION_OPTIONS); fprintf(stderr, "System options: %s\n", SYSTEM_OPTIONS); exit(0); break; case 'h': usage(argv[0]); exit(0); break; case 'l': __set_bit(LOG_CONSOLE_BIT, &debug); reopen_log = true; break; case 'n': __set_bit(DONT_FORK_BIT, &debug); break; case 'd': __set_bit(DUMP_CONF_BIT, &debug); break; #ifdef _WITH_VRRP_ case 'V': __set_bit(DONT_RELEASE_VRRP_BIT, &debug); break; #endif #ifdef _WITH_LVS_ case 'I': __set_bit(DONT_RELEASE_IPVS_BIT, &debug); break; #endif case 'D': if (__test_bit(LOG_DETAIL_BIT, &debug)) __set_bit(LOG_EXTRA_DETAIL_BIT, &debug); else __set_bit(LOG_DETAIL_BIT, &debug); break; case 'R': __set_bit(DONT_RESPAWN_BIT, &debug); break; #ifdef _WITH_VRRP_ case 'X': __set_bit(RELEASE_VIPS_BIT, &debug); break; #endif case 'S': if (!read_unsigned(optarg, &facility, 0, LOG_FACILITY_MAX, false)) fprintf(stderr, "Invalid log facility '%s'\n", optarg); else { log_facility = LOG_FACILITY[facility].facility; reopen_log = true; } break; case 'g': if (optarg && optarg[0]) log_file_name = optarg; else log_file_name = "/tmp/keepalived.log"; open_log_file(log_file_name, NULL, NULL, NULL); break; case 'G': __set_bit(NO_SYSLOG_BIT, &debug); reopen_log = true; break; case 'u': new_umask_val = set_umask(optarg); if (umask_cmdline) umask_val = new_umask_val; break; case 't': __set_bit(CONFIG_TEST_BIT, &debug); __set_bit(DONT_RESPAWN_BIT, &debug); __set_bit(DONT_FORK_BIT, &debug); __set_bit(NO_SYSLOG_BIT, &debug); if (optarg && optarg[0]) { int fd = open(optarg, O_WRONLY | O_APPEND | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); if (fd == -1) { fprintf(stderr, "Unable to open config-test log file %s\n", optarg); exit(EXIT_FAILURE); } dup2(fd, STDERR_FILENO); close(fd); } break; case 'f': conf_file = optarg; break; case 2: /* --flush-log-file */ set_flush_log_file(); break; #if defined _WITH_VRRP_ && defined _WITH_LVS_ case 'P': __clear_bit(DAEMON_CHECKERS, &daemon_mode); break; case 'C': __clear_bit(DAEMON_VRRP, &daemon_mode); break; #endif #ifdef _WITH_BFD_ case 'B': __clear_bit(DAEMON_BFD, &daemon_mode); break; #endif case 'p': main_pidfile = optarg; break; #ifdef _WITH_LVS_ case 'c': checkers_pidfile = optarg; break; case 'a': __set_bit(LOG_ADDRESS_CHANGES, &debug); break; #endif #ifdef _WITH_VRRP_ case 'r': vrrp_pidfile = optarg; break; #endif #ifdef _WITH_BFD_ case 'b': bfd_pidfile = optarg; break; #endif #ifdef _WITH_SNMP_ case 'x': snmp = 1; break; case 'A': snmp_socket = optarg; break; #endif case 'M': set_core_dump_pattern = true; if (optarg && optarg[0]) core_dump_pattern = optarg; /* ... falls through ... */ case 'm': create_core_dump = true; break; #ifdef _MEM_CHECK_LOG_ case 'L': __set_bit(MEM_CHECK_LOG_BIT, &debug); break; #endif #if HAVE_DECL_CLONE_NEWNET case 's': override_namespace = MALLOC(strlen(optarg) + 1); strcpy(override_namespace, optarg); break; #endif case 'i': FREE_PTR(config_id); config_id = MALLOC(strlen(optarg) + 1); strcpy(config_id, optarg); break; case 4: /* --signum */ signum = get_signum(optarg); if (signum == -1) { fprintf(stderr, "Unknown sigfunc %s\n", optarg); exit(1); } printf("%d\n", signum); exit(0); break; case 3: /* --all */ __set_bit(RUN_ALL_CHILDREN, &daemon_mode); #ifdef _WITH_VRRP_ __set_bit(DAEMON_VRRP, &daemon_mode); #endif #ifdef _WITH_LVS_ __set_bit(DAEMON_CHECKERS, &daemon_mode); #endif #ifdef _WITH_BFD_ __set_bit(DAEMON_BFD, &daemon_mode); #endif break; #ifdef _WITH_PERF_ case 5: if (optarg && optarg[0]) { if (!strcmp(optarg, "run")) perf_run = PERF_RUN; else if (!strcmp(optarg, "all")) perf_run = PERF_ALL; else if (!strcmp(optarg, "end")) perf_run = PERF_END; else log_message(LOG_INFO, "Unknown perf start point %s", optarg); } else perf_run = PERF_RUN; break; #endif #ifdef WITH_DEBUG_OPTIONS case 6: set_debug_options(optarg && optarg[0] ? optarg : NULL); break; #endif case '?': if (optopt && argv[curind][1] != '-') fprintf(stderr, "Unknown option -%c\n", optopt); else fprintf(stderr, "Unknown option %s\n", argv[curind]); bad_option = true; break; case ':': if (optopt && argv[curind][1] != '-') fprintf(stderr, "Missing parameter for option -%c\n", optopt); else fprintf(stderr, "Missing parameter for option --%s\n", long_options[longindex].name); bad_option = true; break; default: exit(1); break; } curind = optind; } if (optind < argc) { printf("Unexpected argument(s): "); while (optind < argc) printf("%s ", argv[optind++]); printf("\n"); } if (bad_option) exit(1); return reopen_log; } #ifdef THREAD_DUMP static void register_parent_thread_addresses(void) { register_scheduler_addresses(); register_signal_thread_addresses(); #ifdef _WITH_LVS_ register_check_parent_addresses(); #endif #ifdef _WITH_VRRP_ register_vrrp_parent_addresses(); #endif #ifdef _WITH_BFD_ register_bfd_parent_addresses(); #endif #ifndef _DEBUG_ register_signal_handler_address("propagate_signal", propagate_signal); register_signal_handler_address("sigend", sigend); #endif register_signal_handler_address("thread_child_handler", thread_child_handler); } #endif /* Entry point */ int keepalived_main(int argc, char **argv) { bool report_stopped = true; struct utsname uname_buf; char *end; /* Ensure time_now is set. We then don't have to check anywhere * else if it is set. */ set_time_now(); /* Save command line options in case need to log them later */ save_cmd_line_options(argc, argv); /* Init debugging level */ debug = 0; /* We are the parent process */ #ifndef _DEBUG_ prog_type = PROG_TYPE_PARENT; #endif /* Initialise daemon_mode */ #ifdef _WITH_VRRP_ __set_bit(DAEMON_VRRP, &daemon_mode); #endif #ifdef _WITH_LVS_ __set_bit(DAEMON_CHECKERS, &daemon_mode); #endif #ifdef _WITH_BFD_ __set_bit(DAEMON_BFD, &daemon_mode); #endif /* Set default file creation mask */ umask(022); /* Open log with default settings so we can log initially */ openlog(PACKAGE_NAME, LOG_PID, log_facility); #ifdef _MEM_CHECK_ mem_log_init(PACKAGE_NAME, "Parent process"); #endif /* Some functionality depends on kernel version, so get the version here */ if (uname(&uname_buf)) log_message(LOG_INFO, "Unable to get uname() information - error %d", errno); else { os_major = (unsigned)strtoul(uname_buf.release, &end, 10); if (*end != '.') os_major = 0; else { os_minor = (unsigned)strtoul(end + 1, &end, 10); if (*end != '.') os_major = 0; else { if (!isdigit(end[1])) os_major = 0; else os_release = (unsigned)strtoul(end + 1, &end, 10); } } if (!os_major) log_message(LOG_INFO, "Unable to parse kernel version %s", uname_buf.release); /* config_id defaults to hostname */ if (!config_id) { end = strchrnul(uname_buf.nodename, '.'); config_id = MALLOC((size_t)(end - uname_buf.nodename) + 1); strncpy(config_id, uname_buf.nodename, (size_t)(end - uname_buf.nodename)); config_id[end - uname_buf.nodename] = '\0'; } } /* * Parse command line and set debug level. * bits 0..7 reserved by main.c */ if (parse_cmdline(argc, argv)) { closelog(); if (!__test_bit(NO_SYSLOG_BIT, &debug)) openlog(PACKAGE_NAME, LOG_PID | ((__test_bit(LOG_CONSOLE_BIT, &debug)) ? LOG_CONS : 0) , log_facility); } if (__test_bit(LOG_CONSOLE_BIT, &debug)) enable_console_log(); #ifdef GIT_COMMIT log_message(LOG_INFO, "Starting %s, git commit %s", version_string, GIT_COMMIT); #else log_message(LOG_INFO, "Starting %s", version_string); #endif /* Handle any core file requirements */ core_dump_init(); if (os_major) { if (KERNEL_VERSION(os_major, os_minor, os_release) < LINUX_VERSION_CODE) { /* keepalived was build for a later kernel version */ log_message(LOG_INFO, "WARNING - keepalived was build for newer Linux %d.%d.%d, running on %s %s %s", (LINUX_VERSION_CODE >> 16) & 0xff, (LINUX_VERSION_CODE >> 8) & 0xff, (LINUX_VERSION_CODE ) & 0xff, uname_buf.sysname, uname_buf.release, uname_buf.version); } else { /* keepalived was build for a later kernel version */ log_message(LOG_INFO, "Running on %s %s %s (built for Linux %d.%d.%d)", uname_buf.sysname, uname_buf.release, uname_buf.version, (LINUX_VERSION_CODE >> 16) & 0xff, (LINUX_VERSION_CODE >> 8) & 0xff, (LINUX_VERSION_CODE ) & 0xff); } } #ifndef _DEBUG_ log_command_line(0); #endif /* Check we can read the configuration file(s). NOTE: the working directory will be / if we forked, but will be the current working directory when keepalived was run if we haven't forked. This means that if any config file names are not absolute file names, the behaviour will be different depending on whether we forked or not. */ if (!check_conf_file(conf_file)) { if (__test_bit(CONFIG_TEST_BIT, &debug)) config_test_exit(); goto end; } global_data = alloc_global_data(); global_data->umask = umask_val; read_config_file(); init_global_data(global_data, NULL); #if HAVE_DECL_CLONE_NEWNET if (override_namespace) { if (global_data->network_namespace) { log_message(LOG_INFO, "Overriding config net_namespace '%s' with command line namespace '%s'", global_data->network_namespace, override_namespace); FREE(global_data->network_namespace); } global_data->network_namespace = override_namespace; override_namespace = NULL; } #endif if (!__test_bit(CONFIG_TEST_BIT, &debug) && (global_data->instance_name #if HAVE_DECL_CLONE_NEWNET || global_data->network_namespace #endif )) { if ((syslog_ident = make_syslog_ident(PACKAGE_NAME))) { log_message(LOG_INFO, "Changing syslog ident to %s", syslog_ident); closelog(); openlog(syslog_ident, LOG_PID | ((__test_bit(LOG_CONSOLE_BIT, &debug)) ? LOG_CONS : 0), log_facility); } else log_message(LOG_INFO, "Unable to change syslog ident"); use_pid_dir = true; open_log_file(log_file_name, NULL, #if HAVE_DECL_CLONE_NEWNET global_data->network_namespace, #else NULL, #endif global_data->instance_name); } /* Initialise pointer to child finding function */ set_child_finder_name(find_keepalived_child_name); if (!__test_bit(CONFIG_TEST_BIT, &debug)) { if (use_pid_dir) { /* Create the directory for pid files */ create_pid_dir(); } } #if HAVE_DECL_CLONE_NEWNET if (global_data->network_namespace) { if (global_data->network_namespace && !set_namespaces(global_data->network_namespace)) { log_message(LOG_ERR, "Unable to set network namespace %s - exiting", global_data->network_namespace); goto end; } } #endif if (!__test_bit(CONFIG_TEST_BIT, &debug)) { if (global_data->instance_name) { if (!main_pidfile && (main_pidfile = make_pidfile_name(KEEPALIVED_PID_DIR KEEPALIVED_PID_FILE, global_data->instance_name, PID_EXTENSION))) free_main_pidfile = true; #ifdef _WITH_LVS_ if (!checkers_pidfile && (checkers_pidfile = make_pidfile_name(KEEPALIVED_PID_DIR CHECKERS_PID_FILE, global_data->instance_name, PID_EXTENSION))) free_checkers_pidfile = true; #endif #ifdef _WITH_VRRP_ if (!vrrp_pidfile && (vrrp_pidfile = make_pidfile_name(KEEPALIVED_PID_DIR VRRP_PID_FILE, global_data->instance_name, PID_EXTENSION))) free_vrrp_pidfile = true; #endif #ifdef _WITH_BFD_ if (!bfd_pidfile && (bfd_pidfile = make_pidfile_name(KEEPALIVED_PID_DIR VRRP_PID_FILE, global_data->instance_name, PID_EXTENSION))) free_bfd_pidfile = true; #endif } if (use_pid_dir) { if (!main_pidfile) main_pidfile = KEEPALIVED_PID_DIR KEEPALIVED_PID_FILE PID_EXTENSION; #ifdef _WITH_LVS_ if (!checkers_pidfile) checkers_pidfile = KEEPALIVED_PID_DIR CHECKERS_PID_FILE PID_EXTENSION; #endif #ifdef _WITH_VRRP_ if (!vrrp_pidfile) vrrp_pidfile = KEEPALIVED_PID_DIR VRRP_PID_FILE PID_EXTENSION; #endif #ifdef _WITH_BFD_ if (!bfd_pidfile) bfd_pidfile = KEEPALIVED_PID_DIR BFD_PID_FILE PID_EXTENSION; #endif } else { if (!main_pidfile) main_pidfile = PID_DIR KEEPALIVED_PID_FILE PID_EXTENSION; #ifdef _WITH_LVS_ if (!checkers_pidfile) checkers_pidfile = PID_DIR CHECKERS_PID_FILE PID_EXTENSION; #endif #ifdef _WITH_VRRP_ if (!vrrp_pidfile) vrrp_pidfile = PID_DIR VRRP_PID_FILE PID_EXTENSION; #endif #ifdef _WITH_BFD_ if (!bfd_pidfile) bfd_pidfile = PID_DIR BFD_PID_FILE PID_EXTENSION; #endif } /* Check if keepalived is already running */ if (keepalived_running(daemon_mode)) { log_message(LOG_INFO, "daemon is already running"); report_stopped = false; goto end; } } /* daemonize process */ if (!__test_bit(DONT_FORK_BIT, &debug) && xdaemon(false, false, true) > 0) { closelog(); FREE_PTR(config_id); FREE_PTR(orig_core_dump_pattern); close_std_fd(); exit(0); } #ifdef _MEM_CHECK_ enable_mem_log_termination(); #endif if (__test_bit(CONFIG_TEST_BIT, &debug)) { validate_config(); config_test_exit(); } /* write the father's pidfile */ if (!pidfile_write(main_pidfile, getpid())) goto end; /* Create the master thread */ master = thread_make_master(); /* Signal handling initialization */ signal_init(); /* Init daemon */ if (!start_keepalived()) log_message(LOG_INFO, "Warning - keepalived has no configuration to run"); initialise_debug_options(); #ifdef THREAD_DUMP register_parent_thread_addresses(); #endif /* Launch the scheduling I/O multiplexer */ launch_thread_scheduler(master); /* Finish daemon process */ stop_keepalived(); #ifdef THREAD_DUMP deregister_thread_addresses(); #endif /* * Reached when terminate signal catched. * finally return from system */ end: if (report_stopped) { #ifdef GIT_COMMIT log_message(LOG_INFO, "Stopped %s, git commit %s", version_string, GIT_COMMIT); #else log_message(LOG_INFO, "Stopped %s", version_string); #endif } #if HAVE_DECL_CLONE_NEWNET if (global_data && global_data->network_namespace) clear_namespaces(); #endif if (use_pid_dir) remove_pid_dir(); /* Restore original core_pattern if necessary */ if (orig_core_dump_pattern) update_core_dump_pattern(orig_core_dump_pattern); free_parent_mallocs_startup(false); free_parent_mallocs_exit(); free_global_data(global_data); closelog(); #ifndef _MEM_CHECK_LOG_ FREE_PTR(syslog_ident); #else if (syslog_ident) free(syslog_ident); #endif close_std_fd(); exit(KEEPALIVED_EXIT_OK); }
./CrossVul/dataset_final_sorted/CWE-59/c/bad_436_0
crossvul-cpp_data_bad_436_12
/* * Soft: Keepalived is a failover program for the LVS project * <www.linuxvirtualserver.org>. It monitor & manipulate * a loadbalanced server pool using multi-layer checks. * * Part: General program utils. * * Author: Alexandre Cassen, <acassen@linux-vs.org> * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. * * Copyright (C) 2001-2017 Alexandre Cassen, <acassen@gmail.com> */ #include "config.h" /* System includes */ #include <string.h> #include <unistd.h> #include <fcntl.h> #include <stdlib.h> #include <netdb.h> #include <arpa/inet.h> #include <sys/utsname.h> #include <stdint.h> #include <errno.h> #ifdef _WITH_PERF_ #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/epoll.h> #include <sys/inotify.h> #endif #if !defined _HAVE_LIBIPTC_ || defined _LIBIPTC_DYNAMIC_ #include <signal.h> #include <sys/wait.h> #endif #ifdef _WITH_STACKTRACE_ #include <sys/stat.h> #include <execinfo.h> #include <memory.h> #endif /* Local includes */ #include "utils.h" #include "memory.h" #include "utils.h" #include "signals.h" #include "bitops.h" #include "parser.h" #if !defined _HAVE_LIBIPTC_ || defined _LIBIPTC_DYNAMIC_ || defined _WITH_STACKTRACE_ || defined _WITH_PERF_ #include "logger.h" #endif #if !defined _HAVE_LIBIPTC_ || defined _LIBIPTC_DYNAMIC_ #include "process.h" #endif /* global vars */ unsigned long debug = 0; /* Display a buffer into a HEXA formated output */ void dump_buffer(char *buff, size_t count, FILE* fp, int indent) { size_t i, j, c; bool printnext = true; if (count % 16) c = count + (16 - count % 16); else c = count; for (i = 0; i < c; i++) { if (printnext) { printnext = false; fprintf(fp, "%*s%.4zu ", indent, "", i & 0xffff); } if (i < count) fprintf(fp, "%3.2x", buff[i] & 0xff); else fprintf(fp, " "); if (!((i + 1) % 8)) { if ((i + 1) % 16) fprintf(fp, " -"); else { fprintf(fp, " "); for (j = i - 15; j <= i; j++) if (j < count) { if ((buff[j] & 0xff) >= 0x20 && (buff[j] & 0xff) <= 0x7e) fprintf(fp, "%c", buff[j] & 0xff); else fprintf(fp, "."); } else fprintf(fp, " "); fprintf(fp, "\n"); printnext = true; } } } } #ifdef _WITH_STACKTRACE_ void write_stacktrace(const char *file_name, const char *str) { int fd; void *buffer[100]; int nptrs; int i; char **strs; nptrs = backtrace(buffer, 100); if (file_name) { fd = open(file_name, O_WRONLY | O_APPEND | O_CREAT, 0644); if (str) dprintf(fd, "%s\n", str); backtrace_symbols_fd(buffer, nptrs, fd); if (write(fd, "\n", 1) != 1) { /* We don't care, but this stops a warning on Ubuntu */ } close(fd); } else { if (str) log_message(LOG_INFO, "%s", str); strs = backtrace_symbols(buffer, nptrs); if (strs == NULL) { log_message(LOG_INFO, "Unable to get stack backtrace"); return; } /* We don't need the call to this function, or the first two entries on the stack */ for (i = 1; i < nptrs - 2; i++) log_message(LOG_INFO, " %s", strs[i]); free(strs); } } #endif char * make_file_name(const char *name, const char *prog, const char *namespace, const char *instance) { const char *extn_start; const char *dir_end; size_t len; char *file_name; if (!name) return NULL; len = strlen(name); if (prog) len += strlen(prog) + 1; if (namespace) len += strlen(namespace) + 1; if (instance) len += strlen(instance) + 1; file_name = MALLOC(len + 1); dir_end = strrchr(name, '/'); extn_start = strrchr(dir_end ? dir_end : name, '.'); strncpy(file_name, name, extn_start ? (size_t)(extn_start - name) : len); if (prog) { strcat(file_name, "_"); strcat(file_name, prog); } if (namespace) { strcat(file_name, "_"); strcat(file_name, namespace); } if (instance) { strcat(file_name, "_"); strcat(file_name, instance); } if (extn_start) strcat(file_name, extn_start); return file_name; } #ifdef _WITH_PERF_ void run_perf(const char *process, const char *network_namespace, const char *instance_name) { int ret; pid_t pid; char *orig_name = NULL; char *new_name; const char *perf_name = "perf.data"; int in = -1; int ep = -1; do { orig_name = MALLOC(PATH_MAX); if (!getcwd(orig_name, PATH_MAX)) { log_message(LOG_INFO, "Unable to get cwd"); break; } #ifdef IN_CLOEXEC in = inotify_init1(IN_CLOEXEC | IN_NONBLOCK); #else if ((in = inotify_init()) != -1) { fcntl(in, F_SETFD, FD_CLOEXEC | fcntl(n, F_GETFD)); fcntl(in, F_SETFL, O_NONBLOCK | fcntl(n, F_GETFL)); } #endif if (in == -1) { log_message(LOG_INFO, "inotify_init failed %d - %m", errno); break; } if (inotify_add_watch(in, orig_name, IN_CREATE) == -1) { log_message(LOG_INFO, "inotify_add_watch of %s failed %d - %m", orig_name, errno); break; } pid = fork(); if (pid == -1) { log_message(LOG_INFO, "fork() for perf failed"); break; } /* Child */ if (!pid) { char buf[9]; snprintf(buf, sizeof buf, "%d", getppid()); execlp("perf", "perf", "record", "-p", buf, "-q", "-g", "--call-graph", "fp", NULL); exit(0); } /* Parent */ char buf[sizeof(struct inotify_event) + NAME_MAX + 1]; struct inotify_event *ie = (struct inotify_event*)buf; struct epoll_event ee = { .events = EPOLLIN, .data.fd = in }; if ((ep = epoll_create(1)) == -1) { log_message(LOG_INFO, "perf epoll_create failed errno %d - %m", errno); break; } if (epoll_ctl(ep, EPOLL_CTL_ADD, in, &ee) == -1) { log_message(LOG_INFO, "perf epoll_ctl failed errno %d - %m", errno); break; } do { ret = epoll_wait(ep, &ee, 1, 1000); if (ret == 0) { log_message(LOG_INFO, "Timed out waiting for creation of %s", perf_name); break; } else if (ret == -1) { if (errno == EINTR) continue; log_message(LOG_INFO, "perf epoll returned errno %d - %m", errno); break; } ret = read(in, buf, sizeof(buf)); if (ret == -1) { if (errno == EINTR) continue; log_message(LOG_INFO, "perf inotify read returned errno %d %m", errno); break; } if (ret < (int)sizeof(*ie)) { log_message(LOG_INFO, "read returned %d", ret); break; } if (!(ie->mask & IN_CREATE)) { log_message(LOG_INFO, "mask is 0x%x", ie->mask); continue; } if (!ie->len) { log_message(LOG_INFO, "perf inotify read returned no len"); continue; } if (strcmp(ie->name, perf_name)) continue; /* Rename the /perf.data file */ strcat(orig_name, perf_name); new_name = make_file_name(orig_name, process, #if HAVE_DECL_CLONE_NEWNET network_namespace, #else NULL, #endif instance_name); if (rename(orig_name, new_name)) log_message(LOG_INFO, "Rename %s to %s failed - %m (%d)", orig_name, new_name, errno); FREE(new_name); } while (false); } while (false); if (ep != -1) close(ep); if (in != -1) close(in); if (orig_name) FREE(orig_name); } #endif /* Compute a checksum */ uint16_t in_csum(const uint16_t *addr, size_t len, uint32_t csum, uint32_t *acc) { register size_t nleft = len; const uint16_t *w = addr; register uint16_t answer; register uint32_t sum = csum; /* * Our algorithm is simple, using a 32 bit accumulator (sum), * we add sequential 16 bit words to it, and at the end, fold * back all the carry bits from the top 16 bits into the lower * 16 bits. */ while (nleft > 1) { sum += *w++; nleft -= 2; } /* mop up an odd byte, if necessary */ if (nleft == 1) sum += htons(*(u_char *) w << 8); if (acc) *acc = sum; /* * add back carry outs from top 16 bits to low 16 bits */ sum = (sum >> 16) + (sum & 0xffff); /* add hi 16 to low 16 */ sum += (sum >> 16); /* add carry */ answer = (~sum & 0xffff); /* truncate to 16 bits */ return (answer); } /* IP network to ascii representation */ char * inet_ntop2(uint32_t ip) { static char buf[16]; unsigned char *bytep; bytep = (unsigned char *) &(ip); sprintf(buf, "%d.%d.%d.%d", bytep[0], bytep[1], bytep[2], bytep[3]); return buf; } #ifdef _INCLUDE_UNUSED_CODE_ /* * IP network to ascii representation. To use * for multiple IP address convertion into the same call. */ char * inet_ntoa2(uint32_t ip, char *buf) { unsigned char *bytep; bytep = (unsigned char *) &(ip); sprintf(buf, "%d.%d.%d.%d", bytep[0], bytep[1], bytep[2], bytep[3]); return buf; } #endif /* IP string to network range representation. */ bool inet_stor(const char *addr, uint32_t *range_end) { const char *cp; char *endptr; unsigned long range; int family = strchr(addr, ':') ? AF_INET6 : AF_INET; char *warn = ""; #ifndef _STRICT_CONFIG_ if (!__test_bit(CONFIG_TEST_BIT, &debug)) warn = "WARNING - "; #endif /* Return UINT32_MAX to indicate no range */ if (!(cp = strchr(addr, '-'))) { *range_end = UINT32_MAX; return true; } errno = 0; range = strtoul(cp + 1, &endptr, family == AF_INET6 ? 16 : 10); *range_end = range; if (*endptr) report_config_error(CONFIG_INVALID_NUMBER, "%sVirtual server group range '%s' has extra characters at end '%s'", warn, addr, endptr); else if (errno == ERANGE || (family == AF_INET6 && range > 0xffff) || (family == AF_INET && range > 255)) { report_config_error(CONFIG_INVALID_NUMBER, "Virtual server group range '%s' end '%s' too large", addr, cp + 1); /* Indicate error */ return false; } else return true; #ifdef _STRICT_CONFIG_ return false; #else return !__test_bit(CONFIG_TEST_BIT, &debug); #endif } /* Domain to sockaddr_storage */ int domain_stosockaddr(const char *domain, const char *port, struct sockaddr_storage *addr) { struct addrinfo *res = NULL; unsigned port_num; if (port) { if (!read_unsigned(port, &port_num, 1, 65535, true)) { addr->ss_family = AF_UNSPEC; return -1; } } if (getaddrinfo(domain, NULL, NULL, &res) != 0 || !res) { addr->ss_family = AF_UNSPEC; return -1; } addr->ss_family = (sa_family_t)res->ai_family; if (addr->ss_family == AF_INET6) { struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)addr; *addr6 = *(struct sockaddr_in6 *)res->ai_addr; if (port) addr6->sin6_port = htons(port_num); } else { struct sockaddr_in *addr4 = (struct sockaddr_in *)addr; *addr4 = *(struct sockaddr_in *)res->ai_addr; if (port) addr4->sin_port = htons(port_num); } freeaddrinfo(res); return 0; } /* IP string to sockaddr_storage */ int inet_stosockaddr(char *ip, const char *port, struct sockaddr_storage *addr) { void *addr_ip; char *cp; char sav_cp; unsigned port_num; int res; addr->ss_family = (strchr(ip, ':')) ? AF_INET6 : AF_INET; if (port) { if (!read_unsigned(port, &port_num, 1, 65535, true)) { addr->ss_family = AF_UNSPEC; return -1; } } if (addr->ss_family == AF_INET6) { struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *) addr; if (port) addr6->sin6_port = htons(port_num); addr_ip = &addr6->sin6_addr; } else { struct sockaddr_in *addr4 = (struct sockaddr_in *) addr; if (port) addr4->sin_port = htons(port_num); addr_ip = &addr4->sin_addr; } /* remove range and mask stuff */ if ((cp = strchr(ip, '-')) || (cp = strchr(ip, '/'))) { sav_cp = *cp; *cp = 0; } res = inet_pton(addr->ss_family, ip, addr_ip); /* restore range and mask stuff */ if (cp) *cp = sav_cp; if (!res) { addr->ss_family = AF_UNSPEC; return -1; } return 0; } /* IPv4 to sockaddr_storage */ void inet_ip4tosockaddr(struct in_addr *sin_addr, struct sockaddr_storage *addr) { struct sockaddr_in *addr4 = (struct sockaddr_in *) addr; addr4->sin_family = AF_INET; addr4->sin_addr = *sin_addr; } /* IPv6 to sockaddr_storage */ void inet_ip6tosockaddr(struct in6_addr *sin_addr, struct sockaddr_storage *addr) { struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *) addr; addr6->sin6_family = AF_INET6; addr6->sin6_addr = *sin_addr; } /* IP network to string representation */ static char * inet_sockaddrtos2(struct sockaddr_storage *addr, char *addr_str) { void *addr_ip; if (addr->ss_family == AF_INET6) { struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *) addr; addr_ip = &addr6->sin6_addr; } else { struct sockaddr_in *addr4 = (struct sockaddr_in *) addr; addr_ip = &addr4->sin_addr; } if (!inet_ntop(addr->ss_family, addr_ip, addr_str, INET6_ADDRSTRLEN)) return NULL; return addr_str; } char * inet_sockaddrtos(struct sockaddr_storage *addr) { static char addr_str[INET6_ADDRSTRLEN]; inet_sockaddrtos2(addr, addr_str); return addr_str; } uint16_t inet_sockaddrport(struct sockaddr_storage *addr) { uint16_t port; if (addr->ss_family == AF_INET6) { struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *) addr; port = addr6->sin6_port; } else { /* Note: this might be AF_UNSPEC if it is the sequence number of * a virtual server in a virtual server group */ struct sockaddr_in *addr4 = (struct sockaddr_in *) addr; port = addr4->sin_port; } return port; } char * inet_sockaddrtopair(struct sockaddr_storage *addr) { char addr_str[INET6_ADDRSTRLEN]; static char ret[sizeof(addr_str) + 8]; /* '[' + addr_str + ']' + ':' + 'nnnnn' */ inet_sockaddrtos2(addr, addr_str); snprintf(ret, sizeof(ret), "[%s]:%d" , addr_str , ntohs(inet_sockaddrport(addr))); return ret; } char * inet_sockaddrtotrio(struct sockaddr_storage *addr, uint16_t proto) { char addr_str[INET6_ADDRSTRLEN]; static char ret[sizeof(addr_str) + 13]; /* '[' + addr_str + ']' + ':' + 'sctp' + ':' + 'nnnnn' */ char *proto_str = proto == IPPROTO_TCP ? "tcp" : proto == IPPROTO_UDP ? "udp" : proto == IPPROTO_SCTP ? "sctp" : proto == 0 ? "none" : "?"; inet_sockaddrtos2(addr, addr_str); snprintf(ret, sizeof(ret), "[%s]:%s:%d" ,addr_str, proto_str, ntohs(inet_sockaddrport(addr))); return ret; } uint32_t inet_sockaddrip4(struct sockaddr_storage *addr) { if (addr->ss_family != AF_INET) return 0xffffffff; return ((struct sockaddr_in *) addr)->sin_addr.s_addr; } int inet_sockaddrip6(struct sockaddr_storage *addr, struct in6_addr *ip6) { if (addr->ss_family != AF_INET6) return -1; *ip6 = ((struct sockaddr_in6 *) addr)->sin6_addr; return 0; } /* IPv6 address compare */ int inet_inaddrcmp(const int family, const void *a, const void *b) { int64_t addr_diff; if (family == AF_INET) { addr_diff = (int64_t)ntohl(*((const uint32_t *) a)) - (int64_t)ntohl(*((const uint32_t *) b)); if (addr_diff > 0) return 1; if (addr_diff < 0) return -1; return 0; } if (family == AF_INET6) { int i; for (i = 0; i < 4; i++ ) { addr_diff = (int64_t)ntohl(((const uint32_t *) (a))[i]) - (int64_t)ntohl(((const uint32_t *) (b))[i]); if (addr_diff > 0) return 1; if (addr_diff < 0) return -1; } return 0; } return -2; } int inet_sockaddrcmp(const struct sockaddr_storage *a, const struct sockaddr_storage *b) { if (a->ss_family != b->ss_family) return -2; if (a->ss_family == AF_INET) return inet_inaddrcmp(a->ss_family, &((struct sockaddr_in *) a)->sin_addr, &((struct sockaddr_in *) b)->sin_addr); if (a->ss_family == AF_INET6) return inet_inaddrcmp(a->ss_family, &((struct sockaddr_in6 *) a)->sin6_addr, &((struct sockaddr_in6 *) b)->sin6_addr); return 0; } #ifdef _INCLUDE_UNUSED_CODE_ /* * IP string to network representation * Highly inspired from Paul Vixie code. */ int inet_ston(const char *addr, uint32_t * dst) { static char digits[] = "0123456789"; int saw_digit, octets, ch; u_char tmp[INADDRSZ], *tp; saw_digit = 0; octets = 0; *(tp = tmp) = 0; while ((ch = *addr++) != '\0' && ch != '/' && ch != '-') { const char *pch; if ((pch = strchr(digits, ch)) != NULL) { u_int new = *tp * 10 + (pch - digits); if (new > 255) return 0; *tp = new; if (!saw_digit) { if (++octets > 4) return 0; saw_digit = 1; } } else if (ch == '.' && saw_digit) { if (octets == 4) return 0; *++tp = 0; saw_digit = 0; } else return 0; } if (octets < 4) return 0; memcpy(dst, tmp, INADDRSZ); return 1; } /* * Return broadcast address from network and netmask. */ uint32_t inet_broadcast(uint32_t network, uint32_t netmask) { return 0xffffffff - netmask + network; } /* * Convert CIDR netmask notation to long notation. */ uint32_t inet_cidrtomask(uint8_t cidr) { uint32_t mask = 0; int b; for (b = 0; b < cidr; b++) mask |= (1 << (31 - b)); return ntohl(mask); } #endif /* Getting localhost official canonical name */ char * get_local_name(void) { struct utsname name; struct addrinfo hints, *res = NULL; char *canonname = NULL; size_t len = 0; memset(&hints, 0, sizeof(struct addrinfo)); hints.ai_flags = AI_CANONNAME; if (uname(&name) < 0) return NULL; if (getaddrinfo(name.nodename, NULL, &hints, &res) != 0) return NULL; if (res && res->ai_canonname) { len = strlen(res->ai_canonname); canonname = MALLOC(len + 1); if (canonname) { memcpy(canonname, res->ai_canonname, len); } } freeaddrinfo(res); return canonname; } /* String compare with NULL string handling */ bool string_equal(const char *str1, const char *str2) { if (!str1 && !str2) return true; if (!str1 != !str2) return false; return !strcmp(str1, str2); } void set_std_fd(bool force) { int fd; if (force || __test_bit(DONT_FORK_BIT, &debug)) { fd = open("/dev/null", O_RDWR); if (fd != -1) { dup2(fd, STDIN_FILENO); dup2(fd, STDOUT_FILENO); dup2(fd, STDERR_FILENO); if (fd > STDERR_FILENO) close(fd); } } signal_fd_close(STDERR_FILENO+1); } void close_std_fd(void) { close(STDIN_FILENO); close(STDOUT_FILENO); close(STDERR_FILENO); } #if !defined _HAVE_LIBIPTC_ || defined _LIBIPTC_DYNAMIC_ int fork_exec(char **argv) { pid_t pid; int status; struct sigaction act, old_act; int res = 0; act.sa_handler = SIG_DFL; sigemptyset(&act.sa_mask); act.sa_flags = 0; sigaction(SIGCHLD, &act, &old_act); if (log_file_name) flush_log_file(); pid = local_fork(); if (pid < 0) res = -1; else if (pid == 0) { /* Child */ set_std_fd(false); signal_handler_script(); execvp(*argv, argv); exit(EXIT_FAILURE); } else { /* Parent */ while (waitpid(pid, &status, 0) != pid); if (!WIFEXITED(status) || WEXITSTATUS(status) != EXIT_SUCCESS) res = -1; } sigaction(SIGCHLD, &old_act, NULL); return res; } #endif #if defined _WITH_VRRP_ || defined _WITH_BFD_ int open_pipe(int pipe_arr[2]) { /* Open pipe */ #ifdef HAVE_PIPE2 if (pipe2(pipe_arr, O_CLOEXEC | O_NONBLOCK) == -1) #else if (pipe(pipe_arr) == -1) #endif return -1; #ifndef HAVE_PIPE2 fcntl(pipe_arr[0], F_SETFL, O_NONBLOCK | fcntl(pipe_arr[0], F_GETFL)); fcntl(pipe_arr[1], F_SETFL, O_NONBLOCK | fcntl(pipe_arr[1], F_GETFL)); fcntl(pipe_arr[0], F_SETFD, FD_CLOEXEC | fcntl(pipe_arr[0], F_GETFD)); fcntl(pipe_arr[1], F_SETFD, FD_CLOEXEC | fcntl(pipe_arr[1], F_GETFD)); #endif return 0; } #endif
./CrossVul/dataset_final_sorted/CWE-59/c/bad_436_12
crossvul-cpp_data_bad_3264_0
/* * ProFTPD - FTP server daemon * Copyright (c) 1997, 1998 Public Flood Software * Copyright (c) 1999, 2000 MacGyver aka Habeeb J. Dihu <macgyver@tos.net> * Copyright (c) 2001-2017 The ProFTPD Project team * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Suite 500, Boston, MA 02110-1335, USA. * * As a special exemption, Public Flood Software/MacGyver aka Habeeb J. Dihu * and other respective copyright holders give permission to link this program * with OpenSSL, and distribute the resulting executable, without including * the source code for OpenSSL in the source distribution. */ /* Authentication module for ProFTPD */ #include "conf.h" #include "privs.h" #ifdef HAVE_USERSEC_H # include <usersec.h> #endif #ifdef HAVE_SYS_AUDIT_H # include <sys/audit.h> #endif extern pid_t mpid; module auth_module; #ifdef PR_USE_LASTLOG static unsigned char lastlog = FALSE; #endif /* PR_USE_LASTLOG */ static unsigned char mkhome = FALSE; static unsigned char authenticated_without_pass = FALSE; static int TimeoutLogin = PR_TUNABLE_TIMEOUTLOGIN; static int logged_in = FALSE; static int auth_anon_allow_robots = FALSE; static int auth_anon_allow_robots_enabled = FALSE; static int auth_client_connected = FALSE; static unsigned int auth_tries = 0; static char *auth_pass_resp_code = R_230; static pr_fh_t *displaylogin_fh = NULL; static int TimeoutSession = 0; static int saw_first_user_cmd = FALSE; static const char *timing_channel = "timing"; static int auth_count_scoreboard(cmd_rec *, const char *); static int auth_scan_scoreboard(void); static int auth_sess_init(void); /* auth_cmd_chk_cb() is hooked into the main server's auth_hook function, * so that we can deny all commands until authentication is complete. * * Note: Once this function returns true (i.e. client has authenticated), * it will ALWAYS return true. At least until REIN is implemented. Thus * we have a flag for such a situation, to save on redundant lookups for * the "authenticated" record. */ static int auth_have_authenticated = FALSE; static int auth_cmd_chk_cb(cmd_rec *cmd) { if (auth_have_authenticated == FALSE) { unsigned char *authd; authd = get_param_ptr(cmd->server->conf, "authenticated", FALSE); if (authd == NULL || *authd == FALSE) { pr_response_send(R_530, _("Please login with USER and PASS")); return FALSE; } auth_have_authenticated = TRUE; } return TRUE; } static int auth_login_timeout_cb(CALLBACK_FRAME) { pr_response_send_async(R_421, _("Login timeout (%d %s): closing control connection"), TimeoutLogin, TimeoutLogin != 1 ? "seconds" : "second"); /* It's possible that any listeners of this event might terminate the * session process themselves (e.g. mod_ban). So write out that the * TimeoutLogin has been exceeded to the log here, in addition to the * scheduled session exit message. */ pr_log_pri(PR_LOG_INFO, "%s", "Login timeout exceeded, disconnected"); pr_event_generate("core.timeout-login", NULL); pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_TIMEOUT, "TimeoutLogin"); /* Do not restart the timer (should never be reached). */ return 0; } static int auth_session_timeout_cb(CALLBACK_FRAME) { pr_event_generate("core.timeout-session", NULL); pr_response_send_async(R_421, _("Session Timeout (%d seconds): closing control connection"), TimeoutSession); pr_log_pri(PR_LOG_INFO, "%s", "FTP session timed out, disconnected"); pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_TIMEOUT, "TimeoutSession"); /* no need to restart the timer -- session's over */ return 0; } /* Event listeners */ static void auth_exit_ev(const void *event_data, void *user_data) { pr_auth_cache_clear(); /* Close the scoreboard descriptor that we opened. */ (void) pr_close_scoreboard(FALSE); } static void auth_sess_reinit_ev(const void *event_data, void *user_data) { int res; /* A HOST command changed the main_server pointer, reinitialize ourselves. */ pr_event_unregister(&auth_module, "core.exit", auth_exit_ev); pr_event_unregister(&auth_module, "core.session-reinit", auth_sess_reinit_ev); pr_timer_remove(PR_TIMER_LOGIN, &auth_module); /* Reset the CreateHome setting. */ mkhome = FALSE; /* Reset any MaxPasswordSize setting. */ (void) pr_auth_set_max_password_len(session.pool, 0); #if defined(PR_USE_LASTLOG) lastlog = FALSE; #endif /* PR_USE_LASTLOG */ mkhome = FALSE; res = auth_sess_init(); if (res < 0) { pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_SESSION_INIT_FAILED, NULL); } } /* Initialization functions */ static int auth_init(void) { /* Add the commands handled by this module to the HELP list. */ pr_help_add(C_USER, _("<sp> username"), TRUE); pr_help_add(C_PASS, _("<sp> password"), TRUE); pr_help_add(C_ACCT, _("is not implemented"), FALSE); pr_help_add(C_REIN, _("is not implemented"), FALSE); /* By default, enable auth checking */ set_auth_check(auth_cmd_chk_cb); return 0; } static int auth_sess_init(void) { config_rec *c = NULL; unsigned char *tmp = NULL; pr_event_register(&auth_module, "core.session-reinit", auth_sess_reinit_ev, NULL); /* Check for any MaxPasswordSize. */ c = find_config(main_server->conf, CONF_PARAM, "MaxPasswordSize", FALSE); if (c != NULL) { size_t len; len = *((size_t *) c->argv[0]); (void) pr_auth_set_max_password_len(session.pool, len); } /* Check for a server-specific TimeoutLogin */ c = find_config(main_server->conf, CONF_PARAM, "TimeoutLogin", FALSE); if (c != NULL) { TimeoutLogin = *((int *) c->argv[0]); } /* Start the login timer */ if (TimeoutLogin) { pr_timer_remove(PR_TIMER_LOGIN, &auth_module); pr_timer_add(TimeoutLogin, PR_TIMER_LOGIN, &auth_module, auth_login_timeout_cb, "TimeoutLogin"); } if (auth_client_connected == FALSE) { int res = 0; PRIVS_ROOT res = pr_open_scoreboard(O_RDWR); PRIVS_RELINQUISH if (res < 0) { switch (res) { case PR_SCORE_ERR_BAD_MAGIC: pr_log_debug(DEBUG0, "error opening scoreboard: bad/corrupted file"); break; case PR_SCORE_ERR_OLDER_VERSION: pr_log_debug(DEBUG0, "error opening scoreboard: bad version (too old)"); break; case PR_SCORE_ERR_NEWER_VERSION: pr_log_debug(DEBUG0, "error opening scoreboard: bad version (too new)"); break; default: pr_log_debug(DEBUG0, "error opening scoreboard: %s", strerror(errno)); break; } } } pr_event_register(&auth_module, "core.exit", auth_exit_ev, NULL); if (auth_client_connected == FALSE) { /* Create an entry in the scoreboard for this session, if we don't already * have one. */ if (pr_scoreboard_entry_get(PR_SCORE_CLIENT_ADDR) == NULL) { if (pr_scoreboard_entry_add() < 0) { pr_log_pri(PR_LOG_NOTICE, "notice: unable to add scoreboard entry: %s", strerror(errno)); } pr_scoreboard_entry_update(session.pid, PR_SCORE_USER, "(none)", PR_SCORE_SERVER_PORT, main_server->ServerPort, PR_SCORE_SERVER_ADDR, session.c->local_addr, session.c->local_port, PR_SCORE_SERVER_LABEL, main_server->ServerName, PR_SCORE_CLIENT_ADDR, session.c->remote_addr, PR_SCORE_CLIENT_NAME, session.c->remote_name, PR_SCORE_CLASS, session.conn_class ? session.conn_class->cls_name : "", PR_SCORE_PROTOCOL, "ftp", PR_SCORE_BEGIN_SESSION, time(NULL), NULL); } } else { /* We're probably handling a HOST comand, and the server changed; just * update the SERVER_LABEL field. */ pr_scoreboard_entry_update(session.pid, PR_SCORE_SERVER_LABEL, main_server->ServerName, NULL); } /* Should we create the home for a user, if they don't have one? */ tmp = get_param_ptr(main_server->conf, "CreateHome", FALSE); if (tmp != NULL && *tmp == TRUE) { mkhome = TRUE; } else { mkhome = FALSE; } #ifdef PR_USE_LASTLOG /* Use the lastlog file, if supported and requested. */ tmp = get_param_ptr(main_server->conf, "UseLastlog", FALSE); if (tmp && *tmp == TRUE) { lastlog = TRUE; } else { lastlog = FALSE; } #endif /* PR_USE_LASTLOG */ /* Scan the scoreboard now, in order to tally up certain values for * substituting in any of the Display* file variables. This function * also performs the MaxConnectionsPerHost enforcement. */ auth_scan_scoreboard(); auth_client_connected = TRUE; return 0; } static int do_auth(pool *p, xaset_t *conf, const char *u, char *pw) { char *cpw = NULL; config_rec *c; if (conf != NULL) { c = find_config(conf, CONF_PARAM, "UserPassword", FALSE); while (c != NULL) { pr_signals_handle(); if (strcmp(c->argv[0], u) == 0) { cpw = (char *) c->argv[1]; break; } c = find_config_next(c, c->next, CONF_PARAM, "UserPassword", FALSE); } } if (cpw != NULL) { if (pr_auth_getpwnam(p, u) == NULL) { int xerrno = errno; if (xerrno == ENOENT) { pr_log_pri(PR_LOG_NOTICE, "no such user '%s'", u); } errno = xerrno; return PR_AUTH_NOPWD; } return pr_auth_check(p, cpw, u, pw); } return pr_auth_authenticate(p, u, pw); } /* Command handlers */ static void login_failed(pool *p, const char *user) { #ifdef HAVE_LOGINFAILED const char *host, *sess_ttyname; int res, xerrno; host = pr_netaddr_get_dnsstr(session.c->remote_addr); sess_ttyname = pr_session_get_ttyname(p); PRIVS_ROOT res = loginfailed((char *) user, (char *) host, (char *) sess_ttyname, AUDIT_FAIL); xerrno = errno; PRIVS_RELINQUISH if (res < 0) { pr_trace_msg("auth", 3, "AIX loginfailed() error for user '%s', " "host '%s', tty '%s', reason %d: %s", user, host, sess_ttyname, AUDIT_FAIL, strerror(errno)); } #endif /* HAVE_LOGINFAILED */ } MODRET auth_err_pass(cmd_rec *cmd) { const char *user; user = pr_table_get(session.notes, "mod_auth.orig-user", NULL); if (user != NULL) { login_failed(cmd->tmp_pool, user); } /* Remove the stashed original USER name here in a LOG_CMD_ERR handler, so * that other modules, who may want to lookup the original USER parameter on * a failed login in an earlier command handler phase, have a chance to do * so. This removal of the USER parameter on failure was happening directly * in the CMD handler previously, thus preventing POST_CMD_ERR handlers from * using USER. */ pr_table_remove(session.notes, "mod_auth.orig-user", NULL); return PR_HANDLED(cmd); } MODRET auth_log_pass(cmd_rec *cmd) { /* Only log, to the syslog, that the login has succeeded here, where we * know that the login has definitely succeeded. */ pr_log_auth(PR_LOG_INFO, "%s %s: Login successful.", (session.anon_config != NULL) ? "ANON" : C_USER, session.user); if (cmd->arg != NULL) { size_t passwd_len; /* And scrub the memory holding the password sent by the client, for * safety/security. */ passwd_len = strlen(cmd->arg); pr_memscrub(cmd->arg, passwd_len); } return PR_DECLINED(cmd); } static void login_succeeded(pool *p, const char *user) { #ifdef HAVE_LOGINSUCCESS const char *host, *sess_ttyname; char *msg = NULL; int res, xerrno; host = pr_netaddr_get_dnsstr(session.c->remote_addr); sess_ttyname = pr_session_get_ttyname(p); PRIVS_ROOT res = loginsuccess((char *) user, (char *) host, (char *) sess_ttyname, &msg); xerrno = errno; PRIVS_RELINQUISH if (res == 0) { if (msg != NULL) { pr_trace_msg("auth", 14, "AIX loginsuccess() report: %s", msg); } } else { pr_trace_msg("auth", 3, "AIX loginsuccess() error for user '%s', " "host '%s', tty '%s': %s", user, host, sess_ttyname, strerror(errno)); } if (msg != NULL) { free(msg); } #endif /* HAVE_LOGINSUCCESS */ } MODRET auth_post_pass(cmd_rec *cmd) { config_rec *c = NULL; const char *grantmsg = NULL, *user; unsigned int ctxt_precedence = 0; unsigned char have_user_timeout, have_group_timeout, have_class_timeout, have_all_timeout, *root_revoke = NULL, *authenticated; struct stat st; /* Was there a precending USER command? Was the client successfully * authenticated? */ authenticated = get_param_ptr(cmd->server->conf, "authenticated", FALSE); /* Clear the list of auth-only modules. */ pr_auth_clear_auth_only_modules(); if (authenticated != NULL && *authenticated == TRUE) { /* At this point, we can look up the Protocols config if the client * has been authenticated, which may have been tweaked via mod_ifsession's * user/group/class-specific sections. */ c = find_config(main_server->conf, CONF_PARAM, "Protocols", FALSE); if (c != NULL) { register unsigned int i; array_header *protocols; char **elts; const char *protocol; protocols = c->argv[0]; elts = protocols->elts; protocol = pr_session_get_protocol(PR_SESS_PROTO_FL_LOGOUT); /* We only want to check for 'ftp' in the configured Protocols list * if a) a RFC2228 mechanism (e.g. SSL or GSS) is not in use, and * b) an SSH protocol is not in use. */ if (session.rfc2228_mech == NULL && strncmp(protocol, "SSH2", 5) != 0) { int allow_ftp = FALSE; for (i = 0; i < protocols->nelts; i++) { char *proto; proto = elts[i]; if (proto != NULL) { if (strncasecmp(proto, "ftp", 4) == 0) { allow_ftp = TRUE; break; } } } if (!allow_ftp) { pr_log_debug(DEBUG0, "%s", "ftp protocol denied by Protocols config"); pr_response_send(R_530, "%s", _("Login incorrect.")); pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_CONFIG_ACL, "Denied by Protocols setting"); } } } } user = pr_table_get(session.notes, "mod_auth.orig-user", NULL); /* Count up various quantities in the scoreboard, checking them against * the Max* limits to see if the session should be barred from going * any further. */ auth_count_scoreboard(cmd, session.user); /* Check for dynamic configuration. This check needs to be after the * setting of any possible anon_config, as that context may be allowed * or denied .ftpaccess-parsing separately from the containing server. */ if (pr_fsio_stat(session.cwd, &st) != -1) build_dyn_config(cmd->tmp_pool, session.cwd, &st, TRUE); have_user_timeout = have_group_timeout = have_class_timeout = have_all_timeout = FALSE; c = find_config(TOPLEVEL_CONF, CONF_PARAM, "TimeoutSession", FALSE); while (c != NULL) { pr_signals_handle(); if (c->argc == 3) { if (strncmp(c->argv[1], "user", 5) == 0) { if (pr_expr_eval_user_or((char **) &c->argv[2]) == TRUE) { if (*((unsigned int *) c->argv[1]) > ctxt_precedence) { /* Set the context precedence. */ ctxt_precedence = *((unsigned int *) c->argv[1]); TimeoutSession = *((int *) c->argv[0]); have_group_timeout = have_class_timeout = have_all_timeout = FALSE; have_user_timeout = TRUE; } } } else if (strncmp(c->argv[1], "group", 6) == 0) { if (pr_expr_eval_group_and((char **) &c->argv[2]) == TRUE) { if (*((unsigned int *) c->argv[1]) > ctxt_precedence) { /* Set the context precedence. */ ctxt_precedence = *((unsigned int *) c->argv[1]); TimeoutSession = *((int *) c->argv[0]); have_user_timeout = have_class_timeout = have_all_timeout = FALSE; have_group_timeout = TRUE; } } } else if (strncmp(c->argv[1], "class", 6) == 0) { if (session.conn_class != NULL && strcmp(session.conn_class->cls_name, c->argv[2]) == 0) { if (*((unsigned int *) c->argv[1]) > ctxt_precedence) { /* Set the context precedence. */ ctxt_precedence = *((unsigned int *) c->argv[1]); TimeoutSession = *((int *) c->argv[0]); have_user_timeout = have_group_timeout = have_all_timeout = FALSE; have_class_timeout = TRUE; } } } } else { if (*((unsigned int *) c->argv[1]) > ctxt_precedence) { /* Set the context precedence. */ ctxt_precedence = *((unsigned int *) c->argv[1]); TimeoutSession = *((int *) c->argv[0]); have_user_timeout = have_group_timeout = have_class_timeout = FALSE; have_all_timeout = TRUE; } } c = find_config_next(c, c->next, CONF_PARAM, "TimeoutSession", FALSE); } /* If configured, start a session timer. The timer ID value for * session timers will not be #defined, as I think that is a bad approach. * A better mechanism would be to use the random timer ID generation, and * store the returned ID in order to later remove the timer. */ if (have_user_timeout || have_group_timeout || have_class_timeout || have_all_timeout) { pr_log_debug(DEBUG4, "setting TimeoutSession of %d seconds for current %s", TimeoutSession, have_user_timeout ? "user" : have_group_timeout ? "group" : have_class_timeout ? "class" : "all"); pr_timer_add(TimeoutSession, PR_TIMER_SESSION, &auth_module, auth_session_timeout_cb, "TimeoutSession"); } /* Handle a DisplayLogin file. */ if (displaylogin_fh) { if (!(session.sf_flags & SF_ANON)) { if (pr_display_fh(displaylogin_fh, NULL, auth_pass_resp_code, 0) < 0) { pr_log_debug(DEBUG6, "unable to display DisplayLogin file '%s': %s", displaylogin_fh->fh_path, strerror(errno)); } pr_fsio_close(displaylogin_fh); displaylogin_fh = NULL; } else { /* We're an <Anonymous> login, but there was a previous DisplayLogin * configured which was picked up earlier. Close that filehandle, * and look for a new one. */ char *displaylogin; pr_fsio_close(displaylogin_fh); displaylogin_fh = NULL; displaylogin = get_param_ptr(TOPLEVEL_CONF, "DisplayLogin", FALSE); if (displaylogin) { if (pr_display_file(displaylogin, NULL, auth_pass_resp_code, 0) < 0) { pr_log_debug(DEBUG6, "unable to display DisplayLogin file '%s': %s", displaylogin, strerror(errno)); } } } } else { char *displaylogin = get_param_ptr(TOPLEVEL_CONF, "DisplayLogin", FALSE); if (displaylogin) { if (pr_display_file(displaylogin, NULL, auth_pass_resp_code, 0) < 0) { pr_log_debug(DEBUG6, "unable to display DisplayLogin file '%s': %s", displaylogin, strerror(errno)); } } } grantmsg = get_param_ptr(TOPLEVEL_CONF, "AccessGrantMsg", FALSE); if (grantmsg == NULL) { /* Append the final greeting lines. */ if (session.sf_flags & SF_ANON) { pr_response_add(auth_pass_resp_code, "%s", _("Anonymous access granted, restrictions apply")); } else { pr_response_add(auth_pass_resp_code, _("User %s logged in"), user); } } else { /* Handle any AccessGrantMsg directive. */ grantmsg = sreplace(cmd->tmp_pool, grantmsg, "%u", user, NULL); pr_response_add(auth_pass_resp_code, "%s", grantmsg); } login_succeeded(cmd->tmp_pool, user); /* A RootRevoke value of 0 indicates 'false', 1 indicates 'true', and * 2 indicates 'NonCompliantActiveTransfer'. We will drop root privs for any * RootRevoke value greater than 0. */ root_revoke = get_param_ptr(TOPLEVEL_CONF, "RootRevoke", FALSE); if (root_revoke != NULL && *root_revoke > 0) { pr_signals_block(); PRIVS_ROOT PRIVS_REVOKE pr_signals_unblock(); /* Disable future attempts at UID/GID manipulation. */ session.disable_id_switching = TRUE; if (*root_revoke == 1) { /* If the server's listening port is less than 1024, block PORT * commands (effectively allowing only passive connections, which is * not necessarily a Bad Thing). Only log this here -- the blocking * will need to occur in mod_core's handling of the PORT/EPRT commands. */ if (session.c->local_port < 1024) { pr_log_debug(DEBUG0, "RootRevoke in effect, active data transfers may not succeed"); } } pr_log_debug(DEBUG0, "RootRevoke in effect, dropped root privs"); } c = find_config(TOPLEVEL_CONF, CONF_PARAM, "AnonAllowRobots", FALSE); if (c != NULL) { auth_anon_allow_robots = *((int *) c->argv[0]); } return PR_DECLINED(cmd); } /* Handle group based authentication, only checked if pw based fails. */ static config_rec *auth_group(pool *p, const char *user, char **group, char **ournamep, char **anonnamep, char *pass) { config_rec *c; char *ourname = NULL, *anonname = NULL; char **grmem; struct group *grp; ourname = get_param_ptr(main_server->conf, "UserName", FALSE); if (ournamep != NULL && ourname != NULL) { *ournamep = ourname; } c = find_config(main_server->conf, CONF_PARAM, "GroupPassword", TRUE); if (c) do { grp = pr_auth_getgrnam(p, c->argv[0]); if (grp == NULL) { continue; } for (grmem = grp->gr_mem; *grmem; grmem++) { if (strcmp(*grmem, user) == 0) { if (pr_auth_check(p, c->argv[1], user, pass) == 0) { break; } } } if (*grmem) { if (group != NULL) { *group = c->argv[0]; } if (c->parent != NULL) { c = c->parent; } if (c->config_type == CONF_ANON) { anonname = get_param_ptr(c->subset, "UserName", FALSE); } if (anonnamep != NULL) { *anonnamep = anonname; } if (anonnamep != NULL && !anonname && ourname != NULL) { *anonnamep = ourname; } break; } } while((c = find_config_next(c, c->next, CONF_PARAM, "GroupPassword", TRUE)) != NULL); return c; } /* Determine any applicable chdirs. */ static const char *get_default_chdir(pool *p, xaset_t *conf) { config_rec *c; const char *dir = NULL; c = find_config(conf, CONF_PARAM, "DefaultChdir", FALSE); while (c != NULL) { int res; pr_signals_handle(); /* Check the groups acl */ if (c->argc < 2) { dir = c->argv[0]; break; } res = pr_expr_eval_group_and(((char **) c->argv)+1); if (res) { dir = c->argv[0]; break; } c = find_config_next(c, c->next, CONF_PARAM, "DefaultChdir", FALSE); } /* If the directory is relative, concatenate w/ session.cwd. */ if (dir != NULL && *dir != '/' && *dir != '~') { dir = pdircat(p, session.cwd, dir, NULL); } /* Check for any expandable variables. */ if (dir != NULL) { dir = path_subst_uservar(p, &dir); } return dir; } /* Determine if the user (non-anon) needs a default root dir other than /. */ static int get_default_root(pool *p, int allow_symlinks, const char **root) { config_rec *c = NULL; const char *dir = NULL; int res; c = find_config(main_server->conf, CONF_PARAM, "DefaultRoot", FALSE); while (c != NULL) { pr_signals_handle(); /* Check the groups acl */ if (c->argc < 2) { dir = c->argv[0]; break; } res = pr_expr_eval_group_and(((char **) c->argv)+1); if (res) { dir = c->argv[0]; break; } c = find_config_next(c, c->next, CONF_PARAM, "DefaultRoot", FALSE); } if (dir != NULL) { const char *new_dir; /* Check for any expandable variables. */ new_dir = path_subst_uservar(p, &dir); if (new_dir != NULL) { dir = new_dir; } if (strncmp(dir, "/", 2) == 0) { dir = NULL; } else { char *realdir; int xerrno = 0; if (allow_symlinks == FALSE) { char *path, target_path[PR_TUNABLE_PATH_MAX + 1]; struct stat st; size_t pathlen; /* First, deal with any possible interpolation. dir_realpath() will * do this for us, but dir_realpath() ALSO automatically follows * symlinks, which is what we do NOT want to do here. */ path = pstrdup(p, dir); if (*path != '/') { if (*path == '~') { if (pr_fs_interpolate(dir, target_path, sizeof(target_path)-1) < 0) { return -1; } path = target_path; } } /* Note: lstat(2) is sensitive to the presence of a trailing slash on * the path, particularly in the case of a symlink to a directory. * Thus to get the correct test, we need to remove any trailing slash * that might be present. Subtle. */ pathlen = strlen(path); if (pathlen > 1 && path[pathlen-1] == '/') { path[pathlen-1] = '\0'; } pr_fs_clear_cache2(path); res = pr_fsio_lstat(path, &st); if (res < 0) { xerrno = errno; pr_log_pri(PR_LOG_WARNING, "error: unable to check %s: %s", path, strerror(xerrno)); errno = xerrno; return -1; } if (S_ISLNK(st.st_mode)) { pr_log_pri(PR_LOG_WARNING, "error: DefaultRoot %s is a symlink (denied by AllowChrootSymlinks " "config)", path); errno = EPERM; return -1; } } /* We need to be the final user here so that if the user has their home * directory with a mode the user proftpd is running (i.e. the User * directive) as can not traverse down, we can still have the default * root. */ pr_fs_clear_cache2(dir); PRIVS_USER realdir = dir_realpath(p, dir); xerrno = errno; PRIVS_RELINQUISH if (realdir) { dir = realdir; } else { /* Try to provide a more informative message. */ char interp_dir[PR_TUNABLE_PATH_MAX + 1]; memset(interp_dir, '\0', sizeof(interp_dir)); (void) pr_fs_interpolate(dir, interp_dir, sizeof(interp_dir)-1); pr_log_pri(PR_LOG_NOTICE, "notice: unable to use DefaultRoot '%s' [resolved to '%s']: %s", dir, interp_dir, strerror(xerrno)); errno = xerrno; } } } *root = dir; return 0; } static struct passwd *passwd_dup(pool *p, struct passwd *pw) { struct passwd *npw; npw = pcalloc(p, sizeof(struct passwd)); npw->pw_name = pstrdup(p, pw->pw_name); npw->pw_passwd = pstrdup(p, pw->pw_passwd); npw->pw_uid = pw->pw_uid; npw->pw_gid = pw->pw_gid; npw->pw_gecos = pstrdup(p, pw->pw_gecos); npw->pw_dir = pstrdup(p, pw->pw_dir); npw->pw_shell = pstrdup(p, pw->pw_shell); return npw; } static void ensure_open_passwd(pool *p) { /* Make sure pass/group is open. */ pr_auth_setpwent(p); pr_auth_setgrent(p); /* On some unices the following is necessary to ensure the files * are open (BSDI 3.1) */ pr_auth_getpwent(p); pr_auth_getgrent(p); /* Per Debian bug report: * https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=717235 * we might want to do another set{pw,gr}ent(), to play better with * some NSS modules. */ pr_auth_setpwent(p); pr_auth_setgrent(p); } /* Next function (the biggie) handles all authentication, setting * up chroot() jail, etc. */ static int setup_env(pool *p, cmd_rec *cmd, const char *user, char *pass) { struct passwd *pw; config_rec *c, *tmpc; const char *defchdir = NULL, *defroot = NULL, *origuser, *sess_ttyname; char *ourname = NULL, *anonname = NULL, *anongroup = NULL, *ugroup = NULL; char *xferlog = NULL; int aclp, i, res = 0, allow_chroot_symlinks = TRUE, showsymlinks; unsigned char *wtmp_log = NULL, *anon_require_passwd = NULL; /********************* Authenticate the user here *********************/ session.hide_password = TRUE; origuser = user; c = pr_auth_get_anon_config(p, &user, &ourname, &anonname); if (c != NULL) { session.anon_config = c; } if (user == NULL) { pr_log_auth(PR_LOG_NOTICE, "USER %s: user is not a UserAlias from %s [%s] " "to %s:%i", origuser, session.c->remote_name, pr_netaddr_get_ipstr(session.c->remote_addr), pr_netaddr_get_ipstr(session.c->local_addr), session.c->local_port); goto auth_failure; } pw = pr_auth_getpwnam(p, user); if (pw == NULL && c != NULL && ourname != NULL) { /* If the client is authenticating using an alias (e.g. "AuthAliasOnly on"), * then we need to try checking using the real username, too (Bug#4255). */ pr_trace_msg("auth", 16, "no user entry found for <Anonymous> alias '%s', using '%s'", user, ourname); pw = pr_auth_getpwnam(p, ourname); } if (pw == NULL) { int auth_code = PR_AUTH_NOPWD; pr_log_auth(PR_LOG_NOTICE, "USER %s: no such user found from %s [%s] to %s:%i", user, session.c->remote_name, pr_netaddr_get_ipstr(session.c->remote_addr), pr_netaddr_get_ipstr(session.c->local_addr), session.c->local_port); pr_event_generate("mod_auth.authentication-code", &auth_code); goto auth_failure; } /* Security: other functions perform pw lookups, thus we need to make * a local copy of the user just looked up. */ pw = passwd_dup(p, pw); if (pw->pw_uid == PR_ROOT_UID) { unsigned char *root_allow = NULL; pr_event_generate("mod_auth.root-login", NULL); /* If RootLogin is set to true, we allow this... even though we * still log a warning. :) */ if ((root_allow = get_param_ptr(c ? c->subset : main_server->conf, "RootLogin", FALSE)) == NULL || *root_allow != TRUE) { if (pass) { pr_memscrub(pass, strlen(pass)); } pr_log_auth(PR_LOG_NOTICE, "SECURITY VIOLATION: Root login attempted"); return 0; } } session.user = pstrdup(p, pw->pw_name); session.group = pstrdup(p, pr_auth_gid2name(p, pw->pw_gid)); /* Set the login_uid and login_uid */ session.login_uid = pw->pw_uid; session.login_gid = pw->pw_gid; /* Check for any expandable variables in session.cwd. */ pw->pw_dir = (char *) path_subst_uservar(p, (const char **) &pw->pw_dir); /* Before we check for supplemental groups, check to see if the locally * resolved name of the user, returned via auth_getpwnam(), is different * from the USER argument sent by the client. The name can change, since * auth modules can play all sorts of neat tricks on us. * * If the names differ, assume that any cached data in the session.gids * and session.groups lists are stale, and clear them out. */ if (strcmp(pw->pw_name, user) != 0) { pr_trace_msg("auth", 10, "local user name '%s' differs from client-sent " "user name '%s', clearing cached group data", pw->pw_name, user); session.gids = NULL; session.groups = NULL; } if (!session.gids && !session.groups) { /* Get the supplemental groups. Note that we only look up the * supplemental group credentials if we have not cached the group * credentials before, in session.gids and session.groups. * * Those credentials may have already been retrieved, as part of the * pr_auth_get_anon_config() call. */ res = pr_auth_getgroups(p, pw->pw_name, &session.gids, &session.groups); if (res < 1) { pr_log_debug(DEBUG5, "no supplemental groups found for user '%s'", pw->pw_name); } } tmpc = find_config(main_server->conf, CONF_PARAM, "AllowChrootSymlinks", FALSE); if (tmpc != NULL) { allow_chroot_symlinks = *((int *) tmpc->argv[0]); } /* If c != NULL from this point on, we have an anonymous login */ aclp = login_check_limits(main_server->conf, FALSE, TRUE, &i); if (c != NULL) { anongroup = get_param_ptr(c->subset, "GroupName", FALSE); if (anongroup == NULL) { anongroup = get_param_ptr(main_server->conf, "GroupName",FALSE); } #ifdef PR_USE_REGEX /* Check for configured AnonRejectPasswords regex here, and fail the login * if the given password matches the regex. */ tmpc = find_config(c->subset, CONF_PARAM, "AnonRejectPasswords", FALSE); if (tmpc != NULL) { int re_notmatch; pr_regex_t *pw_regex; pw_regex = (pr_regex_t *) tmpc->argv[0]; re_notmatch = *((int *) tmpc->argv[1]); if (pw_regex != NULL && pass != NULL) { int re_res; re_res = pr_regexp_exec(pw_regex, pass, 0, NULL, 0, 0, 0); if (re_res == 0 || (re_res != 0 && re_notmatch == TRUE)) { char errstr[200] = {'\0'}; pr_regexp_error(re_res, pw_regex, errstr, sizeof(errstr)); pr_log_auth(PR_LOG_NOTICE, "ANON %s: AnonRejectPasswords denies login", origuser); pr_event_generate("mod_auth.anon-reject-passwords", session.c); goto auth_failure; } } } #endif if (!login_check_limits(c->subset, FALSE, TRUE, &i) || (!aclp && !i) ){ pr_log_auth(PR_LOG_NOTICE, "ANON %s (Login failed): Limit access denies " "login", origuser); goto auth_failure; } } if (c == NULL && aclp == 0) { pr_log_auth(PR_LOG_NOTICE, "USER %s (Login failed): Limit access denies login", origuser); goto auth_failure; } if (c != NULL) { anon_require_passwd = get_param_ptr(c->subset, "AnonRequirePassword", FALSE); } if (c == NULL || (anon_require_passwd != NULL && *anon_require_passwd == TRUE)) { int auth_code; const char *user_name = user; if (c != NULL && origuser != NULL && strcasecmp(user, origuser) != 0) { unsigned char *auth_using_alias; auth_using_alias = get_param_ptr(c->subset, "AuthUsingAlias", FALSE); /* If 'AuthUsingAlias' set and we're logging in under an alias, * then auth using that alias. */ if (auth_using_alias && *auth_using_alias == TRUE) { user_name = origuser; pr_log_auth(PR_LOG_INFO, "ANON AUTH: User %s, authenticating using alias %s", user, user_name); } } /* It is possible for the user to have already been authenticated during * the handling of the USER command, as by an RFC2228 mechanism. If * that had happened, we won't need to call do_auth() here. */ if (!authenticated_without_pass) { auth_code = do_auth(p, c ? c->subset : main_server->conf, user_name, pass); } else { auth_code = PR_AUTH_OK_NO_PASS; } pr_event_generate("mod_auth.authentication-code", &auth_code); if (auth_code < 0) { /* Normal authentication has failed, see if group authentication * passes */ c = auth_group(p, user, &anongroup, &ourname, &anonname, pass); if (c != NULL) { if (c->config_type != CONF_ANON) { c = NULL; ugroup = anongroup; anongroup = NULL; } auth_code = PR_AUTH_OK; } } if (pass) pr_memscrub(pass, strlen(pass)); if (session.auth_mech) pr_log_debug(DEBUG2, "user '%s' authenticated by %s", user, session.auth_mech); switch (auth_code) { case PR_AUTH_OK_NO_PASS: auth_pass_resp_code = R_232; break; case PR_AUTH_OK: auth_pass_resp_code = R_230; break; case PR_AUTH_NOPWD: pr_log_auth(PR_LOG_NOTICE, "USER %s (Login failed): No such user found", user); goto auth_failure; case PR_AUTH_BADPWD: pr_log_auth(PR_LOG_NOTICE, "USER %s (Login failed): Incorrect password", origuser); goto auth_failure; case PR_AUTH_AGEPWD: pr_log_auth(PR_LOG_NOTICE, "USER %s (Login failed): Password expired", user); goto auth_failure; case PR_AUTH_DISABLEDPWD: pr_log_auth(PR_LOG_NOTICE, "USER %s (Login failed): Account disabled", user); goto auth_failure; case PR_AUTH_CRED_INSUFFICIENT: pr_log_auth(PR_LOG_NOTICE, "USER %s (Login failed): Insufficient credentials", user); goto auth_failure; case PR_AUTH_CRED_UNAVAIL: pr_log_auth(PR_LOG_NOTICE, "USER %s (Login failed): Unavailable credentials", user); goto auth_failure; case PR_AUTH_CRED_ERROR: pr_log_auth(PR_LOG_NOTICE, "USER %s (Login failed): Failure setting credentials", user); goto auth_failure; case PR_AUTH_INFO_UNAVAIL: pr_log_auth(PR_LOG_NOTICE, "USER %s (Login failed): Unavailable authentication service", user); goto auth_failure; case PR_AUTH_MAX_ATTEMPTS_EXCEEDED: pr_log_auth(PR_LOG_NOTICE, "USER %s (Login failed): Max authentication service attempts reached", user); goto auth_failure; case PR_AUTH_INIT_ERROR: pr_log_auth(PR_LOG_NOTICE, "USER %s (Login failed): Failed initializing authentication service", user); goto auth_failure; case PR_AUTH_NEW_TOKEN_REQUIRED: pr_log_auth(PR_LOG_NOTICE, "USER %s (Login failed): New authentication token required", user); goto auth_failure; default: break; }; /* Catch the case where we forgot to handle a bad auth code above. */ if (auth_code < 0) goto auth_failure; if (pw->pw_uid == PR_ROOT_UID) { pr_log_auth(PR_LOG_WARNING, "ROOT FTP login successful"); } } else if (c && (!anon_require_passwd || *anon_require_passwd == FALSE)) { session.hide_password = FALSE; } pr_auth_setgrent(p); res = pr_auth_is_valid_shell(c ? c->subset : main_server->conf, pw->pw_shell); if (res == FALSE) { pr_log_auth(PR_LOG_NOTICE, "USER %s (Login failed): Invalid shell: '%s'", user, pw->pw_shell); goto auth_failure; } res = pr_auth_banned_by_ftpusers(c ? c->subset : main_server->conf, pw->pw_name); if (res == TRUE) { pr_log_auth(PR_LOG_NOTICE, "USER %s (Login failed): User in " PR_FTPUSERS_PATH, user); goto auth_failure; } if (c) { struct group *grp = NULL; unsigned char *add_userdir = NULL; const char *u; char *chroot_dir; u = pr_table_get(session.notes, "mod_auth.orig-user", NULL); add_userdir = get_param_ptr(c->subset, "UserDirRoot", FALSE); /* If resolving an <Anonymous> user, make sure that user's groups * are set properly for the check of the home directory path (which * depend on those supplemental group memberships). Additionally, * temporarily switch to the new user's uid. */ pr_signals_block(); PRIVS_ROOT res = set_groups(p, pw->pw_gid, session.gids); if (res < 0) { if (errno != ENOSYS) { pr_log_pri(PR_LOG_WARNING, "error: unable to set groups: %s", strerror(errno)); } } #ifndef PR_DEVEL_COREDUMP # ifdef __hpux if (setresuid(0, 0, 0) < 0) { pr_log_pri(PR_LOG_ERR, "unable to setresuid(): %s", strerror(errno)); } if (setresgid(0, 0, 0) < 0) { pr_log_pri(PR_LOG_ERR, "unable to setresgid(): %s", strerror(errno)); } # else if (setuid(PR_ROOT_UID) < 0) { pr_log_pri(PR_LOG_ERR, "unable to setuid(): %s", strerror(errno)); } if (setgid(PR_ROOT_GID) < 0) { pr_log_pri(PR_LOG_ERR, "unable to setgid(): %s", strerror(errno)); } # endif /* __hpux */ #endif /* PR_DEVEL_COREDUMP */ PRIVS_SETUP(pw->pw_uid, pw->pw_gid) if ((add_userdir && *add_userdir == TRUE) && strcmp(u, user) != 0) { chroot_dir = pdircat(p, c->name, u, NULL); } else { chroot_dir = c->name; } if (allow_chroot_symlinks == FALSE) { char *chroot_path, target_path[PR_TUNABLE_PATH_MAX+1]; struct stat st; chroot_path = chroot_dir; if (chroot_path[0] != '/') { if (chroot_path[0] == '~') { if (pr_fs_interpolate(chroot_path, target_path, sizeof(target_path)-1) == 0) { chroot_path = target_path; } else { chroot_path = NULL; } } } if (chroot_path != NULL) { size_t chroot_pathlen; /* Note: lstat(2) is sensitive to the presence of a trailing slash on * the path, particularly in the case of a symlink to a directory. * Thus to get the correct test, we need to remove any trailing slash * that might be present. Subtle. */ chroot_pathlen = strlen(chroot_path); if (chroot_pathlen > 1 && chroot_path[chroot_pathlen-1] == '/') { chroot_path[chroot_pathlen-1] = '\0'; } pr_fs_clear_cache2(chroot_path); res = pr_fsio_lstat(chroot_path, &st); if (res < 0) { int xerrno = errno; pr_log_pri(PR_LOG_WARNING, "error: unable to check %s: %s", chroot_path, strerror(xerrno)); errno = xerrno; chroot_path = NULL; } else { if (S_ISLNK(st.st_mode)) { pr_log_pri(PR_LOG_WARNING, "error: <Anonymous %s> is a symlink (denied by " "AllowChrootSymlinks config)", chroot_path); errno = EPERM; chroot_path = NULL; } } } if (chroot_path != NULL) { session.chroot_path = dir_realpath(p, chroot_dir); } else { session.chroot_path = NULL; } if (session.chroot_path == NULL) { pr_log_debug(DEBUG8, "error resolving '%s': %s", chroot_dir, strerror(errno)); } } else { session.chroot_path = dir_realpath(p, chroot_dir); if (session.chroot_path == NULL) { pr_log_debug(DEBUG8, "error resolving '%s': %s", chroot_dir, strerror(errno)); } } if (session.chroot_path && pr_fsio_access(session.chroot_path, X_OK, session.uid, session.gid, session.gids) != 0) { session.chroot_path = NULL; } else { session.chroot_path = pstrdup(session.pool, session.chroot_path); } /* Return all privileges back to that of the daemon, for now. */ PRIVS_ROOT res = set_groups(p, daemon_gid, daemon_gids); if (res < 0) { if (errno != ENOSYS) { pr_log_pri(PR_LOG_ERR, "error: unable to set groups: %s", strerror(errno)); } } #ifndef PR_DEVEL_COREDUMP # ifdef __hpux if (setresuid(0, 0, 0) < 0) { pr_log_pri(PR_LOG_ERR, "unable to setresuid(): %s", strerror(errno)); } if (setresgid(0, 0, 0) < 0) { pr_log_pri(PR_LOG_ERR, "unable to setresgid(): %s", strerror(errno)); } # else if (setuid(PR_ROOT_UID) < 0) { pr_log_pri(PR_LOG_ERR, "unable to setuid(): %s", strerror(errno)); } if (setgid(PR_ROOT_GID) < 0) { pr_log_pri(PR_LOG_ERR, "unable to setgid(): %s", strerror(errno)); } # endif /* __hpux */ #endif /* PR_DEVEL_COREDUMP */ PRIVS_SETUP(daemon_uid, daemon_gid) pr_signals_unblock(); /* Sanity check, make sure we have daemon_uid and daemon_gid back */ #ifdef HAVE_GETEUID if (getegid() != daemon_gid || geteuid() != daemon_uid) { PRIVS_RELINQUISH pr_log_pri(PR_LOG_WARNING, "switching IDs from user %s back to daemon uid/gid failed: %s", session.user, strerror(errno)); pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_BY_APPLICATION, NULL); } #endif /* HAVE_GETEUID */ if (anon_require_passwd && *anon_require_passwd == TRUE) { session.anon_user = pstrdup(session.pool, origuser); } else { session.anon_user = pstrdup(session.pool, pass); } if (!session.chroot_path) { pr_log_pri(PR_LOG_NOTICE, "%s: Directory %s is not accessible", session.user, c->name); pr_response_add_err(R_530, _("Unable to set anonymous privileges.")); goto auth_failure; } sstrncpy(session.cwd, "/", sizeof(session.cwd)); xferlog = get_param_ptr(c->subset, "TransferLog", FALSE); if (anongroup) { grp = pr_auth_getgrnam(p, anongroup); if (grp) { pw->pw_gid = grp->gr_gid; session.group = pstrdup(p, grp->gr_name); } } } else { struct group *grp; char *homedir; if (ugroup) { grp = pr_auth_getgrnam(p, ugroup); if (grp) { pw->pw_gid = grp->gr_gid; session.group = pstrdup(p, grp->gr_name); } } /* Attempt to resolve any possible symlinks. */ PRIVS_USER homedir = dir_realpath(p, pw->pw_dir); PRIVS_RELINQUISH if (homedir) sstrncpy(session.cwd, homedir, sizeof(session.cwd)); else sstrncpy(session.cwd, pw->pw_dir, sizeof(session.cwd)); } /* Create the home directory, if need be. */ if (!c && mkhome) { if (create_home(p, session.cwd, origuser, pw->pw_uid, pw->pw_gid) < 0) { /* NOTE: should this cause the login to fail? */ goto auth_failure; } } /* Get default chdir (if any) */ defchdir = get_default_chdir(p, (c ? c->subset : main_server->conf)); if (defchdir != NULL) { sstrncpy(session.cwd, defchdir, sizeof(session.cwd)); } /* Check limits again to make sure deny/allow directives still permit * access. */ if (!login_check_limits((c ? c->subset : main_server->conf), FALSE, TRUE, &i)) { pr_log_auth(PR_LOG_NOTICE, "%s %s: Limit access denies login", (c != NULL) ? "ANON" : C_USER, origuser); goto auth_failure; } /* Perform a directory fixup. */ resolve_deferred_dirs(main_server); fixup_dirs(main_server, CF_DEFER); /* If running under an anonymous context, resolve all <Directory> * blocks inside it. */ if (c && c->subset) resolve_anonymous_dirs(c->subset); /* Write the login to wtmp. This must be done here because we won't * have access after we give up root. This can result in falsified * wtmp entries if an error kicks the user out before we get * through with the login process. Oh well. */ sess_ttyname = pr_session_get_ttyname(p); /* Perform wtmp logging only if not turned off in <Anonymous> * or the current server */ if (c) wtmp_log = get_param_ptr(c->subset, "WtmpLog", FALSE); if (wtmp_log == NULL) wtmp_log = get_param_ptr(main_server->conf, "WtmpLog", FALSE); /* As per Bug#3482, we need to disable WtmpLog for FreeBSD 9.0, as * an interim measure. * * The issue is that some platforms update multiple files for a single * pututxline(3) call; proftpd tries to update those files manually, * do to chroots (after which a pututxline(3) call will fail). A proper * solution requires a separate process, running with the correct * privileges, which would handle wtmp logging. The proftpd session * processes would send messages to this logging daemon (via Unix domain * socket, or FIFO, or TCP socket). * * Also note that this hack to disable WtmpLog may need to be extended * to other platforms in the future. */ #if defined(HAVE_UTMPX_H) && \ defined(__FreeBSD_version) && __FreeBSD_version >= 900007 if (wtmp_log == NULL || *wtmp_log == TRUE) { wtmp_log = pcalloc(p, sizeof(unsigned char)); *wtmp_log = FALSE; pr_log_debug(DEBUG5, "WtpmLog automatically disabled; see Bug#3482 for details"); } #endif PRIVS_ROOT if (wtmp_log == NULL || *wtmp_log == TRUE) { log_wtmp(sess_ttyname, session.user, session.c->remote_name, session.c->remote_addr); session.wtmp_log = TRUE; } #ifdef PR_USE_LASTLOG if (lastlog) { log_lastlog(pw->pw_uid, session.user, sess_ttyname, session.c->remote_addr); } #endif /* PR_USE_LASTLOG */ /* Open any TransferLogs */ if (!xferlog) { if (c) xferlog = get_param_ptr(c->subset, "TransferLog", FALSE); if (!xferlog) xferlog = get_param_ptr(main_server->conf, "TransferLog", FALSE); if (!xferlog) xferlog = PR_XFERLOG_PATH; } if (strcasecmp(xferlog, "NONE") == 0) { xferlog_open(NULL); } else { xferlog_open(xferlog); } res = set_groups(p, pw->pw_gid, session.gids); if (res < 0) { if (errno != ENOSYS) { pr_log_pri(PR_LOG_ERR, "error: unable to set groups: %s", strerror(errno)); } } PRIVS_RELINQUISH /* Now check to see if the user has an applicable DefaultRoot */ if (c == NULL) { if (get_default_root(session.pool, allow_chroot_symlinks, &defroot) < 0) { pr_log_pri(PR_LOG_NOTICE, "error: unable to determine DefaultRoot directory"); pr_response_send(R_530, _("Login incorrect.")); pr_session_end(0); } ensure_open_passwd(p); if (defroot != NULL) { if (pr_auth_chroot(defroot) == -1) { pr_log_pri(PR_LOG_NOTICE, "error: unable to set DefaultRoot directory"); pr_response_send(R_530, _("Login incorrect.")); pr_session_end(0); } /* Re-calc the new cwd based on this root dir. If not applicable * place the user in / (of defroot) */ if (strncmp(session.cwd, defroot, strlen(defroot)) == 0) { char *newcwd = &session.cwd[strlen(defroot)]; if (*newcwd == '/') newcwd++; session.cwd[0] = '/'; sstrncpy(&session.cwd[1], newcwd, sizeof(session.cwd)); } } } if (c) ensure_open_passwd(p); if (c && pr_auth_chroot(session.chroot_path) == -1) { pr_log_pri(PR_LOG_NOTICE, "error: unable to set anonymous privileges"); pr_response_send(R_530, _("Login incorrect.")); pr_session_end(0); } /* new in 1.1.x, I gave in and we don't give up root permanently.. * sigh. */ PRIVS_ROOT #ifndef PR_DEVEL_COREDUMP # ifdef __hpux if (setresuid(0, 0, 0) < 0) { pr_log_pri(PR_LOG_ERR, "unable to setresuid(): %s", strerror(errno)); } if (setresgid(0, 0, 0) < 0) { pr_log_pri(PR_LOG_ERR, "unable to setresgid(): %s", strerror(errno)); } # else if (setuid(PR_ROOT_UID) < 0) { pr_log_pri(PR_LOG_ERR, "unable to setuid(): %s", strerror(errno)); } if (setgid(PR_ROOT_GID) < 0) { pr_log_pri(PR_LOG_ERR, "unable to setgid(): %s", strerror(errno)); } # endif /* __hpux */ #endif /* PR_DEVEL_COREDUMP */ PRIVS_SETUP(pw->pw_uid, pw->pw_gid) #ifdef HAVE_GETEUID if (getegid() != pw->pw_gid || geteuid() != pw->pw_uid) { PRIVS_RELINQUISH pr_log_pri(PR_LOG_ERR, "error: %s setregid() or setreuid(): %s", session.user, strerror(errno)); pr_response_send(R_530, _("Login incorrect.")); pr_session_end(0); } #endif /* If the home directory is NULL or "", reject the login. */ if (pw->pw_dir == NULL || strncmp(pw->pw_dir, "", 1) == 0) { pr_log_pri(PR_LOG_WARNING, "error: user %s home directory is NULL or \"\"", session.user); pr_response_send(R_530, _("Login incorrect.")); pr_session_end(0); } { unsigned char *show_symlinks = get_param_ptr( c ? c->subset : main_server->conf, "ShowSymlinks", FALSE); if (!show_symlinks || *show_symlinks == TRUE) showsymlinks = TRUE; else showsymlinks = FALSE; } /* chdir to the proper directory, do this even if anonymous * to make sure we aren't outside our chrooted space. */ /* Attempt to change to the correct directory -- use session.cwd first. * This will contain the DefaultChdir directory, if configured... */ if (pr_fsio_chdir_canon(session.cwd, !showsymlinks) == -1) { /* if we've got DefaultRoot or anonymous login, ignore this error * and chdir to / */ if (session.chroot_path != NULL || defroot) { pr_log_debug(DEBUG2, "unable to chdir to %s (%s), defaulting to chroot " "directory %s", session.cwd, strerror(errno), (session.chroot_path ? session.chroot_path : defroot)); if (pr_fsio_chdir_canon("/", !showsymlinks) == -1) { pr_log_pri(PR_LOG_NOTICE, "%s chdir(\"/\") failed: %s", session.user, strerror(errno)); pr_response_send(R_530, _("Login incorrect.")); pr_session_end(0); } } else if (defchdir) { /* If we've got defchdir, failure is ok as well, simply switch to * user's homedir. */ pr_log_debug(DEBUG2, "unable to chdir to %s (%s), defaulting to home " "directory %s", session.cwd, strerror(errno), pw->pw_dir); if (pr_fsio_chdir_canon(pw->pw_dir, !showsymlinks) == -1) { pr_log_pri(PR_LOG_NOTICE, "%s chdir(\"%s\") failed: %s", session.user, session.cwd, strerror(errno)); pr_response_send(R_530, _("Login incorrect.")); pr_session_end(0); } } else { /* Unable to switch to user's real home directory, which is not * allowed. */ pr_log_pri(PR_LOG_NOTICE, "%s chdir(\"%s\") failed: %s", session.user, session.cwd, strerror(errno)); pr_response_send(R_530, _("Login incorrect.")); pr_session_end(0); } } sstrncpy(session.cwd, pr_fs_getcwd(), sizeof(session.cwd)); sstrncpy(session.vwd, pr_fs_getvwd(), sizeof(session.vwd)); /* Make sure directory config pointers are set correctly */ dir_check_full(p, cmd, G_NONE, session.cwd, NULL); if (c) { if (!session.hide_password) { session.proc_prefix = pstrcat(session.pool, session.c->remote_name, ": anonymous/", pass, NULL); } else { session.proc_prefix = pstrcat(session.pool, session.c->remote_name, ": anonymous", NULL); } session.sf_flags = SF_ANON; } else { session.proc_prefix = pstrdup(session.pool, session.c->remote_name); session.sf_flags = 0; } /* While closing the pointer to the password database would avoid any * potential attempt to hijack this information, it is unfortunately needed * in a chroot()ed environment. Otherwise, mappings from UIDs to names, * among other things, would fail. */ /* pr_auth_endpwent(p); */ /* Authentication complete, user logged in, now kill the login * timer. */ /* Update the scoreboard entry */ pr_scoreboard_entry_update(session.pid, PR_SCORE_USER, session.user, PR_SCORE_CWD, session.cwd, NULL); pr_session_set_idle(); pr_timer_remove(PR_TIMER_LOGIN, &auth_module); /* These copies are made from the session.pool, instead of the more * volatile pool used originally, in order that the copied data maintain * its integrity for the lifetime of the session. */ session.user = pstrdup(session.pool, session.user); if (session.group) session.group = pstrdup(session.pool, session.group); if (session.gids) session.gids = copy_array(session.pool, session.gids); /* session.groups is an array of strings, so we must copy the string data * as well as the pointers. */ session.groups = copy_array_str(session.pool, session.groups); /* Resolve any deferred-resolution paths in the FS layer */ pr_resolve_fs_map(); return 1; auth_failure: if (pass) pr_memscrub(pass, strlen(pass)); session.user = session.group = NULL; session.gids = session.groups = NULL; session.wtmp_log = FALSE; return 0; } /* This function counts the number of connected users. It only fills in the * Class-based counters and an estimate for the number of clients. The primary * purpose is to make it so that the %N/%y escapes work in a DisplayConnect * greeting. A secondary purpose is to enforce any configured * MaxConnectionsPerHost limit. */ static int auth_scan_scoreboard(void) { char *key; void *v; config_rec *c = NULL; pr_scoreboard_entry_t *score = NULL; unsigned int cur = 0, ccur = 0, hcur = 0; char curr_server_addr[80] = {'\0'}; const char *client_addr = pr_netaddr_get_ipstr(session.c->remote_addr); snprintf(curr_server_addr, sizeof(curr_server_addr), "%s:%d", pr_netaddr_get_ipstr(session.c->local_addr), main_server->ServerPort); curr_server_addr[sizeof(curr_server_addr)-1] = '\0'; /* Determine how many users are currently connected */ if (pr_rewind_scoreboard() < 0) { pr_log_pri(PR_LOG_NOTICE, "error rewinding scoreboard: %s", strerror(errno)); } while ((score = pr_scoreboard_entry_read()) != NULL) { pr_signals_handle(); /* Make sure it matches our current server */ if (strcmp(score->sce_server_addr, curr_server_addr) == 0) { cur++; if (strcmp(score->sce_client_addr, client_addr) == 0) hcur++; /* Only count up authenticated clients, as per the documentation. */ if (strncmp(score->sce_user, "(none)", 7) == 0) continue; /* Note: the class member of the scoreboard entry will never be * NULL. At most, it may be the empty string. */ if (session.conn_class != NULL && strcasecmp(score->sce_class, session.conn_class->cls_name) == 0) { ccur++; } } } pr_restore_scoreboard(); key = "client-count"; (void) pr_table_remove(session.notes, key, NULL); v = palloc(session.pool, sizeof(unsigned int)); *((unsigned int *) v) = cur; if (pr_table_add(session.notes, key, v, sizeof(unsigned int)) < 0) { if (errno != EEXIST) { pr_log_pri(PR_LOG_WARNING, "warning: error stashing '%s': %s", key, strerror(errno)); } } if (session.conn_class != NULL) { key = "class-client-count"; (void) pr_table_remove(session.notes, key, NULL); v = palloc(session.pool, sizeof(unsigned int)); *((unsigned int *) v) = ccur; if (pr_table_add(session.notes, key, v, sizeof(unsigned int)) < 0) { if (errno != EEXIST) { pr_log_pri(PR_LOG_WARNING, "warning: error stashing '%s': %s", key, strerror(errno)); } } } /* Lookup any configured MaxConnectionsPerHost. */ c = find_config(main_server->conf, CONF_PARAM, "MaxConnectionsPerHost", FALSE); if (c) { unsigned int *max = c->argv[0]; if (*max && hcur > *max) { char maxstr[20]; char *msg = "Sorry, the maximum number of connections (%m) for your host " "are already connected."; pr_event_generate("mod_auth.max-connections-per-host", session.c); if (c->argc == 2) msg = c->argv[1]; memset(maxstr, '\0', sizeof(maxstr)); snprintf(maxstr, sizeof(maxstr), "%u", *max); maxstr[sizeof(maxstr)-1] = '\0'; pr_response_send(R_530, "%s", sreplace(session.pool, msg, "%m", maxstr, NULL)); pr_log_auth(PR_LOG_NOTICE, "Connection refused (MaxConnectionsPerHost %u)", *max); pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_CONFIG_ACL, "Denied by MaxConnectionsPerHost"); } } return 0; } static int have_client_limits(cmd_rec *cmd) { if (find_config(TOPLEVEL_CONF, CONF_PARAM, "MaxClientsPerClass", FALSE) != NULL) { return TRUE; } if (find_config(TOPLEVEL_CONF, CONF_PARAM, "MaxClientsPerHost", FALSE) != NULL) { return TRUE; } if (find_config(TOPLEVEL_CONF, CONF_PARAM, "MaxClientsPerUser", FALSE) != NULL) { return TRUE; } if (find_config(TOPLEVEL_CONF, CONF_PARAM, "MaxClients", FALSE) != NULL) { return TRUE; } if (find_config(TOPLEVEL_CONF, CONF_PARAM, "MaxHostsPerUser", FALSE) != NULL) { return TRUE; } return FALSE; } static int auth_count_scoreboard(cmd_rec *cmd, const char *user) { char *key; void *v; pr_scoreboard_entry_t *score = NULL; long cur = 0, hcur = 0, ccur = 0, hostsperuser = 1, usersessions = 0; config_rec *c = NULL, *maxc = NULL; /* First, check to see which Max* directives are configured. If none * are configured, then there is no need for us to needlessly scan the * ScoreboardFile. */ if (have_client_limits(cmd) == FALSE) { return 0; } /* Determine how many users are currently connected. */ /* We use this call to get the possibly-changed user name. */ c = pr_auth_get_anon_config(cmd->tmp_pool, &user, NULL, NULL); /* Gather our statistics. */ if (user != NULL) { char curr_server_addr[80] = {'\0'}; snprintf(curr_server_addr, sizeof(curr_server_addr), "%s:%d", pr_netaddr_get_ipstr(session.c->local_addr), main_server->ServerPort); curr_server_addr[sizeof(curr_server_addr)-1] = '\0'; if (pr_rewind_scoreboard() < 0) { pr_log_pri(PR_LOG_NOTICE, "error rewinding scoreboard: %s", strerror(errno)); } while ((score = pr_scoreboard_entry_read()) != NULL) { unsigned char same_host = FALSE; pr_signals_handle(); /* Make sure it matches our current server. */ if (strcmp(score->sce_server_addr, curr_server_addr) == 0) { if ((c != NULL && c->config_type == CONF_ANON && !strcmp(score->sce_user, user)) || c == NULL) { /* This small hack makes sure that cur is incremented properly * when dealing with anonymous logins (the timing of anonymous * login updates to the scoreboard makes this...odd). */ if (c != NULL && c->config_type == CONF_ANON && cur == 0) { cur = 1; } /* Only count authenticated clients, as per the documentation. */ if (strncmp(score->sce_user, "(none)", 7) == 0) { continue; } cur++; /* Count up sessions on a per-host basis. */ if (!strcmp(score->sce_client_addr, pr_netaddr_get_ipstr(session.c->remote_addr))) { same_host = TRUE; /* This small hack makes sure that hcur is incremented properly * when dealing with anonymous logins (the timing of anonymous * login updates to the scoreboard makes this...odd). */ if (c != NULL && c->config_type == CONF_ANON && hcur == 0) { hcur = 1; } hcur++; } /* Take a per-user count of connections. */ if (strcmp(score->sce_user, user) == 0) { usersessions++; /* Count up unique hosts. */ if (!same_host) { hostsperuser++; } } } if (session.conn_class != NULL && strcasecmp(score->sce_class, session.conn_class->cls_name) == 0) { ccur++; } } } pr_restore_scoreboard(); PRIVS_RELINQUISH } key = "client-count"; (void) pr_table_remove(session.notes, key, NULL); v = palloc(session.pool, sizeof(unsigned int)); *((unsigned int *) v) = cur; if (pr_table_add(session.notes, key, v, sizeof(unsigned int)) < 0) { if (errno != EEXIST) { pr_log_pri(PR_LOG_WARNING, "warning: error stashing '%s': %s", key, strerror(errno)); } } if (session.conn_class != NULL) { key = "class-client-count"; (void) pr_table_remove(session.notes, key, NULL); v = palloc(session.pool, sizeof(unsigned int)); *((unsigned int *) v) = ccur; if (pr_table_add(session.notes, key, v, sizeof(unsigned int)) < 0) { if (errno != EEXIST) { pr_log_pri(PR_LOG_WARNING, "warning: error stashing '%s': %s", key, strerror(errno)); } } } /* Try to determine what MaxClients/MaxHosts limits apply to this session * (if any) and count through the runtime file to see if this limit would * be exceeded. */ maxc = find_config(cmd->server->conf, CONF_PARAM, "MaxClientsPerClass", FALSE); while (session.conn_class != NULL && maxc) { char *maxstr = "Sorry, the maximum number of clients (%m) from your class " "are already connected."; unsigned int *max = maxc->argv[1]; if (strcmp(maxc->argv[0], session.conn_class->cls_name) != 0) { maxc = find_config_next(maxc, maxc->next, CONF_PARAM, "MaxClientsPerClass", FALSE); continue; } if (maxc->argc > 2) { maxstr = maxc->argv[2]; } if (*max && ccur > *max) { char maxn[20] = {'\0'}; pr_event_generate("mod_auth.max-clients-per-class", session.conn_class->cls_name); snprintf(maxn, sizeof(maxn), "%u", *max); pr_response_send(R_530, "%s", sreplace(cmd->tmp_pool, maxstr, "%m", maxn, NULL)); (void) pr_cmd_dispatch_phase(cmd, LOG_CMD_ERR, 0); pr_log_auth(PR_LOG_NOTICE, "Connection refused (MaxClientsPerClass %s %u)", session.conn_class->cls_name, *max); pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_CONFIG_ACL, "Denied by MaxClientsPerClass"); } break; } maxc = find_config(TOPLEVEL_CONF, CONF_PARAM, "MaxClientsPerHost", FALSE); if (maxc) { char *maxstr = "Sorry, the maximum number of clients (%m) from your host " "are already connected."; unsigned int *max = maxc->argv[0]; if (maxc->argc > 1) { maxstr = maxc->argv[1]; } if (*max && hcur > *max) { char maxn[20] = {'\0'}; pr_event_generate("mod_auth.max-clients-per-host", session.c); snprintf(maxn, sizeof(maxn), "%u", *max); pr_response_send(R_530, "%s", sreplace(cmd->tmp_pool, maxstr, "%m", maxn, NULL)); (void) pr_cmd_dispatch_phase(cmd, LOG_CMD_ERR, 0); pr_log_auth(PR_LOG_NOTICE, "Connection refused (MaxClientsPerHost %u)", *max); pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_CONFIG_ACL, "Denied by MaxClientsPerHost"); } } /* Check for any configured MaxClientsPerUser. */ maxc = find_config(TOPLEVEL_CONF, CONF_PARAM, "MaxClientsPerUser", FALSE); if (maxc) { char *maxstr = "Sorry, the maximum number of clients (%m) for this user " "are already connected."; unsigned int *max = maxc->argv[0]; if (maxc->argc > 1) { maxstr = maxc->argv[1]; } if (*max && usersessions > *max) { char maxn[20] = {'\0'}; pr_event_generate("mod_auth.max-clients-per-user", user); snprintf(maxn, sizeof(maxn), "%u", *max); pr_response_send(R_530, "%s", sreplace(cmd->tmp_pool, maxstr, "%m", maxn, NULL)); (void) pr_cmd_dispatch_phase(cmd, LOG_CMD_ERR, 0); pr_log_auth(PR_LOG_NOTICE, "Connection refused (MaxClientsPerUser %u)", *max); pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_CONFIG_ACL, "Denied by MaxClientsPerUser"); } } maxc = find_config(TOPLEVEL_CONF, CONF_PARAM, "MaxClients", FALSE); if (maxc) { char *maxstr = "Sorry, the maximum number of allowed clients (%m) are " "already connected."; unsigned int *max = maxc->argv[0]; if (maxc->argc > 1) { maxstr = maxc->argv[1]; } if (*max && cur > *max) { char maxn[20] = {'\0'}; pr_event_generate("mod_auth.max-clients", NULL); snprintf(maxn, sizeof(maxn), "%u", *max); pr_response_send(R_530, "%s", sreplace(cmd->tmp_pool, maxstr, "%m", maxn, NULL)); (void) pr_cmd_dispatch_phase(cmd, LOG_CMD_ERR, 0); pr_log_auth(PR_LOG_NOTICE, "Connection refused (MaxClients %u)", *max); pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_CONFIG_ACL, "Denied by MaxClients"); } } maxc = find_config(TOPLEVEL_CONF, CONF_PARAM, "MaxHostsPerUser", FALSE); if (maxc) { char *maxstr = "Sorry, the maximum number of hosts (%m) for this user are " "already connected."; unsigned int *max = maxc->argv[0]; if (maxc->argc > 1) { maxstr = maxc->argv[1]; } if (*max && hostsperuser > *max) { char maxn[20] = {'\0'}; pr_event_generate("mod_auth.max-hosts-per-user", user); snprintf(maxn, sizeof(maxn), "%u", *max); pr_response_send(R_530, "%s", sreplace(cmd->tmp_pool, maxstr, "%m", maxn, NULL)); (void) pr_cmd_dispatch_phase(cmd, LOG_CMD_ERR, 0); pr_log_auth(PR_LOG_NOTICE, "Connection refused (MaxHostsPerUser %u)", *max); pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_CONFIG_ACL, "Denied by MaxHostsPerUser"); } } return 0; } MODRET auth_pre_user(cmd_rec *cmd) { if (saw_first_user_cmd == FALSE) { if (pr_trace_get_level(timing_channel)) { unsigned long elapsed_ms; uint64_t finish_ms; pr_gettimeofday_millis(&finish_ms); elapsed_ms = (unsigned long) (finish_ms - session.connect_time_ms); pr_trace_msg(timing_channel, 4, "Time before first USER: %lu ms", elapsed_ms); } saw_first_user_cmd = TRUE; } if (logged_in) { return PR_DECLINED(cmd); } /* Close the passwd and group databases, because libc won't let us see new * entries to these files without this (only in PersistentPasswd mode). */ pr_auth_endpwent(cmd->tmp_pool); pr_auth_endgrent(cmd->tmp_pool); /* Check for a user name that exceeds PR_TUNABLE_LOGIN_MAX. */ if (strlen(cmd->arg) > PR_TUNABLE_LOGIN_MAX) { pr_log_pri(PR_LOG_NOTICE, "USER %s (Login failed): " "maximum USER length exceeded", cmd->arg); pr_response_add_err(R_501, _("Login incorrect.")); pr_cmd_set_errno(cmd, EPERM); errno = EPERM; return PR_ERROR(cmd); } return PR_DECLINED(cmd); } MODRET auth_user(cmd_rec *cmd) { int nopass = FALSE; config_rec *c; const char *denymsg = NULL, *user, *origuser; int failnopwprompt = 0, aclp, i; unsigned char *anon_require_passwd = NULL, *login_passwd_prompt = NULL; if (cmd->argc < 2) { return PR_ERROR_MSG(cmd, R_500, _("USER: command requires a parameter")); } if (logged_in) { /* If the client has already authenticated, BUT the given USER command * here is for the exact same user name, then allow the command to * succeed (Bug#4217). */ origuser = pr_table_get(session.notes, "mod_auth.orig-user", NULL); if (origuser != NULL && strcmp(origuser, cmd->arg) == 0) { pr_response_add(R_230, _("User %s logged in"), origuser); return PR_HANDLED(cmd); } pr_response_add_err(R_501, "%s", _("Reauthentication not supported")); return PR_ERROR(cmd); } user = cmd->arg; (void) pr_table_remove(session.notes, "mod_auth.orig-user", NULL); (void) pr_table_remove(session.notes, "mod_auth.anon-passwd", NULL); if (pr_table_add_dup(session.notes, "mod_auth.orig-user", user, 0) < 0) { pr_log_debug(DEBUG3, "error stashing 'mod_auth.orig-user' in " "session.notes: %s", strerror(errno)); } origuser = user; c = pr_auth_get_anon_config(cmd->tmp_pool, &user, NULL, NULL); /* Check for AccessDenyMsg */ denymsg = get_param_ptr((c ? c->subset : cmd->server->conf), "AccessDenyMsg", FALSE); if (denymsg != NULL) { if (strstr(denymsg, "%u") != NULL) { denymsg = sreplace(cmd->tmp_pool, denymsg, "%u", user, NULL); } } login_passwd_prompt = get_param_ptr( (c && c->config_type == CONF_ANON) ? c->subset : main_server->conf, "LoginPasswordPrompt", FALSE); if (login_passwd_prompt && *login_passwd_prompt == FALSE) { failnopwprompt = TRUE; } else { failnopwprompt = FALSE; } if (failnopwprompt) { if (!user) { (void) pr_table_remove(session.notes, "mod_auth.orig-user", NULL); (void) pr_table_remove(session.notes, "mod_auth.anon-passwd", NULL); pr_log_pri(PR_LOG_NOTICE, "USER %s (Login failed): Not a UserAlias", origuser); if (denymsg) { pr_response_send(R_530, "%s", denymsg); } else { pr_response_send(R_530, _("Login incorrect.")); } pr_session_end(0); } aclp = login_check_limits(main_server->conf, FALSE, TRUE, &i); if (c && c->config_type != CONF_ANON) { c = (config_rec *) pcalloc(session.pool, sizeof(config_rec)); c->config_type = CONF_ANON; c->name = ""; /* don't really need this yet */ c->subset = main_server->conf; } if (c) { if (!login_check_limits(c->subset, FALSE, TRUE, &i) || (!aclp && !i) ) { (void) pr_table_remove(session.notes, "mod_auth.orig-user", NULL); (void) pr_table_remove(session.notes, "mod_auth.anon-passwd", NULL); pr_log_auth(PR_LOG_NOTICE, "ANON %s: Limit access denies login", origuser); if (denymsg) { pr_response_send(R_530, "%s", denymsg); } else { pr_response_send(R_530, _("Login incorrect.")); } pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_CONFIG_ACL, "Denied by <Limit LOGIN>"); } } if (c == NULL && aclp == 0) { (void) pr_table_remove(session.notes, "mod_auth.orig-user", NULL); (void) pr_table_remove(session.notes, "mod_auth.anon-passwd", NULL); pr_log_auth(PR_LOG_NOTICE, "USER %s: Limit access denies login", origuser); if (denymsg) { pr_response_send(R_530, "%s", denymsg); } else { pr_response_send(R_530, "%s", _("Login incorrect.")); } pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_CONFIG_ACL, "Denied by <Limit LOGIN>"); } } if (c) anon_require_passwd = get_param_ptr(c->subset, "AnonRequirePassword", FALSE); if (c && user && (!anon_require_passwd || *anon_require_passwd == FALSE)) nopass = TRUE; session.gids = NULL; session.groups = NULL; session.user = NULL; session.group = NULL; if (nopass) { pr_response_add(R_331, _("Anonymous login ok, send your complete email " "address as your password")); } else if (pr_auth_requires_pass(cmd->tmp_pool, user) == FALSE) { /* Check to see if a password from the client is required. In the * vast majority of cases, a password will be required. */ /* Act as if we received a PASS command from the client. */ cmd_rec *fakecmd = pr_cmd_alloc(cmd->pool, 2, NULL); /* We use pstrdup() here, rather than assigning C_PASS directly, since * code elsewhere will attempt to modify this buffer, and C_PASS is * a string literal. */ fakecmd->argv[0] = pstrdup(fakecmd->pool, C_PASS); fakecmd->argv[1] = NULL; fakecmd->arg = NULL; c = add_config_param_set(&cmd->server->conf, "authenticated", 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = TRUE; authenticated_without_pass = TRUE; pr_log_auth(PR_LOG_NOTICE, "USER %s: Authenticated without password", user); pr_cmd_dispatch(fakecmd); } else { pr_response_add(R_331, _("Password required for %s"), (char *) cmd->argv[1]); } return PR_HANDLED(cmd); } /* Close the passwd and group databases, similar to auth_pre_user(). */ MODRET auth_pre_pass(cmd_rec *cmd) { const char *user; char *displaylogin; pr_auth_endpwent(cmd->tmp_pool); pr_auth_endgrent(cmd->tmp_pool); /* Handle cases where PASS might be sent before USER. */ user = pr_table_get(session.notes, "mod_auth.orig-user", NULL); if (user != NULL) { config_rec *c; c = find_config(main_server->conf, CONF_PARAM, "AllowEmptyPasswords", FALSE); if (c == NULL) { const char *anon_user; config_rec *anon_config; /* Since we have not authenticated yet, we cannot use the TOPLEVEL_CONF * macro to handle <Anonymous> sections. So we do it manually. */ anon_user = pstrdup(cmd->tmp_pool, user); anon_config = pr_auth_get_anon_config(cmd->tmp_pool, &anon_user, NULL, NULL); if (anon_config != NULL) { c = find_config(anon_config->subset, CONF_PARAM, "AllowEmptyPasswords", FALSE); } } if (c != NULL) { int allow_empty_passwords; allow_empty_passwords = *((int *) c->argv[0]); if (allow_empty_passwords == FALSE) { size_t passwd_len = 0; if (cmd->argc > 1) { if (cmd->arg != NULL) { passwd_len = strlen(cmd->arg); } } /* Make sure to NOT enforce 'AllowEmptyPasswords off' if e.g. * the AllowDotLogin TLSOption is in effect. */ if (cmd->argc == 1 || passwd_len == 0) { if (session.auth_mech == NULL || strcmp(session.auth_mech, "mod_tls.c") != 0) { pr_log_debug(DEBUG5, "Refusing empty password from user '%s' (AllowEmptyPasswords " "false)", user); pr_log_auth(PR_LOG_NOTICE, "Refusing empty password from user '%s'", user); pr_event_generate("mod_auth.empty-password", user); pr_response_add_err(R_501, _("Login incorrect.")); return PR_ERROR(cmd); } pr_log_debug(DEBUG9, "%s", "'AllowEmptyPasswords off' in effect, " "BUT client authenticated via the AllowDotLogin TLSOption"); } } } } /* Look for a DisplayLogin file which has an absolute path. If we find one, * open a filehandle, such that that file can be displayed even if the * session is chrooted. DisplayLogin files with relative paths will be * handled after chroot, preserving the old behavior. */ displaylogin = get_param_ptr(TOPLEVEL_CONF, "DisplayLogin", FALSE); if (displaylogin && *displaylogin == '/') { struct stat st; displaylogin_fh = pr_fsio_open(displaylogin, O_RDONLY); if (displaylogin_fh == NULL) { pr_log_debug(DEBUG6, "unable to open DisplayLogin file '%s': %s", displaylogin, strerror(errno)); } else { if (pr_fsio_fstat(displaylogin_fh, &st) < 0) { pr_log_debug(DEBUG6, "unable to stat DisplayLogin file '%s': %s", displaylogin, strerror(errno)); pr_fsio_close(displaylogin_fh); displaylogin_fh = NULL; } else { if (S_ISDIR(st.st_mode)) { errno = EISDIR; pr_log_debug(DEBUG6, "unable to use DisplayLogin file '%s': %s", displaylogin, strerror(errno)); pr_fsio_close(displaylogin_fh); displaylogin_fh = NULL; } } } } return PR_DECLINED(cmd); } MODRET auth_pass(cmd_rec *cmd) { const char *user = NULL; int res = 0; if (logged_in) { return PR_ERROR_MSG(cmd, R_503, _("You are already logged in")); } user = pr_table_get(session.notes, "mod_auth.orig-user", NULL); if (user == NULL) { (void) pr_table_remove(session.notes, "mod_auth.orig-user", NULL); (void) pr_table_remove(session.notes, "mod_auth.anon-passwd", NULL); return PR_ERROR_MSG(cmd, R_503, _("Login with USER first")); } /* Clear any potentially cached directory config */ session.anon_config = NULL; session.dir_config = NULL; res = setup_env(cmd->tmp_pool, cmd, user, cmd->arg); if (res == 1) { config_rec *c = NULL; c = add_config_param_set(&cmd->server->conf, "authenticated", 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = TRUE; set_auth_check(NULL); (void) pr_table_remove(session.notes, "mod_auth.anon-passwd", NULL); if (session.sf_flags & SF_ANON) { if (pr_table_add_dup(session.notes, "mod_auth.anon-passwd", pr_fs_decode_path(cmd->server->pool, cmd->arg), 0) < 0) { pr_log_debug(DEBUG3, "error stashing anonymous password in session.notes: %s", strerror(errno)); } } logged_in = TRUE; if (pr_trace_get_level(timing_channel)) { unsigned long elapsed_ms; uint64_t finish_ms; pr_gettimeofday_millis(&finish_ms); elapsed_ms = (unsigned long) (finish_ms - session.connect_time_ms); pr_trace_msg(timing_channel, 4, "Time before successful login (via '%s'): %lu ms", session.auth_mech, elapsed_ms); } return PR_HANDLED(cmd); } (void) pr_table_remove(session.notes, "mod_auth.anon-passwd", NULL); if (res == 0) { unsigned int max_logins, *max = NULL; const char *denymsg = NULL; /* check for AccessDenyMsg */ if ((denymsg = get_param_ptr((session.anon_config ? session.anon_config->subset : cmd->server->conf), "AccessDenyMsg", FALSE)) != NULL) { if (strstr(denymsg, "%u") != NULL) { denymsg = sreplace(cmd->tmp_pool, denymsg, "%u", user, NULL); } } max = get_param_ptr(main_server->conf, "MaxLoginAttempts", FALSE); if (max != NULL) { max_logins = *max; } else { max_logins = 3; } if (max_logins > 0 && ++auth_tries >= max_logins) { if (denymsg) { pr_response_send(R_530, "%s", denymsg); } else { pr_response_send(R_530, "%s", _("Login incorrect.")); } pr_log_auth(PR_LOG_NOTICE, "Maximum login attempts (%u) exceeded, connection refused", max_logins); /* Generate an event about this limit being exceeded. */ pr_event_generate("mod_auth.max-login-attempts", session.c); pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_CONFIG_ACL, "Denied by MaxLoginAttempts"); } return PR_ERROR_MSG(cmd, R_530, denymsg ? denymsg : _("Login incorrect.")); } return PR_HANDLED(cmd); } MODRET auth_acct(cmd_rec *cmd) { pr_response_add(R_502, _("ACCT command not implemented")); return PR_HANDLED(cmd); } MODRET auth_rein(cmd_rec *cmd) { pr_response_add(R_502, _("REIN command not implemented")); return PR_HANDLED(cmd); } /* FSIO callbacks for providing a fake robots.txt file, for the AnonAllowRobots * functionality. */ #define AUTH_ROBOTS_TXT "User-agent: *\nDisallow: /\n" #define AUTH_ROBOTS_TXT_FD 6742 static int robots_fsio_stat(pr_fs_t *fs, const char *path, struct stat *st) { st->st_dev = (dev_t) 0; st->st_ino = (ino_t) 0; st->st_mode = (S_IFREG|S_IRUSR|S_IRGRP|S_IROTH); st->st_nlink = 0; st->st_uid = (uid_t) 0; st->st_gid = (gid_t) 0; st->st_atime = 0; st->st_mtime = 0; st->st_ctime = 0; st->st_size = strlen(AUTH_ROBOTS_TXT); st->st_blksize = 1024; st->st_blocks = 1; return 0; } static int robots_fsio_fstat(pr_fh_t *fh, int fd, struct stat *st) { if (fd != AUTH_ROBOTS_TXT_FD) { errno = EINVAL; return -1; } return robots_fsio_stat(NULL, NULL, st); } static int robots_fsio_lstat(pr_fs_t *fs, const char *path, struct stat *st) { return robots_fsio_stat(fs, path, st); } static int robots_fsio_unlink(pr_fs_t *fs, const char *path) { return 0; } static int robots_fsio_open(pr_fh_t *fh, const char *path, int flags) { if (flags != O_RDONLY) { errno = EINVAL; return -1; } return AUTH_ROBOTS_TXT_FD; } static int robots_fsio_close(pr_fh_t *fh, int fd) { if (fd != AUTH_ROBOTS_TXT_FD) { errno = EINVAL; return -1; } return 0; } static int robots_fsio_read(pr_fh_t *fh, int fd, char *buf, size_t bufsz) { size_t robots_len; if (fd != AUTH_ROBOTS_TXT_FD) { errno = EINVAL; return -1; } robots_len = strlen(AUTH_ROBOTS_TXT); if (bufsz < robots_len) { errno = EINVAL; return -1; } memcpy(buf, AUTH_ROBOTS_TXT, robots_len); return (int) robots_len; } static int robots_fsio_write(pr_fh_t *fh, int fd, const char *buf, size_t bufsz) { if (fd != AUTH_ROBOTS_TXT_FD) { errno = EINVAL; return -1; } return (int) bufsz; } static int robots_fsio_access(pr_fs_t *fs, const char *path, int mode, uid_t uid, gid_t gid, array_header *suppl_gids) { if (mode != R_OK) { errno = EACCES; return -1; } return 0; } static int robots_fsio_faccess(pr_fh_t *fh, int mode, uid_t uid, gid_t gid, array_header *suppl_gids) { if (fh->fh_fd != AUTH_ROBOTS_TXT_FD) { errno = EINVAL; return -1; } if (mode != R_OK) { errno = EACCES; return -1; } return 0; } MODRET auth_pre_retr(cmd_rec *cmd) { const char *path; pr_fs_t *curr_fs = NULL; struct stat st; /* Only apply this for <Anonymous> logins. */ if (session.anon_config == NULL) { return PR_DECLINED(cmd); } if (auth_anon_allow_robots == TRUE) { return PR_DECLINED(cmd); } auth_anon_allow_robots_enabled = FALSE; path = dir_canonical_path(cmd->tmp_pool, cmd->arg); if (strcasecmp(path, "/robots.txt") != 0) { return PR_DECLINED(cmd); } /* If a previous REST command, with a non-zero value, has been sent, then * do nothing. Ugh. */ if (session.restart_pos > 0) { pr_log_debug(DEBUG10, "'AnonAllowRobots off' in effect, but cannot " "support resumed download (REST %" PR_LU " previously sent by client)", (pr_off_t) session.restart_pos); return PR_DECLINED(cmd); } pr_fs_clear_cache2(path); if (pr_fsio_lstat(path, &st) == 0) { /* There's an existing REAL "robots.txt" file on disk; use that, and * preserve the principle of least surprise. */ pr_log_debug(DEBUG10, "'AnonAllowRobots off' in effect, but have " "real 'robots.txt' file on disk; using that"); return PR_DECLINED(cmd); } curr_fs = pr_get_fs(path, NULL); if (curr_fs != NULL) { pr_fs_t *robots_fs; robots_fs = pr_register_fs(cmd->pool, "robots", path); if (robots_fs == NULL) { pr_log_debug(DEBUG8, "'AnonAllowRobots off' in effect, but failed to " "register FS: %s", strerror(errno)); return PR_DECLINED(cmd); } /* Use enough of our own custom FSIO callbacks to be able to provide * a fake "robots.txt" file. */ robots_fs->stat = robots_fsio_stat; robots_fs->fstat = robots_fsio_fstat; robots_fs->lstat = robots_fsio_lstat; robots_fs->unlink = robots_fsio_unlink; robots_fs->open = robots_fsio_open; robots_fs->close = robots_fsio_close; robots_fs->read = robots_fsio_read; robots_fs->write = robots_fsio_write; robots_fs->access = robots_fsio_access; robots_fs->faccess = robots_fsio_faccess; /* For all other FSIO callbacks, use the underlying FS. */ robots_fs->rename = curr_fs->rename; robots_fs->lseek = curr_fs->lseek; robots_fs->link = curr_fs->link; robots_fs->readlink = curr_fs->readlink; robots_fs->symlink = curr_fs->symlink; robots_fs->ftruncate = curr_fs->ftruncate; robots_fs->truncate = curr_fs->truncate; robots_fs->chmod = curr_fs->chmod; robots_fs->fchmod = curr_fs->fchmod; robots_fs->chown = curr_fs->chown; robots_fs->fchown = curr_fs->fchown; robots_fs->lchown = curr_fs->lchown; robots_fs->utimes = curr_fs->utimes; robots_fs->futimes = curr_fs->futimes; robots_fs->fsync = curr_fs->fsync; pr_fs_clear_cache2(path); auth_anon_allow_robots_enabled = TRUE; } return PR_DECLINED(cmd); } MODRET auth_post_retr(cmd_rec *cmd) { if (auth_anon_allow_robots == TRUE) { return PR_DECLINED(cmd); } if (auth_anon_allow_robots_enabled == TRUE) { int res; res = pr_unregister_fs("/robots.txt"); if (res < 0) { pr_log_debug(DEBUG9, "error removing 'robots' FS for '/robots.txt': %s", strerror(errno)); } auth_anon_allow_robots_enabled = FALSE; } return PR_DECLINED(cmd); } /* Configuration handlers */ MODRET set_accessdenymsg(cmd_rec *cmd) { config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); c = add_config_param_str(cmd->argv[0], 1, cmd->argv[1]); c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } MODRET set_accessgrantmsg(cmd_rec *cmd) { config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); c = add_config_param_str(cmd->argv[0], 1, cmd->argv[1]); c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } /* usage: AllowChrootSymlinks on|off */ MODRET set_allowchrootsymlinks(cmd_rec *cmd) { int allow_chroot_symlinks = -1; config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL); allow_chroot_symlinks = get_boolean(cmd, 1); if (allow_chroot_symlinks == -1) { CONF_ERROR(cmd, "expected Boolean parameter"); } c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(int)); *((int *) c->argv[0]) = allow_chroot_symlinks; return PR_HANDLED(cmd); } /* usage: AllowEmptyPasswords on|off */ MODRET set_allowemptypasswords(cmd_rec *cmd) { int allow_empty_passwords = -1; config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); allow_empty_passwords = get_boolean(cmd, 1); if (allow_empty_passwords == -1) { CONF_ERROR(cmd, "expected Boolean parameter"); } c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(int)); *((int *) c->argv[0]) = allow_empty_passwords; c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } /* usage: AnonAllowRobots on|off */ MODRET set_anonallowrobots(cmd_rec *cmd) { int allow_robots = -1; config_rec *c; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ANON); allow_robots = get_boolean(cmd, 1); if (allow_robots == -1) { CONF_ERROR(cmd, "expected Boolean parameter"); } c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = palloc(c->pool, sizeof(int)); *((int *) c->argv[0]) = allow_robots; return PR_HANDLED(cmd); } MODRET set_anonrequirepassword(cmd_rec *cmd) { int bool = -1; config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ANON); bool = get_boolean(cmd, 1); if (bool == -1) CONF_ERROR(cmd, "expected Boolean parameter"); c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = bool; return PR_HANDLED(cmd); } /* usage: AnonRejectPasswords pattern [flags] */ MODRET set_anonrejectpasswords(cmd_rec *cmd) { #ifdef PR_USE_REGEX config_rec *c; pr_regex_t *pre = NULL; int notmatch = FALSE, regex_flags = REG_EXTENDED|REG_NOSUB, res = 0; char *pattern = NULL; if (cmd->argc-1 < 1 || cmd->argc-1 > 2) { CONF_ERROR(cmd, "bad number of parameters"); } CHECK_CONF(cmd, CONF_ANON); /* Make sure that, if present, the flags parameter is correctly formatted. */ if (cmd->argc-1 == 2) { int flags = 0; /* We need to parse the flags parameter here, to see if any flags which * affect the compilation of the regex (e.g. NC) are present. */ flags = pr_filter_parse_flags(cmd->tmp_pool, cmd->argv[2]); if (flags < 0) { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, ": badly formatted flags parameter: '", cmd->argv[2], "'", NULL)); } if (flags == 0) { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, ": unknown flags '", cmd->argv[2], "'", NULL)); } regex_flags |= flags; } pre = pr_regexp_alloc(&auth_module); pattern = cmd->argv[1]; if (*pattern == '!') { notmatch = TRUE; pattern++; } res = pr_regexp_compile(pre, pattern, regex_flags); if (res != 0) { char errstr[200] = {'\0'}; pr_regexp_error(res, pre, errstr, 200); pr_regexp_free(NULL, pre); CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "Unable to compile regex '", cmd->argv[1], "': ", errstr, NULL)); } c = add_config_param(cmd->argv[0], 2, pre, NULL); c->argv[1] = palloc(c->pool, sizeof(int)); *((int *) c->argv[1]) = notmatch; return PR_HANDLED(cmd); #else CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "The ", cmd->argv[0], " directive " "cannot be used on this system, as you do not have POSIX compliant " "regex support", NULL)); #endif } MODRET set_authaliasonly(cmd_rec *cmd) { int bool = -1; config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); bool = get_boolean(cmd, 1); if (bool == -1) CONF_ERROR(cmd, "expected Boolean parameter"); c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = bool; c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } MODRET set_authusingalias(cmd_rec *cmd) { int bool = -1; config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ANON); bool = get_boolean(cmd, 1); if (bool == -1) CONF_ERROR(cmd, "expected Boolean parameter"); c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = bool; return PR_HANDLED(cmd); } MODRET set_createhome(cmd_rec *cmd) { int bool = -1, start = 2; mode_t mode = (mode_t) 0700, dirmode = (mode_t) 0711; char *skel_path = NULL; config_rec *c = NULL; uid_t cuid = 0; gid_t cgid = 0, hgid = -1; unsigned long flags = 0UL; if (cmd->argc-1 < 1) { CONF_ERROR(cmd, "wrong number of parameters"); } CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL); bool = get_boolean(cmd, 1); if (bool == -1) { CONF_ERROR(cmd, "expected Boolean parameter"); } /* No need to process the rest if bool is FALSE. */ if (bool == FALSE) { c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = bool; return PR_HANDLED(cmd); } /* Check the mode parameter, if present */ if (cmd->argc-1 >= 2 && strcasecmp(cmd->argv[2], "dirmode") != 0 && strcasecmp(cmd->argv[2], "skel") != 0) { char *tmp = NULL; mode = strtol(cmd->argv[2], &tmp, 8); if (tmp && *tmp) CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, ": bad mode parameter: '", cmd->argv[2], "'", NULL)); start = 3; } if (cmd->argc-1 > 2) { register unsigned int i; /* Cycle through the rest of the parameters */ for (i = start; i < cmd->argc;) { if (strcasecmp(cmd->argv[i], "skel") == 0) { struct stat st; /* Check that the skel directory, if configured, meets the * requirements. */ skel_path = cmd->argv[++i]; if (*skel_path != '/') { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "skel path '", skel_path, "' is not a full path", NULL)); } if (pr_fsio_stat(skel_path, &st) < 0) { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "unable to stat '", skel_path, "': ", strerror(errno), NULL)); } if (!S_ISDIR(st.st_mode)) { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "'", skel_path, "' is not a directory", NULL)); } /* Must not be world-writable. */ if (st.st_mode & S_IWOTH) { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "'", skel_path, "' is world-writable", NULL)); } /* Move the index past the skel parameter */ i++; } else if (strcasecmp(cmd->argv[i], "dirmode") == 0) { char *tmp = NULL; dirmode = strtol(cmd->argv[++i], &tmp, 8); if (tmp && *tmp) CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "bad mode parameter: '", cmd->argv[i], "'", NULL)); /* Move the index past the dirmode parameter */ i++; } else if (strcasecmp(cmd->argv[i], "uid") == 0) { /* Check for a "~" parameter. */ if (strncmp(cmd->argv[i+1], "~", 2) != 0) { uid_t uid; if (pr_str2uid(cmd->argv[++i], &uid) < 0) { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "bad UID parameter: '", cmd->argv[i], "'", NULL)); } cuid = uid; } else { cuid = (uid_t) -1; i++; } /* Move the index past the uid parameter */ i++; } else if (strcasecmp(cmd->argv[i], "gid") == 0) { /* Check for a "~" parameter. */ if (strncmp(cmd->argv[i+1], "~", 2) != 0) { gid_t gid; if (pr_str2gid(cmd->argv[++i], &gid) < 0) { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "bad GID parameter: '", cmd->argv[i], "'", NULL)); } cgid = gid; } else { cgid = (gid_t) -1; i++; } /* Move the index past the gid parameter */ i++; } else if (strcasecmp(cmd->argv[i], "homegid") == 0) { char *tmp = NULL; gid_t gid; gid = strtol(cmd->argv[++i], &tmp, 10); if (tmp && *tmp) { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "bad GID parameter: '", cmd->argv[i], "'", NULL)); } hgid = gid; /* Move the index past the homegid parameter */ i++; } else if (strcasecmp(cmd->argv[i], "NoRootPrivs") == 0) { flags |= PR_MKHOME_FL_USE_USER_PRIVS; i++; } else { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "unknown parameter: '", cmd->argv[i], "'", NULL)); } } } c = add_config_param(cmd->argv[0], 8, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = bool; c->argv[1] = pcalloc(c->pool, sizeof(mode_t)); *((mode_t *) c->argv[1]) = mode; c->argv[2] = pcalloc(c->pool, sizeof(mode_t)); *((mode_t *) c->argv[2]) = dirmode; if (skel_path) { c->argv[3] = pstrdup(c->pool, skel_path); } c->argv[4] = pcalloc(c->pool, sizeof(uid_t)); *((uid_t *) c->argv[4]) = cuid; c->argv[5] = pcalloc(c->pool, sizeof(gid_t)); *((gid_t *) c->argv[5]) = cgid; c->argv[6] = pcalloc(c->pool, sizeof(gid_t)); *((gid_t *) c->argv[6]) = hgid; c->argv[7] = pcalloc(c->pool, sizeof(unsigned long)); *((unsigned long *) c->argv[7]) = flags; return PR_HANDLED(cmd); } MODRET add_defaultroot(cmd_rec *cmd) { config_rec *c; char *dir; unsigned int argc; void **argv; array_header *acl = NULL; CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL); if (cmd->argc < 2) { CONF_ERROR(cmd, "syntax: DefaultRoot <directory> [<group-expression>]"); } argc = cmd->argc - 2; argv = cmd->argv; dir = *++argv; /* dir must be / or ~. */ if (*dir != '/' && *dir != '~') { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "(", dir, ") absolute pathname " "required", NULL)); } if (strchr(dir, '*')) { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "(", dir, ") wildcards not allowed " "in pathname", NULL)); } if (*(dir + strlen(dir) - 1) != '/') { dir = pstrcat(cmd->tmp_pool, dir, "/", NULL); } acl = pr_expr_create(cmd->tmp_pool, &argc, (char **) argv); c = add_config_param(cmd->argv[0], 0); c->argc = argc + 1; c->argv = pcalloc(c->pool, (argc + 2) * sizeof(void *)); argv = c->argv; *argv++ = pstrdup(c->pool, dir); if (argc && acl) while(argc--) { *argv++ = pstrdup(c->pool, *((char **) acl->elts)); acl->elts = ((char **) acl->elts) + 1; } *argv = NULL; return PR_HANDLED(cmd); } MODRET add_defaultchdir(cmd_rec *cmd) { config_rec *c; char *dir; unsigned int argc; void **argv; array_header *acl = NULL; CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); if (cmd->argc < 2) { CONF_ERROR(cmd, "syntax: DefaultChdir <directory> [<group-expression>]"); } argc = cmd->argc - 2; argv = cmd->argv; dir = *++argv; if (strchr(dir, '*')) { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "(", dir, ") wildcards not allowed " "in pathname", NULL)); } if (*(dir + strlen(dir) - 1) != '/') { dir = pstrcat(cmd->tmp_pool, dir, "/", NULL); } acl = pr_expr_create(cmd->tmp_pool, &argc, (char **) argv); c = add_config_param(cmd->argv[0], 0); c->argc = argc + 1; c->argv = pcalloc(c->pool, (argc + 2) * sizeof(void *)); argv = c->argv; *argv++ = pstrdup(c->pool, dir); if (argc && acl) { while(argc--) { *argv++ = pstrdup(c->pool, *((char **) acl->elts)); acl->elts = ((char **) acl->elts) + 1; } } *argv = NULL; c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } MODRET set_displaylogin(cmd_rec *cmd) { config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); c = add_config_param_str(cmd->argv[0], 1, cmd->argv[1]); c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } MODRET set_grouppassword(cmd_rec *cmd) { config_rec *c = NULL; CHECK_ARGS(cmd, 2); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); c = add_config_param_str(cmd->argv[0], 2, cmd->argv[1], cmd->argv[2]); c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } MODRET set_loginpasswordprompt(cmd_rec *cmd) { int bool = -1; config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); bool = get_boolean(cmd, 1); if (bool == -1) CONF_ERROR(cmd, "expected Boolean parameter"); c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = bool; c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } /* usage: MaxClientsPerClass class max|"none" ["message"] */ MODRET set_maxclientsclass(cmd_rec *cmd) { int max; config_rec *c; CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL); if (strcasecmp(cmd->argv[2], "none") == 0) max = 0; else { char *endp = NULL; max = (int) strtol(cmd->argv[2], &endp, 10); if ((endp && *endp) || max < 1) CONF_ERROR(cmd, "max must be 'none' or a number greater than 0"); } if (cmd->argc == 4) { c = add_config_param(cmd->argv[0], 3, NULL, NULL, NULL); c->argv[0] = pstrdup(c->pool, cmd->argv[1]); c->argv[1] = pcalloc(c->pool, sizeof(unsigned int)); *((unsigned int *) c->argv[1]) = max; c->argv[2] = pstrdup(c->pool, cmd->argv[3]); } else { c = add_config_param(cmd->argv[0], 2, NULL, NULL); c->argv[0] = pstrdup(c->pool, cmd->argv[1]); c->argv[1] = pcalloc(c->pool, sizeof(unsigned int)); *((unsigned int *) c->argv[1]) = max; } return PR_HANDLED(cmd); } /* usage: MaxClients max|"none" ["message"] */ MODRET set_maxclients(cmd_rec *cmd) { int max; config_rec *c = NULL; if (cmd->argc < 2 || cmd->argc > 3) CONF_ERROR(cmd, "wrong number of parameters"); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); if (!strcasecmp(cmd->argv[1], "none")) max = 0; else { char *endp = NULL; max = (int) strtol(cmd->argv[1], &endp, 10); if ((endp && *endp) || max < 1) CONF_ERROR(cmd, "parameter must be 'none' or a number greater than 0"); } if (cmd->argc == 3) { c = add_config_param(cmd->argv[0], 2, NULL, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned int)); *((unsigned int *) c->argv[0]) = max; c->argv[1] = pstrdup(c->pool, cmd->argv[2]); } else { c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned int)); *((unsigned int *) c->argv[0]) = max; } c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } /* usage: MaxClientsPerHost max|"none" ["message"] */ MODRET set_maxhostclients(cmd_rec *cmd) { int max; config_rec *c = NULL; if (cmd->argc < 2 || cmd->argc > 3) CONF_ERROR(cmd, "wrong number of parameters"); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); if (!strcasecmp(cmd->argv[1], "none")) max = 0; else { char *endp = NULL; max = (int) strtol(cmd->argv[1], &endp, 10); if ((endp && *endp) || max < 1) CONF_ERROR(cmd, "parameter must be 'none' or a number greater than 0"); } if (cmd->argc == 3) { c = add_config_param(cmd->argv[0], 2, NULL, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned int)); *((unsigned int *) c->argv[0]) = max; c->argv[1] = pstrdup(c->pool, cmd->argv[2]); } else { c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned int)); *((unsigned int *) c->argv[0]) = max; } c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } /* usage: MaxClientsPerUser max|"none" ["message"] */ MODRET set_maxuserclients(cmd_rec *cmd) { int max; config_rec *c = NULL; if (cmd->argc < 2 || cmd->argc > 3) CONF_ERROR(cmd, "wrong number of parameters"); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); if (!strcasecmp(cmd->argv[1], "none")) max = 0; else { char *endp = NULL; max = (int) strtol(cmd->argv[1], &endp, 10); if ((endp && *endp) || max < 1) CONF_ERROR(cmd, "parameter must be 'none' or a number greater than 0"); } if (cmd->argc == 3) { c = add_config_param(cmd->argv[0], 2, NULL, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned int)); *((unsigned int *) c->argv[0]) = max; c->argv[1] = pstrdup(c->pool, cmd->argv[2]); } else { c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned int)); *((unsigned int *) c->argv[0]) = max; } c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } /* usage: MaxConnectionsPerHost max|"none" ["message"] */ MODRET set_maxconnectsperhost(cmd_rec *cmd) { int max; config_rec *c; if (cmd->argc < 2 || cmd->argc > 3) CONF_ERROR(cmd, "wrong number of parameters"); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL); if (strcasecmp(cmd->argv[1], "none") == 0) max = 0; else { char *tmp = NULL; max = (int) strtol(cmd->argv[1], &tmp, 10); if ((tmp && *tmp) || max < 1) CONF_ERROR(cmd, "parameter must be 'none' or a number greater than 0"); } if (cmd->argc == 3) { c = add_config_param(cmd->argv[0], 2, NULL, NULL); c->argv[1] = pstrdup(c->pool, cmd->argv[2]); } else c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned int)); *((unsigned int *) c->argv[0]) = max; return PR_HANDLED(cmd); } /* usage: MaxHostsPerUser max|"none" ["message"] */ MODRET set_maxhostsperuser(cmd_rec *cmd) { int max; config_rec *c = NULL; CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); if (cmd->argc < 2 || cmd->argc > 3) CONF_ERROR(cmd, "wrong number of parameters"); if (!strcasecmp(cmd->argv[1], "none")) max = 0; else { char *endp = NULL; max = (int) strtol(cmd->argv[1], &endp, 10); if ((endp && *endp) || max < 1) CONF_ERROR(cmd, "parameter must be 'none' or a number greater than 0"); } if (cmd->argc == 3) { c = add_config_param(cmd->argv[0], 2, NULL, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned int)); *((unsigned int *) c->argv[0]) = max; c->argv[1] = pstrdup(c->pool, cmd->argv[2]); } else { c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned int)); *((unsigned int *) c->argv[0]) = max; } c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } MODRET set_maxloginattempts(cmd_rec *cmd) { int max; config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL); if (strcasecmp(cmd->argv[1], "none") == 0) { max = 0; } else { char *endp = NULL; max = (int) strtol(cmd->argv[1], &endp, 10); if ((endp && *endp) || max < 1) CONF_ERROR(cmd, "parameter must be 'none' or a number greater than 0"); } c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned int)); *((unsigned int *) c->argv[0]) = max; return PR_HANDLED(cmd); } /* usage: MaxPasswordSize len */ MODRET set_maxpasswordsize(cmd_rec *cmd) { config_rec *c; size_t password_len; char *len, *ptr = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL); len = cmd->argv[1]; if (*len == '-') { CONF_ERROR(cmd, "badly formatted parameter"); } password_len = strtoul(len, &ptr, 10); if (ptr && *ptr) { CONF_ERROR(cmd, "badly formatted parameter"); } /* XXX Applies to the following modules, which use crypt(3): * * mod_ldap (ldap_auth_check; "check" authtab) * ldap_auth_auth ("auth" authtab) calls pr_auth_check() * mod_sql (sql_auth_crypt, via SQLAuthTypes; cmd_check "check" authtab dispatches here) * cmd_auth ("auth" authtab) calls pr_auth_check() * mod_auth_file (authfile_chkpass, "check" authtab) * authfile_auth ("auth" authtab) calls pr_auth_check() * mod_auth_unix (pw_check, "check" authtab) * pw_auth ("auth" authtab) calls pr_auth_check() * * mod_sftp uses pr_auth_authenticate(), which will dispatch into above * * mod_radius does NOT use either -- up to RADIUS server policy? * * Is there a common code path that all of the above go through? */ c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = palloc(c->pool, sizeof(size_t)); *((size_t *) c->argv[0]) = password_len; return PR_HANDLED(cmd); } MODRET set_requirevalidshell(cmd_rec *cmd) { int bool = -1; config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); bool = get_boolean(cmd, 1); if (bool == -1) CONF_ERROR(cmd, "expected Boolean parameter"); c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = bool; c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } /* usage: RewriteHome on|off */ MODRET set_rewritehome(cmd_rec *cmd) { int bool = -1; config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL); bool = get_boolean(cmd, 1); if (bool == -1) CONF_ERROR(cmd, "expected Boolean parameter"); c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(int)); *((int *) c->argv[0]) = bool; return PR_HANDLED(cmd); } MODRET set_rootlogin(cmd_rec *cmd) { int bool = -1; config_rec *c = NULL; CHECK_ARGS(cmd,1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); bool = get_boolean(cmd, 1); if (bool == -1) CONF_ERROR(cmd, "expected Boolean parameter"); c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = (unsigned char) bool; c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } /* usage: RootRevoke on|off|UseNonCompliantActiveTransfer */ MODRET set_rootrevoke(cmd_rec *cmd) { int root_revoke = -1; config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); /* A RootRevoke value of 0 indicates 'false', 1 indicates 'true', and * 2 indicates 'NonCompliantActiveTransfer'. */ root_revoke = get_boolean(cmd, 1); if (root_revoke == -1) { if (strcasecmp(cmd->argv[1], "UseNonCompliantActiveTransfer") != 0 && strcasecmp(cmd->argv[1], "UseNonCompliantActiveTransfers") != 0) { CONF_ERROR(cmd, "expected Boolean parameter"); } root_revoke = 2; } c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = (unsigned char) root_revoke; c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } MODRET set_timeoutlogin(cmd_rec *cmd) { int timeout = -1; config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL); if (pr_str_get_duration(cmd->argv[1], &timeout) < 0) { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "error parsing timeout value '", cmd->argv[1], "': ", strerror(errno), NULL)); } c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(int)); *((int *) c->argv[0]) = timeout; return PR_HANDLED(cmd); } MODRET set_timeoutsession(cmd_rec *cmd) { int timeout = 0, precedence = 0; config_rec *c = NULL; int ctxt = (cmd->config && cmd->config->config_type != CONF_PARAM ? cmd->config->config_type : cmd->server->config_type ? cmd->server->config_type : CONF_ROOT); /* this directive must have either 1 or 3 arguments */ if (cmd->argc-1 != 1 && cmd->argc-1 != 3) { CONF_ERROR(cmd, "missing parameters"); } CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); /* Set the precedence for this config_rec based on its configuration * context. */ if (ctxt & CONF_GLOBAL) { precedence = 1; /* These will never appear simultaneously */ } else if ((ctxt & CONF_ROOT) || (ctxt & CONF_VIRTUAL)) { precedence = 2; } else if (ctxt & CONF_ANON) { precedence = 3; } if (pr_str_get_duration(cmd->argv[1], &timeout) < 0) { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "error parsing timeout value '", cmd->argv[1], "': ", strerror(errno), NULL)); } if (timeout == 0) { /* do nothing */ return PR_HANDLED(cmd); } if (cmd->argc-1 == 3) { if (strncmp(cmd->argv[2], "user", 5) == 0 || strncmp(cmd->argv[2], "group", 6) == 0 || strncmp(cmd->argv[2], "class", 6) == 0) { /* no op */ } else { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, cmd->argv[0], ": unknown classifier used: '", cmd->argv[2], "'", NULL)); } } if (cmd->argc-1 == 1) { c = add_config_param(cmd->argv[0], 2, NULL); c->argv[0] = pcalloc(c->pool, sizeof(int)); *((int *) c->argv[0]) = timeout; c->argv[1] = pcalloc(c->pool, sizeof(unsigned int)); *((unsigned int *) c->argv[1]) = precedence; } else if (cmd->argc-1 == 3) { array_header *acl = NULL; unsigned int argc; void **argv; argc = cmd->argc - 3; argv = cmd->argv + 2; acl = pr_expr_create(cmd->tmp_pool, &argc, (char **) argv); c = add_config_param(cmd->argv[0], 0); c->argc = argc + 2; /* Add 3 to argc for the argv of the config_rec: one for the * seconds value, one for the precedence, one for the classifier, * and one for the terminating NULL. */ c->argv = pcalloc(c->pool, ((argc + 4) * sizeof(void *))); /* Capture the config_rec's argv pointer for doing the by-hand * population. */ argv = c->argv; /* Copy in the seconds. */ *argv = pcalloc(c->pool, sizeof(int)); *((int *) *argv++) = timeout; /* Copy in the precedence. */ *argv = pcalloc(c->pool, sizeof(unsigned int)); *((unsigned int *) *argv++) = precedence; /* Copy in the classifier. */ *argv++ = pstrdup(c->pool, cmd->argv[2]); /* now, copy in the expression arguments */ if (argc && acl) { while (argc--) { *argv++ = pstrdup(c->pool, *((char **) acl->elts)); acl->elts = ((char **) acl->elts) + 1; } } /* don't forget the terminating NULL */ *argv = NULL; } else { /* Should never reach here. */ CONF_ERROR(cmd, "wrong number of parameters"); } c->flags |= CF_MERGEDOWN_MULTI; return PR_HANDLED(cmd); } MODRET set_useftpusers(cmd_rec *cmd) { int bool = -1; config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); bool = get_boolean(cmd, 1); if (bool == -1) CONF_ERROR(cmd, "expected Boolean parameter"); c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = bool; c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } /* usage: UseLastlog on|off */ MODRET set_uselastlog(cmd_rec *cmd) { #ifdef PR_USE_LASTLOG int bool; config_rec *c; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL); bool = get_boolean(cmd, 1); if (bool == -1) CONF_ERROR(cmd, "expected Boolean parameter"); c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = bool; return PR_HANDLED(cmd); #else CONF_ERROR(cmd, "requires lastlog support (--with-lastlog)"); #endif /* PR_USE_LASTLOG */ } /* usage: UserAlias alias real-user */ MODRET set_useralias(cmd_rec *cmd) { config_rec *c = NULL; char *alias, *real_user; CHECK_ARGS(cmd, 2); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); /* Make sure that the given names differ. */ alias = cmd->argv[1]; real_user = cmd->argv[2]; if (strcmp(alias, real_user) == 0) { CONF_ERROR(cmd, "alias and real user names must differ"); } c = add_config_param_str(cmd->argv[0], 2, alias, real_user); /* Note: only merge this directive down if it is not appearing in an * <Anonymous> context. */ if (!check_context(cmd, CONF_ANON)) { c->flags |= CF_MERGEDOWN_MULTI; } return PR_HANDLED(cmd); } MODRET set_userdirroot(cmd_rec *cmd) { int bool = -1; config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ANON); bool = get_boolean(cmd, 1); if (bool == -1) CONF_ERROR(cmd, "expected Boolean parameter"); c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = bool; return PR_HANDLED(cmd); } MODRET set_userpassword(cmd_rec *cmd) { config_rec *c = NULL; CHECK_ARGS(cmd, 2); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); c = add_config_param_str(cmd->argv[0], 2, cmd->argv[1], cmd->argv[2]); c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } /* usage: WtmpLog on|off */ MODRET set_wtmplog(cmd_rec *cmd) { int use_wtmp = -1; config_rec *c = NULL; CHECK_ARGS(cmd, 1); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); if (strcasecmp(cmd->argv[1], "NONE") == 0) { use_wtmp = FALSE; } else { use_wtmp = get_boolean(cmd, 1); if (use_wtmp == -1) { CONF_ERROR(cmd, "expected Boolean parameter"); } } c = add_config_param(cmd->argv[0], 1, NULL); c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); *((unsigned char *) c->argv[0]) = use_wtmp; c->flags |= CF_MERGEDOWN; return PR_HANDLED(cmd); } /* Module API tables */ static conftable auth_conftab[] = { { "AccessDenyMsg", set_accessdenymsg, NULL }, { "AccessGrantMsg", set_accessgrantmsg, NULL }, { "AllowChrootSymlinks", set_allowchrootsymlinks, NULL }, { "AllowEmptyPasswords", set_allowemptypasswords, NULL }, { "AnonAllowRobots", set_anonallowrobots, NULL }, { "AnonRequirePassword", set_anonrequirepassword, NULL }, { "AnonRejectPasswords", set_anonrejectpasswords, NULL }, { "AuthAliasOnly", set_authaliasonly, NULL }, { "AuthUsingAlias", set_authusingalias, NULL }, { "CreateHome", set_createhome, NULL }, { "DefaultChdir", add_defaultchdir, NULL }, { "DefaultRoot", add_defaultroot, NULL }, { "DisplayLogin", set_displaylogin, NULL }, { "GroupPassword", set_grouppassword, NULL }, { "LoginPasswordPrompt", set_loginpasswordprompt, NULL }, { "MaxClients", set_maxclients, NULL }, { "MaxClientsPerClass", set_maxclientsclass, NULL }, { "MaxClientsPerHost", set_maxhostclients, NULL }, { "MaxClientsPerUser", set_maxuserclients, NULL }, { "MaxConnectionsPerHost", set_maxconnectsperhost, NULL }, { "MaxHostsPerUser", set_maxhostsperuser, NULL }, { "MaxLoginAttempts", set_maxloginattempts, NULL }, { "MaxPasswordSize", set_maxpasswordsize, NULL }, { "RequireValidShell", set_requirevalidshell, NULL }, { "RewriteHome", set_rewritehome, NULL }, { "RootLogin", set_rootlogin, NULL }, { "RootRevoke", set_rootrevoke, NULL }, { "TimeoutLogin", set_timeoutlogin, NULL }, { "TimeoutSession", set_timeoutsession, NULL }, { "UseFtpUsers", set_useftpusers, NULL }, { "UseLastlog", set_uselastlog, NULL }, { "UserAlias", set_useralias, NULL }, { "UserDirRoot", set_userdirroot, NULL }, { "UserPassword", set_userpassword, NULL }, { "WtmpLog", set_wtmplog, NULL }, { NULL, NULL, NULL } }; static cmdtable auth_cmdtab[] = { { PRE_CMD, C_USER, G_NONE, auth_pre_user, FALSE, FALSE, CL_AUTH }, { CMD, C_USER, G_NONE, auth_user, FALSE, FALSE, CL_AUTH }, { PRE_CMD, C_PASS, G_NONE, auth_pre_pass, FALSE, FALSE, CL_AUTH }, { CMD, C_PASS, G_NONE, auth_pass, FALSE, FALSE, CL_AUTH }, { POST_CMD, C_PASS, G_NONE, auth_post_pass, FALSE, FALSE, CL_AUTH }, { LOG_CMD, C_PASS, G_NONE, auth_log_pass, FALSE, FALSE }, { LOG_CMD_ERR,C_PASS, G_NONE, auth_err_pass, FALSE, FALSE }, { CMD, C_ACCT, G_NONE, auth_acct, FALSE, FALSE, CL_AUTH }, { CMD, C_REIN, G_NONE, auth_rein, FALSE, FALSE, CL_AUTH }, /* For the automatic robots.txt handling */ { PRE_CMD, C_RETR, G_NONE, auth_pre_retr, FALSE, FALSE }, { POST_CMD, C_RETR, G_NONE, auth_post_retr, FALSE, FALSE }, { POST_CMD_ERR,C_RETR,G_NONE, auth_post_retr, FALSE, FALSE }, { 0, NULL } }; /* Module interface */ module auth_module = { NULL, NULL, /* Module API version */ 0x20, /* Module name */ "auth", /* Module configuration directive table */ auth_conftab, /* Module command handler table */ auth_cmdtab, /* Module authentication handler table */ NULL, /* Module initialization function */ auth_init, /* Session initialization function */ auth_sess_init };
./CrossVul/dataset_final_sorted/CWE-59/c/bad_3264_0
crossvul-cpp_data_good_436_6
/* * Soft: Vrrpd is an implementation of VRRPv2 as specified in rfc2338. * VRRP is a protocol which elect a master server on a LAN. If the * master fails, a backup server takes over. * The original implementation has been made by jerome etienne. * * Part: Print running VRRP state information * * Author: John Southworth, <john.southworth@vyatta.com> * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. * * Copyright (C) 2012 John Southworth, <john.southworth@vyatta.com> * Copyright (C) 2015-2017 Alexandre Cassen, <acassen@gmail.com> */ #include "config.h" #include <errno.h> #include <inttypes.h> #include "logger.h" #include "vrrp.h" #include "vrrp_data.h" #include "vrrp_print.h" #include "utils.h" static const char *dump_file = "/tmp/keepalived.data"; static const char *stats_file = "/tmp/keepalived.stats"; void vrrp_print_data(void) { FILE *file = fopen_safe(dump_file, "w"); if (!file) { log_message(LOG_INFO, "Can't open %s (%d: %s)", dump_file, errno, strerror(errno)); return; } dump_data_vrrp(file); fclose(file); } void vrrp_print_stats(void) { FILE *file = fopen_safe(stats_file, "w"); element e; vrrp_t *vrrp; if (!file) { log_message(LOG_INFO, "Can't open %s (%d: %s)", stats_file, errno, strerror(errno)); return; } LIST_FOREACH(vrrp_data->vrrp, vrrp, e) { fprintf(file, "VRRP Instance: %s\n", vrrp->iname); fprintf(file, " Advertisements:\n"); fprintf(file, " Received: %" PRIu64 "\n", vrrp->stats->advert_rcvd); fprintf(file, " Sent: %d\n", vrrp->stats->advert_sent); fprintf(file, " Became master: %d\n", vrrp->stats->become_master); fprintf(file, " Released master: %d\n", vrrp->stats->release_master); fprintf(file, " Packet Errors:\n"); fprintf(file, " Length: %" PRIu64 "\n", vrrp->stats->packet_len_err); fprintf(file, " TTL: %" PRIu64 "\n", vrrp->stats->ip_ttl_err); fprintf(file, " Invalid Type: %" PRIu64 "\n", vrrp->stats->invalid_type_rcvd); fprintf(file, " Advertisement Interval: %" PRIu64 "\n", vrrp->stats->advert_interval_err); fprintf(file, " Address List: %" PRIu64 "\n", vrrp->stats->addr_list_err); fprintf(file, " Authentication Errors:\n"); fprintf(file, " Invalid Type: %d\n", vrrp->stats->invalid_authtype); #ifdef _WITH_VRRP_AUTH_ fprintf(file, " Type Mismatch: %d\n", vrrp->stats->authtype_mismatch); fprintf(file, " Failure: %d\n", vrrp->stats->auth_failure); #endif fprintf(file, " Priority Zero:\n"); fprintf(file, " Received: %" PRIu64 "\n", vrrp->stats->pri_zero_rcvd); fprintf(file, " Sent: %" PRIu64 "\n", vrrp->stats->pri_zero_sent); } fclose(file); }
./CrossVul/dataset_final_sorted/CWE-59/c/good_436_6
crossvul-cpp_data_bad_1506_0
/* Copyright (C) 2010 ABRT team This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "problem_api.h" #include "libabrt.h" /* Maximal length of backtrace. */ #define MAX_BACKTRACE_SIZE (1024*1024) /* Amount of data received from one client for a message before reporting error. */ #define MAX_MESSAGE_SIZE (4*MAX_BACKTRACE_SIZE) /* Maximal number of characters read from socket at once. */ #define INPUT_BUFFER_SIZE (8*1024) /* We exit after this many seconds */ #define TIMEOUT 10 /* Unix socket in ABRT daemon for creating new dump directories. Why to use socket for creating dump dirs? Security. When a Python script throws unexpected exception, ABRT handler catches it, running as a part of that broken Python application. The application is running with certain SELinux privileges, for example it can not execute other programs, or to create files in /var/cache or anything else required to properly fill a problem directory. Adding these privileges to every application would weaken the security. The most suitable solution is for the Python application to open a socket where ABRT daemon is listening, write all relevant data to that socket, and close it. ABRT daemon handles the rest. ** Protocol Initializing new dump: open /var/run/abrt.socket Providing dump data (hook writes to the socket): MANDATORY ITEMS: -> "PID=" number 0 - PID_MAX (/proc/sys/kernel/pid_max) \0 -> "EXECUTABLE=" string \0 -> "BACKTRACE=" string \0 -> "ANALYZER=" string \0 -> "BASENAME=" string (no slashes) \0 -> "REASON=" string \0 You can send more messages using the same KEY=value format. */ static unsigned total_bytes_read = 0; static uid_t client_uid = (uid_t)-1L; /* Remove dump dir */ static int delete_path(const char *dump_dir_name) { /* If doesn't start with "g_settings_dump_location/"... */ if (!dir_is_in_dump_location(dump_dir_name)) { /* Then refuse to operate on it (someone is attacking us??) */ error_msg("Bad problem directory name '%s', should start with: '%s'", dump_dir_name, g_settings_dump_location); return 400; /* Bad Request */ } if (!dir_has_correct_permissions(dump_dir_name)) { error_msg("Problem directory '%s' isn't owned by root:abrt or others are not restricted from access", dump_dir_name); return 400; /* */ } int dir_fd = dd_openfd(dump_dir_name); if (dir_fd < 0) { perror_msg("Can't open problem directory '%s'", dump_dir_name); return 400; } if (!fdump_dir_accessible_by_uid(dir_fd, client_uid)) { close(dir_fd); if (errno == ENOTDIR) { error_msg("Path '%s' isn't problem directory", dump_dir_name); return 404; /* Not Found */ } error_msg("Problem directory '%s' can't be accessed by user with uid %ld", dump_dir_name, (long)client_uid); return 403; /* Forbidden */ } struct dump_dir *dd = dd_fdopendir(dir_fd, dump_dir_name, /*flags:*/ 0); if (dd) { if (dd_delete(dd) != 0) { error_msg("Failed to delete problem directory '%s'", dump_dir_name); dd_close(dd); return 400; } } return 0; /* success */ } static pid_t spawn_event_handler_child(const char *dump_dir_name, const char *event_name, int *fdp) { char *args[7]; args[0] = (char *) LIBEXEC_DIR"/abrt-handle-event"; /* Do not forward ASK_* messages to parent*/ args[1] = (char *) "-i"; args[2] = (char *) "-e"; args[3] = (char *) event_name; args[4] = (char *) "--"; args[5] = (char *) dump_dir_name; args[6] = NULL; int pipeout[2]; int flags = EXECFLG_INPUT_NUL | EXECFLG_OUTPUT | EXECFLG_QUIET | EXECFLG_ERR2OUT; VERB1 flags &= ~EXECFLG_QUIET; char *env_vec[2]; /* Intercept ASK_* messages in Client API -> don't wait for user response */ env_vec[0] = xstrdup("REPORT_CLIENT_NONINTERACTIVE=1"); env_vec[1] = NULL; pid_t child = fork_execv_on_steroids(flags, args, pipeout, env_vec, /*dir:*/ NULL, /*uid(unused):*/ 0); if (fdp) *fdp = pipeout[0]; return child; } static int run_post_create(const char *dirname) { /* If doesn't start with "g_settings_dump_location/"... */ if (!dir_is_in_dump_location(dirname)) { /* Then refuse to operate on it (someone is attacking us??) */ error_msg("Bad problem directory name '%s', should start with: '%s'", dirname, g_settings_dump_location); return 400; /* Bad Request */ } if (!dir_has_correct_permissions(dirname)) { error_msg("Problem directory '%s' isn't owned by root:abrt or others are not restricted from access", dirname); return 400; /* */ } if (g_settings_privatereports) { struct dump_dir *dd = dd_opendir(dirname, DD_OPEN_READONLY); const bool complete = dd && problem_dump_dir_is_complete(dd); dd_close(dd); if (complete) { error_msg("Problem directory '%s' has already been processed", dirname); return 403; } } int child_stdout_fd; int child_pid = spawn_event_handler_child(dirname, "post-create", &child_stdout_fd); char *dup_of_dir = NULL; struct strbuf *cmd_output = strbuf_new(); bool child_is_post_create = 1; /* else it is a notify child */ read_child_output: //log("Reading from event fd %d", child_stdout_fd); /* Read streamed data and split lines */ for (;;) { char buf[250]; /* usually we get one line, no need to have big buf */ errno = 0; int r = safe_read(child_stdout_fd, buf, sizeof(buf) - 1); if (r <= 0) break; buf[r] = '\0'; /* split lines in the current buffer */ char *raw = buf; char *newline; while ((newline = strchr(raw, '\n')) != NULL) { *newline = '\0'; strbuf_append_str(cmd_output, raw); char *msg = cmd_output->buf; /* Hmm, DUP_OF_DIR: ends up in syslog. move log() into 'else'? */ log("%s", msg); if (child_is_post_create && prefixcmp(msg, "DUP_OF_DIR: ") == 0 ) { free(dup_of_dir); dup_of_dir = xstrdup(msg + strlen("DUP_OF_DIR: ")); } strbuf_clear(cmd_output); /* jump to next line */ raw = newline + 1; } /* beginning of next line. the line continues by next read */ strbuf_append_str(cmd_output, raw); } /* EOF/error */ /* Wait for child to actually exit, collect status */ int status = 0; if (safe_waitpid(child_pid, &status, 0) <= 0) /* should not happen */ perror_msg("waitpid(%d)", child_pid); /* If it was a "notify[-dup]" event, then we're done */ if (!child_is_post_create) goto ret; /* exit 0 means "this is a good, non-dup dir" */ /* exit with 1 + "DUP_OF_DIR: dir" string => dup */ if (status != 0) { if (WIFSIGNALED(status)) { log("'post-create' on '%s' killed by signal %d", dirname, WTERMSIG(status)); goto delete_bad_dir; } /* else: it is WIFEXITED(status) */ if (!dup_of_dir) { log("'post-create' on '%s' exited with %d", dirname, WEXITSTATUS(status)); goto delete_bad_dir; } } const char *work_dir = (dup_of_dir ? dup_of_dir : dirname); /* Load problem_data (from the *first dir* if this one is a dup) */ struct dump_dir *dd = dd_opendir(work_dir, /*flags:*/ 0); if (!dd) /* dd_opendir already emitted error msg */ goto delete_bad_dir; /* Update count */ char *count_str = dd_load_text_ext(dd, FILENAME_COUNT, DD_FAIL_QUIETLY_ENOENT); unsigned long count = strtoul(count_str, NULL, 10); /* Don't increase crash count if we are working with newly uploaded * directory (remote crash) which already has its crash count set. */ if ((status != 0 && dup_of_dir) || count == 0) { count++; char new_count_str[sizeof(long)*3 + 2]; sprintf(new_count_str, "%lu", count); dd_save_text(dd, FILENAME_COUNT, new_count_str); /* This condition can be simplified to either * (status * != 0 && * dup_of_dir) or (count == 1). But the * chosen form is much more reliable and safe. We must not call * dd_opendir() to locked dd otherwise we go into a deadlock. */ if (strcmp(dd->dd_dirname, dirname) != 0) { /* Update the last occurrence file by the time file of the new problem */ struct dump_dir *new_dd = dd_opendir(dirname, DD_OPEN_READONLY); char *last_ocr = NULL; if (new_dd) { /* TIME must exists in a valid dump directory but we don't want to die * due to broken duplicated dump directory */ last_ocr = dd_load_text_ext(new_dd, FILENAME_TIME, DD_LOAD_TEXT_RETURN_NULL_ON_FAILURE | DD_FAIL_QUIETLY_ENOENT); dd_close(new_dd); } else { /* dd_opendir() already produced a message with good information about failure */ error_msg("Can't read the last occurrence file from the new dump directory."); } if (!last_ocr) { /* the new dump directory may lie in the dump location for some time */ log("Using current time for the last occurrence file which may be incorrect."); time_t t = time(NULL); last_ocr = xasprintf("%lu", (long)t); } dd_save_text(dd, FILENAME_LAST_OCCURRENCE, last_ocr); free(last_ocr); } } /* Reset mode/uig/gid to correct values for all files created by event run */ dd_sanitize_mode_and_owner(dd); dd_close(dd); if (!dup_of_dir) log_notice("New problem directory %s, processing", work_dir); else { log_warning("Deleting problem directory %s (dup of %s)", strrchr(dirname, '/') + 1, strrchr(dup_of_dir, '/') + 1); delete_dump_dir(dirname); } /* Run "notify[-dup]" event */ int fd; child_pid = spawn_event_handler_child( work_dir, (dup_of_dir ? "notify-dup" : "notify"), &fd ); //log("Started notify, fd %d -> %d", fd, child_stdout_fd); xmove_fd(fd, child_stdout_fd); child_is_post_create = 0; strbuf_clear(cmd_output); free(dup_of_dir); dup_of_dir = NULL; goto read_child_output; delete_bad_dir: log_warning("Deleting problem directory '%s'", dirname); delete_dump_dir(dirname); ret: strbuf_free(cmd_output); free(dup_of_dir); close(child_stdout_fd); return 0; } /* Create a new problem directory from client session. * Caller must ensure that all fields in struct client * are properly filled. */ static int create_problem_dir(GHashTable *problem_info, unsigned pid) { /* Exit if free space is less than 1/4 of MaxCrashReportsSize */ if (g_settings_nMaxCrashReportsSize > 0) { if (low_free_space(g_settings_nMaxCrashReportsSize, g_settings_dump_location)) exit(1); } /* Create temp directory with the problem data. * This directory is renamed to final directory name after * all files have been stored into it. */ gchar *dir_basename = g_hash_table_lookup(problem_info, "basename"); if (!dir_basename) dir_basename = g_hash_table_lookup(problem_info, FILENAME_TYPE); char *path = xasprintf("%s/%s-%s-%u.new", g_settings_dump_location, dir_basename, iso_date_string(NULL), pid); /* This item is useless, don't save it */ g_hash_table_remove(problem_info, "basename"); /* No need to check the path length, as all variables used are limited, * and dd_create() fails if the path is too long. */ struct dump_dir *dd = dd_create(path, g_settings_privatereports ? 0 : client_uid, DEFAULT_DUMP_DIR_MODE); if (!dd) { error_msg_and_die("Error creating problem directory '%s'", path); } dd_create_basic_files(dd, client_uid, NULL); dd_save_text(dd, FILENAME_ABRT_VERSION, VERSION); gpointer gpkey = g_hash_table_lookup(problem_info, FILENAME_CMDLINE); if (!gpkey) { /* Obtain and save the command line. */ char *cmdline = get_cmdline(pid); if (cmdline) { dd_save_text(dd, FILENAME_CMDLINE, cmdline); free(cmdline); } } /* Store id of the user whose application crashed. */ char uid_str[sizeof(long) * 3 + 2]; sprintf(uid_str, "%lu", (long)client_uid); dd_save_text(dd, FILENAME_UID, uid_str); GHashTableIter iter; gpointer gpvalue; g_hash_table_iter_init(&iter, problem_info); while (g_hash_table_iter_next(&iter, &gpkey, &gpvalue)) { dd_save_text(dd, (gchar *) gpkey, (gchar *) gpvalue); } dd_close(dd); /* Not needing it anymore */ g_hash_table_destroy(problem_info); /* Move the completely created problem directory * to final directory. */ char *newpath = xstrndup(path, strlen(path) - strlen(".new")); if (rename(path, newpath) == 0) strcpy(path, newpath); free(newpath); log_notice("Saved problem directory of pid %u to '%s'", pid, path); /* We let the peer know that problem dir was created successfully * _before_ we run potentially long-running post-create. */ printf("HTTP/1.1 201 Created\r\n\r\n"); fflush(NULL); close(STDOUT_FILENO); xdup2(STDERR_FILENO, STDOUT_FILENO); /* paranoia: don't leave stdout fd closed */ /* Trim old problem directories if necessary */ if (g_settings_nMaxCrashReportsSize > 0) { trim_problem_dirs(g_settings_dump_location, g_settings_nMaxCrashReportsSize * (double)(1024*1024), path); } run_post_create(path); /* free(path); */ exit(0); } static gboolean key_value_ok(gchar *key, gchar *value) { char *i; /* check key, it has to be valid filename and will end up in the * bugzilla */ for (i = key; *i != 0; i++) { if (!isalpha(*i) && (*i != '-') && (*i != '_') && (*i != ' ')) return FALSE; } /* check value of 'basename', it has to be valid non-hidden directory * name */ if (strcmp(key, "basename") == 0 || strcmp(key, FILENAME_TYPE) == 0 ) { if (!str_is_correct_filename(value)) { error_msg("Value of '%s' ('%s') is not a valid directory name", key, value); return FALSE; } } return TRUE; } /* Handles a message received from client over socket. */ static void process_message(GHashTable *problem_info, char *message) { gchar *key, *value; value = strchr(message, '='); if (value) { key = g_ascii_strdown(message, value - message); /* result is malloced */ //TODO: is it ok? it uses g_malloc, not malloc! value++; if (key_value_ok(key, value)) { if (strcmp(key, FILENAME_UID) == 0) { error_msg("Ignoring value of %s, will be determined later", FILENAME_UID); } else { g_hash_table_insert(problem_info, key, xstrdup(value)); /* Compat, delete when FILENAME_ANALYZER is replaced by FILENAME_TYPE: */ if (strcmp(key, FILENAME_TYPE) == 0) g_hash_table_insert(problem_info, xstrdup(FILENAME_ANALYZER), xstrdup(value)); /* Prevent freeing key later: */ key = NULL; } } else { /* should use error_msg_and_die() here? */ error_msg("Invalid key or value format: %s", message); } free(key); } else { /* should use error_msg_and_die() here? */ error_msg("Invalid message format: '%s'", message); } } static void die_if_data_is_missing(GHashTable *problem_info) { gboolean missing_data = FALSE; gchar **pstring; static const gchar *const needed[] = { FILENAME_TYPE, FILENAME_REASON, /* FILENAME_BACKTRACE, - ECC errors have no such elements */ /* FILENAME_EXECUTABLE, */ NULL }; for (pstring = (gchar**) needed; *pstring; pstring++) { if (!g_hash_table_lookup(problem_info, *pstring)) { error_msg("Element '%s' is missing", *pstring); missing_data = TRUE; } } if (missing_data) error_msg_and_die("Some data is missing, aborting"); } /* * Takes hash table, looks for key FILENAME_PID and tries to convert its value * to int. */ unsigned convert_pid(GHashTable *problem_info) { long ret; gchar *pid_str = (gchar *) g_hash_table_lookup(problem_info, FILENAME_PID); char *err_pos; if (!pid_str) error_msg_and_die("PID data is missing, aborting"); errno = 0; ret = strtol(pid_str, &err_pos, 10); if (errno || pid_str == err_pos || *err_pos != '\0' || ret > UINT_MAX || ret < 1) error_msg_and_die("Malformed or out-of-range PID number: '%s'", pid_str); return (unsigned) ret; } static int perform_http_xact(void) { /* use free instead of g_free so that we can use xstr* functions from * libreport/lib/xfuncs.c */ GHashTable *problem_info = g_hash_table_new_full(g_str_hash, g_str_equal, free, free); /* Read header */ char *body_start = NULL; char *messagebuf_data = NULL; unsigned messagebuf_len = 0; /* Loop until EOF/error/timeout/end_of_header */ while (1) { messagebuf_data = xrealloc(messagebuf_data, messagebuf_len + INPUT_BUFFER_SIZE); char *p = messagebuf_data + messagebuf_len; int rd = read(STDIN_FILENO, p, INPUT_BUFFER_SIZE); if (rd < 0) { if (errno == EINTR) /* SIGALRM? */ error_msg_and_die("Timed out"); perror_msg_and_die("read"); } if (rd == 0) break; log_debug("Received %u bytes of data", rd); messagebuf_len += rd; total_bytes_read += rd; if (total_bytes_read > MAX_MESSAGE_SIZE) error_msg_and_die("Message is too long, aborting"); /* Check whether we see end of header */ /* Note: we support both [\r]\n\r\n and \n\n */ char *past_end = messagebuf_data + messagebuf_len; if (p > messagebuf_data+1) p -= 2; /* start search from two last bytes in last read - they might be '\n\r' */ while (p < past_end) { p = memchr(p, '\n', past_end - p); if (!p) break; p++; if (p >= past_end) break; if (*p == '\n' || (*p == '\r' && p+1 < past_end && p[1] == '\n') ) { body_start = p + 1 + (*p == '\r'); *p = '\0'; goto found_end_of_header; } } } /* while (read) */ found_end_of_header: ; log_debug("Request: %s", messagebuf_data); /* Sanitize and analyze header. * Header now is in messagebuf_data, NUL terminated string, * with last empty line deleted (by placement of NUL). * \r\n are not (yet) converted to \n, multi-line headers also * not converted. */ /* First line must be "op<space>[http://host]/path<space>HTTP/n.n". * <space> is exactly one space char. */ if (prefixcmp(messagebuf_data, "DELETE ") == 0) { messagebuf_data += strlen("DELETE "); char *space = strchr(messagebuf_data, ' '); if (!space || prefixcmp(space+1, "HTTP/") != 0) return 400; /* Bad Request */ *space = '\0'; //decode_url(messagebuf_data); %20 => ' ' alarm(0); return delete_path(messagebuf_data); } /* We erroneously used "PUT /" to create new problems. * POST is the correct request in this case: * "PUT /" implies creation or replace of resource named "/"! * Delete PUT in 2014. */ if (prefixcmp(messagebuf_data, "PUT ") != 0 && prefixcmp(messagebuf_data, "POST ") != 0 ) { return 400; /* Bad Request */ } enum { CREATION_NOTIFICATION, CREATION_REQUEST, }; int url_type; char *url = skip_non_whitespace(messagebuf_data) + 1; /* skip "POST " */ if (prefixcmp(url, "/creation_notification ") == 0) url_type = CREATION_NOTIFICATION; else if (prefixcmp(url, "/ ") == 0) url_type = CREATION_REQUEST; else return 400; /* Bad Request */ /* Read body */ if (!body_start) { log_warning("Premature EOF detected, exiting"); return 400; /* Bad Request */ } messagebuf_len -= (body_start - messagebuf_data); memmove(messagebuf_data, body_start, messagebuf_len); log_debug("Body so far: %u bytes, '%s'", messagebuf_len, messagebuf_data); /* Loop until EOF/error/timeout */ while (1) { if (url_type == CREATION_REQUEST) { while (1) { unsigned len = strnlen(messagebuf_data, messagebuf_len); if (len >= messagebuf_len) break; /* messagebuf has at least one NUL - process the line */ process_message(problem_info, messagebuf_data); messagebuf_len -= (len + 1); memmove(messagebuf_data, messagebuf_data + len + 1, messagebuf_len); } } messagebuf_data = xrealloc(messagebuf_data, messagebuf_len + INPUT_BUFFER_SIZE + 1); int rd = read(STDIN_FILENO, messagebuf_data + messagebuf_len, INPUT_BUFFER_SIZE); if (rd < 0) { if (errno == EINTR) /* SIGALRM? */ error_msg_and_die("Timed out"); perror_msg_and_die("read"); } if (rd == 0) break; log_debug("Received %u bytes of data", rd); messagebuf_len += rd; total_bytes_read += rd; if (total_bytes_read > MAX_MESSAGE_SIZE) error_msg_and_die("Message is too long, aborting"); } /* Body received, EOF was seen. Don't let alarm to interrupt after this. */ alarm(0); int ret = 0; if (url_type == CREATION_NOTIFICATION) { if (client_uid != 0) { error_msg("UID=%ld is not authorized to trigger post-create processing", (long)client_uid); ret = 403; /* Forbidden */ goto out; } messagebuf_data[messagebuf_len] = '\0'; return run_post_create(messagebuf_data); } /* Save problem dir */ unsigned pid = convert_pid(problem_info); die_if_data_is_missing(problem_info); char *executable = g_hash_table_lookup(problem_info, FILENAME_EXECUTABLE); if (executable) { char *last_file = concat_path_file(g_settings_dump_location, "last-via-server"); int repeating_crash = check_recent_crash_file(last_file, executable); free(last_file); if (repeating_crash) /* Only pretend that we saved it */ goto out; /* ret is 0: "success" */ } #if 0 //TODO: /* At least it should generate local problem identifier UUID */ problem_data_add_basics(problem_info); //...the problem being that problem_info here is not a problem_data_t! #endif create_problem_dir(problem_info, pid); /* does not return */ out: g_hash_table_destroy(problem_info); return ret; /* Used as HTTP response code */ } static void dummy_handler(int sig_unused) {} int main(int argc, char **argv) { /* I18n */ setlocale(LC_ALL, ""); #if ENABLE_NLS bindtextdomain(PACKAGE, LOCALEDIR); textdomain(PACKAGE); #endif abrt_init(argv); /* Can't keep these strings/structs static: _() doesn't support that */ const char *program_usage_string = _( "& [options]" ); enum { OPT_v = 1 << 0, OPT_u = 1 << 1, OPT_s = 1 << 2, OPT_p = 1 << 3, }; /* Keep enum above and order of options below in sync! */ struct options program_options[] = { OPT__VERBOSE(&g_verbose), OPT_INTEGER('u', NULL, &client_uid, _("Use NUM as client uid")), OPT_BOOL( 's', NULL, NULL , _("Log to syslog")), OPT_BOOL( 'p', NULL, NULL , _("Add program names to log")), OPT_END() }; unsigned opts = parse_opts(argc, argv, program_options, program_usage_string); export_abrt_envvars(opts & OPT_p); msg_prefix = xasprintf("%s[%u]", g_progname, getpid()); if (opts & OPT_s) { logmode = LOGMODE_JOURNAL; } /* Set up timeout handling */ /* Part 1 - need this to make SIGALRM interrupt syscalls * (as opposed to restarting them): I want read syscall to be interrupted */ struct sigaction sa; /* sa.sa_flags.SA_RESTART bit is clear: make signal interrupt syscalls */ memset(&sa, 0, sizeof(sa)); sa.sa_handler = dummy_handler; /* pity, SIG_DFL won't do */ sigaction(SIGALRM, &sa, NULL); /* Part 2 - set the timeout per se */ alarm(TIMEOUT); if (client_uid == (uid_t)-1L) { /* Get uid of the connected client */ struct ucred cr; socklen_t crlen = sizeof(cr); if (0 != getsockopt(STDIN_FILENO, SOL_SOCKET, SO_PEERCRED, &cr, &crlen)) perror_msg_and_die("getsockopt(SO_PEERCRED)"); if (crlen != sizeof(cr)) error_msg_and_die("%s: bad crlen %d", "getsockopt(SO_PEERCRED)", (int)crlen); client_uid = cr.uid; } load_abrt_conf(); int r = perform_http_xact(); if (r == 0) r = 200; free_abrt_conf_data(); printf("HTTP/1.1 %u \r\n\r\n", r); return (r >= 400); /* Error if 400+ */ } #if 0 // TODO: example of SSLed connection #include <openssl/ssl.h> #include <openssl/err.h> if (flags & OPT_SSL) { /* load key and cert files */ SSL_CTX *ctx; SSL *ssl; ctx = init_ssl_context(); if (SSL_CTX_use_certificate_file(ctx, cert_path, SSL_FILETYPE_PEM) <= 0 || SSL_CTX_use_PrivateKey_file(ctx, key_path, SSL_FILETYPE_PEM) <= 0 ) { ERR_print_errors_fp(stderr); error_msg_and_die("SSL certificates err\n"); } if (!SSL_CTX_check_private_key(ctx)) { error_msg_and_die("Private key does not match public key\n"); } (void)SSL_CTX_set_mode(ctx, SSL_MODE_AUTO_RETRY); //TODO more errors? ssl = SSL_new(ctx); SSL_set_fd(ssl, sockfd_in); //SSL_set_accept_state(ssl); if (SSL_accept(ssl) == 1) { //while whatever serve while (serve(ssl, flags)) continue; //TODO errors SSL_shutdown(ssl); } SSL_free(ssl); SSL_CTX_free(ctx); } else { while (serve(&sockfd_in, flags)) continue; } err = (flags & OPT_SSL) ? SSL_read(sock, buffer, READ_BUF-1): read(*(int*)sock, buffer, READ_BUF-1); if ( err < 0 ) { //TODO handle errno || SSL_get_error(ssl,err); break; } if ( err == 0 ) break; if (!head) { buffer[err] = '\0'; clean[i%2] = delete_cr(buffer); cut = g_strstr_len(buffer, -1, "\n\n"); if ( cut == NULL ) { g_string_append(headers, buffer); } else { g_string_append_len(headers, buffer, cut-buffer); } } /* end of header section? */ if ( !head && ( cut != NULL || (clean[(i+1)%2] && buffer[0]=='\n') ) ) { parse_head(&request, headers); head = TRUE; c_len = has_body(&request); if ( c_len ) { //if we want to read body some day - this will be the right place to begin //malloc body append rest of the (fixed) buffer at the beginning of a body //if clean buffer[1]; } else { break; } break; //because we don't support body yet } else if ( head == TRUE ) { /* body-reading stuff * read body, check content-len * save body to request */ break; } else { // count header size len += err; if ( len > READ_BUF-1 ) { //TODO header is too long break; } } i++; } g_string_free(headers, true); //because we allocated it rt = generate_response(&request, &response); /* write headers */ if ( flags & OPT_SSL ) { //TODO err err = SSL_write(sock, response.response_line, strlen(response.response_line)); err = SSL_write(sock, response.head->str , strlen(response.head->str)); err = SSL_write(sock, "\r\n", 2); } else { //TODO err err = write(*(int*)sock, response.response_line, strlen(response.response_line)); err = write(*(int*)sock, response.head->str , strlen(response.head->str)); err = write(*(int*)sock, "\r\n", 2); } #endif
./CrossVul/dataset_final_sorted/CWE-59/c/bad_1506_0
crossvul-cpp_data_bad_1471_1
404: Not Found
./CrossVul/dataset_final_sorted/CWE-59/c/bad_1471_1
crossvul-cpp_data_bad_1505_0
/* Copyright (C) 2010 ABRT team This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "problem_api.h" #include "libabrt.h" /* Maximal length of backtrace. */ #define MAX_BACKTRACE_SIZE (1024*1024) /* Amount of data received from one client for a message before reporting error. */ #define MAX_MESSAGE_SIZE (4*MAX_BACKTRACE_SIZE) /* Maximal number of characters read from socket at once. */ #define INPUT_BUFFER_SIZE (8*1024) /* We exit after this many seconds */ #define TIMEOUT 10 /* Unix socket in ABRT daemon for creating new dump directories. Why to use socket for creating dump dirs? Security. When a Python script throws unexpected exception, ABRT handler catches it, running as a part of that broken Python application. The application is running with certain SELinux privileges, for example it can not execute other programs, or to create files in /var/cache or anything else required to properly fill a problem directory. Adding these privileges to every application would weaken the security. The most suitable solution is for the Python application to open a socket where ABRT daemon is listening, write all relevant data to that socket, and close it. ABRT daemon handles the rest. ** Protocol Initializing new dump: open /var/run/abrt.socket Providing dump data (hook writes to the socket): MANDATORY ITEMS: -> "PID=" number 0 - PID_MAX (/proc/sys/kernel/pid_max) \0 -> "EXECUTABLE=" string \0 -> "BACKTRACE=" string \0 -> "ANALYZER=" string \0 -> "BASENAME=" string (no slashes) \0 -> "REASON=" string \0 You can send more messages using the same KEY=value format. */ static unsigned total_bytes_read = 0; static uid_t client_uid = (uid_t)-1L; /* Remove dump dir */ static int delete_path(const char *dump_dir_name) { /* If doesn't start with "g_settings_dump_location/"... */ if (!dir_is_in_dump_location(dump_dir_name)) { /* Then refuse to operate on it (someone is attacking us??) */ error_msg("Bad problem directory name '%s', should start with: '%s'", dump_dir_name, g_settings_dump_location); return 400; /* Bad Request */ } if (!dir_has_correct_permissions(dump_dir_name)) { error_msg("Problem directory '%s' isn't owned by root:abrt or others are not restricted from access", dump_dir_name); return 400; /* */ } int dir_fd = dd_openfd(dump_dir_name); if (dir_fd < 0) { perror_msg("Can't open problem directory '%s'", dump_dir_name); return 400; } if (!fdump_dir_accessible_by_uid(dir_fd, client_uid)) { close(dir_fd); if (errno == ENOTDIR) { error_msg("Path '%s' isn't problem directory", dump_dir_name); return 404; /* Not Found */ } error_msg("Problem directory '%s' can't be accessed by user with uid %ld", dump_dir_name, (long)client_uid); return 403; /* Forbidden */ } struct dump_dir *dd = dd_fdopendir(dir_fd, dump_dir_name, /*flags:*/ 0); if (dd) { if (dd_delete(dd) != 0) { error_msg("Failed to delete problem directory '%s'", dump_dir_name); dd_close(dd); return 400; } } return 0; /* success */ } static pid_t spawn_event_handler_child(const char *dump_dir_name, const char *event_name, int *fdp) { char *args[7]; args[0] = (char *) LIBEXEC_DIR"/abrt-handle-event"; /* Do not forward ASK_* messages to parent*/ args[1] = (char *) "-i"; args[2] = (char *) "-e"; args[3] = (char *) event_name; args[4] = (char *) "--"; args[5] = (char *) dump_dir_name; args[6] = NULL; int pipeout[2]; int flags = EXECFLG_INPUT_NUL | EXECFLG_OUTPUT | EXECFLG_QUIET | EXECFLG_ERR2OUT; VERB1 flags &= ~EXECFLG_QUIET; char *env_vec[2]; /* Intercept ASK_* messages in Client API -> don't wait for user response */ env_vec[0] = xstrdup("REPORT_CLIENT_NONINTERACTIVE=1"); env_vec[1] = NULL; pid_t child = fork_execv_on_steroids(flags, args, pipeout, env_vec, /*dir:*/ NULL, /*uid(unused):*/ 0); if (fdp) *fdp = pipeout[0]; return child; } static int run_post_create(const char *dirname) { /* If doesn't start with "g_settings_dump_location/"... */ if (!dir_is_in_dump_location(dirname)) { /* Then refuse to operate on it (someone is attacking us??) */ error_msg("Bad problem directory name '%s', should start with: '%s'", dirname, g_settings_dump_location); return 400; /* Bad Request */ } if (!dir_has_correct_permissions(dirname)) { error_msg("Problem directory '%s' isn't owned by root:abrt or others are not restricted from access", dirname); return 400; /* */ } if (g_settings_privatereports) { struct dump_dir *dd = dd_opendir(dirname, DD_OPEN_READONLY); const bool complete = dd && problem_dump_dir_is_complete(dd); dd_close(dd); if (complete) { error_msg("Problem directory '%s' has already been processed", dirname); return 403; } } else if (!dump_dir_accessible_by_uid(dirname, client_uid)) { if (errno == ENOTDIR) { error_msg("Path '%s' isn't problem directory", dirname); return 404; /* Not Found */ } error_msg("Problem directory '%s' can't be accessed by user with uid %ld", dirname, (long)client_uid); return 403; /* Forbidden */ } int child_stdout_fd; int child_pid = spawn_event_handler_child(dirname, "post-create", &child_stdout_fd); char *dup_of_dir = NULL; struct strbuf *cmd_output = strbuf_new(); bool child_is_post_create = 1; /* else it is a notify child */ read_child_output: //log("Reading from event fd %d", child_stdout_fd); /* Read streamed data and split lines */ for (;;) { char buf[250]; /* usually we get one line, no need to have big buf */ errno = 0; int r = safe_read(child_stdout_fd, buf, sizeof(buf) - 1); if (r <= 0) break; buf[r] = '\0'; /* split lines in the current buffer */ char *raw = buf; char *newline; while ((newline = strchr(raw, '\n')) != NULL) { *newline = '\0'; strbuf_append_str(cmd_output, raw); char *msg = cmd_output->buf; /* Hmm, DUP_OF_DIR: ends up in syslog. move log() into 'else'? */ log("%s", msg); if (child_is_post_create && prefixcmp(msg, "DUP_OF_DIR: ") == 0 ) { free(dup_of_dir); dup_of_dir = xstrdup(msg + strlen("DUP_OF_DIR: ")); } strbuf_clear(cmd_output); /* jump to next line */ raw = newline + 1; } /* beginning of next line. the line continues by next read */ strbuf_append_str(cmd_output, raw); } /* EOF/error */ /* Wait for child to actually exit, collect status */ int status = 0; if (safe_waitpid(child_pid, &status, 0) <= 0) /* should not happen */ perror_msg("waitpid(%d)", child_pid); /* If it was a "notify[-dup]" event, then we're done */ if (!child_is_post_create) goto ret; /* exit 0 means "this is a good, non-dup dir" */ /* exit with 1 + "DUP_OF_DIR: dir" string => dup */ if (status != 0) { if (WIFSIGNALED(status)) { log("'post-create' on '%s' killed by signal %d", dirname, WTERMSIG(status)); goto delete_bad_dir; } /* else: it is WIFEXITED(status) */ if (!dup_of_dir) { log("'post-create' on '%s' exited with %d", dirname, WEXITSTATUS(status)); goto delete_bad_dir; } } const char *work_dir = (dup_of_dir ? dup_of_dir : dirname); /* Load problem_data (from the *first dir* if this one is a dup) */ struct dump_dir *dd = dd_opendir(work_dir, /*flags:*/ 0); if (!dd) /* dd_opendir already emitted error msg */ goto delete_bad_dir; /* Update count */ char *count_str = dd_load_text_ext(dd, FILENAME_COUNT, DD_FAIL_QUIETLY_ENOENT); unsigned long count = strtoul(count_str, NULL, 10); /* Don't increase crash count if we are working with newly uploaded * directory (remote crash) which already has its crash count set. */ if ((status != 0 && dup_of_dir) || count == 0) { count++; char new_count_str[sizeof(long)*3 + 2]; sprintf(new_count_str, "%lu", count); dd_save_text(dd, FILENAME_COUNT, new_count_str); /* This condition can be simplified to either * (status * != 0 && * dup_of_dir) or (count == 1). But the * chosen form is much more reliable and safe. We must not call * dd_opendir() to locked dd otherwise we go into a deadlock. */ if (strcmp(dd->dd_dirname, dirname) != 0) { /* Update the last occurrence file by the time file of the new problem */ struct dump_dir *new_dd = dd_opendir(dirname, DD_OPEN_READONLY); char *last_ocr = NULL; if (new_dd) { /* TIME must exists in a valid dump directory but we don't want to die * due to broken duplicated dump directory */ last_ocr = dd_load_text_ext(new_dd, FILENAME_TIME, DD_LOAD_TEXT_RETURN_NULL_ON_FAILURE | DD_FAIL_QUIETLY_ENOENT); dd_close(new_dd); } else { /* dd_opendir() already produced a message with good information about failure */ error_msg("Can't read the last occurrence file from the new dump directory."); } if (!last_ocr) { /* the new dump directory may lie in the dump location for some time */ log("Using current time for the last occurrence file which may be incorrect."); time_t t = time(NULL); last_ocr = xasprintf("%lu", (long)t); } dd_save_text(dd, FILENAME_LAST_OCCURRENCE, last_ocr); free(last_ocr); } } /* Reset mode/uig/gid to correct values for all files created by event run */ dd_sanitize_mode_and_owner(dd); dd_close(dd); if (!dup_of_dir) log_notice("New problem directory %s, processing", work_dir); else { log_warning("Deleting problem directory %s (dup of %s)", strrchr(dirname, '/') + 1, strrchr(dup_of_dir, '/') + 1); delete_dump_dir(dirname); } /* Run "notify[-dup]" event */ int fd; child_pid = spawn_event_handler_child( work_dir, (dup_of_dir ? "notify-dup" : "notify"), &fd ); //log("Started notify, fd %d -> %d", fd, child_stdout_fd); xmove_fd(fd, child_stdout_fd); child_is_post_create = 0; strbuf_clear(cmd_output); free(dup_of_dir); dup_of_dir = NULL; goto read_child_output; delete_bad_dir: log_warning("Deleting problem directory '%s'", dirname); delete_dump_dir(dirname); ret: strbuf_free(cmd_output); free(dup_of_dir); close(child_stdout_fd); return 0; } /* Create a new problem directory from client session. * Caller must ensure that all fields in struct client * are properly filled. */ static int create_problem_dir(GHashTable *problem_info, unsigned pid) { /* Exit if free space is less than 1/4 of MaxCrashReportsSize */ if (g_settings_nMaxCrashReportsSize > 0) { if (low_free_space(g_settings_nMaxCrashReportsSize, g_settings_dump_location)) exit(1); } /* Create temp directory with the problem data. * This directory is renamed to final directory name after * all files have been stored into it. */ gchar *dir_basename = g_hash_table_lookup(problem_info, "basename"); if (!dir_basename) dir_basename = g_hash_table_lookup(problem_info, FILENAME_TYPE); char *path = xasprintf("%s/%s-%s-%u.new", g_settings_dump_location, dir_basename, iso_date_string(NULL), pid); /* This item is useless, don't save it */ g_hash_table_remove(problem_info, "basename"); /* No need to check the path length, as all variables used are limited, * and dd_create() fails if the path is too long. */ struct dump_dir *dd = dd_create(path, g_settings_privatereports ? 0 : client_uid, DEFAULT_DUMP_DIR_MODE); if (!dd) { error_msg_and_die("Error creating problem directory '%s'", path); } dd_create_basic_files(dd, client_uid, NULL); dd_save_text(dd, FILENAME_ABRT_VERSION, VERSION); gpointer gpkey = g_hash_table_lookup(problem_info, FILENAME_CMDLINE); if (!gpkey) { /* Obtain and save the command line. */ char *cmdline = get_cmdline(pid); if (cmdline) { dd_save_text(dd, FILENAME_CMDLINE, cmdline); free(cmdline); } } /* Store id of the user whose application crashed. */ char uid_str[sizeof(long) * 3 + 2]; sprintf(uid_str, "%lu", (long)client_uid); dd_save_text(dd, FILENAME_UID, uid_str); GHashTableIter iter; gpointer gpvalue; g_hash_table_iter_init(&iter, problem_info); while (g_hash_table_iter_next(&iter, &gpkey, &gpvalue)) { dd_save_text(dd, (gchar *) gpkey, (gchar *) gpvalue); } dd_close(dd); /* Not needing it anymore */ g_hash_table_destroy(problem_info); /* Move the completely created problem directory * to final directory. */ char *newpath = xstrndup(path, strlen(path) - strlen(".new")); if (rename(path, newpath) == 0) strcpy(path, newpath); free(newpath); log_notice("Saved problem directory of pid %u to '%s'", pid, path); /* We let the peer know that problem dir was created successfully * _before_ we run potentially long-running post-create. */ printf("HTTP/1.1 201 Created\r\n\r\n"); fflush(NULL); close(STDOUT_FILENO); xdup2(STDERR_FILENO, STDOUT_FILENO); /* paranoia: don't leave stdout fd closed */ /* Trim old problem directories if necessary */ if (g_settings_nMaxCrashReportsSize > 0) { trim_problem_dirs(g_settings_dump_location, g_settings_nMaxCrashReportsSize * (double)(1024*1024), path); } run_post_create(path); /* free(path); */ exit(0); } static gboolean key_value_ok(gchar *key, gchar *value) { char *i; /* check key, it has to be valid filename and will end up in the * bugzilla */ for (i = key; *i != 0; i++) { if (!isalpha(*i) && (*i != '-') && (*i != '_') && (*i != ' ')) return FALSE; } /* check value of 'basename', it has to be valid non-hidden directory * name */ if (strcmp(key, "basename") == 0 || strcmp(key, FILENAME_TYPE) == 0 ) { if (!str_is_correct_filename(value)) { error_msg("Value of '%s' ('%s') is not a valid directory name", key, value); return FALSE; } } return TRUE; } /* Handles a message received from client over socket. */ static void process_message(GHashTable *problem_info, char *message) { gchar *key, *value; value = strchr(message, '='); if (value) { key = g_ascii_strdown(message, value - message); /* result is malloced */ //TODO: is it ok? it uses g_malloc, not malloc! value++; if (key_value_ok(key, value)) { if (strcmp(key, FILENAME_UID) == 0) { error_msg("Ignoring value of %s, will be determined later", FILENAME_UID); } else { g_hash_table_insert(problem_info, key, xstrdup(value)); /* Compat, delete when FILENAME_ANALYZER is replaced by FILENAME_TYPE: */ if (strcmp(key, FILENAME_TYPE) == 0) g_hash_table_insert(problem_info, xstrdup(FILENAME_ANALYZER), xstrdup(value)); /* Prevent freeing key later: */ key = NULL; } } else { /* should use error_msg_and_die() here? */ error_msg("Invalid key or value format: %s", message); } free(key); } else { /* should use error_msg_and_die() here? */ error_msg("Invalid message format: '%s'", message); } } static void die_if_data_is_missing(GHashTable *problem_info) { gboolean missing_data = FALSE; gchar **pstring; static const gchar *const needed[] = { FILENAME_TYPE, FILENAME_REASON, /* FILENAME_BACKTRACE, - ECC errors have no such elements */ /* FILENAME_EXECUTABLE, */ NULL }; for (pstring = (gchar**) needed; *pstring; pstring++) { if (!g_hash_table_lookup(problem_info, *pstring)) { error_msg("Element '%s' is missing", *pstring); missing_data = TRUE; } } if (missing_data) error_msg_and_die("Some data is missing, aborting"); } /* * Takes hash table, looks for key FILENAME_PID and tries to convert its value * to int. */ unsigned convert_pid(GHashTable *problem_info) { long ret; gchar *pid_str = (gchar *) g_hash_table_lookup(problem_info, FILENAME_PID); char *err_pos; if (!pid_str) error_msg_and_die("PID data is missing, aborting"); errno = 0; ret = strtol(pid_str, &err_pos, 10); if (errno || pid_str == err_pos || *err_pos != '\0' || ret > UINT_MAX || ret < 1) error_msg_and_die("Malformed or out-of-range PID number: '%s'", pid_str); return (unsigned) ret; } static int perform_http_xact(void) { /* use free instead of g_free so that we can use xstr* functions from * libreport/lib/xfuncs.c */ GHashTable *problem_info = g_hash_table_new_full(g_str_hash, g_str_equal, free, free); /* Read header */ char *body_start = NULL; char *messagebuf_data = NULL; unsigned messagebuf_len = 0; /* Loop until EOF/error/timeout/end_of_header */ while (1) { messagebuf_data = xrealloc(messagebuf_data, messagebuf_len + INPUT_BUFFER_SIZE); char *p = messagebuf_data + messagebuf_len; int rd = read(STDIN_FILENO, p, INPUT_BUFFER_SIZE); if (rd < 0) { if (errno == EINTR) /* SIGALRM? */ error_msg_and_die("Timed out"); perror_msg_and_die("read"); } if (rd == 0) break; log_debug("Received %u bytes of data", rd); messagebuf_len += rd; total_bytes_read += rd; if (total_bytes_read > MAX_MESSAGE_SIZE) error_msg_and_die("Message is too long, aborting"); /* Check whether we see end of header */ /* Note: we support both [\r]\n\r\n and \n\n */ char *past_end = messagebuf_data + messagebuf_len; if (p > messagebuf_data+1) p -= 2; /* start search from two last bytes in last read - they might be '\n\r' */ while (p < past_end) { p = memchr(p, '\n', past_end - p); if (!p) break; p++; if (p >= past_end) break; if (*p == '\n' || (*p == '\r' && p+1 < past_end && p[1] == '\n') ) { body_start = p + 1 + (*p == '\r'); *p = '\0'; goto found_end_of_header; } } } /* while (read) */ found_end_of_header: ; log_debug("Request: %s", messagebuf_data); /* Sanitize and analyze header. * Header now is in messagebuf_data, NUL terminated string, * with last empty line deleted (by placement of NUL). * \r\n are not (yet) converted to \n, multi-line headers also * not converted. */ /* First line must be "op<space>[http://host]/path<space>HTTP/n.n". * <space> is exactly one space char. */ if (prefixcmp(messagebuf_data, "DELETE ") == 0) { messagebuf_data += strlen("DELETE "); char *space = strchr(messagebuf_data, ' '); if (!space || prefixcmp(space+1, "HTTP/") != 0) return 400; /* Bad Request */ *space = '\0'; //decode_url(messagebuf_data); %20 => ' ' alarm(0); return delete_path(messagebuf_data); } /* We erroneously used "PUT /" to create new problems. * POST is the correct request in this case: * "PUT /" implies creation or replace of resource named "/"! * Delete PUT in 2014. */ if (prefixcmp(messagebuf_data, "PUT ") != 0 && prefixcmp(messagebuf_data, "POST ") != 0 ) { return 400; /* Bad Request */ } enum { CREATION_NOTIFICATION, CREATION_REQUEST, }; int url_type; char *url = skip_non_whitespace(messagebuf_data) + 1; /* skip "POST " */ if (prefixcmp(url, "/creation_notification ") == 0) url_type = CREATION_NOTIFICATION; else if (prefixcmp(url, "/ ") == 0) url_type = CREATION_REQUEST; else return 400; /* Bad Request */ /* Read body */ if (!body_start) { log_warning("Premature EOF detected, exiting"); return 400; /* Bad Request */ } messagebuf_len -= (body_start - messagebuf_data); memmove(messagebuf_data, body_start, messagebuf_len); log_debug("Body so far: %u bytes, '%s'", messagebuf_len, messagebuf_data); /* Loop until EOF/error/timeout */ while (1) { if (url_type == CREATION_REQUEST) { while (1) { unsigned len = strnlen(messagebuf_data, messagebuf_len); if (len >= messagebuf_len) break; /* messagebuf has at least one NUL - process the line */ process_message(problem_info, messagebuf_data); messagebuf_len -= (len + 1); memmove(messagebuf_data, messagebuf_data + len + 1, messagebuf_len); } } messagebuf_data = xrealloc(messagebuf_data, messagebuf_len + INPUT_BUFFER_SIZE + 1); int rd = read(STDIN_FILENO, messagebuf_data + messagebuf_len, INPUT_BUFFER_SIZE); if (rd < 0) { if (errno == EINTR) /* SIGALRM? */ error_msg_and_die("Timed out"); perror_msg_and_die("read"); } if (rd == 0) break; log_debug("Received %u bytes of data", rd); messagebuf_len += rd; total_bytes_read += rd; if (total_bytes_read > MAX_MESSAGE_SIZE) error_msg_and_die("Message is too long, aborting"); } /* Body received, EOF was seen. Don't let alarm to interrupt after this. */ alarm(0); if (url_type == CREATION_NOTIFICATION) { messagebuf_data[messagebuf_len] = '\0'; return run_post_create(messagebuf_data); } /* Save problem dir */ int ret = 0; unsigned pid = convert_pid(problem_info); die_if_data_is_missing(problem_info); char *executable = g_hash_table_lookup(problem_info, FILENAME_EXECUTABLE); if (executable) { char *last_file = concat_path_file(g_settings_dump_location, "last-via-server"); int repeating_crash = check_recent_crash_file(last_file, executable); free(last_file); if (repeating_crash) /* Only pretend that we saved it */ goto out; /* ret is 0: "success" */ } #if 0 //TODO: /* At least it should generate local problem identifier UUID */ problem_data_add_basics(problem_info); //...the problem being that problem_info here is not a problem_data_t! #endif create_problem_dir(problem_info, pid); /* does not return */ out: g_hash_table_destroy(problem_info); return ret; /* Used as HTTP response code */ } static void dummy_handler(int sig_unused) {} int main(int argc, char **argv) { /* I18n */ setlocale(LC_ALL, ""); #if ENABLE_NLS bindtextdomain(PACKAGE, LOCALEDIR); textdomain(PACKAGE); #endif abrt_init(argv); /* Can't keep these strings/structs static: _() doesn't support that */ const char *program_usage_string = _( "& [options]" ); enum { OPT_v = 1 << 0, OPT_u = 1 << 1, OPT_s = 1 << 2, OPT_p = 1 << 3, }; /* Keep enum above and order of options below in sync! */ struct options program_options[] = { OPT__VERBOSE(&g_verbose), OPT_INTEGER('u', NULL, &client_uid, _("Use NUM as client uid")), OPT_BOOL( 's', NULL, NULL , _("Log to syslog")), OPT_BOOL( 'p', NULL, NULL , _("Add program names to log")), OPT_END() }; unsigned opts = parse_opts(argc, argv, program_options, program_usage_string); export_abrt_envvars(opts & OPT_p); msg_prefix = xasprintf("%s[%u]", g_progname, getpid()); if (opts & OPT_s) { logmode = LOGMODE_JOURNAL; } /* Set up timeout handling */ /* Part 1 - need this to make SIGALRM interrupt syscalls * (as opposed to restarting them): I want read syscall to be interrupted */ struct sigaction sa; /* sa.sa_flags.SA_RESTART bit is clear: make signal interrupt syscalls */ memset(&sa, 0, sizeof(sa)); sa.sa_handler = dummy_handler; /* pity, SIG_DFL won't do */ sigaction(SIGALRM, &sa, NULL); /* Part 2 - set the timeout per se */ alarm(TIMEOUT); if (client_uid == (uid_t)-1L) { /* Get uid of the connected client */ struct ucred cr; socklen_t crlen = sizeof(cr); if (0 != getsockopt(STDIN_FILENO, SOL_SOCKET, SO_PEERCRED, &cr, &crlen)) perror_msg_and_die("getsockopt(SO_PEERCRED)"); if (crlen != sizeof(cr)) error_msg_and_die("%s: bad crlen %d", "getsockopt(SO_PEERCRED)", (int)crlen); client_uid = cr.uid; } load_abrt_conf(); int r = perform_http_xact(); if (r == 0) r = 200; free_abrt_conf_data(); printf("HTTP/1.1 %u \r\n\r\n", r); return (r >= 400); /* Error if 400+ */ } #if 0 // TODO: example of SSLed connection #include <openssl/ssl.h> #include <openssl/err.h> if (flags & OPT_SSL) { /* load key and cert files */ SSL_CTX *ctx; SSL *ssl; ctx = init_ssl_context(); if (SSL_CTX_use_certificate_file(ctx, cert_path, SSL_FILETYPE_PEM) <= 0 || SSL_CTX_use_PrivateKey_file(ctx, key_path, SSL_FILETYPE_PEM) <= 0 ) { ERR_print_errors_fp(stderr); error_msg_and_die("SSL certificates err\n"); } if (!SSL_CTX_check_private_key(ctx)) { error_msg_and_die("Private key does not match public key\n"); } (void)SSL_CTX_set_mode(ctx, SSL_MODE_AUTO_RETRY); //TODO more errors? ssl = SSL_new(ctx); SSL_set_fd(ssl, sockfd_in); //SSL_set_accept_state(ssl); if (SSL_accept(ssl) == 1) { //while whatever serve while (serve(ssl, flags)) continue; //TODO errors SSL_shutdown(ssl); } SSL_free(ssl); SSL_CTX_free(ctx); } else { while (serve(&sockfd_in, flags)) continue; } err = (flags & OPT_SSL) ? SSL_read(sock, buffer, READ_BUF-1): read(*(int*)sock, buffer, READ_BUF-1); if ( err < 0 ) { //TODO handle errno || SSL_get_error(ssl,err); break; } if ( err == 0 ) break; if (!head) { buffer[err] = '\0'; clean[i%2] = delete_cr(buffer); cut = g_strstr_len(buffer, -1, "\n\n"); if ( cut == NULL ) { g_string_append(headers, buffer); } else { g_string_append_len(headers, buffer, cut-buffer); } } /* end of header section? */ if ( !head && ( cut != NULL || (clean[(i+1)%2] && buffer[0]=='\n') ) ) { parse_head(&request, headers); head = TRUE; c_len = has_body(&request); if ( c_len ) { //if we want to read body some day - this will be the right place to begin //malloc body append rest of the (fixed) buffer at the beginning of a body //if clean buffer[1]; } else { break; } break; //because we don't support body yet } else if ( head == TRUE ) { /* body-reading stuff * read body, check content-len * save body to request */ break; } else { // count header size len += err; if ( len > READ_BUF-1 ) { //TODO header is too long break; } } i++; } g_string_free(headers, true); //because we allocated it rt = generate_response(&request, &response); /* write headers */ if ( flags & OPT_SSL ) { //TODO err err = SSL_write(sock, response.response_line, strlen(response.response_line)); err = SSL_write(sock, response.head->str , strlen(response.head->str)); err = SSL_write(sock, "\r\n", 2); } else { //TODO err err = write(*(int*)sock, response.response_line, strlen(response.response_line)); err = write(*(int*)sock, response.head->str , strlen(response.head->str)); err = write(*(int*)sock, "\r\n", 2); } #endif
./CrossVul/dataset_final_sorted/CWE-59/c/bad_1505_0
crossvul-cpp_data_bad_436_11
/* * Soft: Keepalived is a failover program for the LVS project * <www.linuxvirtualserver.org>. It monitor & manipulate * a loadbalanced server pool using multi-layer checks. * * Part: Configuration file parser/reader. Place into the dynamic * data structure representation the conf file representing * the loadbalanced server pool. * * Author: Alexandre Cassen, <acassen@linux-vs.org> * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. * * Copyright (C) 2001-2017 Alexandre Cassen, <acassen@gmail.com> */ #include "config.h" #include <glob.h> #include <unistd.h> #include <libgen.h> #include <errno.h> #include <sys/stat.h> #include <sys/types.h> #include <fcntl.h> #include <stdlib.h> #include <ctype.h> #include <stdbool.h> #include <linux/version.h> #include <pwd.h> #include <string.h> #include <stdio.h> #include <stdarg.h> #include <math.h> #include <inttypes.h> #include "parser.h" #include "memory.h" #include "logger.h" #include "rttables.h" #include "scheduler.h" #include "notify.h" #include "list.h" #include "bitops.h" #include "utils.h" /* #define PARSER_DEBUG */ #define DUMP_KEYWORDS 0 #define DEF_LINE_END "\n" #define BOB "{" #define EOB "}" #define WHITE_SPACE_STR " \t\f\n\r\v" typedef struct _defs { char *name; size_t name_len; char *value; size_t value_len; bool multiline; char *(*fn)(void); } def_t; /* global vars */ vector_t *keywords; char *config_id; const char *WHITE_SPACE = WHITE_SPACE_STR; /* local vars */ static vector_t *current_keywords; static FILE *current_stream; static const char *current_file_name; static size_t current_file_line_no; static int sublevel = 0; static int skip_sublevel = 0; static list multiline_stack; static char *buf_extern; static config_err_t config_err = CONFIG_OK; /* Highest level of config error for --config-test */ /* Parameter definitions */ static list defs; /* Forward declarations for recursion */ static bool read_line(char *, size_t); void report_config_error(config_err_t err, const char *format, ...) { va_list args; char *format_buf = NULL; /* current_file_name will be set if there is more than one config file, in which * case we need to specify the file name. */ if (current_file_name) { /* "(file_name:line_no) format" + '\0' */ format_buf = MALLOC(1 + strlen(current_file_name) + 1 + 10 + 1 + 1 + strlen(format) + 1); sprintf(format_buf, "(%s:%zd) %s", current_file_name, current_file_line_no, format); } else if (current_file_line_no) { /* Set while reading from config files */ /* "(Line line_no) format" + '\0' */ format_buf = MALLOC(1 + 5 + 10 + 1 + 1 + strlen(format) + 1); sprintf(format_buf, "(%s %zd) %s", "Line", current_file_line_no, format); } va_start(args, format); if (__test_bit(CONFIG_TEST_BIT, &debug)) { vfprintf(stderr, format_buf ? format_buf : format, args); fputc('\n', stderr); if (config_err == CONFIG_OK || config_err < err) config_err = err; } else vlog_message(LOG_INFO, format_buf ? format_buf : format, args); va_end(args); if (format_buf) FREE(format_buf); } config_err_t get_config_status(void) { return config_err; } static char * null_strvec(const vector_t *strvec, size_t index) { if (index - 1 < vector_size(strvec) && index > 0 && vector_slot(strvec, index - 1)) report_config_error(CONFIG_MISSING_PARAMETER, "*** Configuration line starting `%s` is missing a parameter after keyword `%s` at word position %zu", vector_slot(strvec, 0) ? (char *)vector_slot(strvec, 0) : "***MISSING ***", (char *)vector_slot(strvec, index - 1), index + 1); else report_config_error(CONFIG_MISSING_PARAMETER, "*** Configuration line starting `%s` is missing a parameter at word position %zu", vector_slot(strvec, 0) ? (char *)vector_slot(strvec, 0) : "***MISSING ***", index + 1); exit(KEEPALIVED_EXIT_CONFIG); return NULL; } static bool read_int_func(const char *number, int base, int *res, int min_val, int max_val, __attribute__((unused)) bool ignore_error) { long val; char *endptr; char *warn = ""; #ifndef _STRICT_CONFIG_ if (ignore_error && !__test_bit(CONFIG_TEST_BIT, &debug)) warn = "WARNING - "; #endif errno = 0; val = strtol(number, &endptr, base); *res = (int)val; if (*endptr) report_config_error(CONFIG_INVALID_NUMBER, "%sinvalid number '%s'", warn, number); else if (errno == ERANGE || val < INT_MIN || val > INT_MAX) report_config_error(CONFIG_INVALID_NUMBER, "%snumber '%s' outside integer range", warn, number); else if (val < min_val || val > max_val) report_config_error(CONFIG_INVALID_NUMBER, "number '%s' outside range [%d, %d]", number, min_val, max_val); else return true; #ifdef _STRICT_CONFIG_ return false; #else return ignore_error && val >= min_val && val <= max_val && !__test_bit(CONFIG_TEST_BIT, &debug); #endif } static bool read_unsigned_func(const char *number, int base, unsigned *res, unsigned min_val, unsigned max_val, __attribute__((unused)) bool ignore_error) { unsigned long val; char *endptr; char *warn = ""; size_t offset; #ifndef _STRICT_CONFIG_ if (ignore_error && !__test_bit(CONFIG_TEST_BIT, &debug)) warn = "WARNING - "; #endif /* In case the string starts with spaces (even in the configuration this * can be achieved by enclosing the number in quotes - e.g. weight " -100") * skip any leading whitespace */ offset = strspn(number, WHITE_SPACE); errno = 0; val = strtoul(number + offset, &endptr, base); *res = (unsigned)val; if (number[offset] == '-') report_config_error(CONFIG_INVALID_NUMBER, "%snegative number '%s'", warn, number); else if (*endptr) report_config_error(CONFIG_INVALID_NUMBER, "%sinvalid number '%s'", warn, number); else if (errno == ERANGE || val > UINT_MAX) report_config_error(CONFIG_INVALID_NUMBER, "%snumber '%s' outside unsigned integer range", warn, number); else if (val < min_val || val > max_val) report_config_error(CONFIG_INVALID_NUMBER, "number '%s' outside range [%u, %u]", number, min_val, max_val); else return true; #ifdef _STRICT_CONFIG_ return false; #else return ignore_error && val >= min_val && val <= max_val && !__test_bit(CONFIG_TEST_BIT, &debug); #endif } static bool read_unsigned64_func(const char *number, int base, uint64_t *res, uint64_t min_val, uint64_t max_val, __attribute__((unused)) bool ignore_error) { unsigned long long val; char *endptr; char *warn = ""; size_t offset; #ifndef _STRICT_CONFIG_ if (ignore_error && !__test_bit(CONFIG_TEST_BIT, &debug)) warn = "WARNING - "; #endif /* In case the string starts with spaces (even in the configuration this * can be achieved by enclosing the number in quotes - e.g. weight " -100") * skip any leading whitespace */ offset = strspn(number, WHITE_SPACE); errno = 0; val = strtoull(number + offset, &endptr, base); *res = (unsigned)val; if (number[offset] == '-') report_config_error(CONFIG_INVALID_NUMBER, "%snegative number '%s'", warn, number); else if (*endptr) report_config_error(CONFIG_INVALID_NUMBER, "%sinvalid number '%s'", warn, number); else if (errno == ERANGE) report_config_error(CONFIG_INVALID_NUMBER, "%snumber '%s' outside unsigned 64 bit range", warn, number); else if (val < min_val || val > max_val) report_config_error(CONFIG_INVALID_NUMBER, "number '%s' outside range [%" PRIu64 ", %" PRIu64 "]", number, min_val, max_val); else return true; #ifdef _STRICT_CONFIG_ return false; #else return ignore_error && val >= min_val && val <= max_val && !__test_bit(CONFIG_TEST_BIT, &debug); #endif } static bool read_double_func(const char *number, double *res, double min_val, double max_val, __attribute__((unused)) bool ignore_error) { double val; char *endptr; char *warn = ""; #ifndef _STRICT_CONFIG_ if (ignore_error && !__test_bit(CONFIG_TEST_BIT, &debug)) warn = "WARNING - "; #endif errno = 0; val = strtod(number, &endptr); *res = val; if (*endptr) report_config_error(CONFIG_INVALID_NUMBER, "%sinvalid number '%s'", warn, number); else if (errno == ERANGE) report_config_error(CONFIG_INVALID_NUMBER, "%snumber '%s' out of range", warn, number); else if (val == -HUGE_VAL || val == HUGE_VAL) /* +/- Inf */ report_config_error(CONFIG_INVALID_NUMBER, "infinite number '%s'", number); else if (!(val <= 0 || val >= 0)) /* NaN */ report_config_error(CONFIG_INVALID_NUMBER, "not a number '%s'", number); else if (val < min_val || val > max_val) report_config_error(CONFIG_INVALID_NUMBER, "number '%s' outside range [%g, %g]", number, min_val, max_val); else return true; #ifdef _STRICT_CONFIG_ return false; #else return ignore_error && val >= min_val && val <= max_val && !__test_bit(CONFIG_TEST_BIT, &debug); #endif } bool read_int(const char *str, int *res, int min_val, int max_val, bool ignore_error) { return read_int_func(str, 10, res, min_val, max_val, ignore_error); } bool read_unsigned(const char *str, unsigned *res, unsigned min_val, unsigned max_val, bool ignore_error) { return read_unsigned_func(str, 10, res, min_val, max_val, ignore_error); } bool read_unsigned64(const char *str, uint64_t *res, uint64_t min_val, uint64_t max_val, bool ignore_error) { return read_unsigned64_func(str, 10, res, min_val, max_val, ignore_error); } bool read_double(const char *str, double *res, double min_val, double max_val, bool ignore_error) { return read_double_func(str, res, min_val, max_val, ignore_error); } bool read_int_strvec(const vector_t *strvec, size_t index, int *res, int min_val, int max_val, bool ignore_error) { return read_int_func(strvec_slot(strvec, index), 10, res, min_val, max_val, ignore_error); } bool read_unsigned_strvec(const vector_t *strvec, size_t index, unsigned *res, unsigned min_val, unsigned max_val, bool ignore_error) { return read_unsigned_func(strvec_slot(strvec, index), 10, res, min_val, max_val, ignore_error); } bool read_unsigned64_strvec(const vector_t *strvec, size_t index, uint64_t *res, uint64_t min_val, uint64_t max_val, bool ignore_error) { return read_unsigned64_func(strvec_slot(strvec, index), 10, res, min_val, max_val, ignore_error); } bool read_double_strvec(const vector_t *strvec, size_t index, double *res, double min_val, double max_val, bool ignore_error) { return read_double_func(strvec_slot(strvec, index), res, min_val, max_val, ignore_error); } bool read_unsigned_base_strvec(const vector_t *strvec, size_t index, int base, unsigned *res, unsigned min_val, unsigned max_val, bool ignore_error) { return read_unsigned_func(strvec_slot(strvec, index), base, res, min_val, max_val, ignore_error); } static void keyword_alloc(vector_t *keywords_vec, const char *string, void (*handler) (vector_t *), bool active) { keyword_t *keyword; vector_alloc_slot(keywords_vec); keyword = (keyword_t *) MALLOC(sizeof(keyword_t)); keyword->string = string; keyword->handler = handler; keyword->active = active; vector_set_slot(keywords_vec, keyword); } static void keyword_alloc_sub(vector_t *keywords_vec, const char *string, void (*handler) (vector_t *)) { int i = 0; keyword_t *keyword; /* fetch last keyword */ keyword = vector_slot(keywords_vec, vector_size(keywords_vec) - 1); /* Don't install subordinate keywords if configuration block inactive */ if (!keyword->active) return; /* position to last sub level */ for (i = 0; i < sublevel; i++) keyword = vector_slot(keyword->sub, vector_size(keyword->sub) - 1); /* First sub level allocation */ if (!keyword->sub) keyword->sub = vector_alloc(); /* add new sub keyword */ keyword_alloc(keyword->sub, string, handler, true); } /* Exported helpers */ void install_sublevel(void) { sublevel++; } void install_sublevel_end(void) { sublevel--; } void install_keyword_root(const char *string, void (*handler) (vector_t *), bool active) { /* If the root keyword is inactive, the handler will still be called, * but with a NULL strvec */ keyword_alloc(keywords, string, handler, active); } void install_root_end_handler(void (*handler) (void)) { keyword_t *keyword; /* fetch last keyword */ keyword = vector_slot(keywords, vector_size(keywords) - 1); if (!keyword->active) return; keyword->sub_close_handler = handler; } void install_keyword(const char *string, void (*handler) (vector_t *)) { keyword_alloc_sub(keywords, string, handler); } void install_sublevel_end_handler(void (*handler) (void)) { int i = 0; keyword_t *keyword; /* fetch last keyword */ keyword = vector_slot(keywords, vector_size(keywords) - 1); if (!keyword->active) return; /* position to last sub level */ for (i = 0; i < sublevel; i++) keyword = vector_slot(keyword->sub, vector_size(keyword->sub) - 1); keyword->sub_close_handler = handler; } #if DUMP_KEYWORDS static void dump_keywords(vector_t *keydump, int level, FILE *fp) { unsigned int i; keyword_t *keyword_vec; char file_name[21]; if (!level) { snprintf(file_name, sizeof(file_name), "/tmp/keywords.%d", getpid()); fp = fopen(file_name, "w"); if (!fp) return; } for (i = 0; i < vector_size(keydump); i++) { keyword_vec = vector_slot(keydump, i); fprintf(fp, "%*sKeyword : %s (%s)\n", level * 2, "", keyword_vec->string, keyword_vec->active ? "active": "disabled"); if (keyword_vec->sub) dump_keywords(keyword_vec->sub, level + 1, fp); } if (!level) fclose(fp); } #endif static void free_keywords(vector_t *keywords_vec) { keyword_t *keyword_vec; unsigned int i; for (i = 0; i < vector_size(keywords_vec); i++) { keyword_vec = vector_slot(keywords_vec, i); if (keyword_vec->sub) free_keywords(keyword_vec->sub); FREE(keyword_vec); } vector_free(keywords_vec); } /* Functions used for standard definitions */ static char * get_cwd(void) { char *dir = MALLOC(PATH_MAX); /* Since keepalived doesn't do a chroot(), we don't need to be concerned * about (unreachable) - see getcwd(3) man page. */ return getcwd(dir, PATH_MAX); } static char * get_instance(void) { char *conf_id = MALLOC(strlen(config_id) + 1); strcpy(conf_id, config_id); return conf_id; } vector_t * alloc_strvec_quoted_escaped(char *src) { char *token; vector_t *strvec; char cur_quote = 0; char *ofs_op; char *op_buf; char *ofs, *ofs1; char op_char; if (!src) { if (!buf_extern) return NULL; src = buf_extern; } /* Create a vector and alloc each command piece */ strvec = vector_alloc(); op_buf = MALLOC(MAXBUF); ofs = src; while (*ofs) { /* Find the next 'word' */ ofs += strspn(ofs, WHITE_SPACE); if (!*ofs) break; ofs_op = op_buf; while (*ofs) { ofs1 = strpbrk(ofs, cur_quote == '"' ? "\"\\" : cur_quote == '\'' ? "'\\" : WHITE_SPACE_STR "'\"\\"); if (!ofs1) { size_t len; if (cur_quote) { report_config_error(CONFIG_UNMATCHED_QUOTE, "String '%s': missing terminating %c", src, cur_quote); goto err_exit; } strcpy(ofs_op, ofs); len = strlen(ofs); ofs += len; ofs_op += len; break; } /* Save the wanted text */ strncpy(ofs_op, ofs, ofs1 - ofs); ofs_op += ofs1 - ofs; ofs = ofs1; if (*ofs == '\\') { /* It is a '\' */ ofs++; if (!*ofs) { log_message(LOG_INFO, "Missing escape char at end: '%s'", src); goto err_exit; } if (*ofs == 'x' && isxdigit(ofs[1])) { op_char = 0; ofs++; while (isxdigit(*ofs)) { op_char <<= 4; op_char |= isdigit(*ofs) ? *ofs - '0' : (10 + *ofs - (isupper(*ofs) ? 'A' : 'a')); ofs++; } } else if (*ofs == 'c' && ofs[1]) { op_char = *++ofs & 0x1f; /* Convert to control character */ ofs++; } else if (*ofs >= '0' && *ofs <= '7') { op_char = *ofs++ - '0'; if (*ofs >= '0' && *ofs <= '7') { op_char <<= 3; op_char += *ofs++ - '0'; } if (*ofs >= '0' && *ofs <= '7') { op_char <<= 3; op_char += *ofs++ - '0'; } } else { switch (*ofs) { case 'a': op_char = '\a'; break; case 'b': op_char = '\b'; break; case 'E': op_char = 0x1b; break; case 'f': op_char = '\f'; break; case 'n': op_char = '\n'; break; case 'r': op_char = '\r'; break; case 't': op_char = '\t'; break; case 'v': op_char = '\v'; break; default: /* \"' */ op_char = *ofs; break; } ofs++; } *ofs_op++ = op_char; continue; } if (cur_quote) { /* It's the close quote */ ofs++; cur_quote = 0; continue; } if (*ofs == '"' || *ofs == '\'') { cur_quote = *ofs++; continue; } break; } token = MALLOC(ofs_op - op_buf + 1); memcpy(token, op_buf, ofs_op - op_buf); token[ofs_op - op_buf] = '\0'; /* Alloc & set the slot */ vector_alloc_slot(strvec); vector_set_slot(strvec, token); } FREE(op_buf); if (!vector_size(strvec)) { free_strvec(strvec); return NULL; } return strvec; err_exit: free_strvec(strvec); FREE(op_buf); return NULL; } vector_t * alloc_strvec_r(char *string) { char *cp, *start, *token; size_t str_len; vector_t *strvec; if (!string) return NULL; /* Create a vector and alloc each command piece */ strvec = vector_alloc(); cp = string; while (true) { cp += strspn(cp, WHITE_SPACE); if (!*cp) break; start = cp; /* Save a quoted string without the ""s as a single string */ if (*start == '"') { start++; if (!(cp = strchr(start, '"'))) { report_config_error(CONFIG_UNMATCHED_QUOTE, "Unmatched quote: '%s'", string); break; } str_len = (size_t)(cp - start); cp++; } else { cp += strcspn(start, WHITE_SPACE_STR "\""); str_len = (size_t)(cp - start); } token = MALLOC(str_len + 1); memcpy(token, start, str_len); token[str_len] = '\0'; /* Alloc & set the slot */ vector_alloc_slot(strvec); vector_set_slot(strvec, token); } if (!vector_size(strvec)) { free_strvec(strvec); return NULL; } return strvec; } typedef struct _seq { char *var; int next; int last; int step; char *text; } seq_t; static list seq_list; /* List of seq_t */ #ifdef PARSER_DEBUG static void dump_seqs(void) { seq_t *seq; element e; LIST_FOREACH(seq_list, seq, e) log_message(LOG_INFO, "SEQ: %s => %d -> %d step %d: '%s'", seq->var, seq->next, seq->last, seq->step, seq->text); log_message(LOG_INFO, "%s", ""); } #endif static void free_seq(void *s) { seq_t *seq = s; FREE(seq->var); FREE(seq->text); FREE(seq); } static bool add_seq(char *buf) { char *p = buf + 4; /* Skip ~SEQ */ long one, two, three; long start, step, end; seq_t *seq_ent; char *var; char *var_end; p += strspn(p, " \t"); if (*p++ != '(') return false; p += strspn(p, " \t"); var = p; p += strcspn(p, " \t,)"); var_end = p; p += strspn(p, " \t"); if (!*p || *p == ')' || p == var) { report_config_error(CONFIG_GENERAL_ERROR, "Invalid ~SEQ definition '%s'", buf); return false; } p++; do { // Handle missing number one = strtol(p, &p, 0); p += strspn(p, " \t"); if (*p == ')') { end = one; step = (end < 1) ? -1 : 1; start = (end < 0) ? -1 : 1; break; } if (*p != ',') { report_config_error(CONFIG_GENERAL_ERROR, "Invalid ~SEQ definition '%s'", buf); return false; } two = strtol(p + 1, &p, 0); p += strspn(p, " \t"); if (*p == ')') { start = one; end = two; step = start <= end ? 1 : -1; break; } if (*p != ',') { report_config_error(CONFIG_GENERAL_ERROR, "Invalid ~SEQ definition '%s'", buf); return false; } three = strtol(p + 1, &p, 0); p += strspn(p, " \t"); if (*p != ')') { report_config_error(CONFIG_GENERAL_ERROR, "Invalid ~SEQ definition '%s'", buf); return false; } start = one; step = two; end = three; if (!step || (start < end && step < 0) || (start > end && step > 0)) { report_config_error(CONFIG_GENERAL_ERROR, "Invalid ~SEQ values '%s'", buf); return false; } } while (false); p += strspn(p + 1, " \t") + 1; PMALLOC(seq_ent); seq_ent->var = MALLOC(var_end - var + 1); strncpy(seq_ent->var, var, var_end - var); seq_ent->next = start; seq_ent->step = step; seq_ent->last = end; seq_ent->text = MALLOC(strlen(p) + 1); strcpy(seq_ent->text, p); if (!seq_list) seq_list = alloc_list(free_seq, NULL); list_add(seq_list, seq_ent); return true; } #ifdef PARSER_DEBUG static void dump_definitions(void) { def_t *def; element e; LIST_FOREACH(defs, def, e) log_message(LOG_INFO, "Defn %s = '%s'", def->name, def->value); log_message(LOG_INFO, "%s", ""); } #endif /* recursive configuration stream handler */ static int kw_level; static int block_depth; static bool process_stream(vector_t *keywords_vec, int need_bob) { unsigned int i; keyword_t *keyword_vec; char *str; char *buf; vector_t *strvec; vector_t *prev_keywords = current_keywords; current_keywords = keywords_vec; int bob_needed = 0; bool ret_err = false; bool ret; buf = MALLOC(MAXBUF); while (read_line(buf, MAXBUF)) { strvec = alloc_strvec(buf); if (!strvec) continue; str = vector_slot(strvec, 0); if (skip_sublevel == -1) { /* There wasn't a '{' on the keyword line */ if (!strcmp(str, BOB)) { /* We've got the opening '{' now */ skip_sublevel = 1; need_bob = 0; free_strvec(strvec); continue; } /* The skipped keyword doesn't have a {} block, so we no longer want to skip */ skip_sublevel = 0; } if (skip_sublevel) { for (i = 0; i < vector_size(strvec); i++) { str = vector_slot(strvec,i); if (!strcmp(str,BOB)) skip_sublevel++; else if (!strcmp(str,EOB)) { if (--skip_sublevel == 0) break; } } /* If we have reached the outer level of the block and we have * nested keyword level, then we need to return to restore the * next level up of keywords. */ if (!strcmp(str, EOB) && skip_sublevel == 0 && kw_level > 0) { ret_err = true; free_strvec(strvec); break; } free_strvec(strvec); continue; } if (need_bob) { need_bob = 0; if (!strcmp(str, BOB) && kw_level > 0) { free_strvec(strvec); continue; } else report_config_error(CONFIG_MISSING_BOB, "Missing '%s' at beginning of configuration block", BOB); } else if (!strcmp(str, BOB)) { report_config_error(CONFIG_UNEXPECTED_BOB, "Unexpected '%s' - ignoring", BOB); free_strvec(strvec); continue; } if (!strcmp(str, EOB) && kw_level > 0) { free_strvec(strvec); break; } if (!strncmp(str, "~SEQ", 4)) { if (!add_seq(buf)) report_config_error(CONFIG_GENERAL_ERROR, "Invalid ~SEQ specification '%s'", buf); free_strvec(strvec); #ifdef PARSER_DEBUG dump_definitions(); dump_seqs(); #endif continue; } for (i = 0; i < vector_size(keywords_vec); i++) { keyword_vec = vector_slot(keywords_vec, i); if (!strcmp(keyword_vec->string, str)) { if (!keyword_vec->active) { if (!strcmp(vector_slot(strvec, vector_size(strvec)-1), BOB)) skip_sublevel = 1; else skip_sublevel = -1; /* Sometimes a process wants to know if another process * has any of a type of configuration. For example, there * is no point starting the VRRP process of there are no * vrrp instances, and so the parent process would be * interested in that. */ if (keyword_vec->handler) (*keyword_vec->handler)(NULL); } /* There is an inconsistency here. 'static_ipaddress' for example * does not have sub levels, but needs a '{' */ if (keyword_vec->sub) { /* Remove a trailing '{' */ char *bob = vector_slot(strvec, vector_size(strvec)-1) ; if (!strcmp(bob, BOB)) { vector_unset(strvec, vector_size(strvec)-1); FREE(bob); bob_needed = 0; } else bob_needed = 1; } if (keyword_vec->active && keyword_vec->handler) { buf_extern = buf; /* In case the raw line wants to be accessed */ (*keyword_vec->handler) (strvec); } if (keyword_vec->sub) { kw_level++; ret = process_stream(keyword_vec->sub, bob_needed); kw_level--; /* We mustn't run any close handler if the block was skipped */ if (!ret && keyword_vec->active && keyword_vec->sub_close_handler) (*keyword_vec->sub_close_handler) (); } break; } } if (i >= vector_size(keywords_vec)) report_config_error(CONFIG_UNKNOWN_KEYWORD, "Unknown keyword '%s'", str); free_strvec(strvec); } current_keywords = prev_keywords; FREE(buf); return ret_err; } static bool read_conf_file(const char *conf_file) { FILE *stream; glob_t globbuf; size_t i; int res; struct stat stb; unsigned num_matches = 0; globbuf.gl_offs = 0; res = glob(conf_file, GLOB_MARK #if HAVE_DECL_GLOB_BRACE | GLOB_BRACE #endif , NULL, &globbuf); if (res) { if (res == GLOB_NOMATCH) log_message(LOG_INFO, "No config files matched '%s'.", conf_file); else log_message(LOG_INFO, "Error reading config file(s): glob(\"%s\") returned %d, skipping.", conf_file, res); return true; } for (i = 0; i < globbuf.gl_pathc; i++) { if (globbuf.gl_pathv[i][strlen(globbuf.gl_pathv[i])-1] == '/') { /* This is a directory - so skip */ continue; } log_message(LOG_INFO, "Opening file '%s'.", globbuf.gl_pathv[i]); stream = fopen(globbuf.gl_pathv[i], "r"); if (!stream) { log_message(LOG_INFO, "Configuration file '%s' open problem (%s) - skipping" , globbuf.gl_pathv[i], strerror(errno)); continue; } /* Make sure what we have opened is a regular file, and not for example a directory or executable */ if (fstat(fileno(stream), &stb) || !S_ISREG(stb.st_mode) || (stb.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))) { log_message(LOG_INFO, "Configuration file '%s' is not a regular non-executable file - skipping", globbuf.gl_pathv[i]); fclose(stream); continue; } num_matches++; current_stream = stream; /* We only want to report the file name if there is more than one file used */ if (current_file_name || globbuf.gl_pathc > 1) current_file_name = globbuf.gl_pathv[i]; current_file_line_no = 0; int curdir_fd = -1; if (strchr(globbuf.gl_pathv[i], '/')) { /* If the filename contains a directory element, change to that directory. The man page open(2) states that fchdir() didn't support O_PATH until Linux 3.5, even though testing on Linux 3.1 shows it appears to work. To be safe, don't use it until Linux 3.5. */ curdir_fd = open(".", O_RDONLY | O_DIRECTORY #if HAVE_DECL_O_PATH && LINUX_VERSION_CODE >= KERNEL_VERSION(3,5,0) | O_PATH #endif ); char *confpath = strdup(globbuf.gl_pathv[i]); dirname(confpath); if (chdir(confpath) < 0) log_message(LOG_INFO, "chdir(%s) error (%s)", confpath, strerror(errno)); free(confpath); } process_stream(current_keywords, 0); fclose(stream); free_list(&seq_list); /* If we changed directory, restore the previous directory */ if (curdir_fd != -1) { if ((res = fchdir(curdir_fd))) log_message(LOG_INFO, "Failed to restore previous directory after include"); close(curdir_fd); if (res) return true; } } globfree(&globbuf); if (!num_matches) log_message(LOG_INFO, "No config files matched '%s'.", conf_file); return false; } bool check_conf_file(const char *conf_file) { glob_t globbuf; size_t i; bool ret = true; int res; struct stat stb; unsigned num_matches = 0; globbuf.gl_offs = 0; res = glob(conf_file, GLOB_MARK #if HAVE_DECL_GLOB_BRACE | GLOB_BRACE #endif , NULL, &globbuf); if (res) { report_config_error(CONFIG_FILE_NOT_FOUND, "Unable to find configuration file %s (glob returned %d)", conf_file, res); return false; } for (i = 0; i < globbuf.gl_pathc; i++) { if (globbuf.gl_pathv[i][strlen(globbuf.gl_pathv[i])-1] == '/') { /* This is a directory - so skip */ continue; } if (access(globbuf.gl_pathv[i], R_OK)) { log_message(LOG_INFO, "Unable to read configuration file %s", globbuf.gl_pathv[i]); ret = false; break; } /* Make sure that the file is a regular file, and not for example a directory or executable */ if (stat(globbuf.gl_pathv[i], &stb) || !S_ISREG(stb.st_mode) || (stb.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))) { log_message(LOG_INFO, "Configuration file '%s' is not a regular non-executable file", globbuf.gl_pathv[i]); ret = false; break; } num_matches++; } if (ret) { if (num_matches > 1) report_config_error(CONFIG_MULTIPLE_FILES, "WARNING, more than one file matches configuration file %s, using %s", conf_file, globbuf.gl_pathv[0]); else if (num_matches == 0) { report_config_error(CONFIG_FILE_NOT_FOUND, "Unable to find configuration file %s", conf_file); ret = false; } } globfree(&globbuf); return ret; } static bool check_include(char *buf) { vector_t *strvec; bool ret = false; FILE *prev_stream; const char *prev_file_name; size_t prev_file_line_no; /* Simple check first for include */ if (!strstr(buf, "include")) return false; strvec = alloc_strvec(buf); if (!strvec) return false; if(!strcmp("include", vector_slot(strvec, 0)) && vector_size(strvec) == 2) { prev_stream = current_stream; prev_file_name = current_file_name; prev_file_line_no = current_file_line_no; read_conf_file(vector_slot(strvec, 1)); current_stream = prev_stream; current_file_name = prev_file_name; current_file_line_no = prev_file_line_no; ret = true; } free_strvec(strvec); return ret; } static def_t * find_definition(const char *name, size_t len, bool definition) { element e; def_t *def; const char *p; bool using_braces = false; bool allow_multiline; if (LIST_ISEMPTY(defs)) return NULL; if (!definition && *name == BOB[0]) { using_braces = true; name++; } if (!isalpha(*name) && *name != '_') return NULL; if (!len) { for (len = 1, p = name + 1; *p != '\0' && (isalnum(*p) || *p == '_'); len++, p++); /* Check we have a suitable end character */ if (using_braces && *p != EOB[0]) return NULL; if (!using_braces && !definition && *p != ' ' && *p != '\t' && *p != '\0') return NULL; } if (definition || (!using_braces && name[len] == '\0') || (using_braces && name[len+1] == '\0')) allow_multiline = true; else allow_multiline = false; for (e = LIST_HEAD(defs); e; ELEMENT_NEXT(e)) { def = ELEMENT_DATA(e); if (def->name_len == len && (allow_multiline || !def->multiline) && !strncmp(def->name, name, len)) return def; } return NULL; } static bool replace_param(char *buf, size_t max_len, char **multiline_ptr_ptr) { char *cur_pos = buf; size_t len_used = strlen(buf); def_t *def; char *s, *d, *e; ssize_t i; size_t extra_braces; size_t replacing_len; char *next_ptr = NULL; bool found_defn = false; char *multiline_ptr = *multiline_ptr_ptr; while ((cur_pos = strchr(cur_pos, '$')) && cur_pos[1] != '\0') { if ((def = find_definition(cur_pos + 1, 0, false))) { found_defn = true; extra_braces = cur_pos[1] == BOB[0] ? 2 : 0; next_ptr = multiline_ptr; /* We are in a multiline expansion, and now have another * one, so save the previous state on the multiline stack */ if (def->multiline && multiline_ptr) { if (!LIST_EXISTS(multiline_stack)) multiline_stack = alloc_list(NULL, NULL); list_add(multiline_stack, multiline_ptr); } if (def->fn) { /* This is a standard definition that uses a function for the replacement text */ if (def->value) FREE(def->value); def->value = (*def->fn)(); def->value_len = strlen(def->value); } /* Ensure there is enough room to replace $PARAM or ${PARAM} with value */ if (def->multiline) { replacing_len = strcspn(def->value, DEF_LINE_END); next_ptr = def->value + replacing_len + 1; multiline_ptr = next_ptr; } else replacing_len = def->value_len; if (len_used + replacing_len - (def->name_len + 1 + extra_braces) >= max_len) { log_message(LOG_INFO, "Parameter substitution on line '%s' would exceed maximum line length", buf); return NULL; } if (def->name_len + 1 + extra_braces != replacing_len) { /* We need to move the existing text */ if (def->name_len + 1 + extra_braces < replacing_len) { /* We are lengthening the buf text */ s = cur_pos + strlen(cur_pos); d = s - (def->name_len + 1 + extra_braces) + replacing_len; e = cur_pos; i = -1; } else { /* We are shortening the buf text */ s = cur_pos + (def->name_len + 1 + extra_braces) - replacing_len; d = cur_pos; e = cur_pos + strlen(cur_pos); i = 1; } do { *d = *s; if (s == e) break; d += i; s += i; } while (true); len_used = len_used + replacing_len - (def->name_len + 1 + extra_braces); } /* Now copy the replacement text */ strncpy(cur_pos, def->value, replacing_len); if (def->value[strspn(def->value, " \t")] == '~') break; } else cur_pos++; } /* If we did a replacement, update the multiline_ptr */ if (found_defn) *multiline_ptr_ptr = next_ptr; return found_defn; } static void free_definition(void *d) { def_t *def = d; FREE(def->name); FREE_PTR(def->value); FREE(def); } static def_t* set_definition(const char *name, const char *value) { def_t *def; size_t name_len = strlen(name); if ((def = find_definition(name, name_len, false))) { FREE(def->value); def->fn = NULL; /* Allow a standard definition to be overridden */ } else { def = MALLOC(sizeof(*def)); def->name_len = name_len; def->name = MALLOC(name_len + 1); strcpy(def->name, name); if (!LIST_EXISTS(defs)) defs = alloc_list(free_definition, NULL); list_add(defs, def); } def->value_len = strlen(value); def->value = MALLOC(def->value_len + 1); strcpy(def->value, value); #ifdef PARSER_DEBUG log_message(LOG_INFO, "Definition %s now '%s'", def->name, def->value); #endif return def; } /* A definition is of the form $NAME=TEXT */ static def_t* check_definition(const char *buf) { const char *p; def_t* def; size_t def_name_len; char *str; if (buf[0] != '$') return false; if (!isalpha(buf[1]) && buf[1] != '_') return NULL; for (p = buf + 2; *p; p++) { if (*p == '=') break; if (!isalnum(*p) && !isdigit(*p) && *p != '_') return NULL; } def_name_len = (size_t)(p - &buf[1]); p += strspn(p, " \t"); if (*p != '=') return NULL; if ((def = find_definition(&buf[1], def_name_len, true))) { FREE(def->value); def->fn = NULL; /* Allow a standard definition to be overridden */ } else { def = MALLOC(sizeof(*def)); def->name_len = def_name_len; str = MALLOC(def->name_len + 1); strncpy(str, &buf[1], def->name_len); str[def->name_len] = '\0'; def->name = str; if (!LIST_EXISTS(defs)) defs = alloc_list(free_definition, NULL); list_add(defs, def); } /* Skip leading whitespace */ p += strspn(p + 1, " \t") + 1; def->value_len = strlen(p); if (p[def->value_len - 1] == '\\') { /* Remove trailing whitespace */ while (def->value_len >= 2 && isblank(p[def->value_len - 2])) def->value_len--; if (def->value_len < 2) { /* If the string has nothing except spaces and terminating '\' * point to the string terminator. */ p += def->value_len; def->value_len = 0; } def->multiline = true; } else def->multiline = false; str = MALLOC(def->value_len + 1); strcpy(str, p); def->value = str; /* If it a multiline definition, we need to mark the end of the first line * by overwriting the '\' with the line end marker. */ if (def->value_len >= 2 && def->multiline) def->value[def->value_len - 1] = DEF_LINE_END[0]; return def; } static void add_std_definition(const char *name, const char *value, char *(*fn)(void)) { def_t* def; def = MALLOC(sizeof(*def)); def->name_len = strlen(name); def->name = MALLOC(def->name_len + 1); strcpy(def->name, name); if (value) { def->value_len = strlen(value); def->value = MALLOC(def->value_len + 1); strcpy(def->value, value); } def->fn = fn; if (!LIST_EXISTS(defs)) defs = alloc_list(free_definition, NULL); list_add(defs, def); } static void set_std_definitions(void) { add_std_definition("_PWD", NULL, get_cwd); add_std_definition("_INSTANCE", NULL, get_instance); } static void free_parser_data(void) { if (LIST_EXISTS(defs)) free_list(&defs); if (LIST_EXISTS(multiline_stack)) free_list(&multiline_stack); } /* decomment() removes comments, the escaping of comment start characters, * and leading and trailing whitespace, including whitespace before a * terminating \ character */ static void decomment(char *str) { bool quote = false; bool cont = false; char *skip = NULL; char *p = str + strspn(str, " \t"); /* Remove leading whitespace */ if (p != str) memmove(str, p, strlen(p) + 1); p = str; while ((p = strpbrk(p, "!#\"\\"))) { if (*p == '"') { if (!skip) quote = !quote; p++; continue; } if (*p == '\\') { if (p[1]) { /* Don't modify quoted strings */ if (!quote && (p[1] == '#' || p[1] == '!')) { memmove(p, p + 1, strlen(p + 1) + 1); p++; } else p += 2; continue; } *p = '\0'; cont = true; break; } if (!quote && !skip && (*p == '!' || *p == '#')) skip = p; p++; } if (quote) report_config_error(CONFIG_GENERAL_ERROR, "Unterminated quote '%s'", str); if (skip) *skip = '\0'; /* Remove trailing whitespace */ p = str + strlen(str) - 1; while (p >= str && isblank(*p)) *p-- = '\0'; if (cont) { *++p = '\\'; *++p = '\0'; } } static bool read_line(char *buf, size_t size) { size_t len ; bool eof = false; size_t config_id_len; char *buf_start; bool rev_cmp; size_t ofs; bool recheck; static def_t *def = NULL; static char *next_ptr = NULL; bool multiline_param_def = false; char *end; static char *line_residue = NULL; size_t skip; char *p; config_id_len = config_id ? strlen(config_id) : 0; do { if (line_residue) { strcpy(buf, line_residue); FREE(line_residue); line_residue = NULL; } else if (next_ptr) { /* We are expanding a multiline parameter, so copy next line */ end = strchr(next_ptr, DEF_LINE_END[0]); if (!end) { strcpy(buf, next_ptr); if (!LIST_ISEMPTY(multiline_stack)) { next_ptr = LIST_TAIL_DATA(multiline_stack); list_remove(multiline_stack, multiline_stack->tail); } else next_ptr = NULL; } else { strncpy(buf, next_ptr, (size_t)(end - next_ptr)); buf[end - next_ptr] = '\0'; next_ptr = end + 1; } } else if (!LIST_ISEMPTY(seq_list)) { seq_t *seq = LIST_TAIL_DATA(seq_list); char val[12]; snprintf(val, sizeof(val), "%d", seq->next); #ifdef PARSER_DEBUG log_message(LOG_INFO, "Processing seq %d of %s for '%s'", seq->next, seq->var, seq->text); #endif set_definition(seq->var, val); strcpy(buf, seq->text); seq->next += seq->step; if ((seq->step > 0 && seq->next > seq->last) || (seq->step < 0 && seq->next < seq->last)) { #ifdef PARSER_DEBUG log_message(LOG_INFO, "Removing seq %s for '%s'", seq->var, seq->text); #endif list_remove(seq_list, seq_list->tail); } } else { retry: if (!fgets(buf, (int)size, current_stream)) { eof = true; buf[0] = '\0'; break; } /* Check if we have read the end of a line */ len = strlen(buf); if (buf[0] && buf[len-1] == '\n') current_file_line_no++; /* Remove end of line chars */ while (len && (buf[len-1] == '\n' || buf[len-1] == '\r')) len--; /* Skip blank lines */ if (!len) goto retry; buf[len] = '\0'; decomment(buf); } len = strlen(buf); /* Handle multi-line definitions */ if (multiline_param_def) { /* Remove trailing whitespace */ if (len && buf[len-1] == '\\') { len--; while (len >= 1 && isblank(buf[len - 1])) len--; buf[len++] = DEF_LINE_END[0]; } else { multiline_param_def = false; if (!def->value_len) def->multiline = false; } /* Don't add blank lines */ if (len >= 2 || (len && !multiline_param_def)) { /* Add the line to the definition */ def->value = REALLOC(def->value, def->value_len + len + 1); strncpy(def->value + def->value_len, buf, len); def->value_len += len; def->value[def->value_len] = '\0'; } buf[0] = '\0'; continue; } if (len == 0) continue; recheck = false; do { if (buf[0] == '@') { /* If the line starts '@', check the following word matches the system id. @^ reverses the sense of the match */ if (buf[1] == '^') { rev_cmp = true; ofs = 2; } else { rev_cmp = false; ofs = 1; } /* We need something after the system_id */ if (!(buf_start = strpbrk(buf + ofs, " \t"))) { buf[0] = '\0'; break; } /* Check if config_id matches/doesn't match as appropriate */ if ((!config_id || (size_t)(buf_start - (buf + ofs)) != config_id_len || strncmp(buf + ofs, config_id, config_id_len)) != rev_cmp) { buf[0] = '\0'; break; } /* Remove the @config_id from start of line */ buf_start += strspn(buf_start, " \t"); len -= (buf_start - buf); memmove(buf, buf_start, len + 1); } if (buf[0] == '$' && (def = check_definition(buf))) { /* check_definition() saves the definition */ if (def->multiline) multiline_param_def = true; buf[0] = '\0'; break; } if (buf[0] == '~') break; if (!LIST_ISEMPTY(defs) && (p = strchr(buf, '$'))) { if (!replace_param(buf, size, &next_ptr)) { /* If nothing has changed, we don't need to do any more processing */ break; } if (buf[0] == '@') recheck = true; if (strchr(buf, '$')) recheck = true; } } while (recheck); } while (buf[0] == '\0' || check_include(buf)); /* Search for BOB[0] or EOB[0] not in "" */ if (buf[0]) { p = buf; if (p[0] != BOB[0] && p[0] != EOB[0]) { while ((p = strpbrk(p, BOB EOB "\""))) { if (*p != '"') break; /* Skip over anything in ""s */ if (!(p = strchr(p + 1, '"'))) break; p++; } } if (p && (p[0] == BOB[0] || p[0] == EOB[0])) { if (p == buf) skip = strspn(p + 1, " \t") + 1; else skip = 0; if (p[skip]) { /* Skip trailing whitespace */ len = strlen(p + skip); while (len && (p[skip+len-1] == ' ' || p[skip+len-1] == '\t')) len--; line_residue = MALLOC(len + 1); p[skip+len] = '\0'; strcpy(line_residue, p + skip); p[skip] = '\0'; } } /* Skip trailing whitespace */ len = strlen(buf); while (len && (buf[len-1] == ' ' || buf[len-1] == '\t')) len--; buf[len] = '\0'; /* Check that we haven't got too many '}'s */ if (!strcmp(buf, BOB)) block_depth++; else if (!strcmp(buf, EOB)) { if (--block_depth < 0) { report_config_error(CONFIG_UNEXPECTED_EOB, "Extra '}' found"); block_depth = 0; } } } #ifdef PARSER_DEBUG log_message(LOG_INFO, "read_line(%d): '%s'", block_depth, buf); #endif return !eof; } void alloc_value_block(void (*alloc_func) (vector_t *), const char *block_type) { char *buf; char *str = NULL; vector_t *vec = NULL; bool first_line = true; buf = (char *) MALLOC(MAXBUF); while (read_line(buf, MAXBUF)) { if (!(vec = alloc_strvec(buf))) continue; if (first_line) { first_line = false; if (!strcmp(vector_slot(vec, 0), BOB)) { free_strvec(vec); continue; } log_message(LOG_INFO, "'%s' missing from beginning of block %s", BOB, block_type); } str = vector_slot(vec, 0); if (!strcmp(str, EOB)) { free_strvec(vec); break; } if (vector_size(vec)) (*alloc_func) (vec); free_strvec(vec); } FREE(buf); } static vector_t *read_value_block_vec; static void read_value_block_line(vector_t *strvec) { size_t word; char *str; char *dup; if (!read_value_block_vec) read_value_block_vec = vector_alloc(); vector_foreach_slot(strvec, str, word) { dup = (char *) MALLOC(strlen(str) + 1); strcpy(dup, str); vector_alloc_slot(read_value_block_vec); vector_set_slot(read_value_block_vec, dup); } } vector_t * read_value_block(vector_t *strvec) { vector_t *ret_vec; alloc_value_block(read_value_block_line, vector_slot(strvec,0)); ret_vec = read_value_block_vec; read_value_block_vec = NULL; return ret_vec; } void * set_value(vector_t *strvec) { char *str; size_t size; char *alloc; if (vector_size(strvec) < 2) return NULL; str = vector_slot(strvec, 1); size = strlen(str); alloc = (char *) MALLOC(size + 1); if (!alloc) return NULL; memcpy(alloc, str, size); return alloc; } bool read_timer(vector_t *strvec, size_t index, unsigned long *res, unsigned long min_time, unsigned long max_time, __attribute__((unused)) bool ignore_error) { unsigned long timer; char *endptr; char *warn = ""; #ifndef _STRICT_CONFIG_ if (ignore_error && !__test_bit(CONFIG_TEST_BIT, &debug)) warn = "WARNING - "; #endif if (!max_time) max_time = TIMER_MAX; errno = 0; timer = strtoul(vector_slot(strvec, index), &endptr, 10); *res = (timer > TIMER_MAX ? TIMER_MAX : timer) * TIMER_HZ; if (FMT_STR_VSLOT(strvec, index)[0] == '-') report_config_error(CONFIG_INVALID_NUMBER, "%snegative number '%s'", warn, FMT_STR_VSLOT(strvec, index)); else if (*endptr) report_config_error(CONFIG_INVALID_NUMBER, "%sinvalid number '%s'", warn, FMT_STR_VSLOT(strvec, index)); else if (errno == ERANGE || timer > TIMER_MAX) report_config_error(CONFIG_INVALID_NUMBER, "%snumber '%s' outside timer range", warn, FMT_STR_VSLOT(strvec, index)); else if (timer < min_time || timer > max_time) report_config_error(CONFIG_INVALID_NUMBER, "number '%s' outside range [%ld, %ld]", FMT_STR_VSLOT(strvec, index), min_time, max_time ? max_time : TIMER_MAX); else return true; #ifdef _STRICT_CONFIG_ return false; #else return ignore_error && timer >= min_time && timer <= max_time && !__test_bit(CONFIG_TEST_BIT, &debug); #endif } /* Checks for on/true/yes or off/false/no */ int check_true_false(char *str) { if (!strcmp(str, "true") || !strcmp(str, "on") || !strcmp(str, "yes")) return true; if (!strcmp(str, "false") || !strcmp(str, "off") || !strcmp(str, "no")) return false; return -1; /* error */ } void skip_block(bool need_block_start) { /* Don't process the rest of the configuration block */ if (need_block_start) skip_sublevel = -1; else skip_sublevel = 1; } /* Data initialization */ void init_data(const char *conf_file, vector_t * (*init_keywords) (void)) { /* Init Keywords structure */ keywords = vector_alloc(); (*init_keywords) (); /* Add out standard definitions */ set_std_definitions(); #if DUMP_KEYWORDS /* Dump configuration */ dump_keywords(keywords, 0, NULL); #endif /* Stream handling */ current_keywords = keywords; current_file_name = NULL; current_file_line_no = 0; /* A parent process may have left these set */ block_depth = 0; kw_level = 0; register_null_strvec_handler(null_strvec); read_conf_file(conf_file); unregister_null_strvec_handler(); /* Report if there are missing '}'s. If there are missing '{'s it will already have been reported */ if (block_depth > 0) report_config_error(CONFIG_MISSING_EOB, "There are %d missing '%s's or extra '%s's", block_depth, EOB, BOB); /* We have finished reading the configuration files, so any configuration * errors report from now mustn't include a reference to the config file name */ current_file_line_no = 0; /* Close the password database if it was opened */ endpwent(); free_keywords(keywords); free_parser_data(); #ifdef _WITH_VRRP_ clear_rt_names(); #endif notify_resource_release(); }
./CrossVul/dataset_final_sorted/CWE-59/c/bad_436_11
crossvul-cpp_data_good_1670_1
/* Copyright (C) 2011 ABRT Team Copyright (C) 2011 RedHat inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "libabrt.h" #define EXECUTABLE "abrt-action-install-debuginfo" #define IGNORE_RESULT(func_call) do { if (func_call) /* nothing */; } while (0) /* A binary wrapper is needed around python scripts if we want * to run them in sgid/suid mode. * * This is such a wrapper. */ int main(int argc, char **argv) { /* I18n */ setlocale(LC_ALL, ""); #if ENABLE_NLS bindtextdomain(PACKAGE, LOCALEDIR); textdomain(PACKAGE); #endif abrt_init(argv); /* Can't keep these strings/structs static: _() doesn't support that */ const char *program_usage_string = _( "& [-y] [-i BUILD_IDS_FILE|-i -] [-e PATH[:PATH]...]\n" "\t[-r REPO]\n" "\n" "Installs debuginfo packages for all build-ids listed in BUILD_IDS_FILE to\n" "ABRT system cache." ); enum { OPT_v = 1 << 0, OPT_y = 1 << 1, OPT_i = 1 << 2, OPT_e = 1 << 3, OPT_r = 1 << 4, OPT_s = 1 << 5, }; const char *build_ids = "build_ids"; const char *exact = NULL; const char *repo = NULL; const char *size_mb = NULL; struct options program_options[] = { OPT__VERBOSE(&g_verbose), OPT_BOOL ('y', "yes", NULL, _("Noninteractive, assume 'Yes' to all questions")), OPT_STRING('i', "ids", &build_ids, "BUILD_IDS_FILE", _("- means STDIN, default: build_ids")), OPT_STRING('e', "exact", &exact, "EXACT", _("Download only specified files")), OPT_STRING('r', "repo", &repo, "REPO", _("Pattern to use when searching for repos, default: *debug*")), OPT_STRING('s', "size_mb", &size_mb, "SIZE_MB", _("Ignored option")), OPT_END() }; const unsigned opts = parse_opts(argc, argv, program_options, program_usage_string); const gid_t egid = getegid(); const gid_t rgid = getgid(); const uid_t euid = geteuid(); const gid_t ruid = getuid(); /* We need to open the build ids file under the caller's UID/GID to avoid * information disclosures when reading files with changed UID. * Unfortunately, we cannot replace STDIN with the new fd because ABRT uses * STDIN to communicate with the caller. So, the following code opens a * dummy file descriptor to the build ids file and passes the new fd's proc * path to the wrapped program in the ids argument. * The new fd remains opened, the OS will close it for us. */ char *build_ids_self_fd = NULL; if (strcmp("-", build_ids) != 0) { if (setregid(egid, rgid) < 0) perror_msg_and_die("setregid(egid, rgid)"); if (setreuid(euid, ruid) < 0) perror_msg_and_die("setreuid(euid, ruid)"); const int build_ids_fd = open(build_ids, O_RDONLY); if (setregid(rgid, egid) < 0) perror_msg_and_die("setregid(rgid, egid)"); if (setreuid(ruid, euid) < 0 ) perror_msg_and_die("setreuid(ruid, euid)"); if (build_ids_fd < 0) perror_msg_and_die("Failed to open file '%s'", build_ids); /* We are not going to free this memory. There is no place to do so. */ build_ids_self_fd = xasprintf("/proc/self/fd/%d", build_ids_fd); } char tmp_directory[] = LARGE_DATA_TMP_DIR"/abrt-tmp-debuginfo.XXXXXX"; if (mkdtemp(tmp_directory) == NULL) perror_msg_and_die("Failed to create working directory"); log_info("Created working directory: %s", tmp_directory); /* name, -v, --ids, -, -y, -e, EXACT, -r, REPO, -t, PATH, --, NULL */ const char *args[13]; { const char *verbs[] = { "", "-v", "-vv", "-vvv" }; unsigned i = 0; args[i++] = EXECUTABLE; args[i++] = "--ids"; args[i++] = (build_ids_self_fd != NULL) ? build_ids_self_fd : "-"; if (g_verbose > 0) args[i++] = verbs[g_verbose <= 3 ? g_verbose : 3]; if ((opts & OPT_y)) args[i++] = "-y"; if ((opts & OPT_e)) { args[i++] = "--exact"; args[i++] = exact; } if ((opts & OPT_r)) { args[i++] = "--repo"; args[i++] = repo; } args[i++] = "--tmpdir"; args[i++] = tmp_directory; args[i++] = "--"; args[i] = NULL; } /* Switch real user/group to effective ones. * Otherwise yum library gets confused - gets EPERM (why??). */ /* do setregid only if we have to, to not upset selinux needlessly */ if (egid != rgid) IGNORE_RESULT(setregid(egid, egid)); if (euid != ruid) { IGNORE_RESULT(setreuid(euid, euid)); /* We are suid'ed! */ /* Prevent malicious user from messing up with suid'ed process: */ #if 1 // We forgot to sanitize PYTHONPATH. And who knows what else we forgot // (especially considering *future* new variables of this kind). // We switched to clearing entire environment instead: // However since we communicate through environment variables // we have to keep a whitelist of variables to keep. static const char *whitelist[] = { "REPORT_CLIENT_SLAVE", // Check if the app is being run as a slave "LANG", }; const size_t wlsize = sizeof(whitelist)/sizeof(char*); char *setlist[sizeof(whitelist)/sizeof(char*)] = { 0 }; char *p = NULL; for (size_t i = 0; i < wlsize; i++) if ((p = getenv(whitelist[i])) != NULL) setlist[i] = xstrdup(p); // Now we can clear the environment clearenv(); // And once again set whitelisted variables for (size_t i = 0; i < wlsize; i++) if (setlist[i] != NULL) { xsetenv(whitelist[i], setlist[i]); free(setlist[i]); } #else /* Clear dangerous stuff from env */ static const char forbid[] = "LD_LIBRARY_PATH" "\0" "LD_PRELOAD" "\0" "LD_TRACE_LOADED_OBJECTS" "\0" "LD_BIND_NOW" "\0" "LD_AOUT_LIBRARY_PATH" "\0" "LD_AOUT_PRELOAD" "\0" "LD_NOWARN" "\0" "LD_KEEPDIR" "\0" ; const char *p = forbid; do { unsetenv(p); p += strlen(p) + 1; } while (*p); #endif /* Set safe PATH */ // Adding configure --bindir and --sbindir to the PATH so that // abrt-action-install-debuginfo doesn't fail when spawning // abrt-action-trim-files char path_env[] = "PATH=/usr/sbin:/sbin:/usr/bin:/bin:"BIN_DIR":"SBIN_DIR; if (euid != 0) strcpy(path_env, "PATH=/usr/bin:/bin:"BIN_DIR); putenv(path_env); /* Use safe umask */ umask(0022); } pid_t pid = fork(); if (pid < 0) perror_msg_and_die("fork"); if (pid == 0) { execvp(EXECUTABLE, (char **)args); error_msg_and_die("Can't execute %s", EXECUTABLE); } int status; if (safe_waitpid(pid, &status, 0) < 0) perror_msg_and_die("waitpid"); if (rmdir(tmp_directory) >= 0) log_info("Removed working directory: %s", tmp_directory); else if (errno != ENOENT) perror_msg("Failed to remove working directory"); /* Normal execution should exit here. */ if (WIFEXITED(status)) return WEXITSTATUS(status); if (WIFSIGNALED(status)) error_msg_and_die("Child terminated with signal %d", WTERMSIG(status)); error_msg_and_die("Child exit failed"); }
./CrossVul/dataset_final_sorted/CWE-59/c/good_1670_1