Exemple #1
0
int main()
{
	FBDEV fbdev;
	memset(&fbdev,0,sizeof(FBDEV));
	strcpy(fbdev.dev,"/dev/fb0");	

	if(0 == fb_open(&fbdev)){
		printf("Open fail!!\n");
		return -1;
	}
	
	//打印frame buffer 所占内存的开始地址 
	pmem_start(&fbdev);
	//打印FB_TYPE
	p_type(&fbdev);
	//打印可见清晰度
	p_visible_res(&fbdev);
	//打印虚拟分辨率
	p_virt_res(&fbdev);
	//打印虚拟到可见的偏移量
	p_offset(&fbdev);
	//打印每个像素的位数
	p_bpp(&fbdev);
	//打印R,G,B和透明度
	p_rgbt(&fbdev);
	//打印在内存中的高度和宽度
	p_hw(&fbdev);

	fb_close(&fbdev);

	return 0;
}
Exemple #2
0
static void
nslookupComplain(const char *sysloginfo, 
                 const char *net_queryname, 
                 const char *complaint, 
                 const char *net_dname, 
                 const struct databuf *a_rr, 
                 const struct databuf *nsdp)
{
  char queryname[INSZ+1], dname[INSZ+1];
  const char *a, *ns;
  const char *a_type;
  int print_a;

  strncpy(queryname, net_queryname, sizeof queryname);
  queryname[(sizeof queryname) - 1] = EOS;
  strncpy(dname, net_dname, sizeof dname);
  dname[(sizeof dname) - 1] = EOS;
  
  if (sysloginfo && queryname && !haveComplained(queryname, complaint)) {
    char buf[BUFSZ];
    
    a = ns = (char *)NULL;
    print_a = (a_rr->d_type == T_A);
    a_type = p_type(a_rr->d_type);
    
    /* OK */
    r_strncpy (buf, sysloginfo, BUFSZ);
  }
}
Exemple #3
0
static void
do_section(ns_msg *handle, ns_sect section, int pflag, FILE *file) {
    int n, sflag, rrnum;
    ns_opcode opcode;
    ns_rr rr;

    /*
     * Print answer records.
     */
    sflag = (int)(_res.pfcode & pflag);
    if (_res.pfcode && !sflag)
        return;

    opcode = ns_msg_getflag(*handle, ns_f_opcode);
    rrnum = 0;
    for (;;) {
        if (ns_parserr(handle, section, rrnum, &rr)) {
            if (errno != ENODEV)
                fprintf(file, ";; ns_parserr: %s\n",
                    strerror(errno));
            else if (rrnum > 0 && sflag != 0 &&
                 (_res.pfcode & RES_PRF_HEAD1))
                putc('\n', file);
            return;
        }
        if (rrnum == 0 && sflag != 0 && (_res.pfcode & RES_PRF_HEAD1))
            fprintf(file, ";; %s SECTION:\n",
                p_section(section, opcode));
        if (section == ns_s_qd)
            fprintf(file, ";;\t%s, type = %s, class = %s\n",
                ns_rr_name(rr),
                p_type(ns_rr_type(rr)),
                p_class(ns_rr_class(rr)));
        else {
            char *buf;
            buf = (char*)malloc(2024);
            if (buf) {
                n = ns_sprintrr(handle, &rr, NULL, NULL,
                        buf, sizeof buf);
                if (n < 0) {
                    fprintf(file, ";; ns_sprintrr: %s\n",
                        strerror(errno));
                    free(buf);
                    return;
                }
                fputs(buf, file);
                fputc('\n', file);
                free(buf);
            }
        }
        rrnum++;
    }
}
Exemple #4
0
/**
==================== Decl =============================================
   Grammar:
      decl : type id ';' 
*/
static TreeDecl p_decl(void) {
   TreeDecl decl = 0; // set null by default
   TokenCode code = curr()->code;
   // body
   TreeType l0type = p_type();
   TreeId l1id = p_id();
   eat(';');
   decl = t_decl_type(l0type, l1id);

   
   return decl;
}
Exemple #5
0
static void
do_section(const res_state statp,
	   ns_msg *handle, ns_sect section,
	   int pflag, FILE *file)
{
	int n, sflag, rrnum;
	int buflen = 2048;
	char *buf;
	ns_opcode opcode;
	ns_rr rr;

	/*
	 * Print answer records.
	 */
	sflag = (statp->pfcode & pflag);
	if (statp->pfcode && !sflag)
		return;

	buf = malloc((size_t)buflen);
	if (buf == NULL) {
		fprintf(file, ";; memory allocation failure\n");
		return;
	}

	opcode = (ns_opcode) ns_msg_getflag(*handle, ns_f_opcode);
	rrnum = 0;
	for (;;) {
		if (ns_parserr(handle, section, rrnum, &rr)) {
			if (errno != ENODEV)
				fprintf(file, ";; ns_parserr: %s\n",
					strerror(errno));
			else if (rrnum > 0 && sflag != 0 &&
				 (statp->pfcode & RES_PRF_HEAD1))
				putc('\n', file);
			goto cleanup;
		}
		if (rrnum == 0 && sflag != 0 && (statp->pfcode & RES_PRF_HEAD1))
			fprintf(file, ";; %s SECTION:\n",
				p_section(section, opcode));
		if (section == ns_s_qd)
			fprintf(file, ";;\t%s, type = %s, class = %s\n",
				ns_rr_name(rr),
				p_type(ns_rr_type(rr)),
				p_class(ns_rr_class(rr)));
		else if (section == ns_s_ar && ns_rr_type(rr) == ns_t_opt) {
			u_int32_t ttl = ns_rr_ttl(rr);
			fprintf(file,
				"; EDNS: version: %u, udp=%u, flags=%04x\n",
				(ttl>>16)&0xff, ns_rr_class(rr), ttl&0xffff);
		} else {
Exemple #6
0
void
val_log_val_rrset_pfx(const val_context_t * ctx, int level,
                      const char *pfx, struct val_rrset_rec *val_rrset_rec)
{
    char            buf1[2049], buf2[2049];

    if (!val_rrset_rec)
        return;

    val_log(ctx, level, "%srrs->val_rrset_name=%s rrs->val_rrset_type=%s "
            "rrs->val_rrset_class=%s rrs->val_rrset_ttl=%d "
            "rrs->val_rrset_section=%s\nrrs->val_rrset_data=%s\n"
            "rrs->val_rrset_sig=%s", pfx ? pfx : "", 
            val_rrset_rec->val_rrset_name,
            p_type(val_rrset_rec->val_rrset_type),
            p_class(val_rrset_rec->val_rrset_class),
            val_rrset_rec->val_rrset_ttl,
            p_section(val_rrset_rec->val_rrset_section - 1, !ns_o_update),
            get_rr_string(val_rrset_rec->val_rrset_data, buf1, 2048),
            get_rr_string(val_rrset_rec->val_rrset_sig, buf2, 2048));
}
    void TestArchivingOfCell() throw(Exception)
    {
        OutputFileHandler handler("archive", false);
        handler.SetArchiveDirectory();
        std::string archive_filename = handler.GetOutputDirectoryFullPath() + "cell.arch";

        // Archive a cell
        {
            SimulationTime* p_simulation_time = SimulationTime::Instance();
            p_simulation_time->SetEndTimeAndNumberOfTimeSteps(2.0, 4);

            // Create mutation state
            boost::shared_ptr<AbstractCellProperty> p_healthy_state(CellPropertyRegistry::Instance()->Get<WildTypeCellMutationState>());
            boost::shared_ptr<AbstractCellProperty> p_type(CellPropertyRegistry::Instance()->Get<StemCellProliferativeType>());

            // Create cell-cycle model
            FixedDurationGenerationBasedCellCycleModel* p_cell_model = new FixedDurationGenerationBasedCellCycleModel();

            // Create SRN
            Goldbeter1991SrnModel* p_srn_model = new Goldbeter1991SrnModel();

            // Create cell property collection
            CellPropertyCollection collection;
            MAKE_PTR(CellLabel, p_label);
            collection.AddProperty(p_label);

            // Create cell
            CellPtr p_cell(new Cell(p_healthy_state, p_cell_model, p_srn_model,  false, collection));
            p_cell->SetCellProliferativeType(p_type);
            p_cell->InitialiseCellCycleModel();
            p_cell->InitialiseSrnModel();
            p_simulation_time->IncrementTimeOneStep();

            TS_ASSERT_EQUALS(p_cell->GetAge(), 0.5);
            TS_ASSERT_EQUALS(p_cell->GetAncestor(), UNSIGNED_UNSET);

            // Set ancestor
            MAKE_PTR_ARGS(CellAncestor, p_cell_ancestor, (2u));
            p_cell->SetAncestor(p_cell_ancestor);
            TS_ASSERT_EQUALS(p_cell->GetAncestor(), 2u);

            // Set CellVecData with some actual content
            boost::shared_ptr<AbstractCellProperty> p_vec_data(CellPropertyRegistry::Instance()->Get<CellVecData>());
            p_cell->AddCellProperty(p_vec_data);
            Vec item_1 = PetscTools::CreateAndSetVec(2, -17.3); // <-17.3, -17.3>
            p_cell->GetCellVecData()->SetItem("item 1", item_1);

            // Check properties set correctly
            CellPropertyCollection& final_collection = p_cell->rGetCellPropertyCollection();
            TS_ASSERT_EQUALS(final_collection.GetSize(), 7u);
            TS_ASSERT_EQUALS(final_collection.HasProperty<WildTypeCellMutationState>(), true);
            TS_ASSERT_EQUALS(final_collection.HasProperty<ApcOneHitCellMutationState>(), false);
            TS_ASSERT_EQUALS(final_collection.HasProperty<ApcTwoHitCellMutationState>(), false);
            TS_ASSERT_EQUALS(final_collection.HasProperty<CellLabel>(), true);
            TS_ASSERT_EQUALS(final_collection.HasPropertyType<AbstractCellProperty>(), true);
            TS_ASSERT_EQUALS(final_collection.HasPropertyType<AbstractCellMutationState>(), true);
            TS_ASSERT_EQUALS(final_collection.HasPropertyType<CellAncestor>(), true);
            TS_ASSERT_EQUALS(final_collection.HasPropertyType<CellId>(), true);
            TS_ASSERT_EQUALS(p_cell->GetAncestor(), 2u);

            for (CellPropertyCollection::Iterator it = final_collection.Begin(); it != final_collection.End(); ++it)
            {
                TS_ASSERT_EQUALS(final_collection.HasProperty(*it), true);

                bool is_wildtype = (*it)->IsType<WildTypeCellMutationState>();
                bool is_label = (*it)->IsType<CellLabel>();
                bool is_ancestor = (*it)->IsType<CellAncestor>();
                bool is_cellid = (*it)->IsType<CellId>();
                bool is_data = (*it)->IsType<CellData>();
                bool is_vec_data = (*it)->IsType<CellVecData>();
                bool is_stem = (*it)->IsType<StemCellProliferativeType>();

                bool is_any_of_above = is_wildtype || is_label || is_ancestor || is_cellid || is_data || is_vec_data || is_stem;
                TS_ASSERT_EQUALS(is_any_of_above, true);
            }

            // Create another cell
            boost::shared_ptr<AbstractCellProperty> p_another_healthy_state(CellPropertyRegistry::Instance()->Get<WildTypeCellMutationState>());
            FixedDurationGenerationBasedCellCycleModel* p_another_cell_model = new FixedDurationGenerationBasedCellCycleModel();
            Goldbeter1991SrnModel* p_another_srn_model = new Goldbeter1991SrnModel();
            CellPtr p_another_cell(new Cell(p_another_healthy_state, p_another_cell_model, p_another_srn_model, false, collection));
            boost::shared_ptr<AbstractCellProperty> p_another_vec_data(new CellVecData);
            p_another_cell->AddCellProperty(p_another_vec_data);
            TS_ASSERT_EQUALS(p_cell->GetCellVecData()->GetNumItems(), 1u);
            TS_ASSERT_EQUALS(p_another_cell->GetCellVecData()->GetNumItems(), 0u);
            Vec another_item_1 = PetscTools::CreateAndSetVec(2, 42.0); // <42, 42>

            p_another_cell->GetCellVecData()->SetItem("item 1", another_item_1);

            // Create an output archive
            std::ofstream ofs(archive_filename.c_str());
            boost::archive::text_oarchive output_arch(ofs);

            CellPtr const p_const_cell = p_cell;

            // Write the cell to the archive
            output_arch << static_cast<const SimulationTime&> (*p_simulation_time);
            output_arch << p_const_cell;
            // Write the second cell also
            CellPtr const p_another_const_cell = p_another_cell;
            output_arch << p_another_const_cell;

            // Tidy up
            SimulationTime::Destroy();
            PetscTools::Destroy(item_1);
            PetscTools::Destroy(another_item_1);
        }

        // Restore CellPtr
        {
            // Need to set up time to initialize a cell
            SimulationTime* p_simulation_time = SimulationTime::Instance();
            p_simulation_time->SetStartTime(1.0);
            p_simulation_time->SetEndTimeAndNumberOfTimeSteps(2.0, 1); // will be restored

            // Initialize a cell

            CellPtr p_cell;

            // Restore the cell
            std::ifstream ifs(archive_filename.c_str(), std::ios::binary);
            boost::archive::text_iarchive input_arch(ifs);

            input_arch >> *p_simulation_time;
            input_arch >> p_cell;

            // Check the simulation time has been restored (through the cell)
            TS_ASSERT_EQUALS(p_simulation_time->GetTime(), 0.5);
            TS_ASSERT_EQUALS(p_simulation_time->GetTimeStep(), 0.5);

            TS_ASSERT_EQUALS(p_cell->GetAge(), 0.5);
            TS_ASSERT_EQUALS(static_cast<FixedDurationGenerationBasedCellCycleModel*>(p_cell->GetCellCycleModel())->GetGeneration(), 0u);
            TS_ASSERT(dynamic_cast<Goldbeter1991SrnModel*>(p_cell->GetSrnModel()));
            TS_ASSERT_EQUALS(p_cell->GetCellProliferativeType()->IsType<StemCellProliferativeType>(), true);

            AbstractCellCycleModel* p_cc_model = p_cell->GetCellCycleModel();
            TS_ASSERT_EQUALS(p_cc_model->GetCell(), p_cell);

            AbstractSrnModel* p_srn_model = p_cell->GetSrnModel();
            TS_ASSERT_EQUALS(p_srn_model->GetCell(), p_cell);

            CellPropertyCollection& collection = p_cell->rGetCellPropertyCollection();
            TS_ASSERT_EQUALS(collection.GetSize(), 7u);
            TS_ASSERT_EQUALS(collection.HasProperty<WildTypeCellMutationState>(), true);
            TS_ASSERT_EQUALS(collection.HasProperty<ApcOneHitCellMutationState>(), false);
            TS_ASSERT_EQUALS(collection.HasProperty<ApcTwoHitCellMutationState>(), false);
            TS_ASSERT_EQUALS(collection.HasProperty<CellLabel>(), true);
            TS_ASSERT_EQUALS(collection.HasPropertyType<AbstractCellProperty>(), true);
            TS_ASSERT_EQUALS(collection.HasPropertyType<AbstractCellMutationState>(), true);
            TS_ASSERT_EQUALS(collection.HasPropertyType<CellAncestor>(), true);
            TS_ASSERT_EQUALS(collection.HasPropertyType<CellId>(), true);
            TS_ASSERT_EQUALS(p_cell->GetAncestor(), 2u);

            // Check explicitly for CellVecData as it is not available by default as CellData
            TS_ASSERT_EQUALS(collection.HasPropertyType<CellVecData>(), true);

            // Check that the Vec stored in CellVecData was unarchived correctly
            boost::shared_ptr<CellVecData> p_cell_vec_data = boost::static_pointer_cast<CellVecData>(collection.GetPropertiesType<CellVecData>().GetProperty());
            PetscInt vec_size;
            VecGetSize(p_cell_vec_data->GetItem("item 1"), &vec_size);
            TS_ASSERT_EQUALS(vec_size, 2);
            ReplicatableVector rep_item_1(p_cell_vec_data->GetItem("item 1"));
            TS_ASSERT_DELTA(rep_item_1[0], -17.3, 2e-14);

            for (CellPropertyCollection::Iterator it = collection.Begin(); it != collection.End(); ++it)
            {
                TS_ASSERT_EQUALS(collection.HasProperty(*it), true);

                bool is_wildtype = (*it)->IsType<WildTypeCellMutationState>();
                bool is_label = (*it)->IsType<CellLabel>();
                bool is_ancestor = (*it)->IsType<CellAncestor>();
                bool is_cellid = (*it)->IsType<CellId>();
                bool is_data = (*it)->IsType<CellData>();
                bool is_vec_data = (*it)->IsType<CellVecData>();
                bool is_stem = (*it)->IsType<StemCellProliferativeType>();

                bool is_any_of_above = is_wildtype || is_label || is_ancestor || is_cellid || is_data || is_vec_data || is_stem;
                TS_ASSERT_EQUALS(is_any_of_above, true);
            }

            // Try another cell
            CellPtr p_another_cell;
            input_arch >> p_another_cell;
            ReplicatableVector rep_another_item_1(p_another_cell->GetCellVecData()->GetItem("item 1"));
            TS_ASSERT_DELTA(rep_another_item_1[0], 42.0, 2e-14);
        }
    }
Exemple #8
0
void
val_log_authentication_chain(const val_context_t * ctx, int level,
                             const char * name_p, int class_h,
                             int type_h,
                             struct val_result_chain *results)
{
    struct val_result_chain *next_result;
    int real_type_h;
    int real_class_h;

    if (results == NULL) { 
        return;
    } 
    
    for (next_result = results; next_result;
         next_result = next_result->val_rc_next) {
        struct val_authentication_chain *next_as;
        int             i;

        /* Display the correct owner name, class,type for the record */
        if (next_result->val_rc_rrset) {
            real_type_h = next_result->val_rc_rrset->val_rrset_type; 
            real_class_h = next_result->val_rc_rrset->val_rrset_class; 
        } else {
            real_type_h = type_h;
            real_class_h = class_h;
        }

        if (val_isvalidated(next_result->val_rc_status)) {
            val_log(ctx, level, "Validation result for {%s, %s(%d), %s(%d)}: %s:%d (Validated)",
                    name_p, p_class(real_class_h), real_class_h,
                    p_type(real_type_h), real_type_h,
                    p_val_status(next_result->val_rc_status),
                    next_result->val_rc_status);
        } else if (val_istrusted(next_result->val_rc_status)) {
            val_log(ctx, level, "Validation result for {%s, %s(%d), %s(%d)}: %s:%d (Trusted but not Validated)",
                    name_p, p_class(real_class_h), real_class_h,
                    p_type(real_type_h), real_type_h,
                    p_val_status(next_result->val_rc_status),
                    next_result->val_rc_status);
        } else {
            val_log(ctx, level, "Validation result for {%s, %s(%d), %s(%d)}: %s:%d (Untrusted)",
                    name_p, p_class(real_class_h), real_class_h,
                    p_type(real_type_h), real_type_h,
                    p_val_status(next_result->val_rc_status),
                    next_result->val_rc_status);
        }

        for (next_as = next_result->val_rc_answer; next_as;
             next_as = next_as->val_ac_trust) {

            if (next_as->val_ac_rrset == NULL) {
                val_log(ctx, level, "    Assertion status = %s:%d",
                        p_ac_status(next_as->val_ac_status),
                        next_as->val_ac_status);
            } else {
                const char   *t_name;
                t_name = next_as->val_ac_rrset->val_rrset_name;
                if (t_name == NULL)
                    t_name = (const char *) "NULL_DATA";

                val_log_assertion_pfx(ctx, level, "    ", t_name,
                                      next_as);
                //                val_log_val_rrset_pfx(ctx, level, "     ",
                //                                  next_as->val_ac_rrset);
            }
        }

        for (i = 0; i < next_result->val_rc_proof_count; i++) {
            val_log(ctx, level, "    Proof of non-existence [%d of %d]", 
                    i+1, next_result->val_rc_proof_count);
            for (next_as = next_result->val_rc_proofs[i]; next_as;
                 next_as = next_as->val_ac_trust) {
                if (next_as->val_ac_rrset == NULL) {
                    val_log(ctx, level, "      Assertion status = %s:%d",
                            p_ac_status(next_as->val_ac_status),
                            next_as->val_ac_status);
                } else {
                    const char   *t_name;
                    t_name = next_as->val_ac_rrset->val_rrset_name;
                    if (t_name == NULL)
                        t_name = (const char *) "NULL_DATA";

                    val_log_assertion_pfx(ctx, level, "      ", t_name,
                                          next_as);
                }
            }
        }
    }
}
Exemple #9
0
static void
do_section (int pfcode, ns_msg *handle, ns_sect section, int pflag, FILE *file)
{
	int n, sflag, rrnum;
	static int buflen = 2048;
	char *buf;
	ns_opcode opcode;
	ns_rr rr;

	/*
	 * Print answer records.
	 */
	sflag = (pfcode & pflag);
	if (pfcode && !sflag)
		return;

	buf = malloc(buflen);
	if (buf == NULL) {
		fprintf(file, ";; memory allocation failure\n");
		return;
	}

	opcode = (ns_opcode) ns_msg_getflag(*handle, ns_f_opcode);
	rrnum = 0;
	for (;;) {
		if (ns_parserr(handle, section, rrnum, &rr)) {
			if (errno != ENODEV)
				fprintf(file, ";; ns_parserr: %s\n",
					strerror(errno));
			else if (rrnum > 0 && sflag != 0 &&
				 (pfcode & RES_PRF_HEAD1))
				putc('\n', file);
			goto cleanup;
		}
		if (rrnum == 0 && sflag != 0 && (pfcode & RES_PRF_HEAD1))
			fprintf(file, ";; %s SECTION:\n",
				p_section(section, opcode));
		if (section == ns_s_qd)
			fprintf(file, ";;\t%s, type = %s, class = %s\n",
				ns_rr_name(rr),
				p_type(ns_rr_type(rr)),
				p_class(ns_rr_class(rr)));
		else {
			n = ns_sprintrr(handle, &rr, NULL, NULL,
					buf, buflen);
			if (n < 0) {
				if (errno == ENOSPC) {
					free(buf);
					buf = NULL;
					if (buflen < 131072)
						buf = malloc(buflen += 1024);
					if (buf == NULL) {
						fprintf(file,
					      ";; memory allocation failure\n");
					      return;
					}
					continue;
				}
				fprintf(file, ";; ns_sprintrr: %s\n",
					strerror(errno));
				goto cleanup;
			}
			fputs(buf, file);
			fputc('\n', file);
		}
		rrnum++;
	}
 cleanup:
	free(buf);
}
Exemple #10
0
void
val_log_assertion_pfx(const val_context_t * ctx, int level,
                      const char *prefix, const char * name_pr,
                      struct val_authentication_chain *next_as)
{
    char            name_buf[INET6_ADDRSTRLEN + 1];
    const char     *serv_pr;
    int             tag = 0;
    int             class_h;
    int             type_h;
    struct          val_rr_rec  *data;
    struct          sockaddr *serv;
    val_astatus_t   status;
    struct val_rr_rec  *curkey;
#undef VAL_LOG_SIG
#ifdef VAL_LOG_SIG
    struct          val_rr_rec  *sig;
    struct val_rr_rec  *cursig;
#endif


    if (next_as == NULL)
        return;

    class_h = next_as->val_ac_rrset->val_rrset_class;
    type_h = next_as->val_ac_rrset->val_rrset_type;
    data = next_as->val_ac_rrset->val_rrset_data;
#ifdef VAL_LOG_SIG
    sig = next_as->val_ac_rrset->val_rrset_sig;
#endif
    serv = next_as->val_ac_rrset->val_rrset_server;
    status = next_as->val_ac_status;

    if (NULL == prefix)
        prefix = "";

    if (serv)
        serv_pr =
            ((serv_pr =
              val_get_ns_string(serv, name_buf, sizeof(name_buf))) == NULL) ?  "VAL_CACHE" : serv_pr;
    else
        serv_pr = "NULL";

    if (type_h == ns_t_dnskey) {
        for (curkey = data; curkey; curkey = curkey->rr_next) {
            if ((curkey->rr_status == VAL_AC_VERIFIED_LINK) ||
                (curkey->rr_status == VAL_AC_TRUST_POINT) ||
                (curkey->rr_status == VAL_AC_UNKNOWN_ALGORITHM_LINK)) {
                /*
                 * Extract the key tag 
                 */
                val_dnskey_rdata_t dnskey;
                if (VAL_NO_ERROR != val_parse_dnskey_rdata(curkey->rr_rdata,
                                       curkey->rr_rdata_length, &dnskey)) {
                    val_log(ctx, LOG_INFO, "val_log_assertion_pfx(): Cannot parse DNSKEY data");
                } else {
                    tag = dnskey.key_tag;
                    if (dnskey.public_key)
                        FREE(dnskey.public_key);
                }
                break;
            }
        }
    }

    if (tag != 0) {
        val_log(ctx, level,
                "%sname=%s class=%s type=%s[tag=%d] from-server=%s "
                "status=%s:%d", prefix, name_pr, p_class(class_h),
                p_type(type_h), tag, serv_pr, p_ac_status(status), status);
    } else {
        val_log(ctx, level,
                "%sname=%s class=%s type=%s from-server=%s status=%s:%d",
                prefix, name_pr, p_class(class_h), p_type(type_h), serv_pr,
                p_ac_status(status), status);
    }
#ifdef VAL_LOG_SIG
    for (cursig = sig; cursig; cursig = cursig->rr_next) {
        char incpTime[1028];
        char exprTime[1028];
        struct timeval  tv_sig;
        val_rrsig_rdata_t rrsig;

        val_parse_rrsig_rdata(cursig->rr_rdata, cursig->rr_rdata_length, &rrsig);

        memset(&tv_sig, 0, sizeof(tv_sig));
        tv_sig.tv_sec = rrsig.sig_incp;
        GET_TIME_BUF((const time_t *)(&tv_sig.tv_sec), incpTime);

        memset(&tv_sig, 0, sizeof(tv_sig));
        tv_sig.tv_sec = rrsig.sig_expr;
        GET_TIME_BUF((const time_t *)(&tv_sig.tv_sec), exprTime);

        val_log(ctx, level,
                "%s    ->tag=%d status=%s sig-incep=%s sig-expr=%s",
                prefix, rrsig.key_tag,
                p_ac_status(cursig->rr_status),
                incpTime, exprTime);
    }
#endif

#ifdef VAL_LOG_SIG
    struct val_rr_rec  *rr;
    struct val_rr_rec  *sig = next_as->val_ac_rrset->val_rrset_sig;
    for (rr = data; rr; rr = rr->rr_next) {
        val_log(ctx, level, "    data_status=%s:%d",
                p_ac_status(rr->rr_status), rr->rr_status);
    }
    for (rr = sig; rr; rr = rr->rr_next) {
        val_log(ctx, level, "    sig_status=%s:%d",
                p_ac_status(rr->rr_status), rr->rr_status);
    }
#endif
}
int main(int argc, char *argv[])
{
    if (argc != 2) {
        fprintf(stderr, "usage: %s /path/to/elf64_file\n", argv[0]);
        return 1;
    }

    int fd;
    struct stat buf;
    u8 *f;

    fd = open(argv[1], O_RDONLY);
    if (fd == -1) {
        perror("open");
        return 1;
    }

    if (fstat(fd, &buf) == -1) {
        perror("fstat");
        return 1;
    }

    f = mmap(NULL, buf.st_size, PROT_READ, MAP_SHARED, fd, 0);
    if (f == MAP_FAILED) {
        perror("mmap");
        return 1;
    }

    Elf64_Ehdr *elf_header = (Elf64_Ehdr *)f;
    printf("ELF header:\n");
    printf("    header size = %#x\n", elf_header->e_ehsize);
    printf("    program header table at = %#lx, entry count = %d, entry size = %#x\n",
                                    elf_header->e_phoff,
                                    elf_header->e_phnum,
                                    elf_header->e_phentsize);
    printf("    section header table at = %#lx, entry count = %d, entry size = %#x\n",
                                    elf_header->e_shoff,
                                    elf_header->e_shnum,
                                    elf_header->e_shentsize);
    printf("    e_entry = %#lx\n", elf_header->e_entry);
    printf("    e_type  = %#x (ET_EXEC = %#x, ET_DYN = %#x, ET_CORE = %#x)\n",
                                elf_header->e_type,
                                ET_EXEC,
                                ET_DYN,
                                ET_CORE);
    printf("    e_machine = %#x (ET_X86_64 = %#x)\n", elf_header->e_machine, EM_X86_64);
    printf("    e_shstrndx = %d\n", elf_header->e_shstrndx);

    printf("\nProgram header table:\n");
    Elf64_Phdr *program_header_table = (Elf64_Phdr *)(f + elf_header->e_phoff);
    int i;
    Elf64_Phdr *ph;
    u8 *pt_note;
    int pt_note_count, pt_note_namesize, pt_note_descsize;
    Elf64_Dyn *dyn;
    for (i = 0; i < elf_header->e_phnum; i++) {
        ph = program_header_table + i;
        printf("    %4d: ", i);
        printf("type = %-16s", p_type(ph->p_type));
        if (ph->p_flags & PF_R) {
            printf("R");
        }
        if (ph->p_flags & PF_W) {
            printf("W");
        }
        if (ph->p_flags & PF_X) {
            printf("X");
        }
        printf("\t");
        printf("offset = %#lx size = %ld ", ph->p_offset, ph->p_filesz);
        if (ph->p_type == PT_LOAD) {
            printf("p_vaddr = %#lx p_memsz = %#lx ", ph->p_vaddr, ph->p_memsz);
        }
        printf("\n");
        if (ph->p_type == PT_INTERP) {
            printf("\t\t%s\n", (char *)(f + ph->p_offset));
        }
        if (ph->p_type == PT_NOTE) {
            pt_note = (u8 *)(f + ph->p_offset);
            while (pt_note_count < ph->p_filesz) {
                printf("\t\t");
                pt_note_namesize = (u32)(*pt_note);
                printf("name size = %d, ", pt_note_namesize);
                pt_note += 4;
                pt_note_count += 4;
                pt_note_descsize = (u32)(*pt_note);
                printf("desc size = %d, ", pt_note_descsize);
                pt_note += 4;
                pt_note_count += 4;
                printf("type = %d\n", (u32)(*pt_note));
                pt_note += 4;
                pt_note_count += 4;
                printf("\t\tname: ");
                while (pt_note_namesize--) {
                    printf("%#x ", *pt_note);
                    if (*pt_note) {
                        printf("(%c) ", *pt_note);
                    }
                    pt_note++;
                    pt_note_count++;
                }
                printf("\n");
                printf("\t\tdesc: ");
                while (pt_note_descsize--) {
                    printf("%#x ", *pt_note);
                    pt_note++;
                    pt_note_count++;
                }
                printf("\n");
            }
        } else if (ph->p_type == PT_DYNAMIC) {
            dyn = (Elf64_Dyn *)(f + ph->p_offset);
            while (dyn->d_tag != DT_NULL) {
                printf("\t\td_tag = %-20s d_un = %#lx\n", d_tag(dyn->d_tag), dyn->d_un.d_val);
                dyn = dyn + 1;
            }
        }
    }

    Elf64_Shdr *section_header_table = (Elf64_Shdr *)(f + elf_header->e_shoff);
    Elf64_Shdr *name_sh = NULL;
    printf("\nFind section name string table:\n");
    if (elf_header->e_shstrndx != SHN_UNDEF) {
        name_sh = section_header_table + elf_header->e_shstrndx;
        printf("    offset = %#lx, size = %ld\n", name_sh->sh_offset, name_sh->sh_size);
    }

    printf("\nSection header table:\n");
    Elf64_Shdr *sh;
    Elf64_Shdr *symtab_sh = NULL, *dynsym_sh = NULL,
               *strtab_sh = NULL, *dynstr_sh = NULL,
               *got_sh    = NULL, *gotplt_sh = NULL;
    char *name;
    Elf64_Rela *rela_sh;
    int rela_count, rela_idx;
    for (i = 0; i < elf_header->e_shnum; i++) {
        sh = section_header_table + i;
        printf("    %4d: ", i);
        if (name_sh) {
            name = (char *)(f + name_sh->sh_offset + sh->sh_name);
            printf("name = %-20s ", name);
            if (sh->sh_type == SHT_STRTAB) {
                if (strcmp(name, ".strtab") == 0) {
                    strtab_sh = sh;
                } else if (strcmp(name, ".dynstr") == 0) {
                    dynstr_sh = sh;
                }
            }
            if (strcmp(name, ".got") == 0) {
                got_sh = sh;
            }
            if (strcmp(name, ".got.plt") == 0) {
                gotplt_sh = sh;
            }
        }
        printf("type = %-16s ", sh_type(sh->sh_type));
        printf("offset = %#lx ", sh->sh_offset);
        printf("size = %ld ", sh->sh_size);
        printf("\n");
        if (sh->sh_type == SHT_SYMTAB) {
            symtab_sh = sh;
        } else if (sh->sh_type == SHT_DYNSYM) {
            dynsym_sh = sh;
        } else if (sh->sh_type == SHT_RELA) {
            printf("\t\tsh_link = %s, sh_info = %s\n",
                                (f + name_sh->sh_offset + (section_header_table + sh->sh_link)->sh_name),
                                (f + name_sh->sh_offset + (section_header_table + sh->sh_info)->sh_name));
            rela_sh = (Elf64_Rela *)(f + sh->sh_offset);
            rela_count = sh->sh_size / sizeof(Elf64_Rela);
            rela_idx = 0;
            while (rela_idx < rela_count - 1) {
                rela_sh = rela_sh + 1;
                printf("\t\tr_offset = %#lx, r_info = (SYM = %lu, TYPE = %#lx), r_addend = %#lx\n",
                                    rela_sh->r_offset,
                                    ELF64_R_SYM(rela_sh->r_info),
                                    ELF64_R_TYPE(rela_sh->r_info),
                                    rela_sh->r_addend);
                rela_idx++;
            }
        }
    }

    if (symtab_sh && strtab_sh) {
        printf("\nFound symbol table:\n");
        Elf64_Sym *symtab = (Elf64_Sym *)(f + symtab_sh->sh_offset);
        int count = symtab_sh->sh_size / symtab_sh->sh_entsize;
        Elf64_Sym *sym;
        for (i = 0; i < count; i++) {
            sym = symtab + i;
            printf("    %d: ", i);
            printf("name = %-30s ", f + strtab_sh->sh_offset + sym->st_name);
            printf("value = %#-8lx   ", sym->st_value);
            printf("size = %#-8lx ", sym->st_size);
            printf("type = %-16s ", symbol_type(sym->st_info));
            printf("binding = %-16s ", symbol_binding(sym->st_info));
            printf("defined section index = ");
            if (sym->st_shndx > 0 && sym->st_shndx < elf_header->e_shnum - 1) {
                printf("%s", f + name_sh->sh_offset + (section_header_table + sym->st_shndx)->sh_name);
            } else {
                printf("%s", special_seciton_name(sym->st_shndx));
            }
            printf("\n");
        }
    }

    if (dynsym_sh && dynstr_sh) {
        printf("\nFound dynamic linking symbol table:\n");
        Elf64_Sym *symtab = (Elf64_Sym *)(f + dynsym_sh->sh_offset);
        int count = dynsym_sh->sh_size / dynsym_sh->sh_entsize;
        Elf64_Sym *sym;
        for (i = 0; i < count; i++) {
            sym = symtab + i;
            printf("    %d: ", i);
            printf("name = %-30s ", f + dynstr_sh->sh_offset + sym->st_name);
            printf("value = %#-8lx   ", sym->st_value);
            printf("size = %#-8lx ", sym->st_size);
            printf("type = %-16s ", symbol_type(sym->st_info));
            printf("binding = %-16s ", symbol_binding(sym->st_info));
            printf("defined section index = ");
            if (sym->st_shndx > 0 && sym->st_shndx < elf_header->e_shnum - 1) {
                printf("%s", f + name_sh->sh_offset + (section_header_table + sym->st_shndx)->sh_name);
            } else {
                printf("%s", special_seciton_name(sym->st_shndx));
            }
            printf("\n");
        }
    }

    if (got_sh) {
        printf("\nGOT:\n");
        int count = got_sh->sh_size / 8;
        uint64_t *got = (uint64_t *)(f + got_sh->sh_offset);
        for (i = 0; i < count; i++) {
            printf("%d: %#lx\n", i, *got);
            got++;
        }
    }

    if (gotplt_sh) {
        printf("\nGOT.PLT:\n");
        int count = gotplt_sh->sh_size / 8;
        uint64_t *gotplt = (uint64_t *)(f + gotplt_sh->sh_offset);
        for (i = 0; i < count; i++) {
            printf("%d: %#lx\n", i, *gotplt);
            gotplt++;
        }
    }

    munmap(f, buf.st_size);
    close(fd);

    return 0;
}
Exemple #12
0
void txtout_output(const char* descr, iaddr from, iaddr to, uint8_t proto, unsigned flags,
    unsigned sport, unsigned dport, my_bpftimeval ts,
    const u_char* pkt_copy, unsigned olen,
    const u_char* payload, unsigned payloadlen)
{
    /*
     * Short output, only print QTYPE and QNAME for IN records
     */
    if (opt_s) {
        if (flags & DNSCAP_OUTPUT_ISDNS) {
            ns_msg msg;
            int    qdcount, err = 0;
            ns_rr  rr;
            if (ns_initparse(payload, payloadlen, &msg) < 0) {
                if (tcpstate_getcurr && tcpstate_reset)
                    tcpstate_reset(tcpstate_getcurr(), "");
                return;
            }
            qdcount = ns_msg_count(msg, ns_s_qd);

            if (qdcount > 0 && 0 == (err = ns_parserr(&msg, ns_s_qd, 0, &rr)) && ns_rr_class(rr) == 1) {
                fprintf(out, "%s %s\n",
                    p_type(ns_rr_type(rr)),
                    ns_rr_name(rr));
            }
            if (err < 0) {
                if (tcpstate_getcurr && tcpstate_reset)
                    tcpstate_reset(tcpstate_getcurr(), "");
            }
        }
        return;
    }

    /*
     * IP Stuff
     */
    fprintf(out, "%10ld.%06ld", (long)ts.tv_sec, (long)ts.tv_usec);
    fprintf(out, " %s %u", ia_str(from), sport);
    fprintf(out, " %s %u", ia_str(to), dport);
    fprintf(out, " %hhu", proto);

    if (flags & DNSCAP_OUTPUT_ISDNS) {
        ns_msg msg;
        int    qdcount, err = 0;
        ns_rr  rr;
        if (ns_initparse(payload, payloadlen, &msg) < 0) {
            if (tcpstate_getcurr && tcpstate_reset)
                tcpstate_reset(tcpstate_getcurr(), "");
            fprintf(out, "\n");
            return;
        }

        /*
         * DNS Header
         */
        fprintf(out, " %u", ns_msg_id(msg));
        fprintf(out, " %u", ns_msg_getflag(msg, ns_f_opcode));
        fprintf(out, " %u", ns_msg_getflag(msg, ns_f_rcode));
        fprintf(out, " |");
        if (ns_msg_getflag(msg, ns_f_qr))
            fprintf(out, "QR|");
        if (ns_msg_getflag(msg, ns_f_aa))
            fprintf(out, "AA|");
        if (ns_msg_getflag(msg, ns_f_tc))
            fprintf(out, "TC|");
        if (ns_msg_getflag(msg, ns_f_rd))
            fprintf(out, "RD|");
        if (ns_msg_getflag(msg, ns_f_ra))
            fprintf(out, "RA|");
        if (ns_msg_getflag(msg, ns_f_ad))
            fprintf(out, "AD|");
        if (ns_msg_getflag(msg, ns_f_cd))
            fprintf(out, "CD|");

        qdcount = ns_msg_count(msg, ns_s_qd);
        if (qdcount > 0 && 0 == (err = ns_parserr(&msg, ns_s_qd, 0, &rr))) {
            fprintf(out, " %s %s %s",
                p_class(ns_rr_class(rr)),
                p_type(ns_rr_type(rr)),
                ns_rr_name(rr));
        }
        if (err < 0) {
            if (tcpstate_getcurr && tcpstate_reset)
                tcpstate_reset(tcpstate_getcurr(), "");
        }
    }
    /*
     * Done
     */
    fprintf(out, "\n");
}
/*
 * Print resource record fields in human readable form.
 */
char *
p_rr(char *cp, char *msg, FILE *file)
{
	int type, class, dlen, n, c;
	struct in_addr inaddr;
	char *cp1, *cp2;

	if ((cp = p_cdname(cp, msg, file)) == NULL)
		return (NULL);			/* compression error */
	fprintf(file,"\n\ttype = %s", p_type(type = _getshort(cp)));
	cp += sizeof(u_short);
	fprintf(file,", class = %s", p_class(class = _getshort(cp)));
	cp += sizeof(u_short);
	fprintf(file,", ttl = %s", p_time(_getlong(cp)));
	cp += sizeof(u_long);
	fprintf(file,", dlen = %d\n", dlen = _getshort(cp));
	cp += sizeof(u_short);
	cp1 = cp;
	/*
	 * Print type specific data, if appropriate
	 */
	switch (type) {
	case T_A:
		switch (class) {
		case C_IN:
		case C_HS:
			bcopy(cp, (char *)&inaddr, sizeof(inaddr));
			if (dlen == 4) {
				fprintf(file,"\tinternet address = %s\n",
					inet_ntoa(inaddr));
				cp += dlen;
			} else if (dlen == 7) {
				fprintf(file,"\tinternet address = %s",
					inet_ntoa(inaddr));
				fprintf(file,", protocol = %d", cp[4]);
				fprintf(file,", port = %d\n",
					(cp[5] << 8) + cp[6]);
				cp += dlen;
			}
			break;
		default:
			cp += dlen;
		}
		break;
	case T_CNAME:
	case T_MB:
	case T_MG:
	case T_MR:
	case T_NS:
	case T_PTR:
		fprintf(file,"\tdomain name = ");
		cp = p_cdname(cp, msg, file);
		fprintf(file,"\n");
		break;

	case T_HINFO:
		if (n = *cp++) {
			fprintf(file,"\tCPU=%.*s\n", n, cp);
			cp += n;
		}
		if (n = *cp++) {
			fprintf(file,"\tOS=%.*s\n", n, cp);
			cp += n;
		}
		break;

	case T_SOA:
		fprintf(file,"\torigin = ");
		cp = p_cdname(cp, msg, file);
		fprintf(file,"\n\tmail addr = ");
		cp = p_cdname(cp, msg, file);
		fprintf(file,"\n\tserial = %ld", _getlong(cp));
		cp += sizeof(u_long);
		fprintf(file,"\n\trefresh = %s", p_time(_getlong(cp)));
		cp += sizeof(u_long);
		fprintf(file,"\n\tretry = %s", p_time(_getlong(cp)));
		cp += sizeof(u_long);
		fprintf(file,"\n\texpire = %s", p_time(_getlong(cp)));
		cp += sizeof(u_long);
		fprintf(file,"\n\tmin = %s\n", p_time(_getlong(cp)));
		cp += sizeof(u_long);
		break;

	case T_MX:
		fprintf(file,"\tpreference = %ld,",_getshort(cp));
		cp += sizeof(u_short);
		fprintf(file," name = ");
		cp = p_cdname(cp, msg, file);
		break;

  	case T_TXT:
		(void) fputs("\t\"", file);
		cp2 = cp1 + dlen;
		while (cp < cp2) {
			if (n = (unsigned char) *cp++) {
				for (c = n; c > 0 && cp < cp2; c--)
					if (*cp == '\n') {
					    (void) putc('\\', file);
					    (void) putc(*cp++, file);
					} else
					    (void) putc(*cp++, file);
			}
		}
		(void) fputs("\"\n", file);
  		break;

	case T_MINFO:
		fprintf(file,"\trequests = ");
		cp = p_cdname(cp, msg, file);
		fprintf(file,"\n\terrors = ");
		cp = p_cdname(cp, msg, file);
		break;

	case T_UINFO:
		fprintf(file,"\t%s\n", cp);
		cp += dlen;
		break;

	case T_UID:
	case T_GID:
		if (dlen == 4) {
			fprintf(file,"\t%ld\n", _getlong(cp));
			cp += sizeof(int);
		}
		break;

	case T_WKS:
		if (dlen < sizeof(u_long) + 1)
			break;
		bcopy(cp, (char *)&inaddr, sizeof(inaddr));
		cp += sizeof(u_long);
		fprintf(file,"\tinternet address = %s, protocol = %d\n\t",
			inet_ntoa(inaddr), *cp++);
		n = 0;
		while (cp < cp1 + dlen) {
			c = *cp++;
			do {
 				if (c & 0200)
					fprintf(file," %d", n);
 				c <<= 1;
			} while (++n & 07);
		}
		putc('\n',file);
		break;

#ifdef ALLOW_T_UNSPEC
	case T_UNSPEC:
		{
			int NumBytes = 8;
			char *DataPtr;
			int i;

			if (dlen < NumBytes) NumBytes = dlen;
			fprintf(file, "\tFirst %d bytes of hex data:",
				NumBytes);
			for (i = 0, DataPtr = cp; i < NumBytes; i++, DataPtr++)
				fprintf(file, " %x", *DataPtr);
			fputs("\n", file);
			cp += dlen;
		}
		break;
#endif /* ALLOW_T_UNSPEC */

	default:
		fprintf(file,"\t???\n");
		cp += dlen;
	}
	if (cp != cp1 + dlen) {
		fprintf(file,"packet size error (%#x != %#x)\n", cp, cp1+dlen);
		cp = NULL;
	}
	fprintf(file,"\n");
	return (cp);
}
Exemple #14
0
void
verify_next_assertion(val_context_t * ctx,
                      struct val_digested_auth_chain *as,
                      struct val_digested_auth_chain *the_trust,
                      u_int32_t flags)
{
    struct rrset_rec *the_set;
    struct rrset_rr  *the_sig;
    u_char       *signby_name_n;
    u_int16_t       signby_footprint_n;
    val_dnskey_rdata_t dnskey;
    int             is_a_wildcard;
    struct rrset_rr  *nextrr;
    struct rrset_rr  *keyrr;
    u_int16_t       tag_h;
    char            name_p[NS_MAXDNAME];

    if ((as == NULL) || (as->val_ac_rrset.ac_data == NULL) || (the_trust == NULL)) {
        val_log(ctx, LOG_INFO, "verify_next_assertion(): Cannot verify assertion - no data");
        return;
    }

    the_set = as->val_ac_rrset.ac_data;
    dnskey.public_key = NULL;


    if (-1 == ns_name_ntop(the_set->rrs_name_n, name_p, sizeof(name_p)))
        snprintf(name_p, sizeof(name_p), "unknown/error");

    if (the_set->rrs_sig == NULL) {
        val_log(ctx, LOG_INFO, "verify_next_assertion(): RRSIG is missing");
        as->val_ac_status = VAL_AC_RRSIG_MISSING;
        return;
    }

    if (the_set->rrs_type_h != ns_t_dnskey) {
        /*
         * trust path contains the key 
         */
        if (the_trust->val_ac_rrset.ac_data == NULL) {
            val_log(ctx, LOG_INFO, "verify_next_assertion(): Key is empty");
            as->val_ac_status = VAL_AC_DNSKEY_MISSING;
            return;
        }
        keyrr = the_trust->val_ac_rrset.ac_data->rrs_data;
    } else {
        /*
         * data itself contains the key 
         */
        if (the_set->rrs_data == NULL) {
            val_log(ctx, LOG_INFO, "verify_next_assertion(): Key is empty");
            as->val_ac_status = VAL_AC_DNSKEY_MISSING;
            return;
        }
        keyrr = the_set->rrs_data;
    }

    for (the_sig = the_set->rrs_sig;
         the_sig; the_sig = the_sig->rr_next) {

        /*
         * do wildcard processing 
         */
        if (!check_label_count(the_set, the_sig, &is_a_wildcard)) {
            SET_STATUS(as->val_ac_status, the_sig,
                       VAL_AC_WRONG_LABEL_COUNT);
            val_log(ctx, LOG_INFO, "verify_next_assertion(): Incorrect RRSIG label count");
            continue;
        }

        /*
         * for each sig, identify key, 
         */
        if (VAL_NO_ERROR != identify_key_from_sig(the_sig, &signby_name_n,
                              &signby_footprint_n)) {
            SET_STATUS(as->val_ac_status, the_sig,
                       VAL_AC_INVALID_RRSIG);
            val_log(ctx, LOG_INFO, "verify_next_assertion(): Cannot extract key footprint from RRSIG");
            continue;
        }

        tag_h = ntohs(signby_footprint_n);
        for (nextrr = keyrr; nextrr; nextrr = nextrr->rr_next) {
            int             is_verified = 0;
            if (VAL_NO_ERROR != val_parse_dnskey_rdata(nextrr->rr_rdata,
                                             nextrr->rr_rdata_length,
                                             &dnskey)) {
                val_log(ctx, LOG_INFO, "verify_next_assertion(): Cannot parse DNSKEY data");
                nextrr->rr_status = VAL_AC_INVALID_KEY;
                continue;
            }

            dnskey.next = NULL;
            if (dnskey.key_tag != tag_h) {
                if (dnskey.public_key != NULL) {
                    FREE(dnskey.public_key);
                    dnskey.public_key = NULL;
                }
                continue;
            }

            val_log(ctx, LOG_DEBUG, "verify_next_assertion(): Found potential matching DNSKEY for RRSIG");

            /*
             * check the signature 
             */
            is_verified = do_verify(ctx, signby_name_n,
                      &nextrr->rr_status,
                      &the_sig->rr_status,
                      the_set, the_sig, &dnskey, is_a_wildcard, flags);

            /*
             * There might be multiple keys with the same key tag; set this as
             * the signing key only if we dont have other status for this key
             */
            SET_STATUS(as->val_ac_status, the_sig, the_sig->rr_status);
            if (nextrr->rr_status == VAL_AC_UNSET) {
                nextrr->rr_status = VAL_AC_SIGNING_KEY;
            }

            if (is_verified) {

                val_log(ctx, LOG_INFO, "verify_next_assertion(): Verified a RRSIG for %s (%s) using a DNSKEY (%d)",
                        name_p, p_type(the_set->rrs_type_h),
                        dnskey.key_tag);

                if ( as->val_ac_status == VAL_AC_TRUST ||
                    nextrr->rr_status == VAL_AC_TRUST_POINT) {
                    /* we've verified a trust anchor */
                    as->val_ac_status = VAL_AC_TRUST; 
                    val_log(ctx, LOG_INFO, "verify_next_assertion(): verification traces back to trust anchor");
                    if (dnskey.public_key != NULL) {
                        FREE(dnskey.public_key);
                        dnskey.public_key = NULL;
                    }
                    return;
                }
            
                /* Check if we're trying to verify some key in the authentication chain */
                if ( the_set->rrs_type_h == ns_t_dnskey && 
                    as != the_trust) {
                    /* Check if we have reached our trust key */
                    /*
                     * If this record contains a DNSKEY, check if the DS record contains this key 
                     * DNSKEYs cannot be wildcard expanded, so VAL_AC_WCARD_VERIFIED does not
                     * count as a good sig
                     * Create the link even if the DNSKEY algorithm is unknown since this 
                     * may be the provably insecure case
                     */
                    /*
                     * follow the trust path 
                     */
                    struct rrset_rr  *dsrec =
                        the_trust->val_ac_rrset.ac_data->rrs_data;
                    while (dsrec) {
                        val_ds_rdata_t  ds;
                        ds.d_hash = NULL;
                        int retval = val_parse_ds_rdata(dsrec->rr_rdata,
                                       dsrec->rr_rdata_length, &ds);
                        if(retval == VAL_NOT_IMPLEMENTED) {
                            val_log(ctx, LOG_INFO, "verify_next_assertion(): DS hash not supported");
                            dsrec->rr_status = VAL_AC_ALGORITHM_NOT_SUPPORTED;
                        } else if (retval != VAL_NO_ERROR) {
                            val_log(ctx, LOG_INFO, "verify_next_assertion(): DS parse error");
                            dsrec->rr_status = VAL_AC_INVALID_DS;
                        } else if (DNSKEY_MATCHES_DS(ctx, &dnskey, &ds, 
                                    the_set->rrs_name_n, nextrr, 
                                    &dsrec->rr_status)) {
                            val_log(ctx, LOG_DEBUG, 
                                    "verify_next_assertion(): DNSKEY tag (%d) matches DS tag (%d)",
                                    (&dnskey)->key_tag,                                         
                                    (&ds)->d_keytag);
                            /*
                             * the first match is enough 
                             */
                            nextrr->rr_status = VAL_AC_VERIFIED_LINK;
                            FREE(ds.d_hash);
                            ds.d_hash = NULL;
                            if (dnskey.public_key) {
                                FREE(dnskey.public_key);
                                dnskey.public_key = NULL;
                            }
                            val_log(ctx, LOG_INFO, "verify_next_assertion(): Key links upward");
                            return;
                        } else {
                            /*
                             * Didn't find a valid entry in the DS record set 
                             * Not necessarily a problem, since there is no requirement that a DS be present
                             * If none match, then we set the status accordingly. See below.
                             */
                            nextrr->rr_status = VAL_AC_DS_NOMATCH;
                        } 

                        if (ds.d_hash != NULL)
                            FREE(ds.d_hash);

                        dsrec = dsrec->rr_next;
                    }
                }
            } 

            if (dnskey.public_key != NULL) {
                FREE(dnskey.public_key);
            }
            dnskey.public_key = NULL;
        }

        val_log(ctx, LOG_INFO, "verify_next_assertion(): Could not link this RRSIG to a DNSKEY");
        SET_STATUS(as->val_ac_status, the_sig, VAL_AC_DNSKEY_NOMATCH);
    }
        
    /* 
     * If we reach here and we're a keyset, we either didn't verify the keyset or
     * didn't verify the link from the key to the DS 
     */ 
    if (the_set->rrs_type_h == ns_t_dnskey){
        as->val_ac_status = VAL_AC_NO_LINK;
    }
}
static void
do_section(const res_state statp,
	   ns_msg *handle, ns_sect section,
	   int pflag, FILE *file)
{
	int n, sflag, rrnum;
	static int buflen = 2048;
	char *buf;
	ns_opcode opcode;
	ns_rr rr;

	/*
	 * Print answer records.
	 */
	sflag = (statp->pfcode & pflag);
	if (statp->pfcode && !sflag)
		return;

	buf = malloc(buflen);
	if (buf == NULL) {
		fprintf(file, ";; memory allocation failure\n");
		return;
	}

	opcode = (ns_opcode) ns_msg_getflag(*handle, ns_f_opcode);
	rrnum = 0;
	for (;;) {
		if (ns_parserr(handle, section, rrnum, &rr)) {
			if (errno != ENODEV)
				fprintf(file, ";; ns_parserr: %s\n",
					strerror(errno));
			else if (rrnum > 0 && sflag != 0 &&
				 (statp->pfcode & RES_PRF_HEAD1))
				putc('\n', file);
			goto cleanup;
		}
		if (rrnum == 0 && sflag != 0 && (statp->pfcode & RES_PRF_HEAD1))
			fprintf(file, ";; %s SECTION:\n",
				p_section(section, opcode));
		if (section == ns_s_qd)
			fprintf(file, ";;\t%s, type = %s, class = %s\n",
				ns_rr_name(rr),
				p_type(ns_rr_type(rr)),
				p_class(ns_rr_class(rr)));
		else if (section == ns_s_ar && ns_rr_type(rr) == ns_t_opt) {
			u_int16_t optcode, optlen, rdatalen = ns_rr_rdlen(rr);
			u_int32_t ttl = ns_rr_ttl(rr);

			fprintf(file,
				"; EDNS: version: %u, udp=%u, flags=%04x\n",
				(ttl>>16)&0xff, ns_rr_class(rr), ttl&0xffff);

			while (rdatalen >= 4) {
				const u_char *cp = ns_rr_rdata(rr);
				int i;

				GETSHORT(optcode, cp);
				GETSHORT(optlen, cp);

				if (optcode == NS_OPT_NSID) {
					fputs("; NSID: ", file);
					if (optlen == 0) {
						fputs("; NSID\n", file);
					} else {
						fputs("; NSID: ", file);
						for (i = 0; i < optlen; i++)
							fprintf(file, "%02x ",
								cp[i]);
						fputs(" (",file);
						for (i = 0; i < optlen; i++)
							fprintf(file, "%c",
								isprint(cp[i])?
								cp[i] : '.');
						fputs(")\n", file);
					}
				} else {
					if (optlen == 0) {
						fprintf(file, "; OPT=%u\n",
							optcode);
					} else {
						fprintf(file, "; OPT=%u: ",
							optcode);
						for (i = 0; i < optlen; i++)
							fprintf(file, "%02x ",
								cp[i]);
						fputs(" (",file);
						for (i = 0; i < optlen; i++)
							fprintf(file, "%c",
								isprint(cp[i]) ?
									cp[i] : '.');
						fputs(")\n", file);
					}
				}
				rdatalen -= 4 + optlen;
			}
		} else {
Exemple #16
0
static int
printZone(ns_type xfr, const char *zone, const struct sockaddr_in *sin,
	  ns_tsig_key *key)
{
	static u_char *answer = NULL;
	static int answerLen = 0;

	querybuf buf;
	int msglen, amtToRead, numRead, result, sockFD, len;
	int count, type, rlen, done, n;
	int numAnswers, numRecords, soacnt;
	u_char *cp, tmp[NS_INT16SZ];
	char dname[2][NS_MAXDNAME];
	enum { NO_ERRORS, ERR_READING_LEN, ERR_READING_MSG, ERR_PRINTING }
		error;
	pid_t zpid = -1;
	u_char *newmsg;
	int newmsglen;
	ns_tcp_tsig_state tsig_state;
	int tsig_ret, tsig_required, tsig_present;

	switch (xfr) {
	case ns_t_axfr:
	case ns_t_zxfr:
		break;
	default:
		fprintf(stderr, ";; %s - transfer type not supported\n",
			p_type(xfr));
		return (ERROR);
	}

	/*
	 *  Create a query packet for the requested zone name.
	 */
	msglen = res_nmkquery(&res, ns_o_query, zone,
			      queryClass, ns_t_axfr, NULL,
			      0, 0, buf.qb2, sizeof buf);
	if (msglen < 0) {
		if (res.options & RES_DEBUG)
			fprintf(stderr, ";; res_nmkquery failed\n");
		return (ERROR);
	}

	/*
	 * Sign the message if a key was sent
	 */
	if (key == NULL) {
		newmsg = (u_char *)&buf;
		newmsglen = msglen;
	} else {
		DST_KEY *dstkey;
		int bufsize, siglen;
		u_char sig[64];
		int ret;
		
		/* ns_sign() also calls dst_init(), but there is no harm
		 * doing it twice
		 */
		dst_init();
		
		bufsize = msglen + 1024;
		newmsg = (u_char *) malloc(bufsize);
		if (newmsg == NULL) {
			errno = ENOMEM;
			return (-1);
		}
		memcpy(newmsg, (u_char *)&buf, msglen);
		newmsglen = msglen;
		
		if (strcmp(key->alg, NS_TSIG_ALG_HMAC_MD5) != 0)
			dstkey = NULL;
		else
			dstkey = dst_buffer_to_key(key->name, KEY_HMAC_MD5,
							NS_KEY_TYPE_AUTH_ONLY,
							NS_KEY_PROT_ANY,
							key->data, key->len);
		if (dstkey == NULL) {
			errno = EINVAL;
			if (key)
				free(newmsg);
			return (-1);
		}
		
		siglen = sizeof(sig);
/* newmsglen++; */
		ret = ns_sign(newmsg, &newmsglen, bufsize, NOERROR, dstkey, NULL, 0,
		      sig, &siglen, 0);
		if (ret < 0) {
			if (key)
				free (newmsg);
			if (ret == NS_TSIG_ERROR_NO_SPACE)
				errno  = EMSGSIZE;
			else if (ret == -1)
				errno  = EINVAL;
			return (ret);
		}
		ns_verify_tcp_init(dstkey, sig, siglen, &tsig_state);
	}

	/*
	 *  Set up a virtual circuit to the server.
	 */
	if ((sockFD = socket(sin->sin_family, SOCK_STREAM, 0)) < 0) {
		int e = errno;

		perror(";; socket");
		return (e);
	}
	
	switch (sin->sin_family) {
	case AF_INET:
		if (bind(sockFD, (struct sockaddr *)&myaddress,
			 sizeof myaddress) < 0){
			int e = errno;

			fprintf(stderr, ";; bind(%s port %u): %s\n",
				inet_ntoa(myaddress.sin_addr),
				ntohs(myaddress.sin_port),
				strerror(e));
			(void) close(sockFD);
			sockFD = -1;
			return (e);
		}
		if (connect(sockFD, (const struct sockaddr *)sin,
			    sizeof *sin) < 0) {
			int e = errno;

			perror(";; connect");
			(void) close(sockFD);
			sockFD = -1;
			return (e);
		}
		break;
	case AF_INET6:
		if (bind(sockFD, (struct sockaddr *)&myaddress6,
			 sizeof myaddress6) < 0){
			int e = errno;
			char buf[80];

			fprintf(stderr, ";; bind(%s port %u): %s\n",
				inet_ntop(AF_INET6, &myaddress6.sin6_addr,
					  buf, sizeof(buf)),
				ntohs(myaddress6.sin6_port),
				strerror(e));
			(void) close(sockFD);
			sockFD = -1;
			return (e);
		}
		if (connect(sockFD, (const struct sockaddr *)sin,
			    sizeof(struct sockaddr_in6)) < 0) {
			int e = errno;

			perror(";; connect");
			(void) close(sockFD);
			sockFD = -1;
			return (e);
		}
		break;
	}

	/*
	 * Send length & message for zone transfer
	 */

	ns_put16(newmsglen, tmp);
        if (write(sockFD, (char *)tmp, NS_INT16SZ) != NS_INT16SZ ||
            write(sockFD, (char *)newmsg, newmsglen) != newmsglen) {
		int e = errno;
		if (key)
			free (newmsg);
		perror(";; write");
		(void) close(sockFD);
		sockFD = -1;
		return (e);
	} else if (key)
		free (newmsg);

	/*
	 * If we're compressing, push a gzip into the pipeline.
	 */
	if (xfr == ns_t_zxfr) {
		enum { rd = 0, wr = 1 };
		int z[2];

		if (pipe(z) < 0) {
			int e = errno;

			perror(";; pipe");
			(void) close(sockFD);
			sockFD = -1;
			return (e);
		}
		zpid = vfork();
		if (zpid < 0) {
			int e = errno;

			perror(";; fork");
			(void) close(sockFD);
			sockFD = -1;
			return (e);
		} else if (zpid == 0) {
			/* Child. */
			(void) close(z[rd]);
			(void) dup2(sockFD, STDIN_FILENO);
			(void) close(sockFD);
			(void) dup2(z[wr], STDOUT_FILENO);
			(void) close(z[wr]);
			execlp("gzip", "gzip", "-d", "-v", NULL);
			perror(";; child: execlp(gunzip)");
			_exit(1);
		}
		/* Parent. */
		(void) close(z[wr]);
		(void) dup2(z[rd], sockFD);
		(void) close(z[rd]);
	}
	result = 0;
	numAnswers = 0;
	numRecords = 0;
	soacnt = 0;
	error = NO_ERRORS;
	numRead = 0;

	dname[0][0] = '\0';
	for (done = 0; !done; (void)NULL) {
		/*
		 * Read the length of the response.
		 */

		cp = tmp;
		amtToRead = INT16SZ;
		while (amtToRead > 0 &&
		   (numRead = read(sockFD, cp, amtToRead)) > 0) {
			cp += numRead;
			amtToRead -= numRead;
		}
		if (numRead <= 0) {
			error = ERR_READING_LEN;
			break;
		}

		len = ns_get16(tmp);
		if (len == 0)
			break;	/* nothing left to read */

		/*
		 * The server sent too much data to fit the existing buffer --
		 * allocate a new one.
		 */
		if (len > answerLen) {
			if (answerLen != 0)
				free(answer);
			answerLen = len;
			answer = (u_char *)malloc(answerLen);
		}

		/*
		 * Read the response.
		 */

		amtToRead = len;
		cp = answer;
		while (amtToRead > 0 &&
		       (numRead = read(sockFD, cp, amtToRead)) > 0) {
			cp += numRead;
			amtToRead -= numRead;
		}
		if (numRead <= 0) {
			error = ERR_READING_MSG;
			break;
		}

		result = print_axfr(stdout, answer, len);
		if (result != 0) {
			error = ERR_PRINTING;
			break;
		}
		numRecords += htons(((HEADER *)answer)->ancount);
		numAnswers++;

		/* Header. */
		cp = answer + HFIXEDSZ;
		/* Question. */
		for (count = ntohs(((HEADER *)answer)->qdcount);	
		     count > 0;
		     count--) {
			n = dn_skipname(cp, answer + len);
			if (n < 0) {
				error = ERR_PRINTING;
				done++;
				break;
			}
			cp += n + QFIXEDSZ;
			if (cp > answer + len) {
				error = ERR_PRINTING;
				done++;
				break;
			}
		}
		/* Answer. */
		for (count = ntohs(((HEADER *)answer)->ancount);
		     count > 0 && !done;
		     count--) {
			n = dn_expand(answer, answer + len, cp,
				      dname[soacnt], sizeof dname[0]);
			if (n < 0) {
				error = ERR_PRINTING;
				done++;
				break;
			}
			cp += n;
			if (cp + 3 * INT16SZ + INT32SZ > answer + len) {
				error = ERR_PRINTING;
				done++;
				break;
			}
			GETSHORT(type, cp);
			cp += INT16SZ;
			cp += INT32SZ;	/* ttl */
			GETSHORT(rlen, cp);
			cp += rlen;
			if (cp > answer + len) {
				error = ERR_PRINTING;
				done++;
				break;
			}
			if (type == T_SOA && soacnt++ &&
			    ns_samename(dname[0], dname[1]) == 1) {
				done++;
				break;
			}
		}

		/*
		 * Verify the TSIG
		 */

		if (key) {
			if (ns_find_tsig(answer, answer + len) != NULL)
				tsig_present = 1;
			else
				tsig_present = 0;
			if (numAnswers == 1 || soacnt > 1)
				tsig_required = 1;
			else
				tsig_required = 0;
			tsig_ret = ns_verify_tcp(answer, &len, &tsig_state,
						 tsig_required);
			if (tsig_ret == 0) {
				if (tsig_present)
					printf("; TSIG ok\n");
			}
			else
				printf("; TSIG invalid\n");
		}

	}

	printf(";; Received %d answer%s (%d record%s).\n",
	       numAnswers, (numAnswers != 1) ? "s" : "",
	       numRecords, (numRecords != 1) ? "s" : "");

	(void) close(sockFD);
	sockFD = -1;

	/*
	 * If we were uncompressing, reap the uncompressor.
	 */
	if (xfr == ns_t_zxfr) {
		pid_t pid;
		int status = 0;

		pid = wait(&status);
		if (pid < 0) {
			int e = errno;

			perror(";; wait");
			return (e);
		}
		if (pid != zpid) {
			fprintf(stderr, ";; wrong pid (%lu != %lu)\n",
				(u_long)pid, (u_long)zpid);
			return (ERROR);
		}
		printf(";; pid %lu: exit %d, signal %d, core %c\n",
		       (u_long)pid, WEXITSTATUS(status),
		       WIFSIGNALED(status) ? WTERMSIG(status) : 0,
		       WCOREDUMP(status) ? 't' : 'f');
	}

	switch (error) {
	case NO_ERRORS:
		return (0);

	case ERR_READING_LEN:
		return (EMSGSIZE);

	case ERR_PRINTING:
		return (result);

	case ERR_READING_MSG:
		return (EMSGSIZE);

	default:
		return (EFAULT);
	}
}
/*
 * Print the contents of a query.
 * This is intended to be primarily a debugging routine.
 */
void
fp_query(char *msg, FILE *file)
{
	register char *cp;
	register HEADER *hp;
	register int n;

	/*
	 * Print header fields.
	 */
	hp = (HEADER *)msg;
	cp = msg + sizeof(HEADER);
	fprintf(file,"HEADER:\n");
	fprintf(file,"\topcode = %s", _res_opcodes[hp->opcode]);
	fprintf(file,", id = %d", ntohs(hp->id));
	fprintf(file,", rcode = %s\n", _res_resultcodes[hp->rcode]);
	fprintf(file,"\theader flags: ");
	if (hp->qr)
		fprintf(file," qr");
	if (hp->aa)
		fprintf(file," aa");
	if (hp->tc)
		fprintf(file," tc");
	if (hp->rd)
		fprintf(file," rd");
	if (hp->ra)
		fprintf(file," ra");
	if (hp->pr)
		fprintf(file," pr");
	fprintf(file,"\n\tqdcount = %d", ntohs(hp->qdcount));
	fprintf(file,", ancount = %d", ntohs(hp->ancount));
	fprintf(file,", nscount = %d", ntohs(hp->nscount));
	fprintf(file,", arcount = %d\n\n", ntohs(hp->arcount));
	/*
	 * Print question records.
	 */
	if (n = ntohs(hp->qdcount)) {
		fprintf(file,"QUESTIONS:\n");
		while (--n >= 0) {
			fprintf(file,"\t");
			cp = p_cdname(cp, msg, file);
			if (cp == NULL)
				return;
			fprintf(file,", type = %s", p_type(_getshort(cp)));
			cp += sizeof(u_short);
			fprintf(file,", class = %s\n\n", p_class(_getshort(cp)));
			cp += sizeof(u_short);
		}
	}
	/*
	 * Print authoritative answer records
	 */
	if (n = ntohs(hp->ancount)) {
		fprintf(file,"ANSWERS:\n");
		while (--n >= 0) {
			fprintf(file,"\t");
			cp = p_rr(cp, msg, file);
			if (cp == NULL)
				return;
		}
	}
	/*
	 * print name server records
	 */
	if (n = ntohs(hp->nscount)) {
		fprintf(file,"NAME SERVERS:\n");
		while (--n >= 0) {
			fprintf(file,"\t");
			cp = p_rr(cp, msg, file);
			if (cp == NULL)
				return;
		}
	}
	/*
	 * print additional records
	 */
	if (n = ntohs(hp->arcount)) {
		fprintf(file,"ADDITIONAL RECORDS:\n");
		while (--n >= 0) {
			fprintf(file,"\t");
			cp = p_rr(cp, msg, file);
			if (cp == NULL)
				return;
		}
	}
}