answer
stringlengths
15
1.25M
@import url 'http://fonts.googleapis.com/css?family=PT+Serif|Cabin'; html { font-family: sans-serif; -ms-text-size-adjust: 100%; -<API key>: 100%; } body { margin: 0; } article, aside, details, figcaption, figure, footer, header, hgroup, main, nav, section, summary { display: block; } audio, canvas, progress, video { display: inline-block; vertical-align: baseline; } audio:not([controls]) { display: none; height: 0; } [hidden], template { display: none; } a { background: transparent; } a:active, a:hover { outline: 0; } abbr[title] { border-bottom: 1px dotted; } b, strong { font-weight: bold; } dfn { font-style: italic; } h1 { font-size: 2em; margin: 0.67em 0; } mark { background: #ff0; color: #000; } small { font-size: 80%; } sub, sup { font-size: 75%; line-height: 0; position: relative; vertical-align: baseline; } sup { top: -0.5em; } sub { bottom: -0.25em; } img { border: 0; } svg:not(:root) { overflow: hidden; } figure { margin: 1em 40px; } hr { -moz-box-sizing: content-box; box-sizing: content-box; height: 0; } pre { overflow: auto; } code, kbd, pre, samp { font-family: monospace, monospace; font-size: 1em; } button, input, optgroup, select, textarea { color: inherit; font: inherit; margin: 0; } button { overflow: visible; } button, select { text-transform: none; } button, html input[type="button"], * 1 */, input[type="reset"], input[type="submit"] { -webkit-appearance: button; cursor: pointer; } button[disabled], html input[disabled] { cursor: default; } button::-moz-focus-inner, input::-moz-focus-inner { border: 0; padding: 0; } input { line-height: normal; } input[type="checkbox"], input[type="radio"] { box-sizing: border-box; padding: 0; } input[type="number"]::-<API key>, input[type="number"]::-<API key> { height: auto; } input[type="search"] { -webkit-appearance: textfield; -moz-box-sizing: content-box; -webkit-box-sizing: content-box; box-sizing: content-box; } input[type="search"]::-<API key>, input[type="search"]::-<API key> { -webkit-appearance: none; } fieldset { border: 1px solid #c0c0c0; margin: 0 2px; padding: 0.35em 0.625em 0.75em; } legend { border: 0; padding: 0; } textarea { overflow: auto; } optgroup { font-weight: bold; } table { border-collapse: collapse; border-spacing: 0; } td, th { padding: 0; } html { background: #896f65; color: #bdbec0; font-size: 14px; font-family: 'PT Serif', serif; } h1, .h1, h2, .h2, h3, h4, .h4, h5, .h5, h6, .h6 { color: #0f0e0f; font-family: 'Cabin', sans-serif; line-height: 1em; margin: 0; padding: 0; } h1, .h1 { font-size: 2.6em; } h2, .h2 { font-size: 2.2em; } h3, .h3 { font-size: 1.8em; } h4, .h4 { font-size: 1.6em; } h5, .h5 { font-size: 1.3em; } h6, .h6 { font-size: 1em; } a { color: #546d71; text-decoration: none; } a:hover { color: #0f0e0f; } .largetext { font-size: 4em; } .uppercase { text-transform: uppercase; } .textcenter { text-align: center; } .header { margin-top: 100px; } .button-nav { display: none; } .navigation { display: block; } @media all and (max-width:640px) { .button-nav { display: block; } .navigation { display: none; } }
#ifndef <API key> #define <API key> #ifdef __WXGTK__ #include "wxCustomControlsGTK.hpp" #elif defined(__WXOSX__) // macOS #include "<API key>.hpp" #else // Windows #include "wxCustomControlsMSW.hpp" #endif #endif // <API key>
// <API key>: GPL-2.0-or-later #include <common.h> #include <init.h> #include <driver.h> #include <linux/clk.h> #include <io.h> #include <of.h> #include <linux/clkdev.h> #include <linux/err.h> #include <mach/imx6-regs.h> #include <mach/revision.h> #include <mach/imx6.h> #include <dt-bindings/clock/imx6ul-clock.h> #include "clk.h" #define <API key> (0x2 << 16) #define CCDR 0x4 static const char *pll_bypass_src_sels[] = { "osc", "dummy", }; static const char *pll1_bypass_sels[] = { "pll1", "pll1_bypass_src", }; static const char *pll2_bypass_sels[] = { "pll2", "pll2_bypass_src", }; static const char *pll3_bypass_sels[] = { "pll3", "pll3_bypass_src", }; static const char *pll4_bypass_sels[] = { "pll4", "pll4_bypass_src", }; static const char *pll5_bypass_sels[] = { "pll5", "pll5_bypass_src", }; static const char *pll6_bypass_sels[] = { "pll6", "pll6_bypass_src", }; static const char *pll7_bypass_sels[] = { "pll7", "pll7_bypass_src", }; static const char *ca7_secondary_sels[] = { "pll2_pfd2_396m", "pll2_bus", }; static const char *step_sels[] = { "osc", "ca7_secondary_sel", }; static const char *pll1_sw_sels[] = { "pll1_sys", "step", }; static const char *axi_alt_sels[] = { "pll2_pfd2_396m", "pll3_pfd1_540m", }; static const char *axi_sels[] = {"periph", "axi_alt_sel", }; static const char *periph_pre_sels[] = { "pll2_bus", "pll2_pfd2_396m", "pll2_pfd0_352m", "pll2_198m", }; static const char *periph2_pre_sels[] = { "pll2_bus", "pll2_pfd2_396m", "pll2_pfd0_352m", "pll4_audio_div", }; static const char *periph_clk2_sels[] = { "pll3_usb_otg", "osc", "osc", }; static const char *periph2_clk2_sels[] = { "pll3_usb_otg", "osc", }; static const char *periph_sels[] = { "periph_pre", "periph_clk2", }; static const char *periph2_sels[] = { "periph2_pre", "periph2_clk2", }; static const char *usdhc_sels[] = { "pll2_pfd2_396m", "pll2_pfd0_352m", }; static const char *bch_sels[] = { "pll2_pfd2_396m", "pll2_pfd0_352m", }; static const char *gpmi_sels[] = { "pll2_pfd2_396m", "pll2_pfd0_352m", }; static const char *eim_slow_sels[] = { "axi", "pll3_usb_otg", "pll2_pfd2_396m", "pll3_pfd0_720m", }; static const char *spdif_sels[] = { "pll4_audio_div", "pll3_pfd2_508m", "pll5_video_div", "pll3_usb_otg", }; static const char *sai_sels[] = { "pll3_pfd2_508m", "pll5_video_div", "pll4_audio_div", }; static const char *lcdif_pre_sels[] = { "pll2_bus", "pll3_pfd3_454m", "pll5_video_div", "pll2_pfd0_352m", "pll2_pfd1_594m", "pll3_pfd1_540m", }; static const char *sim_pre_sels[] = { "pll2_bus", "pll3_usb_otg", "pll5_video_div", "pll2_pfd0_352m", "pll2_pfd2_396m", "pll3_pfd2_508m", }; static const char *ldb_di0_sels[] = { "pll5_video_div", "pll2_pfd0_352m", "pll2_pfd2_396m", "pll2_pfd3_594m", "pll2_pfd1_594m", "pll3_pfd3_454m", }; static const char *ldb_di0_div_sels[] = { "ldb_di0_div_3_5", "ldb_di0_div_7", }; static const char *ldb_di1_div_sels[] = { "ldb_di1_div_3_5", "ldb_di1_div_7", }; static const char *qspi1_sels[] = { "pll3_usb_otg", "pll2_pfd0_352m", "pll2_pfd2_396m", "pll2_bus", "pll3_pfd3_454m", "pll3_pfd2_508m", }; static const char *enfc_sels[] = { "pll2_pfd0_352m", "pll2_bus", "pll3_usb_otg", "pll2_pfd2_396m", "pll3_pfd3_454m", "dummy", "dummy", "dummy", }; static const char *can_sels[] = { "pll3_60m", "osc", "pll3_80m", "dummy", }; static const char *ecspi_sels[] = { "pll3_60m", "osc", }; static const char *uart_sels[] = { "pll3_80m", "osc", }; static const char *perclk_sels[] = { "ipg", "osc", }; static const char *lcdif_sels[] = { "lcdif_podf", "ipp_di0", "ipp_di1", "ldb_di0", "ldb_di1", }; static const char *csi_sels[] = { "osc", "pll2_pfd2_396m", "pll3_120m", "pll3_pfd1_540m", }; static const char *sim_sels[] = { "sim_podf", "ipp_di0", "ipp_di1", "ldb_di0", "ldb_di1", }; /* epdc_pre_sels, epdc_sels, esai_sels only exists on i.MX6ULL */ static const char *epdc_pre_sels[] = { "pll2_bus", "pll3_usb_otg", "pll5_video_div", "pll2_pfd0_352m", "pll2_pfd2_396m", "pll3_pfd2_508m", }; static const char *esai_sels[] = { "pll4_audio_div", "pll3_pfd2_508m", "pll5_video_div", "pll3_usb_otg", }; static const char *epdc_sels[] = { "epdc_podf", "ipp_di0", "ipp_di1", "ldb_di0", "ldb_di1", }; static struct clk *clks[IMX6UL_CLK_END]; static struct clk_onecell_data clk_data; static inline int clk_on_imx6ul(void) { return <API key>("fsl,imx6ul"); } static inline int clk_on_imx6ull(void) { return <API key>("fsl,imx6ull"); } static int const clks_init_on[] __initconst = { IMX6UL_CLK_AIPSTZ1, IMX6UL_CLK_AIPSTZ2, IMX6UL_CLK_AIPSTZ3, IMX6UL_CLK_AXI, IMX6UL_CLK_ARM, IMX6UL_CLK_ROM, <API key>, <API key>, }; static struct clk_div_table clk_enet_ref_table[] = { { .val = 0, .div = 20, }, { .val = 1, .div = 10, }, { .val = 2, .div = 5, }, { .val = 3, .div = 4, }, { } }; static int imx6_ccm_probe(struct device_d *dev) { struct resource *iores; void __iomem *base, *anatop_base, *ccm_base; int i; struct device_node *ccm_node = dev->device_node; anatop_base = IOMEM(<API key>); iores = <API key>(dev, 0); if (IS_ERR(iores)) return PTR_ERR(iores); ccm_base = IOMEM(iores->start); base = anatop_base; clks[IMX6UL_CLK_DUMMY] = clk_fixed("dummy", 0); clks[<API key>] = imx_clk_mux("pll1_bypass_src", base + 0x00, 14, 1, pll_bypass_src_sels, ARRAY_SIZE(pll_bypass_src_sels)); clks[<API key>] = imx_clk_mux("pll2_bypass_src", base + 0x30, 14, 1, pll_bypass_src_sels, ARRAY_SIZE(pll_bypass_src_sels)); clks[<API key>] = imx_clk_mux("pll3_bypass_src", base + 0x10, 14, 1, pll_bypass_src_sels, ARRAY_SIZE(pll_bypass_src_sels)); clks[<API key>] = imx_clk_mux("pll4_bypass_src", base + 0x70, 14, 1, pll_bypass_src_sels, ARRAY_SIZE(pll_bypass_src_sels)); clks[<API key>] = imx_clk_mux("pll5_bypass_src", base + 0xa0, 14, 1, pll_bypass_src_sels, ARRAY_SIZE(pll_bypass_src_sels)); clks[<API key>] = imx_clk_mux("pll6_bypass_src", base + 0xe0, 14, 1, pll_bypass_src_sels, ARRAY_SIZE(pll_bypass_src_sels)); clks[<API key>] = imx_clk_mux("pll7_bypass_src", base + 0x20, 14, 1, pll_bypass_src_sels, ARRAY_SIZE(pll_bypass_src_sels)); clks[IMX6UL_CLK_PLL1] = imx_clk_pllv3(IMX_PLLV3_SYS, "pll1", "osc", base + 0x00, 0x7f); clks[IMX6UL_CLK_PLL2] = imx_clk_pllv3(IMX_PLLV3_GENERIC, "pll2", "osc", base + 0x30, 0x1); clks[IMX6UL_CLK_PLL3] = imx_clk_pllv3(IMX_PLLV3_USB, "pll3", "osc", base + 0x10, 0x3); clks[IMX6UL_CLK_PLL4] = imx_clk_pllv3(IMX_PLLV3_AV, "pll4", "osc", base + 0x70, 0x7f); clks[IMX6UL_CLK_PLL5] = imx_clk_pllv3(IMX_PLLV3_AV, "pll5", "osc", base + 0xa0, 0x7f); clks[IMX6UL_CLK_PLL6] = imx_clk_pllv3(IMX_PLLV3_ENET, "pll6", "osc", base + 0xe0, 0x3); clks[IMX6UL_CLK_PLL7] = imx_clk_pllv3(IMX_PLLV3_USB, "pll7", "osc", base + 0x20, 0x3); clks[IMX6UL_PLL1_BYPASS] = imx_clk_mux_p("pll1_bypass", base + 0x00, 16, 1, pll1_bypass_sels, ARRAY_SIZE(pll1_bypass_sels)); clks[IMX6UL_PLL2_BYPASS] = imx_clk_mux_p("pll2_bypass", base + 0x30, 16, 1, pll2_bypass_sels, ARRAY_SIZE(pll2_bypass_sels)); clks[IMX6UL_PLL3_BYPASS] = imx_clk_mux_p("pll3_bypass", base + 0x10, 16, 1, pll3_bypass_sels, ARRAY_SIZE(pll3_bypass_sels)); clks[IMX6UL_PLL4_BYPASS] = imx_clk_mux_p("pll4_bypass", base + 0x70, 16, 1, pll4_bypass_sels, ARRAY_SIZE(pll4_bypass_sels)); clks[IMX6UL_PLL5_BYPASS] = imx_clk_mux_p("pll5_bypass", base + 0xa0, 16, 1, pll5_bypass_sels, ARRAY_SIZE(pll5_bypass_sels)); clks[IMX6UL_PLL6_BYPASS] = imx_clk_mux_p("pll6_bypass", base + 0xe0, 16, 1, pll6_bypass_sels, ARRAY_SIZE(pll6_bypass_sels)); clks[IMX6UL_PLL7_BYPASS] = imx_clk_mux_p("pll7_bypass", base + 0x20, 16, 1, pll7_bypass_sels, ARRAY_SIZE(pll7_bypass_sels)); clks[IMX6UL_CLK_CSI_SEL] = imx_clk_mux_p("csi_sel", base + 0x3c, 9, 2, csi_sels, ARRAY_SIZE(csi_sels)); /* Do not bypass PLLs initially */ clk_set_parent(clks[IMX6UL_PLL1_BYPASS], clks[IMX6UL_CLK_PLL1]); clk_set_parent(clks[IMX6UL_PLL2_BYPASS], clks[IMX6UL_CLK_PLL2]); clk_set_parent(clks[IMX6UL_PLL3_BYPASS], clks[IMX6UL_CLK_PLL3]); clk_set_parent(clks[IMX6UL_PLL4_BYPASS], clks[IMX6UL_CLK_PLL4]); clk_set_parent(clks[IMX6UL_PLL5_BYPASS], clks[IMX6UL_CLK_PLL5]); clk_set_parent(clks[IMX6UL_PLL6_BYPASS], clks[IMX6UL_CLK_PLL6]); clk_set_parent(clks[IMX6UL_PLL7_BYPASS], clks[IMX6UL_CLK_PLL7]); clks[IMX6UL_CLK_PLL1_SYS] = <API key>("pll1_sys", "pll1_bypass", 1, 1); clks[IMX6UL_CLK_PLL2_BUS] = imx_clk_gate("pll2_bus", "pll2_bypass", base + 0x30, 13); clks[<API key>] = imx_clk_gate("pll3_usb_otg", "pll3_bypass", base + 0x10, 13); clks[<API key>] = imx_clk_gate("pll4_audio", "pll4_bypass", base + 0x70, 13); clks[<API key>] = imx_clk_gate("pll5_video", "pll5_bypass", base + 0xa0, 13); clks[<API key>] = imx_clk_gate("pll6_enet", "pll6_bypass", base + 0xe0, 13); clks[<API key>] = imx_clk_gate("pll7_usb_host", "pll7_bypass", base + 0x20, 13); /* * Bit 20 is the reserved and read-only bit, we do this only for: * - Do nothing for usbphy clk_enable/disable * - Keep refcount when do usbphy clk_enable/disable, in that case, * the clk framework many need to enable/disable usbphy's parent */ clks[IMX6UL_CLK_USBPHY1] = imx_clk_gate("usbphy1", "pll3_usb_otg", base + 0x10, 20); clks[IMX6UL_CLK_USBPHY2] = imx_clk_gate("usbphy2", "pll7_usb_host", base + 0x20, 20); /* * usbphy*_gate needs to be on after system boots up, and software * never needs to control it anymore. */ clks[<API key>] = imx_clk_gate("usbphy1_gate", "dummy", base + 0x10, 6); clks[<API key>] = imx_clk_gate("usbphy2_gate", "dummy", base + 0x20, 6); /* name parent_name reg idx */ clks[<API key>] = imx_clk_pfd("pll2_pfd0_352m", "pll2_bus", base + 0x100, 0); clks[<API key>] = imx_clk_pfd("pll2_pfd1_594m", "pll2_bus", base + 0x100, 1); clks[<API key>] = imx_clk_pfd("pll2_pfd2_396m", "pll2_bus", base + 0x100, 2); clks[<API key>] = imx_clk_pfd("pll2_pfd3_594m", "pll2_bus", base + 0x100, 3); clks[<API key>] = imx_clk_pfd("pll3_pfd0_720m", "pll3_usb_otg", base + 0xf0, 0); clks[<API key>] = imx_clk_pfd("pll3_pfd1_540m", "pll3_usb_otg", base + 0xf0, 1); clks[<API key>] = imx_clk_pfd("pll3_pfd2_508m", "pll3_usb_otg", base + 0xf0, 2); clks[<API key>] = imx_clk_pfd("pll3_pfd3_454m", "pll3_usb_otg", base + 0xf0, 3); clks[IMX6UL_CLK_ENET_REF] = <API key>("enet_ref", "pll6_enet", base + 0xe0, 0, 2, clk_enet_ref_table); clks[<API key>] = <API key>("enet2_ref", "pll6_enet", base + 0xe0, 2, 2, clk_enet_ref_table); clks[<API key>] = imx_clk_gate("enet_ref_125m", "enet2_ref", base + 0xe0, 20); clks[<API key>] = <API key>("enet_ptp_ref", "pll6_enet", 1, 20); clks[IMX6UL_CLK_ENET_PTP] = imx_clk_gate("enet_ptp", "enet_ptp_ref", base + 0xe0, 21); /* name parent_name mult div */ clks[<API key>] = <API key>("pll2_198m", "pll2_pfd2_396m", 1, 2); clks[IMX6UL_CLK_PLL3_80M] = <API key>("pll3_80m", "pll3_usb_otg", 1, 6); clks[IMX6UL_CLK_PLL3_60M] = <API key>("pll3_60m", "pll3_usb_otg", 1, 8); clks[IMX6UL_CLK_GPT_3M] = <API key>("gpt_3m", "osc", 1, 8); base = ccm_base; clks[<API key>] = imx_clk_mux("ca7_secondary_sel", base + 0xc, 3, 1, ca7_secondary_sels, ARRAY_SIZE(ca7_secondary_sels)); clks[IMX6UL_CLK_STEP] = imx_clk_mux("step", base + 0x0c, 8, 1, step_sels, ARRAY_SIZE(step_sels)); clks[IMX6UL_CLK_PLL1_SW] = imx_clk_mux("pll1_sw", base + 0x0c, 2, 1, pll1_sw_sels, ARRAY_SIZE(pll1_sw_sels)); clks[<API key>] = imx_clk_mux("axi_alt_sel", base + 0x14, 7, 1, axi_alt_sels, ARRAY_SIZE(axi_alt_sels)); clks[IMX6UL_CLK_AXI_SEL] = imx_clk_mux("axi_sel", base + 0x14, 6, 1, axi_sels, ARRAY_SIZE(axi_sels)); clks[<API key>] = imx_clk_mux("periph_pre", base + 0x18, 18, 2, periph_pre_sels, ARRAY_SIZE(periph_pre_sels)); clks[<API key>] = imx_clk_mux("periph2_pre", base + 0x18, 21, 2, periph2_pre_sels, ARRAY_SIZE(periph2_pre_sels)); clks[<API key>] = imx_clk_mux("periph_clk2_sel", base + 0x18, 12, 2, periph_clk2_sels, ARRAY_SIZE(periph_clk2_sels)); clks[<API key>] = imx_clk_mux("periph2_clk2_sel", base + 0x18, 20, 1, periph2_clk2_sels, ARRAY_SIZE(periph2_clk2_sels)); clks[<API key>] = imx_clk_mux("eim_slow_sel", base + 0x1c, 29, 2, eim_slow_sels, ARRAY_SIZE(eim_slow_sels)); clks[IMX6UL_CLK_GPMI_SEL] = imx_clk_mux("gpmi_sel", base + 0x1c, 19, 1, gpmi_sels, ARRAY_SIZE(gpmi_sels)); clks[IMX6UL_CLK_BCH_SEL] = imx_clk_mux("bch_sel", base + 0x1c, 18, 1, bch_sels, ARRAY_SIZE(bch_sels)); clks[<API key>] = imx_clk_mux("usdhc2_sel", base + 0x1c, 17, 1, usdhc_sels, ARRAY_SIZE(usdhc_sels)); clks[<API key>] = imx_clk_mux("usdhc1_sel", base + 0x1c, 16, 1, usdhc_sels, ARRAY_SIZE(usdhc_sels)); clks[IMX6UL_CLK_SAI3_SEL] = imx_clk_mux("sai3_sel", base + 0x1c, 14, 2, sai_sels, ARRAY_SIZE(sai_sels)); clks[IMX6UL_CLK_SAI2_SEL] = imx_clk_mux("sai2_sel", base + 0x1c, 12, 2, sai_sels, ARRAY_SIZE(sai_sels)); clks[IMX6UL_CLK_SAI1_SEL] = imx_clk_mux("sai1_sel", base + 0x1c, 10, 2, sai_sels, ARRAY_SIZE(sai_sels)); clks[<API key>] = imx_clk_mux("qspi1_sel", base + 0x1c, 7, 3, qspi1_sels, ARRAY_SIZE(qspi1_sels)); clks[<API key>] = imx_clk_mux("perclk_sel", base + 0x1c, 6, 1, perclk_sels, ARRAY_SIZE(perclk_sels)); clks[IMX6UL_CLK_CAN_SEL] = imx_clk_mux("can_sel", base + 0x20, 8, 2, can_sels, ARRAY_SIZE(can_sels)); if (clk_on_imx6ull()) clks[<API key>] = imx_clk_mux("esai_sel", base + 0x20, 19, 2, esai_sels, ARRAY_SIZE(esai_sels)); clks[IMX6UL_CLK_UART_SEL] = imx_clk_mux("uart_sel", base + 0x24, 6, 1, uart_sels, ARRAY_SIZE(uart_sels)); clks[IMX6UL_CLK_ENFC_SEL] = imx_clk_mux("enfc_sel", base + 0x2c, 15, 3, enfc_sels, ARRAY_SIZE(enfc_sels)); clks[<API key>] = imx_clk_mux("ldb_di0_sel", base + 0x2c, 9, 3, ldb_di0_sels, ARRAY_SIZE(ldb_di0_sels)); clks[<API key>] = imx_clk_mux("spdif_sel", base + 0x30, 20, 2, spdif_sels, ARRAY_SIZE(spdif_sels)); if (clk_on_imx6ul()) { clks[<API key>] = imx_clk_mux("sim_pre_sel", base + 0x34, 15, 3, sim_pre_sels, ARRAY_SIZE(sim_pre_sels)); clks[IMX6UL_CLK_SIM_SEL] = imx_clk_mux("sim_sel", base + 0x34, 9, 3, sim_sels, ARRAY_SIZE(sim_sels)); } else if (clk_on_imx6ull()) { clks[<API key>] = imx_clk_mux("epdc_pre_sel", base + 0x34, 15, 3, epdc_pre_sels, ARRAY_SIZE(epdc_pre_sels)); clks[<API key>] = imx_clk_mux("epdc_sel", base + 0x34, 9, 3, epdc_sels, ARRAY_SIZE(epdc_sels)); } clks[<API key>] = imx_clk_mux("ecspi_sel", base + 0x38, 18, 1, ecspi_sels, ARRAY_SIZE(ecspi_sels)); clks[<API key>] = imx_clk_mux("lcdif_pre_sel", base + 0x38, 15, 3, lcdif_pre_sels, ARRAY_SIZE(lcdif_pre_sels)); clks[<API key>] = imx_clk_mux("lcdif_sel", base + 0x38, 9, 3, lcdif_sels, ARRAY_SIZE(lcdif_sels)); clks[<API key>] = imx_clk_mux("ldb_di0", base + 0x20, 10, 1, ldb_di0_div_sels, ARRAY_SIZE(ldb_di0_div_sels)); clks[<API key>] = imx_clk_mux("ldb_di1", base + 0x20, 11, 1, ldb_di1_div_sels, ARRAY_SIZE(ldb_di1_div_sels)); clks[<API key>] = <API key>("ldb_di0_div_3_5", "ldb_di0_sel", 2, 7); clks[<API key>] = <API key>("ldb_di0_div_7", "ldb_di0_sel", 1, 7); clks[<API key>] = <API key>("ldb_di1_div_3_5", "qspi1_sel", 2, 7); clks[<API key>] = <API key>("ldb_di1_div_7", "qspi1_sel", 1, 7); clks[IMX6UL_CLK_PERIPH] = imx_clk_busy_mux("periph", base + 0x14, 25, 1, base + 0x48, 5, periph_sels, ARRAY_SIZE(periph_sels)); clks[IMX6UL_CLK_PERIPH2] = imx_clk_busy_mux("periph2", base + 0x14, 26, 1, base + 0x48, 3, periph2_sels, ARRAY_SIZE(periph2_sels)); clks[<API key>] = imx_clk_divider("periph_clk2", "periph_clk2_sel", base + 0x14, 27, 3); clks[<API key>] = imx_clk_divider("periph2_clk2", "periph2_clk2_sel", base + 0x14, 0, 3); clks[IMX6UL_CLK_IPG] = imx_clk_divider("ipg", "ahb", base + 0x14, 8, 2); clks[<API key>] = imx_clk_divider("lcdif_podf", "lcdif_pred", base + 0x18, 23, 3); clks[<API key>] = imx_clk_divider("qspi1_podf", "qspi1_sel", base + 0x1c, 26, 3); clks[<API key>] = imx_clk_divider("eim_slow_podf", "eim_slow_sel", base + 0x1c, 23, 3); clks[IMX6UL_CLK_PERCLK] = imx_clk_divider("perclk", "perclk_sel", base + 0x1c, 0, 6); clks[IMX6UL_CLK_CAN_PODF] = imx_clk_divider("can_podf", "can_sel", base + 0x20, 2, 6); clks[<API key>] = imx_clk_divider("gpmi_podf", "gpmi_sel", base + 0x24, 22, 3); clks[IMX6UL_CLK_BCH_PODF] = imx_clk_divider("bch_podf", "bch_sel", base + 0x24, 19, 3); clks[<API key>] = imx_clk_divider("usdhc2_podf", "usdhc2_sel", base + 0x24, 16, 3); clks[<API key>] = imx_clk_divider("usdhc1_podf", "usdhc1_sel", base + 0x24, 11, 3); clks[<API key>] = imx_clk_divider("uart_podf", "uart_sel", base + 0x24, 0, 6); clks[<API key>] = imx_clk_divider("sai3_pred", "sai3_sel", base + 0x28, 22, 3); clks[<API key>] = imx_clk_divider("sai3_podf", "sai3_pred", base + 0x28, 16, 6); clks[<API key>] = imx_clk_divider("sai1_pred", "sai1_sel", base + 0x28, 6, 3); clks[<API key>] = imx_clk_divider("sai1_podf", "sai1_pred", base + 0x28, 0, 6); if (clk_on_imx6ull()) { clks[<API key>] = imx_clk_divider("esai_pred", "esai_sel", base + 0x28, 9, 3); clks[<API key>] = imx_clk_divider("esai_podf", "esai_pred", base + 0x28, 25, 3); } clks[<API key>] = imx_clk_divider("enfc_pred", "enfc_sel", base + 0x2c, 18, 3); clks[<API key>] = imx_clk_divider("enfc_podf", "enfc_pred", base + 0x2c, 21, 6); clks[<API key>] = imx_clk_divider("sai2_pred", "sai2_sel", base + 0x2c, 6, 3); clks[<API key>] = imx_clk_divider("sai2_podf", "sai2_pred", base + 0x2c, 0, 6); clks[<API key>] = imx_clk_divider("spdif_pred", "spdif_sel", base + 0x30, 25, 3); clks[<API key>] = imx_clk_divider("spdif_podf", "spdif_pred", base + 0x30, 22, 3); clks[IMX6UL_CLK_SIM_PODF] = imx_clk_divider("sim_podf", "sim_pre_sel", base + 0x34, 12, 3); clks[<API key>] = imx_clk_divider("ecspi_podf", "ecspi_sel", base + 0x38, 19, 6); clks[<API key>] = imx_clk_divider("lcdif_pred", "lcdif_pre_sel", base + 0x38, 12, 3); clks[IMX6UL_CLK_CSI_PODF] = imx_clk_divider("csi_podf", "csi_sel", base + 0x3c, 11, 3); clks[IMX6UL_CLK_ARM] = <API key>("arm", "pll1_sw", base + 0x10, 0, 3, base + 0x48, 16); clks[<API key>] = <API key>("mmdc_podf", "periph2", base + 0x14, 3, 3, base + 0x48, 2); clks[IMX6UL_CLK_AXI_PODF] = <API key>("axi_podf", "axi_sel", base + 0x14, 16, 3, base + 0x48, 0); clks[IMX6UL_CLK_AHB] = <API key>("ahb", "periph", base + 0x14, 10, 3, base + 0x48, 1); /* CCGR0 */ clks[IMX6UL_CLK_AIPSTZ1] = imx_clk_gate2("aips_tz1", "ahb", base + 0x68, 0); clks[IMX6UL_CLK_AIPSTZ2] = imx_clk_gate2("aips_tz2", "ahb", base + 0x68, 2); clks[IMX6UL_CLK_APBHDMA] = imx_clk_gate2("apbh_dma", "bch_podf", base + 0x68, 4); if (clk_on_imx6ul()) { clks[IMX6UL_CLK_CAAM_MEM] = imx_clk_gate2("caam_mem", "ahb", base + 0x68, 8); clks[<API key>] = imx_clk_gate2("caam_aclk", "ahb", base + 0x68, 10); clks[IMX6UL_CLK_CAAM_IPG] = imx_clk_gate2("caam_ipg", "ipg", base + 0x68, 12); } else if (clk_on_imx6ull()) { clks[IMX6ULL_CLK_DCP_CLK] = imx_clk_gate2("dcp", "ahb", base + 0x68, 10); clks[IMX6UL_CLK_ENET] = imx_clk_gate2("enet", "ipg", base + 0x68, 12); clks[IMX6UL_CLK_ENET_AHB] = imx_clk_gate2("enet_ahb", "ahb", base + 0x68, 12); } clks[IMX6UL_CLK_CAN1_IPG] = imx_clk_gate2("can1_ipg", "ipg", base + 0x68, 14); clks[<API key>] = imx_clk_gate2("can1_serial", "can_podf", base + 0x68, 16); clks[IMX6UL_CLK_CAN2_IPG] = imx_clk_gate2("can2_ipg", "ipg", base + 0x68, 18); clks[<API key>] = imx_clk_gate2("can2_serial", "can_podf", base + 0x68, 20); clks[IMX6UL_CLK_GPT2_BUS] = imx_clk_gate2("gpt2_bus", "perclk", base + 0x68, 24); clks[<API key>] = imx_clk_gate2("gpt2_serial", "perclk", base + 0x68, 26); clks[<API key>] = imx_clk_gate2("uart2_ipg", "ipg", base + 0x68, 28); clks[<API key>] = imx_clk_gate2("uart2_serial", "uart_podf", base + 0x68, 28); if (clk_on_imx6ul()) clks[IMX6UL_CLK_AIPSTZ3] = imx_clk_gate2("aips_tz3", "ahb", base + 0x68, 30); else if (clk_on_imx6ull()) clks[IMX6UL_CLK_AIPSTZ3] = imx_clk_gate2("aips_tz3", "ahb", base + 0x80, 18); /* CCGR1 */ clks[IMX6UL_CLK_ECSPI1] = imx_clk_gate2("ecspi1", "ecspi_podf", base + 0x6c, 0); clks[IMX6UL_CLK_ECSPI2] = imx_clk_gate2("ecspi2", "ecspi_podf", base + 0x6c, 2); clks[IMX6UL_CLK_ECSPI3] = imx_clk_gate2("ecspi3", "ecspi_podf", base + 0x6c, 4); clks[IMX6UL_CLK_ECSPI4] = imx_clk_gate2("ecspi4", "ecspi_podf", base + 0x6c, 6); clks[IMX6UL_CLK_ADC2] = imx_clk_gate2("adc2", "ipg", base + 0x6c, 8); clks[<API key>] = imx_clk_gate2("uart3_ipg", "ipg", base + 0x6c, 10); clks[<API key>] = imx_clk_gate2("uart3_serial", "uart_podf", base + 0x6c, 10); clks[IMX6UL_CLK_EPIT1] = imx_clk_gate2("epit1", "perclk", base + 0x6c, 12); clks[IMX6UL_CLK_EPIT2] = imx_clk_gate2("epit2", "perclk", base + 0x6c, 14); clks[IMX6UL_CLK_ADC1] = imx_clk_gate2("adc1", "ipg", base + 0x6c, 16); clks[IMX6UL_CLK_GPT1_BUS] = imx_clk_gate2("gpt1_bus", "perclk", base + 0x6c, 20); clks[<API key>] = imx_clk_gate2("gpt1_serial", "perclk", base + 0x6c, 22); clks[<API key>] = imx_clk_gate2("uart4_ipg", "ipg", base + 0x6c, 24); clks[<API key>] = imx_clk_gate2("uart4_serail", "uart_podf", base + 0x6c, 24); /* CCGR2 */ if (clk_on_imx6ull()) { clks[<API key>] = imx_clk_gate2("esai_extal", "esai_podf", base + 0x70, 0); clks[<API key>] = imx_clk_gate2("esai_ipg", "ahb", base + 0x70, 0); clks[<API key>] = imx_clk_gate2("esai_mem", "ahb", base + 0x70, 0); } clks[IMX6UL_CLK_CSI] = imx_clk_gate2("csi", "csi_podf", base + 0x70, 2); clks[IMX6UL_CLK_I2C1] = imx_clk_gate2("i2c1", "perclk", base + 0x70, 6); clks[IMX6UL_CLK_I2C2] = imx_clk_gate2("i2c2", "perclk", base + 0x70, 8); clks[IMX6UL_CLK_I2C3] = imx_clk_gate2("i2c3", "perclk", base + 0x70, 10); clks[IMX6UL_CLK_OCOTP] = imx_clk_gate2("ocotp", "ipg", base + 0x70, 12); clks[IMX6UL_CLK_IOMUXC] = imx_clk_gate2("iomuxc", "lcdif_podf", base + 0x70, 14); clks[<API key>] = imx_clk_gate2("lcdif_apb", "axi", base + 0x70, 28); clks[IMX6UL_CLK_PXP] = imx_clk_gate2("pxp", "axi", base + 0x70, 30); /* CCGR3 */ clks[<API key>] = imx_clk_gate2("uart5_ipg", "ipg", base + 0x74, 2); clks[<API key>] = imx_clk_gate2("uart5_serial", "uart_podf", base + 0x74, 2); if (clk_on_imx6ul()) { clks[IMX6UL_CLK_ENET] = imx_clk_gate2("enet", "ipg", base + 0x74, 4); clks[IMX6UL_CLK_ENET_AHB] = imx_clk_gate2("enet_ahb", "ahb", base + 0x74, 4); } else if (clk_on_imx6ull()) { clks[<API key>] = imx_clk_gate2("epdc_aclk", "axi", base + 0x74, 4); clks[<API key>] = imx_clk_gate2("epdc_pix", "epdc_podf", base + 0x74, 4); } clks[<API key>] = imx_clk_gate2("uart6_ipg", "ipg", base + 0x74, 6); clks[<API key>] = imx_clk_gate2("uart6_serial", "uart_podf", base + 0x74, 6); clks[<API key>] = imx_clk_gate2("lcdif_pix", "lcdif_podf", base + 0x74, 10); clks[IMX6UL_CLK_QSPI] = imx_clk_gate2("qspi1", "qspi1_podf", base + 0x74, 14); clks[IMX6UL_CLK_WDOG1] = imx_clk_gate2("wdog1", "ipg", base + 0x74, 16); clks[<API key>] = imx_clk_gate("mmdc_p0_fast", "mmdc_podf", base + 0x74, 20); clks[<API key>] = imx_clk_gate2("mmdc_p0_ipg", "ipg", base + 0x74, 24); clks[IMX6UL_CLK_AXI] = imx_clk_gate("axi", "axi_podf", base + 0x74, 28); /* CCGR4 */ clks[IMX6UL_CLK_PER_BCH] = imx_clk_gate2("per_bch", "bch_podf", base + 0x78, 12); clks[IMX6UL_CLK_PWM1] = imx_clk_gate2("pwm1", "perclk", base + 0x78, 16); clks[IMX6UL_CLK_PWM2] = imx_clk_gate2("pwm2", "perclk", base + 0x78, 18); clks[IMX6UL_CLK_PWM3] = imx_clk_gate2("pwm3", "perclk", base + 0x78, 20); clks[IMX6UL_CLK_PWM4] = imx_clk_gate2("pwm4", "perclk", base + 0x78, 22); clks[<API key>] = imx_clk_gate2("gpmi_bch_apb", "bch_podf", base + 0x78, 24); clks[IMX6UL_CLK_GPMI_BCH] = imx_clk_gate2("gpmi_bch", "gpmi_podf", base + 0x78, 26); clks[IMX6UL_CLK_GPMI_IO] = imx_clk_gate2("gpmi_io", "enfc_podf", base + 0x78, 28); clks[IMX6UL_CLK_GPMI_APB] = imx_clk_gate2("gpmi_apb", "bch_podf", base + 0x78, 30); /* CCGR5 */ clks[IMX6UL_CLK_ROM] = imx_clk_gate2("rom", "ahb", base + 0x7c, 0); clks[IMX6UL_CLK_SDMA] = imx_clk_gate2("sdma", "ahb", base + 0x7c, 6); clks[IMX6UL_CLK_KPP] = imx_clk_gate2("kpp", "ipg", base + 0x7c, 8); clks[IMX6UL_CLK_WDOG2] = imx_clk_gate2("wdog2", "ipg", base + 0x7c, 10); clks[IMX6UL_CLK_SPBA] = imx_clk_gate2("spba", "ipg", base + 0x7c, 12); clks[<API key>] = imx_clk_gate2("uart1_ipg", "ipg", base + 0x7c, 24); clks[<API key>] = imx_clk_gate2("uart1_serial", "uart_podf", base + 0x7c, 24); clks[<API key>] = imx_clk_gate2("uart7_ipg", "ipg", base + 0x7c, 26); clks[<API key>] = imx_clk_gate2("uart7_serial", "uart_podf", base + 0x7c, 26); /* CCGR6 */ clks[IMX6UL_CLK_USBOH3] = imx_clk_gate2("usboh3", "ipg", base + 0x80, 0); clks[IMX6UL_CLK_USDHC1] = imx_clk_gate2("usdhc1", "usdhc1_podf", base + 0x80, 2); clks[IMX6UL_CLK_USDHC2] = imx_clk_gate2("usdhc2", "usdhc2_podf", base + 0x80, 4); if (clk_on_imx6ul()) { clks[IMX6UL_CLK_SIM1] = imx_clk_gate2("sim1", "sim_sel", base + 0x80, 6); clks[IMX6UL_CLK_SIM2] = imx_clk_gate2("sim2", "sim_sel", base + 0x80, 8); } clks[IMX6UL_CLK_EIM] = imx_clk_gate2("eim", "eim_slow_podf", base + 0x80, 10); clks[IMX6UL_CLK_PWM8] = imx_clk_gate2("pwm8", "perclk", base + 0x80, 16); clks[<API key>] = imx_clk_gate2("uart8_ipg", "ipg", base + 0x80, 14); clks[<API key>] = imx_clk_gate2("uart8_serial", "uart_podf", base + 0x80, 14); clks[IMX6UL_CLK_WDOG3] = imx_clk_gate2("wdog3", "ipg", base + 0x80, 20); clks[IMX6UL_CLK_I2C4] = imx_clk_gate2("i2c4", "perclk", base + 0x80, 24); clks[IMX6UL_CLK_PWM5] = imx_clk_gate2("pwm5", "perclk", base + 0x80, 26); clks[IMX6UL_CLK_PWM6] = imx_clk_gate2("pwm6", "perclk", base + 0x80, 28); clks[IMX6UL_CLK_PWM7] = imx_clk_gate2("pwm7", "perclk", base + 0x80, 30); /* mask handshake of mmdc */ writel(<API key>, base + CCDR); clk_data.clks = clks; clk_data.clk_num = ARRAY_SIZE(clks); of_clk_add_provider(ccm_node, <API key>, &clk_data); /* * Lower the AHB clock rate before changing the parent clock source, * as AHB clock rate can NOT be higher than 133MHz, but its parent * will be switched from 396MHz PFD to 528MHz PLL in order to increase * AXI clock rate, so we need to lower AHB rate first to make sure at * any time, AHB rate is <= 133MHz. */ clk_set_rate(clks[IMX6UL_CLK_AHB], 99000000); /* Change periph_pre clock to pll2_bus to adjust AXI rate to 264MHz */ clk_set_parent(clks[<API key>], clks[<API key>]); clk_set_parent(clks[IMX6UL_CLK_PERIPH], clks[<API key>]); clk_set_parent(clks[<API key>], clks[IMX6UL_CLK_PLL2_BUS]); clk_set_parent(clks[IMX6UL_CLK_PERIPH], clks[<API key>]); /* Make sure AHB rate is 132MHz */ clk_set_rate(clks[IMX6UL_CLK_AHB], 132000000); /* set perclk to from OSC */ clk_set_parent(clks[<API key>], clks[IMX6UL_CLK_OSC]); clk_set_rate(clks[IMX6UL_CLK_ENET_REF], 50000000); clk_set_rate(clks[<API key>], 50000000); clk_set_rate(clks[IMX6UL_CLK_CSI], 24000000); /* keep all the clks on just for bringup */ for (i = 0; i < ARRAY_SIZE(clks_init_on); i++) clk_enable(clks[clks_init_on[i]]); if (IS_ENABLED(CONFIG_USB_IMX_PHY)) { clk_enable(clks[<API key>]); clk_enable(clks[<API key>]); } clk_set_parent(clks[IMX6UL_CLK_CAN_SEL], clks[IMX6UL_CLK_PLL3_60M]); if (clk_on_imx6ul()) clk_set_parent(clks[<API key>], clks[<API key>]); else if (clk_on_imx6ull()) clk_set_parent(clks[<API key>], clks[<API key>]); /* Disable GPMI_IO clk before reparenting to avoid glitches */ clks[IMX6UL_CLK_GPMI_IO]->ops->disable(clks[IMX6UL_CLK_GPMI_IO]); clk_set_parent(clks[IMX6UL_CLK_ENFC_SEL], clks[<API key>]); return 0; } static __maybe_unused struct of_device_id imx6_ccm_dt_ids[] = { { .compatible = "fsl,imx6ul-ccm", }, { /* sentinel */ } }; static struct driver_d imx6_ccm_driver = { .probe = imx6_ccm_probe, .name = "imx6-ccm", .of_compatible = DRV_OF_COMPAT(imx6_ccm_dt_ids), }; static int imx6_ccm_init(void) { return <API key>(&imx6_ccm_driver); } core_initcall(imx6_ccm_init);
# Read Back Comments This plugin will automatically add a button to the comment form to read back the current comment text. It makes use of the Speech Synthesis API and is therefor _not_ going to work in all browsers. But that's okay, because this is really just for fun. Inspired by [https: Support list: [http://caniuse.com/ ## TODO * Add i18n. * Handle support for other comment plugins (JetPack?) * Settings screen for voice settings
#include <config.h> #include <compat.h> #include <string.h> #include <stdlib.h> #undef strndup char * strndup(const char *s, size_t n) { size_t len; char *str; len = strnlen(s, n); str = malloc(len + 1); if (str == NULL) return NULL; memcpy(str, s, len); str[len] = '\0'; return str; }
package org.safehaus.penrose.filter; import java.util.Collection; public class SimpleFilter extends ItemFilter { String attribute; String operator; Object value; public SimpleFilter(String attribute, String operator, Object value) { this.attribute = attribute; this.operator = operator; this.value = value; } public String getAttribute() { return attribute; } public void setAttribute(String attribute) { this.attribute = attribute; } public String getOperator() { return operator; } public void setOperator(String operator) { this.operator = operator; } public Object getValue() { return value; } public void setValue(Object value) { this.value = value; } public int hashCode() { return (attribute == null ? 0 : attribute.hashCode()) + (operator == null ? 0 : operator.hashCode()) + (value == null ? 0 : value.hashCode()); } boolean equals(Object o1, Object o2) { if (o1 == null && o2 == null) return true; if (o1 != null) return o1.equals(o2); return o2.equals(o1); } public boolean equals(Object object) { if (this == object) return true; if (object == null) return false; if (object.getClass() != this.getClass()) return false; SimpleFilter simpleFilter = (SimpleFilter)object; if (!equals(attribute, simpleFilter.attribute)) return false; if (!equals(operator, simpleFilter.operator)) return false; if (!equals(value, simpleFilter.value)) return false; return true; } public String toString() { StringBuilder sb = new StringBuilder(); sb.append("("); sb.append(attribute); sb.append(operator); sb.append(FilterTool.escape(value)); sb.append(")"); return sb.toString(); } public String toString(Collection<Object> args) { StringBuilder sb = new StringBuilder(); sb.append("("); sb.append(attribute); sb.append(operator); sb.append("{"); sb.append(args.size()); sb.append("}"); sb.append(")"); args.add(value); return sb.toString(); } public Object clone() throws <API key> { SimpleFilter filter = (SimpleFilter)super.clone(); filter.attribute = attribute; filter.operator = operator; filter.value = value; return filter; } public boolean matches(Filter filter) throws Exception { if (filter == null) return false; if (filter == this) return true; if (filter.getClass() != getClass()) return false; SimpleFilter f = (SimpleFilter)filter; String name1 = attribute.toLowerCase(); String name2 = f.attribute.toLowerCase(); if (!"...".equals(name1) && !"...".equals(name2) && !name1.equals(name2)) return false; if (!operator.equals(f.operator)) return false; String value1 = value.toString().toLowerCase(); String value2 = f.value.toString().toLowerCase(); if (!"...".equals(value1) && !"...".equals(value2) && !value1.equals(value2)) return false; return true; } }
var app = angular.module('githubsearch', []); app.controller('SearchController', function SearchController($scope, GitHub) { $scope.errors = []; $scope.activeRepo = null; $scope.repos = []; $scope.user = null; $scope.query = null; $scope.reset = function() { $scope.activeRepo = null; $scope.user = null; }; $scope.executeSearch = function executeSearch() { $scope.reset(); GitHub.searchRepos($scope.query, function (error, data) { if (!error && data) { $scope.repos = data.items; } else { $scope.handleError(error); } }); }; $scope.openRepo = function openRepo(name) { GitHub.getRepo(name, function (error, data) { if (!error) { $scope.activeRepo = data; $scope.user = data.owner; $scope.getReadme(name); $scope.getUserRepos($scope.user.login); } else { $scope.handleError(error); } }); }; $scope.getReadme = function getReadme(name) { GitHub.getReadme(name, function(error, data) { if (!error) { $scope.activeRepo.readme = data; } else { $scope.activeRepo.readme = 'No README found!'; } }); }; $scope.getUserRepos = function getUserRepos(login) { GitHub.getUserRepos(login, function(error, data) { if (!error) { $scope.user.repos = data; } else { $scope.user.repos = []; $scope.handleError(error); } }); }; $scope.handleError = function handleError(data) { var error = data || { message: "Request failed." }; $scope.errors.push(error); console.error(data); }; }); app.factory('GitHub', function GitHub($http) { return { searchRepos: function searchRepos(query, callback) { $http.get('https://api.github.com/search/repositories', { params: { q: query } }) .success(function(data) { callback(null, data); }) .error(function(data, status) { callback(data); }); }, getRepo: function getRepo(name, callback) { $http.get('https://api.github.com/repos/' + name) .success(function(data) { callback(null, data); }) .error(function(data, status) { callback(data); }); }, getReadme: function getReadme(name, callback) { $http.get('https://api.github.com/repos/'+ name +'/readme') .success(function(data) { callback(null, atob(data.content)); }) .error(function(data, status) { callback(data); }); }, getUserRepos: function getUserRepos(name, callback) { $http.get('https://api.github.com/users/'+ name +'/repos') .success(function(data) { callback(null, data); }) .error(function(data, status) { callback(data); }); } }; });
<?php defined('_JEXEC') or die; class <API key> extends modQlformDatabase { /** * Method for construction darabase params * * @param string $database database name * @param string $table Name of table to save data in * * @return bool true on success, false on failure * */ function __construct($params) { $this->params=$params; } /** * Method for construction darabase params * * @param string $database database name * @param string $table Name of table to save data in * * @return bool true on success, false on failure * */ function getDatabase() { return JDatabaseDriver::getInstance($this->params); } /** * Method for getting Joomla! database name * * @return string database name * */ function getDatabaseName() { return $this->params['database']; } /** * Method for getting Joomla! prefix name * * @return string database name * */ function getPrefix() { return $this->params['prefix']; } /** * Method for getting Joomla! database name * * @return string database name * */ function getTableName($table) { return $table; } }
/* * Machine dependent MSP430X UART0 code. */ #include <stdlib.h> #include "contiki.h" #include "sys/energest.h" #include "dev/uart0.h" #include "dev/watchdog.h" #include "lib/ringbuf.h" #include "isr_compat.h" static int (*uart0_input_handler)(unsigned char c); static volatile uint8_t transmitting; #ifdef <API key> #define TX_WITH_INTERRUPT <API key> #else /* <API key> */ #define TX_WITH_INTERRUPT 1 #endif /* <API key> */ #if TX_WITH_INTERRUPT #define TXBUFSIZE 64 static struct ringbuf txbuf; static uint8_t txbuf_data[TXBUFSIZE]; #endif /* TX_WITH_INTERRUPT */ uint8_t uart0_active(void) { return (UCA0STAT & UCBUSY) | transmitting; } void uart0_set_input(int (*input)(unsigned char c)) { uart0_input_handler = input; } void uart0_writeb(unsigned char c) { watchdog_periodic(); #if TX_WITH_INTERRUPT /* Put the outgoing byte on the transmission buffer. If the buffer is full, we just keep on trying to put the byte into the buffer until it is possible to put it there. */ while(ringbuf_put(&txbuf, c) == 0); /* If there is no transmission going, we need to start it by putting the first byte into the UART. */ if(transmitting == 0) { transmitting = 1; UCA0TXBUF = ringbuf_get(&txbuf); } #else /* TX_WITH_INTERRUPT */ /* Loop until the transmission buffer is available. */ /*Enric while((IFG2 & UCA0TXIFG) == 0); */ while((UCA0STAT & UCBUSY)); /* Transmit the data. */ UCA0TXBUF = c; #endif /* TX_WITH_INTERRUPT */ } #if ! WITH_UIP /* If WITH_UIP is defined, putchar() is defined by the SLIP driver */ #endif /* ! WITH_UIP */ /** * Initalize the RS232 port. * */ void uart0_init(unsigned long ubr) { /* RS232 */ UCA0CTL1 |= UCSWRST; /* Hold peripheral in reset state */ UCA0CTL1 |= UCSSEL_2; /* CLK = SMCLK */ UCA0BR0 = 0x45; /* 8MHz/115200 = 69 = 0x45 */ UCA0BR1 = 0x00; UCA0MCTL = UCBRS_3; /* Modulation UCBRSx = 3 */ P3DIR &= ~0x20; /* P3.5 = USCI_A0 RXD as input */ P3DIR |= 0x10; /* P3.4 = USCI_A0 TXD as output */ P3SEL |= 0x30; /* P3.4,5 = USCI_A0 TXD/RXD */ /*UCA0CTL1 &= ~UCSWRST;*/ /* Initialize USCI state machine */ transmitting = 0; /* XXX Clear pending interrupts before enable */ IFG2 &= ~UCA0RXIFG; IFG2 &= ~UCA0TXIFG; UCA0CTL1 &= ~UCSWRST; /* Initialize USCI state machine **before** enabling interrupts */ IE2 |= UCA0RXIE; /* Enable UCA0 RX interrupt */ /* Enable USCI_A0 TX interrupts (if TX_WITH_INTERRUPT enabled) */ #if TX_WITH_INTERRUPT ringbuf_init(&txbuf, txbuf_data, sizeof(txbuf_data)); IE2 |= UCA0TXIE; /* Enable UCA0 TX interrupt */ #endif /* TX_WITH_INTERRUPT */ } ISR(USCIAB0RX, uart0_rx_interrupt) { uint8_t c; ENERGEST_ON(ENERGEST_TYPE_IRQ); if(UCA0STAT & UCRXERR) { c = UCA0RXBUF; /* Clear error flags by forcing a dummy read. */ } else { c = UCA0RXBUF; if(uart0_input_handler != NULL) { if(uart0_input_handler(c)) { LPM4_EXIT; } } } ENERGEST_OFF(ENERGEST_TYPE_IRQ); } #if TX_WITH_INTERRUPT ISR(USCIAB0TX, uart0_tx_interrupt) { ENERGEST_ON(ENERGEST_TYPE_IRQ); if((IFG2 & UCA0TXIFG)){ if(ringbuf_elements(&txbuf) == 0) { transmitting = 0; } else { UCA0TXBUF = ringbuf_get(&txbuf); } } /* In a stand-alone app won't work without this. Is the UG misleading? */ IFG2 &= ~UCA0TXIFG; ENERGEST_OFF(ENERGEST_TYPE_IRQ); } #endif /* TX_WITH_INTERRUPT */
<?php // no direct access defined('_JEXEC') or die('Restricted access'); jimport( 'joomla.plugin.plugin' ); class plgSystemRSD extends JPlugin { public function onAfterRoute() { $app = JFactory::getApplication(); if($app->isAdmin()){ return; } $menus = $app->getMenu('site'); $menu = $menus->getActive(); if(!$menu || $menu->home != 1) return; $doc = JFactory::getDocument(); if($doc->getType() != 'html') return; $params = JComponentHelper::getParams('com_xmlrpc'); if($params->get('show_rsd', 1)){ class_exists('XMLRPCHelperRoute') or require(JPATH_SITE.'/components/com_xmlrpc/helpers/route.php'); $link = JRoute::_(XMLRPCHelperRoute::getRsdRoute()); $doc->addHeadLink($link, 'EditURI', 'rel', array('type' => 'application/rsd+xml', 'title'=>'RSD')); } if($params->get('show_manifest', 1)){ class_exists('XMLRPCHelperRoute') or require(JPATH_SITE.'/components/com_xmlrpc/helpers/route.php'); $link = JRoute::_(XMLRPCHelperRoute::getManifestRoute()); $doc->addHeadLink($link, 'wlwmanifest', 'rel', array('type'=>'application/wlwmanifest+xml')); } } }
<!DOCTYPE html PUBLIC "- <html xmlns="http: <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.4"/> <title>Member List</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <!-- end header part --> <!-- Generated by Doxygen 1.8.4 --> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="pages.html"><span>Related&#160;Pages</span></a></li> <li><a href="modules.html"><span>Modules</span></a></li> <li><a href="namespaces.html"><span>Namespaces</span></a></li> <li class="current"><a href="annotated.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Files</span></a></li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="annotated.html"><span>Class&#160;List</span></a></li> <li><a href="hierarchy.html"><span>Class&#160;Hierarchy</span></a></li> <li><a href="functions.html"><span>Class&#160;Members</span></a></li> </ul> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="a00239.html">tbb</a></li><li class="navelem"><a class="el" href="a00022.html">blocked_range2d</a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="headertitle"> <div class="title">tbb::blocked_range2d&lt; RowValue, ColValue &gt; Member List</div> </div> </div><!--header <div class="contents"> <p>This is the complete list of members for <a class="el" href="a00022.html">tbb::blocked_range2d&lt; RowValue, ColValue &gt;</a>, including all inherited members.</p> <table class="directory"> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>blocked_range2d</b>(RowValue row_begin, RowValue row_end, typename row_range_type::size_type row_grainsize, ColValue col_begin, ColValue col_end, typename col_range_type::size_type col_grainsize) (defined in <a class="el" href="a00022.html">tbb::blocked_range2d&lt; RowValue, ColValue &gt;</a>)</td><td class="entry"><a class="el" href="a00022.html">tbb::blocked_range2d&lt; RowValue, ColValue &gt;</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>blocked_range2d</b>(RowValue row_begin, RowValue row_end, ColValue col_begin, ColValue col_end) (defined in <a class="el" href="a00022.html">tbb::blocked_range2d&lt; RowValue, ColValue &gt;</a>)</td><td class="entry"><a class="el" href="a00022.html">tbb::blocked_range2d&lt; RowValue, ColValue &gt;</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>blocked_range2d</b>(blocked_range2d &amp;r, split) (defined in <a class="el" href="a00022.html">tbb::blocked_range2d&lt; RowValue, ColValue &gt;</a>)</td><td class="entry"><a class="el" href="a00022.html">tbb::blocked_range2d&lt; RowValue, ColValue &gt;</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>blocked_range2d</b>(blocked_range2d &amp;r, proportional_split &amp;proportion) (defined in <a class="el" href="a00022.html">tbb::blocked_range2d&lt; RowValue, ColValue &gt;</a>)</td><td class="entry"><a class="el" href="a00022.html">tbb::blocked_range2d&lt; RowValue, ColValue &gt;</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>col_range_type</b> typedef (defined in <a class="el" href="a00022.html">tbb::blocked_range2d&lt; RowValue, ColValue &gt;</a>)</td><td class="entry"><a class="el" href="a00022.html">tbb::blocked_range2d&lt; RowValue, ColValue &gt;</a></td><td class="entry"></td></tr> <tr><td class="entry"><a class="el" href="a00022.html#<API key>">cols</a>() const </td><td class="entry"><a class="el" href="a00022.html">tbb::blocked_range2d&lt; RowValue, ColValue &gt;</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>do_split</b>(blocked_range2d &amp;r, Split &amp;split_obj) (defined in <a class="el" href="a00022.html">tbb::blocked_range2d&lt; RowValue, ColValue &gt;</a>)</td><td class="entry"><a class="el" href="a00022.html">tbb::blocked_range2d&lt; RowValue, ColValue &gt;</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr><td class="entry"><a class="el" href="a00022.html#<API key>">empty</a>() const </td><td class="entry"><a class="el" href="a00022.html">tbb::blocked_range2d&lt; RowValue, ColValue &gt;</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="a00022.html#<API key>">is_divisible</a>() const </td><td class="entry"><a class="el" href="a00022.html">tbb::blocked_range2d&lt; RowValue, ColValue &gt;</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr><td class="entry"><a class="el" href="a00022.html#<API key>"><API key></a></td><td class="entry"><a class="el" href="a00022.html">tbb::blocked_range2d&lt; RowValue, ColValue &gt;</a></td><td class="entry"><span class="mlabel">static</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="a00022.html#<API key>">row_range_type</a> typedef</td><td class="entry"><a class="el" href="a00022.html">tbb::blocked_range2d&lt; RowValue, ColValue &gt;</a></td><td class="entry"></td></tr> <tr><td class="entry"><a class="el" href="a00022.html#<API key>">rows</a>() const </td><td class="entry"><a class="el" href="a00022.html">tbb::blocked_range2d&lt; RowValue, ColValue &gt;</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> </table></div><!-- contents --> <hr> <p></p> Copyright &copy; 2005-2015 Intel Corporation. All Rights Reserved. <p></p> Intel, Pentium, Intel Xeon, Itanium, Intel XScale and VTune are registered trademarks or trademarks of Intel Corporation or its subsidiaries in the United States and other countries. <p></p> * Other names and brands may be claimed as the property of others.
<?php namespace Drupal\image_effects\Plugin\ImageToolkit\Operation\imagemagick; use Drupal\imagemagick\Plugin\ImageToolkit\Operation\imagemagick\<API key>; use Drupal\image_effects\Component\Rectangle; use Drupal\image_effects\Plugin\ImageToolkit\Operation\RotateTrait; /** * Defines ImageMagick Rotate operation. * * @<API key>( * id = "<API key>", * toolkit = "imagemagick", * operation = "rotate_ie", * label = @Translation("Rotate"), * description = @Translation("Rotate image.") * ) */ class Rotate extends <API key> { use RotateTrait; use <API key>; /** * {@inheritdoc} */ protected function execute(array $arguments) { $toolkit_arguments = $this->getToolkit()->arguments(); if ($this->getToolkit()->getExecManager()->getPackage() === 'graphicsmagick' && !empty($arguments['background'])) { // GraphicsMagick does not support alpha in background color. $arguments['background'] = substr($arguments['background'], 0, 7); } if (empty($arguments['background'])) { $format = $toolkit_arguments-><API key>() ?: $toolkit_arguments->getSourceFormat(); $mime_type = $this->getFormatMapper()-><API key>($format); if ($mime_type === 'image/jpeg') { // JPEG does not allow transparency. Set to fallback color. $this->addArgument('-background ' . $this->escapeArgument($arguments['<API key>'])); } else { $this->addArgument('-background transparent'); } } else { $this->addArgument('-background ' . $this->escapeArgument($arguments['background'])); } // Rotate. $this->addArgument('-rotate ' . $arguments['degrees']); $this->addArgument('+repage'); // Need to resize the image after rotation to make sure it complies with // the dimensions expected, calculated via the Rectangle class. if ($this->getToolkit()->getWidth() && $this->getToolkit()->getHeight()) { $box = new Rectangle($this->getToolkit()->getWidth(), $this->getToolkit()->getHeight()); $box = $box->rotate((float) $arguments['degrees']); return $this->getToolkit()->apply('resize', [ 'width' => $box->getBoundingWidth(), 'height' => $box->getBoundingHeight(), 'filter' => $arguments['resize_filter'], ]); } return TRUE; } }
// gchip - a simple recompiling chip-8 emulator // This program is free software; you can redistribute it and/or modify it // option) any later version. // This program is distributed in the hope that it will be useful, but // for more details. // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. #include <stdio.h> #include <stdlib.h> #include <assert.h> #include "xlat.h" #ifdef ARCH_X86 #define HOST_REGS 8 #else #define HOST_REGS 16 #endif // Generate an offset from the current translated instruction to addr. INLINE uint32_t memaddr(const xlat_block_t *xb, const void *addr, size_t length) { #ifdef ARCH_X86_64 int64_t off = (int64_t)addr - ((int64_t)xb->ptr + length); if (off < -0x7FFFFFFF || off > 0x7FFFFFFF) { log_err("offset: %p - %p = %p\n", xb->ptr + length, addr, (void *)off); assert(!"cannot create RIP offset over 4GB!"); } return (uint32_t)(off & 0xFFFFFFFF); #else return (uint32_t)((int32_t)addr - ((int32_t)xb->ptr + length)); #endif } // Write an arbitrary 8-bit value to the translation buffer. INLINE void emit_08(xlat_block_t *xb, uint8_t data) { *(uint8_t *)xb->ptr++ = data; } // Write an arbitrary 16-bit value to the translation buffer. INLINE void emit_16(xlat_block_t *xb, uint16_t data) { *(uint16_t *)xb->ptr = data; xb->ptr += 2; } // Write an arbitrary 24-bit value to the translation buffer. INLINE void emit_24(xlat_block_t *xb, uint32_t data) { *(uint8_t *)xb->ptr++ = data & 0xFF; *(uint8_t *)xb->ptr++ = (data >> 8) & 0xFF; *(uint8_t *)xb->ptr++ = (data >> 16) & 0xFF; } // Write an arbitrary 32-bit value to the translation buffer. INLINE void emit_32(xlat_block_t *xb, uint32_t data) { *(uint32_t *)xb->ptr = data; xb->ptr += 4; } // Write an arbitrary 64-bit value to the translation buffer. INLINE void emit_64(xlat_block_t *xb, uint64_t data) { *(uint64_t *)xb->ptr = data; xb->ptr += 8; } // Write a ModR/M formatted prefix byte to the translation buffer. INLINE void emit_modrm(xlat_block_t *xb, int mod, int reg, int rm) { emit_08(xb, (mod << 6) | ((reg & 7) << 3) | (rm & 7)); } // Write a SIB formatted prefix byte to the translation buffer. INLINE void emit_sib(xlat_block_t *xb, int scale, int index, int base) { emit_08(xb, (scale << 6) | ((index & 7) << 3) | (base & 7)); } #ifdef ARCH_X86_64 // Write a REX formatted prefix byte to the translation buffer. INLINE void emit_rex(xlat_block_t *xb, int w, int r, int x, int b) { emit_08(xb, 0x40 | ((w&1) << 3) | ((r&1) << 2) | ((x&1) << 1) | (b&1)); } INLINE void emit_rexr(xlat_block_t *xb, int w, int r) { if (w || (r >= 8)) emit_rex(xb, w, r >= 8, 0, 0); } INLINE void emit_rexb(xlat_block_t *xb, int w, int b) { if (w || (b >= 8)) emit_rex(xb, w, 0, 0, b >= 8); } INLINE void emit_rexrb(xlat_block_t *xb, int w, int r, int b) { if (w || (r >= 8) || (b >= 8)) emit_rex(xb, w, r >= 8, 0, b >= 8); } INLINE void emit_rexrxb(xlat_block_t *xb, int w, int r, int x, int b) { if (w || (r >= 8) || (x >= 8) || (b >= 8)) emit_rex(xb, w, r >= 8, x >= 8, b >= 8); } #else #define emit_rex(xb, w, r, x, b) #define emit_rexr(xb, w, r) #define emit_rexb(xb, w, b) #define emit_rexrb(xb, w, r, b) #define emit_rexrxb(xb, w, r, x, b) #endif void emit_call_func_0(xlat_state_t *xs, void *func) { int r0 = <API key>(xs, 32, 0); #ifdef PLATFORM_WIN32 xlat_emit_sub_sp(xs->xb, 32); #endif <API key>(xs->xb, (uint64_t)func, r0); xlat_emit_call_r64(xs->xb, r0); #ifdef PLATFORM_WIN32 xlat_emit_add_sp(xs->xb, 32); #endif } void emit_call_func_1(xlat_state_t *xs, void *func, uint64_t data1) { #ifdef PLATFORM_WIN32 xlat_emit_push_r32(xs->xb, 0); xlat_emit_push_r32(xs->xb, 1); xlat_emit_sub_sp(xs->xb, 32); #endif <API key>(xs->xb, data1, 1); <API key>(xs->xb, (uint64_t)func, 0); xlat_emit_call_r64(xs->xb, 0); #ifdef PLATFORM_WIN32 xlat_emit_add_sp(xs->xb, 32); xlat_emit_pop_r32(xs->xb, 1); xlat_emit_pop_r32(xs->xb, 0); #endif } void emit_call_func_2(xlat_state_t *xs, void *func, uint64_t data1, uint64_t data2) { #ifdef PLATFORM_WIN32 xlat_emit_push_r32(xs->xb, 0); xlat_emit_push_r32(xs->xb, 1); xlat_emit_push_r32(xs->xb, 2); xlat_emit_sub_sp(xs->xb, 32); #endif <API key>(xs->xb, data1, 1); <API key>(xs->xb, data2, 2); <API key>(xs->xb, (uint64_t)func, 0); xlat_emit_call_r64(xs->xb, 0); #ifdef PLATFORM_WIN32 xlat_emit_add_sp(xs->xb, 32); xlat_emit_pop_r32(xs->xb, 2); xlat_emit_pop_r32(xs->xb, 1); xlat_emit_pop_r32(xs->xb, 0); #endif } void emit_call_func_3(xlat_state_t *xs, void *func, uint64_t data1, uint64_t data2, uint64_t data3) { #ifdef PLATFORM_WIN32 xlat_emit_push_r32(xs->xb, 0); xlat_emit_push_r32(xs->xb, 1); xlat_emit_push_r32(xs->xb, 2); xlat_emit_push_r32(xs->xb, 8); xlat_emit_sub_sp(xs->xb, 32); #endif <API key>(xs->xb, data1, 1); <API key>(xs->xb, data2, 2); <API key>(xs->xb, data3, 8); <API key>(xs->xb, (uint64_t)func, 0); xlat_emit_call_r64(xs->xb, 0); #ifdef PLATFORM_WIN32 xlat_emit_add_sp(xs->xb, 32); xlat_emit_pop_r32(xs->xb, 8); xlat_emit_pop_r32(xs->xb, 2); xlat_emit_pop_r32(xs->xb, 1); xlat_emit_pop_r32(xs->xb, 0); #endif } void emit_call_func_4(xlat_state_t *xs, void *func, uint64_t data1, uint64_t data2, uint64_t data3, uint64_t data4) { #ifdef PLATFORM_WIN32 xlat_emit_push_r32(xs->xb, 0); xlat_emit_push_r32(xs->xb, 1); xlat_emit_push_r32(xs->xb, 2); xlat_emit_push_r32(xs->xb, 8); xlat_emit_push_r32(xs->xb, 9); xlat_emit_sub_sp(xs->xb, 32); #endif <API key>(xs->xb, data1, 1); <API key>(xs->xb, data2, 2); <API key>(xs->xb, data3, 8); <API key>(xs->xb, data4, 9); <API key>(xs->xb, (uint64_t)func, 0); xlat_emit_call_r64(xs->xb, 0); #ifdef PLATFORM_WIN32 xlat_emit_add_sp(xs->xb, 32); xlat_emit_pop_r32(xs->xb, 9); xlat_emit_pop_r32(xs->xb, 8); xlat_emit_pop_r32(xs->xb, 2); xlat_emit_pop_r32(xs->xb, 1); xlat_emit_pop_r32(xs->xb, 0); #endif } void xlat_emit_call_0(xlat_state_t *xs, void *f) { int rax = <API key>(xs, 32, 0); <API key>(xs->xb, (uint64_t)f, rax); xlat_emit_call_r64(xs->xb, rax); } void xlat_emit_call_1(xlat_state_t *xs, void *f, size_t d1) { int rax = <API key>(xs, 32, 0); int rdi = <API key>(xs, 32, 7); <API key>(xs->xb, d1, rdi); <API key>(xs->xb, (uint64_t)f, rax); xlat_emit_call_r64(xs->xb, rax); } void xlat_emit_call_2(xlat_state_t *xs, void *f, size_t d1, size_t d2) { int rax = <API key>(xs, 32, 0); int rdi = <API key>(xs, 32, 7); int rsi = <API key>(xs, 32, 6); <API key>(xs->xb, d1, rdi); <API key>(xs->xb, d2, rsi); <API key>(xs->xb, (uint64_t)f, rax); xlat_emit_call_r64(xs->xb, rax); } void xlat_emit_call_4(xlat_state_t *xs, void *f, size_t d1, size_t d2, size_t d3, size_t d4) { int rax = <API key>(xs, 32, 0); int rdi = <API key>(xs, 32, 7); int rsi = <API key>(xs, 32, 6); int rdx = <API key>(xs, 32, 2); int rcx = <API key>(xs, 32, 1); <API key>(xs->xb, d1, rdi); <API key>(xs->xb, d2, rsi); <API key>(xs->xb, d3, rdx); <API key>(xs->xb, d4, rcx); <API key>(xs->xb, (uint64_t)f, rax); xlat_emit_call_r64(xs->xb, rax); } void xlat_emit_call_5(xlat_state_t *xs, void *f, size_t d1, size_t d2, size_t d3, size_t d4, size_t d5) { int rax = <API key>(xs, 32, 0); int rdi = <API key>(xs, 32, 7); int rsi = <API key>(xs, 32, 6); int rdx = <API key>(xs, 32, 2); int rcx = <API key>(xs, 32, 1); int r08 = <API key>(xs, 32, 8); <API key>(xs->xb, d1, rdi); <API key>(xs->xb, d2, rsi); <API key>(xs->xb, d3, rdx); <API key>(xs->xb, d4, rcx); <API key>(xs->xb, d5, r08); <API key>(xs->xb, (uint64_t)f, rax); xlat_emit_call_r64(xs->xb, rax); } void xlat_emit_add_sp(xlat_block_t *xb, int bytes) { emit_rex(xb, 1, 0, 0, 0); emit_08(xb, 0x81); emit_modrm(xb, 3, 0, 4); emit_32(xb, bytes); } void xlat_emit_sub_sp(xlat_block_t *xb, int bytes) { emit_rex(xb, 1, 0, 0, 0); emit_08(xb, 0x81); emit_modrm(xb, 3, 5, 4); emit_32(xb, bytes); } void xlat_emit_push_i16(xlat_block_t *xb, uint16_t is) { emit_08(xb, 0x68); emit_32(xb, is); } void xlat_emit_push_r16(xlat_block_t *xb, int rs) { emit_08(xb, 0x66); emit_08(xb, 0x50 | rs); } void xlat_emit_push_i32(xlat_block_t *xb, uint32_t is) { emit_32(xb, is); } void xlat_emit_push_r32(xlat_block_t *xb, int rs) { emit_rex(xb, 0, 0, 0, rs >> 3); emit_08(xb, 0x50 | (rs & 7)); } void xlat_emit_pop_r16(xlat_block_t *xb, int rd) { emit_08(xb, 0x66); emit_08(xb, 0x58 | rd); } void xlat_emit_pop_r32(xlat_block_t *xb, int rd) { emit_rex(xb, 0, 0, 0, rd >> 3); emit_08(xb, 0x58 | (rd & 7)); } void xlat_emit_call_i32(xlat_block_t *xb, void *is) { uint64_t off = (uint64_t)is - ((uint64_t)xb->ptr + 5); assert((int64_t)off <= 0x7fffffff && (int64_t)off >= -0x7fffffff); emit_08(xb, 0xE8); emit_32(xb, (uint32_t)off); } void xlat_emit_call_r32(xlat_block_t *xb, int rs) { emit_08(xb, 0xFF); emit_modrm(xb, 3, 2, rs); } void xlat_emit_call_r64(xlat_block_t *xb, int rs) { emit_rexb(xb, 0, rs); emit_08(xb, 0xFF); emit_modrm(xb, 3, 2, rs); } void xlat_emit_or_r8r8(xlat_block_t *xb, int rs, int rd) { emit_rexrb(xb, 0, rs, rd); emit_08(xb, 0x08); emit_modrm(xb, 3, rs, rd); } void xlat_emit_and_r8r8(xlat_block_t *xb, int rs, int rd) { emit_rexrb(xb, 0, rd, rs); emit_08(xb, 0x22); emit_modrm(xb, 3, rd, rs); } void xlat_emit_xor_r8r8(xlat_block_t *xb, int rs, int rd) { emit_rexrb(xb, 0, rd, rs); emit_08(xb, 0x32); emit_modrm(xb, 3, rd, rs); } void xlat_emit_add_r8r8(xlat_block_t *xb, int rs, int rd) { emit_rexrb(xb, 0, rd, rs); emit_08(xb, 0x00); emit_modrm(xb, 3, rd, rs); } void xlat_emit_or_i8r8(xlat_block_t *xb, uint8_t imm, int rd) { emit_rexb(xb, 0, rd); emit_08(xb, 0x80); emit_modrm(xb, 3, 1, rd); emit_08(xb, imm); } void xlat_emit_and_i8r8(xlat_block_t *xb, uint8_t imm, int rd) { emit_rexb(xb, 0, rd); emit_08(xb, 0x80); emit_modrm(xb, 3, 4, rd); emit_08(xb, imm); } void xlat_emit_xor_i8r8(xlat_block_t *xb, uint8_t imm, int rd) { emit_rexb(xb, 0, rd); emit_08(xb, 0x80); emit_modrm(xb, 3, 6, rd); emit_08(xb, imm); } void xlat_emit_add_i8r8(xlat_block_t *xb, uint8_t imm, int rd) { emit_rexb(xb, 0, rd); emit_08(xb, 0x80); emit_modrm(xb, 3, 0, rd); emit_08(xb, imm); } void <API key>(xlat_block_t *xb, uint16_t imm, int rd) { } void <API key>(xlat_block_t *xb, uint16_t imm, int rd) { emit_08(xb, 0x66); emit_rexb(xb, 0, rd); emit_08(xb, 0x83); emit_modrm(xb, 3, 0, rd); emit_08(xb, imm); } void <API key>(xlat_block_t *xb, int rs, int rd) { emit_08(xb, 0x66); emit_rexrb(xb, 0, rd, rs); emit_08(xb, 0x03 ); emit_modrm(xb, 3, rd, rs); } void <API key>(xlat_block_t *xb, uint32_t is, int rd) { emit_rex(xb, 1, 0, 0, rd >> 3); if (rd == 0) { emit_08(xb, 0x05); } else { emit_08(xb, 0x81); emit_modrm(xb, 3, 0, rd); } emit_32(xb, is); } void <API key>(xlat_block_t *xb, int rs, int rd) { emit_rexrb(xb, 1, rs, rd); emit_08(xb, 0x01); emit_modrm(xb, 3, rs, rd); } void xlat_emit_mov_r8r8(xlat_block_t *xb, int rs, int rd) { emit_rexrb(xb, 0, rs, rd); emit_08(xb, 0x88); emit_modrm(xb, 3, rs, rd); } void xlat_emit_mov_r8m8(xlat_block_t *xb, int rs, uint8_t *md) { emit_rexr(xb, 0, rs); emit_08(xb, 0x88); emit_modrm(xb, 0, rs, 5); emit_32(xb, memaddr(xb, md, 4)); } void xlat_emit_mov_m8r8(xlat_block_t *xb, uint8_t *ms, int rd) { emit_rexr(xb, 0, rd); emit_08(xb, 0x8A); emit_modrm(xb, 0, rd, 5); emit_32(xb, memaddr(xb, ms, 4)); } void xlat_emit_mov_i8r8(xlat_block_t *xb, uint8_t is, int rd) { emit_rexb(xb, 0, rd); emit_08(xb, 0xB0 | (rd & 7)); emit_08(xb, is); } void xlat_emit_mov_i8m8(xlat_block_t *xb, uint8_t is, uint8_t *md) { emit_08(xb, 0xC6); emit_modrm(xb, 0, 0, 5); emit_32(xb, memaddr(xb, md, 5)); emit_08(xb, is); } // XXX: borrowed from PCSX2 -- rewrite me INLINE void WriteRmOffset(xlat_block_t *xb, int to, int32_t offset) { if ((to & 7) == 7) { if (offset == 0) { emit_modrm(xb, 0, 0, 4); emit_sib(xb, 0, 7, 4); } else if (offset < 128 && offset >= -128) { emit_modrm(xb, 1, 0, 4); emit_sib(xb, 0, 7, 4); emit_08(xb,offset); } else { emit_modrm(xb, 2, 0, 4); emit_sib(xb, 0, 7, 4); emit_32(xb,offset); } } else { if (offset == 0) { emit_modrm(xb, 0, 0, to); } else if (offset < 128 && offset >= -128) { emit_modrm(xb, 1, 0, to); emit_08(xb,offset); } else { emit_modrm(xb, 2, 0, to); emit_32(xb,offset); } } } // XXX: borrowed from PCSX2 -- rewrite me INLINE void WriteRmOffsetFrom(xlat_block_t *xb, int to, int from, int offset) { if ((from&7) == 4) { if( offset == 0 ) { emit_modrm(xb, 0, to, 0x4); emit_sib(xb, 0, 0x4, 0x4); } else if( offset < 128 && offset >= -128 ) { emit_modrm(xb, 1, to, 0x4); emit_sib(xb, 0, 0x4, 0x4); emit_08(xb, offset); } else { emit_modrm(xb, 2, to, 0x4); emit_sib(xb, 0, 0x4, 0x4); emit_32(xb, offset); } } else { if( offset == 0 ) { emit_modrm(xb, 0, to, from ); } else if( offset < 128 && offset >= -128 ) { emit_modrm(xb, 1, to, from ); emit_08(xb, offset); } else { emit_modrm(xb, 2, to, from ); emit_32(xb, offset); } } } void xlat_emit_mov_rmr8(xlat_block_t *xb, int rs, int rd) { emit_rexrb(xb, 0, rd, rs); emit_08(xb, 0x8A); WriteRmOffsetFrom(xb, rd, rs, 0); } void xlat_emit_mov_r8rm(xlat_block_t *xb, int rs, int rd) { emit_rexrb(xb, 0, rs, rd); emit_08(xb, 0x88); WriteRmOffsetFrom(xb, rs, rd, 0); } void <API key>(xlat_block_t *xb, int rs, uint16_t *md) { emit_08(xb, 0x66); emit_rexr(xb, 0, rs); emit_08(xb, 0x89); emit_modrm(xb, 0, rs, 5); emit_32(xb, memaddr(xb, md, 4)); } void <API key>(xlat_block_t *xb, uint16_t *ms, int rd) { emit_08(xb, 0x66); emit_rexr(xb, 0, rd); emit_08(xb, 0x8B); emit_modrm(xb, 0, rd, 5); emit_32(xb, memaddr(xb, ms, 4)); } void <API key>(xlat_block_t *xb, uint16_t is, int rd) { emit_08(xb, 0x66); emit_rexb(xb, 0, rd); emit_08(xb, 0xB8 | (rd & 0x7)); emit_16(xb, is); } void <API key>(xlat_block_t *xb, uint16_t is, uint16_t *md) { emit_08(xb, 0x66); emit_08(xb, 0xC7); emit_modrm(xb, 0, 0, 5); emit_32(xb, memaddr(xb, md, 6)); emit_16(xb, is); } void <API key>(xlat_block_t *xb, uint16_t is, int rb, int ri) { emit_08(xb, 0x66); emit_rexb(xb, 0, rb); emit_08(xb, 0xC7); emit_modrm(xb, 0, 0, 4); emit_sib(xb, 0, ri, rb); emit_16(xb, is); } void <API key>(xlat_block_t *xb, int rs, int rd, int off) { emit_08(xb, 0x66); emit_rexrb(xb, 0, rd, rs); emit_08(xb, 0x8B); WriteRmOffsetFrom(xb, rd, rs, off); } void <API key>(xlat_block_t *xb, uint16_t is, int rd, int off) { emit_08(xb, 0x66); emit_rexb(xb, 0, rd); emit_08(xb, 0xC7); WriteRmOffset(xb, rd, off); emit_16(xb, is); } void <API key>(xlat_block_t *xb, int rs, int rd, int off) { emit_08(xb, 0x66); emit_rexrb(xb, 0, rs, rd); emit_08(xb, 0x89); emit_modrm(xb, 0, rs, rd ); } void <API key>(xlat_block_t *xb, int rs, int rb, int ri, int scale) { emit_08(xb, 0x66); emit_rexrxb(xb, 0, rs, ri, rb); emit_08(xb, 0x8B); emit_modrm(xb, 0, rs, 0x4 ); emit_sib(xb, scale, ri, rb); } void <API key>(xlat_block_t *xb, int rb, int ri, int scale, int rd) { emit_08(xb, 0x66); emit_rexrxb(xb, 0, rd, ri, rb); emit_08(xb, 0x89); emit_modrm(xb, 0, rd, 0x4 ); emit_sib(xb, scale, ri, rb); } void <API key>(xlat_block_t *xb, int rs, int rd, int off) { emit_rexrb(xb, 1, rd, rs); emit_08(xb, 0x8B); WriteRmOffsetFrom(xb, rd, rs, off); } void <API key>(xlat_block_t *xb, int rs, int rd, int off) { emit_rexrb(xb, 1, rs, rd); emit_08(xb, 0x89); WriteRmOffsetFrom(xb, rs, rd, off); } void <API key>(xlat_block_t *xb, uint64_t is, int rd) { emit_rexb(xb, 1, rd); emit_08(xb, 0xB8 | (rd & 7)); emit_64(xb, is); } void <API key>(xlat_block_t *xb, uint8_t *is, int rd) { emit_rexr(xb, 0, rd); emit_16(xb, 0xB60F); emit_modrm(xb, 0, rd, 5); emit_32(xb, memaddr(xb, is, 4)); } void <API key>(xlat_block_t *xb, uint16_t *is, int rd) { emit_rexr(xb, 0, rd); emit_16(xb, 0xB70F); emit_modrm(xb, 0, rd, 5); emit_32(xb, memaddr(xb, is, 4)); } void <API key>(xlat_block_t *xb, uint8_t *is, int rd) { } void xlat_emit_cmp_r8r8(xlat_block_t *xb, int rs, int rd) { emit_rexrb(xb, 0, rs, rd); emit_08(xb, 0x3A); emit_modrm(xb, 3, rs, rd); } void xlat_emit_cmp_i8r8(xlat_block_t *xb, uint8_t i8, int rd) { emit_rexb(xb, 0, rd); if (rd == 0) { emit_08(xb, 0x3C); } else { emit_08(xb, 0x80 ); emit_modrm(xb, 3, 7, rd); } emit_08(xb, i8); } void <API key>(xlat_block_t *xb, int is, uint16_t *md) { } void <API key>(xlat_block_t *xb, int rs, uint16_t *md) { } void <API key>(xlat_block_t *xb, int rs, int rd) { emit_08(xb, 0x66); emit_rexrb(xb, 0, rd, rs); emit_08(xb, 0x0F); emit_08(xb, 0x44); emit_modrm(xb, 3, rd, rs); } void <API key>(xlat_block_t *xb, int rs, int rd) { emit_08(xb, 0x66); emit_rexrb(xb, 0, rd, rs); emit_08(xb, 0x0F); emit_08(xb, 0x45); emit_modrm(xb, 3, rd, rs); } void xlat_emit_ret(xlat_block_t *xb) { emit_08(xb, 0xC3); } void xlat_emit_shl_i8r64(xlat_block_t *xb, uint8_t imm, int rd) { emit_rexb(xb, 1, rd); if (imm == 1) { emit_08(xb, 0xD1); emit_modrm(xb, 3, 4, rd); } else { emit_08(xb, 0xC1); emit_modrm(xb, 3, 4, rd); emit_08(xb, imm); } } void xlat_emit_mul_r8(xlat_block_t *xb, int rs) { emit_rexb(xb, 0, rs); emit_08(xb, 0xF6); emit_modrm(xb, 3, 4, rs); } int xlat_alloc_state(xlat_state_t *xs) { int i; // allocate and populate host register list xs->num_free = HOST_REGS; xs->free_regs = (int *)malloc(sizeof(int) * HOST_REGS); for (i = 0; i < HOST_REGS; ++i) xs->free_regs[i] = i; // set all guest register mappings to unreserved state for (i = 0; i < GUEST_REGS; ++i) xs->reg_map[i] = -1; return 0; } void xlat_free_state(xlat_state_t *xs) { assert(NULL != xs->free_regs); SAFE_FREE(xs->free_regs); } int <API key>(xlat_state_t *xs, int bits, int reg, void *sync) { if ((reg >= 0) && (xs->reg_map[reg] >= 0)) { // the register is already reserved, just return its assigned index return xs->reg_map[reg]; } if (xs->num_free <= 0) { // we're out of registers, need to do a replacement... (TODO) assert(!"register replacement not yet implemented!"); return -1; } else { // pull the next unreserved host register from the free list int host_reg = xs->free_regs[--xs->num_free]; if ((reg < 0) || (NULL == sync)) return host_reg; assert((reg >= 0) && (NULL != sync)); xs->reg_map[reg] = host_reg; xs->reg_bits[reg] = bits; xs->reg_sync[reg] = sync; // initialize the register using the emulator context switch (bits) { default: assert(!"<API key>: invalid bit width specified"); // fall through to 8-bit for release builds case 8: <API key>(xs->xb, (uint8_t *)sync, host_reg); break; case 16: <API key>(xs->xb, (uint16_t *)sync, host_reg); break; } return host_reg; } } int <API key>(xlat_state_t *xs, int bits, int reg, void *sync) { if ((reg >= 0) && (xs->reg_map[reg] >= 0)) { // the register is already reserved, just return its assigned index return xs->reg_map[reg]; } if (xs->num_free <= 0) { // we're out of registers, need to do a replacement... (TODO) assert(!"register replacement not yet implemented!"); return -1; } else { // pull the next unreserved host register from the free list int host_reg = xs->free_regs[--xs->num_free]; if ((reg < 0) || (NULL == sync)) return host_reg; assert((reg >= 0) && (NULL != sync)); xs->reg_map[reg] = host_reg; xs->reg_bits[reg] = bits; xs->reg_sync[reg] = sync; return host_reg; } } int <API key>(xlat_state_t *xs, int bits) { return <API key>(xs, bits, -1, NULL); } int <API key>(xlat_state_t *xs, int bits, int index) { int i; for (i = 0; i < GUEST_REGS; i++) { if (xs->reg_map[i] == index) { log_spew("ejecting register index %d (%d)\n", index, i); xlat_free_register(xs, i); break; } } return index; } void <API key>(xlat_state_t *xs, int bits, int reg) { void *reg_sync = xs->reg_sync[reg]; int host_reg = xs->reg_map[reg]; if (host_reg < 0) return; switch (bits) { default: assert(!"xlat_free_register: invalid bit width specified"); // fall through to 8-bit for release builds case 8: xlat_emit_mov_r8m8(xs->xb, host_reg, (uint8_t *)reg_sync); break; case 16: <API key>(xs->xb, host_reg, (uint16_t *)reg_sync); break; } } void xlat_free_register(xlat_state_t *xs, int reg) { if (xs->reg_map[reg] < 0) { assert(!"attempting to free unreserved register"); return; } // write register back to the emulator context and add to unreserved list xs->free_regs[xs->num_free++] = xs->reg_map[reg]; <API key>(xs, xs->reg_bits[reg], reg); } void <API key>(xlat_state_t *xs, int host_reg) { xs->free_regs[xs->num_free++] = host_reg; } void xlat_emit_prologue(xlat_state_t *state) { // save the reserved registers to the stack before we continue #ifdef PLATFORM_WIN32 xlat_emit_push_r32(state->xb, 3); xlat_emit_push_r32(state->xb, 6); xlat_emit_push_r32(state->xb, 7); #else xlat_emit_push_r32(state->xb, 0xC); xlat_emit_push_r32(state->xb, 0xE); #endif // PLATFORM_WIN32 } void xlat_emit_epilogue(xlat_state_t *state) { int i; // commit updated registers to the emulator context for (i = 0; i < GUEST_REGS; ++i) if (state->reg_map[i] >= 0) xlat_free_register(state, i); // pop the reserved registers from the stack before returning to interpreter #ifdef PLATFORM_WIN32 xlat_emit_pop_r32(state->xb, 7); xlat_emit_pop_r32(state->xb, 6); xlat_emit_pop_r32(state->xb, 3); #else xlat_emit_pop_r32(state->xb, 0xE); xlat_emit_pop_r32(state->xb, 0xC); #endif // PLATFORM_WIN32 // generate a return to escape back to the interpreter xlat_emit_ret(state->xb); }
/* Monday 1st of June 2015 10:11:59 PM*/ .nextend-image { cursor: pointer; z-index: 10; overflow: hidden; position: relative; } .nextend-element .nextend-image{ margin-top: 0; } .<API key>{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/next/circle-button.png); width: 36px; height: 32px; } .<API key>:HOVER{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/next/circle-button.png); background-position: 36px 0; } .<API key>{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/previous/circle-button.png); width: 36px; height: 32px; } .<API key>:HOVER{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/previous/circle-button.png); background-position: 36px 0; } .<API key>{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/next/<API key>.png); width: 36px; height: 32px; } .<API key>:HOVER{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/next/<API key>.png); background-position: 36px 0; } .<API key>{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/previous/<API key>.png); width: 36px; height: 32px; } .<API key>:HOVER{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/previous/<API key>.png); background-position: 36px 0; } .<API key>{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/next/circle-button-cream.png); width: 36px; height: 36px; } .<API key>:HOVER{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/next/circle-button-cream.png); background-position: 36px 0; } .<API key>{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/previous/circle-button-cream.png); width: 36px; height: 36px; } .<API key>:HOVER{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/previous/circle-button-cream.png); background-position: 36px 0; } .<API key>{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/next/<API key>.png); width: 36px; height: 32px; } .<API key>:HOVER{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/next/<API key>.png); background-position: 36px 0; } .<API key>{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/previous/<API key>.png); width: 36px; height: 32px; } .<API key>:HOVER{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/previous/<API key>.png); background-position: 36px 0; } .<API key>{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/next/rectangle.png); width: 40px; height: 50px; } .<API key>:HOVER{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/next/rectangle.png); background-position: 40px 0; } .<API key>{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/previous/rectangle.png); width: 40px; height: 50px; } .<API key>:HOVER{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/previous/rectangle.png); background-position: 40px 0; } .<API key>{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/next/half-circle.png); width: 60px; height: 120px; } .<API key>:HOVER{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/next/half-circle.png); background-position: 60px 0; } .<API key>{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/previous/half-circle.png); width: 60px; height: 120px; } .<API key>:HOVER{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/previous/half-circle.png); background-position: 60px 0; } .<API key>{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/next/half-circle-cream.png); width: 58px; height: 126px; } .<API key>:HOVER{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/next/half-circle-cream.png); background-position: 70px 0; } .<API key>{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/previous/half-circle-cream.png); background-position: -6px 0; width: 58px; height: 126px; } .<API key>:HOVER{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/previous/half-circle-cream.png); background-position: 64px 0; } .<API key>{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/next/half-circle-small.png); width: 40px; height: 70px; } .<API key>:HOVER{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/next/half-circle-small.png); background-position: 40px 0; } .<API key>{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/previous/half-circle-small.png); width: 40px; height: 70px; } .<API key>:HOVER{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/previous/half-circle-small.png); background-position: 40px 0; } .<API key>{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/next/<API key>.png); width: 40px; height: 70px; } .<API key>:HOVER{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/next/<API key>.png); background-position: 40px 0; } .<API key>{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/previous/<API key>.png); width: 40px; height: 70px; } .<API key>:HOVER{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/previous/<API key>.png); background-position: 40px 0; } .<API key>{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/next/<API key>.png); width: 40px; height: 70px; } .<API key>:HOVER{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/next/<API key>.png); background-position: 40px 0; } .<API key>{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/previous/<API key>.png); width: 40px; height: 70px; } .<API key>:HOVER{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/previous/<API key>.png); background-position: 40px 0; } .<API key>{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/next/<API key>.png); width: 40px; height: 70px; } .<API key>:HOVER{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/next/<API key>.png); background-position: 40px 0; } .<API key>{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/previous/<API key>.png); width: 40px; height: 70px; } .<API key>:HOVER{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/previous/<API key>.png); background-position: 40px 0; } .<API key>{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/next/simple-white.png); width: 40px; height: 55px; } .<API key>:HOVER{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/next/simple-white.png); background-position: 40px 0; } .<API key>{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/previous/simple-white.png); width: 40px; height: 55px; } .<API key>:HOVER{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/previous/simple-white.png); background-position: 40px 0; } .<API key>{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/next/simple-black.png); width: 40px; height: 55px; } .<API key>:HOVER{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/next/simple-black.png); background-position: 40px 0; } .<API key>{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/previous/simple-black.png); width: 40px; height: 55px; } .<API key>:HOVER{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/previous/simple-black.png); background-position: 40px 0; } .<API key>{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/next/rounded-button-dark.png); width: 28px; height: 26px; } .<API key>:HOVER{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/next/rounded-button-dark.png); background-position: 30px 0; } .<API key>{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/previous/rounded-button-dark.png); width: 28px; height: 26px; } .<API key>:HOVER{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/previous/rounded-button-dark.png); background-position: 30px 0; } .<API key>{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/next/<API key>.png); width: 28px; height: 26px; } .<API key>:HOVER{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/next/<API key>.png); background-position: 30px 0; } .<API key>{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/previous/<API key>.png); width: 28px; height: 26px; } .<API key>:HOVER{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/previous/<API key>.png); background-position: 30px 0; } .<API key>{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/next/<API key>.png); width: 28px; height: 26px; } .<API key>:HOVER{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/next/<API key>.png); background-position: 30px 0; } .<API key>{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/previous/<API key>.png); width: 28px; height: 26px; } .<API key>:HOVER{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/previous/<API key>.png); background-position: 30px 0; } .<API key>{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/next/<API key>.png); width: 28px; height: 26px; } .<API key>:HOVER{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/next/<API key>.png); background-position: 30px 0; } .<API key>{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/previous/<API key>.png); width: 28px; height: 26px; } .<API key>:HOVER{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/previous/<API key>.png); background-position: 30px 0; } .<API key>{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/next/half-circle-outer.png); width: 60px; height: 120px; } .<API key>:HOVER{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/next/half-circle-outer.png); background-position: 60px 0; } .<API key>{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/previous/half-circle-outer.png); width: 60px; height: 120px; } .<API key>:HOVER{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/previous/half-circle-outer.png); background-position: 60px 0; } .<API key>{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/next/mini-light.png); width: 11px; height: 16px;; } .<API key>:HOVER{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/next/mini-light.png); background-position: 11px 0; } .<API key>{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/previous/mini-light.png); width: 11px; height: 16px; } .<API key>:HOVER{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/previous/mini-light.png); background-position: 11px 0; } .<API key>{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/next/mini-dark.png); width: 11px; height: 16px; } .<API key>:HOVER{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/next/mini-dark.png); background-position: 11px 0; } .<API key>{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/previous/mini-dark.png); width: 11px; height: 16px; } .<API key>:HOVER{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/previous/mini-dark.png); background-position: 11px 0; } .nextend-tab .<API key>, .nextend-tab .<API key>, .nextend-tab .<API key>, .nextend-tab .<API key>, .nextend-tab .<API key>, .nextend-tab .<API key>, .nextend-tab .<API key>, .nextend-tab .<API key>, .nextend-tab .<API key>, .nextend-tab .<API key>{ background-color: #5e5e5e; } .<API key>{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/next/circle.png); width: 70px; height: 64px; } .<API key>:HOVER{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/next/circle.png); background-position: 70px 0; } .<API key>{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/previous/circle.png); width: 70px; height: 64px; } .<API key>:HOVER{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/previous/circle.png); background-position: 70px 0; } .<API key>{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/next/circle-vertical.png); width: 70px; height: 64px; } .<API key>:HOVER{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/next/circle-vertical.png); background-position: 70px 0; } .<API key>{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/previous/circle-vertical.png); width: 70px; height: 64px; } .<API key>:HOVER{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/previous/circle-vertical.png); background-position: 70px 0; } .<API key>{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/next/<API key>.png); width: 31px; height: 31px; } .<API key>:HOVER{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/next/<API key>.png); background-position: 31px 0; } .<API key>{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/previous/<API key>.png); width: 31px; height: 31px; } .<API key>:HOVER{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/previous/circle-mini.png); background-position: 31px 0; } .<API key>{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/next/circle-mini.png); width: 31px; height: 31px; } .<API key>:HOVER{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/next/circle-mini.png); background-position: 31px 0; } .<API key>{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/previous/circle-mini.png); width: 31px; height: 31px; } .<API key>:HOVER{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/previous/circle-mini.png); background-position: 31px 0; } .<API key>{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/next/simple-arrow.png); width: 25px; height: 42px; } .<API key>:HOVER{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/next/simple-arrow.png); background-position: 25px 0; } .<API key>{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/previous/simple-arrow.png); width: 25px; height: 42px; } .<API key>:HOVER{ background-image: url(//localhost:8888/wp-content/plugins/<API key>/plugins/<API key>/image/image/previous/simple-arrow.png); background-position: 25px 0; }.<API key>{ z-index: 10; visibility: visible; display: inline-block; } .nextend-bullet{ cursor: pointer; } .nextend-bullet.active{ cursor: default; } .<API key> .nextend-bullet{ float: left; clear: left; } .nextend-bullet .<API key>.bullet-shadow-inner{ box-shadow: 0 1px 0 RGBA(255,255,255,.2), 0 1px 2px RGBA(0,0,0,.5) inset; } .nextend-bullet .<API key>.bullet-shadow-outer{ box-shadow: 0 1px 1px RGBA(0,0,0,.3); } .<API key>.nextend-bullet.<API key>.<API key>{ -<API key>: 99px; -moz-border-radius: 99px; border-radius: 99px; padding: 8px 10px; } .<API key>.nextend-bullet.<API key>.<API key>{ -<API key>: 99px; -moz-border-radius: 99px; border-radius: 99px; padding: 6px 10px; box-shadow: 0 0 0 1px RGBA(0,0,0,.5), 0 0 0 1px RGBA(255,255,255,.2) inset; } .<API key>.nextend-bullet.<API key>.bullet-bar-simple{ padding: 8px 10px; } .<API key>.nextend-bullet.<API key>.bullet-bar-elegant{ padding: 6px 10px; box-shadow: 0 0 0 1px RGBA(0,0,0,.5), 0 0 0 1px RGBA(255,255,255,.2) inset; } .<API key> .<API key>{ -webkit-transition: all 0.3s ease-out 0s; -moz-transition: all 0.3s ease-out 0s; -ms-transition: all 0.3s ease-out 0s; -o-transition: all 0.3s ease-out 0s; transition: all 0.3s ease-out 0s; display: inline-block; line-height: 14px !important; background: RGBA(0,0,0,0.6); text-align: center; } .<API key> .<API key> span{ font-size: 12px !important; line-height: 14px !important; } .<API key> .<API key>.active, .<API key> .<API key>:HOVER{ background: #7670C7; } .<API key>.<API key> .nextend-bullet{ margin: 4px; padding: 4px; width: 14px; height: 14px; } .<API key>.<API key> .nextend-bullet{ margin: 3px; padding: 4px; width: 14px; height: 14px; -<API key>: 99px; -moz-border-radius: 99px; border-radius: 99px; } .nextend-element .nextend-bullet span{ color: #fff; text-shadow: 0 1px 1px rgba(0, 0, 0, 0.5); line-height: 13px; padding: 3px; } .<API key> .<API key>{ margin-right: 10px; padding: 3px 8px; -<API key>: 50px; -moz-border-radius: 50px; border-radius: 50px; } /* Monday 1st of June 2015 10:11:10 PM*/ div#<API key> .<API key>.<API key> { z-index: 3; } div#<API key> .<API key>.<API key> { z-index: 2; } div#<API key> .<API key>.<API key> { z-index: 2; opacity: 1; } div#<API key> .<API key>.<API key> { z-index: 3; opacity: 1; } div#<API key> { margin: 0px 0px 0px 0px; position: relative; } div#<API key> * { font-size: inherit; line-height: inherit; } div#<API key> *, div#<API key> *:before, div#<API key> *:after { -moz-box-sizing: content-box; box-sizing: content-box; } div#<API key>.<API key> { position: absolute; opacity: 0; -webkit-transition: opacity 0.3s ease-in-out; -moz-transition: opacity 0.3s ease-in-out; transition: opacity 0.3s ease-in-out; } div#<API key>.<API key>.nextend-loaded { opacity: 1; position: relative; } div#<API key> a, div#<API key> a:focus { outline: none !important; } div#<API key> h1, div#<API key> h2, div#<API key> h3, div#<API key> h4, div#<API key> h5, div#<API key> h6, div#<API key> p { margin: 0; padding-left: 0; padding-right: 0; height: auto; width: auto; border: 0; box-shadow: none; } div#<API key> img { box-shadow: none; -<API key>: 0; -moz-border-radius: 0; border-radius: 0; background: transparent; background: none; padding: 0; margin: 0; border: 0; } div#<API key> .smart-slider-canvas { position: relative; } div#<API key> .smart-slider-canvas, div#<API key> .smart-slider-layer { overflow: hidden !important; } div#<API key> .<API key> { position: relative; width: 100%; height: 100%; } div#<API key> .sliderfont1 { color: #ffffff;font-size:320%;text-shadow: 0px 1px 1px RGBA(0,0,0,0.78);font-family: 'Open Sans',Arial;line-height: 1.3;font-weight: bold;font-style: normal;text-decoration: none;text-align: left;-moz-transition: padding-left 0.4s ease;-webkit-transition: padding-left 0.4s ease;-o-transition: padding-left 0.4s ease;transition: padding-left 0.4s ease;padding-left: 0px; } div#<API key> .sliderfont1 a, div#<API key> .sliderfont1 a:LINK, div#<API key> .sliderfont1 a:VISITED, div#<API key> .sliderfont1 a:FOCUS, div#<API key> .sliderfont1 a:ACTIVE { background: none; color: #ffffff;font-size:100%;text-shadow: 0px 1px 1px RGBA(0,0,0,0.78);font-family: 'Open Sans',Arial;line-height: 1.3;font-weight: bold;font-style: normal;text-decoration: none;text-align: left;-moz-transition: padding-left 0.4s ease;-webkit-transition: padding-left 0.4s ease;-o-transition: padding-left 0.4s ease;transition: padding-left 0.4s ease;padding-left: 0px; } div#<API key> .sliderfont1 a:HOVER { background: none; color: #ffffff;font-size:100%;text-shadow: 0px 1px 1px RGBA(0,0,0,0.78);font-family: 'Open Sans',Arial;line-height: 1.3;font-weight: bold;font-style: normal;text-decoration: none;text-align: left;-moz-transition: padding-left 0.4s ease;-webkit-transition: padding-left 0.4s ease;-o-transition: padding-left 0.4s ease;transition: padding-left 0.4s ease;padding-left: 0px; } div#<API key> .sliderfont2 { color: #000000;color: RGBA(0,0,0,0.86);font-size:320%;text-shadow: 0px 1px 0px RGBA(255,255,255,0.2);font-family: 'Open Sans',Arial;line-height: 1.3;font-weight: bold;font-style: normal;text-decoration: none;text-align: left;-moz-transition: padding-left 0.4s ease;-webkit-transition: padding-left 0.4s ease;-o-transition: padding-left 0.4s ease;transition: padding-left 0.4s ease;padding-left: 0px; } div#<API key> .sliderfont2 a, div#<API key> .sliderfont2 a:LINK, div#<API key> .sliderfont2 a:VISITED, div#<API key> .sliderfont2 a:FOCUS, div#<API key> .sliderfont2 a:ACTIVE { background: none; color: #000000;color: RGBA(0,0,0,0.86);font-size:100%;text-shadow: 0px 1px 0px RGBA(255,255,255,0.2);font-family: 'Open Sans',Arial;line-height: 1.3;font-weight: bold;font-style: normal;text-decoration: none;text-align: left;-moz-transition: padding-left 0.4s ease;-webkit-transition: padding-left 0.4s ease;-o-transition: padding-left 0.4s ease;transition: padding-left 0.4s ease;padding-left: 0px; } div#<API key> .sliderfont2 a:HOVER { background: none; color: #000000;color: RGBA(0,0,0,0.86);font-size:100%;text-shadow: 0px 1px 0px RGBA(255,255,255,0.2);font-family: 'Open Sans',Arial;line-height: 1.3;font-weight: bold;font-style: normal;text-decoration: none;text-align: left;-moz-transition: padding-left 0.4s ease;-webkit-transition: padding-left 0.4s ease;-o-transition: padding-left 0.4s ease;transition: padding-left 0.4s ease;padding-left: 0px; } div#<API key> .sliderfont3 { color: #ffffff;font-size:170%;text-shadow: 0px 1px 1px RGBA(0,0,0,0.78);font-family: 'Open Sans',Arial;line-height: 1.2;font-weight: normal;font-style: normal;text-decoration: none;text-align: left;-moz-transition: padding-left 0.4s ease;-webkit-transition: padding-left 0.4s ease;-o-transition: padding-left 0.4s ease;transition: padding-left 0.4s ease;padding-left: 0px; } div#<API key> .sliderfont3 a, div#<API key> .sliderfont3 a:LINK, div#<API key> .sliderfont3 a:VISITED, div#<API key> .sliderfont3 a:FOCUS, div#<API key> .sliderfont3 a:ACTIVE { background: none; color: #ffffff;font-size:100%;text-shadow: 0px 1px 1px RGBA(0,0,0,0.78);font-family: 'Open Sans',Arial;line-height: 1.2;font-weight: normal;font-style: normal;text-decoration: none;text-align: left;-moz-transition: padding-left 0.4s ease;-webkit-transition: padding-left 0.4s ease;-o-transition: padding-left 0.4s ease;transition: padding-left 0.4s ease;padding-left: 0px; } div#<API key> .sliderfont3 a:HOVER { background: none; color: #ffffff;font-size:100%;text-shadow: 0px 1px 1px RGBA(0,0,0,0.78);font-family: 'Open Sans',Arial;line-height: 1.2;font-weight: normal;font-style: normal;text-decoration: none;text-align: left;-moz-transition: padding-left 0.4s ease;-webkit-transition: padding-left 0.4s ease;-o-transition: padding-left 0.4s ease;transition: padding-left 0.4s ease;padding-left: 0px; } div#<API key> .sliderfont4 { color: #000000;color: RGBA(0,0,0,0.86);font-size:170%;text-shadow: 0px 1px 0px RGBA(255,255,255,0.2);font-family: 'Open Sans',Arial;line-height: 1.2;font-weight: normal;font-style: normal;text-decoration: none;text-align: left;-moz-transition: padding-left 0.4s ease;-webkit-transition: padding-left 0.4s ease;-o-transition: padding-left 0.4s ease;transition: padding-left 0.4s ease;padding-left: 0px; } div#<API key> .sliderfont4 a, div#<API key> .sliderfont4 a:LINK, div#<API key> .sliderfont4 a:VISITED, div#<API key> .sliderfont4 a:FOCUS, div#<API key> .sliderfont4 a:ACTIVE { background: none; color: #000000;color: RGBA(0,0,0,0.86);font-size:100%;text-shadow: 0px 1px 0px RGBA(255,255,255,0.2);font-family: 'Open Sans',Arial;line-height: 1.2;font-weight: normal;font-style: normal;text-decoration: none;text-align: left;-moz-transition: padding-left 0.4s ease;-webkit-transition: padding-left 0.4s ease;-o-transition: padding-left 0.4s ease;transition: padding-left 0.4s ease;padding-left: 0px; } div#<API key> .sliderfont4 a:HOVER { background: none; color: #000000;color: RGBA(0,0,0,0.86);font-size:100%;text-shadow: 0px 1px 0px RGBA(255,255,255,0.2);font-family: 'Open Sans',Arial;line-height: 1.2;font-weight: normal;font-style: normal;text-decoration: none;text-align: left;-moz-transition: padding-left 0.4s ease;-webkit-transition: padding-left 0.4s ease;-o-transition: padding-left 0.4s ease;transition: padding-left 0.4s ease;padding-left: 0px; } div#<API key> .sliderfont5 { color: #ffffff;font-size:114%;text-shadow: 0px 1px 1px RGBA(0,0,0,0.78);font-family: 'Open Sans',Arial;line-height: 1.4;font-weight: normal;font-style: normal;text-decoration: none;text-align: justify;-moz-transition: padding-left 0.4s ease;-webkit-transition: padding-left 0.4s ease;-o-transition: padding-left 0.4s ease;transition: padding-left 0.4s ease;padding-left: 0px; } div#<API key> .sliderfont5 a, div#<API key> .sliderfont5 a:LINK, div#<API key> .sliderfont5 a:VISITED, div#<API key> .sliderfont5 a:FOCUS, div#<API key> .sliderfont5 a:ACTIVE { background: none; color: #ffffff;font-size:100%;text-shadow: 0px 1px 1px RGBA(0,0,0,0.78);font-family: 'Open Sans',Arial;line-height: 1.4;font-weight: normal;font-style: normal;text-decoration: none;text-align: justify;-moz-transition: padding-left 0.4s ease;-webkit-transition: padding-left 0.4s ease;-o-transition: padding-left 0.4s ease;transition: padding-left 0.4s ease;padding-left: 0px; } div#<API key> .sliderfont5 a:HOVER { background: none; color: #ffffff;font-size:100%;text-shadow: 0px 1px 1px RGBA(0,0,0,0.78);font-family: 'Open Sans',Arial;line-height: 1.4;font-weight: normal;font-style: normal;text-decoration: none;text-align: justify;-moz-transition: padding-left 0.4s ease;-webkit-transition: padding-left 0.4s ease;-o-transition: padding-left 0.4s ease;transition: padding-left 0.4s ease;padding-left: 0px; } div#<API key> .sliderfont6 { color: #000000;color: RGBA(0,0,0,0.86);font-size:114%;text-shadow: 0px 1px 0px RGBA(255,255,255,0.2);font-family: 'Open Sans',Arial;line-height: 1.4;font-weight: normal;font-style: normal;text-decoration: none;text-align: justify;-moz-transition: padding-left 0.4s ease;-webkit-transition: padding-left 0.4s ease;-o-transition: padding-left 0.4s ease;transition: padding-left 0.4s ease;padding-left: 0px; } div#<API key> .sliderfont6 a, div#<API key> .sliderfont6 a:LINK, div#<API key> .sliderfont6 a:VISITED, div#<API key> .sliderfont6 a:FOCUS, div#<API key> .sliderfont6 a:ACTIVE { background: none; color: #000000;color: RGBA(0,0,0,0.86);font-size:100%;text-shadow: 0px 1px 0px RGBA(255,255,255,0.2);font-family: 'Open Sans',Arial;line-height: 1.4;font-weight: normal;font-style: normal;text-decoration: none;text-align: justify;-moz-transition: padding-left 0.4s ease;-webkit-transition: padding-left 0.4s ease;-o-transition: padding-left 0.4s ease;transition: padding-left 0.4s ease;padding-left: 0px; } div#<API key> .sliderfont6 a:HOVER { background: none; color: #000000;color: RGBA(0,0,0,0.86);font-size:100%;text-shadow: 0px 1px 0px RGBA(255,255,255,0.2);font-family: 'Open Sans',Arial;line-height: 1.4;font-weight: normal;font-style: normal;text-decoration: none;text-align: justify;-moz-transition: padding-left 0.4s ease;-webkit-transition: padding-left 0.4s ease;-o-transition: padding-left 0.4s ease;transition: padding-left 0.4s ease;padding-left: 0px; } div#<API key> .sliderfont7 { color: #ffffff;font-size:90%;text-shadow: 0px 1px 1px RGBA(0,0,0,0.78);font-family: 'Open Sans',Arial;line-height: 1.2;font-weight: normal;font-style: normal;text-decoration: none;text-align: left;-moz-transition: padding-left 0.4s ease;-webkit-transition: padding-left 0.4s ease;-o-transition: padding-left 0.4s ease;transition: padding-left 0.4s ease;padding-left: 0px; } div#<API key> .sliderfont7 a, div#<API key> .sliderfont7 a:LINK, div#<API key> .sliderfont7 a:VISITED, div#<API key> .sliderfont7 a:FOCUS, div#<API key> .sliderfont7 a:ACTIVE { background: none; color: #ffffff;font-size:100%;text-shadow: 0px 1px 1px RGBA(0,0,0,0.78);font-family: 'Open Sans',Arial;line-height: 1.2;font-weight: normal;font-style: normal;text-decoration: none;text-align: left;-moz-transition: padding-left 0.4s ease;-webkit-transition: padding-left 0.4s ease;-o-transition: padding-left 0.4s ease;transition: padding-left 0.4s ease;padding-left: 0px; } div#<API key> .sliderfont7 a:HOVER { background: none; color: #ffffff;font-size:100%;text-shadow: 0px 1px 1px RGBA(0,0,0,0.78);font-family: 'Open Sans',Arial;line-height: 1.2;font-weight: normal;font-style: normal;text-decoration: none;text-align: left;-moz-transition: padding-left 0.4s ease;-webkit-transition: padding-left 0.4s ease;-o-transition: padding-left 0.4s ease;transition: padding-left 0.4s ease;padding-left: 0px; } div#<API key> .sliderfont8 { color: #000000;color: RGBA(0,0,0,0.86);font-size:90%;text-shadow: 0px 1px 0px RGBA(255,255,255,0.2);font-family: 'Open Sans',Arial;line-height: 1.1;font-weight: normal;font-style: normal;text-decoration: none;text-align: left;-moz-transition: padding-left 0.4s ease;-webkit-transition: padding-left 0.4s ease;-o-transition: padding-left 0.4s ease;transition: padding-left 0.4s ease;padding-left: 0px; } div#<API key> .sliderfont8 a, div#<API key> .sliderfont8 a:LINK, div#<API key> .sliderfont8 a:VISITED, div#<API key> .sliderfont8 a:FOCUS, div#<API key> .sliderfont8 a:ACTIVE { background: none; color: #000000;color: RGBA(0,0,0,0.86);font-size:100%;text-shadow: 0px 1px 0px RGBA(255,255,255,0.2);font-family: 'Open Sans',Arial;line-height: 1.1;font-weight: normal;font-style: normal;text-decoration: none;text-align: left;-moz-transition: padding-left 0.4s ease;-webkit-transition: padding-left 0.4s ease;-o-transition: padding-left 0.4s ease;transition: padding-left 0.4s ease;padding-left: 0px; } div#<API key> .sliderfont8 a:HOVER { background: none; color: #000000;color: RGBA(0,0,0,0.86);font-size:100%;text-shadow: 0px 1px 0px RGBA(255,255,255,0.2);font-family: 'Open Sans',Arial;line-height: 1.1;font-weight: normal;font-style: normal;text-decoration: none;text-align: left;-moz-transition: padding-left 0.4s ease;-webkit-transition: padding-left 0.4s ease;-o-transition: padding-left 0.4s ease;transition: padding-left 0.4s ease;padding-left: 0px; } div#<API key> .sliderfont9 { color: #ffffff;font-size:140%;text-shadow: 0px 1px 1px RGBA(0,0,0,0.78);font-family: 'Pacifico',Arial;line-height: 1.3;font-weight: normal;font-style: normal;text-decoration: none;text-align: left;-moz-transition: padding-left 0.4s ease;-webkit-transition: padding-left 0.4s ease;-o-transition: padding-left 0.4s ease;transition: padding-left 0.4s ease;padding-left: 0px; } div#<API key> .sliderfont9 a, div#<API key> .sliderfont9 a:LINK, div#<API key> .sliderfont9 a:VISITED, div#<API key> .sliderfont9 a:FOCUS, div#<API key> .sliderfont9 a:ACTIVE { background: none; color: #ffffff;font-size:100%;text-shadow: 0px 1px 1px RGBA(0,0,0,0.78);font-family: 'Pacifico',Arial;line-height: 1.3;font-weight: normal;font-style: normal;text-decoration: none;text-align: left;-moz-transition: padding-left 0.4s ease;-webkit-transition: padding-left 0.4s ease;-o-transition: padding-left 0.4s ease;transition: padding-left 0.4s ease;padding-left: 0px; } div#<API key> .sliderfont9 a:HOVER { background: none; color: #ffffff;font-size:100%;text-shadow: 0px 1px 1px RGBA(0,0,0,0.78);font-family: 'Pacifico',Arial;line-height: 1.3;font-weight: normal;font-style: normal;text-decoration: none;text-align: left;-moz-transition: padding-left 0.4s ease;-webkit-transition: padding-left 0.4s ease;-o-transition: padding-left 0.4s ease;transition: padding-left 0.4s ease;padding-left: 0px; } div#<API key> .sliderfont10 { color: #000000;color: RGBA(0,0,0,0.86);font-size:140%;text-shadow: 0px 1px 0px RGBA(255,255,255,0.2);font-family: 'Pacifico',Arial;line-height: 1.3;font-weight: normal;font-style: normal;text-decoration: none;text-align: left;-moz-transition: padding-left 0.4s ease;-webkit-transition: padding-left 0.4s ease;-o-transition: padding-left 0.4s ease;transition: padding-left 0.4s ease;padding-left: 0px; } div#<API key> .sliderfont10 a, div#<API key> .sliderfont10 a:LINK, div#<API key> .sliderfont10 a:VISITED, div#<API key> .sliderfont10 a:FOCUS, div#<API key> .sliderfont10 a:ACTIVE { background: none; color: #000000;color: RGBA(0,0,0,0.86);font-size:100%;text-shadow: 0px 1px 0px RGBA(255,255,255,0.2);font-family: 'Pacifico',Arial;line-height: 1.3;font-weight: normal;font-style: normal;text-decoration: none;text-align: left;-moz-transition: padding-left 0.4s ease;-webkit-transition: padding-left 0.4s ease;-o-transition: padding-left 0.4s ease;transition: padding-left 0.4s ease;padding-left: 0px; } div#<API key> .sliderfont10 a:HOVER { background: none; color: #000000;color: RGBA(0,0,0,0.86);font-size:100%;text-shadow: 0px 1px 0px RGBA(255,255,255,0.2);font-family: 'Pacifico',Arial;line-height: 1.3;font-weight: normal;font-style: normal;text-decoration: none;text-align: left;-moz-transition: padding-left 0.4s ease;-webkit-transition: padding-left 0.4s ease;-o-transition: padding-left 0.4s ease;transition: padding-left 0.4s ease;padding-left: 0px; } div#<API key> .sliderfont11 { color: #ffffff;font-size:100%;text-shadow: 0px 1px 1px RGBA(0,0,0,0.78);font-family: 'Open Sans',Arial;line-height: 1.3;font-weight: normal;font-style: normal;text-decoration: none;text-align: center;-moz-transition: padding-left 0.4s ease;-webkit-transition: padding-left 0.4s ease;-o-transition: padding-left 0.4s ease;transition: padding-left 0.4s ease;padding-left: 0px; } div#<API key> .sliderfont11 a, div#<API key> .sliderfont11 a:LINK, div#<API key> .sliderfont11 a:VISITED, div#<API key> .sliderfont11 a:FOCUS, div#<API key> .sliderfont11 a:ACTIVE { background: none; color: #ffffff;font-size:100%;text-shadow: 0px 1px 1px RGBA(0,0,0,0.78);font-family: 'Open Sans',Arial;line-height: 1.3;font-weight: normal;font-style: normal;text-decoration: none;text-align: center;-moz-transition: padding-left 0.4s ease;-webkit-transition: padding-left 0.4s ease;-o-transition: padding-left 0.4s ease;transition: padding-left 0.4s ease;padding-left: 0px; } div#<API key> .sliderfont11 a:HOVER { background: none; color: #ffffff;font-size:100%;text-shadow: 0px 1px 1px RGBA(0,0,0,0.78);font-family: 'Open Sans',Arial;line-height: 1.3;font-weight: normal;font-style: normal;text-decoration: none;text-align: center;-moz-transition: padding-left 0.4s ease;-webkit-transition: padding-left 0.4s ease;-o-transition: padding-left 0.4s ease;transition: padding-left 0.4s ease;padding-left: 0px; } div#<API key> .sliderfont12 { color: #000000;color: RGBA(0,0,0,0.86);font-size:100%;text-shadow: 0px 1px 0px RGBA(255,255,255,0.2);font-family: 'Open Sans',Arial;line-height: 1.3;font-weight: normal;font-style: normal;text-decoration: none;text-align: center;-moz-transition: padding-left 0.4s ease;-webkit-transition: padding-left 0.4s ease;-o-transition: padding-left 0.4s ease;transition: padding-left 0.4s ease;padding-left: 0px; } div#<API key> .sliderfont12 a, div#<API key> .sliderfont12 a:LINK, div#<API key> .sliderfont12 a:VISITED, div#<API key> .sliderfont12 a:FOCUS, div#<API key> .sliderfont12 a:ACTIVE { background: none; color: #000000;color: RGBA(0,0,0,0.86);font-size:100%;text-shadow: 0px 1px 0px RGBA(255,255,255,0.2);font-family: 'Open Sans',Arial;line-height: 1.3;font-weight: normal;font-style: normal;text-decoration: none;text-align: center;-moz-transition: padding-left 0.4s ease;-webkit-transition: padding-left 0.4s ease;-o-transition: padding-left 0.4s ease;transition: padding-left 0.4s ease;padding-left: 0px; } div#<API key> .sliderfont12 a:HOVER { background: none; color: #000000;color: RGBA(0,0,0,0.86);font-size:100%;text-shadow: 0px 1px 0px RGBA(255,255,255,0.2);font-family: 'Open Sans',Arial;line-height: 1.3;font-weight: normal;font-style: normal;text-decoration: none;text-align: center;-moz-transition: padding-left 0.4s ease;-webkit-transition: padding-left 0.4s ease;-o-transition: padding-left 0.4s ease;transition: padding-left 0.4s ease;padding-left: 0px; } div#<API key> .sliderfontcustom1 { color: #1abc9c;font-size:360%;text-shadow: 0px 1px 1px RGBA(0,0,0,0.78);font-family: 'Pacifico',Arial;line-height: 1.3;font-weight: normal;font-style: normal;text-decoration: none;text-align: left;-moz-transition: padding-left 0.4s ease;-webkit-transition: padding-left 0.4s ease;-o-transition: padding-left 0.4s ease;transition: padding-left 0.4s ease;padding-left: 0px; } div#<API key> .sliderfontcustom1 a, div#<API key> .sliderfontcustom1 a:LINK, div#<API key> .sliderfontcustom1 a:VISITED, div#<API key> .sliderfontcustom1 a:FOCUS, div#<API key> .sliderfontcustom1 a:ACTIVE { background: none; color: #1abc9c;font-size:100%;text-shadow: 0px 1px 1px RGBA(0,0,0,0.78);font-family: 'Pacifico',Arial;line-height: 1.3;font-weight: normal;font-style: normal;text-decoration: none;text-align: left;-moz-transition: padding-left 0.4s ease;-webkit-transition: padding-left 0.4s ease;-o-transition: padding-left 0.4s ease;transition: padding-left 0.4s ease;padding-left: 0px; } div#<API key> .sliderfontcustom1 a:HOVER { background: none; color: #1abc9c;font-size:100%;text-shadow: 0px 1px 1px RGBA(0,0,0,0.78);font-family: 'Pacifico',Arial;line-height: 1.3;font-weight: normal;font-style: normal;text-decoration: none;text-align: left;-moz-transition: padding-left 0.4s ease;-webkit-transition: padding-left 0.4s ease;-o-transition: padding-left 0.4s ease;transition: padding-left 0.4s ease;padding-left: 0px; } div#<API key> .sliderfontcustom2 { color: #ffffff;font-size:140%;text-shadow: 0px 1px 1px RGBA(0,0,0,0.78);font-family: 'Open Sans',Arial;line-height: 1.2;font-weight: normal;font-style: normal;text-decoration: none;text-align: center;-moz-transition: padding-left 0.4s ease;-webkit-transition: padding-left 0.4s ease;-o-transition: padding-left 0.4s ease;transition: padding-left 0.4s ease;padding-left: 0px; } div#<API key> .sliderfontcustom2 a, div#<API key> .sliderfontcustom2 a:LINK, div#<API key> .sliderfontcustom2 a:VISITED, div#<API key> .sliderfontcustom2 a:FOCUS, div#<API key> .sliderfontcustom2 a:ACTIVE { background: none; color: #ffffff;font-size:100%;text-shadow: 0px 1px 1px RGBA(0,0,0,0.78);font-family: 'Open Sans',Arial;line-height: 1.2;font-weight: normal;font-style: normal;text-decoration: none;text-align: center;-moz-transition: padding-left 0.4s ease;-webkit-transition: padding-left 0.4s ease;-o-transition: padding-left 0.4s ease;transition: padding-left 0.4s ease;padding-left: 0px; } div#<API key> .sliderfontcustom2 a:HOVER { background: none; color: #ffffff;font-size:100%;text-shadow: 0px 1px 1px RGBA(0,0,0,0.78);font-family: 'Open Sans',Arial;line-height: 1.2;font-weight: normal;font-style: normal;text-decoration: none;text-align: center;-moz-transition: padding-left 0.4s ease;-webkit-transition: padding-left 0.4s ease;-o-transition: padding-left 0.4s ease;transition: padding-left 0.4s ease;padding-left: 0px; } div#<API key> .sliderfontcustom3 { color: #1abc9c;font-size:120%;text-shadow: 0px 1px 1px RGBA(0,0,0,0.78);font-family: 'Open Sans',Arial;line-height: 1.2;font-weight: normal;font-style: normal;text-decoration: none;text-align: center;-moz-transition: padding-left 0.4s ease;-webkit-transition: padding-left 0.4s ease;-o-transition: padding-left 0.4s ease;transition: padding-left 0.4s ease;padding-left: 0px; } div#<API key> .sliderfontcustom3 a, div#<API key> .sliderfontcustom3 a:LINK, div#<API key> .sliderfontcustom3 a:VISITED, div#<API key> .sliderfontcustom3 a:FOCUS, div#<API key> .sliderfontcustom3 a:ACTIVE { background: none; color: #1abc9c;font-size:100%;text-shadow: 0px 1px 1px RGBA(0,0,0,0.78);font-family: 'Open Sans',Arial;line-height: 1.2;font-weight: normal;font-style: normal;text-decoration: none;text-align: center;-moz-transition: padding-left 0.4s ease;-webkit-transition: padding-left 0.4s ease;-o-transition: padding-left 0.4s ease;transition: padding-left 0.4s ease;padding-left: 0px; } div#<API key> .sliderfontcustom3 a:HOVER { background: none; color: #1abc9c;font-size:100%;text-shadow: 0px 1px 1px RGBA(0,0,0,0.78);font-family: 'Open Sans',Arial;line-height: 1.2;font-weight: normal;font-style: normal;text-decoration: none;text-align: center;-moz-transition: padding-left 0.4s ease;-webkit-transition: padding-left 0.4s ease;-o-transition: padding-left 0.4s ease;transition: padding-left 0.4s ease;padding-left: 0px; } div#<API key> .sliderfontcustom4 { color: #1abc9c;font-size:120%;text-shadow: 0px 1px 1px RGBA(0,0,0,0.78);font-family: 'Open Sans',Arial;line-height: 1.2;font-weight: normal;font-style: normal;text-decoration: none;text-align: right;-moz-transition: padding-left 0.4s ease;-webkit-transition: padding-left 0.4s ease;-o-transition: padding-left 0.4s ease;transition: padding-left 0.4s ease;padding-left: 0px; } div#<API key> .sliderfontcustom4 a, div#<API key> .sliderfontcustom4 a:LINK, div#<API key> .sliderfontcustom4 a:VISITED, div#<API key> .sliderfontcustom4 a:FOCUS, div#<API key> .sliderfontcustom4 a:ACTIVE { background: none; color: #1abc9c;font-size:100%;text-shadow: 0px 1px 1px RGBA(0,0,0,0.78);font-family: 'Open Sans',Arial;line-height: 1.2;font-weight: normal;font-style: normal;text-decoration: none;text-align: right;-moz-transition: padding-left 0.4s ease;-webkit-transition: padding-left 0.4s ease;-o-transition: padding-left 0.4s ease;transition: padding-left 0.4s ease;padding-left: 0px; } div#<API key> .sliderfontcustom4 a:HOVER { background: none; color: #1abc9c;font-size:100%;text-shadow: 0px 1px 1px RGBA(0,0,0,0.78);font-family: 'Open Sans',Arial;line-height: 1.2;font-weight: normal;font-style: normal;text-decoration: none;text-align: right;-moz-transition: padding-left 0.4s ease;-webkit-transition: padding-left 0.4s ease;-o-transition: padding-left 0.4s ease;transition: padding-left 0.4s ease;padding-left: 0px; } div#<API key> .nextend-widget { display: none; -<API key>: hidden; -webkit-perspective: 1; } div#<API key>.nextend-desktop .<API key>, div#<API key>.nextend-tablet .<API key>, div#<API key>.nextend-phone .<API key> { display: block; } div#<API key> .<API key> { -webkit-transform: translate3d(0,0,0); } div#<API key> .<API key> { visibility: hidden; opacity: 0; -webkit-transition: opacity 0.4s ease; -moz-transition: opacity 0.4s ease; -o-transition: opacity 0.4s ease; transition: opacity 0.4s ease; } div#<API key>.<API key> .<API key> { opacity: 1; } div#<API key> .smart-slider-canvas .nextend-slide-bg { position: absolute; top: 0; left: 0; width: 100%; max-width: none !important; height: auto; background: rgba(0,0,0,0.002); } div#<API key> { width: 1400px; height: 550px; float: left; } .x-rtl div#<API key> { float: right; } div#<API key> .<API key> { position: relative; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; height: 550px; overflow: hidden; border-style: solid; border-width: 0px; border-color: #3E3E3E; border-color: RGBA(62,62,62,1); -<API key>: 0px; -<API key>: 0px; -<API key>: 0px; -<API key>: 0px; -<API key>: 0px; -<API key>: 0px; -<API key>: 0px; -<API key>: 0px; <API key>: 0px; <API key>: 0px; <API key>: 0px; <API key>: 0px; -moz-background-clip: padding-box; -<API key>: padding-box; background-clip: padding-box; background-repeat: repeat; background-position: 0 0; background-size: auto; } div#<API key> .<API key> { position: relative; width: 100%; height: 100%; -<API key>: 0px; -<API key>: 0px; -<API key>: 0px; -<API key>: 0px; -<API key>: 0px; -<API key>: 0px; -<API key>: 0px; -<API key>: 0px; <API key>: 0px; <API key>: 0px; <API key>: 0px; <API key>: 0px; -moz-background-clip: padding-box; -<API key>: padding-box; background-clip: padding-box; overflow: hidden; } .x-firefox div#<API key> .<API key> { opacity: 0.99999; } div#<API key> .smart-slider-canvas { position: absolute; top: 0; left: 0; width: 1400px; height: 550px; z-index: 2; display: block; -<API key>: hidden; } div#<API key> .<API key> { position: relative; width: 1400px; height: 550px; } div#<API key> .<API key> { z-index: 3; } div#<API key> .smart-slider-layer { position: absolute; } div#<API key> .nextend-flux { position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: 1; } div#<API key> .nextend-flux img { max-width: none !important; opacity: 0.999; } div#<API key> .current { border: 0; padding: 0; } #<API key> .<API key> .<API key>.nextend-bullet{ background:RGBA(0,0,0,0.38); } #<API key> .<API key> .<API key>.nextend-bullet.active, #<API key> .<API key> .<API key>.nextend-bullet:HOVER{ background:RGBA(118,112,199,1); } #<API key> .<API key>.nextend-bullet.<API key>.<API key>, #<API key> .<API key>.nextend-bullet.<API key>.<API key>, #<API key> .<API key>.nextend-bullet.<API key>.bullet-bar-simple, #<API key> .<API key>.nextend-bullet.<API key>.bullet-bar-elegant{ background:RGBA(0,0,0,0.38); } #<API key> .<API key> .qtip-content{ width:100px; height:60px; padding: 4px; } #<API key> .<API key> .qtip-content img{ box-shadow: 0 0px 0px 1px RGBA(255,255,255,.2); } #<API key> .<API key>{ background: RGBA(0,0,0,0.38); }div#<API key>.<API key>{position: absolute; opacity: 0;}
.center { margin: 0 auto; text-align: center } /* width */ .fifty-percent { width: 50%; } .ten-percent { width: 10%; } /* margin, padding */ .indent { padding-left: 40px; } .one-space { margin-left: .5em; } .top-div { margin-top: 50px } .small-links { font-size: .8em; padding-left: 5px; } .bottom-bar{ position: fixed; bottom: 0px; width: 100%; margin-bottom: 0px; } .center { margin: 0 auto; text-align: center; } .bottom-space { margin-bottom: 50px; } ul.off-canvas-list li a { display: block; padding: 0.66667rem; /*color: rgba(255, 255, 255, 0.7);*/ color: #da493a !important; border-bottom: 1px solid #262626; transition: background 300ms ease; }
<?php /** * @file * Default theme implementation to provide an HTML container for comments. */ ?> <div id="comments"> <div class="comment-count"> <?php if ($node->comment == 1 || $node->comment == 2): ?> <?php if ($node->comment_count == 0): ?> <h2><?php print t('No comments available.'); ?></h2> <?php elseif ($node->comment_count == 1): ?> <h2><?php print t('1 comment'); ?></h2> <?php else: ?> <h2><?php print 'comments'; ?></h2> <?php endif; ?> <?php endif; ?> </div> <?php print render($content['comments']); ?> <?php if ($content['comment_form']): ?> <h2 class="title comment-form"><?php print t('Add new comment'); ?></h2> <?php print render($content['comment_form']); ?> <?php endif; ?> </div>
package projet.ihm; import projet.datas.*; import projet.ctrl.*; import java.awt.*; import javax.swing.*; import java.util.*; import java.awt.event.*; import javax.swing.event.*; import java.io.*; import java.net.*; public class Interface extends JFrame implements Serializable { /** *version pour la sauvegarde Serializable. *@see Serializable */ private static final long serialVersionUID = 0; /** *Controleur de l'application. */ private Controleur ctrl; private JPanel panelBarreOutils; private JPanel panelNord; private JTextPane area; private Color couleurBorder; private JMenuBar bar; /** *items[0] : itemsFichier *items[1] : itemsEdition *items[2] : itemsExecution *items[3] : itemsAffichage *items[4] : itemsOutils *items[5] : itemsAide */ private JMenuItem[][] items; private Bouton[] boutons; public Interface(Controleur ctrl) { super("aucun projet"); this.ctrl = ctrl; couleurBorder = Color.BLACK; this.init(); this.creerInterface(); this.attacherReactions(); this.setMinimumSize(new Dimension(400, 300)); this.setSize( 600, 400 ); this.<API key>(null); this.setIconImage(new ImageIcon(getClass().getResource("/data/images/boutons/code.png")).getImage()); this.<API key> ( DO_NOTHING_ON_CLOSE ); } public void setMenuColor(Color couleur) { this.setBackground(couleur); panelBarreOutils.setBackground(couleur); bar.setBackground(couleur); bar.setBorder(BorderFactory.createLineBorder(couleur)); MenuElement[] elements = bar.getSubElements(); JComponent[] elements1 = new JComponent[elements.length]; for (int i = 0 ; i < elements.length ; i++) elements1[i] = (JMenu) elements[i]; setMenuColor(elements1, couleur); } private void setMenuColor(JComponent[] elements, Color couleur) { for (int i = 0 ; i < elements.length ; i++) { try { JMenu menu = (JMenu) elements[i]; menu.getPopupMenu().setBackground(couleur); Component[] tab1 = menu.getMenuComponents(); JComponent[] tab = new JComponent[tab1.length]; for (int j = 0 ; j < tab.length ; j++) { tab[j] = (JComponent) tab1[j]; } setMenuColor(tab, couleur); } catch (Exception e) {} elements[i].setBackground(couleur); elements[i].setBorder(BorderFactory.createLineBorder(couleur)); } } public Bouton[] getBoutons() { return boutons; } public void setTextInArea(String texte) { area.setText(texte); } public String getTextInArea() { return area.getText(); } public JTextPane getArea() { return area; } private void init() { panelBarreOutils = new JPanel(new FlowLayout(FlowLayout.LEFT)); panelBarreOutils.setBackground(Color.WHITE); panelNord = new JPanel(new BorderLayout()); area = new JTextPane(); area.setAutoscrolls(true); area.setEditable(false); initMenu(); initBoutons(); } private KeyStroke getCtrlKeyStroke(int charactere) { return KeyStroke.getKeyStroke(charactere, InputEvent.CTRL_MASK); } private void initMenu() { bar = new JMenuBar(); bar.setBackground(Color.WHITE); char[] mnemonics = {'F', 'E', 'A', 'O', '?'}; String[][] noms = {{"Fichier", "Nouveau", "Ouvrir", "Derniers projets", "Vider la liste", "Quitter"}, {"Projet", "Compiler", "Execution rapide", "Executer...", "Générer la javadoc", "Générer un jar file", "Infos sur le projet", "Gérer le classpath"}, {"Affichage", "Afficher Barre d'Outils", "Toujours afficher la fenetre"}, {"Outils", "Preferences", "Rechercher", "Réinitialiser recherche"}, {"?", "Aide", "A Propos", "Envoyer un retour"}}; KeyStroke[][] raccourcis = {{null, getCtrlKeyStroke(KeyEvent.VK_N), getCtrlKeyStroke(KeyEvent.VK_O), null, null, getCtrlKeyStroke(KeyEvent.VK_Q)}, {null, null, null, null, null, null, null, null}, {null, null, null}, {null, null, getCtrlKeyStroke(KeyEvent.VK_F), null}, {null, null, null, null}}; String[][] images = {{null, "/data/images/menus/new_15px.png", "/data/images/menus/open_15px.png", null, null, "/data/images/menus/exit_15px.png"}, {null, "/data/images/menus/code_15px.png", "/data/images/menus/run_15px.png", "/data/images/menus/run_15px.png", "/data/images/menus/java_15px.png", "/data/images/menus/java_15px.png", null, null}, {null, null, null}, {null, null, "/data/images/menus/research_15px.png", null}, {null, null, null, null}}; items = new JMenuItem[noms.length][]; for (int i = 0 ; i < items.length ; i++) items[i] = new JMenuItem[noms[i].length]; for (int i = 0 ; i < items.length ; i++) { for (int j = 0 ; j < items[i].length ; j++) { if (j == 0) { items[i][j] = new JMenu(noms[i][j]); items[i][j].setMnemonic(mnemonics[i]); } else if (i == 2) { if (j == 1) items[i][j] = new JCheckBoxMenuItem(noms[i][j], true); else items[i][j] = new JCheckBoxMenuItem(noms[i][j], false); } else if (i == 0 && j == 3) { items[i][j] = new JMenu(noms[i][j]); } else { items[i][j] = new JMenuItem(noms[i][j]); if (raccourcis[i][j] != null) items[i][j].setAccelerator(raccourcis[i][j]); } if (images[i][j] != null) items[i][j].setIcon(new ImageIcon(getClass().getResource(images[i][j]))); } } } private void initBoutons() { String[] pathImages = {"/data/images/boutons/new.png", "/data/images/boutons/open.png", "/data/images/boutons/code.png", "/data/images/boutons/run.png", "/data/images/boutons/java.png"}; boutons = new Bouton[pathImages.length]; String[] textes = {"", "", "Compiler", "Executer", "Javadoc"}; String[] toolTips = {"Nouveau projet", "Ouvrir un projet", "Compiler le projet", "Executer le main", "Générer la javadoc"}; for (int i = 0 ; i < boutons.length ; i++) { boutons[i] = new Bouton(textes[i], new ImageIcon(getClass().getResource(pathImages[i])), couleurBorder); boutons[i].setToolTipText(toolTips[i]); } boutons[3].setForeground(new Color(91, 192, 72)); } private void creerInterface() { this.setLayout(new BorderLayout(10, 0)); area.setBorder(BorderFactory.createLineBorder(couleurBorder)); //panelNord.setBorder(BorderFactory.createLineBorder(couleurBorder)); for (int i = 0 ; i < items.length ; i++) { bar.add(items[i][0]); for (int j = 1 ; j < items[i].length ; j++) { items[i][0].add(items[i][j]); if ((i == 0 && (j == 2 || j == 4)) || ((i == 1) && (j == 1 || j == 3 || j == 5)) || (i == 3 && j == 1) || (i == 4 && j == 2)) { ((JMenu) items[i][0]).addSeparator(); } } } this.setJMenuBar(bar); JScrollPane scroller = new JScrollPane(area); scroller.setAutoscrolls(true); this.add(panelNord, BorderLayout.NORTH); this.add(scroller, BorderLayout.CENTER); for (int i = 0 ; i < boutons.length ; i++) panelBarreOutils.add(boutons[i]); afficherBarreOutils(true); } public void afficherBarreOutils(boolean b) { panelNord.setVisible(false); panelNord.removeAll(); if (b)panelNord.add(panelBarreOutils, BorderLayout.NORTH); panelNord.setVisible(true); } private void attacherReactions() { this.addWindowListener(ctrl); for (int i = 0 ; i < items.length ; i++) { for (int j = 1 ; j < items[i].length ; j++) { items[i][j].addActionListener(ctrl); } } for (int i = 0 ; i < boutons.length ; i++) { boutons[i].addActionListener(ctrl); } } public JMenuItem[][] getItems() { return items; } }
#include <stdint.h> #include <stdio.h> #include <string.h> #include <sys/queue.h> #include <errno.h> #include <stdarg.h> #include <inttypes.h> #include <rte_common.h> #include <rte_memory.h> #include <rte_memzone.h> #include <rte_eal.h> #include <rte_byteorder.h> #include <rte_atomic.h> #include <rte_launch.h> #include <rte_per_lcore.h> #include <rte_lcore.h> #include <<API key>.h> #include <rte_debug.h> #include <rte_ring.h> #include <rte_log.h> #include <rte_mempool.h> #include <rte_memcpy.h> #include <rte_mbuf.h> #include <rte_interrupts.h> #include <rte_ether.h> #include <rte_ethdev.h> #include <rte_malloc.h> #include <rte_string_fns.h> #include <rte_cycles.h> #include "common.h" #include "args.h" #include "init.h" #define MBUFS_PER_CLIENT 1536 #define MBUFS_PER_PORT 1536 #define MBUF_CACHE_SIZE 512 #define <API key> 1024 #define <API key> 1024 #define <API key> 128 #define NO_FLAGS 0 /* The mbuf pool for packet rx */ struct rte_mempool *pktmbuf_pool; /* array of info/queues for clients */ struct client *clients = NULL; /* the port details */ struct port_info *ports; /** * Initialise the mbuf pool for packet reception for the NIC, and any other * buffer pools needed by the app - currently none. */ static int init_mbuf_pools(void) { const unsigned num_mbufs = (num_clients * MBUFS_PER_CLIENT) \ + (ports->num_ports * MBUFS_PER_PORT); /* don't pass single-producer/single-consumer flags to mbuf create as it * seems faster to use a cache instead */ printf("Creating mbuf pool '%s' [%u mbufs] ...\n", PKTMBUF_POOL_NAME, num_mbufs); pktmbuf_pool = <API key>(PKTMBUF_POOL_NAME, num_mbufs, MBUF_CACHE_SIZE, 0, <API key>, rte_socket_id()); return pktmbuf_pool == NULL; /* 0 on success */ } /** * Initialise an individual port: * - configure number of rx and tx rings * - set up each rx ring, to pull from the main mbuf pool * - set up each tx ring * - start the port and report its status to stdout */ static int init_port(uint16_t port_num) { /* for port configuration all features are off by default */ const struct rte_eth_conf port_conf = { .rxmode = { .mq_mode = ETH_MQ_RX_RSS } }; const uint16_t rx_rings = 1, tx_rings = num_clients; uint16_t rx_ring_size = <API key>; uint16_t tx_ring_size = <API key>; uint16_t q; int retval; printf("Port %u init ... ", port_num); fflush(stdout); /* Standard DPDK port initialisation - config port, then set up * rx and tx rings */ if ((retval = <API key>(port_num, rx_rings, tx_rings, &port_conf)) != 0) return retval; retval = <API key>(port_num, &rx_ring_size, &tx_ring_size); if (retval != 0) return retval; for (q = 0; q < rx_rings; q++) { retval = <API key>(port_num, q, rx_ring_size, <API key>(port_num), NULL, pktmbuf_pool); if (retval < 0) return retval; } for ( q = 0; q < tx_rings; q ++ ) { retval = <API key>(port_num, q, tx_ring_size, <API key>(port_num), NULL); if (retval < 0) return retval; } <API key>(port_num); retval = rte_eth_dev_start(port_num); if (retval < 0) return retval; printf( "done: \n"); return 0; } /** * Set up the DPDK rings which will be used to pass packets, via * pointers, between the multi-process server and client processes. * Each client needs one RX queue. */ static int init_shm_rings(void) { unsigned i; unsigned socket_id; const char * q_name; const unsigned ringsize = <API key>; clients = rte_malloc("client details", sizeof(*clients) * num_clients, 0); if (clients == NULL) rte_exit(EXIT_FAILURE, "Cannot allocate memory for client program details\n"); for (i = 0; i < num_clients; i++) { /* Create an RX queue for each client */ socket_id = rte_socket_id(); q_name = get_rx_queue_name(i); clients[i].rx_q = rte_ring_create(q_name, ringsize, socket_id, RING_F_SP_ENQ | RING_F_SC_DEQ ); /* single prod, single cons */ if (clients[i].rx_q == NULL) rte_exit(EXIT_FAILURE, "Cannot create rx ring queue for client %u\n", i); } return 0; } /* Check the link status of all ports in up to 9s, and print them finally */ static void <API key>(uint16_t port_num, uint32_t port_mask) { #define CHECK_INTERVAL 100 /* 100ms */ #define MAX_CHECK_TIME 90 /* 9s (90 * 100ms) in total */ uint16_t portid; uint8_t count, all_ports_up, print_flag = 0; struct rte_eth_link link; printf("\nChecking link status"); fflush(stdout); for (count = 0; count <= MAX_CHECK_TIME; count++) { all_ports_up = 1; for (portid = 0; portid < port_num; portid++) { if ((port_mask & (1 << ports->id[portid])) == 0) continue; memset(&link, 0, sizeof(link)); <API key>(ports->id[portid], &link); /* print link status if flag set */ if (print_flag == 1) { if (link.link_status) printf("Port %d Link Up - speed %u " "Mbps - %s\n", ports->id[portid], (unsigned)link.link_speed, (link.link_duplex == <API key>) ? ("full-duplex") : ("half-duplex\n")); else printf("Port %d Link Down\n", (uint8_t)ports->id[portid]); continue; } /* clear all_ports_up flag if any link down */ if (link.link_status == ETH_LINK_DOWN) { all_ports_up = 0; break; } } /* after finally printing all link status, get out */ if (print_flag == 1) break; if (all_ports_up == 0) { printf("."); fflush(stdout); rte_delay_ms(CHECK_INTERVAL); } /* set the print_flag if all ports up or timeout */ if (all_ports_up == 1 || count == (MAX_CHECK_TIME - 1)) { print_flag = 1; printf("done\n"); } } } /** * Main init function for the multi-process server app, * calls subfunctions to do each stage of the initialisation. */ int init(int argc, char *argv[]) { int retval; const struct rte_memzone *mz; uint16_t i, total_ports; /* init EAL, parsing EAL args */ retval = rte_eal_init(argc, argv); if (retval < 0) return -1; argc -= retval; argv += retval; /* get total number of ports */ total_ports = rte_eth_dev_count(); /* set up array for port data */ mz = rte_memzone_reserve(MZ_PORT_INFO, sizeof(*ports), rte_socket_id(), NO_FLAGS); if (mz == NULL) rte_exit(EXIT_FAILURE, "Cannot reserve memory zone for port information\n"); memset(mz->addr, 0, sizeof(*ports)); ports = mz->addr; /* parse additional, application arguments */ retval = parse_app_args(total_ports, argc, argv); if (retval != 0) return -1; /* initialise mbuf pools */ retval = init_mbuf_pools(); if (retval != 0) rte_exit(EXIT_FAILURE, "Cannot create needed mbuf pools\n"); /* now initialise the ports we will use */ for (i = 0; i < ports->num_ports; i++) { retval = init_port(ports->id[i]); if (retval != 0) rte_exit(EXIT_FAILURE, "Cannot initialise port %u\n", (unsigned)i); } <API key>(ports->num_ports, (~0x0)); /* initialise the client queues/rings for inter-eu comms */ init_shm_rings(); return 0; }
#!/usr/bin/perl # RRD script to display hardware temperature # This script should be run every 5 minutes. use strict; use warnings; use Device::SMBus; use Time::HiRes qw( usleep ualarm gettimeofday tv_interval nanosleep clock_gettime clock_getres clock_nanosleep clock stat ); use Data::Dumper; package Rrdpi::BarometricPressure; # Define the sensor registers. Many of these store calibration data # which is used to calculate temperature compensated pressure readings. use constant BMP180_CAL_AC1 => 0xAA; # Calibration data (16 bit) use constant BMP180_CAL_AC2 => 0xAC; # Calibration data (16 bit) use constant BMP180_CAL_AC3 => 0xAE; # Calibration data (16 bit) use constant BMP180_CAL_AC4 => 0xB0; # Calibration data (16 bit) use constant BMP180_CAL_AC5 => 0xB2; # Calibration data (16 bit) use constant BMP180_CAL_AC6 => 0xB4; # Calibration data (16 bit) use constant BMP180_CAL_B1 => 0xB6; # Calibration data (16 bit) use constant BMP180_CAL_B2 => 0xB8; # Calibration data (16 bit) use constant BMP180_CAL_MB => 0xBA; # Calibration data (16 bit) use constant BMP180_CAL_MC => 0xBC; # Calibration data (16 bit) use constant BMP180_CAL_MD => 0xBE; # Calibration data (16 bit) use constant BMP180_CONTROL => 0xF4; use constant BMP180_TEMPDATA => 0xF6; use constant BMP180_PRESSUREDATA => 0xF6; use constant BMP180_READTEMPCMD => 0x2E; use constant <API key> => 0x34; # Define a standard list of operating modes for the sensor. # These control the number of samples per second that the # sensor takes internally. use constant <API key> => 0; use constant BMP180_STANDARD => 1; use constant BMP180_HIRES => 2; use constant BMP180_ULTRAHIRES => 3; sub new { my ($class, $conf) = @_; my $self = {conf => $conf}; bless( $self, $class ); $self->{rrdParams} = $self->getRrdParams(); # Instantiate an SMBus object referring to the correct I2C bus # and the device address of the sensor. The Adafruit BMP180 # sensor always has an address of 0x77. The rev2 RPi puts the # primary I2C bus on i2c-1. The rev1 uses i2c-0. $self->{bmp180} = Device::SMBus->new( I2CBusDevicePath => '/dev/i2c-1', I2CDeviceAddress => 0x77, ); $self->{cal_AC1} = $self->readS16(BMP180_CAL_AC1); $self->{cal_AC2} = $self->readS16(BMP180_CAL_AC2); $self->{cal_AC3} = $self->readS16(BMP180_CAL_AC3); $self->{cal_AC4} = $self->readU16(BMP180_CAL_AC4); $self->{cal_AC5} = $self->readU16(BMP180_CAL_AC5); $self->{cal_AC6} = $self->readU16(BMP180_CAL_AC6); $self->{cal_B1} = $self->readS16(BMP180_CAL_B1); $self->{cal_B2} = $self->readS16(BMP180_CAL_B2); $self->{cal_MB} = $self->readS16(BMP180_CAL_MB); $self->{cal_MC} = $self->readS16(BMP180_CAL_MC); $self->{cal_MD} = $self->readS16(BMP180_CAL_MD); return $self; } sub getRrdParams { my ($self) = @_; return { name => 'pressure', datafiles => [$self->{conf}->{DBPATH}."/pressure.rrd"], picBase => [$self->{conf}->{OUTPATH}."/pressure-"], DS => ['pressure'], DSChecks => [], DSDescr => ['Barometric pressure'], rrdCreate => [ 'DS:pressure:GAUGE:300:500:1000', ], graphTitles => [''], rrdGraph => [ '--imgformat=PNG', '--title=Barometric pressure (mmHg)', "--width=".$self->{conf}->{GRAPH_WIDTH}, "--height=".$self->{conf}->{GRAPH_HEIGHT}, '--alt-autoscale', # '--slope-mode', 'DEF:pressure=DATAFILE:pressure:AVERAGE', 'AREA:pressure#3FCC50:pressure', 'COMMENT:\n', 'COMMENT:\n', ] }; } sub gather { my ($self) = @_; # Call the compensated pressure function to print barometric pressure # my $Temperature = $self->readTemp(); my $pressureHPa = $self->readPressure(BMP180_STANDARD) / 100.0; my $pressuremmHg = $pressureHPa*0.75006375541921; return ["N:$pressuremmHg"]; } sub readS8 { my ($self, $register) = @_; my $readVal = $self->{bmp180}->readByteData($register); if($readVal > 127) { $readVal -= 256; } return $readVal; } sub readS16 { my ($self, $register) = @_; my $readValHi = $self->readS8($register); my $readValLo = $self->{bmp180}->readByteData($register+1); my $bufferHi = $readValHi << 8; my $retVal = $bufferHi + $readValLo; return $retVal; } sub readU16 { my ($self,$register) = @_; my $readValHi = $self->{bmp180}->readByteData($register); my $readValLo = $self->{bmp180}->readByteData($register+1); my $bufferHi = $readValHi << 8; my $retVal = $bufferHi + $readValLo; return $retVal; } sub readRawTemp { my ($self) = @_; $self->{bmp180}->writeByteData(BMP180_CONTROL,BMP180_READTEMPCMD); # usleep takes microseconds, so this is 5 milliseconds Time::HiRes::usleep(5000); my $rawTemp = $self->readU16(BMP180_TEMPDATA); return $rawTemp; } # Read the raw (uncompensated) barometric pressure from the sensor sub readRawPressure { my ($self,$mode) = @_; my $writeVal = <API key> + ($mode << 6); $self->{bmp180}->writeByteData(BMP180_CONTROL,$writeVal); if ($mode == <API key>) { Time::HiRes::usleep(5000); } elsif ($mode == BMP180_HIRES) { Time::HiRes::usleep(14000); } elsif ($mode == BMP180_ULTRAHIRES) { Time::HiRes::usleep(26000); } else { Time::HiRes::usleep(8000); } my $msb = $self->{bmp180}->readByteData(BMP180_PRESSUREDATA); my $lsb = $self->{bmp180}->readByteData(BMP180_PRESSUREDATA+1); my $xlsb = $self->{bmp180}->readByteData(BMP180_PRESSUREDATA+2); my $rawPressure = (($msb << 16) + ($lsb << 8) + $xlsb) >> (8 - $mode); return $rawPressure; } # Read the compensated temperature sub readTemp { my ($self) = @_; my $UT = 0; my $X1 = 0; my $X2 = 0; my $B5 = 0; my $temp = 0.0; $UT = $self->readRawTemp(); use integer; $X1 = (($UT - $self->{cal_AC6}) * $self->{cal_AC5}) >> 15; $X2 = ($self->{cal_MC} << 11) / ($X1 + $self->{cal_MD}); $B5 = $X1 + $X2; no integer; $temp = (($B5 + 8) >> 4) / 10.0; return $temp; } # Read the compensated barometric pressure sub readPressure { my ($self,$mode) = @_; my $UT = $self->readRawTemp(); my $UP = $self->readRawPressure($mode); # Calculate true temperature, but don't convert to simple output format yet use integer; my $X1 = (($UT - $self->{cal_AC6}) * $self->{cal_AC5}) >> 15; my $X2 = ($self->{cal_MC} << 11) / ($X1 + $self->{cal_MD}); my $B5 = $X1 + $X2; no integer; my $temp = (($B5 + 8) >> 4) / 10.0; # Calculate compensated pressure use integer; my $B6 = $B5 - 4000; #printf "B6 = $B6\n"; $X1 = ($self->{cal_B2} * ($B6 * $B6) >> 12) >> 11; #printf "X1 = $X1\n"; $X2 = ($self->{cal_AC2} * $B6) >> 11; my $X3 = $X1 + $X2; my $B3 = ((($self->{cal_AC1} * 4 + $X3) << $mode) + 2) /4; $X1 = ($self->{cal_AC3} * $B6) >> 13; $X2 = ($self->{cal_B1} * (($B6 * $B6)) >> 12 ) >> 16; $X3 = (($X1 + $X2) + 2) >> 2; my $B4 = ($self->{cal_AC4} * ($X3 + 32768)) >> 15; my $B7 = ($UP - $B3) * (50000 >> $mode); my $p = 0; if ($B7 < 0x80000000) { $p = ($B7 * 2) / $B4; } else { $p = ($B7 / $B4) * 2; } $X1 = ($p >> 8) * ($p >> 8); $X1 = ($X1 * 3038) >> 16; $X2 = (-7357 * $p) >> 16; $p = $p + (($X1 + $X2 + 3791) >> 4); #printf "Calibration pressure is %d Pa\n", $p; return $p; } 1;
package com.web.crawler; import cn.edu.hfut.dmic.webcollector.model.Links; import cn.edu.hfut.dmic.webcollector.model.Page; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.io.xml.StaxDriver; import com.web.config.Config; import com.web.executor.parser.ParseTask; import com.web.parser.CSDNBlogParser; import com.web.scheduler.ParserTaskScheduler; import com.web.util.SpringFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.ClassPathResource; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import java.io.File; import java.io.IOException; import java.util.regex.Pattern; /** * @author jayson 2015-08-13 17:04 * @since v1.0 */ @Component("CSDNBlogCrawler") public class CSDNBlogCrawler extends Crawler { private static final Logger LOGGER = LoggerFactory.getLogger(CSDNBlogCrawler.class); @Autowired private ParserTaskScheduler scheduler; @Autowired private SpringFactory factory; @Autowired private Config config; @PostConstruct public void init() throws IOException { CrawlerInfo crawlerInfo = factory.create(CrawlerInfo.class); ClassPathResource resource = new ClassPathResource(config.get("CSDNBlogCrawler")); XStream xStream = new XStream(new StaxDriver()); xStream.alias("CrawlerInfo" , CrawlerInfo.class); xStream.alias("String" , String.class); xStream.fromXML(resource.getFile() , crawlerInfo); setCrawlerInfo(crawlerInfo); } @Override public void visit(Page page, Links nextLinks) { String url = page.getUrl(); for(Pattern p : patterns) { if (p.matcher(url).matches()) { try { ParseTask task = factory.create(ParseTask.class); CSDNBlogParser parser = factory.create(CSDNBlogParser.class); task.setPage(page); task.setParser(parser); scheduler.schedule(task); } catch (<API key> e) { LOGGER.error("" , e); } break; } } } @Override public String getCrawlPath() { return String.format("%s%s%s" , config.get("crawlerPath") , File.separator , crawlerInfo.getId()); } }
#include <stdio.h> #include <stdlib.h> #include <stddef.h> #include <string.h> #include <errno.h> #include <signal.h> #include <ctype.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/socket.h> #include <sys/un.h> #ifdef SOLARIS # include <sys/sockio.h> /* for Solaris 2.6: defines SIOCGIFCONF */ #endif #include <netinet/in.h> #include <arpa/inet.h> #include <sys/time.h> #include <sys/poll.h> /* only used for forensic poll call */ #include <netdb.h> #include <unistd.h> #include <fcntl.h> #include <net/if.h> #include <sys/ioctl.h> #include <arpa/nameser.h> /* missing from <resolv.h> on old systems */ #include <sys/resource.h> #include <sys/wait.h> #if defined(IP_RECVERR) && defined(MSG_ERRQUEUE) # include <asm/types.h> /* for __u8, __u32 */ # include <linux/errqueue.h> # include <sys/uio.h> /* struct iovec */ #endif #include <openswan.h> #include "sysdep.h" #include "constants.h" #include "defs.h" #include "state.h" #include "id.h" #include "x509.h" #include "pgp.h" #include "certs.h" #include "smartcard.h" #ifdef XAUTH_USEPAM #include <security/pam_appl.h> #endif #include "connections.h" /* needs id.h */ #include "kernel.h" /* for no_klips; needs connections.h */ #include "log.h" #include "server.h" #include "timer.h" #include "packet.h" #include "demux.h" /* needs packet.h */ #include "rcv_whack.h" #include "rcv_info.h" #include "keys.h" #include "adns.h" /* needs <resolv.h> */ #include "dnskey.h" /* needs keys.h and adns.h */ #include "whack.h" /* for RC_LOG_SERIOUS */ #include "pluto_crypt.h" /* cryptographic helper functions */ #include "udpfromto.h" #include <openswan/pfkeyv2.h> #include <openswan/pfkey.h> #include "kameipsec.h" #ifdef NAT_TRAVERSAL #include "nat_traversal.h" #endif /* * Server main loop and socket initialization routines. */ static const int on = TRUE; /* by-reference parameter; constant, we hope */ bool no_retransmits = FALSE; /* list of interface devices */ struct iface_list interface_dev; /* control (whack) socket */ int ctl_fd = NULL_FD; /* file descriptor of control (whack) socket */ struct sockaddr_un ctl_addr = { .sun_family=AF_UNIX, #if defined(HAS_SUN_LEN) .sun_len=sizeof(struct sockaddr_un), #endif .sun_path =DEFAULT_CTLBASE CTL_SUFFIX }; /* info (showpolicy) socket */ int policy_fd = NULL_FD; struct sockaddr_un info_addr= { .sun_family=AF_UNIX, #if defined(HAS_SUN_LEN) .sun_len=sizeof(struct sockaddr_un), #endif .sun_path =DEFAULT_CTLBASE INFO_SUFFIX }; /* Initialize the control socket. * Note: this is called very early, so little infrastructure is available. * It is important that the socket is created before the original * Pluto process returns. */ err_t init_ctl_socket(void) { err_t failed = NULL; LIST_INIT(&interface_dev); delete_ctl_socket(); /* preventative medicine */ ctl_fd = socket(AF_UNIX, SOCK_STREAM, 0); if (ctl_fd == -1) failed = "create"; else if (fcntl(ctl_fd, F_SETFD, FD_CLOEXEC) == -1) failed = "fcntl FD+CLOEXEC"; else if (setsockopt(ctl_fd, SOL_SOCKET, SO_REUSEADDR, (const void *)&on, sizeof(on)) < 0) failed = "setsockopt"; else { /* to keep control socket secure, use umask */ #ifdef PLUTO_GROUP_CTL mode_t ou = umask(~(S_IRWXU|S_IRWXG)); #else mode_t ou = umask(~S_IRWXU); #endif if (bind(ctl_fd, (struct sockaddr *)&ctl_addr , offsetof(struct sockaddr_un, sun_path) + strlen(ctl_addr.sun_path)) < 0) failed = "bind"; umask(ou); } #ifdef PLUTO_GROUP_CTL { struct group *g; g = getgrnam("pluto"); if(g != NULL) { if(fchown(ctl_fd, -1, g->gr_gid) != 0) { loglog(RC_LOG_SERIOUS, "Can not chgrp ctl fd(%d) to gid=%d: %s\n" , ctl_fd, g->gr_gid, strerror(errno)); } } } #endif /* 5 is a haphazardly chosen limit for the backlog. * Rumour has it that this is the max on BSD systems. */ if (failed == NULL && listen(ctl_fd, 5) < 0) failed = "listen() on"; return failed == NULL? NULL : builddiag("could not %s control socket: %d %s" , failed, errno, strerror(errno)); } void delete_ctl_socket(void) { /* Is noting failure useful? Not when used as preventative medicine. */ unlink(ctl_addr.sun_path); } #ifdef IPSECPOLICY /* Initialize the info socket. */ err_t init_info_socket(void) { err_t failed = NULL; delete_info_socket(); /* preventative medicine */ info_fd = socket(AF_UNIX, SOCK_STREAM, 0); if (info_fd == -1) failed = "create"; else if (fcntl(info_fd, F_SETFD, FD_CLOEXEC) == -1) failed = "fcntl FD+CLOEXEC"; else if (setsockopt(info_fd, SOL_SOCKET, SO_REUSEADDR, (const void *)&on, sizeof(on)) < 0) failed = "setsockopt"; else { /* this socket should be openable by all proceses */ mode_t ou = umask(0); if (bind(info_fd, (struct sockaddr *)&info_addr , offsetof(struct sockaddr_un, sun_path) + strlen(info_addr.sun_path)) < 0) failed = "bind"; umask(ou); } /* 64 might be big enough, and the system may limit us anyway. */ if (failed == NULL && listen(info_fd, 64) < 0) failed = "listen() on"; return failed == NULL? NULL : builddiag("could not %s info socket: %d %s" , failed, errno, strerror(errno)); } void delete_info_socket(void) { unlink(info_addr.sun_path); } #endif /* IPSECPOLICY */ bool listening = FALSE; /* should we pay attention to IKE messages? */ struct iface_port *interfaces = NULL; /* public interfaces */ /* Initialize the interface sockets. */ static void mark_ifaces_dead(void) { struct iface_port *p; for (p = interfaces; p != NULL; p = p->next) p->change = IFN_DELETE; } static void free_dead_iface_dev(struct iface_dev *id) { if(--id->id_count == 0) { pfree(id->id_vname); pfree(id->id_rname); LIST_REMOVE(id, id_entry); pfree(id); } } static void free_dead_ifaces(void) { struct iface_port *p; bool some_dead = FALSE , some_new = FALSE; for (p = interfaces; p != NULL; p = p->next) { if (p->change == IFN_DELETE) { openswan_log("shutting down interface %s/%s %s:%d" , p->ip_dev->id_vname , p->ip_dev->id_rname , ip_str(&p->ip_addr), p->port); some_dead = TRUE; } else if (p->change == IFN_ADD) { some_new = TRUE; } } if (some_dead) { struct iface_port **pp; <API key>(); for (pp = &interfaces; (p = *pp) != NULL; ) { if (p->change == IFN_DELETE) { struct iface_dev *id; *pp = p->next; /* advance *pp */ close(p->fd); id = p->ip_dev; pfree(p); free_dead_iface_dev(id); } else { pp = &p->next; /* advance pp */ } } } /* this must be done after the <API key> * in case some to the newly unoriented connections can * become oriented here. */ if (some_dead || some_new) check_orientations(); } void free_ifaces(void) { mark_ifaces_dead(); free_dead_ifaces(); } struct raw_iface *static_ifn=NULL; int create_socket(struct raw_iface *ifp, const char *v_name, int port) { int fd = socket(addrtypeof(&ifp->addr), SOCK_DGRAM, IPPROTO_UDP); int fcntl_flags; if (fd < 0) { log_errno((e, "socket() in process_raw_ifaces()")); return -1; } /* Set socket Nonblocking */ if ((fcntl_flags=fcntl(fd, F_GETFL)) >= 0) { if (!(fcntl_flags & O_NONBLOCK)) { fcntl_flags |= O_NONBLOCK; fcntl(fd, F_SETFL, fcntl_flags); } } if (fcntl(fd, F_SETFD, FD_CLOEXEC) == -1) { log_errno((e, "fcntl(,, FD_CLOEXEC) in process_raw_ifaces()")); close(fd); return -1; } if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR , (const void *)&on, sizeof(on)) < 0) { log_errno((e, "setsockopt SO_REUSEADDR in process_raw_ifaces()")); close(fd); return -1; } /* To improve error reporting. See ip(7). */ #if defined(IP_RECVERR) && defined(MSG_ERRQUEUE) if (setsockopt(fd, SOL_IP, IP_RECVERR , (const void *)&on, sizeof(on)) < 0) { log_errno((e, "setsockopt IP_RECVERR in process_raw_ifaces()")); close(fd); return -1; } #endif /* With IPv6, there is no fragmentation after * it leaves our interface. PMTU discovery * is mandatory but doesn't work well with IKE (why?). * So we must set the IPV6_USE_MIN_MTU option. * See <API key>.txt 11.1 */ #ifdef IPV6_USE_MIN_MTU /* YUCK: not always defined */ if (addrtypeof(&ifp->addr) == AF_INET6 && setsockopt(fd, SOL_SOCKET, IPV6_USE_MIN_MTU , (const void *)&on, sizeof(on)) < 0) { log_errno((e, "setsockopt IPV6_USE_MIN_MTU in process_raw_ifaces()")); close(fd); return -1; } #endif #if defined(linux) && defined(NETKEY_SUPPORT) if (kern_interface == USE_NETKEY) { struct sadb_x_policy policy; int level, opt; policy.sadb_x_policy_len = sizeof(policy) / IPSEC_PFKEYv2_ALIGN; policy.<API key> = SADB_X_EXT_POLICY; policy.sadb_x_policy_type = IPSEC_POLICY_BYPASS; policy.sadb_x_policy_dir = IPSEC_DIR_INBOUND; policy.<API key> = 0; policy.sadb_x_policy_id = 0; policy.<API key> = 0; if (addrtypeof(&ifp->addr) == AF_INET6) { level = IPPROTO_IPV6; opt = IPV6_IPSEC_POLICY; } else { level = IPPROTO_IP; opt = IP_IPSEC_POLICY; } if (setsockopt(fd, level, opt , &policy, sizeof(policy)) < 0) { log_errno((e, "setsockopt IPSEC_POLICY in process_raw_ifaces()")); close(fd); return -1; } policy.sadb_x_policy_dir = IPSEC_DIR_OUTBOUND; if (setsockopt(fd, level, opt , &policy, sizeof(policy)) < 0) { log_errno((e, "setsockopt IPSEC_POLICY in process_raw_ifaces()")); close(fd); return -1; } } #endif setportof(htons(port), &ifp->addr); if (bind(fd, sockaddrof(&ifp->addr), sockaddrlenof(&ifp->addr)) < 0) { log_errno((e, "bind() for %s/%s %s:%u in process_raw_ifaces()" , ifp->name, v_name , ip_str(&ifp->addr), (unsigned) port)); close(fd); return -1; } setportof(htons(pluto_port), &ifp->addr); #if defined(HAVE_UDPFROMTO) /* we are going to use udpfromto.c, so initialize it */ udpfromto_init(fd); #endif return fd; } void find_ifaces(void) { mark_ifaces_dead(); if(kernel_ops->process_ifaces) { #if !defined(__CYGWIN32__) kernel_ops->process_ifaces(find_raw_ifaces4()); kernel_ops->process_ifaces(find_raw_ifaces6()); #endif kernel_ops->process_ifaces(static_ifn); } free_dead_ifaces(); /* ditch remaining old entries */ if (interfaces == NULL) loglog(RC_LOG_SERIOUS, "no public interfaces found"); } void show_ifaces_status(void) { struct iface_port *p; for (p = interfaces; p != NULL; p = p->next) whack_log(RC_COMMENT, "interface %s/%s %s" , p->ip_dev->id_vname, p->ip_dev->id_rname, ip_str(&p->ip_addr)); } void show_debug_status(void) { #ifdef DEBUG whack_log(RC_COMMENT, "debug %s" , bitnamesof(debug_bit_names, cur_debugging)); #endif } static volatile sig_atomic_t sighupflag = FALSE; static void huphandler(int sig UNUSED) { sighupflag = TRUE; } static volatile sig_atomic_t sigtermflag = FALSE; static void termhandler(int sig UNUSED) { sigtermflag = TRUE; } static volatile sig_atomic_t sigchildflag = FALSE; static void childhandler(int sig UNUSED) { sigchildflag = TRUE; } /* perform wait4() on all children */ static void reapchildren(void) { pid_t child; int status; struct rusage r; sigchildflag = FALSE; errno=0; while((child = wait3(&status, WNOHANG, &r)) > 0) { /* got a child to reap */ if(adns_reapchild(child, status)) continue; if(<API key>(child, status)) continue; openswan_log("child pid=%d (status=%d) is not my child!", child, status); } if(child == -1) { openswan_log("reapchild failed with errno=%d %s", errno, strerror(errno)); } } /* call_server listens for incoming ISAKMP packets and Whack messages, * and handles timer events. */ void call_server(void) { struct iface_port *ifp; /* catch SIGHUP and SIGTERM */ { int r; struct sigaction act; act.sa_handler = &huphandler; sigemptyset(&act.sa_mask); act.sa_flags = 0; /* no SA_ONESHOT, no SA_RESTART, no nothing */ r = sigaction(SIGHUP, &act, NULL); passert(r == 0); act.sa_handler = &termhandler; r = sigaction(SIGTERM, &act, NULL); passert(r == 0); act.sa_handler = &childhandler; act.sa_flags = SA_RESTART; r = sigaction(SIGCHLD, &act, NULL); passert(r == 0); } for (;;) { fd_set readfds; fd_set writefds; int ndes; /* wait for next interesting thing */ for (;;) { long next_time = next_event(); /* time to any pending timer event */ int maxfd = ctl_fd; if (sigtermflag) exit_pluto(0); if (sighupflag) { /* Ignorant folks think poking any daemon with SIGHUP * is polite. We catch it and tell them otherwise. * There is one use: unsticking a hung recvfrom. * This sticking happens sometimes -- kernel bug? */ sighupflag = FALSE; openswan_log("Pluto ignores SIGHUP -- perhaps you want \"whack --listen\""); } if(sigchildflag) { reapchildren(); } FD_ZERO(&readfds); FD_ZERO(&writefds); FD_SET(ctl_fd, &readfds); #ifdef IPSECPOLICY FD_SET(info_fd, &readfds); if (maxfd < info_fd) maxfd = info_fd; #endif /* the only write file-descriptor of interest */ if (adns_qfd != NULL_FD && unsent_ADNS_queries) { if (maxfd < adns_qfd) maxfd = adns_qfd; FD_SET(adns_qfd, &writefds); } if (adns_afd != NULL_FD) { if (maxfd < adns_afd) maxfd = adns_afd; FD_SET(adns_afd, &readfds); } #ifdef KLIPS if (kern_interface != NO_KERNEL) { int fd = *kernel_ops->async_fdp; if (kernel_ops->process_queue) kernel_ops->process_queue(); if (maxfd < fd) maxfd = fd; passert(!FD_ISSET(fd, &readfds)); FD_SET(fd, &readfds); } #endif if (listening) { for (ifp = interfaces; ifp != NULL; ifp = ifp->next) { if (maxfd < ifp->fd) maxfd = ifp->fd; passert(!FD_ISSET(ifp->fd, &readfds)); FD_SET(ifp->fd, &readfds); } } /* see if helpers need attention */ <API key>(&readfds); if (no_retransmits || next_time < 0) { /* select without timer */ ndes = select(maxfd + 1, &readfds, &writefds, NULL, NULL); } else if (next_time == 0) { /* timer without select: there is a timer event pending, * and it should fire now so don't bother to do the select. */ ndes = 0; /* signify timer expiration */ } else { /* select with timer */ struct timeval tm; tm.tv_sec = next_time; tm.tv_usec = 0; ndes = select(maxfd + 1, &readfds, &writefds, NULL, &tm); } if (ndes != -1) break; /* success */ if (errno != EINTR) exit_log_errno((e, "select() failed in call_server()")); /* retry if terminated by signal */ } DBG(DBG_CONTROL, DBG_log(BLANK_FORMAT)); /* * we log the time when we are about to do something so that * we know what time things happened, when not using syslog */ if(<API key>) { time_t n; static time_t lastn = 0; time(&n); if(log_did_something) { lastn=n; log_did_something=FALSE; if((n-lastn) > 60) { DBG_log("time is %s (%lu)", ctime(&n), (unsigned long)n); } } } /* figure out what is interesting */ if (ndes == 0) { /* timer event */ if(!no_retransmits) { DBG(DBG_CONTROL, DBG_log("*time to handle event")); handle_timer_event(); passert(GLOBALS_ARE_RESET()); } } else { /* at least one file descriptor is ready */ if (adns_qfd != NULL_FD && FD_ISSET(adns_qfd, &writefds)) { passert(ndes > 0); <API key>(); passert(GLOBALS_ARE_RESET()); ndes } if (adns_afd != NULL_FD && FD_ISSET(adns_afd, &readfds)) { passert(ndes > 0); DBG(DBG_CONTROL, DBG_log("*received adns message")); handle_adns_answer(); passert(GLOBALS_ARE_RESET()); ndes } #ifdef KLIPS if (kern_interface != NO_KERNEL && FD_ISSET(*kernel_ops->async_fdp, &readfds)) { passert(ndes > 0); DBG(DBG_CONTROL, DBG_log("*received kernel message")); kernel_ops->process_msg(); passert(GLOBALS_ARE_RESET()); ndes } #endif for (ifp = interfaces; ifp != NULL; ifp = ifp->next) { if (FD_ISSET(ifp->fd, &readfds)) { /* comm_handle will print DBG_CONTROL intro, * with more info than we have here. */ passert(ndes > 0); comm_handle(ifp); passert(GLOBALS_ARE_RESET()); ndes } } if (FD_ISSET(ctl_fd, &readfds)) { passert(ndes > 0); DBG(DBG_CONTROL, DBG_log("*received whack message")); whack_handle(ctl_fd); passert(GLOBALS_ARE_RESET()); ndes } #ifdef IPSECPOLICY if (FD_ISSET(info_fd, &readfds)) { passert(ndes > 0); DBG(DBG_CONTROL, DBG_log("*received info message")); info_handle(info_fd); passert(GLOBALS_ARE_RESET()); ndes } #endif /* note we process helper things last on purpose */ { int helpers = <API key>(&readfds); DBG(DBG_CONTROL, DBG_log("* processed %d messages from cryptographic helpers\n", helpers)); ndes -= helpers; } passert(ndes == 0); } } } /* Process any message on the MSG_ERRQUEUE * * This information is generated because of the IP_RECVERR socket option. * The API is sparsely documented, and may be LINUX-only, and only on * fairly recent versions at that (hence the conditional compilation). * * - ip(7) describes IP_RECVERR * - recvmsg(2) describes MSG_ERRQUEUE * - readv(2) describes iovec * - cmsg(3) describes how to process auxilliary messages * * ??? we should link this message with one we've sent * so that the diagnostic can refer to that negotiation. * * ??? how long can the messge be? * * ??? poll(2) has a very incomplete description of the POLL* events. * We assume that POLLIN, POLLOUT, and POLLERR are all we need to deal with * and that POLLERR will be on iff there is a MSG_ERRQUEUE message. * * We have to code around a couple of surprises: * * - Select can say that a socket is ready to read from, and * yet a read will hang. It turns out that a message available on the * MSG_ERRQUEUE will cause select to say something is pending, but * a normal read will hang. poll(2) can tell when a MSG_ERRQUEUE * message is pending. * * This is dealt with by calling check_msg_errqueue after select * has indicated that there is something to read, but before the * read is performed. check_msg_errqueue will return TRUE if there * is something left to read. * * - A write to a socket may fail because there is a pending MSG_ERRQUEUE * message, without there being anything wrong with the write. This * makes for confusing diagnostics. * * To avoid this, we call check_msg_errqueue before a write. True, * there is a race condition (a MSG_ERRQUEUE message might arrive * between the check and the write), but we should eliminate many * of the problematic events. To narrow the window, the poll(2) * will await until an event happens (in the case or a write, * POLLOUT; this should be benign for POLLIN). */ #if defined(IP_RECVERR) && defined(MSG_ERRQUEUE) bool check_msg_errqueue(const struct iface_port *ifp, short interest) { struct pollfd pfd; pfd.fd = ifp->fd; pfd.events = interest | POLLPRI | POLLOUT; while (pfd.revents = 0 , poll(&pfd, 1, -1) > 0 && (pfd.revents & POLLERR)) { u_int8_t buffer[3000]; /* hope that this is big enough */ union { struct sockaddr sa; struct sockaddr_in sa_in4; struct sockaddr_in6 sa_in6; } from; int from_len = sizeof(from); int packet_len; struct msghdr emh; struct iovec eiov; union { /* force alignment (not documented as necessary) */ struct cmsghdr ecms; /* how much space is enough? */ unsigned char space[256]; } ecms_buf; struct cmsghdr *cm; char fromstr[sizeof(" for message to port 65536") + INET6_ADDRSTRLEN]; struct state *sender = NULL; zero(&from.sa); from_len = sizeof(from); emh.msg_name = &from.sa; /* ??? filled in? */ emh.msg_namelen = sizeof(from); emh.msg_iov = &eiov; emh.msg_iovlen = 1; emh.msg_control = &ecms_buf; emh.msg_controllen = sizeof(ecms_buf); emh.msg_flags = 0; eiov.iov_base = buffer; /* see readv(2) */ eiov.iov_len = sizeof(buffer); packet_len = recvmsg(ifp->fd, &emh, MSG_ERRQUEUE); if (packet_len == -1) { log_errno((e, "recvmsg(,, MSG_ERRQUEUE) on %s failed in comm_handle" , ifp->ip_dev->id_rname)); break; } else if (packet_len == sizeof(buffer)) { openswan_log("MSG_ERRQUEUE message longer than %lu bytes; truncated" , (unsigned long) sizeof(buffer)); } else { sender = find_sender((size_t) packet_len, buffer); } DBG_cond_dump(DBG_ALL, "rejected packet:\n", buffer, packet_len); DBG_cond_dump(DBG_ALL, "control:\n", emh.msg_control, emh.msg_controllen); /* ??? Andi Kleen <ak@suse.de> and misc documentation * suggests that name will have the original destination * of the packet. We seem to see msg_namelen == 0. * Andi says that this is a kernel bug and has fixed it. * Perhaps in 2.2.18/2.4.0. */ passert(emh.msg_name == &from.sa); DBG_cond_dump(DBG_ALL, "name:\n", emh.msg_name , emh.msg_namelen); fromstr[0] = '\0'; /* usual case :-( */ switch (from.sa.sa_family) { char as[INET6_ADDRSTRLEN]; case AF_INET: if (emh.msg_namelen == sizeof(struct sockaddr_in)) snprintf(fromstr, sizeof(fromstr) , " for message to %s port %u" , inet_ntop(from.sa.sa_family , &from.sa_in4.sin_addr, as, sizeof(as)) , ntohs(from.sa_in4.sin_port)); break; case AF_INET6: if (emh.msg_namelen == sizeof(struct sockaddr_in6)) snprintf(fromstr, sizeof(fromstr) , " for message to %s port %u" , inet_ntop(from.sa.sa_family , &from.sa_in6.sin6_addr, as, sizeof(as)) , ntohs(from.sa_in6.sin6_port)); break; } for (cm = CMSG_FIRSTHDR(&emh) ; cm != NULL ; cm = CMSG_NXTHDR(&emh,cm)) { if (cm->cmsg_level == SOL_IP && cm->cmsg_type == IP_RECVERR) { /* ip(7) and recvmsg(2) specify: * ee_origin is SO_EE_ORIGIN_ICMP for ICMP * or SO_EE_ORIGIN_LOCAL for locally generated errors. * ee_type and ee_code are from the ICMP header. * ee_info is the discovered MTU for EMSGSIZE errors * ee_data is not used. * * ??? recvmsg(2) says "SOCK_EE_OFFENDER" but * means "SO_EE_OFFENDER". The OFFENDER is really * the router that complained. As such, the port * is meaningless. */ /* ??? cmsg(3) claims that CMSG_DATA returns * void *, but RFC 2292 and /usr/include/bits/socket.h * say unsigned char *. The manual is being fixed. */ struct sock_extended_err *ee = (void *)CMSG_DATA(cm); const char *offstr = "unspecified"; char offstrspace[INET6_ADDRSTRLEN]; char orname[50]; if (cm->cmsg_len > CMSG_LEN(sizeof(struct sock_extended_err))) { const struct sockaddr *offender = SO_EE_OFFENDER(ee); switch (offender->sa_family) { case AF_INET: offstr = inet_ntop(offender->sa_family , &((const struct sockaddr_in *)offender)->sin_addr , offstrspace, sizeof(offstrspace)); break; case AF_INET6: offstr = inet_ntop(offender->sa_family , &((const struct sockaddr_in6 *)offender)->sin6_addr , offstrspace, sizeof(offstrspace)); break; default: offstr = "unknown"; break; } } switch (ee->ee_origin) { case SO_EE_ORIGIN_NONE: snprintf(orname, sizeof(orname), "none"); break; case SO_EE_ORIGIN_LOCAL: snprintf(orname, sizeof(orname), "local"); break; case SO_EE_ORIGIN_ICMP: snprintf(orname, sizeof(orname) , "ICMP type %d code %d (not authenticated)" , ee->ee_type, ee->ee_code ); break; case SO_EE_ORIGIN_ICMP6: snprintf(orname, sizeof(orname) , "ICMP6 type %d code %d (not authenticated)" , ee->ee_type, ee->ee_code ); break; default: snprintf(orname, sizeof(orname), "invalid origin %lu" , (unsigned long) ee->ee_origin); break; } { struct state *old_state = cur_state; cur_state = sender; /* note dirty trick to suppress ~ at start of format * if we know what state to blame. */ #ifdef NAT_TRAVERSAL if ((packet_len == 1) && (buffer[0] = 0xff) #ifdef DEBUG && ((cur_debugging & DBG_NATT) == 0) #endif ) { /* don't log NAT-T keepalive related errors unless NATT debug is * enabled */ } else #endif openswan_log((sender != NULL) + "~" "ERROR: asynchronous network error report on %s (sport=%d)" "%s" ", complainant %s" ": %s" " [errno %lu, origin %s" /* ", pad %d, info %ld" */ /* ", data %ld" */ "]" , ifp->ip_dev->id_rname , ifp->port , fromstr , offstr , strerror(ee->ee_errno) , (unsigned long) ee->ee_errno , orname /* , ee->ee_pad, (unsigned long)ee->ee_info */ /* , (unsigned long)ee->ee_data */ ); cur_state = old_state; } } else if (cm->cmsg_level == SOL_IP && cm->cmsg_type == IP_PKTINFO) { } else { /* .cmsg_len is a kernel_size_t(!), but the value * certainly ought to fit in an unsigned long. */ openswan_log("unknown cmsg: level %d, type %d, len %lu" , cm->cmsg_level, cm->cmsg_type , (unsigned long) cm->cmsg_len); } } } return (pfd.revents & interest) != 0; } #endif /* defined(IP_RECVERR) && defined(MSG_ERRQUEUE) */ bool send_packet(struct state *st, const char *where, bool verbose) { bool err; u_int8_t ike_pkt[MAX_OUTPUT_UDP_SIZE]; u_int8_t *ptr; unsigned long len; ssize_t wlen; if ((st->st_interface->ike_float == TRUE) && (st->st_tpacket.len != 1)) { if ((unsigned long) st->st_tpacket.len > (<API key>(u_int32_t))) { DBG_log("send_packet(): really too big"); return FALSE; } ptr = ike_pkt; /** Add Non-ESP marker **/ memset(ike_pkt, 0, sizeof(u_int32_t)); memcpy(ike_pkt + sizeof(u_int32_t), st->st_tpacket.ptr, (unsigned long)st->st_tpacket.len); len = (unsigned long) st->st_tpacket.len + sizeof(u_int32_t); } else { ptr = st->st_tpacket.ptr; len = (unsigned long) st->st_tpacket.len; } DBG(DBG_CONTROL|DBG_RAW , DBG_log("sending %lu bytes for %s through %s:%d to %s:%u (using , (unsigned long) st->st_tpacket.len , where , st->st_interface->ip_dev->id_rname , st->st_interface->port , ip_str(&st->st_remoteaddr) , st->st_remoteport , st->st_serialno)); DBG(DBG_RAW , DBG_dump(NULL, ptr, len)); setportof(htons(st->st_remoteport), &st->st_remoteaddr); #if defined(IP_RECVERR) && defined(MSG_ERRQUEUE) (void) check_msg_errqueue(st->st_interface, POLLOUT); #endif /* defined(IP_RECVERR) && defined(MSG_ERRQUEUE) */ #if 0 wlen = sendfromto(st->st_interface->fd , ptr , len, 0 , sockaddrof(&st->st_remoteaddr) , sockaddrlenof(&st->st_remoteaddr) , sockaddrof(&st->st_localaddr) , sockaddrlenof(&st->st_localaddr)); #else wlen = sendto(st->st_interface->fd , ptr , len, 0 , sockaddrof(&st->st_remoteaddr) , sockaddrlenof(&st->st_remoteaddr)); #ifdef DEBUG if(DBGP(<API key>)) { /* sleep for half a second, and second another packet */ usleep(500000); DBG_log("JACOB 2-2: resending %lu bytes for %s through %s:%d to %s:%u:" , (unsigned long) st->st_tpacket.len , where , st->st_interface->ip_dev->id_rname , st->st_interface->port , ip_str(&st->st_remoteaddr) , st->st_remoteport); #endif wlen = sendto(st->st_interface->fd , ptr , len, 0 , sockaddrof(&st->st_remoteaddr) , sockaddrlenof(&st->st_remoteaddr)); } #endif err = (wlen != (ssize_t)len); if (err) { /* do not log NAT-T Keep Alive packets */ if (!verbose) return FALSE; log_errno((e, "sendto on %s to %s:%u failed in %s" , st->st_interface->ip_dev->id_rname , ip_str(&st->st_remoteaddr) , st->st_remoteport , where)); return FALSE; } else { return TRUE; } } /* * Local Variables: * c-basic-offset: 4 * End Variables: */
#include <stdio.h> #include <errno.h> #include <stdint.h> #include <stdlib.h> #include <unistd.h> #include <stdarg.h> #include <inttypes.h> #include <rte_interrupts.h> #include <rte_log.h> #include <rte_debug.h> #include <rte_eal.h> #include <rte_ether.h> #include <rte_ethdev_driver.h> #include <rte_memcpy.h> #include <rte_malloc.h> #include <rte_random.h> #include "base/ixgbe_common.h" #include "ixgbe_ethdev.h" #include "rte_pmd_ixgbe.h" #define IXGBE_MAX_VFTA (128) #define <API key> 1 #define <API key> 5 #define <API key> 0x8808 static inline uint16_t dev_num_vf(struct rte_eth_dev *eth_dev) { struct rte_pci_device *pci_dev = RTE_ETH_DEV_TO_PCI(eth_dev); return pci_dev->max_vfs; } static inline int <API key>(struct rte_eth_dev *dev, uint16_t vf_num) { unsigned char vf_mac_addr[ETHER_ADDR_LEN]; struct ixgbe_vf_info *vfinfo = *<API key>(dev->data->dev_private); uint16_t vfn; for (vfn = 0; vfn < vf_num; vfn++) { eth_random_addr(vf_mac_addr); /* keep the random address as default */ memcpy(vfinfo[vfn].vf_mac_addresses, vf_mac_addr, ETHER_ADDR_LEN); } return 0; } static inline int ixgbe_mb_intr_setup(struct rte_eth_dev *dev) { struct ixgbe_interrupt *intr = <API key>(dev->data->dev_private); intr->mask |= IXGBE_EICR_MAILBOX; return 0; } void ixgbe_pf_host_init(struct rte_eth_dev *eth_dev) { struct ixgbe_vf_info **vfinfo = <API key>(eth_dev->data->dev_private); struct ixgbe_mirror_info *mirror_info = <API key>(eth_dev->data->dev_private); struct ixgbe_uta_info *uta_info = <API key>(eth_dev->data->dev_private); struct ixgbe_hw *hw = <API key>(eth_dev->data->dev_private); uint16_t vf_num; uint8_t nb_queue; PMD_INIT_FUNC_TRACE(); RTE_ETH_DEV_SRIOV(eth_dev).active = 0; vf_num = dev_num_vf(eth_dev); if (vf_num == 0) return; *vfinfo = rte_zmalloc("vf_info", sizeof(struct ixgbe_vf_info) * vf_num, 0); if (*vfinfo == NULL) rte_panic("Cannot allocate memory for private VF data\n"); memset(mirror_info, 0, sizeof(struct ixgbe_mirror_info)); memset(uta_info, 0, sizeof(struct ixgbe_uta_info)); hw->mac.mc_filter_type = 0; if (vf_num >= ETH_32_POOLS) { nb_queue = 2; RTE_ETH_DEV_SRIOV(eth_dev).active = ETH_64_POOLS; } else if (vf_num >= ETH_16_POOLS) { nb_queue = 4; RTE_ETH_DEV_SRIOV(eth_dev).active = ETH_32_POOLS; } else { nb_queue = 8; RTE_ETH_DEV_SRIOV(eth_dev).active = ETH_16_POOLS; } RTE_ETH_DEV_SRIOV(eth_dev).nb_q_per_pool = nb_queue; RTE_ETH_DEV_SRIOV(eth_dev).def_vmdq_idx = vf_num; RTE_ETH_DEV_SRIOV(eth_dev).def_pool_q_idx = (uint16_t)(vf_num * nb_queue); <API key>(eth_dev, vf_num); /* init_mailbox_params */ hw->mbx.ops.init_params(hw); /* set mb interrupt mask */ ixgbe_mb_intr_setup(eth_dev); } void <API key>(struct rte_eth_dev *eth_dev) { struct ixgbe_vf_info **vfinfo; uint16_t vf_num; PMD_INIT_FUNC_TRACE(); vfinfo = <API key>(eth_dev->data->dev_private); RTE_ETH_DEV_SRIOV(eth_dev).active = 0; RTE_ETH_DEV_SRIOV(eth_dev).nb_q_per_pool = 0; RTE_ETH_DEV_SRIOV(eth_dev).def_vmdq_idx = 0; RTE_ETH_DEV_SRIOV(eth_dev).def_pool_q_idx = 0; vf_num = dev_num_vf(eth_dev); if (vf_num == 0) return; rte_free(*vfinfo); *vfinfo = NULL; } static void <API key>(struct rte_eth_dev *eth_dev) { struct ixgbe_hw *hw = <API key>(eth_dev->data->dev_private); struct ixgbe_filter_info *filter_info = <API key>(eth_dev->data->dev_private); uint16_t vf_num; int i; struct <API key> ethertype_filter; if (!hw->mac.ops.<API key>) { RTE_LOG(INFO, PMD, "ether type anti-spoofing is not" " supported.\n"); return; } i = <API key>(filter_info, <API key>); if (i >= 0) { RTE_LOG(ERR, PMD, "A ether type filter" " entity for flow control already exists!\n"); return; } ethertype_filter.ethertype = <API key>; ethertype_filter.etqf = <API key> | <API key> | <API key>; ethertype_filter.etqs = 0; ethertype_filter.conf = TRUE; i = <API key>(filter_info, &ethertype_filter); if (i < 0) { RTE_LOG(ERR, PMD, "Cannot find an unused ether type filter" " entity for flow control.\n"); return; } IXGBE_WRITE_REG(hw, IXGBE_ETQF(i), (<API key> | <API key> | <API key>)); vf_num = dev_num_vf(eth_dev); for (i = 0; i < vf_num; i++) hw->mac.ops.<API key>(hw, true, i); } int <API key>(struct rte_eth_dev *eth_dev) { uint32_t vtctl, fcrth; uint32_t vfre_slot, vfre_offset; uint16_t vf_num; const uint8_t VFRE_SHIFT = 5; /* VFRE 32 bits per slot */ const uint8_t VFRE_MASK = (uint8_t)((1U << VFRE_SHIFT) - 1); struct ixgbe_hw *hw = <API key>(eth_dev->data->dev_private); uint32_t gpie, gcr_ext; uint32_t vlanctrl; int i; vf_num = dev_num_vf(eth_dev); if (vf_num == 0) return -1; /* enable VMDq and set the default pool for PF */ vtctl = IXGBE_READ_REG(hw, IXGBE_VT_CTL); vtctl |= <API key>; vtctl &= ~<API key>; vtctl |= RTE_ETH_DEV_SRIOV(eth_dev).def_vmdq_idx << <API key>; vtctl |= IXGBE_VT_CTL_REPLEN; IXGBE_WRITE_REG(hw, IXGBE_VT_CTL, vtctl); vfre_offset = vf_num & VFRE_MASK; vfre_slot = (vf_num >> VFRE_SHIFT) > 0 ? 1 : 0; /* Enable pools reserved to PF only */ IXGBE_WRITE_REG(hw, IXGBE_VFRE(vfre_slot), (~0U) << vfre_offset); IXGBE_WRITE_REG(hw, IXGBE_VFRE(vfre_slot ^ 1), vfre_slot - 1); IXGBE_WRITE_REG(hw, IXGBE_VFTE(vfre_slot), (~0U) << vfre_offset); IXGBE_WRITE_REG(hw, IXGBE_VFTE(vfre_slot ^ 1), vfre_slot - 1); /* PFDMA Tx General Switch Control Enables VMDQ loopback */ IXGBE_WRITE_REG(hw, IXGBE_PFDTXGSWC, <API key>); /* clear VMDq map to perment rar 0 */ hw->mac.ops.clear_vmdq(hw, 0, <API key>); /* clear VMDq map to scan rar 127 */ IXGBE_WRITE_REG(hw, IXGBE_MPSAR_LO(hw->mac.num_rar_entries), 0); IXGBE_WRITE_REG(hw, IXGBE_MPSAR_HI(hw->mac.num_rar_entries), 0); /* set VMDq map to default PF pool */ hw->mac.ops.set_vmdq(hw, 0, RTE_ETH_DEV_SRIOV(eth_dev).def_vmdq_idx); /* * SW msut set GCR_EXT.VT_Mode the same as GPIE.VT_Mode */ gcr_ext = IXGBE_READ_REG(hw, IXGBE_GCR_EXT); gcr_ext &= ~<API key>; gpie = IXGBE_READ_REG(hw, IXGBE_GPIE); gpie &= ~<API key>; gpie |= <API key> | <API key>; switch (RTE_ETH_DEV_SRIOV(eth_dev).active) { case ETH_64_POOLS: gcr_ext |= <API key>; gpie |= <API key>; break; case ETH_32_POOLS: gcr_ext |= <API key>; gpie |= <API key>; break; case ETH_16_POOLS: gcr_ext |= <API key>; gpie |= <API key>; break; } IXGBE_WRITE_REG(hw, IXGBE_GCR_EXT, gcr_ext); IXGBE_WRITE_REG(hw, IXGBE_GPIE, gpie); /* * enable vlan filtering and allow all vlan tags through */ vlanctrl = IXGBE_READ_REG(hw, IXGBE_VLNCTRL); vlanctrl |= IXGBE_VLNCTRL_VFE; /* enable vlan filters */ IXGBE_WRITE_REG(hw, IXGBE_VLNCTRL, vlanctrl); /* VFTA - enable all vlan filters */ for (i = 0; i < IXGBE_MAX_VFTA; i++) IXGBE_WRITE_REG(hw, IXGBE_VFTA(i), 0xFFFFFFFF); /* Enable MAC Anti-Spoofing */ hw->mac.ops.<API key>(hw, FALSE, vf_num); /* set flow control threshold to max to avoid tx switch hang */ for (i = 0; i < <API key>; i++) { IXGBE_WRITE_REG(hw, IXGBE_FCRTL_82599(i), 0); fcrth = IXGBE_READ_REG(hw, IXGBE_RXPBSIZE(i)) - 32; IXGBE_WRITE_REG(hw, IXGBE_FCRTH_82599(i), fcrth); } <API key>(eth_dev); return 0; } static void set_rx_mode(struct rte_eth_dev *dev) { struct rte_eth_dev_data *dev_data = dev->data; struct ixgbe_hw *hw = <API key>(dev->data->dev_private); u32 fctrl, vmolr = IXGBE_VMOLR_BAM | IXGBE_VMOLR_AUPE; uint16_t vfn = dev_num_vf(dev); /* Check for Promiscuous and All Multicast modes */ fctrl = IXGBE_READ_REG(hw, IXGBE_FCTRL); /* set all bits that we expect to always be set */ fctrl &= ~IXGBE_FCTRL_SBP; /* disable store-bad-packets */ fctrl |= IXGBE_FCTRL_BAM; /* clear the bits we are changing the status of */ fctrl &= ~(IXGBE_FCTRL_UPE | IXGBE_FCTRL_MPE); if (dev_data->promiscuous) { fctrl |= (IXGBE_FCTRL_UPE | IXGBE_FCTRL_MPE); vmolr |= (IXGBE_VMOLR_ROPE | IXGBE_VMOLR_MPE); } else { if (dev_data->all_multicast) { fctrl |= IXGBE_FCTRL_MPE; vmolr |= IXGBE_VMOLR_MPE; } else { vmolr |= IXGBE_VMOLR_ROMPE; } } if (hw->mac.type != ixgbe_mac_82598EB) { vmolr |= IXGBE_READ_REG(hw, IXGBE_VMOLR(vfn)) & ~(IXGBE_VMOLR_MPE | IXGBE_VMOLR_ROMPE | IXGBE_VMOLR_ROPE); IXGBE_WRITE_REG(hw, IXGBE_VMOLR(vfn), vmolr); } IXGBE_WRITE_REG(hw, IXGBE_FCTRL, fctrl); if (dev->data->dev_conf.rxmode.hw_vlan_strip) <API key>(dev); else <API key>(dev); } static inline void <API key>(struct rte_eth_dev *dev, uint16_t vf) { struct ixgbe_hw *hw = <API key>(dev->data->dev_private); struct ixgbe_vf_info *vfinfo = *(<API key>(dev->data->dev_private)); int rar_entry = hw->mac.num_rar_entries - (vf + 1); uint32_t vmolr = IXGBE_READ_REG(hw, IXGBE_VMOLR(vf)); vmolr |= (IXGBE_VMOLR_ROPE | IXGBE_VMOLR_ROMPE | IXGBE_VMOLR_BAM | IXGBE_VMOLR_AUPE); IXGBE_WRITE_REG(hw, IXGBE_VMOLR(vf), vmolr); IXGBE_WRITE_REG(hw, IXGBE_VMVIR(vf), 0); /* reset multicast table array for vf */ vfinfo[vf].num_vf_mc_hashes = 0; /* reset rx mode */ set_rx_mode(dev); hw->mac.ops.clear_rar(hw, rar_entry); } static inline void ixgbe_vf_reset_msg(struct rte_eth_dev *dev, uint16_t vf) { struct ixgbe_hw *hw = <API key>(dev->data->dev_private); uint32_t reg; uint32_t reg_offset, vf_shift; const uint8_t VFRE_SHIFT = 5; /* VFRE 32 bits per slot */ const uint8_t VFRE_MASK = (uint8_t)((1U << VFRE_SHIFT) - 1); uint8_t nb_q_per_pool; int i; vf_shift = vf & VFRE_MASK; reg_offset = (vf >> VFRE_SHIFT) > 0 ? 1 : 0; /* enable transmit for vf */ reg = IXGBE_READ_REG(hw, IXGBE_VFTE(reg_offset)); reg |= (reg | (1 << vf_shift)); IXGBE_WRITE_REG(hw, IXGBE_VFTE(reg_offset), reg); /* enable all queue drop for IOV */ nb_q_per_pool = RTE_ETH_DEV_SRIOV(dev).nb_q_per_pool; for (i = vf * nb_q_per_pool; i < (vf + 1) * nb_q_per_pool; i++) { IXGBE_WRITE_FLUSH(hw); reg = IXGBE_QDE_ENABLE | IXGBE_QDE_WRITE; reg |= i << IXGBE_QDE_IDX_SHIFT; IXGBE_WRITE_REG(hw, IXGBE_QDE, reg); } /* enable receive for vf */ reg = IXGBE_READ_REG(hw, IXGBE_VFRE(reg_offset)); reg |= (reg | (1 << vf_shift)); IXGBE_WRITE_REG(hw, IXGBE_VFRE(reg_offset), reg); /* Enable counting of spoofed packets in the SSVPC register */ reg = IXGBE_READ_REG(hw, IXGBE_VMECM(reg_offset)); reg |= (1 << vf_shift); IXGBE_WRITE_REG(hw, IXGBE_VMECM(reg_offset), reg); <API key>(dev, vf); } static int <API key>(struct rte_eth_dev *dev, uint32_t vf) { struct ixgbe_hw *hw = <API key>(dev->data->dev_private); uint32_t vmolr; vmolr = IXGBE_READ_REG(hw, IXGBE_VMOLR(vf)); RTE_LOG(INFO, PMD, "VF %u: enabling multicast promiscuous\n", vf); vmolr |= IXGBE_VMOLR_MPE; IXGBE_WRITE_REG(hw, IXGBE_VMOLR(vf), vmolr); return 0; } static int <API key>(struct rte_eth_dev *dev, uint32_t vf) { struct ixgbe_hw *hw = <API key>(dev->data->dev_private); uint32_t vmolr; vmolr = IXGBE_READ_REG(hw, IXGBE_VMOLR(vf)); RTE_LOG(INFO, PMD, "VF %u: disabling multicast promiscuous\n", vf); vmolr &= ~IXGBE_VMOLR_MPE; IXGBE_WRITE_REG(hw, IXGBE_VMOLR(vf), vmolr); return 0; } static int ixgbe_vf_reset(struct rte_eth_dev *dev, uint16_t vf, uint32_t *msgbuf) { struct ixgbe_hw *hw = <API key>(dev->data->dev_private); struct ixgbe_vf_info *vfinfo = *(<API key>(dev->data->dev_private)); unsigned char *vf_mac = vfinfo[vf].vf_mac_addresses; int rar_entry = hw->mac.num_rar_entries - (vf + 1); uint8_t *new_mac = (uint8_t *)(&msgbuf[1]); ixgbe_vf_reset_msg(dev, vf); hw->mac.ops.set_rar(hw, rar_entry, vf_mac, vf, IXGBE_RAH_AV); /* Disable multicast promiscuous at reset */ <API key>(dev, vf); /* reply to reset with ack and vf mac address */ msgbuf[0] = IXGBE_VF_RESET | <API key>; rte_memcpy(new_mac, vf_mac, ETHER_ADDR_LEN); /* * Piggyback the multicast filter type so VF can compute the * correct vectors */ msgbuf[3] = hw->mac.mc_filter_type; ixgbe_write_mbx(hw, msgbuf, <API key>, vf); return 0; } static int <API key>(struct rte_eth_dev *dev, uint32_t vf, uint32_t *msgbuf) { struct ixgbe_hw *hw = <API key>(dev->data->dev_private); struct ixgbe_vf_info *vfinfo = *(<API key>(dev->data->dev_private)); int rar_entry = hw->mac.num_rar_entries - (vf + 1); uint8_t *new_mac = (uint8_t *)(&msgbuf[1]); if (<API key>((struct ether_addr *)new_mac)) { rte_memcpy(vfinfo[vf].vf_mac_addresses, new_mac, 6); return hw->mac.ops.set_rar(hw, rar_entry, new_mac, vf, IXGBE_RAH_AV); } return -1; } static int <API key>(struct rte_eth_dev *dev, uint32_t vf, uint32_t *msgbuf) { struct ixgbe_hw *hw = <API key>(dev->data->dev_private); struct ixgbe_vf_info *vfinfo = *(<API key>(dev->data->dev_private)); int nb_entries = (msgbuf[0] & <API key>) >> <API key>; uint16_t *hash_list = (uint16_t *)&msgbuf[1]; uint32_t mta_idx; uint32_t mta_shift; const uint32_t <API key> = 0x7F; const uint32_t IXGBE_MTA_BIT_SHIFT = 5; const uint32_t IXGBE_MTA_BIT_MASK = (0x1 << IXGBE_MTA_BIT_SHIFT) - 1; uint32_t reg_val; int i; /* Disable multicast promiscuous first */ <API key>(dev, vf); /* only so many hash values supported */ nb_entries = RTE_MIN(nb_entries, <API key>); /* store the mc entries */ vfinfo->num_vf_mc_hashes = (uint16_t)nb_entries; for (i = 0; i < nb_entries; i++) { vfinfo->vf_mc_hashes[i] = hash_list[i]; } for (i = 0; i < vfinfo->num_vf_mc_hashes; i++) { mta_idx = (vfinfo->vf_mc_hashes[i] >> IXGBE_MTA_BIT_SHIFT) & <API key>; mta_shift = vfinfo->vf_mc_hashes[i] & IXGBE_MTA_BIT_MASK; reg_val = IXGBE_READ_REG(hw, IXGBE_MTA(mta_idx)); reg_val |= (1 << mta_shift); IXGBE_WRITE_REG(hw, IXGBE_MTA(mta_idx), reg_val); } return 0; } static int ixgbe_vf_set_vlan(struct rte_eth_dev *dev, uint32_t vf, uint32_t *msgbuf) { int add, vid; struct ixgbe_hw *hw = <API key>(dev->data->dev_private); struct ixgbe_vf_info *vfinfo = *(<API key>(dev->data->dev_private)); add = (msgbuf[0] & <API key>) >> <API key>; vid = (msgbuf[1] & <API key>); if (add) vfinfo[vf].vlan_count++; else if (vfinfo[vf].vlan_count) vfinfo[vf].vlan_count return hw->mac.ops.set_vfta(hw, vid, vf, (bool)add, false); } static int ixgbe_set_vf_lpe(struct rte_eth_dev *dev, __rte_unused uint32_t vf, uint32_t *msgbuf) { struct ixgbe_hw *hw = <API key>(dev->data->dev_private); uint32_t new_mtu = msgbuf[1]; uint32_t max_frs; int max_frame = new_mtu + ETHER_HDR_LEN + ETHER_CRC_LEN; /* X540 and X550 support jumbo frames in IOV mode */ if (hw->mac.type != ixgbe_mac_X540 && hw->mac.type != ixgbe_mac_X550 && hw->mac.type != ixgbe_mac_X550EM_x && hw->mac.type != ixgbe_mac_X550EM_a) return -1; if ((max_frame < ETHER_MIN_LEN) || (max_frame > <API key>)) return -1; max_frs = (IXGBE_READ_REG(hw, IXGBE_MAXFRS) & <API key>) >> <API key>; if (max_frs < new_mtu) { max_frs = new_mtu << <API key>; IXGBE_WRITE_REG(hw, IXGBE_MAXFRS, max_frs); } return 0; } static int <API key>(struct rte_eth_dev *dev, uint32_t vf, uint32_t *msgbuf) { uint32_t api_version = msgbuf[1]; struct ixgbe_vf_info *vfinfo = *<API key>(dev->data->dev_private); switch (api_version) { case ixgbe_mbox_api_10: case ixgbe_mbox_api_11: case ixgbe_mbox_api_12: vfinfo[vf].api_version = (uint8_t)api_version; return 0; default: break; } RTE_LOG(ERR, PMD, "Negotiate invalid api version %u from VF %d\n", api_version, vf); return -1; } static int ixgbe_get_vf_queues(struct rte_eth_dev *dev, uint32_t vf, uint32_t *msgbuf) { struct ixgbe_vf_info *vfinfo = *<API key>(dev->data->dev_private); uint32_t default_q = vf * RTE_ETH_DEV_SRIOV(dev).nb_q_per_pool; struct rte_eth_conf *eth_conf; struct <API key> *vmdq_dcb_tx_conf; u8 num_tcs; struct ixgbe_hw *hw; u32 vmvir; #define <API key> 0xC0000000 #define <API key> 0x00000FFF #define <API key> 0x0000E000 #define VLAN_PRIO_SHIFT 13 u32 vlana; u32 vid; u32 user_priority; /* Verify if the PF supports the mbox APIs version or not */ switch (vfinfo[vf].api_version) { case ixgbe_mbox_api_20: case ixgbe_mbox_api_11: case ixgbe_mbox_api_12: break; default: return -1; } /* Notify VF of Rx and Tx queue number */ msgbuf[IXGBE_VF_RX_QUEUES] = RTE_ETH_DEV_SRIOV(dev).nb_q_per_pool; msgbuf[IXGBE_VF_TX_QUEUES] = RTE_ETH_DEV_SRIOV(dev).nb_q_per_pool; /* Notify VF of default queue */ msgbuf[IXGBE_VF_DEF_QUEUE] = default_q; /* Notify VF of number of DCB traffic classes */ eth_conf = &dev->data->dev_conf; switch (eth_conf->txmode.mq_mode) { case ETH_MQ_TX_NONE: case ETH_MQ_TX_DCB: RTE_LOG(ERR, PMD, "PF must work with virtualization for VF %u" ", but its tx mode = %d\n", vf, eth_conf->txmode.mq_mode); return -1; case ETH_MQ_TX_VMDQ_DCB: vmdq_dcb_tx_conf = &eth_conf->tx_adv_conf.vmdq_dcb_tx_conf; switch (vmdq_dcb_tx_conf->nb_queue_pools) { case ETH_16_POOLS: num_tcs = ETH_8_TCS; break; case ETH_32_POOLS: num_tcs = ETH_4_TCS; break; default: return -1; } break; /* ETH_MQ_TX_VMDQ_ONLY, DCB not enabled */ case ETH_MQ_TX_VMDQ_ONLY: hw = <API key>(dev->data->dev_private); vmvir = IXGBE_READ_REG(hw, IXGBE_VMVIR(vf)); vlana = vmvir & <API key>; vid = vmvir & <API key>; user_priority = (vmvir & <API key>) >> VLAN_PRIO_SHIFT; if ((vlana == <API key>) && ((vid != 0) || (user_priority != 0))) num_tcs = 1; else num_tcs = 0; break; default: RTE_LOG(ERR, PMD, "PF work with invalid mode = %d\n", eth_conf->txmode.mq_mode); return -1; } msgbuf[IXGBE_VF_TRANS_VLAN] = num_tcs; return 0; } static int <API key>(struct rte_eth_dev *dev, uint32_t vf, uint32_t *msgbuf) { struct ixgbe_vf_info *vfinfo = *(<API key>(dev->data->dev_private)); bool enable = !!msgbuf[1]; /* msgbuf contains the flag to enable */ switch (vfinfo[vf].api_version) { case ixgbe_mbox_api_12: break; default: return -1; } if (enable) return <API key>(dev, vf); else return <API key>(dev, vf); } static int <API key>(struct rte_eth_dev *dev, uint16_t vf) { uint16_t mbx_size = <API key>; uint16_t msg_size = <API key>; uint32_t msgbuf[<API key>]; int32_t retval; struct ixgbe_hw *hw = <API key>(dev->data->dev_private); struct ixgbe_vf_info *vfinfo = *<API key>(dev->data->dev_private); struct <API key> ret_param; retval = ixgbe_read_mbx(hw, msgbuf, mbx_size, vf); if (retval) { PMD_DRV_LOG(ERR, "Error mbx recv msg from VF %d", vf); return retval; } /* do nothing with the message already been processed */ if (msgbuf[0] & (<API key> | <API key>)) return retval; /* flush the ack before we write any messages back */ IXGBE_WRITE_FLUSH(hw); /** * initialise structure to send to user application * will return response from user in retval field */ ret_param.retval = <API key>; ret_param.vfid = vf; ret_param.msg_type = msgbuf[0] & 0xFFFF; ret_param.msg = (void *)msgbuf; /* perform VF reset */ if (msgbuf[0] == IXGBE_VF_RESET) { int ret = ixgbe_vf_reset(dev, vf, msgbuf); vfinfo[vf].clear_to_send = true; /* notify application about VF reset */ <API key>(dev, <API key>, &ret_param); return ret; } /** * ask user application if we allowed to perform those functions * if we get ret_param.retval == <API key> * then business as usual, * if 0, do nothing and send ACK to VF * if ret_param.retval > 1, do nothing and send NAK to VF */ <API key>(dev, <API key>, &ret_param); retval = ret_param.retval; /* check & process VF to PF mailbox message */ switch ((msgbuf[0] & 0xFFFF)) { case <API key>: if (retval == <API key>) retval = <API key>(dev, vf, msgbuf); break; case <API key>: if (retval == <API key>) retval = <API key>(dev, vf, msgbuf); break; case IXGBE_VF_SET_LPE: if (retval == <API key>) retval = ixgbe_set_vf_lpe(dev, vf, msgbuf); break; case IXGBE_VF_SET_VLAN: if (retval == <API key>) retval = ixgbe_vf_set_vlan(dev, vf, msgbuf); break; case <API key>: retval = <API key>(dev, vf, msgbuf); break; case IXGBE_VF_GET_QUEUES: retval = ixgbe_get_vf_queues(dev, vf, msgbuf); msg_size = <API key>; break; case <API key>: if (retval == <API key>) retval = <API key>(dev, vf, msgbuf); break; default: PMD_DRV_LOG(DEBUG, "Unhandled Msg %8.8x", (unsigned)msgbuf[0]); retval = IXGBE_ERR_MBX; break; } /* response the VF according to the message process result */ if (retval) msgbuf[0] |= <API key>; else msgbuf[0] |= <API key>; msgbuf[0] |= <API key>; ixgbe_write_mbx(hw, msgbuf, msg_size, vf); return retval; } static inline void <API key>(struct rte_eth_dev *dev, uint16_t vf) { uint32_t msg = <API key>; struct ixgbe_hw *hw = <API key>(dev->data->dev_private); struct ixgbe_vf_info *vfinfo = *<API key>(dev->data->dev_private); if (!vfinfo[vf].clear_to_send) ixgbe_write_mbx(hw, &msg, 1, vf); } void <API key>(struct rte_eth_dev *eth_dev) { uint16_t vf; struct ixgbe_hw *hw = <API key>(eth_dev->data->dev_private); for (vf = 0; vf < dev_num_vf(eth_dev); vf++) { /* check & process vf function level reset */ if (!ixgbe_check_for_rst(hw, vf)) <API key>(eth_dev, vf); /* check & process vf mailbox messages */ if (!ixgbe_check_for_msg(hw, vf)) <API key>(eth_dev, vf); /* check & process acks from vf */ if (!ixgbe_check_for_ack(hw, vf)) <API key>(eth_dev, vf); } }
#include <wlioctl.h> #include <typedefs.h> #include <linuxver.h> #include <osl.h> #include <bcmutils.h> #include <bcmendian.h> #include <proto/ethernet.h> #include <linux/if_arp.h> #include <asm/uaccess.h> #include <dngl_stats.h> #include <dhd.h> #include <dhdioctl.h> typedef void wlc_info_t; typedef void wl_info_t; typedef const struct si_pub si_t; #include <wlioctl.h> #include <proto/ethernet.h> #include <dngl_stats.h> #include <dhd.h> #define WL_ERROR(x) printf x #define WL_TRACE(x) #define WL_ASSOC(x) #define WL_INFORM(x) #define WL_WSEC(x) #define WL_SCAN(x) #ifdef PNO_SET_DEBUG #define WL_PNO(x) printf x #else #define WL_PNO(x) #endif #define JF2MS jiffies_to_msecs(jiffies) #ifdef COEX_DBG #define WL_TRACE_COEX(x) printf("TS:%lu ", JF2MS); \ printf x #else #define WL_TRACE_COEX(x) #endif #ifdef SCAN_DBG #define WL_TRACE_SCAN(x) printf("TS:%lu ", JF2MS); \ printf x #else #define WL_TRACE_SCAN(x) #endif #include <wl_iw.h> #define IW_WSEC_ENABLED(wsec) ((wsec) & (WEP_ENABLED | TKIP_ENABLED | AES_ENABLED)) #include <linux/rtnetlink.h> #define WL_IW_USE_ISCAN 1 #define <API key> 1 #ifdef OEM_CHROMIUMOS bool <API key> = TRUE; #endif #if (LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 25)) && 1 struct mutex g_wl_ss_scan_lock; #endif #if defined(SOFTAP) #define WL_SOFTAP(x) static struct net_device *priv_dev; extern bool ap_cfg_running; extern bool ap_fw_loaded; struct net_device *ap_net_dev = NULL; tsk_ctl_t ap_eth_ctl; static int <API key>(struct net_device *dev, struct ap_profile *ap); static int <API key>(struct net_device *dev, u8 *mac); #endif #define WL_IW_IOCTL_CALL(func_call) \ do { \ func_call; \ } while (0) #define <API key>(extra) \ if (!extra) { \ WL_ERROR(("%s: error : extra is null pointer\n", __FUNCTION__)); \ return -EINVAL; \ } static int g_onoff = G_WLAN_SET_ON; <API key> g_wl_iw_params; #if (LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 25)) && 1 static struct mutex wl_cache_lock; static struct mutex wl_softap_lock; #define DHD_OS_MUTEX_INIT(a) mutex_init(a) #define DHD_OS_MUTEX_LOCK(a) mutex_lock(a) #define DHD_OS_MUTEX_UNLOCK(a) mutex_unlock(a) #else #define DHD_OS_MUTEX_INIT(a) #define DHD_OS_MUTEX_LOCK(a) #define DHD_OS_MUTEX_UNLOCK(a) #endif #include <bcmsdbus.h> extern void <API key>(int onoff); extern uint dhd_dev_reset(struct net_device *dev, uint8 flag); extern int dhd_dev_init_ioctl(struct net_device *dev); uint wl_msg_level = WL_ERROR_VAL; #define MAX_WLIW_IOCTL_LEN 1024 #define htod32(i) i #define htod16(i) i #define dtoh32(i) i #define dtoh16(i) i #define htodchanspec(i) i #define dtohchanspec(i) i extern struct iw_statistics *<API key>(struct net_device *dev); extern int dhd_wait_pend8021x(struct net_device *dev); #if WIRELESS_EXT < 19 #define IW_IOCTL_IDX(cmd) ((cmd) - SIOCIWFIRST) #define IW_EVENT_IDX(cmd) ((cmd) - IWEVFIRST) #endif static void *g_scan = NULL; static volatile uint <API key>; static wlc_ssid_t g_specific_ssid; static wlc_ssid_t g_ssid; #ifdef CONFIG_WPS2 static char *g_wps_probe_req_ie; static int <API key>; #endif bool <API key>(struct net_device *dev); static <API key> g_ss_cache_ctrl; #if defined(CONFIG_FIRST_SCAN) static volatile uint <API key>; static volatile uint <API key>; #define <API key> 3 #endif #if (LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 0)) #define DAEMONIZE(a) daemonize(a); \ allow_signal(SIGKILL); \ allow_signal(SIGTERM); #else #define RAISE_RX_SOFTIRQ() \ cpu_raise_softirq(smp_processor_id(), NET_RX_SOFTIRQ) #define DAEMONIZE(a) daemonize(); \ do { if (a) \ strncpy(current->comm, a, MIN(sizeof(current->comm), (strlen(a) + 1))); \ } while (0); #endif #if defined(WL_IW_USE_ISCAN) #if !defined(CSCAN) static void wl_iw_free_ss_cache(void); static int <API key>(int kick_off); #endif #if defined(CONFIG_FIRST_SCAN) int <API key>(struct net_device *dev, uint flag); #endif static int dev_wlc_bufvar_set(struct net_device *dev, char *name, char *buf, int len); #define ISCAN_STATE_IDLE 0 #define ISCAN_STATE_SCANING 1 #define WLC_IW_ISCAN_MAXLEN 2048 typedef struct iscan_buf { struct iscan_buf * next; char iscan_buf[WLC_IW_ISCAN_MAXLEN]; } iscan_buf_t; typedef struct iscan_info { struct net_device *dev; struct timer_list timer; uint32 timer_ms; uint32 timer_on; int iscan_state; iscan_buf_t * list_hdr; iscan_buf_t * list_cur; tsk_ctl_t tsk_ctl; uint32 scan_flag; #if defined CSCAN char ioctlbuf[WLC_IOCTL_MEDLEN]; #else char ioctlbuf[WLC_IOCTL_SMLEN]; #endif wl_iscan_params_t *iscan_ex_params_p; int iscan_ex_param_size; } iscan_info_t; #define COEX_DHCP 1 #ifdef COEX_DHCP #define BT_DHCP_eSCO_FIX #define BT_DHCP_USE_FLAGS #define <API key> 2500 #define <API key> 5500 static int <API key>( struct net_device *dev, struct iw_request_info *info, union iwreq_data *wrqu, char *extra ); static void wl_iw_bt_flag_set(struct net_device *dev, bool set); static void wl_iw_bt_release(void); typedef enum bt_coex_status { BT_DHCP_IDLE = 0, BT_DHCP_START, <API key>, <API key> } coex_status_t; typedef struct bt_info { struct net_device *dev; struct timer_list timer; uint32 timer_ms; uint32 timer_on; uint32 ts_dhcp_start; uint32 ts_dhcp_ok; bool dhcp_done; int bt_state; tsk_ctl_t tsk_ctl; } bt_info_t; bt_info_t *g_bt = NULL; static void wl_iw_bt_timerfunc(ulong data); #endif iscan_info_t *g_iscan = NULL; void dhd_print_buf(void *pbuf, int len, int bytes_per_line); static void wl_iw_timerfunc(ulong data); static void <API key>(struct net_device *dev); static int wl_iw_iscan(iscan_info_t *iscan, wlc_ssid_t *ssid, uint16 action); #endif static int wl_iw_set_scan( struct net_device *dev, struct iw_request_info *info, union iwreq_data *wrqu, char *extra ); #ifndef CSCAN static int wl_iw_get_scan( struct net_device *dev, struct iw_request_info *info, struct iw_point *dwrq, char *extra ); static uint wl_iw_get_scan_prep( wl_scan_results_t *list, struct iw_request_info *info, char *extra, short max_size ); #endif static void swap_key_from_BE( wl_wsec_key_t *key ) { key->index = htod32(key->index); key->len = htod32(key->len); key->algo = htod32(key->algo); key->flags = htod32(key->flags); key->rxiv.hi = htod32(key->rxiv.hi); key->rxiv.lo = htod16(key->rxiv.lo); key->iv_initialized = htod32(key->iv_initialized); } static void swap_key_to_BE( wl_wsec_key_t *key ) { key->index = dtoh32(key->index); key->len = dtoh32(key->len); key->algo = dtoh32(key->algo); key->flags = dtoh32(key->flags); key->rxiv.hi = dtoh32(key->rxiv.hi); key->rxiv.lo = dtoh16(key->rxiv.lo); key->iv_initialized = dtoh32(key->iv_initialized); } static int dev_wlc_ioctl( struct net_device *dev, int cmd, void *arg, int len ) { struct ifreq ifr; wl_ioctl_t ioc; mm_segment_t fs; int ret = -EINVAL; if (!dev) { WL_ERROR(("%s: dev is null\n", __FUNCTION__)); return ret; } net_os_wake_lock(dev); WL_INFORM(("%s, PID:%x: send Local IOCTL -> dhd: cmd:0x%x, buf:%p, len:%d ,\n", __FUNCTION__, current->pid, cmd, arg, len)); if (g_onoff == G_WLAN_SET_ON) { memset(&ioc, 0, sizeof(ioc)); ioc.cmd = cmd; ioc.buf = arg; ioc.len = len; strcpy(ifr.ifr_name, dev->name); ifr.ifr_data = (caddr_t) &ioc; ret = dev_open(dev); if (ret) { WL_ERROR(("%s: Error dev_open: %d\n", __func__, ret)); net_os_wake_unlock(dev); return ret; } fs = get_fs(); set_fs(get_ds()); #if LINUX_VERSION_CODE <= KERNEL_VERSION(2, 6, 31) ret = dev->do_ioctl(dev, &ifr, SIOCDEVPRIVATE); #else ret = dev->netdev_ops->ndo_do_ioctl(dev, &ifr, SIOCDEVPRIVATE); #endif set_fs(fs); } else { WL_TRACE(("%s: call after driver stop : ignored\n", __FUNCTION__)); } net_os_wake_unlock(dev); return ret; } static int <API key>( struct net_device *dev, char *name, uint reg, int *retval) { union { char buf[WLC_IOCTL_SMLEN]; int val; } var; int error; uint len; len = bcm_mkiovar(name, (char *)(&reg), sizeof(reg), (char *)(&var), sizeof(var.buf)); ASSERT(len); error = dev_wlc_ioctl(dev, WLC_GET_VAR, (void *)&var, len); *retval = dtoh32(var.val); return (error); } static int <API key>( struct net_device *dev, char *name, char *addr, char * val) { char reg_addr[8]; memset(reg_addr, 0, sizeof(reg_addr)); memcpy((char *)&reg_addr[0], (char *)addr, 4); memcpy((char *)&reg_addr[4], (char *)val, 4); return (dev_wlc_bufvar_set(dev, name, (char *)&reg_addr[0], sizeof(reg_addr))); } static int dev_wlc_intvar_set( struct net_device *dev, char *name, int val) { char buf[WLC_IOCTL_SMLEN]; uint len; val = htod32(val); len = bcm_mkiovar(name, (char *)(&val), sizeof(val), buf, sizeof(buf)); ASSERT(len); return (dev_wlc_ioctl(dev, WLC_SET_VAR, buf, len)); } #if defined(WL_IW_USE_ISCAN) static int dev_iw_iovar_setbuf( struct net_device *dev, char *iovar, void *param, int paramlen, void *bufptr, int buflen) { int iolen; iolen = bcm_mkiovar(iovar, param, paramlen, bufptr, buflen); ASSERT(iolen); if (iolen == 0) return 0; return (dev_wlc_ioctl(dev, WLC_SET_VAR, bufptr, iolen)); } static int dev_iw_iovar_getbuf( struct net_device *dev, char *iovar, void *param, int paramlen, void *bufptr, int buflen) { int iolen; iolen = bcm_mkiovar(iovar, param, paramlen, bufptr, buflen); ASSERT(iolen); return (dev_wlc_ioctl(dev, WLC_GET_VAR, bufptr, buflen)); } #endif #if WIRELESS_EXT > 17 static int dev_wlc_bufvar_set( struct net_device *dev, char *name, char *buf, int len) { #if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 31) char ioctlbuf[MAX_WLIW_IOCTL_LEN]; #else static char ioctlbuf[MAX_WLIW_IOCTL_LEN]; #endif uint buflen; buflen = bcm_mkiovar(name, buf, len, ioctlbuf, sizeof(ioctlbuf)); ASSERT(buflen); return (dev_wlc_ioctl(dev, WLC_SET_VAR, ioctlbuf, buflen)); } #endif static int dev_wlc_bufvar_get( struct net_device *dev, char *name, char *buf, int buflen) { #if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 31) char ioctlbuf[MAX_WLIW_IOCTL_LEN]; #else static char ioctlbuf[MAX_WLIW_IOCTL_LEN]; #endif int error; uint len; len = bcm_mkiovar(name, NULL, 0, ioctlbuf, sizeof(ioctlbuf)); ASSERT(len); error = dev_wlc_ioctl(dev, WLC_GET_VAR, (void *)ioctlbuf, MAX_WLIW_IOCTL_LEN); if (!error) bcopy(ioctlbuf, buf, buflen); return (error); } static int dev_wlc_intvar_get( struct net_device *dev, char *name, int *retval) { union { char buf[WLC_IOCTL_SMLEN]; int val; } var; int error; uint len; uint data_null; len = bcm_mkiovar(name, (char *)(&data_null), 0, (char *)(&var), sizeof(var.buf)); ASSERT(len); error = dev_wlc_ioctl(dev, WLC_GET_VAR, (void *)&var, len); *retval = dtoh32(var.val); return (error); } #if WIRELESS_EXT > 12 static int <API key>( struct net_device *dev, struct iw_request_info *info, union iwreq_data *wrqu, char *extra ) { int as = 0; int error = 0; char *p = extra; #if defined(WL_IW_USE_ISCAN) if (g_iscan->iscan_state == ISCAN_STATE_IDLE) #endif error = dev_wlc_ioctl(dev, <API key>, &as, sizeof(as)); #if defined(WL_IW_USE_ISCAN) else g_iscan->scan_flag = as; #endif p += snprintf(p, MAX_WX_STRING, "OK"); wrqu->data.length = p - extra + 1; return error; } static int <API key>( struct net_device *dev, struct iw_request_info *info, union iwreq_data *wrqu, char *extra ) { int ps = 1; int error = 0; char *p = extra; #if defined(WL_IW_USE_ISCAN) if (g_iscan->iscan_state == ISCAN_STATE_IDLE) { #endif if (<API key> == 0) { error = dev_wlc_ioctl(dev, <API key>, &ps, sizeof(ps)); } #if defined(WL_IW_USE_ISCAN) } else g_iscan->scan_flag = ps; #endif p += snprintf(p, MAX_WX_STRING, "OK"); wrqu->data.length = p - extra + 1; return error; } static int wl_iw_set_txpower( struct net_device *dev, struct iw_request_info *info, union iwreq_data *wrqu, char *extra ) { int error = 0; char *p = extra; int txpower = -1; txpower = bcm_atoi(extra + strlen(TXPOWER_SET_CMD) + 1); if ((txpower >= 0) && (txpower <= 127)) { txpower |= WL_TXPWR_OVERRIDE; txpower = htod32(txpower); error = dev_wlc_intvar_set(dev, "qtxpower", txpower); p += snprintf(p, MAX_WX_STRING, "OK"); WL_TRACE(("%s: set TXpower 0x%X is OK\n", __FUNCTION__, txpower)); } else { WL_ERROR(("%s: set tx power failed\n", __FUNCTION__)); p += snprintf(p, MAX_WX_STRING, "FAIL"); } wrqu->data.length = p - extra + 1; return error; } static int wl_iw_get_macaddr( struct net_device *dev, struct iw_request_info *info, union iwreq_data *wrqu, char *extra ) { int error; char buf[128]; struct ether_addr *id; char *p = extra; strcpy(buf, "cur_etheraddr"); error = dev_wlc_ioctl(dev, WLC_GET_VAR, buf, sizeof(buf)); id = (struct ether_addr *) buf; p += snprintf(p, MAX_WX_STRING, "Macaddr = %02X:%02X:%02X:%02X:%02X:%02X\n", id->octet[0], id->octet[1], id->octet[2], id->octet[3], id->octet[4], id->octet[5]); wrqu->data.length = p - extra + 1; return error; } static int wl_iw_set_country( struct net_device *dev, struct iw_request_info *info, union iwreq_data *wrqu, char *extra ) { char country_code[WLC_CNTRY_BUF_SZ]; int error = 0; char *p = extra; int country_offset; int country_code_size; wl_country_t cspec = {{0}, 0, {0}}; char smbuf[WLC_IOCTL_SMLEN]; scb_val_t scbval; cspec.rev = -1; memset(country_code, 0, sizeof(country_code)); memset(smbuf, 0, sizeof(smbuf)); country_offset = strcspn(extra, " "); country_code_size = strlen(extra) - country_offset; if (country_offset != 0) { strncpy(country_code, extra + country_offset +1, MIN(country_code_size, sizeof(country_code))); bzero(&scbval, sizeof(scb_val_t)); if ((error = dev_wlc_ioctl(dev, WLC_DISASSOC, &scbval, sizeof(scb_val_t)))) { WL_ERROR(("%s: set country failed due to Disassoc error\n", __FUNCTION__)); goto exit_failed; } memcpy(cspec.country_abbrev, country_code, WLC_CNTRY_BUF_SZ); memcpy(cspec.ccode, country_code, WLC_CNTRY_BUF_SZ); <API key>((char *)&cspec.country_abbrev, &cspec); if ((error = dev_iw_iovar_setbuf(dev, "country", &cspec, sizeof(cspec), smbuf, sizeof(smbuf))) >= 0) { p += snprintf(p, MAX_WX_STRING, "OK"); WL_ERROR(("%s: set country for %s as %s rev %d is OK\n", __FUNCTION__, country_code, cspec.ccode, cspec.rev)); dhd_bus_country_set(dev, &cspec); goto exit; } } WL_ERROR(("%s: set country for %s as %s rev %d failed\n", __FUNCTION__, country_code, cspec.ccode, cspec.rev)); exit_failed: p += snprintf(p, MAX_WX_STRING, "FAIL"); exit: wrqu->data.length = p - extra + 1; return error; } static int <API key>( struct net_device *dev, struct iw_request_info *info, union iwreq_data *wrqu, char *extra ) { int error = 0; char *p = extra; static int pm = PM_FAST; int pm_local = PM_OFF; char powermode_val = 0; WL_TRACE_COEX(("%s: DHCP session cmd:%s\n", __FUNCTION__, extra)); strncpy((char *)&powermode_val, extra + strlen("POWERMODE") +1, 1); if (strnicmp((char *)&powermode_val, "1", strlen("1")) == 0) { WL_TRACE(("%s: DHCP session starts\n", __FUNCTION__)); dev_wlc_ioctl(dev, WLC_GET_PM, &pm, sizeof(pm)); dev_wlc_ioctl(dev, WLC_SET_PM, &pm_local, sizeof(pm_local)); <API key>(dev, 0); #ifdef COEX_DHCP g_bt->ts_dhcp_start = JF2MS; g_bt->dhcp_done = FALSE; WL_TRACE_COEX(("%s: DHCP start, pm:%d changed to pm:%d\n", __FUNCTION__, pm, pm_local)); #endif } else if (strnicmp((char *)&powermode_val, "0", strlen("0")) == 0) { dev_wlc_ioctl(dev, WLC_SET_PM, &pm, sizeof(pm)); <API key>(dev, 1); #ifdef COEX_DHCP g_bt->dhcp_done = TRUE; g_bt->ts_dhcp_ok = JF2MS; WL_TRACE_COEX(("%s: DHCP done for:%d ms, restored pm:%d\n", __FUNCTION__, (g_bt->ts_dhcp_ok - g_bt->ts_dhcp_start), pm)); #endif } else { WL_ERROR(("%s Unkwown yet power setting, ignored\n", __FUNCTION__)); } p += snprintf(p, MAX_WX_STRING, "OK"); wrqu->data.length = p - extra + 1; return error; } bool <API key>(struct net_device *dev) { int ioc_res = 0; bool res = FALSE; int sco_id_cnt = 0; int param27; int i; for (i = 0; i < 12; i++) { ioc_res = <API key>(dev, "btc_params", 27, &param27); WL_TRACE_COEX(("%s, sample[%d], btc params: 27:%x\n", __FUNCTION__, i, param27)); if (ioc_res < 0) { WL_ERROR(("%s ioc read btc params error\n", __FUNCTION__)); break; } if ((param27 & 0x6) == 2) { sco_id_cnt++; } if (sco_id_cnt > 2) { WL_TRACE_COEX(("%s, sco/esco detected, pkt id_cnt:%d samples:%d\n", __FUNCTION__, sco_id_cnt, i)); res = TRUE; break; } msleep(5); } return res; } #if defined(BT_DHCP_eSCO_FIX) static int set_btc_esco_params(struct net_device *dev, bool trump_sco) { static bool saved_status = FALSE; char buf_reg50va_dhcp_on[8] = { 50, 00, 00, 00, 0x22, 0x80, 0x00, 0x00 }; char buf_reg51va_dhcp_on[8] = { 51, 00, 00, 00, 0x00, 0x00, 0x00, 0x00 }; char buf_reg64va_dhcp_on[8] = { 64, 00, 00, 00, 0x00, 0x00, 0x00, 0x00 }; char buf_reg65va_dhcp_on[8] = { 65, 00, 00, 00, 0x00, 0x00, 0x00, 0x00 }; char buf_reg71va_dhcp_on[8] = { 71, 00, 00, 00, 0x00, 0x00, 0x00, 0x00 }; uint32 regaddr; static uint32 saved_reg50; static uint32 saved_reg51; static uint32 saved_reg64; static uint32 saved_reg65; static uint32 saved_reg71; if (trump_sco) { WL_TRACE_COEX(("Do new SCO/eSCO coex algo {save & override} \n")); if ((!<API key>(dev, "btc_params", 50, &saved_reg50)) && (!<API key>(dev, "btc_params", 51, &saved_reg51)) && (!<API key>(dev, "btc_params", 64, &saved_reg64)) && (!<API key>(dev, "btc_params", 65, &saved_reg65)) && (!<API key>(dev, "btc_params", 71, &saved_reg71))) { saved_status = TRUE; WL_TRACE_COEX(("%s saved bt_params[50,51,64,65,71]:" " 0x%x 0x%x 0x%x 0x%x 0x%x\n", __FUNCTION__, saved_reg50, saved_reg51, saved_reg64, saved_reg65, saved_reg71)); } else { WL_ERROR((":%s: save btc_params failed\n", __FUNCTION__)); saved_status = FALSE; return -1; } WL_TRACE_COEX(("override with [50,51,64,65,71]:" " 0x%x 0x%x 0x%x 0x%x 0x%x\n", *(u32 *)(buf_reg50va_dhcp_on+4), *(u32 *)(buf_reg51va_dhcp_on+4), *(u32 *)(buf_reg64va_dhcp_on+4), *(u32 *)(buf_reg65va_dhcp_on+4), *(u32 *)(buf_reg71va_dhcp_on+4))); dev_wlc_bufvar_set(dev, "btc_params", (char *)&buf_reg50va_dhcp_on[0], 8); dev_wlc_bufvar_set(dev, "btc_params", (char *)&buf_reg51va_dhcp_on[0], 8); dev_wlc_bufvar_set(dev, "btc_params", (char *)&buf_reg64va_dhcp_on[0], 8); dev_wlc_bufvar_set(dev, "btc_params", (char *)&buf_reg65va_dhcp_on[0], 8); dev_wlc_bufvar_set(dev, "btc_params", (char *)&buf_reg71va_dhcp_on[0], 8); saved_status = TRUE; } else if (saved_status) { WL_TRACE_COEX(("Do new SCO/eSCO coex algo {save & override} \n")); regaddr = 50; <API key>(dev, "btc_params", (char *)&regaddr, (char *)&saved_reg50); regaddr = 51; <API key>(dev, "btc_params", (char *)&regaddr, (char *)&saved_reg51); regaddr = 64; <API key>(dev, "btc_params", (char *)&regaddr, (char *)&saved_reg64); regaddr = 65; <API key>(dev, "btc_params", (char *)&regaddr, (char *)&saved_reg65); regaddr = 71; <API key>(dev, "btc_params", (char *)&regaddr, (char *)&saved_reg71); WL_TRACE_COEX(("restore bt_params[50,51,64,65,71]: 0x%x 0x%x 0x%x 0x%x 0x%x\n", saved_reg50, saved_reg51, saved_reg64, saved_reg65, saved_reg71)); saved_status = FALSE; } else { WL_ERROR((":%s att to restore not saved BTCOEX params\n", __FUNCTION__)); return -1; } return 0; } #endif static int <API key>( struct net_device *dev, struct iw_request_info *info, union iwreq_data *wrqu, char *extra ) { int error = 0; int pm_local; char *p = extra; error = dev_wlc_ioctl(dev, WLC_GET_PM, &pm_local, sizeof(pm_local)); if (!error) { WL_TRACE(("%s: Powermode = %d\n", __func__, pm_local)); if (pm_local == PM_OFF) pm_local = 1; else pm_local = 0; p += snprintf(p, MAX_WX_STRING, "powermode = %d", pm_local); } else { WL_TRACE(("%s: Error = %d\n", __func__, error)); p += snprintf(p, MAX_WX_STRING, "FAIL"); } wrqu->data.length = p - extra + 1; return error; } static int <API key>( struct net_device *dev, struct iw_request_info *info, union iwreq_data *wrqu, char *extra ) { int error = 0; char *p = extra; char powermode_val = 0; char buf_reg66va_dhcp_on[8] = { 66, 00, 00, 00, 0x10, 0x27, 0x00, 0x00 }; char buf_reg41va_dhcp_on[8] = { 41, 00, 00, 00, 0x33, 0x00, 0x00, 0x00 }; char buf_reg68va_dhcp_on[8] = { 68, 00, 00, 00, 0x90, 0x01, 0x00, 0x00 }; uint32 regaddr; static uint32 saved_reg66; static uint32 saved_reg41; static uint32 saved_reg68; static bool saved_status = FALSE; #ifdef COEX_DHCP char buf_flag7_default[8] = { 7, 00, 00, 00, 0x0, 0x00, 0x00, 0x00}; #endif strncpy((char *)&powermode_val, extra + strlen("BTCOEXMODE") +1, 1); if (strnicmp((char *)&powermode_val, "1", strlen("1")) == 0) { WL_TRACE(("%s: DHCP session starts\n", __FUNCTION__)); if ((saved_status == FALSE) && (!<API key>(dev, "btc_params", 66, &saved_reg66)) && (!<API key>(dev, "btc_params", 41, &saved_reg41)) && (!<API key>(dev, "btc_params", 68, &saved_reg68))) { saved_status = TRUE; WL_TRACE(("Saved 0x%x 0x%x 0x%x\n", saved_reg66, saved_reg41, saved_reg68)); #ifdef COEX_DHCP if (<API key>(dev)) { dev_wlc_bufvar_set(dev, "btc_params", (char *)&buf_reg66va_dhcp_on[0], sizeof(buf_reg66va_dhcp_on)); dev_wlc_bufvar_set(dev, "btc_params", (char *)&buf_reg41va_dhcp_on[0], sizeof(buf_reg41va_dhcp_on)); dev_wlc_bufvar_set(dev, "btc_params", (char *)&buf_reg68va_dhcp_on[0], sizeof(buf_reg68va_dhcp_on)); saved_status = TRUE; g_bt->bt_state = BT_DHCP_START; g_bt->timer_on = 1; mod_timer(&g_bt->timer, g_bt->timer.expires); WL_TRACE_COEX(("%s enable BT DHCP Timer\n", __FUNCTION__)); } #endif } else if (saved_status == TRUE) { WL_ERROR(("%s was called w/o DHCP OFF. Continue\n", __FUNCTION__)); } } else if (strnicmp((char *)&powermode_val, "2", strlen("2")) == 0) { #ifdef COEX_DHCP WL_TRACE(("%s disable BT DHCP Timer\n", __FUNCTION__)); if (g_bt->timer_on) { g_bt->timer_on = 0; del_timer_sync(&g_bt->timer); if (g_bt->bt_state != BT_DHCP_IDLE) { WL_TRACE_COEX(("%s bt->bt_state:%d\n", __FUNCTION__, g_bt->bt_state)); up(&g_bt->tsk_ctl.sema); } } if (saved_status == TRUE) dev_wlc_bufvar_set(dev, "btc_flags", (char *)&buf_flag7_default[0], sizeof(buf_flag7_default)); #endif if (saved_status == TRUE) { regaddr = 66; <API key>(dev, "btc_params", (char *)&regaddr, (char *)&saved_reg66); regaddr = 41; <API key>(dev, "btc_params", (char *)&regaddr, (char *)&saved_reg41); regaddr = 68; <API key>(dev, "btc_params", (char *)&regaddr, (char *)&saved_reg68); WL_TRACE_COEX(("restore regs {66,41,68} <- 0x%x 0x%x 0x%x\n", saved_reg66, saved_reg41, saved_reg68)); } saved_status = FALSE; } else { WL_ERROR(("%s Unkwown yet power setting, ignored\n", __FUNCTION__)); } p += snprintf(p, MAX_WX_STRING, "OK"); wrqu->data.length = p - extra + 1; return error; } static int <API key>( struct net_device *dev, struct iw_request_info *info, union iwreq_data *wrqu, char *extra ) { int suspend_flag; int ret_now; int ret = 0; suspend_flag = *(extra + strlen(SETSUSPENDOPT_CMD) + 1) - '0'; if (suspend_flag != 0) suspend_flag = 1; ret_now = <API key>(dev, suspend_flag); if (ret_now != suspend_flag) { if (!(ret = net_os_set_suspend(dev, ret_now, 1))) WL_ERROR(("%s: Suspend Flag %d -> %d\n", __FUNCTION__, ret_now, suspend_flag)); else WL_ERROR(("%s: failed %d\n", __FUNCTION__, ret)); } return ret; } static int <API key>( struct net_device *dev, struct iw_request_info *info, union iwreq_data *wrqu, char *extra ) { int ret = 0; #if !defined(<API key>) || !defined(<API key>) int suspend_flag; suspend_flag = *(extra + strlen(SETSUSPENDMODE_CMD) + 1) - '0'; if (suspend_flag != 0) suspend_flag = 1; if (!(ret = net_os_set_suspend(dev, suspend_flag, 0))) WL_ERROR(("%s: Suspend Mode %d\n",__FUNCTION__,suspend_flag)); else WL_ERROR(("%s: failed %d\n", __FUNCTION__, ret)); #endif return ret; } static int wl_format_ssid(char* ssid_buf, uint8* ssid, int ssid_len) { int i, c; char *p = ssid_buf; if (ssid_len > 32) ssid_len = 32; for (i = 0; i < ssid_len; i++) { c = (int)ssid[i]; if (c == '\\') { *p++ = '\\'; *p++ = '\\'; } else if (isprint((uchar)c)) { *p++ = (char)c; } else { p += sprintf(p, "\\x%02X", c); } } *p = '\0'; return p - ssid_buf; } static int <API key>( struct net_device *dev, struct iw_request_info *info, union iwreq_data *wrqu, char *extra ) { int error = 0; char *p = extra; static int link_speed; net_os_wake_lock(dev); if (g_onoff == G_WLAN_SET_ON) { error = dev_wlc_ioctl(dev, WLC_GET_RATE, &link_speed, sizeof(link_speed)); link_speed *= 500000; } p += snprintf(p, MAX_WX_STRING, "LinkSpeed %d", link_speed/1000000); wrqu->data.length = p - extra + 1; net_os_wake_unlock(dev); return error; } static int wl_iw_get_dtim_skip( struct net_device *dev, struct iw_request_info *info, union iwreq_data *wrqu, char *extra ) { int error = -1; char *p = extra; char iovbuf[32]; net_os_wake_lock(dev); if (g_onoff == G_WLAN_SET_ON) { memset(iovbuf, 0, sizeof(iovbuf)); strcpy(iovbuf, "bcn_li_dtim"); if ((error = dev_wlc_ioctl(dev, WLC_GET_VAR, &iovbuf, sizeof(iovbuf))) >= 0) { p += snprintf(p, MAX_WX_STRING, "Dtim_skip %d", iovbuf[0]); WL_TRACE(("%s: get dtim_skip = %d\n", __FUNCTION__, iovbuf[0])); wrqu->data.length = p - extra + 1; } else WL_ERROR(("%s: get dtim_skip failed code %d\n", __FUNCTION__, error)); } net_os_wake_unlock(dev); return error; } static int wl_iw_set_dtim_skip( struct net_device *dev, struct iw_request_info *info, union iwreq_data *wrqu, char *extra ) { int error = -1; char *p = extra; int bcn_li_dtim; char iovbuf[32]; net_os_wake_lock(dev); if (g_onoff == G_WLAN_SET_ON) { bcn_li_dtim = htod32((uint)*(extra + strlen(DTIM_SKIP_SET_CMD) + 1) - '0'); if ((bcn_li_dtim >= 0) || ((bcn_li_dtim <= 5))) { memset(iovbuf, 0, sizeof(iovbuf)); bcm_mkiovar("bcn_li_dtim", (char *)&bcn_li_dtim, 4, iovbuf, sizeof(iovbuf)); if ((error = dev_wlc_ioctl(dev, WLC_SET_VAR, &iovbuf, sizeof(iovbuf))) >= 0) { p += snprintf(p, MAX_WX_STRING, "OK"); <API key>(dev, bcn_li_dtim); WL_TRACE(("%s: set dtim_skip %d OK\n", __FUNCTION__, bcn_li_dtim)); goto exit; } else WL_ERROR(("%s: set dtim_skip %d failed code %d\n", __FUNCTION__, bcn_li_dtim, error)); } else WL_ERROR(("%s Incorrect dtim_skip setting %d, ignored\n", __FUNCTION__, bcn_li_dtim)); } p += snprintf(p, MAX_WX_STRING, "FAIL"); exit: wrqu->data.length = p - extra + 1; net_os_wake_unlock(dev); return error; } static int wl_iw_get_band( struct net_device *dev, struct iw_request_info *info, union iwreq_data *wrqu, char *extra ) { int error = -1; char *p = extra; static int band; net_os_wake_lock(dev); if (g_onoff == G_WLAN_SET_ON) { error = dev_wlc_ioctl(dev, WLC_GET_BAND, &band, sizeof(band)); p += snprintf(p, MAX_WX_STRING, "Band %d", band); wrqu->data.length = p - extra + 1; } net_os_wake_unlock(dev); return error; } static int wl_iw_set_band( struct net_device *dev, struct iw_request_info *info, union iwreq_data *wrqu, char *extra ) { int error = -1; char *p = extra; uint band; net_os_wake_lock(dev); if (g_onoff == G_WLAN_SET_ON) { band = htod32((uint)*(extra + strlen(BAND_SET_CMD) + 1) - '0'); if ((band == WLC_BAND_AUTO) || (band == WLC_BAND_5G) || (band == WLC_BAND_2G)) { if ((error = dev_wlc_ioctl(dev, WLC_SET_BAND, &band, sizeof(band))) >= 0) { p += snprintf(p, MAX_WX_STRING, "OK"); WL_TRACE(("%s: set band %d OK\n", __FUNCTION__, band)); goto exit; } else { WL_ERROR(("%s: set band %d failed code %d\n", __FUNCTION__, band, error)); } } else { WL_ERROR(("%s Incorrect band setting %d, ignored\n", __FUNCTION__, band)); } } p += snprintf(p, MAX_WX_STRING, "FAIL"); exit: wrqu->data.length = p - extra + 1; net_os_wake_unlock(dev); return error; } #ifdef PNO_SUPPORT static int wl_iw_set_pno_reset( struct net_device *dev, struct iw_request_info *info, union iwreq_data *wrqu, char *extra ) { int error = -1; char *p = extra; net_os_wake_lock(dev); if ((g_onoff == G_WLAN_SET_ON) && (dev != NULL)) { if ((error = dhd_dev_pno_reset(dev)) >= 0) { p += snprintf(p, MAX_WX_STRING, "OK"); WL_TRACE(("%s: set OK\n", __FUNCTION__)); goto exit; } else WL_ERROR(("%s: failed code %d\n", __FUNCTION__, error)); } p += snprintf(p, MAX_WX_STRING, "FAIL"); exit: wrqu->data.length = p - extra + 1; net_os_wake_unlock(dev); return error; } static int <API key>( struct net_device *dev, struct iw_request_info *info, union iwreq_data *wrqu, char *extra ) { int error = -1; char *p = extra; int pfn_enabled; net_os_wake_lock(dev); pfn_enabled = htod32((uint)*(extra + strlen(PNOENABLE_SET_CMD) + 1) - '0'); if ((g_onoff == G_WLAN_SET_ON) && (dev != NULL)) { if ((error = dhd_dev_pno_enable(dev, pfn_enabled)) >= 0) { p += snprintf(p, MAX_WX_STRING, "OK"); WL_TRACE(("%s: set OK\n", __FUNCTION__)); goto exit; } else WL_ERROR(("%s: failed code %d\n", __FUNCTION__, error)); } p += snprintf(p, MAX_WX_STRING, "FAIL"); exit: wrqu->data.length = p - extra + 1; net_os_wake_unlock(dev); return error; } static int wl_iw_set_pno_set( struct net_device *dev, struct iw_request_info *info, union iwreq_data *wrqu, char *extra ) { int res = -1; wlc_ssid_t ssids_local[MAX_PFN_LIST_COUNT]; int nssid = 0; cmd_tlv_t *cmd_tlv_temp; char *str_ptr; int tlv_size_left; int pno_time; int pno_repeat; int pno_freq_expo_max; #ifdef PNO_SET_DEBUG int i; char pno_in_example[] = { 'P', 'N', 'O', 'S', 'E', 'T', 'U', 'P', ' ', 'S', '1', '2', '0', 'S', 0x04, 'B', 'R', 'C', 'M', 'S', 0x04, 'G', 'O', 'O', 'G', 'T', '1', 'E', 'R', '2', 'M', '2', 0x00 }; #endif net_os_wake_lock(dev); WL_ERROR(("\n### %s: info->cmd:%x, info->flags:%x, u.data=0x%p, u.len=%d\n", __FUNCTION__, info->cmd, info->flags, wrqu->data.pointer, wrqu->data.length)); if (g_onoff == G_WLAN_SET_OFF) { WL_TRACE(("%s: driver is not up yet after START\n", __FUNCTION__)); goto exit_proc; } if (wrqu->data.length < (strlen(PNOSETUP_SET_CMD) + sizeof(cmd_tlv_t))) { WL_ERROR(("%s argument=%d less %d\n", __FUNCTION__, wrqu->data.length, (int)(strlen(PNOSETUP_SET_CMD) + sizeof(cmd_tlv_t)))); goto exit_proc; } #ifdef PNO_SET_DEBUG if (!(extra = kmalloc(sizeof(pno_in_example) +100, GFP_KERNEL))) { res = -ENOMEM; goto exit_proc; } memcpy(extra, pno_in_example, sizeof(pno_in_example)); wrqu->data.length = sizeof(pno_in_example); for (i = 0; i < wrqu->data.length; i++) printf("%02X ", extra[i]); printf("\n"); #endif str_ptr = extra; #ifdef PNO_SET_DEBUG str_ptr += strlen("PNOSETUP "); tlv_size_left = wrqu->data.length - strlen("PNOSETUP "); #else str_ptr += strlen(PNOSETUP_SET_CMD); tlv_size_left = wrqu->data.length - strlen(PNOSETUP_SET_CMD); #endif cmd_tlv_temp = (cmd_tlv_t *)str_ptr; memset(ssids_local, 0, sizeof(ssids_local)); pno_repeat = pno_freq_expo_max = 0; if ((cmd_tlv_temp->prefix == PNO_TLV_PREFIX) && (cmd_tlv_temp->version == PNO_TLV_VERSION) && (cmd_tlv_temp->subver == PNO_TLV_SUBVERSION)) { str_ptr += sizeof(cmd_tlv_t); tlv_size_left -= sizeof(cmd_tlv_t); if ((nssid = <API key>(&str_ptr, ssids_local, MAX_PFN_LIST_COUNT, &tlv_size_left)) <= 0) { WL_ERROR(("SSID is not presented or corrupted ret=%d\n", nssid)); goto exit_proc; } else { if ((str_ptr[0] != PNO_TLV_TYPE_TIME) || (tlv_size_left <= 1)) { WL_ERROR(("%s scan duration corrupted field size %d\n", __FUNCTION__, tlv_size_left)); goto exit_proc; } str_ptr++; pno_time = simple_strtoul(str_ptr, &str_ptr, 16); WL_PNO(("%s: pno_time=%d\n", __FUNCTION__, pno_time)); if (str_ptr[0] != 0) { if ((str_ptr[0] != PNO_TLV_FREQ_REPEAT)) { WL_ERROR(("%s pno repeat : corrupted field\n", __FUNCTION__)); goto exit_proc; } str_ptr++; pno_repeat = simple_strtoul(str_ptr, &str_ptr, 16); WL_PNO(("%s :got pno_repeat=%d\n", __FUNCTION__, pno_repeat)); if (str_ptr[0] != <API key>) { WL_ERROR(("%s FREQ_EXPO_MAX corrupted field size\n", __FUNCTION__)); goto exit_proc; } str_ptr++; pno_freq_expo_max = simple_strtoul(str_ptr, &str_ptr, 16); WL_PNO(("%s: pno_freq_expo_max=%d\n", __FUNCTION__, pno_freq_expo_max)); } } } else { WL_ERROR(("%s get wrong TLV command\n", __FUNCTION__)); goto exit_proc; } res = dhd_dev_pno_set(dev, ssids_local, nssid, pno_time, pno_repeat, pno_freq_expo_max); exit_proc: net_os_wake_unlock(dev); return res; } static int <API key>( struct net_device *dev, struct iw_request_info *info, union iwreq_data *wrqu, char *extra ) { int ret = -1; char *tmp_ptr; int size, tmp_size; net_os_wake_lock(dev); WL_ERROR(("\n### %s: info->cmd:%x, info->flags:%x, u.data=0x%p, u.len=%d\n", __FUNCTION__, info->cmd, info->flags, wrqu->data.pointer, wrqu->data.length)); if (g_onoff == G_WLAN_SET_OFF) { WL_TRACE(("%s: driver is not up yet after START\n", __FUNCTION__)); goto exit_proc; } if (wrqu->data.length <= strlen(PNOSETADD_SET_CMD) + sizeof(cmd_tlv_t)) { WL_ERROR(("%s argument=%d less than %d\n", __FUNCTION__, wrqu->data.length, (int)(strlen(PNOSETADD_SET_CMD) + sizeof(cmd_tlv_t)))); goto exit_proc; } bcopy(PNOSETUP_SET_CMD, extra, strlen(PNOSETUP_SET_CMD)); tmp_ptr = extra + strlen(PNOSETUP_SET_CMD); size = wrqu->data.length - strlen(PNOSETUP_SET_CMD); tmp_size = size; while (*tmp_ptr && tmp_size > 0) { if ((*tmp_ptr == 'S') && (size - tmp_size) >= sizeof(cmd_tlv_t)) { *(tmp_ptr + 1) = ((*(tmp_ptr + 1) - '0') << 4) + (*(tmp_ptr + 2) - '0'); memmove(tmp_ptr + 2, tmp_ptr + 3, tmp_size - 3); tmp_size -= 2 + *(tmp_ptr + 1); tmp_ptr += 2 + *(tmp_ptr + 1); size } else { tmp_ptr++; tmp_size } } wrqu->data.length = strlen(PNOSETUP_SET_CMD) + size; ret = wl_iw_set_pno_set(dev, info, wrqu, extra); exit_proc: net_os_wake_unlock(dev); return ret; } #endif static int wl_iw_get_rssi( struct net_device *dev, struct iw_request_info *info, union iwreq_data *wrqu, char *extra ) { static int rssi = 0; static wlc_ssid_t ssid = {0}; int error = 0; char *p = extra; static char ssidbuf[SSID_FMT_BUF_LEN]; scb_val_t scb_val; net_os_wake_lock(dev); bzero(&scb_val, sizeof(scb_val_t)); if (g_onoff == G_WLAN_SET_ON) { error = dev_wlc_ioctl(dev, WLC_GET_RSSI, &scb_val, sizeof(scb_val_t)); if (error) { WL_ERROR(("%s: Fails %d\n", __FUNCTION__, error)); net_os_wake_unlock(dev); return error; } rssi = dtoh32(scb_val.val); error = dev_wlc_ioctl(dev, WLC_GET_SSID, &ssid, sizeof(ssid)); if (!error) { ssid.SSID_len = dtoh32(ssid.SSID_len); wl_format_ssid(ssidbuf, ssid.SSID, dtoh32(ssid.SSID_len)); } } p += snprintf(p, MAX_WX_STRING, "%s rssi %d ", ssidbuf, rssi); wrqu->data.length = p - extra + 1; net_os_wake_unlock(dev); return error; } int <API key>( struct net_device *dev, char *flag ) { union iwreq_data wrqu; char extra[IW_CUSTOM_MAX + 1]; int cmd; cmd = IWEVCUSTOM; memset(&wrqu, 0, sizeof(wrqu)); if (strlen(flag) > sizeof(extra)) return -1; strcpy(extra, flag); wrqu.data.length = strlen(extra); wireless_send_event(dev, cmd, &wrqu, extra); <API key>(dev, <API key>); WL_TRACE(("Send IWEVCUSTOM Event as %s\n", extra)); return 0; } int wl_control_wl_start(struct net_device *dev) { wl_iw_t *iw; int ret = 0; WL_TRACE(("Enter %s \n", __FUNCTION__)); if (!dev) { WL_ERROR(("%s: dev is null\n", __FUNCTION__)); return -1; } iw = *(wl_iw_t **)netdev_priv(dev); if (!iw) { WL_ERROR(("%s: wl is null\n", __FUNCTION__)); return -1; } dhd_net_if_lock(dev); if (g_onoff == G_WLAN_SET_OFF) { <API key>(WLAN_RESET_ON); #if defined(BCMLXSDMMC) sdioh_start(NULL, 0); #endif ret = dhd_dev_reset(dev, 0); #if defined(BCMLXSDMMC) sdioh_start(NULL, 1); #endif if (!ret) dhd_dev_init_ioctl(dev); g_onoff = G_WLAN_SET_ON; } WL_TRACE(("Exited %s\n", __FUNCTION__)); dhd_net_if_unlock(dev); return ret; } static int <API key>( struct net_device *dev, struct iw_request_info *info ) { wl_iw_t *iw; int ret = 0; WL_TRACE(("Enter %s\n", __FUNCTION__)); if (!dev) { WL_ERROR(("%s: dev is null\n", __FUNCTION__)); return -1; } iw = *(wl_iw_t **)netdev_priv(dev); if (!iw) { WL_ERROR(("%s: wl is null\n", __FUNCTION__)); return -1; } dhd_net_if_lock(dev); #ifdef SOFTAP ap_cfg_running = FALSE; #endif if (g_onoff == G_WLAN_SET_ON) { g_onoff = G_WLAN_SET_OFF; #if defined(WL_IW_USE_ISCAN) g_iscan->iscan_state = ISCAN_STATE_IDLE; #endif ret = dhd_dev_reset(dev, 1); #if defined(WL_IW_USE_ISCAN) #if !defined(CSCAN) wl_iw_free_ss_cache(); <API key>(0); g_ss_cache_ctrl.m_link_down = 1; #endif memset(g_scan, 0, G_SCAN_RESULTS); <API key> = 0; #if defined(CONFIG_FIRST_SCAN) <API key> = <API key>; <API key> = 0; #endif #endif #if defined(BCMLXSDMMC) sdioh_stop(NULL); #endif <API key>(WLAN_RESET_OFF); <API key>(dev, "STOP"); } dhd_net_if_unlock(dev); WL_TRACE(("Exited %s\n", __FUNCTION__)); return ret; } static int wl_iw_control_wl_on( struct net_device *dev, struct iw_request_info *info ) { int ret = 0; WL_TRACE(("Enter %s \n", __FUNCTION__)); ret = wl_control_wl_start(dev); <API key>(dev, "START"); #ifdef SOFTAP if (!ap_fw_loaded) { <API key>(dev, 0); } #else <API key>(dev, 0); #endif WL_TRACE(("Exited %s\n", __FUNCTION__)); return ret; } #ifdef SOFTAP static struct ap_profile my_ap; static int set_ap_cfg(struct net_device *dev, struct ap_profile *ap); static int get_assoc_sta_list(struct net_device *dev, char *buf, int len); static int set_ap_mac_list(struct net_device *dev, void *buf); #define PTYPE_STRING 0 #define PTYPE_INTDEC 1 #define PTYPE_INTHEX 2 #define PTYPE_STR_HEX 3 static int <API key>( char **str_ptr, const char *token, int param_type, void *dst, int param_max_len); static int hex2num(char c) { if (c >= '0' && c <= '9') return c - '0'; if (c >= 'a' && c <= 'f') return c - 'a' + 10; if (c >= 'A' && c <= 'F') return c - 'A' + 10; return -1; } static int hstr_2_buf(const char *txt, u8 *buf, int len) { int i; for (i = 0; i < len; i++) { int a, b; a = hex2num(*txt++); if (a < 0) return -1; b = hex2num(*txt++); if (b < 0) return -1; *buf++ = (a << 4) | b; } return 0; } static int <API key>(char *param_str, struct ap_profile *ap_cfg) { char *str_ptr = param_str; char sub_cmd[16]; int ret = 0; memset(sub_cmd, 0, sizeof(sub_cmd)); memset(ap_cfg, 0, sizeof(struct ap_profile)); if (<API key>(&str_ptr, "ASCII_CMD=", PTYPE_STRING, sub_cmd, SSID_LEN) != 0) { return -1; } if (strncmp(sub_cmd, "AP_CFG", 6)) { WL_ERROR(("ERROR: sub_cmd:%s != 'AP_CFG'!\n", sub_cmd)); return -1; } ret = <API key>(&str_ptr, "SSID=", PTYPE_STRING, ap_cfg->ssid, SSID_LEN); ret |= <API key>(&str_ptr, "SEC=", PTYPE_STRING, ap_cfg->sec, SEC_LEN); ret |= <API key>(&str_ptr, "KEY=", PTYPE_STRING, ap_cfg->key, KEY_LEN); ret |= <API key>(&str_ptr, "CHANNEL=", PTYPE_INTDEC, &ap_cfg->channel, 5); <API key>(&str_ptr, "PREAMBLE=", PTYPE_INTDEC, &ap_cfg->preamble, 5); <API key>(&str_ptr, "MAX_SCB=", PTYPE_INTDEC, &ap_cfg->max_scb, 5); <API key>(&str_ptr, "HIDDEN=", PTYPE_INTDEC, &ap_cfg->closednet, 5); <API key>(&str_ptr, "COUNTRY=", PTYPE_STRING, &ap_cfg->country_code, 3); return ret; } #endif #ifdef SOFTAP static int <API key>(struct net_device *dev, struct iw_request_info *info, union iwreq_data *wrqu, char *ext) { int res = 0; char *extra = NULL; struct ap_profile *ap_cfg = &my_ap; WL_TRACE(("> Got IWPRIV SET_AP IOCTL: info->cmd:%x, info->flags:%x, u.data:%p, u.len:%d\n", info->cmd, info->flags, wrqu->data.pointer, wrqu->data.length)); if (!ap_fw_loaded) { WL_ERROR(("Can't execute %s(), SOFTAP fw is not Loaded\n", __FUNCTION__)); return -1; } if (wrqu->data.length != 0) { char *str_ptr; if (!(extra = kmalloc(wrqu->data.length+1, GFP_KERNEL))) return -ENOMEM; if (copy_from_user(extra, wrqu->data.pointer, wrqu->data.length)) { kfree(extra); return -EFAULT; } extra[wrqu->data.length] = 0; WL_SOFTAP((" Got str param in iw_point:\n %s\n", extra)); memset(ap_cfg, 0, sizeof(struct ap_profile)); str_ptr = extra; if ((res = <API key>(extra, ap_cfg)) < 0) { WL_ERROR(("%s failed to parse %d\n", __FUNCTION__, res)); kfree(extra); return -1; } } else { WL_ERROR(("IWPRIV argument len = 0 \n")); return -1; } if ((res = set_ap_cfg(dev, ap_cfg)) < 0) WL_ERROR(("%s failed to set_ap_cfg %d\n", __FUNCTION__, res)); kfree(extra); return res; } #endif #ifdef SOFTAP static int <API key>(struct net_device *dev, struct iw_request_info *info, union iwreq_data *p_iwrq, char *extra) { int i, ret = 0; char mac_buf[256]; struct maclist *sta_maclist = (struct maclist *)mac_buf; char mac_lst[384]; char *p_mac_str; char *p_mac_str_end; wl_iw_t *iw; if ((!dev) || (!extra)) { return -EINVAL; } iw = *(wl_iw_t **)netdev_priv(dev); net_os_wake_lock(dev); DHD_OS_MUTEX_LOCK(&wl_softap_lock); WL_TRACE(("\n %s: IWPRIV IOCTL: cmd:%hx, flags:%hx, extra:%p, iwp.len:%d," "iwp.len:%p, iwp.flags:%x \n", __FUNCTION__, info->cmd, info->flags, extra, p_iwrq->data.length, p_iwrq->data.pointer, p_iwrq->data.flags)); memset(sta_maclist, 0, sizeof(mac_buf)); sta_maclist->count = 8; WL_SOFTAP(("%s: net device:%s, buf_sz:%d\n", __FUNCTION__, dev->name, sizeof(mac_buf))); if ((ret = get_assoc_sta_list(dev, mac_buf, sizeof(mac_buf))) < 0) { WL_ERROR(("%s: sta list ioctl error:%d\n", __FUNCTION__, ret)); goto func_exit; } WL_SOFTAP(("%s: got %d stations\n", __FUNCTION__, sta_maclist->count)); memset(mac_lst, 0, sizeof(mac_lst)); p_mac_str = mac_lst; p_mac_str_end = &mac_lst[sizeof(mac_lst)-1]; for (i = 0; i < 8; i++) { struct ether_addr * id = &sta_maclist->ea[i]; if (!ETHER_ISNULLADDR(id->octet)) { scb_val_t scb_val; int rssi = 0; bzero(&scb_val, sizeof(scb_val_t)); if ((p_mac_str_end - p_mac_str) <= 36) { WL_ERROR(("%s: mac list buf is < 36 for item[%i] item\n", __FUNCTION__, i)); break; } p_mac_str += snprintf(p_mac_str, MAX_WX_STRING, "\nMac[%d]=%02X:%02X:%02X:%02X:%02X:%02X,", i, id->octet[0], id->octet[1], id->octet[2], id->octet[3], id->octet[4], id->octet[5]); bcopy(id->octet, &scb_val.ea, 6); ret = dev_wlc_ioctl(dev, WLC_GET_RSSI, &scb_val, sizeof(scb_val_t)); if (ret < 0) { snprintf(p_mac_str, MAX_WX_STRING, "RSSI:ERR"); WL_ERROR(("%s: RSSI ioctl error:%d\n", __FUNCTION__, ret)); break; } rssi = dtoh32(scb_val.val); p_mac_str += snprintf(p_mac_str, MAX_WX_STRING, "RSSI:%d", rssi); } } p_iwrq->data.length = strlen(mac_lst)+1; WL_SOFTAP(("%s: data to user:\n%s\n usr_ptr:%p\n", __FUNCTION__, mac_lst, p_iwrq->data.pointer)); if (p_iwrq->data.length) { bcopy(mac_lst, extra, p_iwrq->data.length); } func_exit: DHD_OS_MUTEX_UNLOCK(&wl_softap_lock); net_os_wake_unlock(dev); WL_SOFTAP(("%s: Exited\n", __FUNCTION__)); return ret; } #endif #ifdef SOFTAP #define MAC_FILT_MAX 8 static int <API key>(struct net_device *dev, struct iw_request_info *info, union iwreq_data *wrqu, char *ext) { int i, ret = -1; char * extra = NULL; int mac_cnt = 0; int mac_mode = 0; struct ether_addr *p_ea; struct mac_list_set mflist_set; WL_SOFTAP((">>> Got IWPRIV SET_MAC_FILTER IOCTL: info->cmd:%x," "info->flags:%x, u.data:%p, u.len:%d\n", info->cmd, info->flags, wrqu->data.pointer, wrqu->data.length)); if (wrqu->data.length != 0) { char *str_ptr; if (!(extra = kmalloc(wrqu->data.length+1, GFP_KERNEL))) return -ENOMEM; if (copy_from_user(extra, wrqu->data.pointer, wrqu->data.length)) { kfree(extra); return -EFAULT; } extra[wrqu->data.length] = 0; WL_SOFTAP((" Got parameter string in iw_point:\n %s \n", extra)); memset(&mflist_set, 0, sizeof(mflist_set)); str_ptr = extra; if (<API key>(&str_ptr, "MAC_MODE=", PTYPE_INTDEC, &mac_mode, 4) != 0) { WL_ERROR(("ERROR: 'MAC_MODE=' token is missing\n")); goto exit_proc; } p_ea = &mflist_set.mac_list.ea[0]; if (<API key>(&str_ptr, "MAC_CNT=", PTYPE_INTDEC, &mac_cnt, 4) != 0) { WL_ERROR(("ERROR: 'MAC_CNT=' token param is missing \n")); goto exit_proc; } if (mac_cnt > MAC_FILT_MAX) { WL_ERROR(("ERROR: number of MAC filters > MAX\n")); goto exit_proc; } for (i=0; i< mac_cnt; i++) if (<API key>(&str_ptr, "MAC=", PTYPE_STR_HEX, &p_ea[i], 12) != 0) { WL_ERROR(("ERROR: MAC_filter[%d] is missing !\n", i)); goto exit_proc; } WL_SOFTAP(("MAC_MODE=:%d, MAC_CNT=%d, MACs:..\n", mac_mode, mac_cnt)); for (i = 0; i < mac_cnt; i++) { WL_SOFTAP(("mac_filt[%d]:", i)); dhd_print_buf(&p_ea[i], 6, 0); } mflist_set.mode = mac_mode; mflist_set.mac_list.count = mac_cnt; set_ap_mac_list(dev, &mflist_set); wrqu->data.pointer = NULL; wrqu->data.length = 0; ret = 0; } else { WL_ERROR(("IWPRIV argument len is 0\n")); return -1; } exit_proc: kfree(extra); return ret; } #endif #ifdef SOFTAP static int <API key>(struct net_device *dev, struct iw_request_info *info, union iwreq_data *wrqu, char *ext) { int res = 0; char sta_mac[6] = {0, 0, 0, 0, 0, 0}; char cmd_buf[256]; char *str_ptr = cmd_buf; WL_SOFTAP((">>%s called\n args: info->cmd:%x," " info->flags:%x, u.data.p:%p, u.data.len:%d\n", __FUNCTION__, info->cmd, info->flags, wrqu->data.pointer, wrqu->data.length)); if (wrqu->data.length != 0) { if (copy_from_user(cmd_buf, wrqu->data.pointer, wrqu->data.length)) { return -EFAULT; } if (<API key>(&str_ptr, "MAC=", PTYPE_STR_HEX, sta_mac, 12) == 0) { res = <API key>(dev, sta_mac); } else { WL_ERROR(("ERROR: STA_MAC= token not found\n")); } } return res; } #endif #endif #if WIRELESS_EXT < 13 struct iw_request_info { __u16 cmd; __u16 flags; }; typedef int (*iw_handler)(struct net_device *dev, struct iw_request_info *info, void *wrqu, char *extra); #endif static int wl_iw_config_commit( struct net_device *dev, struct iw_request_info *info, void *zwrq, char *extra ) { wlc_ssid_t ssid; int error; struct sockaddr bssid; WL_TRACE(("%s: SIOCSIWCOMMIT\n", dev->name)); if ((error = dev_wlc_ioctl(dev, WLC_GET_SSID, &ssid, sizeof(ssid)))) return error; ssid.SSID_len = dtoh32(ssid.SSID_len); if (!ssid.SSID_len) return 0; bzero(&bssid, sizeof(struct sockaddr)); if ((error = dev_wlc_ioctl(dev, WLC_REASSOC, &bssid, ETHER_ADDR_LEN))) { WL_ERROR(("%s: WLC_REASSOC to %s failed \n", __FUNCTION__, ssid.SSID)); return error; } return 0; } static int wl_iw_get_name( struct net_device *dev, struct iw_request_info *info, char *cwrq, char *extra ) { WL_TRACE(("%s: SIOCGIWNAME\n", dev->name)); strcpy(cwrq, "IEEE 802.11-DS"); return 0; } static int wl_iw_set_freq( struct net_device *dev, struct iw_request_info *info, struct iw_freq *fwrq, char *extra ) { int error, chan; uint sf = 0; WL_TRACE(("%s %s: SIOCSIWFREQ\n", __FUNCTION__, dev->name)); #if defined(SOFTAP) if (ap_cfg_running) { WL_TRACE(("%s:>> not executed, 'SOFT_AP is active' \n", __FUNCTION__)); return 0; } #endif if (fwrq->e == 0 && fwrq->m < MAXCHANNEL) { chan = fwrq->m; } else { if (fwrq->e >= 6) { fwrq->e -= 6; while (fwrq->e fwrq->m *= 10; } else if (fwrq->e < 6) { while (fwrq->e++ < 6) fwrq->m /= 10; } if (fwrq->m > 4000 && fwrq->m < 5000) sf = WF_CHAN_FACTOR_4_G; chan = wf_mhz2channel(fwrq->m, sf); } chan = htod32(chan); if ((error = dev_wlc_ioctl(dev, WLC_SET_CHANNEL, &chan, sizeof(chan)))) return error; g_wl_iw_params.target_channel = chan; return -EINPROGRESS; } static int wl_iw_get_freq( struct net_device *dev, struct iw_request_info *info, struct iw_freq *fwrq, char *extra ) { channel_info_t ci; int error; WL_TRACE(("%s: SIOCGIWFREQ\n", dev->name)); if ((error = dev_wlc_ioctl(dev, WLC_GET_CHANNEL, &ci, sizeof(ci)))) return error; fwrq->m = dtoh32(ci.hw_channel); fwrq->e = dtoh32(0); return 0; } static int wl_iw_set_mode( struct net_device *dev, struct iw_request_info *info, __u32 *uwrq, char *extra ) { int infra = 0, ap = 0, error = 0; WL_TRACE(("%s: SIOCSIWMODE\n", dev->name)); switch (*uwrq) { case IW_MODE_MASTER: infra = ap = 1; break; case IW_MODE_ADHOC: case IW_MODE_AUTO: break; case IW_MODE_INFRA: infra = 1; break; default: return -EINVAL; } infra = htod32(infra); ap = htod32(ap); if ((error = dev_wlc_ioctl(dev, WLC_SET_INFRA, &infra, sizeof(infra))) || (error = dev_wlc_ioctl(dev, WLC_SET_AP, &ap, sizeof(ap)))) return error; return -EINPROGRESS; } static int wl_iw_get_mode( struct net_device *dev, struct iw_request_info *info, __u32 *uwrq, char *extra ) { int error, infra = 0, ap = 0; WL_TRACE(("%s: SIOCGIWMODE\n", dev->name)); if ((error = dev_wlc_ioctl(dev, WLC_GET_INFRA, &infra, sizeof(infra))) || (error = dev_wlc_ioctl(dev, WLC_GET_AP, &ap, sizeof(ap)))) return error; infra = dtoh32(infra); ap = dtoh32(ap); *uwrq = infra ? ap ? IW_MODE_MASTER : IW_MODE_INFRA : IW_MODE_ADHOC; return 0; } static int wl_iw_get_range( struct net_device *dev, struct iw_request_info *info, struct iw_point *dwrq, char *extra ) { struct iw_range *range = (struct iw_range *) extra; wl_uint32_list_t *list; wl_rateset_t rateset; int8 *channels; int error, i, k; uint sf, ch; int phytype; int bw_cap = 0, sgi_tx = 0, nmode = 0; channel_info_t ci; uint8 nrate_list2copy = 0; uint16 nrate_list[4][8] = { {13, 26, 39, 52, 78, 104, 117, 130}, {14, 29, 43, 58, 87, 116, 130, 144}, {27, 54, 81, 108, 162, 216, 243, 270}, {30, 60, 90, 120, 180, 240, 270, 300}}; WL_TRACE(("%s: SIOCGIWRANGE\n", dev->name)); if (!extra) return -EINVAL; channels = kmalloc((MAXCHANNEL+1)*4, GFP_KERNEL); if (!channels) { WL_ERROR(("Could not alloc channels\n")); return -ENOMEM; } list = (wl_uint32_list_t *)channels; dwrq->length = sizeof(struct iw_range); memset(range, 0, sizeof(*range)); range->min_nwid = range->max_nwid = 0; list->count = htod32(MAXCHANNEL); if ((error = dev_wlc_ioctl(dev, <API key>, channels, (MAXCHANNEL+1)*4))) { kfree(channels); return error; } for (i = 0; i < dtoh32(list->count) && i < IW_MAX_FREQUENCIES; i++) { range->freq[i].i = dtoh32(list->element[i]); ch = dtoh32(list->element[i]); if (ch <= CH_MAX_2G_CHANNEL) sf = <API key>; else sf = WF_CHAN_FACTOR_5_G; range->freq[i].m = wf_channel2mhz(ch, sf); range->freq[i].e = 6; } range->num_frequency = range->num_channels = i; range->max_qual.qual = 5; range->max_qual.level = 0x100 - 200; range->max_qual.noise = 0x100 - 200; range->sensitivity = 65535; #if WIRELESS_EXT > 11 range->avg_qual.qual = 3; range->avg_qual.level = 0x100 + WL_IW_RSSI_GOOD; range->avg_qual.noise = 0x100 - 75; #endif if ((error = dev_wlc_ioctl(dev, <API key>, &rateset, sizeof(rateset)))) { kfree(channels); return error; } rateset.count = dtoh32(rateset.count); range->num_bitrates = rateset.count; for (i = 0; i < rateset.count && i < IW_MAX_BITRATES; i++) range->bitrate[i] = (rateset.rates[i]& 0x7f) * 500000; dev_wlc_intvar_get(dev, "nmode", &nmode); dev_wlc_ioctl(dev, WLC_GET_PHYTYPE, &phytype, sizeof(phytype)); if (nmode == 1 && phytype == WLC_PHY_TYPE_SSN) { dev_wlc_intvar_get(dev, "mimo_bw_cap", &bw_cap); dev_wlc_intvar_get(dev, "sgi_tx", &sgi_tx); dev_wlc_ioctl(dev, WLC_GET_CHANNEL, &ci, sizeof(channel_info_t)); ci.hw_channel = dtoh32(ci.hw_channel); if (bw_cap == 0 || (bw_cap == 2 && ci.hw_channel <= 14)) { if (sgi_tx == 0) nrate_list2copy = 0; else nrate_list2copy = 1; } if (bw_cap == 1 || (bw_cap == 2 && ci.hw_channel >= 36)) { if (sgi_tx == 0) nrate_list2copy = 2; else nrate_list2copy = 3; } range->num_bitrates += 8; for (k = 0; i < range->num_bitrates; k++, i++) { range->bitrate[i] = (nrate_list[nrate_list2copy][k]) * 500000; } } if ((error = dev_wlc_ioctl(dev, WLC_GET_PHYTYPE, &i, sizeof(i)))) { kfree(channels); return error; } i = dtoh32(i); if (i == WLC_PHY_TYPE_A) range->throughput = 24000000; else range->throughput = 1500000; range->min_rts = 0; range->max_rts = 2347; range->min_frag = 256; range->max_frag = 2346; range->max_encoding_tokens = <API key>; range->num_encoding_sizes = 4; range->encoding_size[0] = WEP1_KEY_SIZE; range->encoding_size[1] = WEP128_KEY_SIZE; #if WIRELESS_EXT > 17 range->encoding_size[2] = TKIP_KEY_SIZE; #else range->encoding_size[2] = 0; #endif range->encoding_size[3] = AES_KEY_SIZE; range->min_pmp = 0; range->max_pmp = 0; range->min_pmt = 0; range->max_pmt = 0; range->pmp_flags = 0; range->pm_capa = 0; range->num_txpower = 2; range->txpower[0] = 1; range->txpower[1] = 255; range->txpower_capa = IW_TXPOW_MWATT; #if WIRELESS_EXT > 10 range->we_version_compiled = WIRELESS_EXT; range->we_version_source = 19; range->retry_capa = IW_RETRY_LIMIT; range->retry_flags = IW_RETRY_LIMIT; range->r_time_flags = 0; range->min_retry = 1; range->max_retry = 255; range->min_r_time = 0; range->max_r_time = 0; #endif #if WIRELESS_EXT > 17 range->enc_capa = IW_ENC_CAPA_WPA; range->enc_capa |= <API key>; range->enc_capa |= <API key>; range->enc_capa |= IW_ENC_CAPA_WPA2; <API key>(range->event_capa); IW_EVENT_CAPA_SET(range->event_capa, SIOCGIWAP); IW_EVENT_CAPA_SET(range->event_capa, SIOCGIWSCAN); IW_EVENT_CAPA_SET(range->event_capa, IWEVTXDROP); IW_EVENT_CAPA_SET(range->event_capa, <API key>); IW_EVENT_CAPA_SET(range->event_capa, IWEVASSOCREQIE); IW_EVENT_CAPA_SET(range->event_capa, IWEVASSOCRESPIE); IW_EVENT_CAPA_SET(range->event_capa, IWEVPMKIDCAND); #endif kfree(channels); return 0; } static int rssi_to_qual(int rssi) { if (rssi <= <API key>) return 0; else if (rssi <= WL_IW_RSSI_VERY_LOW) return 1; else if (rssi <= WL_IW_RSSI_LOW) return 2; else if (rssi <= WL_IW_RSSI_GOOD) return 3; else if (rssi <= <API key>) return 4; else return 5; } static int wl_iw_set_spy( struct net_device *dev, struct iw_request_info *info, struct iw_point *dwrq, char *extra ) { wl_iw_t *iw = NETDEV_PRIV(dev); struct sockaddr *addr = (struct sockaddr *) extra; int i; WL_TRACE(("%s: SIOCSIWSPY\n", dev->name)); if (!extra) return -EINVAL; iw->spy_num = MIN(ARRAYSIZE(iw->spy_addr), dwrq->length); for (i = 0; i < iw->spy_num; i++) memcpy(&iw->spy_addr[i], addr[i].sa_data, ETHER_ADDR_LEN); memset(iw->spy_qual, 0, sizeof(iw->spy_qual)); return 0; } static int wl_iw_get_spy( struct net_device *dev, struct iw_request_info *info, struct iw_point *dwrq, char *extra ) { wl_iw_t *iw = NETDEV_PRIV(dev); struct sockaddr *addr = (struct sockaddr *) extra; struct iw_quality *qual = (struct iw_quality *) &addr[iw->spy_num]; int i; WL_TRACE(("%s: SIOCGIWSPY\n", dev->name)); if (!extra) return -EINVAL; dwrq->length = iw->spy_num; for (i = 0; i < iw->spy_num; i++) { memcpy(addr[i].sa_data, &iw->spy_addr[i], ETHER_ADDR_LEN); addr[i].sa_family = AF_UNIX; memcpy(&qual[i], &iw->spy_qual[i], sizeof(struct iw_quality)); iw->spy_qual[i].updated = 0; } return 0; } static int <API key>(int ch, wl_join_params_t *join_params, int *join_params_size) { chanspec_t chanspec = 0; if (ch != 0) { join_params->params.chanspec_num = 1; join_params->params.chanspec_list[0] = ch; if (join_params->params.chanspec_list[0]) chanspec |= WL_CHANSPEC_BAND_2G; else chanspec |= WL_CHANSPEC_BAND_5G; chanspec |= WL_CHANSPEC_BW_20; chanspec |= <API key>; *join_params_size += <API key> + join_params->params.chanspec_num * sizeof(chanspec_t); join_params->params.chanspec_list[0] &= <API key>; join_params->params.chanspec_list[0] |= chanspec; join_params->params.chanspec_list[0] = htodchanspec(join_params->params.chanspec_list[0]); join_params->params.chanspec_num = htod32(join_params->params.chanspec_num); WL_TRACE(("%s join_params->params.chanspec_list[0]= %X\n", __FUNCTION__, join_params->params.chanspec_list[0])); } return 1; } static int wl_iw_set_wap( struct net_device *dev, struct iw_request_info *info, struct sockaddr *awrq, char *extra ) { int error = -EINVAL; wl_join_params_t join_params; int join_params_size; WL_TRACE(("%s: SIOCSIWAP\n", dev->name)); if (awrq->sa_family != ARPHRD_ETHER) { WL_ERROR(("Invalid Header...sa_family\n")); return -EINVAL; } if (ETHER_ISBCAST(awrq->sa_data) || ETHER_ISNULLADDR(awrq->sa_data)) { scb_val_t scbval; bzero(&scbval, sizeof(scb_val_t)); (void) dev_wlc_ioctl(dev, WLC_DISASSOC, &scbval, sizeof(scb_val_t)); return 0; } memset(&join_params, 0, sizeof(join_params)); join_params_size = sizeof(join_params.ssid); memcpy(join_params.ssid.SSID, g_ssid.SSID, g_ssid.SSID_len); join_params.ssid.SSID_len = htod32(g_ssid.SSID_len); memcpy(&join_params.params.bssid, awrq->sa_data, ETHER_ADDR_LEN); WL_TRACE(("%s target_channel=%d\n", __FUNCTION__, g_wl_iw_params.target_channel)); <API key>(g_wl_iw_params.target_channel, &join_params, &join_params_size); if ((error = dev_wlc_ioctl(dev, WLC_SET_SSID, &join_params, join_params_size))) { WL_ERROR(("%s Invalid ioctl data=%d\n", __FUNCTION__, error)); return error; } if (g_ssid.SSID_len) { WL_TRACE(("%s: join SSID=%s BSSID="MACSTR" ch=%d\n", __FUNCTION__, g_ssid.SSID, MAC2STR((u8 *)awrq->sa_data), g_wl_iw_params.target_channel)); } memset(&g_ssid, 0, sizeof(g_ssid)); return 0; } static int wl_iw_get_wap( struct net_device *dev, struct iw_request_info *info, struct sockaddr *awrq, char *extra ) { WL_TRACE(("%s: SIOCGIWAP\n", dev->name)); awrq->sa_family = ARPHRD_ETHER; memset(awrq->sa_data, 0, ETHER_ADDR_LEN); (void) dev_wlc_ioctl(dev, WLC_GET_BSSID, awrq->sa_data, ETHER_ADDR_LEN); return 0; } #if WIRELESS_EXT > 17 static int wl_iw_mlme( struct net_device *dev, struct iw_request_info *info, struct sockaddr *awrq, char *extra ) { struct iw_mlme *mlme; scb_val_t scbval; int error = -EINVAL; WL_TRACE(("%s: SIOCSIWMLME DISASSOC/DEAUTH\n", dev->name)); mlme = (struct iw_mlme *)extra; if (mlme == NULL) { WL_ERROR(("Invalid ioctl data.\n")); return error; } scbval.val = mlme->reason_code; bcopy(&mlme->addr.sa_data, &scbval.ea, ETHER_ADDR_LEN); if (mlme->cmd == IW_MLME_DISASSOC) { scbval.val = htod32(scbval.val); error = dev_wlc_ioctl(dev, WLC_DISASSOC, &scbval, sizeof(scb_val_t)); } else if (mlme->cmd == IW_MLME_DEAUTH) { scbval.val = htod32(scbval.val); error = dev_wlc_ioctl(dev, WLC_SCB_DE<API key>, &scbval, sizeof(scb_val_t)); } else { WL_ERROR(("Invalid ioctl data.\n")); return error; } return error; } #endif #ifndef WL_IW_USE_ISCAN static int wl_iw_get_aplist( struct net_device *dev, struct iw_request_info *info, struct iw_point *dwrq, char *extra ) { wl_scan_results_t *list; struct sockaddr *addr = (struct sockaddr *) extra; struct iw_quality qual[IW_MAX_AP]; wl_bss_info_t *bi = NULL; int error, i; uint buflen = dwrq->length; WL_TRACE(("%s: SIOCGIWAPLIST\n", dev->name)); if (!extra) return -EINVAL; list = kmalloc(buflen, GFP_KERNEL); if (!list) return -ENOMEM; memset(list, 0, buflen); list->buflen = htod32(buflen); if ((error = dev_wlc_ioctl(dev, WLC_SCAN_RESULTS, list, buflen))) { WL_ERROR(("%d: Scan results error %d\n", __LINE__, error)); kfree(list); return error; } list->buflen = dtoh32(list->buflen); list->version = dtoh32(list->version); list->count = dtoh32(list->count); if (list->version != WL_BSS_INFO_VERSION) { WL_ERROR(("%s : list->version %d != WL_BSS_INFO_VERSION\n", __FUNCTION__, list->version)); kfree(list); return -EINVAL; } for (i = 0, dwrq->length = 0; i < list->count && dwrq->length < IW_MAX_AP; i++) { bi = bi ? (wl_bss_info_t *)((uintptr)bi + dtoh32(bi->length)) : list->bss_info; ASSERT(((uintptr)bi + dtoh32(bi->length)) <= ((uintptr)list + buflen)); if (!(dtoh16(bi->capability) & DOT11_CAP_ESS)) continue; memcpy(addr[dwrq->length].sa_data, &bi->BSSID, ETHER_ADDR_LEN); addr[dwrq->length].sa_family = ARPHRD_ETHER; qual[dwrq->length].qual = rssi_to_qual(dtoh16(bi->RSSI)); qual[dwrq->length].level = 0x100 + dtoh16(bi->RSSI); qual[dwrq->length].noise = 0x100 + bi->phy_noise; #if WIRELESS_EXT > 18 qual[dwrq->length].updated = IW_QUAL_ALL_UPDATED | IW_QUAL_DBM; #else qual[dwrq->length].updated = 7; #endif dwrq->length++; } kfree(list); if (dwrq->length) { memcpy(&addr[dwrq->length], qual, sizeof(struct iw_quality) * dwrq->length); dwrq->flags = 1; } return 0; } #endif #ifdef WL_IW_USE_ISCAN static int <API key>( struct net_device *dev, struct iw_request_info *info, struct iw_point *dwrq, char *extra ) { wl_scan_results_t *list; iscan_buf_t * buf; iscan_info_t *iscan = g_iscan; struct sockaddr *addr = (struct sockaddr *) extra; struct iw_quality qual[IW_MAX_AP]; wl_bss_info_t *bi = NULL; int i; WL_TRACE(("%s: SIOCGIWAPLIST\n", dev->name)); if (!extra) return -EINVAL; if ((!iscan) || (iscan->tsk_ctl.thr_pid < 0)) { WL_ERROR(("%s error\n", __FUNCTION__)); return 0; } buf = iscan->list_hdr; while (buf) { list = &((wl_iscan_results_t*)buf->iscan_buf)->results; if (list->version != WL_BSS_INFO_VERSION) { WL_ERROR(("%s : list->version %d != WL_BSS_INFO_VERSION\n", __FUNCTION__, list->version)); return -EINVAL; } bi = NULL; for (i = 0, dwrq->length = 0; i < list->count && dwrq->length < IW_MAX_AP; i++) { bi = bi ? (wl_bss_info_t *)((uintptr)bi + dtoh32(bi->length)) : list->bss_info; ASSERT(((uintptr)bi + dtoh32(bi->length)) <= ((uintptr)list + WLC_IW_ISCAN_MAXLEN)); if (!(dtoh16(bi->capability) & DOT11_CAP_ESS)) continue; memcpy(addr[dwrq->length].sa_data, &bi->BSSID, ETHER_ADDR_LEN); addr[dwrq->length].sa_family = ARPHRD_ETHER; qual[dwrq->length].qual = rssi_to_qual(dtoh16(bi->RSSI)); qual[dwrq->length].level = 0x100 + dtoh16(bi->RSSI); qual[dwrq->length].noise = 0x100 + bi->phy_noise; #if WIRELESS_EXT > 18 qual[dwrq->length].updated = IW_QUAL_ALL_UPDATED | IW_QUAL_DBM; #else qual[dwrq->length].updated = 7; #endif dwrq->length++; } buf = buf->next; } if (dwrq->length) { memcpy(&addr[dwrq->length], qual, sizeof(struct iw_quality) * dwrq->length); dwrq->flags = 1; } return 0; } static int wl_iw_iscan_prep(wl_scan_params_t *params, wlc_ssid_t *ssid) { int err = 0; memcpy(&params->bssid, &ether_bcast, ETHER_ADDR_LEN); params->bss_type = DOT11_BSSTYPE_ANY; params->scan_type = 0; params->nprobes = -1; params->active_time = -1; params->passive_time = -1; params->home_time = -1; params->channel_num = 0; #if defined(CONFIG_FIRST_SCAN) if (<API key> == <API key>) params->passive_time = 30; #endif params->nprobes = htod32(params->nprobes); params->active_time = htod32(params->active_time); params->passive_time = htod32(params->passive_time); params->home_time = htod32(params->home_time); if (ssid && ssid->SSID_len) memcpy(&params->ssid, ssid, sizeof(wlc_ssid_t)); return err; } static int wl_iw_iscan(iscan_info_t *iscan, wlc_ssid_t *ssid, uint16 action) { int err = 0; iscan->iscan_ex_params_p->version = htod32(ISCAN_REQ_VERSION); iscan->iscan_ex_params_p->action = htod16(action); iscan->iscan_ex_params_p->scan_duration = htod16(0); WL_SCAN(("%s : nprobes=%d\n", __FUNCTION__, iscan->iscan_ex_params_p->params.nprobes)); WL_SCAN(("active_time=%d\n", iscan->iscan_ex_params_p->params.active_time)); WL_SCAN(("passive_time=%d\n", iscan->iscan_ex_params_p->params.passive_time)); WL_SCAN(("home_time=%d\n", iscan->iscan_ex_params_p->params.home_time)); WL_SCAN(("scan_type=%d\n", iscan->iscan_ex_params_p->params.scan_type)); WL_SCAN(("bss_type=%d\n", iscan->iscan_ex_params_p->params.bss_type)); if ((dev_iw_iovar_setbuf(iscan->dev, "iscan", iscan->iscan_ex_params_p, iscan->iscan_ex_param_size, iscan->ioctlbuf, sizeof(iscan->ioctlbuf)))) { WL_ERROR(("Set ISCAN for %s failed with %d\n", __FUNCTION__, err)); err = -1; } return err; } static void wl_iw_timerfunc(ulong data) { iscan_info_t *iscan = (iscan_info_t *)data; if (iscan) { iscan->timer_on = 0; if (iscan->iscan_state != ISCAN_STATE_IDLE) { WL_TRACE(("timer trigger\n")); up(&iscan->tsk_ctl.sema); } } } static void <API key>(struct net_device *dev) { char eventmask[<API key>]; char iovbuf[<API key> + 12]; dev_iw_iovar_getbuf(dev, "event_msgs", "", 0, iovbuf, sizeof(iovbuf)); bcopy(iovbuf, eventmask, <API key>); setbit(eventmask, WLC_E_SCAN_COMPLETE); dev_iw_iovar_setbuf(dev, "event_msgs", eventmask, <API key>, iovbuf, sizeof(iovbuf)); } static uint32 wl_iw_iscan_get(iscan_info_t *iscan) { iscan_buf_t * buf; iscan_buf_t * ptr; wl_iscan_results_t * list_buf; wl_iscan_results_t list; wl_scan_results_t *results; uint32 status; int res = 0; DHD_OS_MUTEX_LOCK(&wl_cache_lock); if (iscan->list_cur) { buf = iscan->list_cur; iscan->list_cur = buf->next; } else { buf = kmalloc(sizeof(iscan_buf_t), GFP_KERNEL); if (!buf) { WL_ERROR(("%s can't alloc iscan_buf_t : going to abort currect iscan\n", __FUNCTION__)); DHD_OS_MUTEX_UNLOCK(&wl_cache_lock); return <API key>; } buf->next = NULL; if (!iscan->list_hdr) iscan->list_hdr = buf; else { ptr = iscan->list_hdr; while (ptr->next) { ptr = ptr->next; } ptr->next = buf; } } memset(buf->iscan_buf, 0, WLC_IW_ISCAN_MAXLEN); list_buf = (wl_iscan_results_t*)buf->iscan_buf; results = &list_buf->results; results->buflen = <API key>; results->version = 0; results->count = 0; memset(&list, 0, sizeof(list)); list.results.buflen = htod32(WLC_IW_ISCAN_MAXLEN); res = dev_iw_iovar_getbuf( iscan->dev, "iscanresults", &list, <API key>, buf->iscan_buf, WLC_IW_ISCAN_MAXLEN); if (res == 0) { results->buflen = dtoh32(results->buflen); results->version = dtoh32(results->version); results->count = dtoh32(results->count); WL_TRACE(("results->count = %d\n", results->count)); WL_TRACE(("results->buflen = %d\n", results->buflen)); status = dtoh32(list_buf->status); } else { WL_ERROR(("%s returns error %d\n", __FUNCTION__, res)); status = <API key>; } DHD_OS_MUTEX_UNLOCK(&wl_cache_lock); return status; } static void <API key>(iscan_info_t *iscan) { WL_TRACE(("%s force Specific SCAN for %s\n", __FUNCTION__, g_specific_ssid.SSID)); #if (LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 27)) rtnl_lock(); #endif (void) dev_wlc_ioctl(iscan->dev, WLC_SCAN, &g_specific_ssid, sizeof(g_specific_ssid)); #if (LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 27)) rtnl_unlock(); #endif } static void <API key>(iscan_info_t *iscan) { union iwreq_data wrqu; memset(&wrqu, 0, sizeof(wrqu)); wireless_send_event(iscan->dev, SIOCGIWSCAN, &wrqu, NULL); #if defined(CONFIG_FIRST_SCAN) if (<API key> == <API key>) <API key> = <API key>; #endif WL_TRACE(("Send Event ISCAN complete\n")); } static int <API key>(void *data) { uint32 status; tsk_ctl_t *tsk_ctl = (tsk_ctl_t *)data; iscan_info_t *iscan = (iscan_info_t *) tsk_ctl->parent; static bool iscan_pass_abort = FALSE; DAEMONIZE("iscan_sysioc"); status = <API key>; complete(&tsk_ctl->completed); while (down_interruptible(&tsk_ctl->sema) == 0) { <API key>(); if (tsk_ctl->terminated) { break; } #if defined(SOFTAP) if (ap_cfg_running) { WL_TRACE(("%s skipping SCAN ops in AP mode !!!\n", __FUNCTION__)); net_os_wake_unlock(iscan->dev); continue; } #endif if (iscan->timer_on) { iscan->timer_on = 0; del_timer_sync(&iscan->timer); } #if (LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 27)) rtnl_lock(); #endif status = wl_iw_iscan_get(iscan); #if (LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 27)) rtnl_unlock(); #endif if (<API key> && (iscan_pass_abort == TRUE)) { WL_TRACE(("%s Get results from specific scan status=%d\n", __FUNCTION__, status)); <API key>(iscan); iscan_pass_abort = FALSE; status = -1; } switch (status) { case <API key>: WL_TRACE(("iscanresults incomplete\n")); #if (LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 27)) rtnl_lock(); #endif wl_iw_iscan(iscan, NULL, <API key>); #if (LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 27)) rtnl_unlock(); #endif mod_timer(&iscan->timer, jiffies + msecs_to_jiffies(iscan->timer_ms)); iscan->timer_on = 1; break; case <API key>: WL_TRACE(("iscanresults complete\n")); iscan->iscan_state = ISCAN_STATE_IDLE; <API key>(iscan); break; case <API key>: WL_TRACE(("iscanresults pending\n")); mod_timer(&iscan->timer, jiffies + msecs_to_jiffies(iscan->timer_ms)); iscan->timer_on = 1; break; case <API key>: WL_TRACE(("iscanresults aborted\n")); iscan->iscan_state = ISCAN_STATE_IDLE; if (<API key> == 0) <API key>(iscan); else { iscan_pass_abort = TRUE; <API key>(iscan); } break; case <API key>: WL_TRACE(("iscanresults can't alloc memory: skip\n")); iscan->iscan_state = ISCAN_STATE_IDLE; break; default: WL_TRACE(("iscanresults returned unknown status %d\n", status)); break; } net_os_wake_unlock(iscan->dev); } if (iscan->timer_on) { iscan->timer_on = 0; del_timer_sync(&iscan->timer); } complete_and_exit(&tsk_ctl->completed, 0); } #endif #if !defined(CSCAN) static void <API key>(void) { g_ss_cache_ctrl.m_timer_expired = 1; WL_TRACE(("%s called\n", __FUNCTION__)); } static int <API key>(void) { WL_TRACE(("%s :\n", __FUNCTION__)); g_ss_cache_ctrl.m_prev_scan_mode = 0; g_ss_cache_ctrl.m_cons_br_scan_cnt = 0; g_ss_cache_ctrl.m_cache_head = NULL; g_ss_cache_ctrl.m_link_down = 0; g_ss_cache_ctrl.m_timer_expired = 0; memset(g_ss_cache_ctrl.m_active_bssid, 0, ETHER_ADDR_LEN); g_ss_cache_ctrl.m_timer = kmalloc(sizeof(struct timer_list), GFP_KERNEL); if (!g_ss_cache_ctrl.m_timer) { return -ENOMEM; } g_ss_cache_ctrl.m_timer->function = (void *)<API key>; init_timer(g_ss_cache_ctrl.m_timer); return 0; } static void wl_iw_free_ss_cache(void) { wl_iw_ss_cache_t *node, *cur; wl_iw_ss_cache_t **spec_scan_head; WL_TRACE(("%s called\n", __FUNCTION__)); DHD_OS_MUTEX_LOCK(&wl_cache_lock); spec_scan_head = &g_ss_cache_ctrl.m_cache_head; node = *spec_scan_head; for (;node;) { WL_TRACE(("%s : SSID - %s\n", __FUNCTION__, node->bss_info->SSID)); cur = node; node = cur->next; kfree(cur); } *spec_scan_head = NULL; DHD_OS_MUTEX_UNLOCK(&wl_cache_lock); } static int <API key>(int kick_off) { struct timer_list **timer; timer = &g_ss_cache_ctrl.m_timer; if (*timer) { if (kick_off) { #ifdef CONFIG_PRESCANNED (*timer)->expires = jiffies + msecs_to_jiffies(70000); #else (*timer)->expires = jiffies + msecs_to_jiffies(30000); #endif add_timer(*timer); WL_TRACE(("%s : timer starts \n", __FUNCTION__)); } else { del_timer_sync(*timer); WL_TRACE(("%s : timer stops \n", __FUNCTION__)); } } return 0; } static void <API key>(void) { WL_TRACE(("%s :\n", __FUNCTION__)); wl_iw_free_ss_cache(); <API key>(0); if (g_ss_cache_ctrl.m_timer) { kfree(g_ss_cache_ctrl.m_timer); } } static void <API key>(void) { wl_iw_ss_cache_t *node, *prev, *cur; wl_iw_ss_cache_t **spec_scan_head; DHD_OS_MUTEX_LOCK(&wl_cache_lock); spec_scan_head = &g_ss_cache_ctrl.m_cache_head; node = *spec_scan_head; prev = node; for (;node;) { WL_TRACE(("%s : node SSID %s \n", __FUNCTION__, node->bss_info->SSID)); if (!node->dirty) { cur = node; if (cur == *spec_scan_head) { *spec_scan_head = cur->next; prev = *spec_scan_head; } else { prev->next = cur->next; } node = cur->next; WL_TRACE(("%s : Del node : SSID %s\n", __FUNCTION__, cur->bss_info->SSID)); kfree(cur); continue; } node->dirty = 0; prev = node; node = node->next; } DHD_OS_MUTEX_UNLOCK(&wl_cache_lock); } static int <API key>(wl_scan_results_t *ss_list) { wl_iw_ss_cache_t *node, *prev, *leaf; wl_iw_ss_cache_t **spec_scan_head; wl_bss_info_t *bi = NULL; int i; if (!ss_list->count) { return 0; } DHD_OS_MUTEX_LOCK(&wl_cache_lock); spec_scan_head = &g_ss_cache_ctrl.m_cache_head; for (i = 0; i < ss_list->count; i++) { node = *spec_scan_head; prev = node; bi = bi ? (wl_bss_info_t *)((uintptr)bi + dtoh32(bi->length)) : ss_list->bss_info; WL_TRACE(("%s : find %d with specific SSID %s\n", __FUNCTION__, i, bi->SSID)); for (;node;) { if (!memcmp(&node->bss_info->BSSID, &bi->BSSID, ETHER_ADDR_LEN)) { WL_TRACE(("dirty marked : SSID %s\n", bi->SSID)); node->dirty = 1; break; } prev = node; node = node->next; } if (node) { continue; } leaf = kmalloc(bi->length + <API key>, GFP_KERNEL); if (!leaf) { WL_ERROR(("Memory alloc failure %d\n", bi->length + <API key>)); DHD_OS_MUTEX_UNLOCK(&wl_cache_lock); return -ENOMEM; } memcpy(leaf->bss_info, bi, bi->length); leaf->next = NULL; leaf->dirty = 1; leaf->count = 1; leaf->version = ss_list->version; if (!prev) { *spec_scan_head = leaf; } else { prev->next = leaf; } } DHD_OS_MUTEX_UNLOCK(&wl_cache_lock); return 0; } static int <API key>(struct iw_request_info *info, char *extra, uint buflen_from_user, __u16 *merged_len) { wl_iw_ss_cache_t *node; wl_scan_results_t *list_merge; DHD_OS_MUTEX_LOCK(&wl_cache_lock); node = g_ss_cache_ctrl.m_cache_head; for (;node;) { list_merge = (wl_scan_results_t *)&node->buflen; WL_TRACE(("%s: Cached Specific APs list=%d\n", __FUNCTION__, list_merge->count)); if (buflen_from_user - *merged_len > 0) { *merged_len += (__u16) wl_iw_get_scan_prep(list_merge, info, extra + *merged_len, buflen_from_user - *merged_len); } else { WL_TRACE(("%s: exit with break\n", __FUNCTION__)); break; } node = node->next; } DHD_OS_MUTEX_UNLOCK(&wl_cache_lock); return 0; } static int <API key>(void *addr) { wl_iw_ss_cache_t *node, *prev; wl_iw_ss_cache_t **spec_scan_head; DHD_OS_MUTEX_LOCK(&wl_cache_lock); spec_scan_head = &g_ss_cache_ctrl.m_cache_head; node = *spec_scan_head; prev = node; for (;node;) { if (!memcmp(&node->bss_info->BSSID, addr, ETHER_ADDR_LEN)) { if (node == *spec_scan_head) { *spec_scan_head = node->next; } else { prev->next = node->next; } WL_TRACE(("%s : Del node : %s\n", __FUNCTION__, node->bss_info->SSID)); kfree(node); break; } prev = node; node = node->next; } memset(addr, 0, ETHER_ADDR_LEN); DHD_OS_MUTEX_UNLOCK(&wl_cache_lock); return 0; } #endif static int wl_iw_set_scan( struct net_device *dev, struct iw_request_info *info, union iwreq_data *wrqu, char *extra ) { int error; WL_TRACE(("\n:%s dev:%s: SIOCSIWSCAN : SCAN\n", __FUNCTION__, dev->name)); #ifdef OEM_CHROMIUMOS <API key> = FALSE; #endif #if defined(CSCAN) WL_ERROR(("%s: Scan from SIOCGIWSCAN not supported\n", __FUNCTION__)); return -EINVAL; #endif #if defined(SOFTAP) if (ap_cfg_running) { WL_TRACE(("\n>%s: Not executed, reason -'SOFTAP is active'\n", __FUNCTION__)); return 0; } #endif if (g_onoff == G_WLAN_SET_OFF) return 0; memset(&g_specific_ssid, 0, sizeof(g_specific_ssid)); #ifndef WL_IW_USE_ISCAN <API key> = 0; #endif #if WIRELESS_EXT > 17 if (wrqu->data.length == sizeof(struct iw_scan_req)) { if (wrqu->data.flags & IW_SCAN_THIS_ESSID) { struct iw_scan_req *req = (struct iw_scan_req *)extra; #if defined(CONFIG_FIRST_SCAN) if (<API key> != <API key>) { WL_TRACE(("%s Ignoring SC %s first BC is not done = %d\n", __FUNCTION__, req->essid, <API key>)); return -EBUSY; } #endif if (<API key>) { WL_TRACE(("%s Specific SCAN is not done ignore scan for = %s \n", __FUNCTION__, req->essid)); return -EBUSY; } else { g_specific_ssid.SSID_len = MIN(sizeof(g_specific_ssid.SSID), req->essid_len); memcpy(g_specific_ssid.SSID, req->essid, g_specific_ssid.SSID_len); g_specific_ssid.SSID_len = htod32(g_specific_ssid.SSID_len); <API key> = 1; WL_TRACE(("### Specific scan ssid=%s len=%d\n", g_specific_ssid.SSID, g_specific_ssid.SSID_len)); } } } #endif if ((error = dev_wlc_ioctl(dev, WLC_SCAN, &g_specific_ssid, sizeof(g_specific_ssid)))) { WL_TRACE((" <API key> = 0; return -EBUSY; } return 0; } #ifdef WL_IW_USE_ISCAN int <API key>(struct net_device *dev, uint flag) { wlc_ssid_t ssid; iscan_info_t *iscan = g_iscan; #if defined(CONFIG_FIRST_SCAN) if (<API key> == <API key>) { <API key> = <API key>; WL_TRACE(("%s: First Brodcast scan was forced\n", __FUNCTION__)); } else if (<API key> == <API key>) { WL_TRACE(("%s: ignore ISCAN request first BS is not done yet\n", __FUNCTION__)); return 0; } #endif #if (LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 27)) if (flag) rtnl_lock(); #endif dev_wlc_ioctl(dev, <API key>, &iscan->scan_flag, sizeof(iscan->scan_flag)); <API key>(dev); WL_TRACE(("+++: Set Broadcast ISCAN\n")); memset(&ssid, 0, sizeof(ssid)); iscan->list_cur = iscan->list_hdr; iscan->iscan_state = ISCAN_STATE_SCANING; memset(&iscan->iscan_ex_params_p->params, 0, iscan->iscan_ex_param_size); wl_iw_iscan_prep(&iscan->iscan_ex_params_p->params, &ssid); wl_iw_iscan(iscan, &ssid, <API key>); #if (LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 27)) if (flag) rtnl_unlock(); #endif mod_timer(&iscan->timer, jiffies + msecs_to_jiffies(iscan->timer_ms)); iscan->timer_on = 1; return 0; } static int <API key>( struct net_device *dev, struct iw_request_info *info, union iwreq_data *wrqu, char *extra ) { wlc_ssid_t ssid; iscan_info_t *iscan = g_iscan; int ret = 0; WL_TRACE_SCAN(("%s: SIOCSIWSCAN : ISCAN\n", dev->name)); #if defined(CSCAN) WL_ERROR(("%s: Scan from SIOCGIWSCAN not supported\n", __FUNCTION__)); return -EINVAL; #endif net_os_wake_lock(dev); #if defined(SOFTAP) if (ap_cfg_running) { WL_TRACE(("\n>%s: Not executed, reason -'SOFTAP is active'\n", __FUNCTION__)); goto set_scan_end; } #endif if (g_onoff == G_WLAN_SET_OFF) { WL_TRACE(("%s: driver is not up yet after START\n", __FUNCTION__)); goto set_scan_end; } #ifdef PNO_SUPPORT if (<API key>(dev)) { WL_ERROR(("%s: Scan called when PNO is active\n", __FUNCTION__)); } #endif if ((!iscan) || (iscan->tsk_ctl.thr_pid < 0)) { WL_ERROR(("%s error \n", __FUNCTION__)); goto set_scan_end; } if (<API key>) { WL_TRACE(("%s Specific SCAN already running ignoring BC scan\n", __FUNCTION__)); ret = EBUSY; goto set_scan_end; } memset(&ssid, 0, sizeof(ssid)); #if WIRELESS_EXT > 17 if (wrqu->data.length == sizeof(struct iw_scan_req)) { if (wrqu->data.flags & IW_SCAN_THIS_ESSID) { int as = 0; struct iw_scan_req *req = (struct iw_scan_req *)extra; ssid.SSID_len = MIN(sizeof(ssid.SSID), req->essid_len); memcpy(ssid.SSID, req->essid, ssid.SSID_len); ssid.SSID_len = htod32(ssid.SSID_len); dev_wlc_ioctl(dev, <API key>, &as, sizeof(as)); <API key>(dev); ret = wl_iw_set_scan(dev, info, wrqu, extra); goto set_scan_end; } else { <API key> = 0; if (iscan->iscan_state == ISCAN_STATE_SCANING) { WL_TRACE(("%s ISCAN already in progress \n", __FUNCTION__)); goto set_scan_end; } } } #endif #if defined(CONFIG_FIRST_SCAN) && !defined(CSCAN) if (<API key> < <API key>) { if (++<API key> == <API key>) { WL_ERROR(("%s Clean up First scan flag which is %d\n", __FUNCTION__, <API key>)); <API key> = <API key>; } else { WL_ERROR(("%s Ignoring Broadcast Scan:First Scan is not done yet %d\n", __FUNCTION__, <API key>)); ret = -EBUSY; goto set_scan_end; } } #endif <API key>(dev, 0); set_scan_end: net_os_wake_unlock(dev); return ret; } #endif #if WIRELESS_EXT > 17 static bool ie_is_wpa_ie(uint8 **wpaie, uint8 **tlvs, int *tlvs_len) { uint8 *ie = *wpaie; if ((ie[1] >= 6) && !bcmp((const void *)&ie[2], (const void *)(WPA_OUI "\x01"), 4)) { return TRUE; } ie += ie[1] + 2; *tlvs_len -= (int)(ie - *tlvs); *tlvs = ie; return FALSE; } static bool ie_is_wps_ie(uint8 **wpsie, uint8 **tlvs, int *tlvs_len) { uint8 *ie = *wpsie; if ((ie[1] >= 4) && !bcmp((const void *)&ie[2], (const void *)(WPA_OUI "\x04"), 4)) { return TRUE; } ie += ie[1] + 2; *tlvs_len -= (int)(ie - *tlvs); *tlvs = ie; return FALSE; } #endif static int <API key>(char **event_p, char *end, struct iw_request_info *info, wl_bss_info_t *bi) { #if WIRELESS_EXT > 17 struct iw_event iwe; char *event; event = *event_p; if (bi->ie_length) { bcm_tlv_t *ie; uint8 *ptr = ((uint8 *)bi) + sizeof(wl_bss_info_t); int ptr_len = bi->ie_length; if ((ie = bcm_parse_tlvs(ptr, ptr_len, DOT11_MNG_RSN_ID))) { iwe.cmd = IWEVGENIE; iwe.u.data.length = ie->len + 2; event = <API key>(info, event, end, &iwe, (char *)ie); } ptr = ((uint8 *)bi) + sizeof(wl_bss_info_t); while ((ie = bcm_parse_tlvs(ptr, ptr_len, DOT11_MNG_WPA_ID))) { if (ie_is_wps_ie(((uint8 **)&ie), &ptr, &ptr_len)) { iwe.cmd = IWEVGENIE; iwe.u.data.length = ie->len + 2; event = <API key>(info, event, end, &iwe, (char *)ie); break; } } ptr = ((uint8 *)bi) + sizeof(wl_bss_info_t); ptr_len = bi->ie_length; while ((ie = bcm_parse_tlvs(ptr, ptr_len, DOT11_MNG_WPA_ID))) { if (ie_is_wpa_ie(((uint8 **)&ie), &ptr, &ptr_len)) { iwe.cmd = IWEVGENIE; iwe.u.data.length = ie->len + 2; event = <API key>(info, event, end, &iwe, (char *)ie); break; } } *event_p = event; } #endif return 0; } #ifndef CSCAN static uint wl_iw_get_scan_prep( wl_scan_results_t *list, struct iw_request_info *info, char *extra, short max_size) { int i, j; struct iw_event iwe; wl_bss_info_t *bi = NULL; char *event = extra, *end = extra + max_size - WE_ADD_EVENT_FIX, *value; int ret = 0; if (!list) { WL_ERROR(("%s: Null list pointer", __FUNCTION__)); return ret; } for (i = 0; i < list->count && i < IW_MAX_AP; i++) { if (list->version != WL_BSS_INFO_VERSION) { WL_ERROR(("%s : list->version %d != WL_BSS_INFO_VERSION\n", __FUNCTION__, list->version)); return ret; } bi = bi ? (wl_bss_info_t *)((uintptr)bi + dtoh32(bi->length)) : list->bss_info; WL_TRACE(("%s : %s\n", __FUNCTION__, bi->SSID)); iwe.cmd = SIOCGIWAP; iwe.u.ap_addr.sa_family = ARPHRD_ETHER; memcpy(iwe.u.ap_addr.sa_data, &bi->BSSID, ETHER_ADDR_LEN); event = <API key>(info, event, end, &iwe, IW_EV_ADDR_LEN); iwe.u.data.length = dtoh32(bi->SSID_len); iwe.cmd = SIOCGIWESSID; iwe.u.data.flags = 1; event = <API key>(info, event, end, &iwe, bi->SSID); if (dtoh16(bi->capability) & (DOT11_CAP_ESS | DOT11_CAP_IBSS)) { iwe.cmd = SIOCGIWMODE; if (dtoh16(bi->capability) & DOT11_CAP_ESS) iwe.u.mode = IW_MODE_INFRA; else iwe.u.mode = IW_MODE_ADHOC; event = <API key>(info, event, end, &iwe, IW_EV_UINT_LEN); } iwe.cmd = SIOCGIWFREQ; iwe.u.freq.m = wf_channel2mhz(CHSPEC_CHANNEL(bi->chanspec), CHSPEC_CHANNEL(bi->chanspec) <= CH_MAX_2G_CHANNEL ? <API key> : WF_CHAN_FACTOR_5_G); iwe.u.freq.e = 6; event = <API key>(info, event, end, &iwe, IW_EV_FREQ_LEN); iwe.cmd = IWEVQUAL; iwe.u.qual.qual = rssi_to_qual(dtoh16(bi->RSSI)); iwe.u.qual.level = 0x100 + dtoh16(bi->RSSI); iwe.u.qual.noise = 0x100 + bi->phy_noise; event = <API key>(info, event, end, &iwe, IW_EV_QUAL_LEN); <API key>(&event, end, info, bi); iwe.cmd = SIOCGIWENCODE; if (dtoh16(bi->capability) & DOT11_CAP_PRIVACY) iwe.u.data.flags = IW_ENCODE_ENABLED | IW_ENCODE_NOKEY; else iwe.u.data.flags = IW_ENCODE_DISABLED; iwe.u.data.length = 0; event = <API key>(info, event, end, &iwe, (char *)event); if (bi->rateset.count) { if (((event -extra) + IW_EV_LCP_LEN) <= (uintptr)end) { value = event + IW_EV_LCP_LEN; iwe.cmd = SIOCGIWRATE; iwe.u.bitrate.fixed = iwe.u.bitrate.disabled = 0; for (j = 0; j < bi->rateset.count && j < IW_MAX_BITRATES; j++) { iwe.u.bitrate.value = (bi->rateset.rates[j] & 0x7f) * 500000; value = <API key>(info, event, value, end, &iwe, IW_EV_PARAM_LEN); } event = value; } } } if ((ret = (event - extra)) < 0) { WL_ERROR(("==> Wrong size\n")); ret = 0; } WL_TRACE(("%s: size=%d bytes prepared \n", __FUNCTION__, (unsigned int)(event - extra))); return (uint)ret; } static int wl_iw_get_scan( struct net_device *dev, struct iw_request_info *info, struct iw_point *dwrq, char *extra ) { channel_info_t ci; wl_scan_results_t *list_merge; wl_scan_results_t *list = (wl_scan_results_t *) g_scan; int error; uint buflen_from_user = dwrq->length; uint len = G_SCAN_RESULTS; __u16 len_ret = 0; #if !defined(CSCAN) __u16 merged_len = 0; #endif #if defined(WL_IW_USE_ISCAN) iscan_info_t *iscan = g_iscan; iscan_buf_t * p_buf; #if !defined(CSCAN) uint32 counter = 0; #endif #endif WL_TRACE(("%s: buflen_from_user %d: \n", dev->name, buflen_from_user)); if (!extra) { WL_TRACE(("%s: wl_iw_get_scan return -EINVAL\n", dev->name)); return -EINVAL; } if ((error = dev_wlc_ioctl(dev, WLC_GET_CHANNEL, &ci, sizeof(ci)))) return error; ci.scan_channel = dtoh32(ci.scan_channel); if (ci.scan_channel) return -EAGAIN; #if !defined(CSCAN) if (g_ss_cache_ctrl.m_timer_expired) { wl_iw_free_ss_cache(); g_ss_cache_ctrl.m_timer_expired ^= 1; } if ((!<API key> && g_ss_cache_ctrl.m_prev_scan_mode) || g_ss_cache_ctrl.m_cons_br_scan_cnt > 4) { g_ss_cache_ctrl.m_cons_br_scan_cnt = 0; <API key>(); } g_ss_cache_ctrl.m_prev_scan_mode = <API key>; if (<API key>) { g_ss_cache_ctrl.m_cons_br_scan_cnt = 0; } else { g_ss_cache_ctrl.m_cons_br_scan_cnt++; } #endif if (<API key>) { list = kmalloc(len, GFP_KERNEL); if (!list) { WL_TRACE(("%s: wl_iw_get_scan return -ENOMEM\n", dev->name)); <API key> = 0; return -ENOMEM; } } memset(list, 0, len); list->buflen = htod32(len); if ((error = dev_wlc_ioctl(dev, WLC_SCAN_RESULTS, list, len))) { WL_ERROR(("%s: %s : Scan_results ERROR %d\n", dev->name, __FUNCTION__, error)); dwrq->length = len; if (<API key>) { <API key> = 0; kfree(list); } return 0; } list->buflen = dtoh32(list->buflen); list->version = dtoh32(list->version); list->count = dtoh32(list->count); if (list->version != WL_BSS_INFO_VERSION) { WL_ERROR(("%s : list->version %d != WL_BSS_INFO_VERSION\n", __FUNCTION__, list->version)); if (<API key>) { <API key> = 0; kfree(list); } return -EINVAL; } #if !defined(CSCAN) if (<API key>) { <API key>(list); kfree(list); } #endif #if !defined(CSCAN) DHD_OS_MUTEX_LOCK(&wl_cache_lock); #if defined(WL_IW_USE_ISCAN) if (<API key>) WL_TRACE(("%s: Specified scan APs from scan=%d\n", __FUNCTION__, list->count)); p_buf = iscan->list_hdr; while (p_buf != iscan->list_cur) { list_merge = &((wl_iscan_results_t*)p_buf->iscan_buf)->results; WL_TRACE(("%s: Bcast APs list=%d\n", __FUNCTION__, list_merge->count)); counter += list_merge->count; if (list_merge->count > 0) len_ret += (__u16) wl_iw_get_scan_prep(list_merge, info, extra+len_ret, buflen_from_user -len_ret); p_buf = p_buf->next; } WL_TRACE(("%s merged with total Bcast APs=%d\n", __FUNCTION__, counter)); #else list_merge = (wl_scan_results_t *) g_scan; len_ret = (__u16) wl_iw_get_scan_prep(list_merge, info, extra, buflen_from_user); #endif DHD_OS_MUTEX_UNLOCK(&wl_cache_lock); if (g_ss_cache_ctrl.m_link_down) { <API key>(g_ss_cache_ctrl.m_active_bssid); } <API key>(info, extra+len_ret, <API key>, &merged_len); len_ret += merged_len; <API key>(0); <API key>(1); #else if (<API key>) { WL_TRACE(("%s: Specified scan APs in the list =%d\n", __FUNCTION__, list->count)); len_ret = (__u16) wl_iw_get_scan_prep(list, info, extra, buflen_from_user); kfree(list); #if defined(WL_IW_USE_ISCAN) p_buf = iscan->list_hdr; while (p_buf != iscan->list_cur) { list_merge = &((wl_iscan_results_t*)p_buf->iscan_buf)->results; WL_TRACE(("%s: Bcast APs list=%d\n", __FUNCTION__, list_merge->count)); if (list_merge->count > 0) len_ret += (__u16) wl_iw_get_scan_prep(list_merge, info, extra+len_ret, buflen_from_user -len_ret); p_buf = p_buf->next; } #else list_merge = (wl_scan_results_t *) g_scan; WL_TRACE(("%s: Bcast APs list=%d\n", __FUNCTION__, list_merge->count)); if (list_merge->count > 0) len_ret += (__u16) wl_iw_get_scan_prep(list_merge, info, extra+len_ret, buflen_from_user -len_ret); #endif } else { list = (wl_scan_results_t *) g_scan; len_ret = (__u16) wl_iw_get_scan_prep(list, info, extra, buflen_from_user); } #endif #if defined(WL_IW_USE_ISCAN) <API key> = 0; #endif if ((len_ret + WE_ADD_EVENT_FIX) < buflen_from_user) len = len_ret; dwrq->length = len; dwrq->flags = 0; WL_TRACE(("%s return to WE %d bytes APs=%d\n", __FUNCTION__, dwrq->length, list->count)); return 0; } #endif #if defined(WL_IW_USE_ISCAN) static int <API key>( struct net_device *dev, struct iw_request_info *info, struct iw_point *dwrq, char *extra ) { wl_scan_results_t *list; struct iw_event iwe; wl_bss_info_t *bi = NULL; int ii, j; int apcnt; char *event = extra, *end = extra + dwrq->length, *value; iscan_info_t *iscan = g_iscan; iscan_buf_t * p_buf; uint32 counter = 0; uint8 channel; #if !defined(CSCAN) __u16 merged_len = 0; uint buflen_from_user = dwrq->length; #endif WL_TRACE(("%s %s buflen_from_user %d:\n", dev->name, __FUNCTION__, dwrq->length)); #if defined(SOFTAP) if (ap_cfg_running) { WL_TRACE(("%s: Not executed, reason -'SOFTAP is active'\n", __FUNCTION__)); return -EINVAL; } #endif if (!extra) { WL_TRACE(("%s: INVALID SIOCGIWSCAN GET bad parameter\n", dev->name)); return -EINVAL; } #if defined(CONFIG_FIRST_SCAN) if (<API key> < <API key>) { WL_TRACE(("%s %s: first ISCAN results are NOT ready yet \n", dev->name, __FUNCTION__)); return -EAGAIN; } #endif if ((!iscan) || (iscan->tsk_ctl.thr_pid < 0)) { WL_ERROR(("%ssysioc_pid\n", __FUNCTION__)); return EAGAIN; } #if !defined(CSCAN) if (g_ss_cache_ctrl.m_timer_expired) { wl_iw_free_ss_cache(); g_ss_cache_ctrl.m_timer_expired ^= 1; } if (<API key>) { return wl_iw_get_scan(dev, info, dwrq, extra); } else { if (g_ss_cache_ctrl.m_link_down) { <API key>(g_ss_cache_ctrl.m_active_bssid); } if (g_ss_cache_ctrl.m_prev_scan_mode || g_ss_cache_ctrl.m_cons_br_scan_cnt > 4) { g_ss_cache_ctrl.m_cons_br_scan_cnt = 0; <API key>(); } g_ss_cache_ctrl.m_prev_scan_mode = <API key>; g_ss_cache_ctrl.m_cons_br_scan_cnt++; } #endif WL_TRACE(("%s: SIOCGIWSCAN GET broadcast results\n", dev->name)); apcnt = 0; p_buf = iscan->list_hdr; while (p_buf != iscan->list_cur) { list = &((wl_iscan_results_t*)p_buf->iscan_buf)->results; counter += list->count; if (list->version != WL_BSS_INFO_VERSION) { WL_ERROR(("%s : list->version %d != WL_BSS_INFO_VERSION\n", __FUNCTION__, list->version)); return -EINVAL; } bi = NULL; for (ii = 0; ii < list->count && apcnt < IW_MAX_AP; apcnt++, ii++) { bi = (bi ? (wl_bss_info_t *)((uintptr)bi + dtoh32(bi->length)) : list->bss_info); ASSERT(((uintptr)bi + dtoh32(bi->length)) <= ((uintptr)list + WLC_IW_ISCAN_MAXLEN)); if (event + ETHER_ADDR_LEN + bi->SSID_len + IW_EV_UINT_LEN + IW_EV_FREQ_LEN + IW_EV_QUAL_LEN >= end) return -E2BIG; iwe.cmd = SIOCGIWAP; iwe.u.ap_addr.sa_family = ARPHRD_ETHER; memcpy(iwe.u.ap_addr.sa_data, &bi->BSSID, ETHER_ADDR_LEN); event = <API key>(info, event, end, &iwe, IW_EV_ADDR_LEN); iwe.u.data.length = dtoh32(bi->SSID_len); iwe.cmd = SIOCGIWESSID; iwe.u.data.flags = 1; event = <API key>(info, event, end, &iwe, bi->SSID); if (dtoh16(bi->capability) & (DOT11_CAP_ESS | DOT11_CAP_IBSS)) { iwe.cmd = SIOCGIWMODE; if (dtoh16(bi->capability) & DOT11_CAP_ESS) iwe.u.mode = IW_MODE_INFRA; else iwe.u.mode = IW_MODE_ADHOC; event = <API key>(info, event, end, &iwe, IW_EV_UINT_LEN); } iwe.cmd = SIOCGIWFREQ; channel = (bi->ctl_ch == 0) ? CHSPEC_CHANNEL(bi->chanspec) : bi->ctl_ch; iwe.u.freq.m = wf_channel2mhz(channel, channel <= CH_MAX_2G_CHANNEL ? <API key> : WF_CHAN_FACTOR_5_G); iwe.u.freq.e = 6; event = <API key>(info, event, end, &iwe, IW_EV_FREQ_LEN); iwe.cmd = IWEVQUAL; iwe.u.qual.qual = rssi_to_qual(dtoh16(bi->RSSI)); iwe.u.qual.level = 0x100 + dtoh16(bi->RSSI); iwe.u.qual.noise = 0x100 + bi->phy_noise; event = <API key>(info, event, end, &iwe, IW_EV_QUAL_LEN); <API key>(&event, end, info, bi); iwe.cmd = SIOCGIWENCODE; if (dtoh16(bi->capability) & DOT11_CAP_PRIVACY) iwe.u.data.flags = IW_ENCODE_ENABLED | IW_ENCODE_NOKEY; else iwe.u.data.flags = IW_ENCODE_DISABLED; iwe.u.data.length = 0; event = <API key>(info, event, end, &iwe, (char *)event); if (bi->rateset.count) { if (event + IW_MAX_BITRATES*IW_EV_PARAM_LEN >= end) return -E2BIG; value = event + IW_EV_LCP_LEN; iwe.cmd = SIOCGIWRATE; iwe.u.bitrate.fixed = iwe.u.bitrate.disabled = 0; for (j = 0; j < bi->rateset.count && j < IW_MAX_BITRATES; j++) { iwe.u.bitrate.value = (bi->rateset.rates[j] & 0x7f) * 500000; value = <API key>(info, event, value, end, &iwe, IW_EV_PARAM_LEN); } event = value; } } p_buf = p_buf->next; } dwrq->length = event - extra; dwrq->flags = 0; #if !defined(CSCAN) <API key>(info, event, buflen_from_user - dwrq->length, &merged_len); dwrq->length += merged_len; <API key>(0); <API key>(1); #endif #if defined(CONFIG_FIRST_SCAN) <API key> = <API key>; #endif WL_TRACE(("%s return to WE %d bytes APs=%d\n", __FUNCTION__, dwrq->length, counter)); return 0; } #endif #define WL_JOIN_PARAMS_MAX 1600 #ifdef CONFIG_PRESCANNED static int check_prescan(wl_join_params_t *join_params, int *join_params_size) { int cnt = 0; int indx = 0; wl_iw_ss_cache_t *node = NULL; wl_bss_info_t *bi = NULL; iscan_info_t *iscan = g_iscan; iscan_buf_t * buf; wl_scan_results_t *list; char *destbuf; buf = iscan->list_hdr; while (buf) { list = &((wl_iscan_results_t*)buf->iscan_buf)->results; bi = NULL; for (indx = 0; indx < list->count; indx++) { bi = bi ? (wl_bss_info_t *)((uintptr)bi + dtoh32(bi->length)) : list->bss_info; if (!(dtoh16(bi->capability) & DOT11_CAP_ESS)) continue; if ((dtoh32(bi->SSID_len) != join_params->ssid.SSID_len) || memcmp(bi->SSID, join_params->ssid.SSID, join_params->ssid.SSID_len)) continue; memcpy(&join_params->params.chanspec_list[cnt], &bi->chanspec, sizeof(chanspec_t)); WL_ERROR(("iscan : chanspec :%d, count %d \n", bi->chanspec, cnt)); cnt++; } buf = buf->next; } if (!cnt) { <API key>(); node = g_ss_cache_ctrl.m_cache_head; for (; node; ) { if (!memcmp(&node->bss_info->SSID, join_params->ssid.SSID, join_params->ssid.SSID_len)) { memcpy(&join_params->params.chanspec_list[cnt], &node->bss_info->chanspec, sizeof(chanspec_t)); WL_ERROR(("cache_scan : chanspec :%d, count %d \n", (int)node->bss_info->chanspec, cnt)); cnt++; } node = node->next; } <API key>(); } if (!cnt) { return 0; } destbuf = (char *)&join_params->params.chanspec_list[cnt]; *join_params_size = destbuf - (char*)join_params; join_params->ssid.SSID_len = htod32(g_ssid.SSID_len); memcpy(&(join_params->params.bssid), &ether_bcast, ETHER_ADDR_LEN); join_params->params.chanspec_num = htod32(cnt); if ((*join_params_size) > WL_JOIN_PARAMS_MAX) { WL_ERROR(("can't fit bssids for all %d APs found\n", cnt)); kfree(join_params); return 0; } WL_ERROR(("Passing %d channel/bssid pairs.\n", cnt)); return cnt; } #endif static int wl_iw_set_essid( struct net_device *dev, struct iw_request_info *info, struct iw_point *dwrq, char *extra ) { int error; wl_join_params_t *join_params; int join_params_size; WL_TRACE(("%s: SIOCSIWESSID\n", dev->name)); <API key>(extra); #ifdef OEM_CHROMIUMOS if (<API key>) return -EAGAIN; #endif if (!(join_params = kmalloc(WL_JOIN_PARAMS_MAX, GFP_KERNEL))) { WL_ERROR(("allocation failed for join_params size is %d\n", WL_JOIN_PARAMS_MAX)); return -ENOMEM; } memset(join_params, 0, WL_JOIN_PARAMS_MAX); memset(&g_ssid, 0, sizeof(g_ssid)); if (dwrq->length && extra) { #if WIRELESS_EXT > 20 g_ssid.SSID_len = MIN(sizeof(g_ssid.SSID), dwrq->length); #else g_ssid.SSID_len = MIN(sizeof(g_ssid.SSID), dwrq->length-1); #endif memcpy(g_ssid.SSID, extra, g_ssid.SSID_len); #ifdef CONFIG_PRESCANNED memcpy(join_params->ssid.SSID, g_ssid.SSID, g_ssid.SSID_len); join_params->ssid.SSID_len = g_ssid.SSID_len; if (check_prescan(join_params, &join_params_size)) { if ((error = dev_wlc_ioctl(dev, WLC_SET_SSID, join_params, join_params_size))) { WL_ERROR(("Invalid ioctl data=%d\n", error)); kfree(join_params); return error; } kfree(join_params); return 0; } else { WL_ERROR(("No matched found\n Trying to join to specific channel\n")); } #endif } else { g_ssid.SSID_len = 0; } g_ssid.SSID_len = htod32(g_ssid.SSID_len); memset(join_params, 0, sizeof(*join_params)); join_params_size = sizeof(join_params->ssid); memcpy(join_params->ssid.SSID, g_ssid.SSID, g_ssid.SSID_len); join_params->ssid.SSID_len = htod32(g_ssid.SSID_len); memcpy(&(join_params->params.bssid), &ether_bcast, ETHER_ADDR_LEN); <API key>(g_wl_iw_params.target_channel, join_params, &join_params_size); if ((error = dev_wlc_ioctl(dev, WLC_SET_SSID, join_params, join_params_size))) { WL_ERROR(("Invalid ioctl data=%d\n", error)); return error; } if (g_ssid.SSID_len) { WL_ERROR(("%s: join SSID=%s ch=%d\n", __FUNCTION__, g_ssid.SSID, g_wl_iw_params.target_channel)); } kfree(join_params); return 0; } static int wl_iw_get_essid( struct net_device *dev, struct iw_request_info *info, struct iw_point *dwrq, char *extra ) { wlc_ssid_t ssid; int error; WL_TRACE(("%s: SIOCGIWESSID\n", dev->name)); if (!extra) return -EINVAL; if ((error = dev_wlc_ioctl(dev, WLC_GET_SSID, &ssid, sizeof(ssid)))) { WL_ERROR(("Error getting the SSID\n")); return error; } ssid.SSID_len = dtoh32(ssid.SSID_len); memcpy(extra, ssid.SSID, ssid.SSID_len); dwrq->length = ssid.SSID_len; dwrq->flags = 1; return 0; } static int wl_iw_set_nick( struct net_device *dev, struct iw_request_info *info, struct iw_point *dwrq, char *extra ) { wl_iw_t *iw = NETDEV_PRIV(dev); WL_TRACE(("%s: SIOCSIWNICKN\n", dev->name)); if (!extra) return -EINVAL; if (dwrq->length > sizeof(iw->nickname)) return -E2BIG; memcpy(iw->nickname, extra, dwrq->length); iw->nickname[dwrq->length - 1] = '\0'; return 0; } static int wl_iw_get_nick( struct net_device *dev, struct iw_request_info *info, struct iw_point *dwrq, char *extra ) { wl_iw_t *iw = NETDEV_PRIV(dev); WL_TRACE(("%s: SIOCGIWNICKN\n", dev->name)); if (!extra) return -EINVAL; strcpy(extra, iw->nickname); dwrq->length = strlen(extra) + 1; return 0; } static int wl_iw_set_rate( struct net_device *dev, struct iw_request_info *info, struct iw_param *vwrq, char *extra ) { wl_rateset_t rateset; int error, rate, i, error_bg, error_a; WL_TRACE(("%s: SIOCSIWRATE\n", dev->name)); if ((error = dev_wlc_ioctl(dev, <API key>, &rateset, sizeof(rateset)))) return error; rateset.count = dtoh32(rateset.count); if (vwrq->value < 0) { rate = rateset.rates[rateset.count - 1] & 0x7f; } else if (vwrq->value < rateset.count) { rate = rateset.rates[vwrq->value] & 0x7f; } else { rate = vwrq->value / 500000; } if (vwrq->fixed) { error_bg = dev_wlc_intvar_set(dev, "bg_rate", rate); error_a = dev_wlc_intvar_set(dev, "a_rate", rate); if (error_bg && error_a) return (error_bg | error_a); } else { error_bg = dev_wlc_intvar_set(dev, "bg_rate", 0); error_a = dev_wlc_intvar_set(dev, "a_rate", 0); if (error_bg && error_a) return (error_bg | error_a); for (i = 0; i < rateset.count; i++) if ((rateset.rates[i] & 0x7f) > rate) break; rateset.count = htod32(i); if ((error = dev_wlc_ioctl(dev, WLC_SET_RATESET, &rateset, sizeof(rateset)))) return error; } return 0; } static int wl_iw_get_rate( struct net_device *dev, struct iw_request_info *info, struct iw_param *vwrq, char *extra ) { int error, rate; WL_TRACE(("%s: SIOCGIWRATE\n", dev->name)); if ((error = dev_wlc_ioctl(dev, WLC_GET_RATE, &rate, sizeof(rate)))) return error; rate = dtoh32(rate); vwrq->value = rate * 500000; return 0; } static int wl_iw_set_rts( struct net_device *dev, struct iw_request_info *info, struct iw_param *vwrq, char *extra ) { int error, rts; WL_TRACE(("%s: SIOCSIWRTS\n", dev->name)); if (vwrq->disabled) rts = <API key>; else if (vwrq->value < 0 || vwrq->value > <API key>) return -EINVAL; else rts = vwrq->value; if ((error = dev_wlc_intvar_set(dev, "rtsthresh", rts))) return error; return 0; } static int wl_iw_get_rts( struct net_device *dev, struct iw_request_info *info, struct iw_param *vwrq, char *extra ) { int error, rts; WL_TRACE(("%s: SIOCGIWRTS\n", dev->name)); if ((error = dev_wlc_intvar_get(dev, "rtsthresh", &rts))) return error; vwrq->value = rts; vwrq->disabled = (rts >= <API key>); vwrq->fixed = 1; return 0; } static int wl_iw_set_frag( struct net_device *dev, struct iw_request_info *info, struct iw_param *vwrq, char *extra ) { int error, frag; WL_TRACE(("%s: SIOCSIWFRAG\n", dev->name)); if (vwrq->disabled) frag = <API key>; else if (vwrq->value < 0 || vwrq->value > <API key>) return -EINVAL; else frag = vwrq->value; if ((error = dev_wlc_intvar_set(dev, "fragthresh", frag))) return error; return 0; } static int wl_iw_get_frag( struct net_device *dev, struct iw_request_info *info, struct iw_param *vwrq, char *extra ) { int error, fragthreshold; WL_TRACE(("%s: SIOCGIWFRAG\n", dev->name)); if ((error = dev_wlc_intvar_get(dev, "fragthresh", &fragthreshold))) return error; vwrq->value = fragthreshold; vwrq->disabled = (fragthreshold >= <API key>); vwrq->fixed = 1; return 0; } static int wl_iw_set_txpow( struct net_device *dev, struct iw_request_info *info, struct iw_param *vwrq, char *extra ) { int error, disable; uint16 txpwrmw; WL_TRACE(("%s: SIOCSIWTXPOW\n", dev->name)); disable = vwrq->disabled ? WL_RADIO_SW_DISABLE : 0; disable += WL_RADIO_SW_DISABLE << 16; disable = htod32(disable); if ((error = dev_wlc_ioctl(dev, WLC_SET_RADIO, &disable, sizeof(disable)))) return error; if (disable & WL_RADIO_SW_DISABLE) return 0; if (!(vwrq->flags & IW_TXPOW_MWATT)) return -EINVAL; if (vwrq->value < 0) return 0; if (vwrq->value > 0xffff) txpwrmw = 0xffff; else txpwrmw = (uint16)vwrq->value; error = dev_wlc_intvar_set(dev, "qtxpower", (int)(bcm_mw_to_qdbm(txpwrmw))); return error; } static int wl_iw_get_txpow( struct net_device *dev, struct iw_request_info *info, struct iw_param *vwrq, char *extra ) { int error, disable, txpwrdbm; uint8 result; WL_TRACE(("%s: SIOCGIWTXPOW\n", dev->name)); if ((error = dev_wlc_ioctl(dev, WLC_GET_RADIO, &disable, sizeof(disable))) || (error = dev_wlc_intvar_get(dev, "qtxpower", &txpwrdbm))) return error; disable = dtoh32(disable); result = (uint8)(txpwrdbm & ~WL_TXPWR_OVERRIDE); vwrq->value = (int32)bcm_qdbm_to_mw(result); vwrq->fixed = 0; vwrq->disabled = (disable & (WL_RADIO_SW_DISABLE | WL_RADIO_HW_DISABLE)) ? 1 : 0; vwrq->flags = IW_TXPOW_MWATT; return 0; } #if WIRELESS_EXT > 10 static int wl_iw_set_retry( struct net_device *dev, struct iw_request_info *info, struct iw_param *vwrq, char *extra ) { int error, lrl, srl; WL_TRACE(("%s: SIOCSIWRETRY\n", dev->name)); if (vwrq->disabled || (vwrq->flags & IW_RETRY_LIFETIME)) return -EINVAL; if (vwrq->flags & IW_RETRY_LIMIT) { #if WIRELESS_EXT > 20 if ((vwrq->flags & IW_RETRY_LONG) ||(vwrq->flags & IW_RETRY_MAX) || !((vwrq->flags & IW_RETRY_SHORT) || (vwrq->flags & IW_RETRY_MIN))) { #else if ((vwrq->flags & IW_RETRY_MAX) || !(vwrq->flags & IW_RETRY_MIN)) { #endif lrl = htod32(vwrq->value); if ((error = dev_wlc_ioctl(dev, WLC_SET_LRL, &lrl, sizeof(lrl)))) return error; } #if WIRELESS_EXT > 20 if ((vwrq->flags & IW_RETRY_SHORT) ||(vwrq->flags & IW_RETRY_MIN) || !((vwrq->flags & IW_RETRY_LONG) || (vwrq->flags & IW_RETRY_MAX))) { #else if ((vwrq->flags & IW_RETRY_MIN) || !(vwrq->flags & IW_RETRY_MAX)) { #endif srl = htod32(vwrq->value); if ((error = dev_wlc_ioctl(dev, WLC_SET_SRL, &srl, sizeof(srl)))) return error; } } return 0; } static int wl_iw_get_retry( struct net_device *dev, struct iw_request_info *info, struct iw_param *vwrq, char *extra ) { int error, lrl, srl; WL_TRACE(("%s: SIOCGIWRETRY\n", dev->name)); vwrq->disabled = 0; if ((vwrq->flags & IW_RETRY_TYPE) == IW_RETRY_LIFETIME) return -EINVAL; if ((error = dev_wlc_ioctl(dev, WLC_GET_LRL, &lrl, sizeof(lrl))) || (error = dev_wlc_ioctl(dev, WLC_GET_SRL, &srl, sizeof(srl)))) return error; lrl = dtoh32(lrl); srl = dtoh32(srl); if (vwrq->flags & IW_RETRY_MAX) { vwrq->flags = IW_RETRY_LIMIT | IW_RETRY_MAX; vwrq->value = lrl; } else { vwrq->flags = IW_RETRY_LIMIT; vwrq->value = srl; if (srl != lrl) vwrq->flags |= IW_RETRY_MIN; } return 0; } #endif static int wl_iw_set_encode( struct net_device *dev, struct iw_request_info *info, struct iw_point *dwrq, char *extra ) { wl_wsec_key_t key; int error, val, wsec; WL_TRACE(("%s: SIOCSIWENCODE index %d, len %d, flags %04x (%s%s%s%s%s)\n", dev->name, dwrq->flags & IW_ENCODE_INDEX, dwrq->length, dwrq->flags, dwrq->flags & IW_ENCODE_NOKEY ? "NOKEY" : "", dwrq->flags & IW_ENCODE_DISABLED ? " DISABLED" : "", dwrq->flags & <API key> ? " RESTRICTED" : "", dwrq->flags & IW_ENCODE_OPEN ? " OPEN" : "", dwrq->flags & IW_ENCODE_TEMP ? " TEMP" : "")); memset(&key, 0, sizeof(key)); if ((dwrq->flags & IW_ENCODE_INDEX) == 0) { for (key.index = 0; key.index < <API key>; key.index++) { val = htod32(key.index); if ((error = dev_wlc_ioctl(dev, WLC_GET_KEY_PRIMARY, &val, sizeof(val)))) return error; val = dtoh32(val); if (val) break; } if (key.index == <API key>) key.index = 0; } else { key.index = (dwrq->flags & IW_ENCODE_INDEX) - 1; if (key.index >= <API key>) return -EINVAL; } if (!extra || !dwrq->length || (dwrq->flags & IW_ENCODE_NOKEY)) { val = htod32(key.index); if ((error = dev_wlc_ioctl(dev, WLC_SET_KEY_PRIMARY, &val, sizeof(val)))) return error; } else { key.len = dwrq->length; if (dwrq->length > sizeof(key.data)) return -EINVAL; memcpy(key.data, extra, dwrq->length); key.flags = WL_PRIMARY_KEY; switch (key.len) { case WEP1_KEY_SIZE: key.algo = CRYPTO_ALGO_WEP1; break; case WEP128_KEY_SIZE: key.algo = CRYPTO_ALGO_WEP128; break; #if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 14) case TKIP_KEY_SIZE: key.algo = CRYPTO_ALGO_TKIP; break; #endif case AES_KEY_SIZE: key.algo = CRYPTO_ALGO_AES_CCM; break; default: return -EINVAL; } swap_key_from_BE(&key); if ((error = dev_wlc_ioctl(dev, WLC_SET_KEY, &key, sizeof(key)))) return error; } val = (dwrq->flags & IW_ENCODE_DISABLED) ? 0 : WEP_ENABLED; if ((error = dev_wlc_intvar_get(dev, "wsec", &wsec))) return error; wsec &= ~(WEP_ENABLED); wsec |= val; if ((error = dev_wlc_intvar_set(dev, "wsec", wsec))) return error; val = (dwrq->flags & <API key>) ? 1 : 0; val = htod32(val); if ((error = dev_wlc_ioctl(dev, WLC_SET_AUTH, &val, sizeof(val)))) return error; return 0; } static int wl_iw_get_encode( struct net_device *dev, struct iw_request_info *info, struct iw_point *dwrq, char *extra ) { wl_wsec_key_t key; int error, val, wsec, auth; WL_TRACE(("%s: SIOCGIWENCODE\n", dev->name)); bzero(&key, sizeof(wl_wsec_key_t)); if ((dwrq->flags & IW_ENCODE_INDEX) == 0) { for (key.index = 0; key.index < <API key>; key.index++) { val = key.index; if ((error = dev_wlc_ioctl(dev, WLC_GET_KEY_PRIMARY, &val, sizeof(val)))) return error; val = dtoh32(val); if (val) break; } } else key.index = (dwrq->flags & IW_ENCODE_INDEX) - 1; if (key.index >= <API key>) key.index = 0; if ((error = dev_wlc_ioctl(dev, WLC_GET_WSEC, &wsec, sizeof(wsec))) || (error = dev_wlc_ioctl(dev, WLC_GET_AUTH, &auth, sizeof(auth)))) return error; swap_key_to_BE(&key); wsec = dtoh32(wsec); auth = dtoh32(auth); dwrq->length = MIN(DOT11_MAX_KEY_SIZE, key.len); dwrq->flags = key.index + 1; if (!(wsec & (WEP_ENABLED | TKIP_ENABLED | AES_ENABLED))) { dwrq->flags |= IW_ENCODE_DISABLED; } if (auth) { dwrq->flags |= <API key>; } if (dwrq->length && extra) memcpy(extra, key.data, dwrq->length); return 0; } static int wl_iw_set_power( struct net_device *dev, struct iw_request_info *info, struct iw_param *vwrq, char *extra ) { int error, pm; WL_TRACE(("%s: SIOCSIWPOWER\n", dev->name)); #ifdef <API key> pm = vwrq->disabled ? PM_OFF : PM_FAST; #else pm = vwrq->disabled ? PM_OFF : PM_MAX; #endif pm = htod32(pm); if ((error = dev_wlc_ioctl(dev, WLC_SET_PM, &pm, sizeof(pm)))) return error; return 0; } static int wl_iw_get_power( struct net_device *dev, struct iw_request_info *info, struct iw_param *vwrq, char *extra ) { int error, pm; WL_TRACE(("%s: SIOCGIWPOWER\n", dev->name)); if ((error = dev_wlc_ioctl(dev, WLC_GET_PM, &pm, sizeof(pm)))) return error; pm = dtoh32(pm); vwrq->disabled = pm ? 0 : 1; vwrq->flags = IW_POWER_ALL_R; return 0; } #if WIRELESS_EXT > 17 static int wl_iw_set_wpaie( struct net_device *dev, struct iw_request_info *info, struct iw_point *iwp, char *extra ) { WL_TRACE(("%s: SIOCSIWGENIE\n", dev->name)); <API key>(extra); #ifdef DHD_DEBUG { int i; for (i = 0; i < iwp->length; i++) WL_TRACE(("%02X ", extra[i])); WL_TRACE(("\n")); } #endif dev_wlc_bufvar_set(dev, "wpaie", extra, iwp->length); return 0; } static int wl_iw_get_wpaie( struct net_device *dev, struct iw_request_info *info, struct iw_point *iwp, char *extra ) { WL_TRACE(("%s: SIOCGIWGENIE\n", dev->name)); iwp->length = 64; dev_wlc_bufvar_get(dev, "wpaie", extra, iwp->length); return 0; } static int wl_iw_set_encodeext( struct net_device *dev, struct iw_request_info *info, struct iw_point *dwrq, char *extra ) { wl_wsec_key_t key; int error; struct iw_encode_ext *iwe; WL_TRACE(("%s: SIOCSIWENCODEEXT\n", dev->name)); <API key>(extra); memset(&key, 0, sizeof(key)); iwe = (struct iw_encode_ext *)extra; if (dwrq->flags & IW_ENCODE_DISABLED) { } key.index = 0; if (dwrq->flags & IW_ENCODE_INDEX) key.index = (dwrq->flags & IW_ENCODE_INDEX) - 1; key.len = iwe->key_len; if (!ETHER_ISMULTI(iwe->addr.sa_data)) bcopy((void *)&iwe->addr.sa_data, (char *)&key.ea, ETHER_ADDR_LEN); if (key.len == 0) { if (iwe->ext_flags & <API key>) { WL_WSEC(("Changing the the primary Key to %d\n", key.index)); key.index = htod32(key.index); error = dev_wlc_ioctl(dev, WLC_SET_KEY_PRIMARY, &key.index, sizeof(key.index)); if (error) return error; } else { swap_key_from_BE(&key); dev_wlc_ioctl(dev, WLC_SET_KEY, &key, sizeof(key)); } } else { if (iwe->key_len > sizeof(key.data)) return -EINVAL; WL_WSEC(("Setting the key index %d\n", key.index)); if (iwe->ext_flags & <API key>) { WL_WSEC(("key is a Primary Key\n")); key.flags = WL_PRIMARY_KEY; } bcopy((void *)iwe->key, key.data, iwe->key_len); if (iwe->alg == IW_ENCODE_ALG_TKIP) { uint8 keybuf[8]; bcopy(&key.data[24], keybuf, sizeof(keybuf)); bcopy(&key.data[16], &key.data[24], sizeof(keybuf)); bcopy(keybuf, &key.data[16], sizeof(keybuf)); } if (iwe->ext_flags & <API key>) { uchar *ivptr; ivptr = (uchar *)iwe->rx_seq; key.rxiv.hi = (ivptr[5] << 24) | (ivptr[4] << 16) | (ivptr[3] << 8) | ivptr[2]; key.rxiv.lo = (ivptr[1] << 8) | ivptr[0]; key.iv_initialized = TRUE; } switch (iwe->alg) { case IW_ENCODE_ALG_NONE: key.algo = CRYPTO_ALGO_OFF; break; case IW_ENCODE_ALG_WEP: if (iwe->key_len == WEP1_KEY_SIZE) key.algo = CRYPTO_ALGO_WEP1; else key.algo = CRYPTO_ALGO_WEP128; break; case IW_ENCODE_ALG_TKIP: key.algo = CRYPTO_ALGO_TKIP; break; case IW_ENCODE_ALG_CCMP: key.algo = CRYPTO_ALGO_AES_CCM; break; default: break; } swap_key_from_BE(&key); dhd_wait_pend8021x(dev); error = dev_wlc_ioctl(dev, WLC_SET_KEY, &key, sizeof(key)); if (error) return error; } return 0; } #if WIRELESS_EXT > 17 struct { pmkid_list_t pmkids; pmkid_t foo[MAXPMKID-1]; } pmkid_list; static int wl_iw_set_pmksa( struct net_device *dev, struct iw_request_info *info, struct iw_param *vwrq, char *extra ) { struct iw_pmksa *iwpmksa; uint i; int ret = 0; char eabuf[ETHER_ADDR_STR_LEN]; pmkid_t * pmkid_array = pmkid_list.pmkids.pmkid; WL_WSEC(("%s: SIOCSIWPMKSA\n", dev->name)); <API key>(extra); iwpmksa = (struct iw_pmksa *)extra; bzero((char *)eabuf, ETHER_ADDR_STR_LEN); if (iwpmksa->cmd == IW_PMKSA_FLUSH) { WL_WSEC(("wl_iw_set_pmksa - IW_PMKSA_FLUSH\n")); bzero((char *)&pmkid_list, sizeof(pmkid_list)); } else if (iwpmksa->cmd == IW_PMKSA_REMOVE) { { pmkid_list_t pmkid, *pmkidptr; uint j; pmkidptr = &pmkid; bcopy(&iwpmksa->bssid.sa_data[0], &pmkidptr->pmkid[0].BSSID, ETHER_ADDR_LEN); bcopy(&iwpmksa->pmkid[0], &pmkidptr->pmkid[0].PMKID, WPA2_PMKID_LEN); WL_WSEC(("wl_iw_set_pmksa,IW_PMKSA_REMOVE - PMKID: %s = ", bcm_ether_ntoa(&pmkidptr->pmkid[0].BSSID, eabuf))); for (j = 0; j < WPA2_PMKID_LEN; j++) WL_WSEC(("%02x ", pmkidptr->pmkid[0].PMKID[j])); WL_WSEC(("\n")); } for (i = 0; i < pmkid_list.pmkids.npmkid; i++) if (!bcmp(&iwpmksa->bssid.sa_data[0], &pmkid_array[i].BSSID, ETHER_ADDR_LEN)) break; if ((pmkid_list.pmkids.npmkid > 0) && (i < pmkid_list.pmkids.npmkid)) { bzero(&pmkid_array[i], sizeof(pmkid_t)); for (; i < (pmkid_list.pmkids.npmkid - 1); i++) { bcopy(&pmkid_array[i+1].BSSID, &pmkid_array[i].BSSID, ETHER_ADDR_LEN); bcopy(&pmkid_array[i+1].PMKID, &pmkid_array[i].PMKID, WPA2_PMKID_LEN); } pmkid_list.pmkids.npmkid } else ret = -EINVAL; } else if (iwpmksa->cmd == IW_PMKSA_ADD) { for (i = 0; i < pmkid_list.pmkids.npmkid; i++) if (!bcmp(&iwpmksa->bssid.sa_data[0], &pmkid_array[i].BSSID, ETHER_ADDR_LEN)) break; if (i < MAXPMKID) { bcopy(&iwpmksa->bssid.sa_data[0], &pmkid_array[i].BSSID, ETHER_ADDR_LEN); bcopy(&iwpmksa->pmkid[0], &pmkid_array[i].PMKID, WPA2_PMKID_LEN); if (i == pmkid_list.pmkids.npmkid) pmkid_list.pmkids.npmkid++; } else ret = -EINVAL; { uint j; uint k; k = pmkid_list.pmkids.npmkid; WL_WSEC(("wl_iw_set_pmksa,IW_PMKSA_ADD - PMKID: %s = ", bcm_ether_ntoa(&pmkid_array[k].BSSID, eabuf))); for (j = 0; j < WPA2_PMKID_LEN; j++) WL_WSEC(("%02x ", pmkid_array[k].PMKID[j])); WL_WSEC(("\n")); } } WL_WSEC(("PRINTING pmkid LIST - No of elements %d", pmkid_list.pmkids.npmkid)); for (i = 0; i < pmkid_list.pmkids.npmkid; i++) { uint j; WL_WSEC(("\nPMKID[%d]: %s = ", i, bcm_ether_ntoa(&pmkid_array[i].BSSID, eabuf))); for (j = 0; j < WPA2_PMKID_LEN; j++) WL_WSEC(("%02x ", pmkid_array[i].PMKID[j])); } WL_WSEC(("\n")); if (!ret) ret = dev_wlc_bufvar_set(dev, "pmkid_info", (char *)&pmkid_list, sizeof(pmkid_list)); return ret; } #endif static int wl_iw_get_encodeext( struct net_device *dev, struct iw_request_info *info, struct iw_param *vwrq, char *extra ) { WL_TRACE(("%s: SIOCGIWENCODEEXT\n", dev->name)); return 0; } static uint32 <API key>(struct net_device *dev) { wl_iw_t *iw = NETDEV_PRIV(dev); uint32 wsec; if (iw->pcipher & (<API key> | <API key>)) wsec = WEP_ENABLED; else if (iw->pcipher & IW_AUTH_CIPHER_TKIP) wsec = TKIP_ENABLED; else if (iw->pcipher & IW_AUTH_CIPHER_CCMP) wsec = AES_ENABLED; else wsec = 0; if (iw->gcipher & (<API key> | <API key>)) wsec |= WEP_ENABLED; else if (iw->gcipher & IW_AUTH_CIPHER_TKIP) wsec |= TKIP_ENABLED; else if (iw->gcipher & IW_AUTH_CIPHER_CCMP) wsec |= AES_ENABLED; if (wsec == 0 && iw->privacy_invoked) wsec = WEP_ENABLED; WL_INFORM(("%s: returning wsec of %d\n", __FUNCTION__, wsec)); return wsec; } static int wl_iw_set_wpaauth( struct net_device *dev, struct iw_request_info *info, struct iw_param *vwrq, char *extra ) { int error = 0; int paramid; int paramval; int val = 0; wl_iw_t *iw = NETDEV_PRIV(dev); paramid = vwrq->flags & IW_AUTH_INDEX; paramval = vwrq->value; WL_TRACE(("%s: SIOCSIWAUTH, %s(%d), paramval = 0x%0x\n", dev->name, paramid == IW_AUTH_WPA_VERSION ? "IW_AUTH_WPA_VERSION" : paramid == IW_<API key> ? "IW_<API key> : paramid == <API key> ? "<API key>" : paramid == IW_AUTH_KEY_MGMT ? "IW_AUTH_KEY_MGMT" : paramid == IW_<API key> ? "IW_<API key> : paramid == IW_<API key> ? "IW_<API key> : paramid == <API key> ? "<API key>" : paramid == IW_AUTH_WPA_ENABLED ? "IW_AUTH_WPA_ENABLED" : paramid == IW_<API key> ? "IW_<API key> : paramid == IW_<API key> ? "IW_<API key> : paramid == IW_<API key> ? "IW_<API key> : "UNKNOWN", paramid, paramval)); #if defined(SOFTAP) if (ap_cfg_running) { WL_TRACE(("%s: Not executed, reason -'SOFTAP is active'\n", __FUNCTION__)); return 0; } #endif switch (paramid) { case IW_AUTH_WPA_VERSION: if (paramval & IW_<API key>) val = WPA_AUTH_DISABLED; else if (paramval & (IW_<API key>)) val = WPA_AUTH_PSK | <API key>; else if (paramval & IW_<API key>) val = WPA2_AUTH_PSK | <API key>; WL_ERROR(("%s: %d: setting wpa_auth to 0x%0x\n", __FUNCTION__, __LINE__, val)); if ((error = dev_wlc_intvar_set(dev, "wpa_auth", val))) return error; break; case IW_<API key>: iw->pcipher = paramval; val = <API key>(dev); if ((error = dev_wlc_intvar_set(dev, "wsec", val))) return error; break; case <API key>: iw->gcipher = paramval; val = <API key>(dev); if ((error = dev_wlc_intvar_set(dev, "wsec", val))) return error; break; case IW_AUTH_KEY_MGMT: if ((error = dev_wlc_intvar_get(dev, "wpa_auth", &val))) return error; if (val & (WPA_AUTH_PSK | <API key>)) { if (paramval & <API key>) val = WPA_AUTH_PSK; else val = <API key>; if (paramval & 0x04) val |= WPA2_AUTH_FT; } else if (val & (WPA2_AUTH_PSK | <API key>)) { if (paramval & <API key>) val = WPA2_AUTH_PSK; else val = <API key>; if (paramval & 0x04) val |= WPA2_AUTH_FT; } else if (paramval & <API key>) { if (iw->wpaversion == IW_<API key>) val = WPA_AUTH_PSK; else if (iw->wpaversion == IW_<API key>) val = WPA2_AUTH_PSK; else val = WPA_AUTH_DISABLED; } else if (paramval & IW_<API key>) { if (iw->wpaversion == IW_<API key>) val = <API key>; else if (iw->wpaversion == IW_<API key>) val = <API key>; else val = WPA_AUTH_DISABLED; } else val = WPA_AUTH_DISABLED; WL_INFORM(("%s: %d: setting wpa_auth to %d\n", __FUNCTION__, __LINE__, val)); if ((error = dev_wlc_intvar_set(dev, "wpa_auth", val))) return error; break; case IW_<API key>: dev_wlc_bufvar_set(dev, "<API key>", (char *)&paramval, 1); break; case <API key>: WL_INFORM(("Setting the D11auth %d\n", paramval)); if (paramval == IW_<API key>) val = 0; else if (paramval == <API key>) val = 1; else if (paramval == (IW_<API key> | <API key>)) val = 2; else error = 1; if (!error && (error = dev_wlc_intvar_set(dev, "auth", val))) return error; break; case IW_AUTH_WPA_ENABLED: if (paramval == 0) { iw->privacy_invoked = 0; iw->pcipher = 0; iw->gcipher = 0; val = <API key>(dev); if ((error = dev_wlc_intvar_set(dev, "wsec", val))) return error; WL_INFORM(("%s: %d: setting wpa_auth to %d, wsec to %d\n", __FUNCTION__, __LINE__, paramval, val)); dev_wlc_intvar_set(dev, "wpa_auth", paramval); return error; } break; case IW_<API key>: if ((error = dev_wlc_intvar_set(dev, "wsec_restrict", paramval))) return error; break; case IW_<API key>: dev_wlc_bufvar_set(dev, "<API key>", (char *)&paramval, 1); break; #if WIRELESS_EXT > 17 case IW_<API key>: WL_INFORM(("%s: IW_<API key>\n", __FUNCTION__)); break; case IW_<API key>: iw->privacy_invoked = paramval; val = <API key>(dev); if ((error = dev_wlc_intvar_set(dev, "wsec", val))) return error; break; #endif default: break; } return 0; } #define VAL_PSK(_val) (((_val) & WPA_AUTH_PSK) || ((_val) & WPA2_AUTH_PSK)) static int wl_iw_get_wpaauth( struct net_device *dev, struct iw_request_info *info, struct iw_param *vwrq, char *extra ) { int error; int paramid; int paramval = 0; int val; wl_iw_t *iw = NETDEV_PRIV(dev); WL_TRACE(("%s: SIOCGIWAUTH\n", dev->name)); paramid = vwrq->flags & IW_AUTH_INDEX; switch (paramid) { case IW_AUTH_WPA_VERSION: paramval = iw->wpaversion; break; case IW_<API key>: paramval = iw->pcipher; break; case <API key>: paramval = iw->gcipher; break; case IW_AUTH_KEY_MGMT: if ((error = dev_wlc_intvar_get(dev, "wpa_auth", &val))) return error; if (VAL_PSK(val)) paramval = <API key>; else paramval = IW_<API key>; break; case IW_<API key>: dev_wlc_bufvar_get(dev, "<API key>", (char *)&paramval, 1); break; case IW_<API key>: dev_wlc_intvar_get(dev, "wsec_restrict", &paramval); break; case IW_<API key>: dev_wlc_bufvar_get(dev, "<API key>", (char *)&paramval, 1); break; case <API key>: if ((error = dev_wlc_intvar_get(dev, "auth", &val))) return error; if (!val) paramval = IW_<API key>; else paramval = <API key>; break; case IW_AUTH_WPA_ENABLED: if ((error = dev_wlc_intvar_get(dev, "wpa_auth", &val))) return error; if (val) paramval = TRUE; else paramval = FALSE; break; #if WIRELESS_EXT > 17 case IW_<API key>: WL_ERROR(("%s: IW_<API key>\n", __FUNCTION__)); break; case IW_<API key>: paramval = iw->privacy_invoked; break; #endif } vwrq->value = paramval; return 0; } #endif #ifdef SOFTAP static int ap_macmode = <API key>; static struct mflist ap_black_list; static int wl_iw_parse_wep(char *keystr, wl_wsec_key_t *key) { char hex[] = "XX"; unsigned char *data = key->data; switch (strlen(keystr)) { case 5: case 13: case 16: key->len = strlen(keystr); memcpy(data, keystr, key->len + 1); break; case 12: case 28: case 34: case 66: if (!strnicmp(keystr, "0x", 2)) keystr += 2; else return -1; case 10: case 26: case 32: case 64: key->len = strlen(keystr) / 2; while (*keystr) { strncpy(hex, keystr, 2); *data++ = (char) bcm_strtoul(hex, NULL, 16); keystr += 2; } break; default: return -1; } switch (key->len) { case 5: key->algo = CRYPTO_ALGO_WEP1; break; case 13: key->algo = CRYPTO_ALGO_WEP128; break; case 16: key->algo = CRYPTO_ALGO_AES_CCM; break; case 32: key->algo = CRYPTO_ALGO_TKIP; break; default: return -1; } key->flags |= WL_PRIMARY_KEY; return 0; } #ifdef EXT_WPA_CRYPTO #define SHA1HashSize 20 extern void pbkdf2_sha1(const char *passphrase, const char *ssid, size_t ssid_len, int iterations, u8 *buf, size_t buflen); #else #define SHA1HashSize 20 static int pbkdf2_sha1(const char *passphrase, const char *ssid, size_t ssid_len, int iterations, u8 *buf, size_t buflen) { WL_ERROR(("WARNING: %s is not implemented !!!\n", __FUNCTION__)); return -1; } #endif static int <API key>(struct net_device *dev, int val) { struct { int cfg; int val; } bss_setbuf; int bss_set_res; char smbuf[WLC_IOCTL_SMLEN]; memset(smbuf, 0, sizeof(smbuf)); bss_setbuf.cfg = 1; bss_setbuf.val = val; bss_set_res = dev_iw_iovar_setbuf(dev, "bss", &bss_setbuf, sizeof(bss_setbuf), smbuf, sizeof(smbuf)); WL_TRACE(("%s: bss_set_result:%d set with %d\n", __FUNCTION__, bss_set_res, val)); return bss_set_res; } #ifndef AP_ONLY static int wl_bssiovar_mkbuf( const char *iovar, int bssidx, void *param, int paramlen, void *bufptr, int buflen, int *perr) { const char *prefix = "bsscfg:"; int8* p; uint prefixlen; uint namelen; uint iolen; prefixlen = strlen(prefix); namelen = strlen(iovar) + 1; iolen = prefixlen + namelen + sizeof(int) + paramlen; if (buflen < 0 || iolen > (uint)buflen) { *perr = BCME_BUFTOOSHORT; return 0; } p = (int8*)bufptr; memcpy(p, prefix, prefixlen); p += prefixlen; memcpy(p, iovar, namelen); p += namelen; bssidx = htod32(bssidx); memcpy(p, &bssidx, sizeof(int32)); p += sizeof(int32); if (paramlen) memcpy(p, param, paramlen); *perr = 0; return iolen; } #endif #define strtoul(nptr, endptr, base) bcm_strtoul((nptr), (endptr), (base)) #if defined(CSCAN) static int <API key>(struct net_device *dev, wlc_ssid_t* ssids_local, int nssid, int nchan) { int params_size = <API key> + WL_NUMCHANNELS * sizeof(uint16); int err = 0; char *p; int i; iscan_info_t *iscan = g_iscan; WL_TRACE(("%s nssid=%d nchan=%d\n", __FUNCTION__, nssid, nchan)); if ((!dev) && (!g_iscan) && (!iscan->iscan_ex_params_p)) { WL_ERROR(("%s error exit\n", __FUNCTION__)); err = -1; goto exit; } #ifdef PNO_SUPPORT if (<API key>(dev)) { WL_ERROR(("%s: Scan called when PNO is active\n", __FUNCTION__)); } #endif params_size += <API key> * sizeof(wlc_ssid_t); if (nssid > 0) { i = OFFSETOF(wl_scan_params_t, channel_list) + nchan * sizeof(uint16); i = ROUNDUP(i, sizeof(uint32)); if (i + nssid * sizeof(wlc_ssid_t) > params_size) { printf("additional ssids exceed params_size\n"); err = -1; goto exit; } p = ((char*)&iscan->iscan_ex_params_p->params) + i; memcpy(p, ssids_local, nssid * sizeof(wlc_ssid_t)); p += nssid * sizeof(wlc_ssid_t); } else { p = (char*)iscan->iscan_ex_params_p->params.channel_list + nchan * sizeof(uint16); } iscan->iscan_ex_params_p->params.channel_num = htod32((nssid << <API key>) | (nchan & <API key>)); nssid = (uint) ((iscan->iscan_ex_params_p->params.channel_num >> <API key>) & <API key>); params_size = (int) (p - (char*)iscan->iscan_ex_params_p + nssid * sizeof(wlc_ssid_t)); iscan->iscan_ex_param_size = params_size; iscan->list_cur = iscan->list_hdr; iscan->iscan_state = ISCAN_STATE_SCANING; <API key>(dev); mod_timer(&iscan->timer, jiffies + msecs_to_jiffies(iscan->timer_ms)); iscan->timer_on = 1; #ifdef SCAN_DUMP { int i; WL_SCAN(("\n for (i = 0; i < nssid; i++) { if (!ssids_local[i].SSID_len) WL_SCAN(("%d: Broadcast scan\n", i)); else WL_SCAN(("%d: scan for %s size =%d\n", i, ssids_local[i].SSID, ssids_local[i].SSID_len)); } WL_SCAN((" for (i = 0; i < nchan; i++) { WL_SCAN(("%d ", iscan->iscan_ex_params_p->params.channel_list[i])); } WL_SCAN(("\nnprobes=%d\n", iscan->iscan_ex_params_p->params.nprobes)); WL_SCAN(("active_time=%d\n", iscan->iscan_ex_params_p->params.active_time)); WL_SCAN(("passive_time=%d\n", iscan->iscan_ex_params_p->params.passive_time)); WL_SCAN(("home_time=%d\n", iscan->iscan_ex_params_p->params.home_time)); WL_SCAN(("scan_type=%d\n", iscan->iscan_ex_params_p->params.scan_type)); WL_SCAN(("\n } #endif if (params_size > WLC_IOCTL_MEDLEN) { WL_ERROR(("Set ISCAN for %s due to params_size=%d \n", __FUNCTION__, params_size)); err = -1; } if ((err = dev_iw_iovar_setbuf(dev, "iscan", iscan->iscan_ex_params_p, iscan->iscan_ex_param_size, iscan->ioctlbuf, sizeof(iscan->ioctlbuf)))) { WL_TRACE(("Set ISCAN for %s failed with %d\n", __FUNCTION__, err)); err = -1; } exit: return err; } static int iwpriv_set_cscan(struct net_device *dev, struct iw_request_info *info, union iwreq_data *wrqu, char *ext) { int res; char *extra = NULL; iscan_info_t *iscan = g_iscan; wlc_ssid_t ssids_local[<API key>]; int nssid = 0; int nchan = 0; char *str_ptr; WL_TRACE(("%s: info->cmd:%x, info->flags:%x, u.data=0x%p, u.len=%d\n", __FUNCTION__, info->cmd, info->flags, wrqu->data.pointer, wrqu->data.length)); if (g_onoff == G_WLAN_SET_OFF) { WL_TRACE(("%s: driver is not up yet after START\n", __FUNCTION__)); return -ENODEV; } if (wrqu->data.length == 0) { WL_ERROR(("IWPRIV argument len = 0\n")); return -EINVAL; } if (!iscan->iscan_ex_params_p) { return -EFAULT; } if (!(extra = kmalloc(wrqu->data.length+1, GFP_KERNEL))) return -ENOMEM; if (copy_from_user(extra, wrqu->data.pointer, wrqu->data.length)) { res = -EFAULT; goto exit_proc; } extra[wrqu->data.length] = 0; WL_ERROR(("Got str param in iw_point:\n %s\n", extra)); str_ptr = extra; if (strncmp(str_ptr, GET_SSID, strlen(GET_SSID))) { WL_ERROR(("%s Error: extracting SSID='' string\n", __FUNCTION__)); res = -EINVAL; goto exit_proc; } str_ptr += strlen(GET_SSID); nssid = <API key>(&str_ptr, ssids_local, nssid, <API key>); if (nssid == -1) { WL_ERROR(("%s wrong ssid list", __FUNCTION__)); res = -EINVAL; goto exit_proc; } memset(iscan->iscan_ex_params_p, 0, iscan->iscan_ex_param_size); ASSERT(iscan->iscan_ex_param_size < WLC_IOCTL_MAXLEN); wl_iw_iscan_prep(&iscan->iscan_ex_params_p->params, NULL); iscan->iscan_ex_params_p->version = htod32(ISCAN_REQ_VERSION); iscan->iscan_ex_params_p->action = htod16(<API key>); iscan->iscan_ex_params_p->scan_duration = htod16(0); if ((nchan = <API key>(&str_ptr, &iscan->iscan_ex_params_p->params.channel_list[0], WL_NUMCHANNELS)) == -1) { WL_ERROR(("%s missing channel list\n", __FUNCTION__)); res = -EINVAL; goto exit_proc; } <API key>(&str_ptr, GET_NPROBE, PTYPE_INTDEC, &iscan->iscan_ex_params_p->params.nprobes, 2); <API key>(&str_ptr, <API key>, PTYPE_INTDEC, &iscan->iscan_ex_params_p->params.active_time, 4); <API key>(&str_ptr, <API key>, PTYPE_INTDEC, &iscan->iscan_ex_params_p->params.passive_time, 4); <API key>(&str_ptr, GET_HOME_DWELL, PTYPE_INTDEC, &iscan->iscan_ex_params_p->params.home_time, 4); <API key>(&str_ptr, GET_SCAN_TYPE, PTYPE_INTDEC, &iscan->iscan_ex_params_p->params.scan_type, 1); res = <API key>(dev, ssids_local, nssid, nchan); exit_proc: kfree(extra); return res; } static int wl_iw_set_cscan( struct net_device *dev, struct iw_request_info *info, union iwreq_data *wrqu, char *extra ) { int res = -1; iscan_info_t *iscan = g_iscan; wlc_ssid_t ssids_local[<API key>]; int nssid = 0; int nchan = 0; cscan_tlv_t *cscan_tlv_temp; char type; char *str_ptr; int tlv_size_left; #ifdef TLV_DEBUG int i; char tlv_in_example[] = { 'C', 'S', 'C', 'A', 'N', ' ', 0x53, 0x01, 0x00, 0x00, 'S', 0x00, 'S', 0x04, 'B', 'R', 'C', 'M', 'C', 0x06, 'P', 0x94, 0x11, 'T', 0x01 }; #endif WL_TRACE(("\n### %s: info->cmd:%x, info->flags:%x, u.data=0x%p, u.len=%d\n", __FUNCTION__, info->cmd, info->flags, wrqu->data.pointer, wrqu->data.length)); net_os_wake_lock(dev); if (g_onoff == G_WLAN_SET_OFF) { WL_TRACE(("%s: driver is not up yet after START\n", __FUNCTION__)); return -1; } if (wrqu->data.length < (strlen(CSCAN_COMMAND) + sizeof(cscan_tlv_t))) { WL_ERROR(("%s argument=%d less %d\n", __FUNCTION__, wrqu->data.length, (int)(strlen(CSCAN_COMMAND) + sizeof(cscan_tlv_t)))); return -1; } #ifdef TLV_DEBUG memcpy(extra, tlv_in_example, sizeof(tlv_in_example)); wrqu->data.length = sizeof(tlv_in_example); for (i = 0; i < wrqu->data.length; i++) printf("%02X ", extra[i]); printf("\n"); #endif str_ptr = extra; str_ptr += strlen(CSCAN_COMMAND); tlv_size_left = wrqu->data.length - strlen(CSCAN_COMMAND); cscan_tlv_temp = (cscan_tlv_t *)str_ptr; memset(ssids_local, 0, sizeof(ssids_local)); if ((cscan_tlv_temp->prefix == CSCAN_TLV_PREFIX) && (cscan_tlv_temp->version == CSCAN_TLV_VERSION) && (cscan_tlv_temp->subver == <API key>)) { str_ptr += sizeof(cscan_tlv_t); tlv_size_left -= sizeof(cscan_tlv_t); if ((nssid = <API key>(&str_ptr, ssids_local, <API key>, &tlv_size_left)) <= 0) { WL_ERROR(("SSID is not presented or corrupted ret=%d\n", nssid)); goto exit_proc; } else { memset(iscan->iscan_ex_params_p, 0, iscan->iscan_ex_param_size); wl_iw_iscan_prep(&iscan->iscan_ex_params_p->params, NULL); iscan->iscan_ex_params_p->version = htod32(ISCAN_REQ_VERSION); iscan->iscan_ex_params_p->action = htod16(<API key>); iscan->iscan_ex_params_p->scan_duration = htod16(0); while (tlv_size_left > 0) { type = str_ptr[0]; switch (type) { case <API key>: if ((nchan = <API key>(&str_ptr, &iscan->iscan_ex_params_p->params.channel_list[0], WL_NUMCHANNELS, &tlv_size_left)) == -1) { WL_ERROR(("%s missing channel list\n", __FUNCTION__)); goto exit_proc; } break; case <API key>: if ((res = <API key>(&str_ptr, &iscan->iscan_ex_params_p->params.nprobes, sizeof(iscan->iscan_ex_params_p->params.nprobes), type, sizeof(char), &tlv_size_left)) == -1) { WL_ERROR(("%s return %d\n", __FUNCTION__, res)); goto exit_proc; } break; case <API key>: if ((res = <API key>(&str_ptr, &iscan->iscan_ex_params_p->params.active_time, sizeof(iscan->iscan_ex_params_p->params.active_time), type, sizeof(short), &tlv_size_left)) == -1) { WL_ERROR(("%s return %d\n", __FUNCTION__, res)); goto exit_proc; } break; case <API key>: if ((res = <API key>(&str_ptr, &iscan->iscan_ex_params_p->params.passive_time, sizeof(iscan->iscan_ex_params_p->params.passive_time), type, sizeof(short), &tlv_size_left)) == -1) { WL_ERROR(("%s return %d\n", __FUNCTION__, res)); goto exit_proc; } break; case <API key>: if ((res = <API key>(&str_ptr, &iscan->iscan_ex_params_p->params.home_time, sizeof(iscan->iscan_ex_params_p->params.home_time), type, sizeof(short), &tlv_size_left)) == -1) { WL_ERROR(("%s return %d\n", __FUNCTION__, res)); goto exit_proc; } break; case <API key>: if ((res = <API key>(&str_ptr, &iscan->iscan_ex_params_p->params.scan_type, sizeof(iscan->iscan_ex_params_p->params.scan_type), type, sizeof(char), &tlv_size_left)) == -1) { WL_ERROR(("%s return %d\n", __FUNCTION__, res)); goto exit_proc; } break; default : WL_ERROR(("%s get unkwown type %X\n", __FUNCTION__, type)); goto exit_proc; break; } } } } else { WL_ERROR(("%s get wrong TLV command\n", __FUNCTION__)); goto exit_proc; } #if defined(CONFIG_FIRST_SCAN) if (<API key> < <API key>) { if (++<API key> == <API key>) { WL_ERROR(("%s Clean up First scan flag which is %d\n", __FUNCTION__, <API key>)); <API key> = <API key>; } else { WL_ERROR(("%s Ignoring CSCAN : First Scan is not done yet %d\n", __FUNCTION__, <API key>)); return -EBUSY; } } #endif res = <API key>(dev, ssids_local, nssid, nchan); exit_proc: net_os_wake_unlock(dev); return res; } #endif #ifdef CONFIG_WPS2 static int <API key>( struct net_device *dev, struct iw_request_info *info, union iwreq_data *wrqu, char *extra ) { int ret; vndr_ie_setbuf_t *ie_delbuf; if (g_wps_probe_req_ie) { ie_delbuf = (vndr_ie_setbuf_t *)(g_wps_probe_req_ie + strlen("vndr_ie ")); strncpy(ie_delbuf->cmd, "del", 3); ie_delbuf->cmd[3] = '\0'; ret = dev_wlc_ioctl(dev, WLC_SET_VAR, g_wps_probe_req_ie, <API key>); if (ret) { WL_ERROR(("ioctl failed %d \n", ret)); } kfree(g_wps_probe_req_ie); g_wps_probe_req_ie = NULL; <API key> = 0; } return 0; } static int <API key>( struct net_device *dev, struct iw_request_info *info, union iwreq_data *wrqu, char *extra ) { char *str_ptr = NULL; char *bufptr = NULL; uint buflen, datalen, iecount, pktflag, iolen, total_len; int ret = 0; vndr_ie_setbuf_t *ie_setbuf = NULL; if (!g_wps_probe_req_ie) { ret = -1; str_ptr = extra; str_ptr += <API key>; datalen = wrqu->data.length - <API key>; buflen = sizeof(vndr_ie_setbuf_t) + datalen - sizeof(vndr_ie_t); ie_setbuf = (vndr_ie_setbuf_t *)kmalloc(buflen, GFP_KERNEL); if (!ie_setbuf) { WL_ERROR(("memory alloc failure ie_setbuf\n")); return ret; } memset(ie_setbuf, 0x00, buflen); strncpy(ie_setbuf->cmd, "add", VNDR_IE_CMD_LEN - 1); ie_setbuf->cmd[VNDR_IE_CMD_LEN - 1] = '\0'; iecount = htod32(1); memcpy((void *)&ie_setbuf->vndr_ie_buffer.iecount, &iecount, sizeof(int)); pktflag = 0x10; memcpy((void *)&ie_setbuf->vndr_ie_buffer.vndr_ie_list[0].pktflag, &pktflag, sizeof(uint32)); memcpy((void *)&ie_setbuf->vndr_ie_buffer.vndr_ie_list[0].vndr_ie_data, str_ptr, datalen); total_len = strlen("vndr_ie ") + buflen; bufptr = (char *)kmalloc(total_len, GFP_KERNEL); if (!bufptr) { WL_ERROR(("memory alloc failure bufptr\n")); goto fail; } iolen = bcm_mkiovar("vndr_ie", (char *)ie_setbuf, buflen, bufptr, total_len); if (iolen == 0) { WL_ERROR(("Buffer length is illegal\n")); goto fail2; } ret = dev_wlc_ioctl(dev, WLC_SET_VAR, bufptr, iolen); if (ret) { WL_ERROR(("ioctl failed\n")); goto fail2; } g_wps_probe_req_ie = (char *)kmalloc(iolen, GFP_KERNEL); if (!g_wps_probe_req_ie) { WL_ERROR(("memory alloc failure g_wps_probe_req_ie\n")); goto fail2; } memcpy(g_wps_probe_req_ie, bufptr, iolen); <API key> = iolen; } fail2: if (bufptr) { kfree(bufptr); bufptr = NULL; } fail: if (ie_setbuf) { kfree(ie_setbuf); ie_setbuf = NULL; } return ret; } #endif #ifdef SOFTAP #ifndef AP_ONLY static int <API key>(void *data) { wl_iw_t *iw; int ret = 0; unsigned long flags = 0; tsk_ctl_t *tsk_ctl = (tsk_ctl_t *)data; struct net_device *dev = (struct net_device *)tsk_ctl->parent; iw = *(wl_iw_t **)netdev_priv(dev); DAEMONIZE("wl0_eth_wthread"); WL_SOFTAP(("\n>%s threda started:, PID:%x\n", __FUNCTION__, current->pid)); #if (LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 27)) if (!iw) { WL_ERROR(("%s: dev is null\n", __FUNCTION__)); tsk_ctl->thr_pid = -1; complete(&tsk_ctl->completed); return -1; } DHD_OS_WAKE_LOCK(iw->pub); complete(&tsk_ctl->completed); if (down_timeout(&tsk_ctl->sema, msecs_to_jiffies(1000)) != 0) { #else if (down_interruptible(&tsk_ctl->sema) != 0) { #endif WL_ERROR(("\n%s: sap_eth_sema timeout \n", __FUNCTION__)); ret = -1; goto fail; } <API key>(); if (tsk_ctl->terminated) { ret = -1; goto fail; } flags = dhd_os_spin_lock(iw->pub); if (!ap_net_dev) { WL_ERROR((" ap_net_dev is null !!!")); ret = -1; dhd_os_spin_unlock(iw->pub, flags); goto fail; } WL_SOFTAP(("\n>%s: Thread:'softap ethdev IF:%s is detected!'\n\n", __FUNCTION__, ap_net_dev->name)); ap_cfg_running = TRUE; dhd_os_spin_unlock(iw->pub, flags); bcm_mdelay(500); <API key>(priv_dev, "AP_SET_CFG_OK"); fail: DHD_OS_WAKE_UNLOCK(iw->pub); WL_SOFTAP(("\n>%s, thread completed\n", __FUNCTION__)); complete_and_exit(&tsk_ctl->completed, 0); return ret; } #endif #ifndef AP_ONLY static int last_auto_channel = 6; #endif static int <API key>(struct net_device *dev, struct ap_profile *ap) { int chosen = 0; wl_uint32_list_t request; int retry = 0; int updown = 0; int ret = 0; wlc_ssid_t null_ssid; int res = 0; #ifndef AP_ONLY int iolen = 0; int mkvar_err = 0; int bsscfg_index = 1; char buf[WLC_IOCTL_SMLEN]; #endif WL_SOFTAP(("Enter %s\n", __FUNCTION__)); #ifndef AP_ONLY if (ap_cfg_running) { ap->channel = last_auto_channel; return res; } #endif memset(&null_ssid, 0, sizeof(wlc_ssid_t)); res |= dev_wlc_ioctl(dev, WLC_UP, &updown, sizeof(updown)); #ifdef AP_ONLY res |= dev_wlc_ioctl(dev, WLC_SET_SSID, &null_ssid, sizeof(null_ssid)); #else iolen = wl_bssiovar_mkbuf("ssid", bsscfg_index, (char *)(&null_ssid), null_ssid.SSID_len+4, buf, sizeof(buf), &mkvar_err); ASSERT(iolen); res |= dev_wlc_ioctl(dev, WLC_SET_VAR, buf, iolen); #endif request.count = htod32(0); ret = dev_wlc_ioctl(dev, <API key>, &request, sizeof(request)); if (ret < 0) { WL_ERROR(("can't start auto channel scan\n")); goto fail; } get_channel_retry: bcm_mdelay(350); ret = dev_wlc_ioctl(dev, WLC_GET_CHANNEL_SEL, &chosen, sizeof(chosen)); if (ret < 0 || dtoh32(chosen) == 0) { if (retry++ < 15) { goto get_channel_retry; } else { if (ret < 0) { WL_ERROR(("can't get auto channel sel, err = %d, " "chosen = 0x%04X\n", ret, (uint16)chosen)); goto fail; } else { ap->channel = (uint16)last_auto_channel; WL_ERROR(("auto channel sel timed out. we get channel %d\n", ap->channel)); } } } if (chosen) { ap->channel = (uint16)chosen & 0x00FF; WL_SOFTAP(("%s: Got auto channel = %d, attempt:%d\n", __FUNCTION__, ap->channel, retry)); } if ((res = dev_wlc_ioctl(dev, WLC_DOWN, &updown, sizeof(updown))) < 0) { WL_ERROR(("%s fail to set up err =%d\n", __FUNCTION__, res)); goto fail; } #ifndef AP_ONLY if (!res || !ret) last_auto_channel = ap->channel; #endif fail : if (ret < 0) { WL_TRACE(("%s: return value %d\n", __FUNCTION__, ret)); return ret; } return res; } static int set_ap_cfg(struct net_device *dev, struct ap_profile *ap) { int updown = 0; int channel = 0; wlc_ssid_t ap_ssid; int max_assoc = 8; int res = 0; int apsta_var = 0; #ifndef AP_ONLY int mpc = 0; int iolen = 0; int mkvar_err = 0; int bsscfg_index = 1; char buf[WLC_IOCTL_SMLEN]; #endif if (!dev) { WL_ERROR(("%s: dev is null\n", __FUNCTION__)); return -1; } net_os_wake_lock(dev); DHD_OS_MUTEX_LOCK(&wl_softap_lock); WL_SOFTAP(("wl_iw: set ap profile:\n")); WL_SOFTAP((" ssid = '%s'\n", ap->ssid)); WL_SOFTAP((" security = '%s'\n", ap->sec)); if (ap->key[0] != '\0') WL_SOFTAP((" key = '%s'\n", ap->key)); WL_SOFTAP((" channel = %d\n", ap->channel)); WL_SOFTAP((" max scb = %d\n", ap->max_scb)); #ifdef AP_ONLY if (ap_cfg_running) { <API key>(dev, NULL); ap_cfg_running = FALSE; } #endif if (ap_cfg_running == FALSE) { #ifndef AP_ONLY sema_init(&ap_eth_ctl.sema, 0); mpc = 0; if ((res = dev_wlc_intvar_set(dev, "mpc", mpc))) { WL_ERROR(("%s fail to set mpc\n", __FUNCTION__)); goto fail; } #endif updown = 0; if ((res = dev_wlc_ioctl(dev, WLC_DOWN, &updown, sizeof(updown)))) { WL_ERROR(("%s fail to set updown\n", __FUNCTION__)); goto fail; } #ifdef AP_ONLY apsta_var = 0; if ((res = dev_wlc_ioctl(dev, WLC_SET_AP, &apsta_var, sizeof(apsta_var)))) { WL_ERROR(("%s fail to set apsta_var 0\n", __FUNCTION__)); goto fail; } apsta_var = 1; if ((res = dev_wlc_ioctl(dev, WLC_SET_AP, &apsta_var, sizeof(apsta_var)))) { WL_ERROR(("%s fail to set apsta_var 1\n", __FUNCTION__)); goto fail; } res = dev_wlc_ioctl(dev, WLC_GET_AP, &apsta_var, sizeof(apsta_var)); #else apsta_var = 1; iolen = wl_bssiovar_mkbuf("apsta", bsscfg_index, &apsta_var, sizeof(apsta_var)+4, buf, sizeof(buf), &mkvar_err); ASSERT(iolen); if ((res = dev_wlc_ioctl(dev, WLC_SET_VAR, buf, iolen)) < 0) { WL_ERROR(("%s fail to set apsta \n", __FUNCTION__)); goto fail; } WL_TRACE(("\n>in %s: apsta set result: %d \n", __FUNCTION__, res)); mpc = 0; if ((res = dev_wlc_intvar_set(dev, "mpc", mpc))) { WL_ERROR(("%s fail to set mpc\n", __FUNCTION__)); goto fail; } #endif updown = 1; if ((res = dev_wlc_ioctl(dev, WLC_UP, &updown, sizeof(updown))) < 0) { WL_ERROR(("%s fail to set apsta \n", __FUNCTION__)); goto fail; } } else { if (!ap_net_dev) { WL_ERROR(("%s: ap_net_dev is null\n", __FUNCTION__)); goto fail; } res = <API key>(ap_net_dev, NULL); if ((res = <API key>(dev, 0)) < 0) { WL_ERROR(("%s fail to set bss down\n", __FUNCTION__)); goto fail; } } if (strlen(ap->country_code)) { WL_ERROR(("%s: Igonored: Country MUST be specified" "COUNTRY command with \n", __FUNCTION__)); } else { WL_SOFTAP(("%s: Country code is not specified," " will use Radio's default\n", __FUNCTION__)); } iolen = wl_bssiovar_mkbuf("closednet", bsscfg_index, &ap->closednet, sizeof(ap->closednet)+4, buf, sizeof(buf), &mkvar_err); ASSERT(iolen); if ((res = dev_wlc_ioctl(dev, WLC_SET_VAR, buf, iolen)) < 0) { WL_ERROR(("%s failed to set 'closednet'for apsta \n", __FUNCTION__)); goto fail; } if ((ap->channel == 0) && (<API key>(dev, ap) < 0)) { ap->channel = 1; WL_ERROR(("%s auto channel failed, use channel=%d\n", __FUNCTION__, ap->channel)); } channel = ap->channel; if ((res = dev_wlc_ioctl(dev, WLC_SET_CHANNEL, &channel, sizeof(channel)))) { WL_ERROR(("%s fail to set channel\n", __FUNCTION__)); } if (ap_cfg_running == FALSE) { updown = 0; if ((res = dev_wlc_ioctl(dev, WLC_UP, &updown, sizeof(updown)))) { WL_ERROR(("%s fail to set up\n", __FUNCTION__)); goto fail; } } max_assoc = ap->max_scb; if ((res = dev_wlc_intvar_set(dev, "maxassoc", max_assoc))) { WL_ERROR(("%s fail to set maxassoc\n", __FUNCTION__)); goto fail; } ap_ssid.SSID_len = strlen(ap->ssid); strncpy(ap_ssid.SSID, ap->ssid, ap_ssid.SSID_len); #ifdef AP_ONLY if ((res = <API key>(dev, &my_ap)) != 0) { WL_ERROR(("ERROR:%d in:%s, <API key> is skipped\n", res, __FUNCTION__)); goto fail; } <API key>(dev, "ASCII_CMD=AP_BSS_START"); ap_cfg_running = TRUE; #else iolen = wl_bssiovar_mkbuf("ssid", bsscfg_index, (char *)(&ap_ssid), ap_ssid.SSID_len+4, buf, sizeof(buf), &mkvar_err); ASSERT(iolen); if ((res = dev_wlc_ioctl(dev, WLC_SET_VAR, buf, iolen)) != 0) { WL_ERROR(("ERROR:%d in:%s, Security & BSS reconfiguration is skipped\n", res, __FUNCTION__)); goto fail; } if (ap_cfg_running == FALSE) { PROC_START(<API key>, dev, &ap_eth_ctl, 0); } else { ap_eth_ctl.thr_pid = -1; if (ap_net_dev == NULL) { WL_ERROR(("%s ERROR: ap_net_dev is NULL !!!\n", __FUNCTION__)); goto fail; } WL_ERROR(("%s: %s Configure security & restart AP bss \n", __FUNCTION__, ap_net_dev->name)); if ((res = <API key>(ap_net_dev, &my_ap)) < 0) { WL_ERROR(("%s fail to set security : %d\n", __FUNCTION__, res)); goto fail; } if ((res = <API key>(dev, 1)) < 0) { WL_ERROR(("%s fail to set bss up\n", __FUNCTION__)); goto fail; } } #endif fail: WL_SOFTAP(("%s exit with %d\n", __FUNCTION__, res)); DHD_OS_MUTEX_UNLOCK(&wl_softap_lock); net_os_wake_unlock(dev); return res; } #endif static int <API key>(struct net_device *dev, struct ap_profile *ap) { int wsec = 0; int wpa_auth = 0; int res = 0; int i; char *ptr; #ifdef AP_ONLY int mpc = 0; wlc_ssid_t ap_ssid; #endif wl_wsec_key_t key; WL_SOFTAP(("\nsetting SOFTAP security mode:\n")); WL_SOFTAP(("wl_iw: set ap profile:\n")); WL_SOFTAP((" ssid = '%s'\n", ap->ssid)); WL_SOFTAP((" security = '%s'\n", ap->sec)); if (ap->key[0] != '\0') WL_SOFTAP((" key = '%s'\n", ap->key)); WL_SOFTAP((" channel = %d\n", ap->channel)); WL_SOFTAP((" max scb = %d\n", ap->max_scb)); if (strnicmp(ap->sec, "open", strlen("open")) == 0) { wsec = 0; res = dev_wlc_intvar_set(dev, "wsec", wsec); wpa_<API key>; res |= dev_wlc_intvar_set(dev, "wpa_auth", wpa_auth); WL_SOFTAP(("=====================\n")); WL_SOFTAP((" wsec & wpa_auth set 'OPEN', result:&d %d\n", res)); WL_SOFTAP(("=====================\n")); } else if (strnicmp(ap->sec, "wep", strlen("wep")) == 0) { memset(&key, 0, sizeof(key)); wsec = WEP_ENABLED; res = dev_wlc_intvar_set(dev, "wsec", wsec); key.index = 0; if (wl_iw_parse_wep(ap->key, &key)) { WL_SOFTAP(("wep key parse err!\n")); return -1; } key.index = htod32(key.index); key.len = htod32(key.len); key.algo = htod32(key.algo); key.flags = htod32(key.flags); res |= dev_wlc_ioctl(dev, WLC_SET_KEY, &key, sizeof(key)); wpa_<API key>; res |= dev_wlc_intvar_set(dev, "wpa_auth", wpa_auth); WL_SOFTAP(("=====================\n")); WL_SOFTAP((" wsec & auth set 'WEP', result:&d %d\n", res)); WL_SOFTAP(("=====================\n")); } else if (strnicmp(ap->sec, "wpa2-psk", strlen("wpa2-psk")) == 0) { wsec_pmk_t psk; size_t key_len; wsec = AES_ENABLED; dev_wlc_intvar_set(dev, "wsec", wsec); key_len = strlen(ap->key); if (key_len < WSEC_MIN_PSK_LEN || key_len > WSEC_MAX_PSK_LEN) { WL_SOFTAP(("passphrase must be between %d and %d characters long\n", WSEC_MIN_PSK_LEN, WSEC_MAX_PSK_LEN)); return -1; } if (key_len < WSEC_MAX_PSK_LEN) { unsigned char output[2*SHA1HashSize]; char key_str_buf[WSEC_MAX_PSK_LEN+1]; memset(output, 0, sizeof(output)); pbkdf2_sha1(ap->key, ap->ssid, strlen(ap->ssid), 4096, output, 32); ptr = key_str_buf; for (i = 0; i < (WSEC_MAX_PSK_LEN/8); i++) { sprintf(ptr, "%02x%02x%02x%02x", (uint)output[i*4], (uint)output[i*4+1], (uint)output[i*4+2], (uint)output[i*4+3]); ptr += 8; } WL_SOFTAP(("%s: passphase = %s\n", __FUNCTION__, key_str_buf)); psk.key_len = htod16((ushort)WSEC_MAX_PSK_LEN); memcpy(psk.key, key_str_buf, psk.key_len); } else { psk.key_len = htod16((ushort) key_len); memcpy(psk.key, ap->key, key_len); } psk.flags = htod16(WSEC_PASSPHRASE); dev_wlc_ioctl(dev, WLC_SET_WSEC_PMK, &psk, sizeof(psk)); wpa_auth = WPA2_AUTH_PSK; dev_wlc_intvar_set(dev, "wpa_auth", wpa_auth); } else if (strnicmp(ap->sec, "wpa-psk", strlen("wpa-psk")) == 0) { wsec_pmk_t psk; size_t key_len; wsec = TKIP_ENABLED; res = dev_wlc_intvar_set(dev, "wsec", wsec); key_len = strlen(ap->key); if (key_len < WSEC_MIN_PSK_LEN || key_len > WSEC_MAX_PSK_LEN) { WL_SOFTAP(("passphrase must be between %d and %d characters long\n", WSEC_MIN_PSK_LEN, WSEC_MAX_PSK_LEN)); return -1; } if (key_len < WSEC_MAX_PSK_LEN) { unsigned char output[2*SHA1HashSize]; char key_str_buf[WSEC_MAX_PSK_LEN+1]; bzero(output, 2*SHA1HashSize); WL_SOFTAP(("%s: do passhash...\n", __FUNCTION__)); pbkdf2_sha1(ap->key, ap->ssid, strlen(ap->ssid), 4096, output, 32); ptr = key_str_buf; for (i = 0; i < (WSEC_MAX_PSK_LEN/8); i++) { WL_SOFTAP(("[%02d]: %08x\n", i, *((unsigned int*)&output[i*4]))); sprintf(ptr, "%02x%02x%02x%02x", (uint)output[i*4], (uint)output[i*4+1], (uint)output[i*4+2], (uint)output[i*4+3]); ptr += 8; } printk("%s: passphase = %s\n", __FUNCTION__, key_str_buf); psk.key_len = htod16((ushort)WSEC_MAX_PSK_LEN); memcpy(psk.key, key_str_buf, psk.key_len); } else { psk.key_len = htod16((ushort) key_len); memcpy(psk.key, ap->key, key_len); } psk.flags = htod16(WSEC_PASSPHRASE); res |= dev_wlc_ioctl(dev, WLC_SET_WSEC_PMK, &psk, sizeof(psk)); wpa_auth = WPA_AUTH_PSK; res |= dev_wlc_intvar_set(dev, "wpa_auth", wpa_auth); WL_SOFTAP((" wsec & auth set 'wpa-psk' (TKIP), result:&d %d\n", res)); } #ifdef AP_ONLY ap_ssid.SSID_len = strlen(ap->ssid); strncpy(ap_ssid.SSID, ap->ssid, ap_ssid.SSID_len); res |= dev_wlc_ioctl(dev, WLC_SET_SSID, &ap_ssid, sizeof(ap_ssid)); mpc = 0; res |= dev_wlc_intvar_set(dev, "mpc", mpc); if (strnicmp(ap->sec, "wep", strlen("wep")) == 0) { res |= dev_wlc_ioctl(dev, WLC_SET_KEY, &key, sizeof(key)); } #endif return res; } static int <API key>( char **str_ptr, const char *token, int param_type, void *dst, int param_max_len) { char int_str[7] = "0"; int parm_str_len; char *param_str_begin; char *param_str_end; char *orig_str = *str_ptr; if ((*str_ptr) && !strncmp(*str_ptr, token, strlen(token))) { strsep(str_ptr, "=,"); param_str_begin = *str_ptr; strsep(str_ptr, "=,"); if (*str_ptr == NULL) { parm_str_len = strlen(param_str_begin); } else { param_str_end = *str_ptr-1; parm_str_len = param_str_end - param_str_begin; } WL_TRACE((" 'token:%s', len:%d, ", token, parm_str_len)); if (parm_str_len > param_max_len) { WL_ERROR((" WARNING: extracted param len:%d is > MAX:%d\n", parm_str_len, param_max_len)); parm_str_len = param_max_len; } switch (param_type) { case PTYPE_INTDEC: { int *pdst_int = dst; char *eptr; if (parm_str_len > sizeof(int_str)) parm_str_len = sizeof(int_str); memcpy(int_str, param_str_begin, parm_str_len); *pdst_int = simple_strtoul(int_str, &eptr, 10); WL_TRACE((" written as integer:%d\n", *pdst_int)); } break; case PTYPE_STR_HEX: { u8 *buf = dst; param_max_len = param_max_len >> 1; hstr_2_buf(param_str_begin, buf, param_max_len); dhd_print_buf(buf, param_max_len, 0); } break; default: memcpy(dst, param_str_begin, parm_str_len); *((char *)dst + parm_str_len) = 0; WL_ERROR((" written as a string:%s\n", (char *)dst)); break; } return 0; } else { WL_ERROR(("\n %s: ERROR: can't find token:%s in str:%s \n", __FUNCTION__, token, orig_str)); return -1; } } static int <API key>(struct net_device *dev, u8 *mac) { int i; int res = 0; char mac_buf[128] = {0}; char z_mac[6] = {0, 0, 0, 0, 0, 0}; char *sta_mac; struct maclist *assoc_maclist = (struct maclist *) mac_buf; bool deauth_all = FALSE; if (mac == NULL) { deauth_all = TRUE; sta_mac = z_mac; } else { sta_mac = mac; } memset(assoc_maclist, 0, sizeof(mac_buf)); assoc_maclist->count = 8; res = dev_wlc_ioctl(dev, WLC_GET_ASSOCLIST, assoc_maclist, 128); if (res != 0) { WL_SOFTAP(("%s: Error:%d Couldn't get ASSOC List\n", __FUNCTION__, res)); return res; } if (assoc_maclist->count) for (i = 0; i < assoc_maclist->count; i++) { scb_val_t scbval; scbval.val = htod32(1); bcopy(&assoc_maclist->ea[i], &scbval.ea, ETHER_ADDR_LEN); if (deauth_all || (memcmp(&scbval.ea, sta_mac, ETHER_ADDR_LEN) == 0)) { WL_SOFTAP(("%s, deauth STA:%d \n", __FUNCTION__, i)); res |= dev_wlc_ioctl(dev, WLC_SCB_DE<API key>, &scbval, sizeof(scb_val_t)); } } else WL_SOFTAP(("%s: No Stations \n", __FUNCTION__)); if (res != 0) { WL_ERROR(("%s: Error:%d\n", __FUNCTION__, res)); } else if (assoc_maclist->count) { bcm_mdelay(200); } return res; } static int iwpriv_softap_stop(struct net_device *dev, struct iw_request_info *info, union iwreq_data *wrqu, char *ext) { int res = 0; WL_SOFTAP(("got iwpriv AP_BSS_STOP \n")); if ((!dev) && (!ap_net_dev)) { WL_ERROR(("%s: dev is null\n", __FUNCTION__)); return res; } net_os_wake_lock(dev); DHD_OS_MUTEX_LOCK(&wl_softap_lock); if ((ap_cfg_running == TRUE)) { #ifdef AP_ONLY <API key>(dev, NULL); #else <API key>(ap_net_dev, NULL); if ((res = <API key>(dev, 2)) < 0) WL_ERROR(("%s failed to del BSS err = %d", __FUNCTION__, res)); #endif bcm_mdelay(100); wrqu->data.length = 0; ap_cfg_running = FALSE; } else WL_ERROR(("%s: was called when SoftAP is OFF : move on\n", __FUNCTION__)); WL_SOFTAP(("%s Done with %d\n", __FUNCTION__, res)); DHD_OS_MUTEX_UNLOCK(&wl_softap_lock); net_os_wake_unlock(dev); return res; } static int iwpriv_fw_reload(struct net_device *dev, struct iw_request_info *info, union iwreq_data *wrqu, char *ext) { int ret = -1; char extra[256]; char *fwstr = fw_path ; WL_SOFTAP(("current firmware_path[]=%s\n", fwstr)); WL_TRACE((">Got FW_RELOAD cmd:" "info->cmd:%x, info->flags:%x, u.data:%p, u.len:%d, " "fw_path:%p, len:%d \n", info->cmd, info->flags, wrqu->data.pointer, wrqu->data.length, fwstr, strlen(fwstr))); if ((wrqu->data.length > 4) && (wrqu->data.length < sizeof(extra))) { char *str_ptr; if (copy_from_user(extra, wrqu->data.pointer, wrqu->data.length)) { ret = -EFAULT; goto exit_proc; } extra[wrqu->data.length] = 8; str_ptr = extra; if (<API key>(&str_ptr, "FW_PATH=", PTYPE_STRING, fwstr, 255) != 0) { WL_ERROR(("Error: extracting FW_PATH='' string\n")); goto exit_proc; } if (strstr(fwstr, "apsta") != NULL) { WL_SOFTAP(("GOT APSTA FIRMWARE\n")); ap_fw_loaded = TRUE; } else { WL_SOFTAP(("GOT STA FIRMWARE\n")); ap_fw_loaded = FALSE; } WL_SOFTAP(("SET firmware_path[]=%s , str_p:%p\n", fwstr, fwstr)); ret = 0; } else { WL_ERROR(("Error: ivalid param len:%d\n", wrqu->data.length)); } exit_proc: return ret; } #ifdef SOFTAP static int <API key>(struct net_device *dev, struct iw_request_info *info, union iwreq_data *wrqu, char *ext) { int res = 0; char *params = NULL; WL_TRACE((">Got IWPRIV wp_supp loopback cmd test:" "info->cmd:%x, info->flags:%x, u.data:%p, u.len:%d\n", info->cmd, info->flags, wrqu->data.pointer, wrqu->data.length)); if (wrqu->data.length != 0) { if (!(params = kmalloc(wrqu->data.length+1, GFP_KERNEL))) return -ENOMEM; if (copy_from_user(params, wrqu->data.pointer, wrqu->data.length)) { kfree(params); return -EFAULT; } params[wrqu->data.length] = 0; WL_SOFTAP(("\n>> copied from user:\n %s\n", params)); } else { WL_ERROR(("ERROR param length is 0\n")); return -EFAULT; } res = <API key>(dev, params); kfree(params); return res; } #endif static int iwpriv_en_ap_bss( struct net_device *dev, struct iw_request_info *info, void *wrqu, char *extra) { int res = 0; if (!dev) { WL_ERROR(("%s: dev is null\n", __FUNCTION__)); return -1; } net_os_wake_lock(dev); DHD_OS_MUTEX_LOCK(&wl_softap_lock); WL_TRACE(("%s: rcvd IWPRIV IOCTL: for dev:%s\n", __FUNCTION__, dev->name)); #ifndef AP_ONLY if ((res = <API key>(dev, &my_ap)) != 0) { WL_ERROR((" %s ERROR setting SOFTAP security in :%d\n", __FUNCTION__, res)); } else { if ((res = <API key>(dev, 1)) < 0) WL_ERROR(("%s fail to set bss up err=%d\n", __FUNCTION__, res)); else bcm_mdelay(100); } #endif WL_SOFTAP(("%s done with res %d \n", __FUNCTION__, res)); DHD_OS_MUTEX_UNLOCK(&wl_softap_lock); net_os_wake_unlock(dev); return res; } static int get_assoc_sta_list(struct net_device *dev, char *buf, int len) { WL_TRACE(("%s: dev_wlc_ioctl(dev:%p, cmd:%d, buf:%p, len:%d)\n", __FUNCTION__, dev, WLC_GET_ASSOCLIST, buf, len)); return dev_wlc_ioctl(dev, WLC_GET_ASSOCLIST, buf, len); } void check_error(int res, const char *msg, const char *func, int line) { if (res != 0) WL_ERROR(("%s, %d function:%s, line:%d\n", msg, res, func, line)); } static int set_ap_mac_list(struct net_device *dev, void *buf) { struct mac_list_set *mac_list_set = (struct mac_list_set *)buf; struct maclist *maclist = (struct maclist *)&mac_list_set->mac_list; int length; int i; int mac_mode = mac_list_set->mode; int ioc_res = 0; ap_macmode = mac_list_set->mode; bzero(&ap_black_list, sizeof(struct mflist)); if (mac_mode == <API key>) { ioc_res = dev_wlc_ioctl(dev, WLC_SET_MACMODE, &mac_mode, sizeof(mac_mode)); check_error(ioc_res, "ioctl ERROR:", __FUNCTION__, __LINE__); WL_SOFTAP(("%s: MAC filtering disabled\n", __FUNCTION__)); } else { scb_val_t scbval; char mac_buf[256] = {0}; struct maclist *assoc_maclist = (struct maclist *) mac_buf; bcopy(maclist, &ap_black_list, sizeof(ap_black_list)); ioc_res = dev_wlc_ioctl(dev, WLC_SET_MACMODE, &mac_mode, sizeof(mac_mode)); check_error(ioc_res, "ioctl ERROR:", __FUNCTION__, __LINE__); length = sizeof(maclist->count) + maclist->count*ETHER_ADDR_LEN; dev_wlc_ioctl(dev, WLC_SET_MACLIST, maclist, length); WL_SOFTAP(("%s: applied MAC List, mode:%d, length %d:\n", __FUNCTION__, mac_mode, length)); for (i = 0; i < maclist->count; i++) WL_SOFTAP(("mac %d: %02X:%02X:%02X:%02X:%02X:%02X\n", i, maclist->ea[i].octet[0], maclist->ea[i].octet[1], maclist->ea[i].octet[2], maclist->ea[i].octet[3], maclist->ea[i].octet[4], maclist->ea[i].octet[5])); assoc_maclist->count = 8; ioc_res = dev_wlc_ioctl(dev, WLC_GET_ASSOCLIST, assoc_maclist, 256); check_error(ioc_res, "ioctl ERROR:", __FUNCTION__, __LINE__); WL_SOFTAP((" Cur assoc clients:%d\n", assoc_maclist->count)); if (assoc_maclist->count) for (i = 0; i < assoc_maclist->count; i++) { int j; bool assoc_mac_matched = FALSE; WL_SOFTAP(("\n Cheking assoc STA: ")); dhd_print_buf(&assoc_maclist->ea[i], 6, 7); WL_SOFTAP(("with the b/w list:")); for (j = 0; j < maclist->count; j++) if (!bcmp(&assoc_maclist->ea[i], &maclist->ea[j], ETHER_ADDR_LEN)) { assoc_mac_matched = TRUE; break; } if (((mac_mode == MACLIST_MODE_ALLOW) && !assoc_mac_matched) || ((mac_mode == MACLIST_MODE_DENY) && assoc_mac_matched)) { WL_SOFTAP(("b-match or w-mismatch," " do deauth/disassoc \n")); scbval.val = htod32(1); bcopy(&assoc_maclist->ea[i], &scbval.ea, ETHER_ADDR_LEN); ioc_res = dev_wlc_ioctl(dev, WLC_SCB_DE<API key>, &scbval, sizeof(scb_val_t)); check_error(ioc_res, "ioctl ERROR:", __FUNCTION__, __LINE__); } else { WL_SOFTAP((" no b/w list hits, let it be\n")); } } else { WL_SOFTAP(("No ASSOC CLIENTS\n")); } } WL_SOFTAP(("%s iocres:%d\n", __FUNCTION__, ioc_res)); return ioc_res; } #endif #ifdef SOFTAP #define PARAM_OFFSET PROFILE_OFFSET static int <API key>( struct net_device *dev, struct iw_request_info *info, union iwreq_data *dwrq, char *cmd_str) { int ret = 0; char *sub_cmd = cmd_str + PROFILE_OFFSET + strlen("ASCII_CMD="); WL_SOFTAP(("\n %s: ASCII_CMD: offs_0:%s, offset_32:\n'%s'\n", __FUNCTION__, cmd_str, cmd_str + PROFILE_OFFSET)); if (strnicmp(sub_cmd, "AP_CFG", strlen("AP_CFG")) == 0) { WL_SOFTAP((" AP_CFG \n")); if (<API key>(cmd_str+PROFILE_OFFSET, &my_ap) != 0) { WL_ERROR(("ERROR: SoftAP CFG prams !\n")); ret = -1; } else { ret = set_ap_cfg(dev, &my_ap); } } else if (strnicmp(sub_cmd, "AP_BSS_START", strlen("AP_BSS_START")) == 0) { WL_SOFTAP(("\n SOFTAP - ENABLE BSS \n")); WL_SOFTAP(("\n!!! got 'WL_AP_EN_BSS' from WPA supplicant, dev:%s\n", dev->name)); #ifndef AP_ONLY if (ap_net_dev == NULL) { printf("\n ERROR: SOFTAP net_dev* is NULL !!!\n"); } else { if ((ret = iwpriv_en_ap_bss(ap_net_dev, info, dwrq, cmd_str)) < 0) WL_ERROR(("%s line %d fail to set bss up\n", __FUNCTION__, __LINE__)); } #else if ((ret = iwpriv_en_ap_bss(dev, info, dwrq, cmd_str)) < 0) WL_ERROR(("%s line %d fail to set bss up\n", __FUNCTION__, __LINE__)); #endif } else if (strnicmp(sub_cmd, "ASSOC_LST", strlen("ASSOC_LST")) == 0) { } else if (strnicmp(sub_cmd, "AP_BSS_STOP", strlen("AP_BSS_STOP")) == 0) { WL_SOFTAP((" \n temp DOWN SOFTAP\n")); #ifndef AP_ONLY if ((ret = <API key>(dev, 0)) < 0) { WL_ERROR(("%s line %d fail to set bss down\n", __FUNCTION__, __LINE__)); } #endif } return ret; } #endif static int wl_iw_set_priv( struct net_device *dev, struct iw_request_info *info, struct iw_point *dwrq, char *ext ) { int ret = 0; char * extra; if (!(extra = kmalloc(dwrq->length, GFP_KERNEL))) return -ENOMEM; if (copy_from_user(extra, dwrq->pointer, dwrq->length)) { kfree(extra); return -EFAULT; } WL_TRACE(("%s: SIOCSIWPRIV request %s, info->cmd:%x, info->flags:%d\n dwrq->length:%d\n", dev->name, extra, info->cmd, info->flags, dwrq->length)); net_os_wake_lock(dev); if (dwrq->length && extra) { if (strnicmp(extra, "START", strlen("START")) == 0) { wl_iw_control_wl_on(dev, info); WL_TRACE(("%s, Received regular START command\n", __FUNCTION__)); } if (g_onoff == G_WLAN_SET_OFF) { WL_TRACE(("%s, missing START, Fail\n", __FUNCTION__)); kfree(extra); net_os_wake_unlock(dev); return -EFAULT; } if (strnicmp(extra, "SCAN-ACTIVE", strlen("SCAN-ACTIVE")) == 0) { #ifdef <API key> WL_TRACE(("%s: active scan setting suppressed\n", dev->name)); #else ret = <API key>(dev, info, (union iwreq_data *)dwrq, extra); #endif } else if (strnicmp(extra, "SCAN-PASSIVE", strlen("SCAN-PASSIVE")) == 0) #ifdef <API key> WL_TRACE(("%s: passive scan setting suppressed\n", dev->name)); #else ret = <API key>(dev, info, (union iwreq_data *)dwrq, extra); #endif else if (strnicmp(extra, "RSSI", strlen("RSSI")) == 0) ret = wl_iw_get_rssi(dev, info, (union iwreq_data *)dwrq, extra); else if (strnicmp(extra, "LINKSPEED", strlen("LINKSPEED")) == 0) ret = <API key>(dev, info, (union iwreq_data *)dwrq, extra); else if (strnicmp(extra, "MACADDR", strlen("MACADDR")) == 0) ret = wl_iw_get_macaddr(dev, info, (union iwreq_data *)dwrq, extra); else if (strnicmp(extra, "COUNTRY", strlen("COUNTRY")) == 0) ret = wl_iw_set_country(dev, info, (union iwreq_data *)dwrq, extra); else if (strnicmp(extra, "STOP", strlen("STOP")) == 0) ret = <API key>(dev, info); else if (strnicmp(extra, BAND_GET_CMD, strlen(BAND_GET_CMD)) == 0) ret = wl_iw_get_band(dev, info, (union iwreq_data *)dwrq, extra); else if (strnicmp(extra, BAND_SET_CMD, strlen(BAND_SET_CMD)) == 0) ret = wl_iw_set_band(dev, info, (union iwreq_data *)dwrq, extra); else if (strnicmp(extra, DTIM_SKIP_GET_CMD, strlen(DTIM_SKIP_GET_CMD)) == 0) ret = wl_iw_get_dtim_skip(dev, info, (union iwreq_data *)dwrq, extra); else if (strnicmp(extra, DTIM_SKIP_SET_CMD, strlen(DTIM_SKIP_SET_CMD)) == 0) ret = wl_iw_set_dtim_skip(dev, info, (union iwreq_data *)dwrq, extra); else if (strnicmp(extra, SETSUSPENDOPT_CMD, strlen(SETSUSPENDOPT_CMD)) == 0) ret = <API key>(dev, info, (union iwreq_data *)dwrq, extra); else if (strnicmp(extra, SETSUSPENDMODE_CMD, strlen(SETSUSPENDMODE_CMD)) == 0) ret = <API key>(dev, info, (union iwreq_data *)dwrq, extra); else if (strnicmp(extra, TXPOWER_SET_CMD, strlen(TXPOWER_SET_CMD)) == 0) ret = wl_iw_set_txpower(dev, info, (union iwreq_data *)dwrq, extra); #if defined(PNO_SUPPORT) else if (strnicmp(extra, PNOSSIDCLR_SET_CMD, strlen(PNOSSIDCLR_SET_CMD)) == 0) ret = wl_iw_set_pno_reset(dev, info, (union iwreq_data *)dwrq, extra); else if (strnicmp(extra, PNOSETUP_SET_CMD, strlen(PNOSETUP_SET_CMD)) == 0) ret = wl_iw_set_pno_set(dev, info, (union iwreq_data *)dwrq, extra); else if (strnicmp(extra, PNOSETADD_SET_CMD, strlen(PNOSETADD_SET_CMD)) == 0) ret = <API key>(dev, info, (union iwreq_data *)dwrq, extra); else if (strnicmp(extra, PNOENABLE_SET_CMD, strlen(PNOENABLE_SET_CMD)) == 0) ret = <API key>(dev, info, (union iwreq_data *)dwrq, extra); #endif #if defined(CSCAN) else if (strnicmp(extra, CSCAN_COMMAND, strlen(CSCAN_COMMAND)) == 0) ret = wl_iw_set_cscan(dev, info, (union iwreq_data *)dwrq, extra); #endif #ifdef CONFIG_WPS2 else if (strnicmp(extra, <API key>, strlen(<API key>)) == 0) ret = <API key>(dev, info, (union iwreq_data *)dwrq, extra); else if (strnicmp(extra, <API key>, strlen(<API key>)) == 0) ret = <API key>(dev, info, (union iwreq_data *)dwrq, extra); #endif else if (strnicmp(extra, "POWERMODE", strlen("POWERMODE")) == 0) ret = <API key>(dev, info, (union iwreq_data *)dwrq, extra); else if (strnicmp(extra, "BTCOEXMODE", strlen("BTCOEXMODE")) == 0) ret = <API key>(dev, info, (union iwreq_data *)dwrq, extra); else if (strnicmp(extra, "GETPOWER", strlen("GETPOWER")) == 0) ret = <API key>(dev, info, (union iwreq_data *)dwrq, extra); #ifdef SOFTAP else if (strnicmp(extra, "ASCII_CMD", strlen("ASCII_CMD")) == 0) { <API key>(dev, info, (union iwreq_data *)dwrq, extra); } else if (strnicmp(extra, "AP_MAC_LIST_SET", strlen("AP_MAC_LIST_SET")) == 0) { WL_SOFTAP(("penguin, set AP_MAC_LIST_SET\n")); set_ap_mac_list(dev, (extra + PROFILE_OFFSET)); } #endif else { WL_ERROR(("Unknown PRIVATE command %s - ignored\n", extra)); snprintf(extra, MAX_WX_STRING, "OK"); dwrq->length = strlen("OK") + 1; } } net_os_wake_unlock(dev); if (extra) { if (copy_to_user(dwrq->pointer, extra, dwrq->length)) { kfree(extra); return -EFAULT; } kfree(extra); } return ret; } static const iw_handler wl_iw_handler[] = { (iw_handler) wl_iw_config_commit, (iw_handler) wl_iw_get_name, (iw_handler) NULL, (iw_handler) NULL, (iw_handler) wl_iw_set_freq, (iw_handler) wl_iw_get_freq, (iw_handler) wl_iw_set_mode, (iw_handler) wl_iw_get_mode, (iw_handler) NULL, (iw_handler) NULL, (iw_handler) NULL, (iw_handler) wl_iw_get_range, (iw_handler) wl_iw_set_priv, (iw_handler) NULL, (iw_handler) NULL, (iw_handler) NULL, (iw_handler) wl_iw_set_spy, (iw_handler) wl_iw_get_spy, (iw_handler) NULL, (iw_handler) NULL, (iw_handler) wl_iw_set_wap, (iw_handler) wl_iw_get_wap, #if WIRELESS_EXT > 17 (iw_handler) wl_iw_mlme, #else (iw_handler) NULL, #endif #if defined(WL_IW_USE_ISCAN) (iw_handler) <API key>, #else (iw_handler) wl_iw_get_aplist, #endif #if WIRELESS_EXT > 13 #if defined(WL_IW_USE_ISCAN) (iw_handler) <API key>, (iw_handler) <API key>, #else (iw_handler) wl_iw_set_scan, (iw_handler) wl_iw_get_scan, #endif #else (iw_handler) NULL, (iw_handler) NULL, #endif (iw_handler) wl_iw_set_essid, (iw_handler) wl_iw_get_essid, (iw_handler) wl_iw_set_nick, (iw_handler) wl_iw_get_nick, (iw_handler) NULL, (iw_handler) NULL, (iw_handler) wl_iw_set_rate, (iw_handler) wl_iw_get_rate, (iw_handler) wl_iw_set_rts, (iw_handler) wl_iw_get_rts, (iw_handler) wl_iw_set_frag, (iw_handler) wl_iw_get_frag, (iw_handler) wl_iw_set_txpow, (iw_handler) wl_iw_get_txpow, #if WIRELESS_EXT > 10 (iw_handler) wl_iw_set_retry, (iw_handler) wl_iw_get_retry, #endif (iw_handler) wl_iw_set_encode, (iw_handler) wl_iw_get_encode, (iw_handler) wl_iw_set_power, (iw_handler) wl_iw_get_power, #if WIRELESS_EXT > 17 (iw_handler) NULL, (iw_handler) NULL, (iw_handler) wl_iw_set_wpaie, (iw_handler) wl_iw_get_wpaie, (iw_handler) wl_iw_set_wpaauth, (iw_handler) wl_iw_get_wpaauth, (iw_handler) wl_iw_set_encodeext, (iw_handler) wl_iw_get_encodeext, (iw_handler) wl_iw_set_pmksa, #endif }; #if WIRELESS_EXT > 12 static const iw_handler wl_iw_priv_handler[] = { NULL, (iw_handler)<API key>, NULL, (iw_handler)wl_iw_get_rssi, NULL, (iw_handler)<API key>, NULL, (iw_handler)<API key>, NULL, (iw_handler)wl_iw_get_macaddr, NULL, (iw_handler)<API key>, NULL, (iw_handler)wl_iw_control_wl_on, #ifdef SOFTAP NULL, (iw_handler)<API key>, NULL, (iw_handler)<API key>, NULL, (iw_handler)<API key>, NULL, (iw_handler)iwpriv_en_ap_bss, NULL, (iw_handler)<API key>, NULL, (iw_handler)iwpriv_softap_stop, NULL, (iw_handler)iwpriv_fw_reload, NULL, (iw_handler)<API key>, #endif #if defined(CSCAN) NULL, (iw_handler)iwpriv_set_cscan #endif }; static const struct iw_priv_args wl_iw_priv_args[] = { { <API key>, 0, IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_FIXED | MAX_WX_STRING, "SCAN-ACTIVE" }, { WL_IW_GET_RSSI, 0, IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_FIXED | MAX_WX_STRING, "RSSI" }, { <API key>, 0, IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_FIXED | MAX_WX_STRING, "SCAN-PASSIVE" }, { <API key>, 0, IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_FIXED | MAX_WX_STRING, "LINKSPEED" }, { <API key>, 0, IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_FIXED | MAX_WX_STRING, "Macaddr" }, { WL_IW_SET_STOP, 0, IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_FIXED | MAX_WX_STRING, "STOP" }, { WL_IW_SET_START, 0, IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_FIXED | MAX_WX_STRING, "START" }, #ifdef SOFTAP { WL_SET_AP_CFG, IW_PRIV_TYPE_CHAR | 256, 0, "AP_SET_CFG" }, { WL_AP_STA_LIST, IW_PRIV_TYPE_CHAR | 0, IW_PRIV_TYPE_CHAR | 1024, "AP_GET_STA_LIST" }, { WL_AP_MAC_FLTR, IW_PRIV_TYPE_CHAR | 256, IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_FIXED | 0, "AP_SET_MAC_FLTR" }, { WL_AP_BSS_START, 0, IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_FIXED | MAX_WX_STRING, "AP_BSS_START" }, { AP_LPB_CMD, IW_PRIV_TYPE_CHAR | 256, IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_FIXED | 0, "AP_LPB_CMD" }, { WL_AP_STOP, IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_FIXED | 0, IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_FIXED | 0, "AP_BSS_STOP" }, { WL_FW_RELOAD, IW_PRIV_TYPE_CHAR | 256, IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_FIXED | 0, "WL_FW_RELOAD" }, #endif #if defined(CSCAN) { WL_COMBO_SCAN, IW_PRIV_TYPE_CHAR | 1024, 0, "CSCAN" }, #endif }; const struct iw_handler_def wl_iw_handler_def = { .num_standard = ARRAYSIZE(wl_iw_handler), .standard = (iw_handler *) wl_iw_handler, .num_private = ARRAYSIZE(wl_iw_priv_handler), .num_private_args = ARRAY_SIZE(wl_iw_priv_args), .private = (iw_handler *)wl_iw_priv_handler, .private_args = (void *) wl_iw_priv_args, #if WIRELESS_EXT >= 19 get_wireless_stats: <API key>, #endif }; #endif int wl_iw_ioctl( struct net_device *dev, struct ifreq *rq, int cmd ) { struct iwreq *wrq = (struct iwreq *) rq; struct iw_request_info info; iw_handler handler; char *extra = NULL; size_t token_size = 1; int max_tokens = 0, ret = 0; net_os_wake_lock(dev); WL_TRACE(("\n%s, cmd:%x called via dhd->do_ioctl()entry point\n", __FUNCTION__, cmd)); if (cmd < SIOCIWFIRST || IW_IOCTL_IDX(cmd) >= ARRAYSIZE(wl_iw_handler) || !(handler = wl_iw_handler[IW_IOCTL_IDX(cmd)])) { WL_ERROR(("%s: error in cmd=%x : not supported\n", __FUNCTION__, cmd)); net_os_wake_unlock(dev); return -EOPNOTSUPP; } switch (cmd) { case SIOCSIWESSID: case SIOCGIWESSID: case SIOCSIWNICKN: case SIOCGIWNICKN: max_tokens = IW_ESSID_MAX_SIZE + 1; break; case SIOCSIWENCODE: case SIOCGIWENCODE: #if WIRELESS_EXT > 17 case SIOCSIWENCODEEXT: case SIOCGIWENCODEEXT: #endif max_tokens = wrq->u.data.length; break; case SIOCGIWRANGE: max_tokens = sizeof(struct iw_range) + 500; break; case SIOCGIWAPLIST: token_size = sizeof(struct sockaddr) + sizeof(struct iw_quality); max_tokens = IW_MAX_AP; break; #if WIRELESS_EXT > 13 case SIOCGIWSCAN: #if defined(WL_IW_USE_ISCAN) if (g_iscan) max_tokens = wrq->u.data.length; else #endif max_tokens = IW_SCAN_MAX_DATA; break; #endif case SIOCSIWSPY: token_size = sizeof(struct sockaddr); max_tokens = IW_MAX_SPY; break; case SIOCGIWSPY: token_size = sizeof(struct sockaddr) + sizeof(struct iw_quality); max_tokens = IW_MAX_SPY; break; #if WIRELESS_EXT > 17 case SIOCSIWPMKSA: case SIOCSIWGENIE: #endif case SIOCSIWPRIV: max_tokens = wrq->u.data.length; break; } if (max_tokens && wrq->u.data.pointer) { if (wrq->u.data.length > max_tokens) { WL_ERROR(("%s: error in cmd=%x wrq->u.data.length=%d > max_tokens=%d\n", __FUNCTION__, cmd, wrq->u.data.length, max_tokens)); ret = -E2BIG; goto wl_iw_ioctl_done; } if (!(extra = kmalloc(max_tokens * token_size, GFP_KERNEL))) { ret = -ENOMEM; goto wl_iw_ioctl_done; } if (copy_from_user(extra, wrq->u.data.pointer, wrq->u.data.length * token_size)) { kfree(extra); ret = -EFAULT; goto wl_iw_ioctl_done; } } info.cmd = cmd; info.flags = 0; ret = handler(dev, &info, &wrq->u, extra); if (extra) { if (copy_to_user(wrq->u.data.pointer, extra, wrq->u.data.length * token_size)) { kfree(extra); ret = -EFAULT; goto wl_iw_ioctl_done; } kfree(extra); } wl_iw_ioctl_done: net_os_wake_unlock(dev); return ret; } static bool <API key>(uint32 event_type, uint32 status, uint32 reason, char* stringBuf, uint buflen) { typedef struct <API key> { uint32 inEvent; uint32 inStatus; uint32 inReason; const char* outName; const char* outCause; } <API key>; #define WL_IW_DONT_CARE 9999 const <API key> event_map [] = { {WLC_E_SET_SSID, <API key>, WL_IW_DONT_CARE, "Conn", "Success"}, {WLC_E_SET_SSID, <API key>, WL_IW_DONT_CARE, "Conn", "NoNetworks"}, {WLC_E_SET_SSID, WLC_E_STATUS_FAIL, WL_IW_DONT_CARE, "Conn", "ConfigMismatch"}, {WLC_E_PRUNE, WL_IW_DONT_CARE, <API key>, "Conn", "EncrypMismatch"}, {WLC_E_PRUNE, WL_IW_DONT_CARE, WLC_E_RSN_MISMATCH, "Conn", "RsnMismatch"}, {WLC_E_AUTH, <API key>, WL_IW_DONT_CARE, "Conn", "AuthTimeout"}, {WLC_E_AUTH, WLC_E_STATUS_FAIL, WL_IW_DONT_CARE, "Conn", "AuthFail"}, {WLC_E_AUTH, WLC_E_STATUS_NO_ACK, WL_IW_DONT_CARE, "Conn", "AuthNoAck"}, {WLC_E_REASSOC, WLC_E_STATUS_FAIL, WL_IW_DONT_CARE, "Conn", "ReassocFail"}, {WLC_E_REASSOC, <API key>, WL_IW_DONT_CARE, "Conn", "ReassocTimeout"}, {WLC_E_REASSOC, WLC_E_STATUS_ABORT, WL_IW_DONT_CARE, "Conn", "ReassocAbort"}, {WLC_E_PSK_SUP, WLC_SUP_KEYED, WL_IW_DONT_CARE, "Sup", "ConnSuccess"}, {WLC_E_PSK_SUP, WL_IW_DONT_CARE, WL_IW_DONT_CARE, "Sup", "WpaHandshakeFail"}, {WLC_E_DEAUTH_IND, WL_IW_DONT_CARE, WL_IW_DONT_CARE, "Conn", "Deauth"}, {WLC_E_DISASSOC_IND, WL_IW_DONT_CARE, WL_IW_DONT_CARE, "Conn", "DisassocInd"}, {WLC_E_DISASSOC, WL_IW_DONT_CARE, WL_IW_DONT_CARE, "Conn", "Disassoc"} }; const char* name = ""; const char* cause = NULL; int i; for (i = 0; i < sizeof(event_map)/sizeof(event_map[0]); i++) { const <API key>* row = &event_map[i]; if (row->inEvent == event_type && (row->inStatus == status || row->inStatus == WL_IW_DONT_CARE) && (row->inReason == reason || row->inReason == WL_IW_DONT_CARE)) { name = row->outName; cause = row->outCause; break; } } if (cause) { memset(stringBuf, 0, buflen); snprintf(stringBuf, buflen, "%s %s %02d %02d", name, cause, status, reason); WL_INFORM(("Connection status: %s\n", stringBuf)); return TRUE; } else { return FALSE; } } #if WIRELESS_EXT > 14 static bool <API key>(wl_event_msg_t *e, char* stringBuf, uint buflen) { uint32 event = ntoh32(e->event_type); uint32 status = ntoh32(e->status); uint32 reason = ntoh32(e->reason); if (<API key>(event, status, reason, stringBuf, buflen)) { return TRUE; } else return FALSE; } #endif #ifndef IW_CUSTOM_MAX #define IW_CUSTOM_MAX 256 #endif void wl_iw_event(struct net_device *dev, wl_event_msg_t *e, void* data) { #if WIRELESS_EXT > 13 union iwreq_data wrqu; char extra[IW_CUSTOM_MAX + 1]; int cmd = 0; uint32 event_type = ntoh32(e->event_type); uint16 flags = ntoh16(e->flags); uint32 datalen = ntoh32(e->datalen); uint32 status = ntoh32(e->status); uint32 toto; memset(&wrqu, 0, sizeof(wrqu)); memset(extra, 0, sizeof(extra)); if (!dev) { WL_ERROR(("%s: dev is null\n", __FUNCTION__)); return; } net_os_wake_lock(dev); WL_TRACE(("%s: dev=%s event=%d \n", __FUNCTION__, dev->name, event_type)); switch (event_type) { #if defined(SOFTAP) case WLC_E_PRUNE: if (ap_cfg_running) { char *macaddr = (char *)&e->addr; WL_SOFTAP(("PRUNE received, %02X:%02X:%02X:%02X:%02X:%02X!\n", macaddr[0], macaddr[1], macaddr[2], macaddr[3], macaddr[4], macaddr[5])); if (ap_macmode) { int i; for (i = 0; i < ap_black_list.count; i++) { if (!bcmp(macaddr, &ap_black_list.ea[i], sizeof(struct ether_addr))) { WL_SOFTAP(("mac in black list, ignore it\n")); break; } } if (i == ap_black_list.count) { char mac_buf[32] = {0}; sprintf(mac_buf, "STA_BLOCK %02X:%02X:%02X:%02X:%02X:%02X", macaddr[0], macaddr[1], macaddr[2], macaddr[3], macaddr[4], macaddr[5]); <API key>(priv_dev, mac_buf); } } } break; #endif case WLC_E_TXFAIL: cmd = IWEVTXDROP; memcpy(wrqu.addr.sa_data, &e->addr, ETHER_ADDR_LEN); wrqu.addr.sa_family = ARPHRD_ETHER; break; #if WIRELESS_EXT > 14 case WLC_E_JOIN: case WLC_E_ASSOC_IND: case WLC_E_REASSOC_IND: #if defined(SOFTAP) WL_SOFTAP(("STA connect received %d\n", event_type)); if (ap_cfg_running) { <API key>(priv_dev, "STA_JOIN"); goto wl_iw_event_end; } #endif memcpy(wrqu.addr.sa_data, &e->addr, ETHER_ADDR_LEN); wrqu.addr.sa_family = ARPHRD_ETHER; cmd = IWEVREGISTERED; break; case WLC_E_ROAM: if (status == <API key>) { WL_ASSOC((" WLC_E_ROAM : success \n")); goto wl_iw_event_end; } break; case WLC_E_DEAUTH_IND: case WLC_E_DISASSOC_IND: #if defined(SOFTAP) WL_SOFTAP(("STA disconnect received %d\n", event_type)); if (ap_cfg_running) { <API key>(priv_dev, "STA_LEAVE"); goto wl_iw_event_end; } #endif cmd = SIOCGIWAP; bzero(wrqu.addr.sa_data, ETHER_ADDR_LEN); wrqu.addr.sa_family = ARPHRD_ETHER; bzero(&extra, ETHER_ADDR_LEN); break; case WLC_E_LINK: case WLC_E_NDIS_LINK: cmd = SIOCGIWAP; if (!(flags & WLC_EVENT_MSG_LINK)) { #ifdef SOFTAP #ifdef AP_ONLY if (ap_cfg_running) { #else if (ap_cfg_running && !strncmp(dev->name, "wl0.1", 5)) { #endif WL_SOFTAP(("AP DOWN %d\n", event_type)); <API key>(priv_dev, "AP_DOWN"); } else { WL_TRACE(("STA_Link Down\n")); g_ss_cache_ctrl.m_link_down = 1; } #else g_ss_cache_ctrl.m_link_down = 1; #endif WL_TRACE(("Link Down\n")); bzero(wrqu.addr.sa_data, ETHER_ADDR_LEN); bzero(&extra, ETHER_ADDR_LEN); } else { memcpy(wrqu.addr.sa_data, &e->addr, ETHER_ADDR_LEN); g_ss_cache_ctrl.m_link_down = 0; memcpy(g_ss_cache_ctrl.m_active_bssid, &e->addr, ETHER_ADDR_LEN); #ifdef SOFTAP #ifdef AP_ONLY if (ap_cfg_running) { #else if (ap_cfg_running && !strncmp(dev->name, "wl0.1", 5)) { #endif WL_SOFTAP(("AP UP %d\n", event_type)); <API key>(priv_dev, "AP_UP"); } else { WL_TRACE(("STA_LINK_UP\n")); } #else #endif WL_TRACE(("Link UP\n")); } wrqu.addr.sa_family = ARPHRD_ETHER; break; case WLC_E_ACTION_FRAME: cmd = IWEVCUSTOM; if (datalen + 1 <= sizeof(extra)) { wrqu.data.length = datalen + 1; extra[0] = WLC_E_ACTION_FRAME; memcpy(&extra[1], data, datalen); WL_TRACE(("WLC_E_ACTION_FRAME len %d \n", wrqu.data.length)); } break; case <API key>: cmd = IWEVCUSTOM; memcpy(&toto, data, 4); if (sizeof(status) + 1 <= sizeof(extra)) { wrqu.data.length = sizeof(status) + 1; extra[0] = <API key>; memcpy(&extra[1], &status, sizeof(status)); printf("wl_iw_event status %d PacketId %d \n", status, toto); printf("<API key> len %d \n", wrqu.data.length); } break; #endif #if WIRELESS_EXT > 17 case WLC_E_MIC_ERROR: { struct <API key> *micerrevt = (struct <API key> *)&extra; cmd = <API key>; wrqu.data.length = sizeof(struct <API key>); if (flags & WLC_EVENT_MSG_GROUP) micerrevt->flags |= IW_MICFAILURE_GROUP; else micerrevt->flags |= <API key>; memcpy(micerrevt->src_addr.sa_data, &e->addr, ETHER_ADDR_LEN); micerrevt->src_addr.sa_family = ARPHRD_ETHER; break; } case WLC_E_ASSOC_REQ_IE: cmd = IWEVASSOCREQIE; wrqu.data.length = datalen; if (datalen < sizeof(extra)) memcpy(extra, data, datalen); break; case WLC_E_ASSOC_RESP_IE: cmd = IWEVASSOCRESPIE; wrqu.data.length = datalen; if (datalen < sizeof(extra)) memcpy(extra, data, datalen); break; case WLC_E_PMKID_CACHE: { if (data) { struct iw_pmkid_cand *iwpmkidcand = (struct iw_pmkid_cand *)&extra; pmkid_cand_list_t *pmkcandlist; pmkid_cand_t *pmkidcand; int count; cmd = IWEVPMKIDCAND; pmkcandlist = data; count = ntoh32_ua((uint8 *)&pmkcandlist->npmkid_cand); ASSERT(count >= 0); wrqu.data.length = sizeof(struct iw_pmkid_cand); pmkidcand = pmkcandlist->pmkid_cand; while (count) { bzero(iwpmkidcand, sizeof(struct iw_pmkid_cand)); if (pmkidcand->preauth) iwpmkidcand->flags |= <API key>; bcopy(&pmkidcand->BSSID, &iwpmkidcand->bssid.sa_data, ETHER_ADDR_LEN); wireless_send_event(dev, cmd, &wrqu, extra); pmkidcand++; count } } goto wl_iw_event_end; } #endif case WLC_E_SCAN_COMPLETE: #if defined(WL_IW_USE_ISCAN) if (!g_iscan) { WL_ERROR(("Event WLC_E_SCAN_COMPLETE on g_iscan NULL!")); goto wl_iw_event_end; } if ((g_iscan) && (g_iscan->tsk_ctl.thr_pid >= 0) && (g_iscan->iscan_state != ISCAN_STATE_IDLE)) { up(&g_iscan->tsk_ctl.sema); } else { cmd = SIOCGIWSCAN; wrqu.data.length = strlen(extra); WL_TRACE(("Event WLC_E_SCAN_COMPLETE from specific scan %d\n", g_iscan->iscan_state)); } #else cmd = SIOCGIWSCAN; wrqu.data.length = strlen(extra); WL_TRACE(("Event WLC_E_SCAN_COMPLETE\n")); #endif break; case WLC_E_PFN_NET_FOUND: { wl_pfn_net_info_t *netinfo; netinfo = (wl_pfn_net_info_t *)(data + sizeof(<API key>) - sizeof(wl_pfn_net_info_t)); WL_ERROR(("%s Event WLC_E_PFN_NET_FOUND, send %s up : find %s len=%d\n", __FUNCTION__, PNO_EVENT_UP, netinfo->pfnsubnet.SSID, netinfo->pfnsubnet.SSID_len)); cmd = IWEVCUSTOM; memset(&wrqu, 0, sizeof(wrqu)); strcpy(extra, PNO_EVENT_UP); wrqu.data.length = strlen(extra); } break; default: WL_TRACE(("Unknown Event %d: ignoring\n", event_type)); break; } if (cmd) { if (cmd == SIOCGIWSCAN) wireless_send_event(dev, cmd, &wrqu, NULL); else wireless_send_event(dev, cmd, &wrqu, extra); } #if WIRELESS_EXT > 14 memset(extra, 0, sizeof(extra)); if (<API key>(e, extra, sizeof(extra))) { cmd = IWEVCUSTOM; wrqu.data.length = strlen(extra); wireless_send_event(dev, cmd, &wrqu, extra); } #endif goto wl_iw_event_end; wl_iw_event_end: net_os_wake_unlock(dev); #endif } int <API key>(struct net_device *dev, struct iw_statistics *wstats) { int res = 0; wl_cnt_t cnt; int phy_noise; int rssi; scb_val_t scb_val; phy_noise = 0; if ((res = dev_wlc_ioctl(dev, WLC_GET_PHY_NOISE, &phy_noise, sizeof(phy_noise)))) goto done; phy_noise = dtoh32(phy_noise); WL_TRACE(("<API key> phy noise=%d\n", phy_noise)); bzero(&scb_val, sizeof(scb_val_t)); if ((res = dev_wlc_ioctl(dev, WLC_GET_RSSI, &scb_val, sizeof(scb_val_t)))) goto done; rssi = dtoh32(scb_val.val); WL_TRACE(("<API key> rssi=%d\n", rssi)); if (rssi <= <API key>) wstats->qual.qual = 0; else if (rssi <= WL_IW_RSSI_VERY_LOW) wstats->qual.qual = 1; else if (rssi <= WL_IW_RSSI_LOW) wstats->qual.qual = 2; else if (rssi <= WL_IW_RSSI_GOOD) wstats->qual.qual = 3; else if (rssi <= <API key>) wstats->qual.qual = 4; else wstats->qual.qual = 5; wstats->qual.level = 0x100 + rssi; wstats->qual.noise = 0x100 + phy_noise; #if WIRELESS_EXT > 18 wstats->qual.updated |= (IW_QUAL_ALL_UPDATED | IW_QUAL_DBM); #else wstats->qual.updated |= 7; #endif #if WIRELESS_EXT > 11 WL_TRACE(("<API key> counters=%d\n", (int)sizeof(wl_cnt_t))); memset(&cnt, 0, sizeof(wl_cnt_t)); res = dev_wlc_bufvar_get(dev, "counters", (char *)&cnt, sizeof(wl_cnt_t)); if (res) { WL_ERROR(("<API key> counters failed error=%d\n", res)); goto done; } cnt.version = dtoh16(cnt.version); if (cnt.version != WL_CNT_T_VERSION) { WL_TRACE(("\tIncorrect version of counters struct: expected %d; got %d\n", WL_CNT_T_VERSION, cnt.version)); goto done; } wstats->discard.nwid = 0; wstats->discard.code = dtoh32(cnt.rxundec); wstats->discard.fragment = dtoh32(cnt.rxfragerr); wstats->discard.retries = dtoh32(cnt.txfail); wstats->discard.misc = dtoh32(cnt.rxrunt) + dtoh32(cnt.rxgiant); wstats->miss.beacon = 0; WL_TRACE(("<API key> counters txframe=%d txbyte=%d\n", dtoh32(cnt.txframe), dtoh32(cnt.txbyte))); WL_TRACE(("<API key> counters rxfrmtoolong=%d\n", dtoh32(cnt.rxfrmtoolong))); WL_TRACE(("<API key> counters rxbadplcp=%d\n", dtoh32(cnt.rxbadplcp))); WL_TRACE(("<API key> counters rxundec=%d\n", dtoh32(cnt.rxundec))); WL_TRACE(("<API key> counters rxfragerr=%d\n", dtoh32(cnt.rxfragerr))); WL_TRACE(("<API key> counters txfail=%d\n", dtoh32(cnt.txfail))); WL_TRACE(("<API key> counters rxrunt=%d\n", dtoh32(cnt.rxrunt))); WL_TRACE(("<API key> counters rxgiant=%d\n", dtoh32(cnt.rxgiant))); #endif done: return res; } #if defined(COEX_DHCP) static void wl_iw_bt_flag_set( struct net_device *dev, bool set) { #if defined(BT_DHCP_USE_FLAGS) char buf_flag7_dhcp_on[8] = { 7, 00, 00, 00, 0x1, 0x0, 0x00, 0x00 }; char buf_flag7_default[8] = { 7, 00, 00, 00, 0x0, 0x00, 0x00, 0x00}; #endif #if (LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 27)) rtnl_lock(); #endif #if defined(BT_DHCP_eSCO_FIX) set_btc_esco_params(dev, set); #endif #if defined(BT_DHCP_USE_FLAGS) WL_TRACE_COEX(("WI-FI priority boost via bt flags, set:%d\n", set)); if (set == TRUE) { dev_wlc_bufvar_set(dev, "btc_flags", (char *)&buf_flag7_dhcp_on[0], sizeof(buf_flag7_dhcp_on)); } else { dev_wlc_bufvar_set(dev, "btc_flags", (char *)&buf_flag7_default[0], sizeof(buf_flag7_default)); } #endif #if (LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 27)) rtnl_unlock(); #endif } static void wl_iw_bt_timerfunc(ulong data) { bt_info_t *bt_local = (bt_info_t *)data; bt_local->timer_on = 0; WL_TRACE(("%s\n", __FUNCTION__)); up(&bt_local->tsk_ctl.sema); } static int <API key>(void *data) { tsk_ctl_t *tsk_ctl = (tsk_ctl_t *)data; DAEMONIZE("dhcp_sysioc"); complete(&tsk_ctl->completed); while (down_interruptible(&tsk_ctl->sema) == 0) { <API key>(); if (tsk_ctl->terminated) { break; } if (g_bt->timer_on) { g_bt->timer_on = 0; del_timer_sync(&g_bt->timer); } switch (g_bt->bt_state) { case BT_DHCP_START: WL_TRACE_COEX(("%s bt_dhcp stm: started \n", __FUNCTION__)); g_bt->bt_state = <API key>; mod_timer(&g_bt->timer, jiffies + msecs_to_jiffies(<API key>)); g_bt->timer_on = 1; break; case <API key>: if (g_bt->dhcp_done) { WL_TRACE_COEX(("%s DHCP Done before T1 expiration\n", __FUNCTION__)); goto btc_coex_idle; } WL_TRACE_COEX(("%s DHCP T1:%d expired\n", __FUNCTION__, <API key>)); if (g_bt->dev) wl_iw_bt_flag_set(g_bt->dev, TRUE); g_bt->bt_state = <API key>; mod_timer(&g_bt->timer, jiffies + msecs_to_jiffies(<API key>)); g_bt->timer_on = 1; break; case <API key>: if (g_bt->dhcp_done) { WL_TRACE_COEX(("%s DHCP Done before T2 expiration\n", __FUNCTION__)); } else { WL_TRACE_COEX(("%s DHCP wait interval T2:%d msec expired\n", __FUNCTION__, <API key>)); } if (g_bt->dev) wl_iw_bt_flag_set(g_bt->dev, FALSE); btc_coex_idle: g_bt->bt_state = BT_DHCP_IDLE; g_bt->timer_on = 0; break; default: WL_ERROR(("%s error g_status=%d !!!\n", __FUNCTION__, g_bt->bt_state)); if (g_bt->dev) wl_iw_bt_flag_set(g_bt->dev, FALSE); g_bt->bt_state = BT_DHCP_IDLE; g_bt->timer_on = 0; break; } net_os_wake_unlock(g_bt->dev); } if (g_bt->timer_on) { g_bt->timer_on = 0; del_timer_sync(&g_bt->timer); } complete_and_exit(&tsk_ctl->completed, 0); } static void wl_iw_bt_release(void) { bt_info_t *bt_local = g_bt; if (!bt_local) { return; } if (bt_local->tsk_ctl.thr_pid >= 0) { PROC_STOP(&bt_local->tsk_ctl); } kfree(bt_local); g_bt = NULL; } static int wl_iw_bt_init(struct net_device *dev) { bt_info_t *bt_dhcp = NULL; bt_dhcp = kmalloc(sizeof(bt_info_t), GFP_KERNEL); if (!bt_dhcp) return -ENOMEM; memset(bt_dhcp, 0, sizeof(bt_info_t)); g_bt = bt_dhcp; bt_dhcp->dev = dev; bt_dhcp->bt_state = BT_DHCP_IDLE; bt_dhcp->timer_ms = 10; init_timer(&bt_dhcp->timer); bt_dhcp->timer.data = (ulong)bt_dhcp; bt_dhcp->timer.function = wl_iw_bt_timerfunc; bt_dhcp->ts_dhcp_start = 0; bt_dhcp->ts_dhcp_ok = 0; PROC_START(<API key>, bt_dhcp, &bt_dhcp->tsk_ctl, 0); if (bt_dhcp->tsk_ctl.thr_pid < 0) { WL_ERROR(("Failed in %s\n", __FUNCTION__)); return -ENOMEM; } return 0; } #endif int wl_iw_attach(struct net_device *dev, void * dhdp) { #if defined(WL_IW_USE_ISCAN) int params_size = 0; #endif wl_iw_t *iw; #if defined(WL_IW_USE_ISCAN) iscan_info_t *iscan = NULL; #endif DHD_OS_MUTEX_INIT(&wl_cache_lock); DHD_OS_MUTEX_INIT(&wl_softap_lock); #if defined(WL_IW_USE_ISCAN) if (!dev) return 0; memset(&g_wl_iw_params, 0, sizeof(<API key>)); #ifdef CSCAN params_size = (<API key> + OFFSETOF(wl_iscan_params_t, params)) + (WL_NUMCHANNELS * sizeof(uint16)) + <API key> * sizeof(wlc_ssid_t); #else params_size = (<API key> + OFFSETOF(wl_iscan_params_t, params)); #endif iscan = kmalloc(sizeof(iscan_info_t), GFP_KERNEL); if (!iscan) return -ENOMEM; memset(iscan, 0, sizeof(iscan_info_t)); iscan->iscan_ex_params_p = (wl_iscan_params_t*)kmalloc(params_size, GFP_KERNEL); if (!iscan->iscan_ex_params_p) { kfree(iscan); return -ENOMEM; } iscan->iscan_ex_param_size = params_size; g_iscan = iscan; iscan->dev = dev; iscan->iscan_state = ISCAN_STATE_IDLE; #if defined(CONFIG_FIRST_SCAN) <API key> = <API key>; <API key> = 0; g_iscan->scan_flag = 0; #endif #ifdef CONFIG_WPS2 g_wps_probe_req_ie = NULL; <API key> = 0; #endif iscan->timer_ms = 8000; init_timer(&iscan->timer); iscan->timer.data = (ulong)iscan; iscan->timer.function = wl_iw_timerfunc; PROC_START(<API key>, iscan, &iscan->tsk_ctl, 0); if (iscan->tsk_ctl.thr_pid < 0) return -ENOMEM; #endif iw = *(wl_iw_t **)netdev_priv(dev); iw->pub = (dhd_pub_t *)dhdp; #ifdef SOFTAP priv_dev = dev; #endif g_scan = NULL; g_scan = (void *)kmalloc(G_SCAN_RESULTS, GFP_KERNEL); if (!g_scan) return -ENOMEM; memset(g_scan, 0, G_SCAN_RESULTS); <API key> = 0; #if !defined(CSCAN) <API key>(); #endif #ifdef COEX_DHCP wl_iw_bt_init(dev); #endif return 0; } void wl_iw_detach(void) { #if defined(WL_IW_USE_ISCAN) iscan_buf_t *buf; iscan_info_t *iscan = g_iscan; if (!iscan) return; if (iscan->tsk_ctl.thr_pid >= 0) { PROC_STOP(&iscan->tsk_ctl); } DHD_OS_MUTEX_LOCK(&wl_cache_lock); while (iscan->list_hdr) { buf = iscan->list_hdr->next; kfree(iscan->list_hdr); iscan->list_hdr = buf; } kfree(iscan->iscan_ex_params_p); kfree(iscan); g_iscan = NULL; DHD_OS_MUTEX_UNLOCK(&wl_cache_lock); #endif if (g_scan) kfree(g_scan); g_scan = NULL; #ifdef CONFIG_WPS2 if (g_wps_probe_req_ie) { kfree(g_wps_probe_req_ie); g_wps_probe_req_ie = NULL; <API key> = 0; } #endif #if !defined(CSCAN) <API key>(); #endif #ifdef COEX_DHCP wl_iw_bt_release(); #endif #ifdef SOFTAP if (ap_cfg_running) { WL_TRACE(("\n%s AP is going down\n", __FUNCTION__)); <API key>(priv_dev, "AP_DOWN"); } #endif }
# This program is free software; you can redistribute it and/or # # as published by the Free Software Foundation; either version 2 # # This program is distributed in the hope that it will be useful, # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # along with this program; if not, write to the Free Software # # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, # # USA. # module BioDSL # == Plot tabular numerical data in a heatmap. # A heatmap can be plotted with +plot_heatmap+ using numerical data (Non- # numerical data is ignored). Data should be tabular with records as rows and # keys as columns - the data cells plotted will be the values. # Default graphics are crufty ASCII and you probably want high resolution # postscript or SVG output instead with is easy using the +terminal+ option. # Plotting is done using GNUplot which allows for different types of output. # GNUplot must be installed for +plot_heatmap+ to work. Read more here: # == Usage # plot_heatmap([keys: <list> | skip: <list>[, output: <file> # [, force: <bool> [, terminal: <string> # [, title: <string>[, xlabel: <string>[, ylabel: <string> # [, test: <bool>]]]]]]]) # * keys: <list> - Comma separated list of keys to plot as columns. # * skip: <list> - Comma separated list of keys to skip as columns. # * output: <file> - Output file. # * force: <bool> - Force overwrite existing output file. # * terminal: <string> - Terminal for output: dumb|post|svg|x11|aqua|png|pdf # (default=dumb). # * title: <string> - Plot title (default="Heatmap"). # * xlabel: <string> - X-axis label (default="x"). # * ylabel: <string> - Y-axis label (default="y"). # * test: <bool> - Output Gnuplot script instead of plot. # == Examples # Here we plot a heatmap of data a table: # BD.new.read_table(input: "test.tab").plot_heatmap.run class PlotHeatmap require 'gnuplotter' require 'set' require 'BioDSL/helpers/aux_helper' include AuxHelper STATS = %i(records_in records_out) # Constructor for PlotHeatmap. # @param options [Hash] Options hash. # @option options [Array] :keys List of keys to plot as column. # @option options [Array] :skip List of keys to skip as column. # @option options [String] :output Path to output file. # @option options [Boolean] :forcea Flag to force overwrite output file. # @option options [Symbol] :terminal Set plot terminal type. # @option options [String] :title Set plot title. # @option options [String] :xlabel Set plot xlabel. # @option options [String] :ylabel Set plot ylabel # @option options [Boolean] :logscale Logscale Z-axis. # @option options [Boolean] :test Output gnuplot script. # @return [PlotHeatmap] Class instance. def initialize(options) @options = options @headings = nil @skip_keys = determine_skip_keys aux_exist('gnuplot') check_options defaults end # Return command lambda for plot_histogram. # @return [Proc] Command lambda. def lmb lambda do |input, output, status| status_init(status, STATS) gp = GnuPlotter.new plot_options(gp) plot_dataset(gp, input, output) plot_output(gp) end end private # Check options. def check_options options_allowed(@options, :keys, :skip, :output, :force, :terminal, :title, :xlabel, :ylabel, :logscale, :test) options_unique(@options, :keys, :skip) <API key>(@options, terminal: [:dumb, :post, :svg, :x11, :aqua, :png, :pdf]) <API key>(@options, test: [nil, true, false]) <API key>(@options, logscale: [nil, true, false]) <API key>(@options, :output) end # Set default options. def defaults @options[:terminal] ||= :dumb @options[:title] ||= 'Heatmap' @options[:xlabel] ||= 'x' @options[:ylabel] ||= 'y' end # Compile a set of keys to skip. # @return [Set] Set of keys to skip. def determine_skip_keys return unless @options[:skip] @options[:skip].each_with_object(Set.new) { |e, a| a << e.to_sym } end # Determine the headings. # @param record [Hash] BioDSL record. def determine_headings(record) @headings = if @options[:keys] @options[:keys].map(&:to_sym) elsif record.keys.first =~ /^V\d+$/ sort_keys(record) else record.keys end @headings.reject! { |r| @skip_keys.include? r } if @options[:skip] end # Sort records keys numerically, when the keys are in the format Vn, where n # is an Integer. # @param record [Hash] BioDSL record. # @return [Array] List of sorted keys. def sort_keys(record) record.keys.sort do |a, b| a.to_s[1..a.to_s.size].to_i <=> b.to_s[1..a.to_s.size].to_i end end # Set options for plot. # @param gp [GnuPlotter] GnuPlotter object. def plot_options(gp) gp.set terminal: @options[:terminal].to_s gp.set title: @options[:title] gp.set xlabel: @options[:xlabel] gp.set ylabel: @options[:ylabel] gp.set output: @options[:output] if @options[:output] gp.set view: 'map' gp.set autoscale: 'xfix' gp.set autoscale: 'yfix' gp.set nokey: true gp.set tic: 'scale 0' gp.set palette: 'rgbformulae 22,13,10' gp.set logscale: 'cb' if @options[:logscale] gp.unset xtics: true gp.unset ytics: true end # Plot relevant data from the input stream. # @param gp [GnuPlotter] GnuPlotter object. # @param input [Enumerator] Input stream. # @param output [Enumerator::Yielder] Output stream. def plot_dataset(gp, input, output) gp.add_dataset(matrix: :true, with: 'image') do |plotter| input.each do |record| @status[:records_in] += 1 determine_headings(record) unless @headings plotter << record.values_at(*@headings) next unless output output << record @status[:records_out] += 1 end end end # Output plot data according to options. # @param gp [GnuPlotter] GnuPlotter object. def plot_output(gp) if @options[:test] $stderr.puts gp.to_gp elsif @options[:terminal] == :dumb puts gp.splot else gp.splot end end end end
.settings_page_aptrc h3 { margin: 2em 0 0 0; } .settings_page_aptrc tr { //border-bottom: 1px solid #ccc; } .settings_page_aptrc th { text-transform: capitalize; } .settings_page_aptrc th span { text-transform: lowercase; display: inline-block; } .settings_page_aptrc #toggle { visibility: visible; margin: 0px 0px 0px -220px; padding: 10px 15px; border-left: 4px solid #0074a2; background: #fff; -webkit-box-shadow: 0 1px 1px 0 rgba(0,0,0,.1); box-shadow: 0 1px 1px 0 rgba(0,0,0,.1); } .settings_page_aptrc #toggle p { font-size: 12px; color: #000; } .settings_page_aptrc label { color: #B2B2B2; } .settings_page_aptrc input[type=checkbox]:checked + label { color: #444; } .settings_page_aptrc .form-table tr select, .settings_page_aptrc .form-table tr select[id^="<API key>"], .settings_page_aptrc .form-table tr select[id*="<API key>"], .settings_page_aptrc .form-table tr select[id^="flat_dropdown_"], .settings_page_aptrc .form-table tr select[id*="flat_dropdown_"] { position: absolute; margin-top: -35px; padding-bottom: 0px !important; margin-bottom: 0px; width: 50px; } .settings_page_aptrc .form-table tr select#<API key>, .settings_page_aptrc .form-table tr select#tags_max_dropdown, .settings_page_aptrc .form-table tr select[id^="<API key>"], .settings_page_aptrc .form-table tr select[id*="<API key>"], .settings_page_aptrc .form-table tr select[id^="flat_max_dropdown_"], .settings_page_aptrc .form-table tr select[id*="flat_max_dropdown_"] { margin-top: -43px; } .settings_page_aptrc .form-table label.dropdown { position: absolute; margin-top: -30px; margin-left: 60px; color: #444; } .settings_page_aptrc .form-table label.max { margin-top: -38px; } @media screen and (max-width: 782px) { .settings_page_aptrc #toggle { margin: 5px 0px 0px 0px; font-size: 13px; } .settings_page_aptrc .form-table tr select { width: 55px; } .settings_page_aptrc .form-table tr select#<API key>, .settings_page_aptrc .form-table tr select#tags_max_dropdown, .settings_page_aptrc .form-table tr select[id^="hierarchical_max_"], .settings_page_aptrc .form-table tr select[id*=" hierarchical_max_"], .settings_page_aptrc .form-table tr select[id^="flat_max_"], .settings_page_aptrc .form-table tr select[id*=" flat_max_"] { margin-top: -30px; } .settings_page_aptrc .form-table label.dropdown { margin-top: -25px; margin-left: 65px; } .settings_page_aptrc .form-table label.max { margin-top: -20px; } }
<div class="<API key>"> <form method="post" action="<?php echo the_permalink()?>"> <input type="submit" value="<?php _e('Subscribe Now!', 'konnichiwa')?>"> <input type="hidden" name="<API key>" value="1"> <input type="hidden" name="plan_id" value="<?php echo $plan_id?>"> </form> </div>
package com.caucho.v5.kelp; import java.util.Comparator; /** * A row for the log store. */ final class KeyComparator implements Comparator<byte[]> { public static final KeyComparator INSTANCE = new KeyComparator(); private KeyComparator() { } @Override public final int compare(byte[] a, byte[] b) { final int aLen = a.length; for (int i = 0; i < aLen; i++) { int cmp = (a[i] & 0xff) - (b[i] & 0xff); if (cmp != 0) { return Integer.signum(cmp); } } return 0; } public final int compare(byte[] a, int aOffset, byte[] b, int bOffset, int length) { for (int i = 0; i < length; i++) { int cmp = (a[i + aOffset] & 0xff) - (b[i + bOffset] & 0xff); if (cmp != 0) { return Integer.signum(cmp); } } return 0; } }
package server; import java.io.*; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; import java.security.<API key>; import java.security.KeyFactory; import java.security.MessageDigest; import java.security.<API key>; import java.security.PrivateKey; import java.security.SecureRandom; import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPublicKey; import java.security.spec.EncodedKeySpec; import java.security.spec.<API key>; import java.security.spec.KeySpec; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import javax.crypto.BadPaddingException; import javax.crypto.SecretKey; import client.ClientApp; import Keys.DHKeyGenerator; import Keys.PBEKeyGenerator; import Messages.LoginReplyMsg; import Messages.LoginReqMsg; import Messages.LoginRequest; import Messages.LogoutACK; import Messages.LogoutRequest; import Messages.TalkingContent; import Messages.TalkingMessage; import Messages.<API key>; import Messages.<API key>; import Messages.Verification; import Messages.message_type; import recordtable.RecordTable; public class Server { static String public_key_path; static String private_key_path; static RSAPublicKey server_public_key; static RSAPrivateKey server_private_key; // List<OnlineClientItem> online_clients; static String hash_algorithm = "SHA1"; static RecordTable record_table; static int challenge = 0; private static ServerSocket serverSocket; // initialize server, public key and private key, and record table public Server(int port) throws IOException { serverSocket = new ServerSocket(port, 20); // initialize record table record_table = new RecordTable(); // initialize public key and private key of server server_private_key = (RSAPrivateKey) <API key>(record_table .<API key>("server")); server_public_key = (RSAPublicKey) read_in_public_keys(record_table .get_public_key_path("server")); } public static void main(String[] args) { try { int serverport = Integer.parseInt(args[0]); Server server = new Server(serverport); System.out.println("Server Start..."); // service(); while (true) { Socket socket = null; try { System.out.println("listeining on port " + args[0]); socket = serverSocket.accept(); System.out.println("a request from " + socket.getInetAddress().toString() + " comes"); invoke(socket); } catch (IOException e) { e.printStackTrace(); } finally { // try { // if (socket != null) // socket.close(); // } catch (IOException e) { // e.printStackTrace(); } } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private static void invoke(final Socket socket) throws IOException { new Thread(new Runnable() { public void run() { Object msg_recv = null; try { ObjectInputStream in = new ObjectInputStream(socket .getInputStream()); msg_recv = in.readObject(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (<API key> e) { // TODO Auto-generated catch block e.printStackTrace(); } Class<? extends Object> class_type = msg_recv.getClass(); String class_name = class_type.getCanonicalName(); System.out.println(class_name); try { if (class_name.equals("java.lang.String")) { String string = (String) msg_recv; System.out.println(string); return; } else if (class_name.equals("Messages.LoginRequest")) { login(socket); } else if (class_name.equals("Messages.TalkingMessage")) { InetAddress ipAddr = socket.getInetAddress(); TalkingMessage t = (TalkingMessage) msg_recv; SecretKey session_key = record_table .get_session_key(record_table.get_user_name(socket.getInetAddress().toString(), t.local_port)); // verify first, if not correct just skip if (!t.<API key>(session_key)) { System.out.println("Verification hmac failed"); OutputStream out = socket.getOutputStream(); out.write("hmac failed".getBytes()); return; } if (t.getType() == message_type.Talk_REQ_Server) { <API key>(socket, t); } else if (t.getType() == message_type.Logout_Server) { logout_client(socket, t.get_logout_request(session_key), session_key); } else if (t.getType() == message_type.Talk_Content) { // might be list command TalkingContent content_obj = t .<API key>(session_key); String text = content_obj.getContent(); if (text.equals("list")) send_list(socket, content_obj, session_key, t.local_port); } } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (<API key> e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (<API key> e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { socket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }).start(); } // read public key from file public static Object read_in_public_keys(String keyFile) { try { File file = new File(keyFile); int fileLength = (int) file.length(); byte[] keyData = new byte[fileLength]; FileInputStream inFileStream = new FileInputStream(keyFile); <API key> bout = new <API key>(); inFileStream.read(keyData); bout.write(keyData); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); EncodedKeySpec publicKeySpec = new X509EncodedKeySpec( bout.toByteArray()); RSAPublicKey objKey = (RSAPublicKey) keyFactory .generatePublic(publicKeySpec); return objKey; } catch (<API key> e) { // TODO Auto-generated catch block // e.printStackTrace(); return null; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (<API key> e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (<API key> e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("Error in read Key" + keyFile); return 0; } // read private key from file public static Object <API key>(String keyFile) { try { File file = new File(keyFile); int fileLength = (int) file.length(); byte[] keyData = new byte[fileLength]; FileInputStream inFileStream = new FileInputStream(keyFile); <API key> bout = new <API key>(); inFileStream.read(keyData); bout.write(keyData); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); KeySpec privateKeySpec = new PKCS8EncodedKeySpec(bout.toByteArray()); RSAPrivateKey objKey = (RSAPrivateKey) keyFactory .generatePrivate(privateKeySpec); return objKey; } catch (<API key> e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (<API key> e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (<API key> e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("Error in read Key" + keyFile); return 0; } static void login(Socket socket) throws IOException, <API key> { InetAddress ipAddr = socket.getInetAddress(); // int port=receivedPacket.getPort(); try { // 1. create a cookie and send it back to client byte[] cookie = create_cookie(ipAddr.getHostAddress(), server_private_key); OutputStream output = socket.getOutputStream(); output.write(cookie); output.flush(); // 2. receive LoginReqMsg System.out.println("Receive LoginReqMsg"); ObjectInputStream in = new ObjectInputStream( socket.getInputStream()); Object object = in.readObject(); if (object.getClass().getCanonicalName().equals("java.lang.String")) { String string = (String) object; System.out.println(string); System.exit(0); } LoginReqMsg login_req_msg = (LoginReqMsg) object; LoginRequest <API key> = login_req_msg .<API key>(server_private_key); String user_name = <API key>.user_name; byte[] returned_cookie = login_req_msg.getCookie(); if (!Arrays.equals(returned_cookie, cookie)) { System.out.println("get unexpected cookie back"); return; } // generate the other part of DH key System.out.println("Generate g b mod p"); DHKeyGenerator dh_key_gen = new DHKeyGenerator("DH_p_g"); byte[] gb_mod_p = dh_key_gen.generate_gx_modp(); SecretKey w = getW_by_name(user_name); // generate DH secret key byte[] ga_mod_p = login_req_msg.getPartial_dh_key(w); SecretKey dh_key = dh_key_gen.generate_secret_key(ga_mod_p); byte[] y = getY_by_name(user_name); // 3. create LoginReplyMsg and sent it back to client LoginReplyMsg login_reply = new LoginReplyMsg(); login_reply.set_encryptedY(y, dh_key); login_reply.<API key>(gb_mod_p, w); // set challenge using secure random generator SecureRandom srg = SecureRandom.getInstance("SHA1PRNG"); challenge = srg.nextInt(); login_reply.set_challenge(challenge); // deserialize LoginReplyMsg and sent out ObjectOutputStream out = new ObjectOutputStream( socket.getOutputStream()); System.out.println("Send LoginReplyMsg"); out.writeObject(login_reply); out.flush(); // 4. receive Verification in = new ObjectInputStream(socket.getInputStream()); System.out.println("Receive Verification"); Verification verification_obj = (Verification) in.readObject(); // get client's public key and verify the signature RSAPublicKey public_key = (RSAPublicKey) read_in_public_keys(record_table .get_public_key_path(user_name)); if (!verification_obj.Verify(public_key, dh_key, challenge)) return; int port = verification_obj.get_verified_port(dh_key); // 5. store online client item in memory if (record_table.online_table.containsKey(user_name)) { record_table.online_table.remove(user_name); } record_table.add_online_entry(user_name, ipAddr.toString(), port, dh_key); System.out.println("user " + user_name + " get verified"); } catch (BadPaddingException e) { // TODO: handle exception ObjectOutputStream outstream = new ObjectOutputStream(socket.getOutputStream()); outstream.writeObject("password incorrect"); } catch (Exception e) { e.printStackTrace(); } } static void <API key>(Socket socket, Object msg_recv) throws <API key>, IOException, <API key> { System.out.println("Messages.<API key>"); InetAddress ipAddr = socket.getInetAddress(); TalkingMessage t = (TalkingMessage) msg_recv; String user_name = record_table.get_user_name(ipAddr.toString(), t.local_port); SecretKey session_key = record_table.get_session_key(user_name); // verify HMAC first, if not correct just skip if (!t.<API key>(session_key)) { System.out.println("Verification hmac failed"); ObjectOutputStream outstream = new ObjectOutputStream(socket.getOutputStream()); outstream.writeObject("hmac failed"); outstream.flush(); return; } <API key> talk_to_server = (<API key>) t .<API key>(session_key); String deString = talk_to_server.getDest(); boolean online_state = record_table.online_table.containsKey(deString); if (!online_state) { System.out.println("user not exist"); ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream()); objectOutputStream.writeObject("user not exist"); } String filepathString = record_table.get_public_key_path(deString); RSAPublicKey target_public_key = (RSAPublicKey) read_in_public_keys(filepathString); String dest_ip = record_table.get_ip_from_user(talk_to_server.getDest()); int dest_port = record_table.get_port_from_user(talk_to_server.getDest()); // create <API key> <API key> reply = new <API key>( talk_to_server.getDest(), dest_ip, dest_port, target_public_key); // create TalkingMessage and set HMAC TalkingMessage talking_msg = new TalkingMessage(); talking_msg.setType(message_type.Talk_REP_Server); talking_msg.<API key>(reply, session_key); <API key> output = new <API key>(); ObjectOutputStream out = new ObjectOutputStream(output); out.writeObject(talking_msg); talking_msg.<API key>(output.toByteArray(), session_key); // send <API key> to client ObjectOutputStream out2 = new ObjectOutputStream( socket.getOutputStream()); out2.writeObject(talking_msg); out2.flush(); System.out.println("send out talking reply message"); } static long <API key>(String usr) { long recorded_timestamp = record_table.get_last_update(usr); long timestamp; if(recorded_timestamp != -1) { timestamp = recorded_timestamp + 1; } else { timestamp = new Date().getTime(); } return timestamp; } static void logout_client(Socket socket, LogoutRequest logout_req, SecretKey session_key) throws IOException { String usr_name = logout_req.getIniciator(); long timestamp = logout_req.getTimestamp(); long last_timestamp = record_table.get_last_update(usr_name); if (last_timestamp != -1) { if (last_timestamp + 1 != timestamp) { System.out.println("Get out of order LogoutRequest"); return; } } timestamp++; LogoutACK logout_ack = new LogoutACK(usr_name, "server"); logout_ack.setTimestamp(timestamp); TalkingMessage logout_msg = new TalkingMessage(); logout_msg.setType(message_type.ACK_Server); logout_msg.<API key>(logout_ack, session_key); <API key> output = new <API key>(); ObjectOutputStream out = new ObjectOutputStream(output); out.writeObject(logout_msg); logout_msg.<API key>(output.toByteArray(), session_key); ObjectOutputStream obj_out = new ObjectOutputStream( socket.getOutputStream()); System.out.println("Send Logout ACK"); obj_out.writeObject(logout_msg); System.out.println("Delete from online clients."); record_table.delete_user(usr_name); } static void send_list(Socket socket, TalkingContent content_obj, SecretKey session_key, int local_port) throws IOException { long timestamp = content_obj.getTimestamp(); InetAddress ip = socket.getInetAddress(); String user = record_table.get_user_name(ip.toString(), local_port); // verify timestamp long last_timestamp = record_table.get_last_update(user); if (last_timestamp != -1) { if (last_timestamp + 1 != timestamp) { System.out.println("Get out of order TalkingMessage"); return; } } record_table.online_table.get(user).setLast_update( new Timestamp(++timestamp)); // Concatenate user names ArrayList<String> online_users = record_table.get_online_users(); TalkingContent content = new TalkingContent( <API key>(online_users), timestamp); TalkingMessage message = new TalkingMessage(); message.<API key>(content, session_key); message.setType(message_type.Talk_Content); // compute Hmac <API key> output = new <API key>(); ObjectOutputStream out = new ObjectOutputStream(output); out.writeObject(message); message.<API key>(output.toByteArray(), session_key); // send TalkingMessage ObjectOutputStream obj_out = new ObjectOutputStream( socket.getOutputStream()); System.out.println("Send out on line list"); obj_out.writeObject(message); } static String <API key>(ArrayList<String> users) { String online_names = ""; for (String user : users) { online_names = online_names + " " + user; } return online_names; } void send_UDP_packet(byte[] sent_bytes, DatagramSocket serverSocket, InetAddress ipAddr, int port) throws IOException { byte[] sendDataBuff = sent_bytes; DatagramPacket sendPacket = new DatagramPacket(sendDataBuff, sendDataBuff.length); sendPacket.setAddress(ipAddr); sendPacket.setPort(port); serverSocket.send(sendPacket); } // public RSAPublicKey get_public_key() // public RSAPrivateKey get_private_key() public void add_online_user() { } public void get_online_users() { ArrayList<String> <API key> = record_table .get_online_users(); for (int i = 0; i < <API key>.size(); i++) { System.out.println(<API key>.get(i)); } } public void remove_online_user() { } // generate a cookie made from Hash(ip, Server's private key) static byte[] create_cookie(String ip_address, PrivateKey server_priv_key) { try { MessageDigest message_digest = MessageDigest .getInstance(hash_algorithm); message_digest.update(ip_address.getBytes()); message_digest.update(server_priv_key.getEncoded()); byte[] md = message_digest.digest(); return md; } catch (<API key> e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } } static private byte[] readBytesFromFile(String fileName) throws IOException { File f = new File(fileName); FileInputStream infile = new FileInputStream(f); byte[] bytes = new byte[(int) f.length()]; try { infile.read(bytes); return bytes; } finally { infile.close(); } } static SecretKey getW_by_name(String usr_name) { String file_name = record_table.get_password_path(usr_name); SecretKey w = null; try { w = PBEKeyGenerator.read_W_from_file(file_name); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return w; } static byte[] getY_by_name(String usr_name) { return record_table.get_private_key(usr_name); } }
#include <linux/kernel.h> #include <linux/spinlock.h> #include <linux/if_bridge.h> #include <asm/atomic.h> #include <asm/uaccess.h> #include "br_private.h" /* if topology_changing then use forward_delay (default 15 sec) * otherwise keep longer (default 5 minutes) */ static __inline__ unsigned long hold_time(const struct net_bridge *br) { return br->topology_change ? br->forward_delay : br->ageing_time; } static __inline__ int has_expired(const struct net_bridge *br, const struct <API key> *fdb) { return !fdb->is_static && time_before_eq(fdb->ageing_timer + hold_time(br), jiffies); } static __inline__ void copy_fdb(struct __fdb_entry *ent, const struct <API key> *f) { memset(ent, 0, sizeof(struct __fdb_entry)); memcpy(ent->mac_addr, f->addr.addr, ETH_ALEN); ent->port_no = f->dst?f->dst->port_no:0; ent->is_local = f->is_local; ent->ageing_timer_value = f->is_static ? 0 : ((jiffies - f->ageing_timer) * USER_HZ) / HZ; } static __inline__ int br_mac_hash(const unsigned char *mac) { unsigned long x; x = mac[0]; x = (x << 2) ^ mac[1]; x = (x << 2) ^ mac[2]; x = (x << 2) ^ mac[3]; x = (x << 2) ^ mac[4]; x = (x << 2) ^ mac[5]; x ^= x >> 8; return x & (BR_HASH_SIZE - 1); } static __inline__ void fdb_delete(struct <API key> *f) { hlist_del(&f->hlist); list_del(&f->age_list); br_fdb_put(f); } void br_fdb_changeaddr(struct net_bridge_port *p, const unsigned char *newaddr) { struct net_bridge *br; int i; int newhash = br_mac_hash(newaddr); br = p->br; write_lock_bh(&br->hash_lock); for (i=0;i<BR_HASH_SIZE;i++) { struct hlist_node *h; hlist_for_each(h, &br->hash[i]) { struct <API key> *f = hlist_entry(h, struct <API key>, hlist); if (f->dst == p && f->is_local) { memcpy(f->addr.addr, newaddr, ETH_ALEN); if (newhash != i) { hlist_del(&f->hlist); hlist_add_head(&f->hlist, &br->hash[newhash]); } goto out; } } } out: write_unlock_bh(&br->hash_lock); } void br_fdb_cleanup(unsigned long _data) { struct net_bridge *br = (struct net_bridge *)_data; struct list_head *l, *n; unsigned long delay; write_lock_bh(&br->hash_lock); delay = hold_time(br); list_for_each_safe(l, n, &br->age_list) { struct <API key> *f = list_entry(l, struct <API key>, age_list); unsigned long expires = f->ageing_timer + delay; if (time_before_eq(expires, jiffies)) { if (!f->is_static) { pr_debug("expire age %lu jiffies %lu\n", f->ageing_timer, jiffies); fdb_delete(f); } } else { mod_timer(&br->gc_timer, expires); break; } } write_unlock_bh(&br->hash_lock); } void <API key>(struct net_bridge *br, struct net_bridge_port *p) { int i; write_lock_bh(&br->hash_lock); for (i=0;i<BR_HASH_SIZE;i++) { struct hlist_node *h, *g; hlist_for_each_safe(h, g, &br->hash[i]) { struct <API key> *f = hlist_entry(h, struct <API key>, hlist); if (f->dst == p) { fdb_delete(f); } } } write_unlock_bh(&br->hash_lock); } struct <API key> *br_fdb_get(struct net_bridge *br, unsigned char *addr) { struct hlist_node *h; read_lock_bh(&br->hash_lock); hlist_for_each(h, &br->hash[br_mac_hash(addr)]) { struct <API key> *fdb = hlist_entry(h, struct <API key>, hlist); if (!memcmp(fdb->addr.addr, addr, ETH_ALEN)) { if (has_expired(br, fdb)) goto ret_null; atomic_inc(&fdb->use_count); read_unlock_bh(&br->hash_lock); return fdb; } } ret_null: read_unlock_bh(&br->hash_lock); return NULL; } void br_fdb_put(struct <API key> *ent) { if (atomic_dec_and_test(&ent->use_count)) kfree(ent); } int br_fdb_get_entries(struct net_bridge *br, unsigned char *_buf, int maxnum, int offset) { int i; int num; struct __fdb_entry *walk; num = 0; walk = (struct __fdb_entry *)_buf; read_lock_bh(&br->hash_lock); for (i=0;i<BR_HASH_SIZE;i++) { struct hlist_node *h; hlist_for_each(h, &br->hash[i]) { struct <API key> *f = hlist_entry(h, struct <API key>, hlist); struct __fdb_entry ent; if (num >= maxnum) goto out; if (has_expired(br, f)) continue; if (offset) { offset continue; } copy_fdb(&ent, f); atomic_inc(&f->use_count); read_unlock_bh(&br->hash_lock); if (copy_to_user(walk, &ent, sizeof(struct __fdb_entry))) return -EFAULT; read_lock_bh(&br->hash_lock); /* entry was deleted during copy_to_user */ if (atomic_dec_and_test(&f->use_count)) { kfree(f); num = -EAGAIN; goto out; } /* entry changed address hash while copying */ if (br_mac_hash(f->addr.addr) != i) { num = -EAGAIN; goto out; } num++; walk++; } } out: read_unlock_bh(&br->hash_lock); return num; } void br_fdb_insert(struct net_bridge *br, struct net_bridge_port *source, const unsigned char *addr, int is_local) { struct hlist_node *h; struct <API key> *fdb; int hash = br_mac_hash(addr); write_lock_bh(&br->hash_lock); hlist_for_each(h, &br->hash[hash]) { fdb = hlist_entry(h, struct <API key>, hlist); if (!memcmp(fdb->addr.addr, addr, ETH_ALEN)) { /* attempt to update an entry for a local interface */ if (unlikely(fdb->is_local)) { if (is_local) printk(KERN_INFO "%s: attempt to add" " interface with same source address.\n", source->dev->name); else if (net_ratelimit()) printk(KERN_WARNING "%s: received packet with " " own address as source address\n", source->dev->name); goto out; } if (likely(!fdb->is_static || is_local)) { /* move to end of age list */ list_del(&fdb->age_list); goto update; } goto out; } } fdb = kmalloc(sizeof(*fdb), GFP_ATOMIC); if (fdb == NULL) goto out; memcpy(fdb->addr.addr, addr, ETH_ALEN); atomic_set(&fdb->use_count, 1); hlist_add_head(&fdb->hlist, &br->hash[hash]); if (!timer_pending(&br->gc_timer)) { br->gc_timer.expires = jiffies + hold_time(br); add_timer(&br->gc_timer); } update: fdb->dst = source; fdb->is_local = is_local; fdb->is_static = is_local; fdb->ageing_timer = jiffies; list_add_tail(&fdb->age_list, &br->age_list); out: write_unlock_bh(&br->hash_lock); }
# The set of languages for which implicit dependencies are needed: set(<API key> "CXX" ) # The set of files for implicit dependencies of each language: set(<API key> "/home/frans/Documents/cpp/sfml/ld33-zoq/src/bloodsplatter.cpp" "/home/frans/Documents/cpp/sfml/ld33-zoq/build/CMakeFiles/SharedCode.dir/bloodsplatter.cpp.o" "/home/frans/Documents/cpp/sfml/ld33-zoq/src/civilian.cpp" "/home/frans/Documents/cpp/sfml/ld33-zoq/build/CMakeFiles/SharedCode.dir/civilian.cpp.o" "/home/frans/Documents/cpp/sfml/ld33-zoq/src/engine/entity.cpp" "/home/frans/Documents/cpp/sfml/ld33-zoq/build/CMakeFiles/SharedCode.dir/engine/entity.cpp.o" "/home/frans/Documents/cpp/sfml/ld33-zoq/src/engine/entitygroup.cpp" "/home/frans/Documents/cpp/sfml/ld33-zoq/build/CMakeFiles/SharedCode.dir/engine/entitygroup.cpp.o" "/home/frans/Documents/cpp/sfml/ld33-zoq/src/engine/ground.cpp" "/home/frans/Documents/cpp/sfml/ld33-zoq/build/CMakeFiles/SharedCode.dir/engine/ground.cpp.o" "/home/frans/Documents/cpp/sfml/ld33-zoq/src/engine/humanentity.cpp" "/home/frans/Documents/cpp/sfml/ld33-zoq/build/CMakeFiles/SharedCode.dir/engine/humanentity.cpp.o" "/home/frans/Documents/cpp/sfml/ld33-zoq/src/engine/line.cpp" "/home/frans/Documents/cpp/sfml/ld33-zoq/build/CMakeFiles/SharedCode.dir/engine/line.cpp.o" "/home/frans/Documents/cpp/sfml/ld33-zoq/src/engine/mouseeventhandler.cpp" "/home/frans/Documents/cpp/sfml/ld33-zoq/build/CMakeFiles/SharedCode.dir/engine/mouseeventhandler.cpp.o" "/home/frans/Documents/cpp/sfml/ld33-zoq/src/engine/physicsentity.cpp" "/home/frans/Documents/cpp/sfml/ld33-zoq/build/CMakeFiles/SharedCode.dir/engine/physicsentity.cpp.o" "/home/frans/Documents/cpp/sfml/ld33-zoq/src/engine/platform.cpp" "/home/frans/Documents/cpp/sfml/ld33-zoq/build/CMakeFiles/SharedCode.dir/engine/platform.cpp.o" "/home/frans/Documents/cpp/sfml/ld33-zoq/src/engine/sprite.cpp" "/home/frans/Documents/cpp/sfml/ld33-zoq/build/CMakeFiles/SharedCode.dir/engine/sprite.cpp.o" "/home/frans/Documents/cpp/sfml/ld33-zoq/src/engine/spriteentity.cpp" "/home/frans/Documents/cpp/sfml/ld33-zoq/build/CMakeFiles/SharedCode.dir/engine/spriteentity.cpp.o" "/home/frans/Documents/cpp/sfml/ld33-zoq/src/engine/vec2f.cpp" "/home/frans/Documents/cpp/sfml/ld33-zoq/build/CMakeFiles/SharedCode.dir/engine/vec2f.cpp.o" "/home/frans/Documents/cpp/sfml/ld33-zoq/src/engine/world.cpp" "/home/frans/Documents/cpp/sfml/ld33-zoq/build/CMakeFiles/SharedCode.dir/engine/world.cpp.o" "/home/frans/Documents/cpp/sfml/ld33-zoq/src/engine/zui/button.cpp" "/home/frans/Documents/cpp/sfml/ld33-zoq/build/CMakeFiles/SharedCode.dir/engine/zui/button.cpp.o" "/home/frans/Documents/cpp/sfml/ld33-zoq/src/engine/zui/imglist.cpp" "/home/frans/Documents/cpp/sfml/ld33-zoq/build/CMakeFiles/SharedCode.dir/engine/zui/imglist.cpp.o" "/home/frans/Documents/cpp/sfml/ld33-zoq/src/engine/zui/imglistelement.cpp" "/home/frans/Documents/cpp/sfml/ld33-zoq/build/CMakeFiles/SharedCode.dir/engine/zui/imglistelement.cpp.o" "/home/frans/Documents/cpp/sfml/ld33-zoq/src/engine/zui/inputcomponent.cpp" "/home/frans/Documents/cpp/sfml/ld33-zoq/build/CMakeFiles/SharedCode.dir/engine/zui/inputcomponent.cpp.o" "/home/frans/Documents/cpp/sfml/ld33-zoq/src/engine/zui/textbutton.cpp" "/home/frans/Documents/cpp/sfml/ld33-zoq/build/CMakeFiles/SharedCode.dir/engine/zui/textbutton.cpp.o" "/home/frans/Documents/cpp/sfml/ld33-zoq/src/engine/zui/uicomponent.cpp" "/home/frans/Documents/cpp/sfml/ld33-zoq/build/CMakeFiles/SharedCode.dir/engine/zui/uicomponent.cpp.o" "/home/frans/Documents/cpp/sfml/ld33-zoq/src/engine/zui/window.cpp" "/home/frans/Documents/cpp/sfml/ld33-zoq/build/CMakeFiles/SharedCode.dir/engine/zui/window.cpp.o" "/home/frans/Documents/cpp/sfml/ld33-zoq/src/hidingspot.cpp" "/home/frans/Documents/cpp/sfml/ld33-zoq/build/CMakeFiles/SharedCode.dir/hidingspot.cpp.o" "/home/frans/Documents/cpp/sfml/ld33-zoq/src/hidingspottemplate.cpp" "/home/frans/Documents/cpp/sfml/ld33-zoq/build/CMakeFiles/SharedCode.dir/hidingspottemplate.cpp.o" "/home/frans/Documents/cpp/sfml/ld33-zoq/src/player.cpp" "/home/frans/Documents/cpp/sfml/ld33-zoq/build/CMakeFiles/SharedCode.dir/player.cpp.o" "/home/frans/Documents/cpp/sfml/ld33-zoq/src/soldier.cpp" "/home/frans/Documents/cpp/sfml/ld33-zoq/build/CMakeFiles/SharedCode.dir/soldier.cpp.o" ) set(<API key> "GNU") # The include file search paths: set(<API key> "." "/usr/local/include" ) # Targets to which this target links. set(<API key> )
<?php // no direct access defined( '_JEXEC' ) or die( 'Restricted access' ); ?> <!DOCTYPE html PUBLIC "- <html xmlns="http: <head> <jdoc:include type="head" /> <link rel="stylesheet" href="<?php echo $this->baseurl ?>/templates/system/css/system.css" type="text/css" /> <link rel="stylesheet" href="<?php echo $this->baseurl ?>/templates/system/css/general.css" type="text/css" /> <link rel="stylesheet" href="<?php echo $this->baseurl ?>/templates/eedz/css/template.css" type="text/css" /> </head> <body> <div id="whole"> <!-- HEADER starts --> <div id="header"> <div id="topmenu"> <div class="bangla"> <a href=""><img src="<?php echo $this->baseurl ?>/templates/eedz/images/banglashongskoron.png" class="banglalink"/></a> </div> <div class="toplinks"> <a href="">Home </a> | <a href="">About </a> | <a href="">Contact </a> | <a href="">Login </a> | <a href="">Web Mail </a> </div> </div> <div id="searchportion"> <div class="searcharea2"><jdoc:include type="modules" name="search" /> <!-- <input type="text" value="" class="searchall"><input type="button" value="Search" class="searchbutton"> --> </div> </div> </div><!-- HEADER ends --> <div id="content"> <!-- LEFT AREA STARTS --> <div id="leftarea"> <div class="linksarea"> <div class="menuheading"><div class="menuheadingtitle">Main Menu</div></div> <jdoc:include type="modules" name="LeftMenu1" /> </div> <div class="linksarea"> <div class="menuheading"><div class="menuheadingtitle">Tender</div></div> <a href="http: <jdoc:include type="modules" name="LeftMenu4" /> <center><a href="http: </a> </div> <div class="linksarea"> <div class="menuheading"><div class="menuheadingtitle">Circuler</div></div> <jdoc:include type="modules" name="LeftMenu5" /> </div> <div class="linksarea"> <div class="menuheading"><div class="menuheadingtitle">Public Procurement</div></div> <jdoc:include type="modules" name="LeftMenu3" /> </div> <div class="linksarea"> <div class="menuheading"><div class="menuheadingtitle">Quick Links</div></div> <jdoc:include type="modules" name="rightQuickLink" /> </div> </div> <!-- LEFT AREA ENDS --> <div id="middlearea"> <?php if ($this->countModules('mainBanner')) { ?> <div class="sliderarea"><jdoc:include type="modules" name="mainBanner" /></div> <?php }else{ ?> <div id="breadcrumbs"> <jdoc:include type="modules" name="breadcrumbs" /> </div> <?php } ?> <div><jdoc:include type="message" /><jdoc:include type="component" /></div> </div> <?php if ($this->countModules('mainBanner')) { ?> <div id="rightarea"> <div class="linksarea" style="width:198px"> <div class="menuheading"><div class="menuheadingtitle">Chief Engineer's Corner</div></div> <div class="edumin1"> <a href="http://eedmoe.gov.bd/index.php/message/<API key>"> <img src="images/chfeng.jpg" title="Chief Engineer of EED"/> </a> </div> <div class="edumin2"> <a href=""> <b>Abdullahil Azad</b> <br><b>Chief Engineer, EED</b> </a> </div> <div class="edumin3"> <a href=""> At present decade, technology has become... [read more] </a> </div> </div> <div class="linksarea"> <div class="menuheading"><div class="menuheadingtitle">EED News</div></div> <jdoc:include type="modules" name="rightMenu3" /> </div> <div class="linksarea"> <div class="menuheading"><div class="menuheadingtitle">Notice Board</div></div> <jdoc:include type="modules" name="rightMenu4" /> </div> <div class="linksarea"> <div class="menuheading"><div class="menuheadingtitle">E-KOSH</div></div> <div class="ekosh"><a href="http: </div> </div> <?php }else{}?> </div> <div id="footer"> <div class="footerleft">Copyright &copy; 2013 <a href="">EED, Shikkha Bhaban</a> | Designed & Developed by <a href="http: </div> <div class="footerright"> <a href="">FAQ</a> | <a href="">Site Map</a> | <a href="">Privacy Policy</a> | <a href="">Terms & Conditions</a> </div> </div> </div> </body> </html>
package com.fasterxml.jackson.databind.deser.impl; import java.io.IOException; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonToken; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.deser.NullValueProvider; import com.fasterxml.jackson.databind.deser.<API key>; import com.fasterxml.jackson.databind.introspect.AnnotatedField; import com.fasterxml.jackson.databind.introspect.AnnotatedMember; import com.fasterxml.jackson.databind.introspect.<API key>; import com.fasterxml.jackson.databind.jsontype.TypeDeserializer; import com.fasterxml.jackson.databind.util.Annotations; import com.fasterxml.jackson.databind.util.ClassUtil; /** * This concrete sub-class implements property that is set * directly assigning to a Field. */ public final class FieldProperty extends <API key> { private static final long serialVersionUID = 1L; final protected AnnotatedField _annotated; /** * Actual field to set when deserializing this property. * Transient since there is no need to persist; only needed during * construction of objects. */ final protected transient Field _field; /** * @since 2.9 */ final protected boolean _skipNulls; public FieldProperty(<API key> propDef, JavaType type, TypeDeserializer typeDeser, Annotations contextAnnotations, AnnotatedField field) { super(propDef, type, typeDeser, contextAnnotations); _annotated = field; _field = field.getAnnotated(); _skipNulls = <API key>.isSkipper(_nullProvider); } protected FieldProperty(FieldProperty src, JsonDeserializer<?> deser, NullValueProvider nva) { super(src, deser, nva); _annotated = src._annotated; _field = src._field; _skipNulls = <API key>.isSkipper(nva); } protected FieldProperty(FieldProperty src, PropertyName newName) { super(src, newName); _annotated = src._annotated; _field = src._field; _skipNulls = src._skipNulls; } /** * Constructor used for JDK Serialization when reading persisted object */ protected FieldProperty(FieldProperty src) { super(src); _annotated = src._annotated; Field f = _annotated.getAnnotated(); if (f == null) { throw new <API key>("Missing field (broken JDK (de)serialization?)"); } _field = f; _skipNulls = src._skipNulls; } @Override public <API key> withName(PropertyName newName) { return new FieldProperty(this, newName); } @Override public <API key> <API key>(JsonDeserializer<?> deser) { if (_valueDeserializer == deser) { return this; } return new FieldProperty(this, deser, _nullProvider); } @Override public <API key> withNullProvider(NullValueProvider nva) { return new FieldProperty(this, _valueDeserializer, nva); } @Override public void fixAccess(<API key> config) { ClassUtil.checkAndFixAccess(_field, config.isEnabled(MapperFeature.<API key>)); } @Override public <A extends Annotation> A getAnnotation(Class<A> acls) { return (_annotated == null) ? null : _annotated.getAnnotation(acls); } @Override public AnnotatedMember getMember() { return _annotated; } @Override public void deserializeAndSet(JsonParser p, <API key> ctxt, Object instance) throws IOException { Object value; if (p.hasToken(JsonToken.VALUE_NULL)) { if (_skipNulls) { return; } value = _nullProvider.getNullValue(ctxt); } else if (<API key> == null) { value = _valueDeserializer.deserialize(p, ctxt); } else { value = _valueDeserializer.deserializeWithType(p, ctxt, <API key>); } try { _field.set(instance, value); } catch (Exception e) { _throwAsIOE(p, e, value); } } @Override public Object <API key>(JsonParser p, <API key> ctxt, Object instance) throws IOException { Object value; if (p.hasToken(JsonToken.VALUE_NULL)) { if (_skipNulls) { return instance; } value = _nullProvider.getNullValue(ctxt); } else if (<API key> == null) { value = _valueDeserializer.deserialize(p, ctxt); } else { value = _valueDeserializer.deserializeWithType(p, ctxt, <API key>); } try { _field.set(instance, value); } catch (Exception e) { _throwAsIOE(p, e, value); } return instance; } @Override public void set(Object instance, Object value) throws IOException { try { _field.set(instance, value); } catch (Exception e) { // 15-Sep-2015, tatu: How could we get a ref to JsonParser? _throwAsIOE(e, value); } } @Override public Object setAndReturn(Object instance, Object value) throws IOException { try { _field.set(instance, value); } catch (Exception e) { // 15-Sep-2015, tatu: How could we get a ref to JsonParser? _throwAsIOE(e, value); } return instance; } Object readResolve() { return new FieldProperty(this); } }
# The Enchiridion of Epictetus [![License: GPL v2](https: [![Buy Me a Coffee](https: The *Enchiridion*, or *Manual*, of Epictetus &#8230; is a short manual of Stoic ethical advice compiled by Arrian, a 2<sup>nd</sup>-century disciple of the Greek philosopher Epictetus (see [Wikipedia](https://en.wikipedia.org/wiki/<API key>)). This projects presents the Enchiridion set in LaTeX as a pdf ebook. A notable feature of this project is that the translation of the Enchiridion can be chosen at compile time by running `make <translator's last name>`. For example, compiling with `make higginson` will compile Thomas Wentworth Higginson's translation of the Enchiridion. If no translator is specified with `make` then Carter's translation is used. The following is a list of download links (pdf) for each currently available translation, along with a link to an online source for each: - [Elizabeth Carter][carter-file] ([Source][carter-source]) - [Thomas Wentworth Higginson][higginson-file] ([Source][higginson-source]) - [P.E. Matheson][matheson-file] ([Source][matheson-source]) - [George Long][long-file] ([Source][long-source]) - [Thomas William Rolleston][rolleston-file] ([Source][rolleston-source]) [carter-file]: https://raw.githubusercontent.com/mapierce271/Enchiridion/master/all-versions/enchiridion-carter.pdf [carter-source]: https://archive.org/details/<API key> [higginson-file]: https://raw.githubusercontent.com/mapierce271/Enchiridion/master/all-versions/<API key>.pdf [higginson-source]: http: [matheson-file]: https://raw.githubusercontent.com/mapierce271/Enchiridion/master/all-versions/<API key>.pdf [matheson-source]: http: [long-file]: https://raw.githubusercontent.com/mapierce271/Enchiridion/master/all-versions/enchiridion-long.pdf [long-source]: http: [rolleston-file]: https://raw.githubusercontent.com/mapierce271/Enchiridion/master/all-versions/<API key>.pdf [rolleston-source]: http:
#ifndef <API key> #define <API key> #include "extended/node_stream_api.h" /* Implements the <<API key>> interface. This stream is only used to store pointers to external callbacks, e.g. written in a scripting language. This class does not store any state or logic, relying on the developer of the external custom stream class to do so. */ typedef struct <API key> <API key>; typedef int (*<API key>)(GtGenomeNode **gn, GtError *err); typedef int (*<API key>)(void*); const GtNodeStreamClass* <API key>(void); GtNodeStream* <API key>(<API key>, <API key>); #endif
#ifndef DETAILEDQMLVIEW_H #define DETAILEDQMLVIEW_H #include <QWidget> #include <QDeclarativeContext> #include "<API key>.h" #include "element.h" class DetailedQmlView : public QWidget { Q_OBJECT public: DetailedQmlView(QWidget *parent); ~DetailedQmlView(); public slots: /** * Set @p el as the element to be drawn */ void setElement(int el); void itemPressed(); private: <API key> *m_elementProperty; Element *m_element; QDeclarativeContext *m_context; protected: /** * Generic event handler, currently defaults to calling parent class * (included for future compatibility) */ // bool event(QEvent *e); /** * is caled every time the view is resized. */ void resizeEvent(QResizeEvent * event); }; #endif //DETAILEDQMLVIEW_H
""" togePy.pkmn_test This module tests functionality for togePy """ import pokeStructs import cPickle as pickle import random import numpy as np # Load Data with open('pokedex', 'rb') as f: pokedex = pickle.load(f) with open('abilities', 'rb') as f: abilities = pickle.load(f) with open('items', 'rb') as f: items = pickle.load(f) with open('moves', 'rb') as f: moves = pickle.load(f) # Create Test Data Suite def random_Move(only_dmg = True): if only_dmg: is_dmg = False while is_dmg == False: m = moves[random.choice(moves.keys())] is_dmg = (m.Damage in ('physical', 'special')) return m else: return moves[random.choice(moves.keys())] def random_Moveset(only_dmg = True): ms = pokeStructs.Moveset() ms.set_All([random_Move(only_dmg) for _ in xrange(4)]) return ms def random_Poke(): def random_EVs(): EV = np.random.randint(256, size=6).astype(float) while EV.sum() != 510 or any(EV > 255): EV_old = EV if EV.sum() != 510: EV = np.round(510./EV.sum()*EV) EV[EV > 255] = 255 if all(EV_old == EV): EV = np.random.randint(256, size=6).astype(float) return pokeStructs.createEVs(EV.astype(int).tolist()) def random_IVs(): return pokeStructs.createIVs(np.random.randint(32, size=6).tolist()) def random_Nature(): return random.choice(['Hardy', 'Lonely', 'Brave', 'Adamant', 'Naughty', 'Bold', 'Docile', 'Relaxed', 'Impish', 'Lax', 'Timid', 'Hasty', 'Serious', 'Jolly', 'Naive', 'Modest', 'Mild', 'Quiet', 'Bashful', 'Rash', 'Calm', 'Gentle', 'Sassy', 'Careful', 'Quirky']) def random_Happiness(): return random.randint(0,255) def random_Ability(): return random.choice(p_dex.Abilities) def random_Moves(): return random_Moveset() p_dex = pokedex[random.choice(pokedex.keys())] p = pokeStructs.Pokemon(p_dex, np.random.randint(1, 101), random_EVs(), random_IVs(), random_Nature(), random_Happiness(), random_Ability(), random_Moves(), random.choice(items.keys())) p.CurHP = int(np.round(p.CurHP * np.random.random())) p.Status = random.choice([None, 'FZN', 'PAR', 'SLP', 'PSN', 'BRN']) return p def random_Team(): t = pokeStructs.Team('Random Team') t.set_All([random_Poke() for _ in xrange(6)]) return t def restore_Team(t): for p in t.Members.values(): p.CurHP = p.Stats['HP'] p.Status = None def nature_list(): l_natures = ['Hardy', 'Lonely', 'Brave', 'Adamant', 'Naughty', 'Bold', 'Docile', 'Relaxed', 'Impish', 'Lax', 'Timid', 'Hasty', 'Serious', 'Jolly', 'Naive', 'Modest', 'Mild', 'Quiet', 'Bashful', 'Rash', 'Calm', 'Gentle', 'Sassy', 'Careful', 'Quirky'] return l_natures if __name__ == '__main__': print 'Ready'
#ifndef __HYPERCALL_H__ #define __HYPERCALL_H__ #include <linux/errno.h> #include <linux/string.h> #include <xen/interface/xen.h> #include <xen/interface/sched.h> #include <xen/interface/physdev.h> extern struct { char _entry[32]; } hypercall_page[]; #define _hypercall0(type, name) \ ({ \ long __res; \ asm volatile ( \ "call %[call]" \ : "=a" (__res) \ : [call] "m" (hypercall_page[__HYPERVISOR_##name]) \ : "memory" ); \ (type)__res; \ }) #define _hypercall1(type, name, a1) \ ({ \ long __res, __ign1; \ asm volatile ( \ "call %[call]" \ : "=a" (__res), "=b" (__ign1) \ : "1" ((long)(a1)), \ [call] "m" (hypercall_page[__HYPERVISOR_##name]) \ : "memory" ); \ (type)__res; \ }) #define _hypercall2(type, name, a1, a2) \ ({ \ long __res, __ign1, __ign2; \ asm volatile ( \ "call %[call]" \ : "=a" (__res), "=b" (__ign1), "=c" (__ign2) \ : "1" ((long)(a1)), "2" ((long)(a2)), \ [call] "m" (hypercall_page[__HYPERVISOR_##name]) \ : "memory" ); \ (type)__res; \ }) #define _hypercall3(type, name, a1, a2, a3) \ ({ \ long __res, __ign1, __ign2, __ign3; \ asm volatile ( \ "call %[call]" \ : "=a" (__res), "=b" (__ign1), "=c" (__ign2), \ "=d" (__ign3) \ : "1" ((long)(a1)), "2" ((long)(a2)), \ "3" ((long)(a3)), \ [call] "m" (hypercall_page[__HYPERVISOR_##name]) \ : "memory" ); \ (type)__res; \ }) #define _hypercall4(type, name, a1, a2, a3, a4) \ ({ \ long __res, __ign1, __ign2, __ign3, __ign4; \ asm volatile ( \ "call %[call]" \ : "=a" (__res), "=b" (__ign1), "=c" (__ign2), \ "=d" (__ign3), "=S" (__ign4) \ : "1" ((long)(a1)), "2" ((long)(a2)), \ "3" ((long)(a3)), "4" ((long)(a4)), \ [call] "m" (hypercall_page[__HYPERVISOR_##name]) \ : "memory" ); \ (type)__res; \ }) #define _hypercall5(type, name, a1, a2, a3, a4, a5) \ ({ \ long __res, __ign1, __ign2, __ign3, __ign4, __ign5; \ asm volatile ( \ "call %[call]" \ : "=a" (__res), "=b" (__ign1), "=c" (__ign2), \ "=d" (__ign3), "=S" (__ign4), "=D" (__ign5) \ : "1" ((long)(a1)), "2" ((long)(a2)), \ "3" ((long)(a3)), "4" ((long)(a4)), \ "5" ((long)(a5)), \ [call] "m" (hypercall_page[__HYPERVISOR_##name]) \ : "memory" ); \ (type)__res; \ }) static inline int <API key>(struct trap_info *table) { return _hypercall1(int, set_trap_table, table); } static inline int <API key>(struct mmu_update *req, int count, int *success_count, domid_t domid) { return _hypercall4(int, mmu_update, req, count, success_count, domid); } static inline int <API key>(struct mmuext_op *op, int count, int *success_count, domid_t domid) { return _hypercall4(int, mmuext_op, op, count, success_count, domid); } static inline int HYPERVISOR_set_gdt(unsigned long *frame_list, int entries) { return _hypercall2(int, set_gdt, frame_list, entries); } static inline int <API key>(unsigned long ss, unsigned long esp) { return _hypercall2(int, stack_switch, ss, esp); } static inline int <API key>(unsigned long event_selector, unsigned long event_address, unsigned long failsafe_selector, unsigned long failsafe_address) { return _hypercall4(int, set_callbacks, event_selector, event_address, failsafe_selector, failsafe_address); } static inline int <API key>(int set) { return _hypercall1(int, fpu_taskswitch, set); } static inline int HYPERVISOR_sched_op(int cmd, unsigned long arg) { return _hypercall2(int, sched_op, cmd, arg); } static inline long <API key>(u64 timeout) { unsigned long timeout_hi = (unsigned long)(timeout>>32); unsigned long timeout_lo = (unsigned long)timeout; return _hypercall2(long, set_timer_op, timeout_lo, timeout_hi); } static inline int <API key>(int reg, unsigned long value) { return _hypercall2(int, set_debugreg, reg, value); } static inline unsigned long <API key>(int reg) { return _hypercall1(unsigned long, get_debugreg, reg); } static inline int <API key>(u64 ma, u64 desc) { return _hypercall4(int, update_descriptor, ma, ma>>32, desc, desc>>32); } static inline int <API key>(unsigned int cmd, void *arg) { return _hypercall2(int, memory_op, cmd, arg); } static inline int <API key>(void *call_list, int nr_calls) { return _hypercall2(int, multicall, call_list, nr_calls); } static inline int <API key>(unsigned long va, pte_t new_val, unsigned long flags) { unsigned long pte_hi = 0; #ifdef CONFIG_X86_PAE pte_hi = new_val.pte_high; #endif return _hypercall4(int, update_va_mapping, va, new_val.pte_low, pte_hi, flags); } static inline int <API key>(int cmd, void *arg) { int rc = _hypercall2(int, event_channel_op, cmd, arg); if (unlikely(rc == -ENOSYS)) { struct evtchn_op op; op.cmd = cmd; memcpy(&op.u, arg, sizeof(op.u)); rc = _hypercall1(int, <API key>, &op); memcpy(arg, &op.u, sizeof(op.u)); } return rc; } static inline int <API key>(int cmd, void *arg) { return _hypercall2(int, xen_version, cmd, arg); } static inline int <API key>(int cmd, int count, char *str) { return _hypercall3(int, console_io, cmd, count, str); } static inline int <API key>(int cmd, void *arg) { int rc = _hypercall2(int, physdev_op, cmd, arg); if (unlikely(rc == -ENOSYS)) { struct physdev_op op; op.cmd = cmd; memcpy(&op.u, arg, sizeof(op.u)); rc = _hypercall1(int, physdev_op_compat, &op); memcpy(arg, &op.u, sizeof(op.u)); } return rc; } static inline int <API key>(unsigned int cmd, void *uop, unsigned int count) { return _hypercall3(int, grant_table_op, cmd, uop, count); } static inline int <API key>(unsigned long va, pte_t new_val, unsigned long flags, domid_t domid) { unsigned long pte_hi = 0; #ifdef CONFIG_X86_PAE pte_hi = new_val.pte_high; #endif return _hypercall5(int, <API key>, va, new_val.pte_low, pte_hi, flags, domid); } static inline int <API key>(unsigned int cmd, unsigned int type) { return _hypercall2(int, vm_assist, cmd, type); } static inline int HYPERVISOR_vcpu_op(int cmd, int vcpuid, void *extra_args) { return _hypercall3(int, vcpu_op, cmd, vcpuid, extra_args); } static inline int HYPERVISOR_suspend(unsigned long srec) { return _hypercall3(int, sched_op, SCHEDOP_shutdown, SHUTDOWN_suspend, srec); } static inline int HYPERVISOR_nmi_op(unsigned long op, unsigned long arg) { return _hypercall2(int, nmi_op, op, arg); } static inline void <API key>(struct multicall_entry *mcl, unsigned long va, pte_t new_val, unsigned long flags) { mcl->op = <API key>; mcl->args[0] = va; #ifdef CONFIG_X86_PAE mcl->args[1] = new_val.pte_low; mcl->args[2] = new_val.pte_high; #else mcl->args[1] = new_val.pte_low; mcl->args[2] = 0; #endif mcl->args[3] = flags; } static inline void <API key>(struct multicall_entry *mcl, unsigned int cmd, void *uop, unsigned int count) { mcl->op = <API key>; mcl->args[0] = cmd; mcl->args[1] = (unsigned long)uop; mcl->args[2] = count; } static inline void <API key>(struct multicall_entry *mcl, unsigned long va, pte_t new_val, unsigned long flags, domid_t domid) { mcl->op = <API key>; mcl->args[0] = va; #ifdef CONFIG_X86_PAE mcl->args[1] = new_val.pte_low; mcl->args[2] = new_val.pte_high; #else mcl->args[1] = new_val.pte_low; mcl->args[2] = 0; #endif mcl->args[3] = flags; mcl->args[4] = domid; } static inline void <API key>(struct multicall_entry *mcl, u64 maddr, struct desc_struct desc) { mcl->op = <API key>; mcl->args[0] = maddr; mcl->args[1] = maddr >> 32; mcl->args[2] = desc.a; mcl->args[3] = desc.b; } static inline void MULTI_memory_op(struct multicall_entry *mcl, unsigned int cmd, void *arg) { mcl->op = <API key>; mcl->args[0] = cmd; mcl->args[1] = (unsigned long)arg; } static inline void MULTI_mmu_update(struct multicall_entry *mcl, struct mmu_update *req, int count, int *success_count, domid_t domid) { mcl->op = <API key>; mcl->args[0] = (unsigned long)req; mcl->args[1] = count; mcl->args[2] = (unsigned long)success_count; mcl->args[3] = domid; } static inline void MULTI_mmuext_op(struct multicall_entry *mcl, struct mmuext_op *op, int count, int *success_count, domid_t domid) { mcl->op = <API key>; mcl->args[0] = (unsigned long)op; mcl->args[1] = count; mcl->args[2] = (unsigned long)success_count; mcl->args[3] = domid; } static inline void MULTI_set_gdt(struct multicall_entry *mcl, unsigned long *frames, int entries) { mcl->op = <API key>; mcl->args[0] = (unsigned long)frames; mcl->args[1] = entries; } static inline void MULTI_stack_switch(struct multicall_entry *mcl, unsigned long ss, unsigned long esp) { mcl->op = <API key>; mcl->args[0] = ss; mcl->args[1] = esp; } #endif
/** * Create two surfaces difference structure * Pinta project was very helpful */ #include "commonDefs.h" #define DEBUG_DIFF 0 #define <API key> 10 jboolean <API key>(JNIEnv *env, jobject obj, jintArray original, jobject updatedSurf, jobject diffResult) { jint* originalPixels; AndroidBitmapInfo updatedInfo; uint32_t* updatedPixels; int ret; // STEP 1 - Find the bounds of the changed pixels. if ((ret = <API key>(env, updatedSurf, &updatedInfo)) < 0) { LOGE("<API key>() failed ! error=%d", ret); return JNI_FALSE; } if (updatedInfo.format != <API key>) { LOGE("Updated surface bitmap format is not RGBA_8888!"); return JNI_FALSE; } uint32_t originalWidth = updatedInfo.width; uint32_t originalHeight = updatedInfo.height; <API key>(env, updatedSurf, (void*)&updatedPixels); originalPixels = (*env)->GetIntArrayElements(env, original, NULL); uint32_t* originalPtr = originalPixels; uint32_t* updatedPtr = updatedPixels; int32_t myBoundLeft = originalWidth + 1; int32_t myBoundRight = -1; int32_t myBoundTop = originalHeight + 1; int32_t myBoundBottom = -1; for (int row = 0; row < originalHeight; row += 1) { int isChangeInRow = 0; for (int i = 0; i < originalWidth; i += 1) { if (*originalPtr++ != *updatedPtr++) { isChangeInRow = 1; myBoundLeft = min(myBoundLeft, i); myBoundRight = max(myBoundRight, i); } } if (isChangeInRow) { myBoundTop = min(myBoundTop, row); myBoundBottom = max(myBoundBottom, row); } } int boundWidth = myBoundRight - myBoundLeft; int boundHeight = myBoundBottom - myBoundTop; if (DEBUG_DIFF) LOGI("Truncated surface size: %dx%d", boundWidth, boundHeight); // STEP 2 - Create a bitarray of whether each pixel in the bounds has changed, and count // how many changed pixels we need to store. uint32_t bitmaskLength = (boundWidth + 1) * (boundHeight + 1); char* bitmask = malloc(bitmaskLength); int32_t numChanged = 0; char* bitmaskPtr = bitmask; for (int y = myBoundTop; y <= myBoundBottom; y += 1) { originalPtr = originalPixels + y * originalWidth + myBoundLeft; updatedPtr = updatedPixels + y * originalWidth + myBoundLeft; for (int x = myBoundLeft; x <= myBoundRight; x += 1) { if (*bitmaskPtr++ = *originalPtr++ != *updatedPtr++) numChanged += 1; } } <API key>(env, updatedSurf); int savings = (int) (100 - (float) numChanged / (float) (originalWidth * originalHeight) * 100); if (DEBUG_DIFF) LOGI("Compressed bitmask: %d/%d = %d%%", numChanged, originalHeight * originalWidth, 100 - savings); if (savings < <API key>) { free(bitmask); return JNI_FALSE; } // Store the old pixels. int32_t* pixels = malloc(numChanged * sizeof(int32_t)); int32_t* pixelsPtr = pixels; bitmaskPtr = bitmask; for (int y = myBoundTop; y <= myBoundBottom; y += 1) { originalPtr = originalPixels + y * originalWidth + myBoundLeft; for (int x = myBoundLeft; x <= myBoundRight; x += 1) { if (*bitmaskPtr) *pixelsPtr++ = *originalPtr; bitmaskPtr += 1; originalPtr += 1; } } (*env)-><API key>(env, original, originalPixels, 0); // Make return object jclass cls = (*env)->FindClass(env, "org/opentalking/drawskill/SurfaceDiff$DiffResult"); jfieldID fld = (*env)->GetFieldID(env, cls, "boundLeft", "I"); (*env)->SetIntField(env, diffResult, fld, myBoundLeft); fld = (*env)->GetFieldID(env, cls, "boundRight", "I"); (*env)->SetIntField(env, diffResult, fld, myBoundRight); fld = (*env)->GetFieldID(env, cls, "boundTop", "I"); (*env)->SetIntField(env, diffResult, fld, myBoundTop); fld = (*env)->GetFieldID(env, cls, "boundBottom", "I"); (*env)->SetIntField(env, diffResult, fld, myBoundBottom); jbooleanArray bitmaskArr = (*env)->NewBooleanArray(env, bitmaskLength); if (NULL == bitmaskArr) { free(bitmask); free(pixels); return JNI_FALSE; } (*env)->SetByteArrayRegion(env, bitmaskArr, 0, bitmaskLength, bitmask); fld = (*env)->GetFieldID(env, cls, "bitmask", "[Z"); (*env)->SetObjectField(env, diffResult, fld, bitmaskArr); (*env)->DeleteLocalRef(env, bitmaskArr); jintArray pixelsArr = (*env)->NewIntArray(env, numChanged); if (NULL == pixelsArr) { free(bitmask); free(pixels); return JNI_FALSE; } (*env)->SetIntArrayRegion(env, pixelsArr, 0, numChanged, pixels); fld = (*env)->GetFieldID(env, cls, "pixels", "[I"); (*env)->SetObjectField(env, diffResult, fld, pixelsArr); (*env)->DeleteLocalRef(env, pixelsArr); free(bitmask); free(pixels); return JNI_TRUE; }
// $Id: writer.h,v 1.8 2002/07/02 22:11:10 t1mpy Exp $ // id3lib: a software library for creating and manipulating id3v1/v2 tags // This library is free software; you can redistribute it and/or modify it // option) any later version. // This library is distributed in the hope that it will be useful, but WITHOUT // FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public // along with this library; if not, write to the Free Software Foundation, // Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // The id3lib authors encourage improvements and optimisations to be sent to // the id3lib coordinator. Please see the README file for details on where to // send such submissions. See the AUTHORS file for a list of people who have // contributed to id3lib. See the ChangeLog file for a list of changes to // id3lib. These files are distributed with id3lib at #ifndef _ID3LIB_WRITER_H_ #define _ID3LIB_WRITER_H_ #include "id3/globals.h" //has <stdlib.h> "id3/sized_types.h" class ID3_CPP_EXPORT ID3_Writer { public: typedef uint32 size_type; typedef uint8 char_type; typedef uint32 pos_type; typedef int32 off_type; typedef int16 int_type; static const int_type END_OF_WRITER; /** Close the writer. Any further actions on the writer should fail. **/ virtual void close() = 0; /** Flush the writer. **/ virtual void flush() = 0; /** Return the beginning position in the writer **/ virtual pos_type getBeg() { return static_cast<pos_type>(0); } /** Return the first position that can't be written to. A return value of ** -1 indicates no (reasonable) limit to the writer. **/ virtual pos_type getEnd() { return static_cast<pos_type>(-1); } /** Return the next position that will be written to */ virtual pos_type getCur() = 0; /** Return the number of bytes written **/ virtual size_type getSize() { return this->getCur() - this->getBeg(); } /** Return the maximum number of bytes that can be written **/ virtual size_type getMaxSize() { return this->getEnd() - this->getBeg(); } /** Write a single character and advance the internal position. Note that ** the interal position may advance more than one byte for a single ** character write. Returns END_OF_WRITER if there isn't a character to ** write. **/ virtual int_type writeChar(char_type ch) { if (this->atEnd()) { return END_OF_WRITER; } this->writeChars(&ch, 1); return ch; } /** Write up to \c len characters into buf and advance the internal position ** accordingly. Returns the number of characters write into buf. Note that ** the value returned may be less than the number of bytes that the internal ** position advances, due to multi-byte characters. **/ virtual size_type writeChars(const char_type buf[], size_type len) = 0; virtual size_type writeChars(const char buf[], size_type len) { return this->writeChars(reinterpret_cast<const char_type *>(buf), len); } virtual bool atEnd() { return this->getCur() >= this->getEnd(); } }; #endif /* _ID3LIB_WRITER_H_ */
#! /bin/sh -e # tup - A file-based build system # This program is free software; you can redistribute it and/or modify # published by the Free Software Foundation. # This program is distributed in the hope that it will be useful, # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # Make sure the output in another dir is deleted from the db when we remove # the rule. . ./tup.sh tmkdir foo cat > Tupfile << HERE : |> touch %o |> foo/ok.txt HERE tup touch Tupfile update tup_object_exist foo ok.txt check_exist foo/ok.txt cat > Tupfile << HERE HERE tup touch Tupfile update tup_object_no_exist foo ok.txt check_not_exist foo/ok.txt eotup
#ifndef <API key> #define <API key> #include <string> #include "ppapi/c/pp_time.h" #include "ppapi/c/pp_var.h" #include "ppapi/proxy/connection.h" #include "ppapi/proxy/plugin_resource.h" #include "ppapi/proxy/ppapi_proxy_export.h" #include "ppapi/thunk/<API key>.h" struct PP_ImageDataDesc; struct <API key>; namespace ppapi { class TrackedCallback; namespace proxy { class PPAPI_PROXY_EXPORT VideoSourceResource : public PluginResource, public thunk::<API key> { public: VideoSourceResource(Connection connection, PP_Instance instance); virtual ~VideoSourceResource(); virtual thunk::<API key>* <API key>() OVERRIDE; virtual int32_t Open( const PP_Var& stream_url, scoped_refptr<TrackedCallback> callback) OVERRIDE; virtual int32_t GetFrame( <API key>* frame, scoped_refptr<TrackedCallback> callback) OVERRIDE; virtual void Close() OVERRIDE; private: void <API key>( const <API key>& reply_params); void <API key>( <API key>* frame, const <API key>& reply_params, const HostResource& image_data, const PP_ImageDataDesc& image_desc_data, PP_TimeTicks timestamp); scoped_refptr<TrackedCallback> open_callback_; scoped_refptr<TrackedCallback> get_frame_callback_; bool is_open_; <API key>(VideoSourceResource); }; } } #endif
package org.yccheok.jstock.gui.analysis; import com.nexes.wizard.<API key>; import java.util.Observable; import java.util.Observer; import org.yccheok.jstock.gui.<API key>; /** * * @author yccheok */ public class <API key> extends <API key> implements Observer { public static final String IDENTIFIER = "<API key>"; public <API key>(<API key> <API key>) { super(IDENTIFIER, new <API key>(<API key>)); this.<API key> = (<API key>)getPanelComponent(); this.<API key>.addObserver(this); } @Override public Object <API key>() { if (this.<API key>.useFinishButton()) { return FINISH; } return <API key>.IDENTIFIER; } @Override public Object <API key>() { return <API key>.IDENTIFIER; } @Override public void aboutToDisplayPanel() { } @Override public void displayingPanel() { this.updateGUIState(); <API key>.start(); } @Override public void aboutToHidePanel() { <API key>.cancel(); } private void updateGUIState() { getWizard().<API key>(<API key>.<API key>()); if (<API key>.<API key>()) { // Update button to determine whether we shall go for next or finish. getWizard().getController().<API key>(); } } @Override public void update(Observable o, Object arg) { this.updateGUIState(); } private final <API key> <API key>; }
\documentclass{article}\usepackage{graphicx, color} %% maxwidth is the original width if it is less than linewidth %% otherwise use linewidth (to make sure the graphics do not exceed the margin) \makeatletter \def\maxwidth{ % \ifdim\Gin@nat@width>\linewidth \linewidth \else \Gin@nat@width \fi } \makeatother \IfFileExists{upquote.sty}{\usepackage{upquote}}{} \definecolor{fgcolor}{rgb}{0.2, 0.2, 0.2} \newcommand{\hlnumber}[1]{\textcolor[rgb]{0,0,0}{ \newcommand{\hlfunctioncall}[1]{\textcolor[rgb]{0.501960784313725,0,0.329411764705882}{\textbf{ \newcommand{\hlstring}[1]{\textcolor[rgb]{0.6,0.6,1}{ \newcommand{\hlkeyword}[1]{\textcolor[rgb]{0,0,0}{\textbf{ \newcommand{\hlargument}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{ \newcommand{\hlcomment}[1]{\textcolor[rgb]{0.180392156862745,0.6,0.341176470588235}{ \newcommand{\hlroxygencomment}[1]{\textcolor[rgb]{0.43921568627451,0.47843137254902,0.701960784313725}{ \newcommand{\hlformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{ \newcommand{\hleqformalargs}[1]{\textcolor[rgb]{0.690196078431373,0.250980392156863,0.0196078431372549}{ \newcommand{\hlassignement}[1]{\textcolor[rgb]{0,0,0}{\textbf{ \newcommand{\hlpackage}[1]{\textcolor[rgb]{0.588235294117647,0.709803921568627,0.145098039215686}{ \newcommand{\hlslot}[1]{\textit{ \newcommand{\hlsymbol}[1]{\textcolor[rgb]{0,0,0}{ \newcommand{\hlprompt}[1]{\textcolor[rgb]{0.2,0.2,0.2}{ \usepackage{framed} \makeatletter \newenvironment{kframe}{% \def\at@end@of@kframe{}% \ifinner\ifhmode% \def\at@end@of@kframe{\end{minipage}}% \begin{minipage}{\columnwidth}% \fi\fi% \def\FrameCommand##1{\hskip\@totalleftmargin \hskip-\fboxsep \colorbox{shadecolor}{##1}\hskip-\fboxsep % There is no \\@totalrightmargin, so: \hskip-\linewidth \hskip-\@totalleftmargin \hskip\columnwidth}% \MakeFramed {\advance\hsize-\width \@totalleftmargin\z@ \linewidth\hsize \@setminipage}}% {\par\unskip\endMakeFramed% \at@end@of@kframe} \makeatother \definecolor{shadecolor}{rgb}{.97, .97, .97} \definecolor{messagecolor}{rgb}{0, 0, 0} \definecolor{warningcolor}{rgb}{1, 0, 1} \definecolor{errorcolor}{rgb}{1, 0, 0} \newenvironment{knitrout}{}{} % an empty environment to be redefined in TeX \usepackage{alltt} %\VignettePackage{rlandscape} %\VignetteDepends{rlandscape} %\VignetteIndexEntry{rlandscape tutorial} \usepackage[margin=1.0in]{geometry} \author{Gregor Passolt} \title{Generating landscapes with the \code{rlandsacpe} package} \date{\today} \newcommand{\code}[1]{{\tt \begin{document} \maketitle \tableofcontents The \code{rlandscape} package is intended to make it easy to simulate random landscapes for testing harvest scheduling models. This vignette will cover use of the two primary functions, \code{rlandscape} and \code{rland}, and is aimed at users that are new to R. Most users will probably find \code{rland} the more useful, but should have a basic understanding of what \code{rlandscape} does so they know what they're getting. To learn about how \code{rlandcsape} works, please refer to Gregor Passolt, Miranda J. Fix, and Sandor F. Toth (in review). A Voronoi Tessellation-based Approach to Generate Hypothetical Forest Landscapes, Canadian Journal of Forest Research. \section{Generating a single landscape with \code{rlandscape}} The foundation of the package is \code{rlandscape}, which generates a single landscape at a time. Its output (a landscape object) can be assigned to a variable for analysis or saving. The first step is to download the \code{rlandscape} package. If you're reading this vignette, that's probably already done, but just in case the command is \verb|install.packages("rlandscape")|. Other dependencies will be installed automatically, which may take a minute. This only needs to be performed once. Every time you start a new R session, you will need to load the package, which can be done either with the \verb|require| or \verb|library| commands. \begin{knitrout} \definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe} \begin{alltt} \hlfunctioncall{library}(rlandscape) \hlcomment{## loading the package} \end{alltt} \end{kframe} \end{knitrout} Now that the package is loaded, all the associated functions are available. Let's get started creating a landscape \begin{knitrout} \definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe} \begin{alltt} myLand <- \hlfunctioncall{rlandscape}() \hlfunctioncall{plot}(myLand) \end{alltt} \end{kframe}\includegraphics[width=\maxwidth]{figure/rlandscape1} \begin{kframe}\begin{alltt} myLand$stats \end{alltt} \begin{verbatim} ## nOut degMean degSD areaCV hAsp n1 n2 n3 n4 pMerge pHole ## 1 100 4.86 1.511 55.15 1 100 0 0 0 0.1 0.1 \end{verbatim} \end{kframe} \end{knitrout} Particular features of this landscape can be extracted using the \verb|$| operator. The \code{stats} display the final number of polygons (nOut), the mean of the degree distribution (degMean), the standard deviation of the degree distribution (degSD), the coefficient of variation of the area distribution (areaCV), the horizontal:vertical aspect ratio (hAsp), the number of points placed by each of the 4 point placement methods (uniform, lattice, cluster, inhibition, respectively), the proportion of edges deleted to merge two polygons together (pMerge), and the proportion of polygons deleted to become holes (pHole). The adjacency table is available as \code{adj}, and the areas are in the \code{dir.area} column of a summary table that includes information for all of original points, such as their x-y coordinates, whether they were deleted, and whether they were merged with another polygon. Note that, due to the deletions and merge events, the polygon numbering will not be sequential. For example, if polygon 2 is deleted, another polygon will not be renamed ``2''. \begin{knitrout} \definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe} \begin{alltt} \hlfunctioncall{head}(myLand$adj) \end{alltt} \begin{verbatim} ## [1] 13 20 67 103 ## [1] 16 32 39 42 62 69 101 ## [1] 51 89 103 115 ## [1] 21 30 46 49 83 ## [1] 6 15 49 83 ## [1] 5 15 23 \end{verbatim} \begin{alltt} \hlfunctioncall{head}(myLand$summary) \end{alltt} \begin{verbatim} ## x y n.tri del.area del.wts n.tside nbpt dir.area dir.wts ## [1,] 0.6262 0.9559 6 0.008947 0.010097 5 2 0.010539 0.010539 ## [2,] 0.2227 0.9439 9 0.008992 0.010147 7 2 0.013722 0.013722 ## [3,] 0.7180 0.8291 5 0.004188 0.004727 5 0 0.005055 0.005055 ## [4,] 0.5592 0.3903 6 0.005205 0.005874 6 0 0.006399 0.006399 ## [5,] 0.4710 0.2936 5 0.003600 0.004062 5 0 0.003873 0.003873 ## [6,] 0.4586 0.2792 4 0.002910 0.003285 4 0 0.003542 0.003542 ## holeThese mergedWith ## [1,] 0 0 ## [2,] 0 0 ## [3,] 0 0 ## [4,] 0 0 ## [5,] 0 0 ## [6,] 0 0 \end{verbatim} \end{kframe} \end{knitrout} You can give arguments to \code{rlandcsape} to alter the landscape under construction. For example, a landscape of 500 polygons, with a 2:1 aspect ratio and a very patchy composition would be given by: \begin{knitrout} \definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe} \begin{alltt} land2 <- \hlfunctioncall{rlandscape}(n = 500, hAsp = 2, pHole = 0.5) \end{alltt} \end{kframe} \end{knitrout} You can access the helpfile for \code{rlandscape} by entering \code{?rlandscape} at the console. It describes all of the options available as well as the defaults. \section{Batch generation using \code{rland}} The \code{rland} function is used when, rather than specifying control parameters for the point processes used to generate landscapes, you want to specify the characteristics of the resulting landscape. It also makes it easy to generate and save any number of landscapes. The most workhorse arguments to \code{rland} are \code{targets} and \code{bounds}. The \code{targets} sets the range of landscape characteristics the algorithm will ``aim'' for, while \code{bounds} sets the range of landscape characteristics that will be accepted. The target ranges must fall inside the bounds ranges. See the \code{rland} help file (enter \code{?rland}) for information on defaults. \code{Rland} is designed to write its output to files rather than display it in R. When you start an R session, there is a ``working directory'' to which, by default, R will save files (or look for files to load). You can see or change the current working directory with the commands \code{getwd} and \code{setwd}, or through file menus which depend on your operating system and interface. The working directory is where \code{rland} will write its output unless you specify a full filepath. The \code{filename} argument to \code{rland} is for the name of the run. For example, if you use \verb|filename = "land-sim"| and create 10 landscapes, they will be named and saved as \code{land-sim-01} to \code{land-sim-10} in the working directory. To have them saved somewhere else, you could set \verb|filename = "C:/otherDirectory/land-sim"|. The default filename is \code{"landscape"}. \subsection{Examples} So, if you wanted to generate 50 landscapes with between 200 and 300 polygons, and save the plots of each landscape, this would do it: \begin{verbatim} rland(targets = list(n = c(200, 300)), bounds = list(n = c(200, 300)), reps = 50, filename = "run1", savePlot = TRUE) \end{verbatim} A similar run with more specifications would look like this: \begin{verbatim} rland(targets = list(n = c(200, 300), degMean = c(4.8, 5.2), areaCV = c(50, 70), hAsp = c(1, 5)), bounds = list(n = c(175, 325), degMean = c(4.8, 5.2), areaCV = c(45, 75)), reps = 50, filename = "run2", savePlot = TRUE) \end{verbatim} By default, the plots are not saved, but the adjacencies and areas are, as well as a summary table giving descriptive statistics about each of the landscapes. This can be viewed in R by \begin{verbatim} run1.summary <- read.table("run1_summary.csv") head(run1.summary) hist(run1.summary$degMean) ## plotting a histogram of the degree means \end{verbatim} A assortment of 100 landscapes with random characteristics is created by \begin{verbatim} rland(reps = 100, method = "random", filename = "random_landscape") \end{verbatim} \subsection{GUI} A graphical user interface (GUI) is available to interact with \code{rland}. All the arguments of \code{rland} can be accessed through the GUI. To start the GUI, simply enter \code{rland.gui()} in the R console. \end{document}
<div class="btn-group"> <button type="button" class="btn btn-xs" dropdown-toggle style="background-color:{{type.color}};color:white;"><span class="glyphicon glyphicon-{{type.icon}}"></span> {{type.name}}</button> <ul class="dropdown-menu" type-list> <li ng-repeat="type in types"><a href="#"><span class="glyphicon glyphicon-{{type.icon}}"></span> {{type.name}}</a></li> </ul> </div>
using System; namespace AL.Data { public interface <API key> : IExecute { BuilderData Data { get; } dynamic Item { get; } <API key> AutoMap(params string[] ignoreProperties); <API key> Column(string columnName, object value, DataTypes parameterType = DataTypes.Object, int size = 0); <API key> Column(string propertyName, DataTypes parameterType = DataTypes.Object, int size = 0); <API key> Where(string name, DataTypes parameterType = DataTypes.Object, int size = 0); <API key> Where(string columnName, object value, DataTypes parameterType = DataTypes.Object, int size = 0); <API key> Fill(Action<<API key>> fillMethod); } }
package jdk.internal.jvmci.hotspot; import java.lang.reflect.Modifier; import jdk.internal.jvmci.meta.JavaMethod; import jdk.internal.jvmci.meta.ResolvedJavaMethod; import jdk.internal.jvmci.meta.ResolvedJavaType; import jdk.internal.jvmci.options.Option; import jdk.internal.jvmci.options.OptionType; import jdk.internal.jvmci.options.OptionValue; /** * Implementation of {@link JavaMethod} for resolved HotSpot methods. */ public interface <API key> extends ResolvedJavaMethod { public static class Options { // @formatter:off @Option(help = "", type = OptionType.Debug) public static final OptionValue<Boolean> <API key> = new OptionValue<>(true); // @formatter:on } /** * Returns true if this method has a {@code CallerSensitive} annotation. * * @return true if CallerSensitive annotation present, false otherwise */ boolean isCallerSensitive(); <API key> getDeclaringClass(); /** * Returns true if this method has a {@code ForceInline} annotation. * * @return true if ForceInline annotation present, false otherwise */ boolean isForceInline(); /** * Returns true if this method has a {@code DontInline} annotation. * * @return true if DontInline annotation present, false otherwise */ boolean isDontInline(); /** * Manually adds a DontInline annotation to this method. */ void setNotInlineable(); /** * Returns true if this method is one of the special methods that is ignored by security stack * walks. * * @return true if special method ignored by security stack walks, false otherwise */ boolean <API key>(); boolean hasBalancedMonitors(); ResolvedJavaMethod <API key>(<API key> receiver); /** * Returns whether this method has compiled code. * * @return true if this method has compiled code, false otherwise */ boolean hasCompiledCode(); /** * @param level * @return true if the currently installed code was generated at {@code level}. */ boolean <API key>(int level); default boolean isDefault() { if (isConstructor()) { return false; } // Copied from java.lang.Method.isDefault() int mask = Modifier.ABSTRACT | Modifier.PUBLIC | Modifier.STATIC; return ((getModifiers() & mask) == Modifier.PUBLIC) && getDeclaringClass().isInterface(); } /** * Returns the offset of this method into the v-table. The method must have a v-table entry as * indicated by {@link #<API key>(ResolvedJavaType)}, otherwise an exception is * thrown. * * @return the offset of this method into the v-table */ int vtableEntryOffset(ResolvedJavaType resolved); int intrinsicId(); /** * Allocates a compile id for this method by asking the VM for one. * * @param entryBCI entry bci * @return compile id */ int allocateCompileId(int entryBCI); boolean hasCodeAtLevel(int entryBCI, int level); }
package com.iucn.whp.dbservice.model; import com.liferay.portal.model.PersistedModel; /** * The extended model interface for the current_state_trend service. Represents a row in the &quot;<API key>&quot; database table, with each column mapped to a property of this class. * * @author alok.sen * @see <API key> * @see com.iucn.whp.dbservice.model.impl.<API key> * @see com.iucn.whp.dbservice.model.impl.<API key> * @generated */ public interface current_state_trend extends <API key>, PersistedModel { /* * NOTE FOR DEVELOPERS: * * Never modify this interface directly. Add methods to {@link com.iucn.whp.dbservice.model.impl.<API key>} and rerun ServiceBuilder to automatically copy the method declarations to this interface. */ }
cmd_drivers/base/bus.o := <API key> -Wp,-MD,drivers/base/.bus.o.d -nostdinc -isystem /home/stesalit/arm-2009q1/bin/../lib/gcc/<API key>/4.3.3/include -I/root/kernel-dev/linux-2.6.37/arch/arm/include -Iinclude -include include/generated/autoconf.h -D__KERNEL__ -mlittle-endian -Iarch/arm/mach-davinci/include -Wall -Wundef -Wstrict-prototypes -Wno-trigraphs -fno-strict-aliasing -fno-common -<API key> -Wno-format-security -<API key> -Os -marm -<API key> -mapcs -mno-sched-prolog -mabi=aapcs-linux -mno-thumb-interwork -D__LINUX_ARM_ARCH__=5 -march=armv5te -mtune=arm9tdmi -msoft-float -Uarm -fno-stack-protector -<API key> -<API key> -<API key> -Wno-pointer-sign -fno-strict-overflow -D"KBUILD_STR(s)=\#s" -D"KBUILD_BASENAME=KBUILD_STR(bus)" -D"KBUILD_MODNAME=KBUILD_STR(bus)" -c -o drivers/base/.tmp_bus.o drivers/base/bus.c deps_drivers/base/bus.o := \ drivers/base/bus.c \ $(wildcard include/config/hotplug.h) \ include/linux/device.h \ $(wildcard include/config/of.h) \ $(wildcard include/config/debug/devres.h) \ $(wildcard include/config/numa.h) \ $(wildcard include/config/devtmpfs.h) \ $(wildcard include/config/printk.h) \ $(wildcard include/config/dynamic/debug.h) \ $(wildcard include/config/sysfs/deprecated.h) \ include/linux/ioport.h \ include/linux/compiler.h \ $(wildcard include/config/sparse/rcu/pointer.h) \ $(wildcard include/config/trace/branch/profiling.h) \ $(wildcard include/config/profile/all/branches.h) \ $(wildcard include/config/enable/must/check.h) \ $(wildcard include/config/enable/warn/deprecated.h) \ include/linux/compiler-gcc.h \ $(wildcard include/config/arch/supports/optimized/inlining.h) \ $(wildcard include/config/optimize/inlining.h) \ include/linux/compiler-gcc4.h \ include/linux/types.h \ $(wildcard include/config/uid16.h) \ $(wildcard include/config/lbdaf.h) \ $(wildcard include/config/phys/addr/t/64bit.h) \ $(wildcard include/config/64bit.h) \ /root/kernel-dev/linux-2.6.37/arch/arm/include/asm/types.h \ include/asm-generic/int-ll64.h \ include/asm-generic/bitsperlong.h \ include/linux/posix_types.h \ include/linux/stddef.h \ /root/kernel-dev/linux-2.6.37/arch/arm/include/asm/posix_types.h \ include/linux/kobject.h \ include/linux/list.h \ $(wildcard include/config/debug/list.h) \ include/linux/poison.h \ $(wildcard include/config/illegal/pointer/value.h) \ include/linux/prefetch.h \ /root/kernel-dev/linux-2.6.37/arch/arm/include/asm/processor.h \ $(wildcard include/config/have/hw/breakpoint.h) \ $(wildcard include/config/mmu.h) \ /root/kernel-dev/linux-2.6.37/arch/arm/include/asm/hw_breakpoint.h \ /root/kernel-dev/linux-2.6.37/arch/arm/include/asm/ptrace.h \ $(wildcard include/config/cpu/endian/be8.h) \ $(wildcard include/config/arm/thumb.h) \ $(wildcard include/config/smp.h) \ /root/kernel-dev/linux-2.6.37/arch/arm/include/asm/hwcap.h \ /root/kernel-dev/linux-2.6.37/arch/arm/include/asm/cache.h \ $(wildcard include/config/arm/l1/cache/shift.h) \ $(wildcard include/config/aeabi.h) \ include/linux/sysfs.h \ $(wildcard include/config/debug/lock/alloc.h) \ $(wildcard include/config/sysfs.h) \ include/linux/errno.h \ /root/kernel-dev/linux-2.6.37/arch/arm/include/asm/errno.h \ include/asm-generic/errno.h \ include/asm-generic/errno-base.h \ include/linux/lockdep.h \ $(wildcard include/config/lockdep.h) \ $(wildcard include/config/lock/stat.h) \ $(wildcard include/config/trace/irqflags.h) \ $(wildcard include/config/prove/locking.h) \ $(wildcard include/config/prove/rcu.h) \ include/linux/kobject_ns.h \ /root/kernel-dev/linux-2.6.37/arch/arm/include/asm/atomic.h \ $(wildcard include/config/generic/atomic64.h) \ /root/kernel-dev/linux-2.6.37/arch/arm/include/asm/system.h \ $(wildcard include/config/cpu/xsc3.h) \ $(wildcard include/config/cpu/fa526.h) \ $(wildcard include/config/arch/has/barriers.h) \ $(wildcard include/config/arm/dma/mem/bufferable.h) \ $(wildcard include/config/cpu/sa1100.h) \ $(wildcard include/config/cpu/sa110.h) \ $(wildcard include/config/cpu/32v6k.h) \ include/linux/linkage.h \ /root/kernel-dev/linux-2.6.37/arch/arm/include/asm/linkage.h \ include/linux/irqflags.h \ $(wildcard include/config/irqsoff/tracer.h) \ $(wildcard include/config/preempt/tracer.h) \ $(wildcard include/config/trace/irqflags/support.h) \ include/linux/typecheck.h \ /root/kernel-dev/linux-2.6.37/arch/arm/include/asm/irqflags.h \ /root/kernel-dev/linux-2.6.37/arch/arm/include/asm/outercache.h \ $(wildcard include/config/outer/cache/sync.h) \ $(wildcard include/config/outer/cache.h) \ /root/kernel-dev/linux-2.6.37/arch/arm/include/asm/memory.h \ $(wildcard include/config/page/offset.h) \ $(wildcard include/config/thumb2/kernel.h) \ $(wildcard include/config/highmem.h) \ $(wildcard include/config/dram/size.h) \ $(wildcard include/config/dram/base.h) \ $(wildcard include/config/have/tcm.h) \ $(wildcard include/config/zone/dma.h) \ include/linux/const.h \ arch/arm/mach-davinci/include/mach/memory.h \ $(wildcard include/config/arch/davinci/da8xx.h) \ $(wildcard include/config/arch/davinci/dmx.h) \ /root/kernel-dev/linux-2.6.37/arch/arm/include/asm/page.h \ $(wildcard include/config/cpu/copy/v3.h) \ $(wildcard include/config/cpu/copy/v4wt.h) \ $(wildcard include/config/cpu/copy/v4wb.h) \ $(wildcard include/config/cpu/copy/feroceon.h) \ $(wildcard include/config/cpu/copy/fa.h) \ $(wildcard include/config/cpu/xscale.h) \ $(wildcard include/config/cpu/copy/v6.h) \ $(wildcard include/config/sparsemem.h) \ /root/kernel-dev/linux-2.6.37/arch/arm/include/asm/glue.h \ $(wildcard include/config/cpu/arm610.h) \ $(wildcard include/config/cpu/arm710.h) \ $(wildcard include/config/cpu/abrt/lv4t.h) \ $(wildcard include/config/cpu/abrt/ev4.h) \ $(wildcard include/config/cpu/abrt/ev4t.h) \ $(wildcard include/config/cpu/abrt/ev5tj.h) \ $(wildcard include/config/cpu/abrt/ev5t.h) \ $(wildcard include/config/cpu/abrt/ev6.h) \ $(wildcard include/config/cpu/abrt/ev7.h) \ $(wildcard include/config/cpu/pabrt/legacy.h) \ $(wildcard include/config/cpu/pabrt/v6.h) \ $(wildcard include/config/cpu/pabrt/v7.h) \ include/asm-generic/getorder.h \ /root/kernel-dev/linux-2.6.37/arch/arm/include/asm/sizes.h \ include/asm-generic/memory_model.h \ $(wildcard include/config/flatmem.h) \ $(wildcard include/config/discontigmem.h) \ $(wildcard include/config/sparsemem/vmemmap.h) \ include/asm-generic/cmpxchg-local.h \ include/asm-generic/cmpxchg.h \ include/asm-generic/atomic64.h \ include/asm-generic/atomic-long.h \ include/linux/spinlock.h \ $(wildcard include/config/debug/spinlock.h) \ $(wildcard include/config/generic/lockbreak.h) \ $(wildcard include/config/preempt.h) \ include/linux/preempt.h \ $(wildcard include/config/debug/preempt.h) \ $(wildcard include/config/preempt/notifiers.h) \ include/linux/thread_info.h \ $(wildcard include/config/compat.h) \ include/linux/bitops.h \ $(wildcard include/config/generic/find/last/bit.h) \ /root/kernel-dev/linux-2.6.37/arch/arm/include/asm/bitops.h \ include/asm-generic/bitops/non-atomic.h \ include/asm-generic/bitops/fls64.h \ include/asm-generic/bitops/sched.h \ include/asm-generic/bitops/hweight.h \ include/asm-generic/bitops/arch_hweight.h \ include/asm-generic/bitops/const_hweight.h \ include/asm-generic/bitops/lock.h \ /root/kernel-dev/linux-2.6.37/arch/arm/include/asm/thread_info.h \ $(wildcard include/config/arm/thumbee.h) \ /root/kernel-dev/linux-2.6.37/arch/arm/include/asm/fpstate.h \ $(wildcard include/config/vfpv3.h) \ $(wildcard include/config/iwmmxt.h) \ /root/kernel-dev/linux-2.6.37/arch/arm/include/asm/domain.h \ $(wildcard include/config/io/36.h) \ include/linux/kernel.h \ $(wildcard include/config/preempt/voluntary.h) \ $(wildcard include/config/debug/spinlock/sleep.h) \ $(wildcard include/config/ring/buffer.h) \ $(wildcard include/config/tracing.h) \ $(wildcard include/config/ftrace/mcount/record.h) \ /home/stesalit/arm-2009q1/bin/../lib/gcc/<API key>/4.3.3/include/stdarg.h \ include/linux/log2.h \ $(wildcard include/config/arch/has/ilog2/u32.h) \ $(wildcard include/config/arch/has/ilog2/u64.h) \ include/linux/printk.h \ include/linux/dynamic_debug.h \ include/linux/jump_label.h \ $(wildcard include/config/jump/label.h) \ /root/kernel-dev/linux-2.6.37/arch/arm/include/asm/byteorder.h \ include/linux/byteorder/little_endian.h \ include/linux/swab.h \ /root/kernel-dev/linux-2.6.37/arch/arm/include/asm/swab.h \ include/linux/byteorder/generic.h \ /root/kernel-dev/linux-2.6.37/arch/arm/include/asm/bug.h \ $(wildcard include/config/bug.h) \ $(wildcard include/config/debug/bugverbose.h) \ include/asm-generic/bug.h \ $(wildcard include/config/generic/bug.h) \ $(wildcard include/config/generic/bug/relative/pointers.h) \ /root/kernel-dev/linux-2.6.37/arch/arm/include/asm/div64.h \ include/linux/stringify.h \ include/linux/bottom_half.h \ include/linux/spinlock_types.h \ include/linux/spinlock_types_up.h \ include/linux/rwlock_types.h \ include/linux/spinlock_up.h \ include/linux/rwlock.h \ include/linux/spinlock_api_up.h \ include/linux/kref.h \ include/linux/wait.h \ /root/kernel-dev/linux-2.6.37/arch/arm/include/asm/current.h \ include/linux/klist.h \ include/linux/module.h \ $(wildcard include/config/symbol/prefix.h) \ $(wildcard include/config/modules.h) \ $(wildcard include/config/modversions.h) \ $(wildcard include/config/unused/symbols.h) \ $(wildcard include/config/kallsyms.h) \ $(wildcard include/config/tracepoints.h) \ $(wildcard include/config/event/tracing.h) \ $(wildcard include/config/module/unload.h) \ $(wildcard include/config/constructors.h) \ include/linux/stat.h \ /root/kernel-dev/linux-2.6.37/arch/arm/include/asm/stat.h \ include/linux/time.h \ $(wildcard include/config/arch/uses/gettimeoffset.h) \ include/linux/cache.h \ $(wildcard include/config/arch/has/cache/line/size.h) \ include/linux/seqlock.h \ include/linux/math64.h \ include/linux/kmod.h \ include/linux/gfp.h \ $(wildcard include/config/kmemcheck.h) \ $(wildcard include/config/zone/dma32.h) \ $(wildcard include/config/debug/vm.h) \ include/linux/mmzone.h \ $(wildcard include/config/force/max/zoneorder.h) \ $(wildcard include/config/memory/hotplug.h) \ $(wildcard include/config/compaction.h) \ $(wildcard include/config/arch/populates/node/map.h) \ $(wildcard include/config/flat/node/mem/map.h) \ $(wildcard include/config/cgroup/mem/res/ctlr.h) \ $(wildcard include/config/no/bootmem.h) \ $(wildcard include/config/have/memory/present.h) \ $(wildcard include/config/have/memoryless/nodes.h) \ $(wildcard include/config/need/node/memmap/size.h) \ $(wildcard include/config/need/multiple/nodes.h) \ $(wildcard include/config/have/arch/early/pfn/to/nid.h) \ $(wildcard include/config/sparsemem/extreme.h) \ $(wildcard include/config/nodes/span/other/nodes.h) \ $(wildcard include/config/holes/in/zone.h) \ $(wildcard include/config/arch/has/holes/memorymodel.h) \ include/linux/threads.h \ $(wildcard include/config/nr/cpus.h) \ $(wildcard include/config/base/small.h) \ include/linux/numa.h \ $(wildcard include/config/nodes/shift.h) \ include/linux/init.h \ include/linux/nodemask.h \ include/linux/bitmap.h \ include/linux/string.h \ $(wildcard include/config/binary/printf.h) \ /root/kernel-dev/linux-2.6.37/arch/arm/include/asm/string.h \ include/linux/pageblock-flags.h \ $(wildcard include/config/hugetlb/page.h) \ $(wildcard include/config/hugetlb/page/size/variable.h) \ include/generated/bounds.h \ include/linux/memory_hotplug.h \ $(wildcard include/config/memory/hotremove.h) \ $(wildcard include/config/have/arch/nodedata/extension.h) \ include/linux/notifier.h \ include/linux/mutex.h \ $(wildcard include/config/debug/mutexes.h) \ include/linux/rwsem.h \ $(wildcard include/config/rwsem/generic/spinlock.h) \ include/linux/rwsem-spinlock.h \ include/linux/srcu.h \ include/linux/topology.h \ $(wildcard include/config/sched/smt.h) \ $(wildcard include/config/sched/mc.h) \ $(wildcard include/config/sched/book.h) \ $(wildcard include/config/use/percpu/numa/node/id.h) \ include/linux/cpumask.h \ $(wildcard include/config/cpumask/offstack.h) \ $(wildcard include/config/hotplug/cpu.h) \ $(wildcard include/config/debug/per/cpu/maps.h) \ $(wildcard include/config/disable/obsolete/cpumask/functions.h) \ include/linux/smp.h \ $(wildcard include/config/use/generic/smp/helpers.h) \ include/linux/percpu.h \ $(wildcard include/config/need/per/cpu/embed/first/chunk.h) \ $(wildcard include/config/need/per/cpu/page/first/chunk.h) \ $(wildcard include/config/have/setup/per/cpu/area.h) \ include/linux/pfn.h \ /root/kernel-dev/linux-2.6.37/arch/arm/include/asm/percpu.h \ include/asm-generic/percpu.h \ include/linux/percpu-defs.h \ $(wildcard include/config/debug/force/weak/per/cpu.h) \ /root/kernel-dev/linux-2.6.37/arch/arm/include/asm/topology.h \ include/asm-generic/topology.h \ include/linux/mmdebug.h \ $(wildcard include/config/debug/virtual.h) \ include/linux/workqueue.h \ $(wildcard include/config/debug/objects/work.h) \ $(wildcard include/config/freezer.h) \ include/linux/timer.h \ $(wildcard include/config/timer/stats.h) \ $(wildcard include/config/debug/objects/timers.h) \ include/linux/ktime.h \ $(wildcard include/config/ktime/scalar.h) \ include/linux/jiffies.h \ include/linux/timex.h \ include/linux/param.h \ /root/kernel-dev/linux-2.6.37/arch/arm/include/asm/param.h \ $(wildcard include/config/hz.h) \ /root/kernel-dev/linux-2.6.37/arch/arm/include/asm/timex.h \ arch/arm/mach-davinci/include/mach/timex.h \ include/linux/debugobjects.h \ $(wildcard include/config/debug/objects.h) \ $(wildcard include/config/debug/objects/free.h) \ include/linux/elf.h \ include/linux/elf-em.h \ /root/kernel-dev/linux-2.6.37/arch/arm/include/asm/elf.h \ /root/kernel-dev/linux-2.6.37/arch/arm/include/asm/user.h \ include/linux/moduleparam.h \ $(wildcard include/config/alpha.h) \ $(wildcard include/config/ia64.h) \ $(wildcard include/config/ppc64.h) \ include/linux/tracepoint.h \ include/linux/rcupdate.h \ $(wildcard include/config/rcu/torture/test.h) \ $(wildcard include/config/preempt/rcu.h) \ $(wildcard include/config/no/hz.h) \ $(wildcard include/config/tree/rcu.h) \ $(wildcard include/config/tree/preempt/rcu.h) \ $(wildcard include/config/tiny/rcu.h) \ $(wildcard include/config/tiny/preempt/rcu.h) \ $(wildcard include/config/debug/objects/rcu/head.h) \ $(wildcard include/config/preempt/rt.h) \ include/linux/completion.h \ include/linux/rcutree.h \ /root/kernel-dev/linux-2.6.37/arch/arm/include/asm/module.h \ $(wildcard include/config/arm/unwind.h) \ include/trace/events/module.h \ include/trace/define_trace.h \ include/linux/pm.h \ $(wildcard include/config/pm.h) \ $(wildcard include/config/pm/sleep.h) \ $(wildcard include/config/pm/runtime.h) \ $(wildcard include/config/pm/ops.h) \ /root/kernel-dev/linux-2.6.37/arch/arm/include/asm/device.h \ $(wildcard include/config/dmabounce.h) \ include/linux/pm_wakeup.h \ include/linux/slab.h \ $(wildcard include/config/slab/debug.h) \ $(wildcard include/config/failslab.h) \ $(wildcard include/config/slub.h) \ $(wildcard include/config/slob.h) \ $(wildcard include/config/debug/slab.h) \ $(wildcard include/config/slab.h) \ include/linux/slub_def.h \ $(wildcard include/config/slub/stats.h) \ $(wildcard include/config/slub/debug.h) \ include/linux/kmemleak.h \ $(wildcard include/config/debug/kmemleak.h) \ include/trace/events/kmem.h \ include/trace/events/gfpflags.h \ drivers/base/base.h \ $(wildcard include/config/sys/hypervisor.h) \ drivers/base/power/power.h \ drivers/base/bus.o: $(deps_drivers/base/bus.o) $(deps_drivers/base/bus.o):
using System; using System.Collections.Generic; using System.Linq; using System.Text; class DesktopGUIBroker: IGUIBroker { public void AddPower(PowerView power_view) { throw new <API key>(); } public void RemovePower(PowerView power_view) { throw new <API key>(); } }
<?php // | PayPal Plugin - geeklog CMS | // | transaction.php | // | Authors: ::Ben - cordiste AT free DOT fr | // | Authors: Hiroron - hiroron AT hiroron DOT com | // | This program is free software; you can redistribute it and/or | // | as published by the Free Software Foundation; either version 2 | // | This program is distributed in the hope that it will be useful, | // | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | // | along with this program; if not, write to the Free Software Foundation, | // | Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. | /** * require core geeklog code */ require_once '../lib-common.php'; if (!in_array('paypal', $_PLUGINS)) { COM_handle404(); exit; } // Incoming variable filter $vars = array('id' => 'number', 'type' => 'alpha', 'mode' => 'alpha' ); paypal_filterVars($vars, $_REQUEST); $pid = Geeklog\Input::fRequest('id', ''); $type = Geeklog\Input::fRequest('type', ''); //purchase or subscription // Ensure sufficient privs to read this page if (($_USER['uid'] < 2) && ($_PAY_CONF['anonymous_buy'] == 0)) { $content = ''; if (SEC_hasRights('paypal.user,paypal.admin')) { $content .= paypal_user_menu(); } else { $content .= paypal_viewer_menu(); } $content .= COM_startBlock($LANG_PAYPAL_1['access_reserved']); $content .= $LANG_PAYPAL_1['you_must_log_in']; $content .= COM_endBlock(); $display = <API key>($content); COM_output($display); exit; } if ($_PAY_CONF['anonymous_buy'] == 0) paypal_access_check('paypal.user'); // query database for transaction if ($type == 'purchase') $res = DB_query("SELECT DISTINCT s.*, i.ipn_data FROM {$_TABLES['paypal_purchases']} AS s, {$_TABLES['paypal_ipnlog']} AS i WHERE s.id = {$pid} AND s.txn_id=i.txn_id"); if ($type == 'subscription') $res = DB_query("SELECT DISTINCT s.*, i.ipn_data FROM {$_TABLES['<API key>']} AS s, {$_TABLES['paypal_ipnlog']} AS i WHERE s.id = {$pid} AND s.txn_id=i.txn_id"); // count number of returned results, if unexpected redirect to product list $numres = DB_numRows($res); if ($numres != 1) { COM_errorLog('Error on Paypal transaction page: Number of rows: ' . $numres . ' Type=' . $type . ' ID=' . $pid . ' User='. $_USER['uid']); echo COM_refresh($_PAY_CONF['site_url'] . '/index.php'); exit; } $A = DB_fetchArray($res, false); $purchase_status = $A['status']; $transaction = new Template($_CONF['path'] . 'plugins/paypal/templates/transaction'); $mode = Geeklog\Input::fRequest('mode', ''); if ($mode == 'print') { $transaction->set_file(array('transaction' => 'print_' . $type . '.thtml')); } else { $transaction->set_file(array('transaction' => $type . '.thtml')); } // Allow all serialized data to be available to the template $ipn =''; if ($A['ipn_data'] != '') { // PHP7 error { // $out = preg_replace('!s:(\d+):"(.*?)";!se', "'s:'.strlen('$2').':\"$2\";'", $A['ipn_data'] ); $out = <API key>( '!s:(\d+):"(.*?)";!s', function ($args) { return sprintf('s:%d:"%s";', strlen($args[2]), $args[2]); }, $A['ipn_data'] ); // } PHP7 error $ipn = unserialize($out); if (!is_array($ipn)) { $ipn = array(); } foreach ($ipn as $name => $value) { $transaction->set_var($name, $value); } } if ( $A['user_id'] != '' && ($_USER['uid'] != $A['user_id']) && SEC_hasRights('paypal.admin') == false) { COM_errorLog('Error on Paypal transaction page: User is not allowed to see transaction. Type=' . $type . ' ID=' . $pid . ' User='. $_USER['uid'] . ' User of the transaction='. $A['user_id']); echo COM_refresh($_PAY_CONF['site_url'] . '/index.php'); exit; } //Log-In to access if (($_USER['uid'] < 2) && ($A['logged'] == 1)) { $content = ''; if (SEC_hasRights('paypal.user,paypal.admin')) { $content .= paypal_user_menu(); } else { $content .= paypal_viewer_menu(); } $content .= COM_startBlock($LANG_PAYPAL_1['access_reserved']); $content .= $LANG_PAYPAL_1['you_must_log_in']; $content .= COM_endBlock(); $display = <API key>($content); COM_output($display); exit; } //Content $transaction->set_var('site_url', $_PAY_CONF['site_url']); $transaction->set_var('charset', COM_getCharset()); $transaction->set_var('br', '<br'. XHTML .'>'); $mode = Geeklog\Input::fRequest('mode', ''); if ($mode == 'print') { $transaction->set_var('print', ''); } else { $transaction->set_var('print', ' <small>(<a href="' . $_PAY_CONF['site_url'] . '/transaction.php?type=' . $type . '&amp;id=' . $pid . '&amp;mode=print" target="_blank">'. $LANG_PAYPAL_1['print'] . '</a>)</small>'); } //shop details $transaction->set_var('shop_name', $_PAY_CONF['shop_name']); $transaction->set_var('shop_street1', $_PAY_CONF['shop_street1']); if ($_PAY_CONF['shop_street2'] != '') { $transaction->set_var('shop_street2', $_PAY_CONF['shop_street2'] . '<br' . XHTML .'>'); } else { $transaction->set_var('shop_street2', ''); } $transaction->set_var('shop_postal', $_PAY_CONF['shop_postal']); $transaction->set_var('shop_city', $_PAY_CONF['shop_city']); $transaction->set_var('shop_country', '<p>' . $_PAY_CONF['shop_country'] .'</p>'); if ($_PAY_CONF['shop_phone1'] != '') { $transaction->set_var('shop_phone1', $LANG_PAYPAL_1['phone1'] . ' ' . $_PAY_CONF['shop_phone1']); } else { $transaction->set_var('shop_phone1', ''); } if ($_PAY_CONF['shop_phone2'] != '') { $transaction->set_var('shop_phone2', '<br' . XHTML .'>' . $LANG_PAYPAL_1['phone2'] . ' ' . $_PAY_CONF['shop_phone2']); } else { $transaction->set_var('shop_phone2', ''); } if ($_PAY_CONF['shop_fax'] != '') { $transaction->set_var('shop_fax', '<br' . XHTML .'>' . $LANG_PAYPAL_1['fax'] . ' ' . $_PAY_CONF['shop_fax'] . '<br' . XHTML .'>'); } else { $transaction->set_var('shop_fax', ''); } $transaction->set_var('shop_proid', '<p>' . $_PAY_CONF['shop_siret'] .'</p>'); //user details if (SEC_hasRights('paypal.admin')) { $transaction->set_var('edit_details', '<small><a href="' . $_PAY_CONF['site_url'] . '/details.php?mode=edit&amp;uid=' . $A['user_id'] . '">' . $LANG_PAYPAL_1['edit_details'] . '</a></small>'); } else { $transaction->set_var('edit_details', ''); } $transaction->set_var('user_name', $ipn['address_name'] ); $transaction->set_var('user_street1', $ipn['address_street']); $transaction->set_var('user_postal', $ipn['address_zip']); $transaction->set_var('user_city', $ipn['address_city']); $transaction->set_var('user_country', '<p>' . $ipn['address_country'] . '</p>'); $purchase_date = <API key>($A['purchase_date']); $expiration = <API key>($A['expiration']); if (!isset($A['quantity'])) $A['quantity'] = ''; if (!isset($A['product_name'])) $A['product_name'] = ''; $transaction->set_var('qty', $A['quantity']); $transaction->set_var('product', $A['product_name']); $transaction->set_var('from', $LANG_PAYPAL_1['from'] . ' ' . $purchase_date[0]); $transaction->set_var('to', $LANG_PAYPAL_1['to'] . ' ' . $expiration[0]); $transaction->set_var('edit', ''); if ($purchase_status == 'complete' || $purchase_status == '') { $transaction->set_var('paid_on', $LANG_PAYPAL_1['paid_on'] . ' ' . $purchase_date[0]); } else { $transaction->set_var('paid_on', $LANG_PAYPAL_1['order_on'] . ' ' . $purchase_date[0]); if (SEC_hasRights('paypal.admin') && $A['status'] == 'pending') { $transaction->set_var('edit', '<p><a href="' . $_CONF['site_url'] . '/admin/plugins/paypal/purchase_history.php?mode=edit&amp;txn_id=' . $ipn['txn_id'] . '" onclick="return confirm(\'' . $LANG_PAYPAL_1['confirm_edit_status'] .'\');"> >> ' . $LANG_PAYPAL_1['validate_order'] . '</a></p>'); } } //Order or invoice $transaction->set_var('receipt', $LANG_PAYPAL_1['transaction'] . ': ' . $ipn['txn_id']); //Todo implement payment_type on purchase if ($ipn['payment_type'] != '') { $transaction->set_var('payment_type', $LANG_PAYPAL_1['by'] . ' ' . $LANG_PAYPAL_PAYMENT[$ipn['payment_type']]); } else { $transaction->set_var('payment_type', ''); } $transaction->set_var('total_price', number_format($ipn['mc_gross'], $_CONF['decimal_count'], $_CONF['decimal_separator'], $_CONF['thousand_separator'])); $transaction->set_var('currency', $_PAY_CONF['currency']); $transaction->set_var('name', $A['product_name']); //Table header $transaction->set_var('quantity', $LANG_PAYPAL_1['quantity']); $transaction->set_var('product_name', $LANG_PAYPAL_1['name']); $transaction->set_var('unit_price_label', $LANG_PAYPAL_1['unit_price_label']); $transaction->set_var('total_row_label', $LANG_PAYPAL_1['total_row_label']); //Table row $transaction->set_block('transaction', 'tablerow','ttablerow'); if (isset($ipn['quantity0']) && $ipn['quantity0'] != '') { $i = 0; for (; ; ) { if (!isset($ipn['quantity'.$i]) || $ipn['quantity'.$i] == '') { break; } $price = $ipn['mc_gross_'.$i] / intval($ipn['quantity'.$i]); $total = $ipn['mc_gross_'.$i]; if ($price == 0) $price = $ipn['mc_gross'.$i] / intval($ipn['quantity'.$i]); if ($total == 0) $total = $ipn['mc_gross'.$i]; $transaction->set_var(array( 'qty' => $ipn['quantity'.$i], 'product' => $ipn['item_name'.$i], 'unit_price' => number_format($price, $_CONF['decimal_count'], $_CONF['decimal_separator'], $_CONF['thousand_separator']), 'total_row' => number_format($total, $_CONF['decimal_count'], $_CONF['decimal_separator'], $_CONF['thousand_separator']) )); $transaction->parse('ttablerow','tablerow',true); $i++; } } else if (isset($ipn['quantity1']) && $ipn['quantity1'] != '') { $i = 1; for (; ; ) { if (!isset($ipn['quantity'.$i]) || $ipn['quantity'.$i] == '') { break; } $price = $ipn['mc_gross_'.$i] / intval($ipn['quantity'.$i]); $total = $ipn['mc_gross_'.$i]; if ($price == 0) $price = $ipn['mc_gross'.$i] / intval($ipn['quantity'.$i]); if ($total == 0) $total = $ipn['mc_gross'.$i]; $transaction->set_var(array( 'qty' => $ipn['quantity'.$i], 'product' => $ipn['item_name'.$i], 'unit_price' => number_format($price, $_CONF['decimal_count'], $_CONF['decimal_separator'], $_CONF['thousand_separator']), 'total_row' => number_format($total, $_CONF['decimal_count'], $_CONF['decimal_separator'], $_CONF['thousand_separator']) )); $transaction->parse('ttablerow','tablerow',true); $i++; } } else if (!isset($ipn['quantity']) || $ipn['quantity'] == 0) { $ipn['quantity']=1; $transaction->set_var(array( 'qty' => $ipn['quantity'], 'product' => $ipn['item_name1'], 'unit_price' => number_format($ipn['mc_gross']/intval($ipn['quantity']), $_CONF['decimal_count'], $_CONF['decimal_separator'], $_CONF['thousand_separator']), 'total_row' => number_format($ipn['mc_gross'], $_CONF['decimal_count'], $_CONF['decimal_separator'], $_CONF['thousand_separator']) )); $transaction->parse('ttablerow','tablerow',true); } //Handling if (isset($ipn['mc_handling']) && $ipn['mc_handling'] > 0) { $transaction->set_var(array( 'qty' => 1, 'product' => $LANG_PAYPAL_1['shipping'], 'unit_price' => '', 'total_row' => number_format($ipn['mc_handling'], $_CONF['decimal_count'], $_CONF['decimal_separator'], $_CONF['thousand_separator']) )); $transaction->parse('ttablerow','tablerow',true); } //Shipping if (isset($ipn['mc_shipping']) && $ipn['mc_shipping'] > 0) { $transaction->set_var(array( 'qty' => 1, 'product' => $LANG_PAYPAL_1['shipping'], 'unit_price' => '', 'total_row' => number_format($ipn['mc_shipping'], $_CONF['decimal_count'], $_CONF['decimal_separator'], $_CONF['thousand_separator']) )); $transaction->parse('ttablerow','tablerow',true); } //Table footer $transaction->set_var('total_price_label', $LANG_PAYPAL_1['total_price_label']); //print mode $transaction->set_var('xhtml', XHTML); if (XHTML != '') { $transaction->set_var('xmlns', ' xmlns="http: } $transaction->set_var('direction', $LANG_DIRECTION); $transaction->parse('output', 'transaction'); $tran_content = $transaction->finish($transaction->get_var('output')); //Display $mode = Geeklog\Input::fRequest('mode', ''); if ($mode == 'print') { $display = $tran_content; } else { $content = ''; if (SEC_hasRights('paypal.user,paypal.admin')) { $content .= paypal_user_menu(); } else { $content .= paypal_viewer_menu(); } $content .= COM_startBlock(); $content .= $tran_content; $content .= COM_endBlock(); $display = <API key>($content); } COM_output($display);
<?php /** * Uploading files from computer, step 1 * Shows the plupload form that handles the uploads and moves * them to a temporary folder. When the queue is empty, the user * is redirected to step 2, and prompted to enter the name, * description and client for each uploaded file. * * @package ProjectSend * @subpackage Upload */ $load_scripts = array( 'plupload', ); require_once('sys.includes.php'); $active_nav = 'files'; $page_title = __('Upload files', 'cftp_admin'); $allowed_levels = array(9,8,7); if (CLIENTS_CAN_UPLOAD == 1) { $allowed_levels[] = 0; } include('header.php'); /** * Get the user level to determine if the uploader is a * system user or a client. */ $current_level = <API key>(); ?> <div id="main"> <h2><?php echo $page_title; ?></h2> <?php /** Count the clients to show an error or the form */ $statement = $dbh->query("SELECT * FROM " . TABLE_USERS . " WHERE level = '0'"); $count = $statement->rowCount(); if ( !$count or $count < 1 ) { /** Echo the no clients default message */ message_no_clients(); } else { ?> <p> <?php _e('Click on Add files to select all the files that you want to upload, and then click continue. On the next step, you will be able to set a name and description for each uploaded file. Remember that the maximum allowed file size (in mb.) is ','cftp_admin'); echo '<strong>'.MAX_FILESIZE.'</strong>.'; ?> </p> <?php /** * Load a plupload translation file, if the ProjectSend language * on sys.config.php is set to anything other than "en", and the * corresponding plupload file exists. */ if(SITE_LANG != 'en') { $plupload_lang_file = 'includes/plupload/js/i18n/'.SITE_LANG.'.js'; if(file_exists($plupload_lang_file)) { echo '<script type="text/javascript" src="'.BASE_URI.$plupload_lang_file.'"></script>'; } } ?> <script type="text/javascript"> $(document).ready(function() { setInterval(function(){ // Send a keep alive action every 1 minute var timestamp = new Date().getTime() $.ajax({ type: 'GET', cache: false, url: 'includes/ajax-keep-alive.php', data: 'timestamp='+timestamp, success: function(result) { var dummy = result; } }); },1000*60); }); $(function() { $("#uploader").pluploadQueue({ runtimes : 'html5,flash,silverlight,html4', url : 'process-upload.php', max_file_size : '<?php echo MAX_FILESIZE; ?>mb', chunk_size : '1mb', multipart : true, <?php if ( false === <API key> ) { ?> filters : [ {title : "Allowed files", extensions : "<?php echo $options_values['allowed_file_types']; ?>"} ], <?php } ?> flash_swf_url : 'includes/plupload/js/plupload.flash.swf', silverlight_xap_url : 'includes/plupload/js/plupload.silverlight.xap', preinit: { Init: function (up, info) { $('#uploader_container').removeAttr("title"); } } /* ,init : { QueueChanged: function(up) { var uploader = $('#uploader').pluploadQueue(); uploader.start(); } } */ }); var uploader = $('#uploader').pluploadQueue(); $('form').submit(function(e) { if (uploader.files.length > 0) { uploader.bind('StateChanged', function() { if (uploader.files.length === (uploader.total.uploaded + uploader.total.failed)) { $('form')[0].submit(); } }); uploader.start(); $("#btn-submit").hide(); $(".message_uploading").fadeIn(); uploader.bind('FileUploaded', function (up, file, info) { var obj = JSON.parse(info.response); var new_file_field = '<input type="hidden" name="finished_files[]" value="'+obj.NewFileName+'" />' $('form').append(new_file_field); }); return false; } else { alert('<?php _e("You must select at least one file to upload.",'cftp_admin'); ?>'); } return false; }); window.onbeforeunload = function (e) { var e = e || window.event; console.log('state? ' + uploader.state); // if uploading if(uploader.state === 2) { <?php $confirmation_msg = "Are you sure? Files currently being uploaded will be discarded if you leave this page."; ?> //IE & Firefox if (e) { e.returnValue = '<?php _e($confirmation_msg,'cftp_admin'); ?>'; } // For Safari return '<?php _e($confirmation_msg,'cftp_admin'); ?>'; } }; }); </script> <form action="upload-process-form.php" name="upload_by_client" id="upload_by_client" method="post" enctype="multipart/form-data"> <input type="hidden" name="uploaded_files" id="uploaded_files" value="" /> <div id="uploader"> <div class="message message_error"> <p><?php _e("Your browser doesn't support HTML5, Flash or Silverlight. Please update your browser or install Adobe Flash or Silverlight to continue.",'cftp_admin'); ?></p> </div> </div> <div class="after_form_buttons"> <button type="submit" name="Submit" class="btn btn-wide btn-primary" id="btn-submit"><?php _e('Upload files','cftp_admin'); ?></button> </div> <div class="message message_info message_uploading"> <p><?php _e("Your files are being uploaded! Progress indicators may take a while to update, but work is still being done behind the scenes.",'cftp_admin'); ?></p> </div> </form> <?php /** End if for users count */ } ?> </div> <?php include('footer.php'); ?>
/* iprtypesle.h -- driver for IBM Power Linux RAID adapters */ /* Written By: Brian King, IBM Corporation */ /* This program is free software; you can redistribute it and/or modify */ /* (at your option) any later version. */ /* This program is distributed in the hope that it will be useful, */ /* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */ /* along with this program; if not, write to the Free Software */ /* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* * $Header: /afs/rchland.ibm.com/usr8/ibmsis/devel/ipr/ipr/src/iprtypesle.h,v 1.2 2003/10/24 20:52:17 bjking1 Exp $ */ /* Note: Any additions/changes here must be duplicated in */ /* iprtypesbe.h */ #ifndef iprtypesle_h #define iprtypesle_h /* Macros */ #define htosis16(x) swab16(x) #define htosis32(x) swab32(x) #define sistoh16(x) swab16(x) #define sistoh32(x) swab32(x) #define _i16(x) _sw16(x) #define _i32(x) _sw32(x) #define IPR_BIG_ENDIAN 0 #define IPR_LITTLE_ENDIAN 1 /* Data Types */ /* Note: All IOA/device data structures using bitfields MUST be */ /* defined here with their bit fields in reverse order */ /* SES Structures */ struct <API key> { u8 status:4; u8 swap:1; u8 reserved:1; u8 predictive_fault:1; u8 select:1; u8 scsi_id:4; u8 reserved2:4; u8 identify:1; u8 reserved4:1; u8 remove:1; u8 insert:1; u8 reserved3:4; u8 reserved6:5; u8 fault_sensed:1; u8 fault_requested:1; u8 reserved5:1; }; struct <API key> { u8 page_code; u8 health_status; u16 byte_count; u8 reserved1[4]; u8 <API key>:4; u8 overall_status_swap:1; u8 <API key>:1; u8 <API key>:1; u8 <API key>:1; u8 <API key>; u8 <API key>:1; u8 <API key>:1; u8 <API key>:1; u8 <API key>:1; u8 <API key>:4; u8 <API key>:1; u8 <API key>:4; u8 <API key>:1; u8 <API key>:1; u8 <API key>:1; struct <API key> elem_status[<API key>]; }; /* SCSI/SIS Structures */ struct ipr_mode_page_hdr { u8 page_code:6; u8 reserved1:1; u8 parms_saveable:1; u8 page_length; }; struct <API key> { struct ipr_res_addr res_addr; u8 reserved2:2; u8 <API key>:1; u8 <API key>:1; u8 term_power_absent:1; u8 enable_target_mode:1; u8 qas_capability:2; #define <API key> 0 #define <API key> 1 #define <API key> 2 /* NOTE: Due to current operation conditions QAS should never be enabled so the change mask will be set to 0 */ #define <API key> 0 u8 scsi_id; #define <API key> 0x80u #define <API key> 0xFFu u8 bus_width; #define <API key> 0 u8 <API key>; #define <API key> 7 u32 max_xfer_rate; #define <API key> 0 u8 min_time_delay; #define <API key> 0xFFu #define <API key> 5 u8 reserved3; u16 reserved4; }; struct <API key> { /* Mode page 0x0A */ struct ipr_mode_page_hdr header; u8 rlec:1; u8 gltsd:1; u8 reserved1:3; u8 tst:3; u8 dque:1; u8 qerr:2; u8 reserved2:1; u8 <API key>:4; u8 eaerp:1; u8 uaaerp:1; u8 raerp:1; u8 swp:1; u8 reserved4:2; u8 rac:1; u8 reserved3:1; u8 reserved5; u16 <API key>; u16 busy_timeout_period; u16 reserved6; }; /* 44 bytes */ struct ipr_std_inq_data{ u8 peri_dev_type:5; u8 peri_qual:3; u8 reserved1:7; u8 removeable_medium:1; u8 version; u8 resp_data_fmt:4; u8 hi_sup:1; u8 norm_aca:1; u8 obsolete1:1; u8 aen:1; u8 additional_len; u8 reserved2:7; u8 sccs:1; u8 addr16:1; u8 obsolete2:2; u8 mchngr:1; u8 multi_port:1; u8 vs:1; u8 enc_serv:1; u8 bque:1; u8 vs2:1; u8 cmd_que:1; u8 trans_dis:1; u8 linked:1; u8 sync:1; u8 wbus16:1; u8 obsolete3:1; u8 rel_adr:1; /* Vendor and Product ID */ struct ipr_std_inq_vpids vpids; /* ROS and RAM levels */ u8 ros_rsvd_ram_rsvd[4]; /* Serial Number */ u8 serial_num[IPR_SERIAL_NUM_LEN]; }; struct <API key> { struct ipr_std_inq_data std_inq_data; u8 z1_term[<API key>]; u8 ius:1; u8 qas:1; u8 clocking:2; u8 reserved:4; u8 reserved1[41]; u8 z2_term[<API key>]; u8 z3_term[<API key>]; u8 reserved2; u8 z4_term[<API key>]; u8 z5_term[<API key>]; u8 part_number[<API key>]; u8 ec_level[<API key>]; u8 fru_number[<API key>]; u8 z6_term[<API key>]; }; /* 1024 bytes */ struct ipr_hostrcb { u8 op_code; u8 notificationType; u8 notificationsLost; u8 reserved0:6; u8 error_resp_sent:1; u8 internal_oper_flag:1; u8 overlayId; u8 reserved1[3]; u32 ilid; u32 <API key>; u32 reserved2; u32 length; union { struct ipr_hostrcb_error error; struct <API key> ccn; }data; }; struct ipr_array_cap_entry { u8 prot_level; #define <API key> "5" u8 reserved:7; u8 include_allowed:1; u16 reserved2; u8 reserved3; u8 <API key>; u8 <API key>; u8 <API key>; u16 reserved4; u16 <API key>; u16 reserved5; u16 <API key>; u8 prot_level_str[8]; }; struct ipr_array_record { struct ipr_record_common common; u8 reserved:6; u8 known_zeroed:1; u8 issue_cmd:1; u8 reserved1; u8 reserved2:5; u8 non_func:1; u8 exposed:1; u8 established:1; u8 reserved3:5; u8 resync_cand:1; u8 stop_cand:1; u8 start_cand:1; u8 reserved4[3]; u8 array_id; u32 reserved5; }; struct ipr_array2_record { struct ipr_record_common common; u8 reserved1:6; u8 known_zeroed:1; u8 issue_cmd:1; u8 reserved2; u8 reserved3:3; u8 no_config_entry:1; u8 high_avail:1; u8 non_func:1; u8 exposed:1; u8 established:1; u8 reserved4:5; u8 resync_cand:1; u8 stop_cand:1; u8 start_cand:1; u16 stripe_size; u8 raid_level; u8 array_id; u32 resource_handle; u32 resource_address; struct ipr_res_addr <API key>; u8 vendor_id[8]; u8 product_id[16]; u8 serial_number[8]; u32 reserved; }; struct ipr_resource_flags { u8 <API key>:2; u8 reserved2:1; u8 aff:1; u8 reserved1:1; u8 is_array_member:1; u8 is_compressed:1; u8 is_ioa_resource:1; u8 reserved3:7; u8 <API key>:1; }; struct ipr_device_record { struct ipr_record_common common; u8 reserved:6; u8 known_zeroed:1; u8 issue_cmd:1; u8 reserved1; u8 reserved2:2; u8 no_cfgte_dev:1; u8 no_cfgte_vol:1; u8 is_hot_spare:1; u8 is_exposed_device:1; u8 has_parity:1; u8 array_member:1; u8 zero_cand:1; u8 rebuild_cand:1; u8 exclude_cand:1; u8 include_cand:1; u8 resync_cand:1; u8 stop_cand:1; u8 parity_cand:1; u8 start_cand:1; u8 reserved3:6; u8 rmv_hot_spare_cand:1; u8 add_hot_spare_cand:1; u8 reserved4[2]; u8 array_id; u32 resource_handle; u16 reserved5; struct ipr_resource_flags <API key>; u32 <API key>; }; struct <API key> { u8 action_status; #define <API key> 0 #define <API key> 1 #define <API key> 2 u8 <API key>:1; u8 reserved3:1; u8 <API key>:1; u8 <API key>:1; u8 reserved2:2; u8 <API key>:1; u8 <API key>:1; u16 num_blocks; u8 <API key>; #define <API key> 0 #define <API key> 1 #define <API key> 2 #define <API key> 3 u8 <API key>; #define <API key> 0 #define <API key> 1 #define <API key> 2 u8 reserved4[2]; u16 raw_power_on_time; u16 <API key>; u16 <API key>; u16 <API key>; u8 reserved5[240]; }; struct ipr_vset_res_state { u16 stripe_size; u8 prot_level; u8 num_devices_in_vset; u32 reserved6; }; struct ipr_dasd_res_state { u32 data_path_width; /* bits */ u32 data_xfer_rate; /* 100 KBytes/second */ }; struct ipr_query_res_state { u8 reserved2:4; u8 not_func:1; u8 not_ready:1; u8 not_oper:1; u8 reserved1:1; u8 reserved3:7; u8 read_write_prot:1; u8 reserved4:3; u8 service_req:1; u8 degraded_oper:1; u8 prot_resuming:1; u8 prot_suspended:1; u8 prot_dev_failed:1; u8 reserved5; union { struct ipr_vset_res_state vset; struct ipr_dasd_res_state dasd; }dev; u32 ilid; u32 failing_dev_ioasc; struct ipr_res_addr <API key>; u32 <API key>; u8 <API key>[8]; }; /* IBM's SIS smart dump table structures */ struct ipr_sdt_entry { u32 bar_str_offset; u32 end_offset; u8 entry_byte; u8 reserved[3]; u8 reserved2:5; u8 valid_entry:1; u8 reserved1:1; u8 endian:1; u8 resv; u16 priority; }; #endif
#undef <API key> /*don't use -- is buggy*/ #define INITIAL_BUFFER_SIZE 50 #define LCMD_OUT_LINE_LEN 70 #define FREAD_BUFFER_SIZE 8192 #include "config.h" #include <stdio.h> #include <ctype.h> #include <errno.h> #ifndef errno extern int errno; #endif #ifdef HAVE_ISATTY # ifdef HAVE_UNISTD_H # include <unistd.h> # endif #endif #ifdef __GNUC__ # if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__-0 >= 7) /* silence warning about unused parameter even for "gcc -W -Wunused" */ # define UNUSED __attribute__((unused)) # endif #endif #ifndef UNUSED # define UNUSED #endif #ifndef HAVE_STRING_H # include <strings.h> # ifdef HAVE_MEMORY_H # include <memory.h> # endif #else # include <string.h> #endif /* HAVE_STRING_H */ #ifdef HAVE_STDLIB_H # include <stdlib.h> #endif #ifdef HAVE_SYS_TYPES_H # include <sys/types.h> #endif #include "regex-sed.h" #include "basicdefs.h" #include "utils.h" #include "sed.h" #ifdef BOOTSTRAP # ifdef memchr # undef memchr # endif # define memchr bootstrap_memchr static VOID *bootstrap_memchr P_((const VOID *s, int c, size_t n)); #endif /*BOOTSTRAP*/ #ifndef HAVE_REGNEXEC # define regnexec(x,t,l,r,n,f) regexec(x,t,r,n,f) #endif /* If set, don't write out the line unless explicitly told to */ extern flagT no_default_output; /* Do we need to be pedantically POSIX compliant? */ extern flagT POSIXLY_CORRECT; /* Sed operates a line at a time. */ struct line { char *text; /* Pointer to line allocated by malloc. */ char *active; /* Pointer to non-consumed part of text. */ size_t length; /* Length of text (or active, if used). */ size_t alloc; /* Allocated space for text. */ flagT chomped; /* Was a trailing newline dropped? */ }; /* A queue of text to write out at the end of a cycle (filled by the "a" and "r" commands.) */ struct append_queue { const char *rfile; const char *text; size_t textlen; struct append_queue *next; }; /* State information for the input stream. */ struct input { char **file_list; /* The list of yet-to-be-opened files. It is invalid for file_list to be NULL. When *file_list is NULL we are currently processing the last file. */ countT bad_count; /* count of files we failed to open */ countT line_number; /* Current input line number (over all files) */ flagT (*read_fn) P_((struct input *)); /* read one line */ /* If fp is NULL, read_fn better not be one which uses fp; in particular, read_always_fail() is recommended. */ FILE *fp; /* if NULL, none of the following are valid */ VOID *base; /* if non-NULL, we are using mmap()ed input */ const char *cur; /* only valid if base is non-NULL */ size_t length; /* only valid if base is non-NULL */ size_t left; /* only valid if base is non-NULL */ #ifdef HAVE_ISATTY flagT is_tty; /* only valid if base is NULL */ #endif }; static void resize_line P_((struct line *lb, size_t len)); static void open_next_file P_((const char *name, struct input *input)); static void closedown P_((struct input *input)); static flagT read_always_fail P_((struct input *input)); static flagT read_mem_line P_((struct input *input)); static size_t slow_getline P_((char *buf, size_t buflen, FILE *in)); static flagT read_file_line P_((struct input *input)); static flagT read_pattern_space P_((struct input *input, flagT append)); static flagT <API key> P_((struct input *input)); static flagT test_dollar_EOF P_((struct input *input)); static flagT match_an_address_p P_((struct addr *, struct input *, flagT)); static flagT match_address_p P_((struct sed_cmd *cmd, struct input *input)); static void do_list P_((void)); static void do_subst P_((struct subst *subst)); static flagT execute_program P_((struct vector *, struct input *input)); static void output_line P_((const char *text, size_t length, flagT nl, FILE *fp)); static void line_init P_((struct line *buf, size_t initial_size)); static void line_copy P_((struct line *from, struct line *to)); static void str_append P_((struct line *to, const char *string, size_t length)); static void nul_append P_((struct line *dest)); static void line_append P_((struct line *from, struct line *to)); static void dump_append_queue P_((void)); static struct append_queue *next_append_slot P_((void)); #ifdef <API key> static countT count_branches P_((struct vector *)); static struct sed_cmd *shrink_program P_((struct vector *vec, struct sed_cmd *cur_cmd, countT*n)); /* Used to attempt a simple-minded optimization. */ static countT <API key>; #endif /*<API key>*/ /* Have we done any replacements lately? This is used by the 't' command. */ static flagT replaced = 0; /* The 'current' input line. */ static struct line line; /* An input line that's been stored by later use by the program */ static struct line hold; /* The buffered input look-ahead. */ static struct line buffer; static struct append_queue *append_head = NULL; static struct append_queue *append_tail = NULL; /* Apply the compiled script to all the named files. */ countT process_files(the_program, argv) struct vector *the_program; char **argv; { static char dash[] = "-"; static char *stdin_argv[2] = { dash, NULL }; struct input input; #ifdef <API key> <API key> = count_branches(the_program); #endif /*<API key>*/ input.file_list = stdin_argv; if (argv && *argv) input.file_list = argv; input.bad_count = 0; input.line_number = 0; input.read_fn = read_always_fail; input.fp = NULL; line_init(&line, INITIAL_BUFFER_SIZE); line_init(&hold, INITIAL_BUFFER_SIZE); line_init(&buffer, FREAD_BUFFER_SIZE); while (read_pattern_space(&input, 0)) { flagT quit = execute_program(the_program, &input); if (!no_default_output) output_line(line.text, line.length, line.chomped, stdout); if (quit) break; } closedown(&input); return input.bad_count; } /* increase a struct line's length, making some attempt at keeping realloc() calls under control by padding for future growth. */ static void resize_line(lb, len) struct line *lb; size_t len; { lb->alloc *= 2; if (lb->alloc - lb->length < len) lb->alloc = lb->length + len; lb->text = REALLOC(lb->text, lb->alloc, char); } /* Initialize a struct input for the named file. */ static void open_next_file(name, input) const char *name; struct input *input; { input->base = NULL; buffer.length = 0; if (name[0] == '-' && name[1] == '\0') { clearerr(stdin); /* clear any stale EOF indication */ input->fp = stdin; } else if ( ! (input->fp = fopen(name, "r")) ) { const char *ptr = strerror(errno); fprintf(stderr, "%s: can't read %s: %s\n", myname, name, ptr); input->read_fn = read_always_fail; /* a redundancy */ ++input->bad_count; return; } input->read_fn = read_file_line; if (map_file(input->fp, &input->base, &input->length)) { input->cur = VCAST(char *)input->base; input->left = input->length; input->read_fn = read_mem_line; } #ifdef HAVE_ISATTY else input->is_tty = isatty(fileno(input->fp)); #endif } /* Clean up an input stream that we are done with. */ static void closedown(input) struct input *input; { input->read_fn = read_always_fail; if (!input->fp) return; if (input->base) unmap_file(input->base, input->length); if (input->fp != stdin) /* stdin can be reused on tty and tape devices */ ck_fclose(input->fp); input->fp = NULL; } /* dummy function to simplify read_pattern_space() */ static flagT read_always_fail(input) struct input *input UNUSED; { return 0; } /* The quick-and-easy mmap()'d case... */ static flagT read_mem_line(input) struct input *input; { const char *e; size_t l; if ( (e = memchr(input->cur, '\n', input->left)) ) { /* common case */ l = e++ - input->cur; line.chomped = 1; } else { /* This test is placed _after_ the memchr() fails for performance reasons (because this branch is the uncommon case and the memchr() will safely fail if input->left == 0). Okay, so the savings is trivial. I'm doing it anyway. */ if (input->left == 0) return 0; e = input->cur + input->left; l = input->left; if (*input->file_list || POSIXLY_CORRECT) line.chomped = 1; } if (line.alloc - line.length < l) resize_line(&line, l); memcpy(line.text + line.length, input->cur, l); line.length += l; input->left -= e - input->cur; input->cur = e; return 1; } #ifdef HAVE_ISATTY /* fgets() doesn't let us handle NULs and fread() buffers too much * for interactive use. */ static size_t slow_getline(buf, buflen, in) char *buf; size_t buflen; FILE *in; { size_t resultlen = 0; int c; while (resultlen<buflen && (c=getc(in))!=EOF) { ++resultlen; *buf++ = c; if (c == '\n') break; } if (ferror(in)) panic("input read error: %s", strerror(errno)); return resultlen; } #endif /*HAVE_ISATTY*/ static flagT read_file_line(input) struct input *input; { char *b; size_t blen; size_t initial_length = line.length; if (!buffer.active) buffer.active = buffer.text; while (!(b = memchr(buffer.active, '\n', buffer.length))) { if (line.alloc-line.length < buffer.length) resize_line(&line, buffer.length); memcpy(line.text+line.length, buffer.active, buffer.length); line.length += buffer.length; buffer.length = 0; if (!feof(input->fp)) { #ifdef HAVE_ISATTY if (input->is_tty) buffer.length = slow_getline(buffer.text, buffer.alloc, input->fp); else #endif buffer.length = ck_fread(buffer.text, 1, buffer.alloc, input->fp); } if (buffer.length == 0) { if (*input->file_list || POSIXLY_CORRECT) line.chomped = 1; /* Did we hit EOF without reading anything? If so, try the next file; otherwise just go with what we did get. */ return (line.length > initial_length); } buffer.active = buffer.text; } blen = b - buffer.active; if (line.alloc-line.length < blen) resize_line(&line, blen); memcpy(line.text+line.length, buffer.active, blen); line.length += blen; ++blen; line.chomped = 1; buffer.active += blen; buffer.length -= blen; return 1; } /* Read in the next line of input, and store it in the pattern space. Return zero if there is nothing left to input. */ static flagT read_pattern_space(input, append) struct input *input; flagT append; { dump_append_queue(); replaced = 0; line.chomped = 0; if (!append) line.length = 0; while ( ! (*input->read_fn)(input) ) { closedown(input); if (!*input->file_list) return 0; open_next_file(*input->file_list++, input); } ++input->line_number; return 1; } static flagT <API key>(input) struct input *input; { /*XXX reference implementation is equivalent to: return !*input->file_list; */ for (;;) { int ch; closedown(input); if (!*input->file_list) return 1; open_next_file(*input->file_list++, input); if (input->fp) { if (input->base) { if (0 < input->left) return 0; } else if ((ch = getc(input->fp)) != EOF) { ungetc(ch, input->fp); return 0; } } } } /* Determine if we match the '$' address. */ static flagT test_dollar_EOF(input) struct input *input; { int ch; if (buffer.length) return 0; if (!input->fp) return <API key>(input); if (input->base) return (input->left==0 && <API key>(input)); if (feof(input->fp)) return <API key>(input); if ((ch = getc(input->fp)) == EOF) return <API key>(input); ungetc(ch, input->fp); return 0; } /* Append a NUL char after the end of DEST, without resizing DEST. This is to permit the use of regexp routines which expect C strings instead of counted strings. */ static void nul_append(dest) struct line *dest; { #ifndef HAVE_REGNEXEC if (dest->alloc - dest->length < 1) resize_line(dest, 1); dest->text[dest->length] = '\0'; #endif } /* Return non-zero if the current line matches the address pointed to by 'addr'. */ static flagT match_an_address_p(addr, input, is_addr2_p) struct addr *addr; struct input *input; flagT is_addr2_p; { switch (addr->addr_type) { case addr_is_null: return 1; case addr_is_num: if (is_addr2_p) return (input->line_number >= addr->a.addr_number); return (input->line_number == addr->a.addr_number); case addr_is_mod: if (addr->a.m.offset < addr->a.m.modulo) return (input->line_number%addr->a.m.modulo == addr->a.m.offset); /* offset >= modulo implies we have an extra initial skip */ if (input->line_number < addr->a.m.offset) return 0; /* normalize */ addr->a.m.offset %= addr->a.m.modulo; return 1; case addr_is_last: return test_dollar_EOF(input); case addr_is_regex: nul_append(&line); return !regnexec(addr->a.addr_regex, line.text, line.length, 0, NULL, 0); default: panic("INTERNAL ERROR: bad address type"); } /*NOTREACHED*/ return 0; } /* return non-zero if current address is valid for cmd */ static flagT match_address_p(cmd, input) struct sed_cmd *cmd; struct input *input; { flagT addr_matched = cmd->a1_matched; if (addr_matched) { if (match_an_address_p(&cmd->a2, input, 1)) cmd->a1_matched = 0; } else if (match_an_address_p(&cmd->a1, input, 0)) { addr_matched = 1; if (cmd->a2.addr_type != addr_is_null) if ( (cmd->a2.addr_type == addr_is_regex) || !match_an_address_p(&cmd->a2, input, 1)) cmd->a1_matched = 1; } if (cmd->addr_bang) addr_matched = !addr_matched; return addr_matched; } static void do_list() { unsigned char *p = CAST(unsigned char *)line.text; countT len = line.length; countT width = 0; char obuf[180]; /* just in case we encounter a 512-bit char ;-) */ char *o; size_t olen; for (; len o = obuf; if (ISPRINT(*p)) { *o++ = *p; if (*p == '\\') *o++ = '\\'; } else { *o++ = '\\'; switch (*p) { #if defined __STDC__ && __STDC__ case '\a': *o++ = 'a'; break; #else /* If not STDC we'll just assume ASCII */ case 007: *o++ = 'a'; break; #endif case '\b': *o++ = 'b'; break; case '\f': *o++ = 'f'; break; case '\n': *o++ = 'n'; break; case '\r': *o++ = 'r'; break; case '\t': *o++ = 't'; break; case '\v': *o++ = 'v'; break; default: sprintf(o, "%03o", *p); o += strlen(o); break; } } olen = o - obuf; if (width+olen >= LCMD_OUT_LINE_LEN) { ck_fwrite("\\\n", 1, 2, stdout); width = 0; } ck_fwrite(obuf, 1, olen, stdout); width += olen; } ck_fwrite("$\n", 1, 2, stdout); } static void do_subst(sub) struct subst *sub; { /* s_accum will accumulate the result of the s command. */ /* static so as to keep malloc() calls down */ static struct line s_accum; size_t start; /* where to start scan for match in LINE */ size_t offset; /* where in LINE a match was found */ size_t remain; /* length after START, sans trailing newline */ countT count; /* number of matches found */ char *rep; /* the replacement string */ char *rep_end; /* end of the replacement string */ flagT not_bol_p; flagT did_subst; regmatch_t regs[10]; if (s_accum.alloc == 0) line_init(&s_accum, INITIAL_BUFFER_SIZE); s_accum.length = 0; count = 0; did_subst = 0; not_bol_p = 0; start = 0; remain = line.length - start; rep = sub->replacement; rep_end = rep + sub->replace_length; nul_append(&line); while ( ! regnexec(sub->regx, line.text + start, remain, sizeof(regs) / sizeof(regs[0]), regs, not_bol_p) ) { ++count; offset = regs[0].rm_so + start; /* * +- line.text +-[offset] * V V * "blah blah blah xyzzy blah blah blah blah" * ^ ^ ^ * +-[start] +-[end] +-[start + remain] * * * regs[0].rm_so == offset - start * regs[0].rm_eo == end - start */ /* Copy stuff to the left of the next match into the output * string. */ if (start < offset) str_append(&s_accum, line.text + start, offset - start); /* If we're counting up to the Nth match, are we there yet? */ if (count < sub->numb) { /* Not there yet...so skip this match. */ size_t matched = regs[0].rm_eo - regs[0].rm_so; /* If the match was vacuous, skip ahead one character * anyway. It isn't at all obvious to me that this is * the right behavior for this case. -t XXX */ if (matched == 0 && offset < line.length) matched = 1; str_append(&s_accum, line.text + offset, matched); start = offset + matched; remain = line.length - start; not_bol_p = 1; continue; } /* Expand the replacement string into the output string. */ { char *rep_cur; /* next burst being processed in replacement */ char *rep_next; /* end of burst in replacement */ /* Replacement strings can be viewed as a sequence of variable * length commands. A command can be a literal string or a * backreference (either numeric or "&"). * * This loop measures off the next command between * REP_CUR and REP_NEXT, handles that command, and loops. */ for (rep_next = rep_cur = rep; rep_next < rep_end; rep_next++) { if (*rep_next == '\\') { /* Preceding the backslash may be some literal * text: */ if (rep_cur < rep_next) str_append(&s_accum, rep_cur, CAST(size_t)(rep_next - rep_cur)); /* Skip the backslash itself and look for * a numeric back-reference: */ rep_next++; if (rep_next < rep_end && '0' <= *rep_next && *rep_next <= '9') { int i = *rep_next - '0'; str_append(&s_accum, line.text + start + regs[i].rm_so, CAST(size_t)(regs[i].rm_eo-regs[i].rm_so)); } else str_append(&s_accum, rep_next, 1); rep_cur = rep_next + 1; } else if (*rep_next == '&') { /* Preceding the ampersand may be some literal * text: */ if (rep_cur < rep_next) str_append(&s_accum, rep_cur, CAST(size_t)(rep_next - rep_cur)); str_append(&s_accum, line.text + start + regs[0].rm_so, CAST(size_t)(regs[0].rm_eo - regs[0].rm_so)); rep_cur = rep_next + 1; } } /* There may be a trailing literal in the replacement string. */ if (rep_cur < rep_next) str_append(&s_accum, rep_cur, CAST(size_t)(rep_next - rep_cur)); } did_subst = 1; not_bol_p = 1; start += regs[0].rm_eo; remain = line.length - start; if (!sub->global || remain == 0) break; /* If the match was vacuous, skip over one character * and add that character to the output. */ if (regs[0].rm_so == regs[0].rm_eo) { str_append(&s_accum, line.text + offset, 1); ++start; --remain; } } if (did_subst) { struct line tmp; if (start < line.length) str_append(&s_accum, line.text + start, remain); memcpy(VCAST(VOID *)&tmp, VCAST(VOID *)&line, sizeof line); memcpy(VCAST(VOID *)&line, VCAST(VOID *)&s_accum, sizeof line); line.chomped = tmp.chomped; memcpy(VCAST(VOID *)&s_accum, VCAST(VOID *)&tmp, sizeof line); if (sub->wfile) output_line(line.text, line.length, line.chomped, sub->wfile); if (sub->print) output_line(line.text, line.length, line.chomped, stdout); replaced = 1; } } /* Execute the program 'vec' on the current input line. Return non-zero if caller should quit, 0 otherwise. */ static flagT execute_program(vec, input) struct vector *vec; struct input *input; { struct vector *cur_vec; struct sed_cmd *cur_cmd; size_t n; cur_vec = vec; cur_cmd = cur_vec->v; n = cur_vec->v_length; while (n) { if (match_address_p(cur_cmd, input)) { switch (cur_cmd->cmd) { case '{': /* Execute sub-program */ if (cur_cmd->x.sub->v_length) { cur_vec = cur_cmd->x.sub; cur_cmd = cur_vec->v; n = cur_vec->v_length; continue; } break; case '}': { countT i = cur_vec->return_i; cur_vec = cur_vec->return_v; cur_cmd = cur_vec->v + i; n = cur_vec->v_length - i; } continue; case 'a': { struct append_queue *aq = next_append_slot(); aq->text = cur_cmd->x.cmd_txt.text; aq->textlen = cur_cmd->x.cmd_txt.text_len; } break; case 'b': if (cur_cmd->x.jump) { struct sed_label *j = cur_cmd->x.jump; countT i = j->v_index; cur_vec = j->v; cur_cmd = cur_vec->v + i; n = cur_vec->v_length - i; continue; } return 0; case 'c': line.length = 0; line.chomped = 0; if (!cur_cmd->a1_matched) output_line(cur_cmd->x.cmd_txt.text, cur_cmd->x.cmd_txt.text_len, 0, stdout); /* POSIX.2 is silent about c starting a new cycle, but it seems to be expected (and make sense). */ return 0; case 'd': line.length = 0; line.chomped = 0; return 0; case 'D': { char *p = memchr(line.text, '\n', line.length); if (!p) { line.length = 0; line.chomped = 0; return 0; } ++p; memmove(line.text, p, line.length); line.length -= p - line.text; /* reset to start next cycle without reading a new line: */ cur_vec = vec; cur_cmd = cur_vec->v; n = cur_vec->v_length; continue; } case 'g': line_copy(&hold, &line); break; case 'G': line_append(&hold, &line); break; case 'h': line_copy(&line, &hold); break; case 'H': line_append(&line, &hold); break; case 'i': output_line(cur_cmd->x.cmd_txt.text, cur_cmd->x.cmd_txt.text_len, 0, stdout); break; case 'l': do_list(); break; case 'n': if (!no_default_output) output_line(line.text, line.length, line.chomped, stdout); if (!read_pattern_space(input, 0)) return 1; break; case 'N': str_append(&line, "\n", 1); if (!read_pattern_space(input, 1)) return 1; break; case 'p': output_line(line.text, line.length, line.chomped, stdout); break; case 'P': { char *p = memchr(line.text, '\n', line.length); output_line(line.text, p ? p - line.text : line.length, p ? 1 : line.chomped, stdout); } break; case 'q': return 1; case 'r': if (cur_cmd->x.rfile) { struct append_queue *aq = next_append_slot(); aq->rfile = cur_cmd->x.rfile; } break; case 's': do_subst(&cur_cmd->x.cmd_regex); break; case 't': if (replaced) { replaced = 0; if (cur_cmd->x.jump) { struct sed_label *j = cur_cmd->x.jump; countT i = j->v_index; cur_vec = j->v; cur_cmd = cur_vec->v + i; n = cur_vec->v_length - i; continue; } return 0; } break; case 'w': if (cur_cmd->x.wfile) output_line(line.text, line.length, line.chomped, cur_cmd->x.wfile); break; case 'x': { struct line temp; memcpy(VCAST(VOID *)&temp, VCAST(VOID *)&line, sizeof line); memcpy(VCAST(VOID *)&line, VCAST(VOID *)&hold, sizeof line); memcpy(VCAST(VOID *)&hold, VCAST(VOID *)&temp, sizeof line); } break; case 'y': { unsigned char *p, *e; p = CAST(unsigned char *)line.text; for (e=p+line.length; p<e; ++p) *p = cur_cmd->x.translate[*p]; } break; case ':': /* Executing labels is easy. */ break; case '=': printf("%lu\n", CAST(unsigned long)input->line_number); break; default: panic("INTERNAL ERROR: Bad cmd %c", cur_cmd->cmd); } } #ifdef <API key> /* If our top-level program consists solely of commands with addr_is_num * address then once we past the last mentioned line we should be able * to quit if no_default_output is true, or otherwise quickly copy input * to output. Now whether this optimization is a win or not depends * on how cheaply we can implement this for the cases where it doesn't * help, as compared against how much time is saved. * One semantic difference (which I think is an improvement) is * that *this* version will terminate after printing line two * in the script "yes | sed -n 2p". */ else { /* can we ever match again? */ if (cur_cmd->a1.addr_type == addr_is_num && ((input->line_number < cur_cmd->a1.a.addr_number) != !cur_cmd->addr_bang)) { /* skip all this next time */ cur_cmd->a1.addr_type = addr_is_null; cur_cmd->addr_bang = 1; /* can we make an optimization? */ if (cur_cmd->cmd == '{' || cur_cmd->cmd == '}' || cur_cmd->cmd == 'b' || cur_cmd->cmd == 't') { if (cur_vec == vec) --<API key>; cur_cmd->cmd = ':'; /* replace with no-op */ } if (cur_vec == vec && <API key> == 0) { /* whew! all that just so that we can get to here! */ countT new_n = n; cur_cmd = shrink_program(cur_vec, cur_cmd, &new_n); n = new_n; if (!cur_cmd && no_default_output) return 1; continue; } } } #endif /*<API key>*/ /* these are buried down here so that a "continue" statement can skip them */ ++cur_cmd; --n; } return 0; } static void output_line(text, length, nl, fp) const char *text; size_t length; flagT nl; FILE *fp; { ck_fwrite(text, 1, length, fp); if (nl) ck_fwrite("\n", 1, 1, fp); if (fp != stdout) ck_fflush(fp); } /* initialize a "struct line" buffer */ static void line_init(buf, initial_size) struct line *buf; size_t initial_size; { buf->text = MALLOC(initial_size, char); buf->active = NULL; buf->alloc = initial_size; buf->length = 0; buf->chomped = 1; } /* Copy the contents of the line 'from' into the line 'to'. This destroys the old contents of 'to'. It will still work if the line 'from' contains NULs. */ static void line_copy(from, to) struct line *from; struct line *to; { if (to->alloc < from->length) { to->alloc = from->length; to->text = REALLOC(to->text, to->alloc, char); } memcpy(to->text, from->text, from->length); to->length = from->length; to->chomped = from->chomped; } /* Append 'length' bytes from 'string' to the line 'to' This routine *will* append NUL bytes without failing. */ static void str_append(to, string, length) struct line *to; const char *string; size_t length; { if (to->alloc - to->length < length) resize_line(to, length); memcpy(to->text + to->length, string, length); to->length += length; } /* Append the contents of the line 'from' to the line 'to'. This routine will work even if the line 'from' contains nulls */ static void line_append(from, to) struct line *from; struct line *to; { str_append(to, "\n", 1); str_append(to, from->text, from->length); to->chomped = from->chomped; } static struct append_queue * next_append_slot() { struct append_queue *n = MALLOC(1, struct append_queue); n->rfile = NULL; n->text = NULL; n->textlen = 0; n->next = NULL; if (append_tail) append_tail->next = n; else append_head = n; return append_tail = n; } static void dump_append_queue() { struct append_queue *p, *q; for (p=append_head; p; p=q) { if (p->text) output_line(p->text, p->textlen, 0, stdout); if (p->rfile) { char buf[FREAD_BUFFER_SIZE]; size_t cnt; FILE *fp; fp = fopen(p->rfile, "r"); /* Not ck_fopen() because: "If _rfile_ does not exist or cannot be read, it shall be treated as if it were an empty file, causing no error condition." IEEE Std 1003.2-1992 */ if (fp) { while ((cnt = ck_fread(buf, 1, sizeof buf, fp)) > 0) ck_fwrite(buf, 1, cnt, stdout); fclose(fp); } } q = p->next; FREE(p); } append_head = append_tail = NULL; } #ifdef <API key> static countT count_branches(program) struct vector *program; { struct sed_cmd *cur_cmd = program->v; countT isn_cnt = program->v_length; countT cnt = 0; while (isn_cnt { switch (cur_cmd->cmd) { case '{': case '}': case 'b': case 't': ++cnt; } } return cnt; } static struct sed_cmd * shrink_program(vec, cur_cmd, n) struct vector *vec; struct sed_cmd *cur_cmd; countT *n; { struct sed_cmd *v = vec->v; struct sed_cmd *last_cmd = v + vec->v_length; struct sed_cmd *p; countT cmd_cnt; for (p=v; p < cur_cmd; ++p) if (p->cmd != ':') *v++ = *p; cmd_cnt = v - vec->v; for (++p; p < last_cmd; ++p) if (p->cmd != ':') *v++ = *p; vec->v_length = v - vec->v; *n = vec->v_length - cmd_cnt; return 0 < vec->v_length ? cur_cmd-cmd_cnt : CAST(struct sed_cmd *)0; } #endif /*<API key>*/ #ifdef BOOTSTRAP /* We can't be sure that the system we're boostrapping on has memchr(), and ../lib/memchr.c requires configuration knowledge about how many bits are in a `long'. This implementation is far from ideal, but it should get us up-and-limping well enough to run the configure script, which is all that matters. */ static VOID * bootstrap_memchr(s, c, n) const VOID *s; int c; size_t n; { char *p; for (p=(char *)s; n-- > 0; ++p) if (*p == c) return p; return CAST(VOID *)0; } #endif /*BOOTSTRAP*/
package cc.dectinc.leetcode; import java.util.HashMap; /** * @author Dectinc * @version Apr 9, 2015 9:45:35 PM * */ public class <API key> { public int longestConsecutive(int[] num) { if (num == null || num.length == 0) { return 0; } int maxLength = 1; HashMap<Integer, Integer> lengthMap = new HashMap<Integer, Integer>(); for (int a : num) { if (lengthMap.containsKey(a)) { continue; } lengthMap.put(a, 1); int end = a; int begin = a; if (lengthMap.containsKey(a - 1)) { begin -= lengthMap.get(a - 1); } if (lengthMap.containsKey(a + 1)) { end += lengthMap.get(a + 1); } int curLength = end - begin + 1; maxLength = Math.max(maxLength, curLength); lengthMap.put(end, curLength); lengthMap.put(begin, curLength); } return maxLength; } public static void main(String args[]) { int[] num = { 100, 4, 200, 1, 3, 2 }; System.out.println(new <API key>() .longestConsecutive(num)); } }
// File: <API key>.h // Project: Kactus2 // Description: // The Address spaces-item in the component editor navigation tree. #ifndef <API key> #define <API key> #include "componenteditoritem.h" #include <QList> class ExpressionParser; class Component; class AddressSpace; class <API key>; class <API key>; class <API key>; class ParameterValidator; //! The Address spaces-item in the component editor navigation tree. class <API key> : public ComponentEditorItem { Q_OBJECT public: /*! * The constructor. * * @param [in] model The model that owns the items. * @param [in] libHandler The instance that manages the library. * @param [in] component The component being edited. * @param [in] referenceCounter The instance for counting references to parameters. * @param [in] parameterFinder The parameter finder. * @param [in] expressionFormatter The expression formatter. * @param [in] expressionParser The expression parser to use. * @param [in] parent The parent item. */ <API key>(<API key>* model, LibraryInterface* libHandler, QSharedPointer<Component> component, QSharedPointer<ReferenceCounter> referenceCounter, QSharedPointer<ParameterFinder> parameterFinder, QSharedPointer<ExpressionFormatter> expressionFormatter, QSharedPointer<ExpressionParser> expressionParser, ComponentEditorItem* parent); //! The destructor. virtual ~<API key>(); /*! * Get the font to be used for text of this item. * * @return QFont instance that defines the font to be used. */ virtual QFont getFont() const; /*! * Get the tool tip for the item. * * @return The text for the tool tip to print to user. */ virtual QString getTooltip() const; /*! * Get the text to be displayed to user in the tree for this item. * * @return QString Contains the text to display. */ virtual QString text() const; /*! * Get pointer to the editor of this item. * * @return The editor to use for this item. */ virtual ItemEditor* editor(); /*! * Add a new child to the item. * * @param [in] index The index to add the child into. */ virtual void createChild(int index); private slots: /*! * Emitted when address unit bits change on an address space. * * @param [in] spaceIndex Index of the address space being changed. */ void <API key>(int spaceIndex); private: //! No copying. <API key>(const <API key>& other); <API key>& operator=(const <API key>& other); /*! * Create the necessary validators for address spaces. */ void <API key>(); /*! * Create the interface for address blocks. */ void <API key>(); /*! * Create interface for accessing bus interfaces. * * @param [in] parameterValidator Validator for parameters. * * @return Interface for accessing bus interfaces. */ <API key>* <API key>(QSharedPointer<ParameterValidator> parameterValidator); // Data. //! The address spaces being edited. QSharedPointer<QList<QSharedPointer<AddressSpace> > > addressSpaces_; //! The expression parser to use. QSharedPointer<ExpressionParser> expressionParser_; //! The current address space validator. QSharedPointer<<API key>> spaceValidator_; //! Interface for address blocks. <API key>* blockInterface_; }; #endif // <API key>
package billing; import org.caesarj.runtime.CaesarThread; import uppercaseserver.*; import java.io.*; import java.net.*; import java.text.DecimalFormat; /** * Deploys billin on the server. * The billing mode is deployed dynamically. */ public deployed class <API key> { /** * Superimposes the functionality of the UppercaseWorker.run()-method. * Receives the a string from the client, that determines the billing-mode. * Depending on that string a BillingAspect is instantiated. * That BillingAspect is deployed around a proceed-call, that triggers the execution * of the original run()-functionality. */ void around(UppercaseWorker worker) : execution(* run()) && target(worker) { String mode = ""; try { BufferedReader modeReader = new BufferedReader( new InputStreamReader( worker._requestSocket.getInputStream())); mode = modeReader.readLine(); } catch (IOException ex) { } finally { } //create the appropriate BillingAspect instance BillingAspect billingAspect = null; if (mode.equals("flat")) { billingAspect = new <API key>(); System.out.println("Billing mode: flat rate"); } else if (mode.equals("request")) { billingAspect = new <API key>(); System.out.println("Billing mode: per request"); } else if (mode.equals("letter")) { billingAspect = new <API key>(); System.out.println("Billing mode: per letter"); } else if (mode.equals("none")) { System.out.println("Billing mode: no billing"); } else { billingAspect = new <API key>(); System.out.println("Billing mode: default = per request"); } //deploy the BillingAspect deploy(billingAspect) { proceed(worker); } if (billingAspect != null) { DecimalFormat df = new DecimalFormat("0.00"); String price = df.format(billingAspect.getTotalPrice()); System.out.println("Session price: " + price + " Euro"); } } }
#include <stdlib.h> #include <kdebug.h> #include <klocale.h> #include <kapplication.h> #include <dcopclient.h> #include <kcmdlineargs.h> #include <qeventloop.h> #include "kio_media.h" static const KCmdLineOptions options[] = {{"+protocol", I18N_NOOP("Protocol name"), 0}, {"+pool", I18N_NOOP("Socket name"), 0}, {"+app", I18N_NOOP("Socket name"), 0}, KCmdLineLastOption}; extern "C" { int KDE_EXPORT kdemain(int argc, char **argv) { // KApplication is necessary to use other ioslaves putenv(strdup("SESSION_MANAGER=")); KCmdLineArgs::init(argc, argv, "kio_media", 0, 0, 0, 0); KCmdLineArgs::addCmdLineOptions(options); KApplication app(false, false); // We want to be anonymous even if we use DCOP app.dcopClient()->attach(); KCmdLineArgs *args = KCmdLineArgs::parsedArgs(); MediaProtocol slave(args->arg(0), args->arg(1), args->arg(2)); slave.dispatchLoop(); return 0; } } MediaProtocol::MediaProtocol(const QCString &protocol, const QCString &pool, const QCString &app) : ForwardingSlaveBase(protocol, pool, app) { connect(&m_impl, SIGNAL(warning(const QString &)), this, SLOT(slotWarning(const QString &))); } MediaProtocol::~MediaProtocol() { } bool MediaProtocol::rewriteURL(const KURL &url, KURL &newUrl) { QString name, path; if(!m_impl.parseURL(url, name, path)) { error(KIO::ERR_MALFORMED_URL, url.prettyURL()); return false; } if(!m_impl.realURL(name, path, newUrl)) { error(m_impl.lastErrorCode(), m_impl.lastErrorMessage()); return false; } return true; } void MediaProtocol::put(const KURL &url, int permissions, bool overwrite, bool resume) { kdDebug(1219) << "MediaProtocol::put: " << url << endl; QString name, path; bool ok = m_impl.parseURL(url, name, path); if(ok && path.isEmpty()) { error(KIO::<API key>, url.prettyURL()); } else { ForwardingSlaveBase::put(url, permissions, overwrite, resume); } } void MediaProtocol::rename(const KURL &src, const KURL &dest, bool overwrite) { kdDebug(1219) << "MediaProtocol::rename: " << src << ", " << dest << ", " << overwrite << endl; QString src_name, src_path; bool ok = m_impl.parseURL(src, src_name, src_path); QString dest_name, dest_path; ok &= m_impl.parseURL(dest, dest_name, dest_path); if(ok && src_path.isEmpty() && dest_path.isEmpty() && src.protocol() == "media" && dest.protocol() == "media") { if(!m_impl.setUserLabel(src_name, dest_name)) { error(m_impl.lastErrorCode(), m_impl.lastErrorMessage()); } else { finished(); } } else { ForwardingSlaveBase::rename(src, dest, overwrite); } } void MediaProtocol::mkdir(const KURL &url, int permissions) { kdDebug(1219) << "MediaProtocol::mkdir: " << url << endl; QString name, path; bool ok = m_impl.parseURL(url, name, path); if(ok && path.isEmpty()) { error(KIO::ERR_COULD_NOT_MKDIR, url.prettyURL()); } else { ForwardingSlaveBase::mkdir(url, permissions); } } void MediaProtocol::del(const KURL &url, bool isFile) { kdDebug(1219) << "MediaProtocol::del: " << url << endl; QString name, path; bool ok = m_impl.parseURL(url, name, path); if(ok && path.isEmpty()) { error(KIO::ERR_CANNOT_DELETE, url.prettyURL()); } else { ForwardingSlaveBase::del(url, isFile); } } void MediaProtocol::stat(const KURL &url) { kdDebug(1219) << "MediaProtocol::stat: " << url << endl; QString path = url.path(); if(path.isEmpty() || path == "/") { // The root is "virtual" - it's not a single physical directory KIO::UDSEntry entry; m_impl.createTopLevelEntry(entry); statEntry(entry); finished(); return; } QString name; bool ok = m_impl.parseURL(url, name, path); if(!ok) { error(KIO::ERR_MALFORMED_URL, url.prettyURL()); return; } if(path.isEmpty()) { KIO::UDSEntry entry; if(m_impl.statMedium(name, entry) || m_impl.statMediumByLabel(name, entry)) { statEntry(entry); finished(); } else { error(KIO::ERR_DOES_NOT_EXIST, url.prettyURL()); } } else { ForwardingSlaveBase::stat(url); } } void MediaProtocol::listDir(const KURL &url) { kdDebug(1219) << "MediaProtocol::listDir: " << url << endl; if(url.path().length() <= 1) { listRoot(); return; } QString name, path; bool ok = m_impl.parseURL(url, name, path); if(!ok) { error(KIO::ERR_MALFORMED_URL, url.prettyURL()); return; } ForwardingSlaveBase::listDir(url); } void MediaProtocol::listRoot() { KIO::UDSEntry entry; KIO::UDSEntryList media_entries; bool ok = m_impl.listMedia(media_entries); if(!ok) { error(m_impl.lastErrorCode(), m_impl.lastErrorMessage()); return; } totalSize(media_entries.count() + 1); m_impl.createTopLevelEntry(entry); listEntry(entry, false); KIO::<API key> it = media_entries.begin(); KIO::<API key> end = media_entries.end(); for(; it != end; ++it) { listEntry(*it, false); } entry.clear(); listEntry(entry, true); finished(); } void MediaProtocol::slotWarning(const QString &msg) { warning(msg); } #include "kio_media.moc"
package org.hibernate.cfg; import java.util.HashMap; import java.util.Iterator; import java.util.Locale; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import org.hibernate.AnnotationException; import org.hibernate.AssertionFailure; import org.hibernate.MappingException; import org.hibernate.boot.spi.<API key>; import org.hibernate.mapping.Column; import org.hibernate.mapping.Component; import org.hibernate.mapping.PersistentClass; import org.hibernate.mapping.Property; import org.hibernate.mapping.Selectable; import org.hibernate.mapping.SimpleValue; import org.jboss.logging.Logger; /** * @author Emmanuel Bernard */ public class <API key> implements SecondPass { private static final Logger log = Logger.getLogger( <API key>.class ); private final String <API key>; private final Component component; private final <API key> buildingContext; private final Ejb3JoinColumn[] joinColumns; public <API key>( Component comp, String <API key>, Ejb3JoinColumn[] joinColumns, <API key> buildingContext) { this.component = comp; this.<API key> = <API key>; this.buildingContext = buildingContext; this.joinColumns = joinColumns; } @SuppressWarnings({ "unchecked" }) public void doSecondPass(Map persistentClasses) throws MappingException { PersistentClass <API key> = (PersistentClass) persistentClasses.get( <API key> ); // TODO better error names if ( <API key> == null ) { throw new AnnotationException( "Unknown entity name: " + <API key> ); } if ( ! ( <API key>.getIdentifier() instanceof Component ) ) { throw new AssertionFailure( "Unexpected identifier type on the referenced entity when mapping a @MapsId: " + <API key> ); } Component referencedComponent = (Component) <API key>.getIdentifier(); Iterator<Property> properties = referencedComponent.getPropertyIterator(); //prepare column name structure boolean isExplicitReference = true; Map<String, Ejb3JoinColumn> <API key> = new HashMap<>(joinColumns.length); for (Ejb3JoinColumn joinColumn : joinColumns) { final String <API key> = joinColumn.getReferencedColumn(); if ( <API key> == null || BinderHelper.<API key>( <API key> ) ) { break; } //JPA 2 requires <API key> to be case insensitive <API key>.put( <API key>.toLowerCase(Locale.ROOT), joinColumn ); } //try default column orientation AtomicInteger index = new AtomicInteger( 0 ); if ( <API key>.isEmpty() ) { isExplicitReference = false; for (Ejb3JoinColumn joinColumn : joinColumns) { <API key>.put( "" + index.get(), joinColumn ); index.getAndIncrement(); } index.set( 0 ); } while ( properties.hasNext() ) { Property referencedProperty = properties.next(); if ( referencedProperty.isComposite() ) { Property property = <API key>( <API key>, isExplicitReference, <API key>, index, referencedProperty ); component.addProperty( property ); } else { Property property = <API key>( <API key>, isExplicitReference, <API key>, index, referencedProperty ); component.addProperty( property ); } } } private Property <API key>( PersistentClass <API key>, boolean isExplicitReference, Map<String, Ejb3JoinColumn> <API key>, AtomicInteger index, Property referencedProperty ) { Property property = new Property(); property.setName( referencedProperty.getName() ); //FIXME set optional? //property.setOptional( property.isOptional() ); property.setPersistentClass( component.getOwner() ); property.<API key>( referencedProperty.<API key>() ); Component value = new Component( buildingContext, component.getOwner() ); property.setValue( value ); final Component referencedValue = (Component) referencedProperty.getValue(); value.setTypeName( referencedValue.getTypeName() ); value.setTypeParameters( referencedValue.getTypeParameters() ); value.<API key>( referencedValue.<API key>() ); Iterator<Property> propertyIterator = referencedValue.getPropertyIterator(); while(propertyIterator.hasNext()) { Property <API key> = propertyIterator.next(); if ( <API key>.isComposite() ) { Property componentProperty = <API key>( referencedValue.getOwner(), isExplicitReference, <API key>, index, <API key> ); value.addProperty( componentProperty ); } else { Property componentProperty = <API key>( referencedValue.getOwner(), isExplicitReference, <API key>, index, <API key> ); value.addProperty( componentProperty ); } } return property; } private Property <API key>( PersistentClass <API key>, boolean isExplicitReference, Map<String, Ejb3JoinColumn> <API key>, AtomicInteger index, Property referencedProperty ) { Property property = new Property(); property.setName( referencedProperty.getName() ); //FIXME set optional? //property.setOptional( property.isOptional() ); property.setPersistentClass( component.getOwner() ); property.<API key>( referencedProperty.<API key>() ); SimpleValue value = new SimpleValue( buildingContext, component.getTable() ); property.setValue( value ); final SimpleValue referencedValue = (SimpleValue) referencedProperty.getValue(); value.setTypeName( referencedValue.getTypeName() ); value.setTypeParameters( referencedValue.getTypeParameters() ); final Iterator<Selectable> columns = referencedValue.getColumnIterator(); if ( joinColumns[0].isNameDeferred() ) { joinColumns[0].<API key>( <API key>, columns, value); } else { //FIXME take care of Formula while ( columns.hasNext() ) { final Selectable selectable = columns.next(); if ( ! Column.class.isInstance( selectable ) ) { log.debug( "Encountered formula definition; skipping" ); continue; } final Column column = (Column) selectable; final Ejb3JoinColumn joinColumn; String logicalColumnName = null; if ( isExplicitReference ) { final String columnName = column.getName(); logicalColumnName = buildingContext.<API key>().<API key>( <API key>.getTable(), columnName ); //JPA 2 requires <API key> to be case insensitive joinColumn = <API key>.get( logicalColumnName.toLowerCase(Locale.ROOT ) ); } else { joinColumn = <API key>.get( "" + index.get() ); index.getAndIncrement(); } if ( joinColumn == null && ! joinColumns[0].isNameDeferred() ) { throw new AnnotationException( isExplicitReference ? "Unable to find column reference in the @MapsId mapping: " + logicalColumnName : "Implicit column reference in the @MapsId mapping fails, try to use explicit <API key>: " + <API key> ); } final String columnName = joinColumn == null || joinColumn.isNameDeferred() ? "tata_" + column.getName() : joinColumn .getName(); value.addColumn( new Column( columnName ) ); if ( joinColumn != null ) { <API key>( column, joinColumn ); joinColumn.linkWithValue( value ); } column.setValue( value ); } } return property; } private void <API key>(Column column, Ejb3JoinColumn joinColumn) { Column mappingColumn = joinColumn.getMappingColumn(); mappingColumn.setLength( column.getLength() ); mappingColumn.setPrecision( column.getPrecision() ); mappingColumn.setScale( column.getScale() ); } public boolean dependentUpon( <API key> other ) { return this.<API key>.equals( other.component.getOwner().getEntityName() ); } }
using iCal_sync.Common; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.Graphics.Display; using Windows.UI.ViewManagement; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; using iCal_sync.ViewModel; using NodaTime; namespace iCal_sync.View { <summary> An empty page that can be used on its own or navigated to within a Frame. </summary> public sealed partial class TimeZoneSelectView : Page { private NavigationHelper navigationHelper; private <API key> defaultViewModel = new <API key>(); public static <API key> ViewModel; public TimeZoneSelectView() { this.InitializeComponent(); this.navigationHelper = new NavigationHelper(this); this.navigationHelper.LoadState += this.<API key>; this.navigationHelper.SaveState += this.<API key>; } <summary> Gets the <see cref="NavigationHelper"/> associated with this <see cref="Page"/>. </summary> public NavigationHelper NavigationHelper { get { return this.navigationHelper; } } <summary> Gets the view model for this <see cref="Page"/>. This can be changed to a strongly typed view model. </summary> public <API key> DefaultViewModel { get { return this.defaultViewModel; } } <summary> Populates the page with content passed during navigation. Any saved state is also provided when recreating a page from a prior session. </summary> <param name="sender"> The source of the event; typically <see cref="NavigationHelper"/> </param> <param name="e">Event data that provides both the navigation parameter passed to <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested and a dictionary of state preserved by this page during an earlier session. The state will be null the first time a page is visited.</param> private void <API key>(object sender, LoadStateEventArgs e) { } <summary> Preserves state associated with this page in case the application is suspended or the page is discarded from the navigation cache. Values must conform to the serialization requirements of <see cref="SuspensionManager.SessionState"/>. </summary> <param name="sender">The source of the event; typically <see cref="NavigationHelper"/></param> <param name="e">Event data that provides an empty dictionary to be populated with serializable state.</param> private void <API key>(object sender, SaveStateEventArgs e) { } #region NavigationHelper registration <summary> The methods provided in this section are simply used to allow NavigationHelper to respond to the page's navigation methods. <para> Page specific logic should be placed in event handlers for the <see cref="NavigationHelper.LoadState"/> and <see cref="NavigationHelper.SaveState"/>. The navigation parameter is available in the LoadState method in addition to page state preserved during an earlier session. </para> </summary> <param name="e">Provides data for navigation methods and event handlers that cannot cancel the navigation request.</param> protected override void OnNavigatedTo(NavigationEventArgs e) { this.navigationHelper.OnNavigatedTo(e); DataContext = ViewModel; AppointmentsPreview.DateTimeZone = null; } protected override void OnNavigatedFrom(NavigationEventArgs e) { this.navigationHelper.OnNavigatedFrom(e); } #endregion private void <API key>(object sender, <API key> e) { AppointmentsPreview.DateTimeZone = (sender as ListView).SelectedItem as DateTimeZone; Frame.GoBack(); } private void <API key>(object sender, <API key> e) { (DataContext as <API key>).SearchDateTimeZones((sender as TextBox).Text); } } }
// MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // This program is free software; you can redistribute it and/or modify // This program is distributed in the hope that it will be useful, but // for more details. // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace MySql.Debugger { public class MetaTrigger : IEquatable<MetaTrigger> { public string TriggerSchema { get; set; } public string Name { get; set; } public TriggerEvent Event { get; set; } public string ObjectSchema { get; set; } public string Table { get; set; } public string Source { get; set; } public TriggerActionTiming ActionTiming { get; set; } public bool Equals(MetaTrigger other) { if (other == null) return false; /* There cannot be two triggers for the same action & timing over a given table. */ return (other.ObjectSchema.Equals(this.ObjectSchema, StringComparison.<API key>)) && (other.Table.Equals(this.Table, StringComparison.InvariantCulture)) && (other.ActionTiming == this.ActionTiming) && (other.Event == this.Event); } public MetaTrigger() { } } }
<!DOCTYPE HTML PUBLIC "- <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_79) on Fri Oct 16 14:53:14 EEST 2015 --> <meta http-equiv="Content-Type" content="text/html" charset="UTF-8"> <title>Uses of Class org.tiralab.particles.Testing</title> <meta name="date" content="2015-10-16"> <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><! if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.tiralab.particles.Testing"; } </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <div class="topNav"><a name="navbar_top"> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../org/tiralab/particles/package-summary.html">Package</a></li> <li><a href="../../../../org/tiralab/particles/Testing.html" title="class in org.tiralab.particles">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../../../../overview-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../index.html?org/tiralab/particles/class-use/Testing.html" target="_top">Frames</a></li> <li><a href="Testing.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <a name="skip-navbar_top"> </a></div> <div class="header"> <h2 title="Uses of Class org.tiralab.particles.Testing" class="title">Uses of Class<br>org.tiralab.particles.Testing</h2> </div> <div class="classUseContainer">No usage of org.tiralab.particles.Testing</div> <div class="bottomNav"><a name="navbar_bottom"> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="<API key>"> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../org/tiralab/particles/package-summary.html">Package</a></li> <li><a href="../../../../org/tiralab/particles/Testing.html" title="class in org.tiralab.particles">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../../../../overview-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../index.html?org/tiralab/particles/class-use/Testing.html" target="_top">Frames</a></li> <li><a href="Testing.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <a name="skip-navbar_bottom"> </a></div> </body> </html>
jQuery(function($){$(window).resize(function(){$('.jp-jplayer').each(function(){var $$=$(this);if($$.data('player-ready')!=undefined){var ratio=Number($$.attr('data-ratio'));$$.jPlayer({size:{height:Math.floor($$.closest('.widget').outerWidth()/1.777)}});}});}) $('.jp-jplayer').each(function(){var $$=$(this);var ratio=Number($$.attr('data-ratio'));$$.jPlayer({ready:function(){$$.data('player-ready',true);$(this).jPlayer("setMedia",{m4v:$(this).attr('data-video'),poster:$(this).attr('data-poster')});if($(this).attr('data-mobile')=='true'){$(this).find('.jp-gui').hide();} else{$(this).find('.jp-gui').show();} if(Number($(this).attr('data-autoplay'))==1){$$.jPlayer("play");} $(this).jPlayer({size:{height:Math.floor($(this).closest('.widget').outerWidth()/ratio)}});},solution:"flash, html",supplied:"m4v",swfPath:$(this).attr('data-swfpath'),autohide:{restored:false,full:false},play:function(){$(this).jPlayer("pauseOthers");$(this).jPlayer('option','autohide',{restored:true,full:true,hold:2000});},size:{width:"100%",height:Math.floor($$.closest('.widget').outerWidth()/ratio)},cssSelectorAncestor:"#"+$$.closest('.jp-video').attr('id')});});});
=head1 NAME PDL::IO - An overview of the modules in the PDL::IO namespace. =head1 SYNOPSIS # At your system shell, type: perldoc PDL::IO =head1 DESCRIPTION PDL contains many modules for displaying, loading, and saving data. =over =item * Perlish or Text-Based A few IO modules provide Perl-inspired capabilities. These are PDL::IO::Dumper and PDL::IO::Storable. PDL::IO::Misc provides simpler routines for dealing with delimited files, though its capabilities are limited to tabular or at most 3-d data sets. =item * Raw Format PDL has two modules that store their data in a raw binary format; they are PDL::IO::FastRaw and PDL::IO::FlexRaw. They are fast but the files they produce will not be readable across different architectures. These two modules are so similar that they could probably be combined. =item * Data Browsing At the moment, only PDL::IO::Browser provides data browsing functionality. =item * Image Handling PDL has a handful of modules that will load images into piddles for you. They include PDL::IO::Dicom, PDL::IO::FITS, PDL::IO::GD, PDL::IO::Pic, and PDL::IO::Pnm. However, PDL::IO::FITS should also be considered something of a general data format. =item * Disk Caching Both PDL::IO::FastRaw and PDL::IO::FlexRaw provide for direct piddle-to-disk mapping, but they use PDL's underlying mmap functionality to do it, and that doesn't work for Windows. However, users of all operating systems can still use PDL::DiskCache, which can use any desired IO read/write functionality (though you may have to write a small wrapper function). =item * General Data Storage Formats PDL has a number of modules that interface general data storage libraries. They include PDL::IO::HDF and PDL::IO::NDF (the latter is now a separate CPAN module). There is a PDL::IO::IDL, though at the moment it is not distributed with PDL. PDL::IO::FITS is something of a general data format, since piddle data can be stored to a FITS file without loss. PDL::IO::FlexRaw and PDL::IO::FastRaw read and write data identical C's low-level C<write> function and PDL::IO::FlexRaw can work with FORTRAN 77 UNFORMATTED files. FlexRaw and Storable provide general data storage capabilities. Finally, PDL can read Grib (weather-data) files using the CPAN module PDL::IO::Grib. =item * Making Movies You can make an MPEG animation using PDL::IO::Pic's wmpeg function. =back Here's a brief summary of all of the modules, in alphabetical order. =head2 PDL::DiskCache The DiskCache module allows you to tie a Perl array to a collection of files on your disk, which will be loaded into and out of memory as piddles. Although the module defaults to working with FITS files, it allows you to specify your own reading and writing functions. This allows you to vastly streamline your code by hiding the unnecessary details of loading and saving files. If you find yourself writing scripts to procss many data files, especially if that data processing is not necessarily in sequential order, you should consider using PDL::DiskCache. To read more, check the L<PDL::DiskCache documentation|PDL::DiskCache>. =head2 PDL::IO::Browser The Browser module provides a text-based data browser for 2D data sets. It uses the CURSES library to do the scrolling, so if your operating system does not have the cureses library, you won't be able to install this on your machine. (Note that the package containing the header files for the CURSES library may be called C<libcurses> or possibly C<libncurses>.) PDL::IO::Browser is not installed by default because it gives trouble on Mac OS X, and not enough is known to fix the problem. If you want to enable it, edit the perldl configuration file and rebuild PDL. To learn more about editing the configuration file, see the INSTALLATION section in L<the FAQ|PDL::FAQ>. (Also, if you are familiar with CURSES on Mac, your help would be much appreciated!) To see if the module is installed on your machine (and to get more information about PDL::IO::Browser), follow L<this link|PDL::IO::Browser> or type at the system prompt: perldoc PDL::IO::Browser If you want to get more information about PDL::IO::Browser and it's not installed on your system, I'm afraid you'll have to pick out the pod from the source file, which can be found online at L<http://pdl.git.sourceforge.net/git/gitweb.cgi?p=pdl/pdl;a=blob_plain;f=IO/Browser/browser.pd;hb=HEAD>. =head2 PDL::IO::Dicom DICOM is an image format, and this module allows you to read image files with the DICOM file format. To read more, check the L<PDL::IO::Dicom documentation|PDL::IO::Dicom>. =head2 PDL::IO::Dumper Provides functionality similar to L<Data::Dumper|Data::Dumper> for piddles. L<Data::Dumper|Data::Dumper> stringifies a data structure, creating a string that can be C<eval>ed to reproduce the original data structure. It's also usually suitable for printing, to visualize the structure. To read more, check the L<PDL::IO::Dumper documentation|PDL::IO::Dumper>. See also PDL::IO::Storable for a more comprehensive structured data solution. =head2 PDL::IO::FastRaw Very simple module for quickly writing, reading, and memory-mapping piddles to/from disk. It is fast to learn and fast to use, though you may be frustrated by its lack of options. To quote from the original POD: "The binary files are in general NOT interchangeable between different architectures since the binary file is simply dumped from the memory region of the piddle. This is what makes the approach efficient." This creates two files for every piddle saved - one that stores the raw data and another that stores the header file, which indicates the dimensions of the data stored in the raw file. Even if you save 1000 different piddles with the exact same dimensions, you will still need to write out a header file for each one. You cannot store multiple piddles in one file. Note that at the time of writing, memory-mapping is not possible on Windows. For more details, see L<PDL::IO::FastRaw>. For a more flexible raw IO module, see PDL::IO::FlexRaw. =head2 PDL::IO::FITS Allows basic reading and writing of FITS files. You can read more about FITS formatted files at L<http://fits.gsfc.nasa.gov/fits_intro.html> and L<http://en.wikipedia.org/wiki/FITS>. It is an image format commonly used in Astronomy. This module may or may not be installed on your machine. To get more information, check online at L<http://pdl.sourceforge.net/PDLdocs/IO/FITS.html>. To see if the module is installed on your machine, follow L<this link|PDL::IO::FITS> or type at the system prompt: perldoc PDL::IO::FITS =head2 PDL::IO::FlexRaw Somewhat smarter module (compared to FastRaw) for reading, writing, and memory mapping piddles to disk. In addition to everything that FastRaw can do, FlexRaw can also store multiple piddles in a single file, take user-specified headers (so you can use one header file for multiple files that have identical structure), and read compressed data. However, FlexRaw cannot memory-map compressed data, and just as with FastRaw, the format will not work across multiple architectures. FlexRaw and FastRaw produce identical raw files and have essentially identical performance. Use whichever module seems to be more comfortable. I would generally recommend using FlexRaw over FastRaw, but the differences are minor for most uses. Note that at the time of writing, memory-mapping is not possible on Windows. For more details on FlexRaw, see L<PDL::IO::FlexRaw>. =head2 PDL::IO::GD GD is a library for reading, creating, and writing bitmapped images, written in C. You can read more about the C-library here: L<http: In addition to reading and writing .png and .jpeg files, GD allows you to modify the bitmap by drawing rectangles, adding text, and probably much more. The documentation can be L<found here|PDL::IO::GD>. As such, it should probably be not only considered an IO module, but a Graphics module as well. This module provides PDL bindings for the GD library, which ought not be confused with the Perl bindings. The perl bindings were developed independently and can be found at L<GD>, if you have Perl's GD bindings installed. =head2 PDL::IO::Grib A CPAN module last updated in 2000 that allows you to read Grib files. GRIB is a data format commonly used in meteorology. In the off-chance that you have it installed, you should L<read PDL::IO::Grib's documenation|PDL::IO::Grib>. =head2 PDL::IO::HDF, PDL::IO::HDF5 Provides an interface to HDF4 and HDF5 file formats, which are kinda like cross-platform binary XML files. HDF stands for B<H>eierarchicl B<D>ata B<F>ormat. HDF was originally developed at the NCSA. To read more about HDF, see L<http: distributed with PDL, and neither HDF4 nor HDF5 will be installed unless you have the associated C libraries that these modules interface. Also note that the HDF5 library on CPAN is rather old and somebody from HDF contacted the mailing list in the Fall of 2009 to develop new and better HDF5 bindings for Perl. You should look into the L<PDL::IO::HDF (4) documentation|PDL::IO::HDF> or L<PDL::IO::HDF5 documentation|PDL::IO::HDF5>, depending upon which module you have installed. =head2 PDL::IO::IDL Once upon a time, PDL had a module for reading IDL data files. Unfortunately, it cannot be distributed because the original author, Craig DeForest, signed the IDL license agreement and was unable to negotiate the administrative hurdles to get it published. However, it can be found in Sourceforge's CVS attic, and any PDL user who has not signed IDL's license agreement can fix it up and resubmit it. =head2 PDL::IO::Misc Provides mostly text-based IO routines. Data input and output is restricted mostly to tabular (i.e. two-dimensional) data sets, though limited support is provided for 3d data sets. Alternative text-based modules support higher dimensions, such as PDL::IO::Dumper and PDL::IO::Storable. Check the L<PDL::IO::Misc documentation|PDL::IO::Misc> for more details. =head2 PDL::IO::NDF Starlink developed a file format for N-Dimensional data Files, which it cleverly dubbed NDF. If you work with these files, you're in luck! Check the L<PDL::IO::NDF documentation|PDL::IO::NDF> for more details. =head2 PDL::IO::Pic Provides reading/writing of images to/from piddles, as well as creating MPEG animations! The module uses the netpbm library, so you will need that on your machine in order for this to work. To read more, see the L<PDL::IO::Pic documentation|PDL::IO::Pic>. Also look into the next module, as well as PDL::IO::GD. =head2 PDL::IO::Pnm Provides methods for reading and writing pnm files (of which pbm is but one). Check the L<PDL::IO::Pnm documentation|PDL::IO::Pnm> for more details. Also check out the previous module and PDL::IO::GD. =head2 PDL::IO::Storable Implements the relevant methods to be able to store and retrieve piddles via Storable. True, you can use many methods to save a single piddle. In contrast, this module is particularly useful if you need to save a complex Perl structure that contain piddles, such as an array of hashes, each of which contains piddles. Check the L<PDL::IO::Storable documentation|PDL::IO::Storable> for more details. See also PDL::IO::Dumper for an alternative stringifier. =head1 COPYRIGHT Copyright 2010 David Mertens (dcmertens.perl@gmail.com). You can distribute and/or modify this document under the same terms as the current Perl license. See: http:
Imports dRemote.Forms.OptionsPages Imports dRemote.App.Runtime Imports dRemote.My Imports WeifenLuo.WinFormsUI.Docking Namespace Forms Partial Public Class OptionsForm 'Inherits DockContent #Region "Constructors" Public Sub New() ' This call is required by the designer. InitializeComponent() ' Add any initialization after the InitializeComponent() call. FontOverride(Me) _pages.Add(New StartupExitPage, New PageInfo) _pages.Add(New AppearancePage, New PageInfo) _pages.Add(New TabsPanelsPage, New PageInfo) _pages.Add(New ConnectionsPage, New PageInfo) _pages.Add(New SqlServerPage, New PageInfo) _pages.Add(New UpdatesPage, New PageInfo) _pages.Add(New ThemePage, New PageInfo) _pages.Add(New AdvancedPage, New PageInfo) _startPage = GetPageFromType(GetType(StartupExitPage)) _pageIconImageList.ColorDepth = ColorDepth.Depth32Bit PageListView.LargeImageList = _pageIconImageList End Sub #End Region #Region "Public Methods" Public Overloads Function ShowDialog(ByVal ownerWindow As IWin32Window, ByVal pageType As Type) As DialogResult _startPage = GetPageFromType(pageType) Return ShowDialog(ownerWindow) End Function #End Region #Region "Private Fields" Private ReadOnly _pages As New Dictionary(Of OptionsPage, PageInfo) Private ReadOnly _pageIconImageList As New ImageList Private _startPage As OptionsPage Private _selectedPage As OptionsPage = Nothing #End Region #Region "Private Methods" #Region "Event Handlers" Private Sub OptionsForm_Load(sender As System.Object, e As EventArgs) Handles MyBase.Load For Each keyValuePair As KeyValuePair(Of OptionsPage, PageInfo) In _pages Dim page As OptionsPage = keyValuePair.Key Dim pageInfo As PageInfo = keyValuePair.Value _pageIconImageList.Images.Add(pageInfo.IconKey, page.PageIcon) pageInfo.ListViewItem = PageListView.Items.Add(page.PageName, pageInfo.IconKey) Next ApplyLanguage() LoadSettings() ShowPage(_startPage) End Sub Private Sub <API key>(sender As System.Object, e As <API key>) Handles MyBase.FormClosing If DialogResult = DialogResult.OK Then SaveSettings() Else RevertSettings() End If End Sub Private Sub <API key>(sender As System.Object, e As <API key>) Handles PageListView.<API key> If Not e.IsSelected Then Return If _pages.Count < 1 Then Return Dim page As OptionsPage = <API key>(e.Item) If _selectedPage IsNot page Then ShowPage(page) End If SelectNextControl(PageListView, True, True, True, True) End Sub Private Sub <API key>(sender As System.Object, e As MouseEventArgs) Handles PageListView.MouseUp If PageListView.SelectedIndices.Count = 0 Then Dim pageInfo As PageInfo = _pages(_selectedPage) pageInfo.ListViewItem.Selected = True End If SelectNextControl(PageListView, True, True, True, True) End Sub Private Sub OkButton_Click(sender As System.Object, e As EventArgs) Handles OkButton.Click DialogResult = DialogResult.OK Close() End Sub Private Sub <API key>(sender As System.Object, e As EventArgs) Handles CancelButtonControl.Click DialogResult = DialogResult.Cancel Close() End Sub #End Region Private Sub ApplyLanguage() Text = Language.strMenuOptions OkButton.Text = Language.strButtonOK CancelButtonControl.Text = Language.strButtonCancel For Each page As OptionsPage In _pages.Keys Try page.ApplyLanguage() Catch ex As Exception MessageCollector.AddExceptionMessage(String.Format("OptionsPage.ApplyLanguage() failed for page {0}.", page.PageName), ex, , True) End Try Next End Sub Private Sub LoadSettings() For Each page As OptionsPage In _pages.Keys Try page.LoadSettings() Catch ex As Exception MessageCollector.AddExceptionMessage(String.Format("OptionsPage.LoadSettings() failed for page {0}.", page.PageName), ex, , True) End Try Next End Sub Private Sub SaveSettings() For Each page As OptionsPage In _pages.Keys Try page.SaveSettings() Catch ex As Exception MessageCollector.AddExceptionMessage(String.Format("OptionsPage.SaveSettings() failed for page {0}.", page.PageName), ex, , True) End Try Next End Sub Private Sub RevertSettings() For Each page As OptionsPage In _pages.Keys Try page.RevertSettings() Catch ex As Exception MessageCollector.AddExceptionMessage(String.Format("OptionsPage.RevertSettings() failed for page {0}.", page.PageName), ex, , True) End Try Next End Sub Private Function GetPageFromType(ByVal pageType As Type) As OptionsPage For Each page As OptionsPage In _pages.Keys If page.GetType() Is pageType Then Return page Next Return Nothing End Function Private Function <API key>(ByVal listViewItem As ListViewItem) As OptionsPage For Each keyValuePair As KeyValuePair(Of OptionsPage, PageInfo) In _pages Dim page As OptionsPage = keyValuePair.Key Dim pageInfo As PageInfo = keyValuePair.Value If pageInfo.ListViewItem Is listViewItem Then Return page Next Return Nothing End Function Private Sub ShowPage(ByVal newPage As OptionsPage) If _selectedPage IsNot Nothing Then Dim oldPage As OptionsPage = _selectedPage oldPage.Visible = False If _pages.ContainsKey(oldPage) Then Dim oldPageInfo As PageInfo = _pages(oldPage) oldPageInfo.ListViewItem.Selected = False End If End If _selectedPage = newPage If newPage IsNot Nothing Then newPage.Parent = PagePanel newPage.Dock = DockStyle.Fill newPage.Visible = True If _pages.ContainsKey(newPage) Then Dim newPageInfo As PageInfo = _pages(newPage) newPageInfo.ListViewItem.Selected = True End If End If End Sub #End Region #Region "Private Classes" Private Class PageInfo Public Property IconKey As String Public Property ListViewItem As ListViewItem Public Sub New() IconKey = Guid.NewGuid.ToString() End Sub End Class #End Region End Class End Namespace
<?php use mvc\interfaces\<API key>; use mvc\controller\controllerClass; use mvc\config\configClass as config; use mvc\request\requestClass as request; use mvc\routing\routingClass as routing; use mvc\session\sessionClass as session; use mvc\i18n\i18nClass as i18n; class <API key> extends controllerClass implements <API key> { public function execute() { try { $where = null; if(request::getInstance()->hasPost('report')){ $report = request::getInstance()->getPost('report'); //validar if(isset($report['ubicacion']) and $report['ubicacion'] !== null and $report['ubicacion'] !== ""){ $where[] = '(' . loteTableClass::getNameField(loteTableClass::UBICACION) . ' LIKE ' . '\'' . $report['ubicacion'] . '%\' ' . 'OR ' . loteTableClass::getNameField(loteTableClass::UBICACION) . ' LIKE ' . '\'%' . $report['ubicacion'] . '%\' ' . 'OR ' . loteTableClass::getNameField(loteTableClass::UBICACION) . ' LIKE ' . '\'%' . $report['ubicacion'].'\') '; }//cierre del filtro ubicacion if((isset($report['tamanoIni']) and $report['tamanoIni'] !== null and $report['tamanoIni'] !== "") and (isset($report['tamanoFin']) and $report['tamanoFin'] !== null and $report['tamanoFin'] !== "" )){ $where[loteTableClass::TAMANO] = array( $report['tamanoIni'], $report['tamanoFin'] ); }//cierre del filtro tamanoIni y tamanoFin if((isset($report['fechaIni']) and $report['fechaIni'] !== null and $report['fechaIni'] !== "") and (isset($report['fechaFin']) and $report['fechaFin'] !== null and $report['fechaFin'] !== "" )){ $where[loteTableClass::CREATED_AT] = array( date(config::getFormatTimestamp(), strtotime($report['fechaIni'].' 00:00:00')), date(config::getFormatTimestamp(), strtotime($report['fechaFin'].' 23:59:59')) ); } //cierre del filtro fechaIni y fechaFin if((isset($report['fechaSI']) and $report['fechaSI'] !== null and $report['fechaSI'] !== "") and (isset($report['fechaSF']) and $report['fechaSF'] !== null and $report['fechaSF'] !== "" )){ $where[loteTableClass::<API key>] = array( date(config::getFormatTimestamp(), strtotime($report['fechaSI'].' 00:00:00')), date(config::getFormatTimestamp(), strtotime($report['fechaSF'].' 23:59:59')) ); } //cierre del filtro fechaSI y fechaSF if(isset($report['ciudad']) and $report['ciudad'] !== null and $report['ciudad'] !== ""){ $where[loteTableClass::ID_CIUDAD] = $report['ciudad']; }//cierre del filtro ciudad }//cierre del POST report $this->mensaje = 'Informacion de Lote'; $fields = array( loteTableClass::ID, loteTableClass::UBICACION, loteTableClass::TAMANO, loteTableClass::DESCRIPCION, loteTableClass::ID_CIUDAD, loteTableClass::NUMERO_PLANTULAS, loteTableClass::<API key>, loteTableClass::FECHA_RIEGO, loteTableClass::PRODUCTO_INSUMO_ID, loteTableClass::CREATED_AT, loteTableClass::UPDATED_AT ); $orderBy = array( loteTableClass::ID ); $this->objLote = loteTableClass::getAll($fields, true, $orderBy, 'ASC',null,null,$where); $fields = array( <API key>::ID, <API key>::DESCRIPCION ); $orderBy = array( <API key>::DESCRIPCION ); $this->objLUD = <API key>::getAll($fields, false, $orderBy, 'ASC'); $fields = array( ciudadTableClass::ID, ciudadTableClass::NOMBRE_CIUDAD ); $orderBy = array( ciudadTableClass::NOMBRE_CIUDAD ); $this->objLC = ciudadTableClass::getAll($fields, false, $orderBy, 'ASC'); $fields = array( <API key>::ID, <API key>::DESCRIPCION ); $orderBy = array( <API key>::DESCRIPCION ); $this->objLPI = <API key>::getAll($fields, true, $orderBy, 'ASC'); $this->defineView('indexLote', 'lote', session::getInstance()->getFormatOutput()); }//cierre del try catch (PDOException $exc) { echo $exc->getMessage(); echo '<br>'; echo '<pre>'; print_r($exc->getTrace()); echo '</pre>'; }//cierre del catch }//cierre de la funcion execute }//cierre de la clase
<div class="mbt-book-buybuttons"> <?php mbt_the_buybuttons(true); ?> <div style="clear:both;"></div> </div>
from Screen import Screen from ServiceScan import ServiceScan from Components.config import config, ConfigSubsection, ConfigSelection, ConfigYesNo, ConfigInteger, getConfigListEntry, ConfigSlider, ConfigEnableDisable from Components.ActionMap import NumberActionMap, ActionMap from Components.ConfigList import ConfigListScreen from Components.NimManager import nimmanager, getConfigSatlist from Components.Label import Label from Components.Sources.StaticText import StaticText from Tools.HardwareInfo import HardwareInfo from Screens.InfoBar import InfoBar from Screens.MessageBox import MessageBox from enigma import eTimer, <API key>, eComponentScan, <API key>, <API key>, <API key>, eDVBResourceManager from Components.Converter.ChannelNumbers import channelnumbers from boxbranding import getMachineBrand def buildTerTransponder(frequency, inversion=2, bandwidth = 7000000, fechigh = 6, feclow = 6, modulation = 2, transmission = 2, guard = 4, hierarchy = 4, system = 0, plpid = 0): # print "freq", frequency, "inv", inversion, "bw", bandwidth, "fech", fechigh, "fecl", feclow, "mod", modulation, "tm", transmission, "guard", guard, "hierarchy", hierarchy parm = <API key>() parm.frequency = frequency parm.inversion = inversion parm.bandwidth = bandwidth parm.code_rate_HP = fechigh parm.code_rate_LP = feclow parm.modulation = modulation parm.transmission_mode = transmission parm.guard_interval = guard parm.hierarchy = hierarchy parm.system = system parm.plpid = plpid return parm def <API key>(tlist, pos): list = nimmanager.getTransponders(pos) for x in list: if x[0] == 0: #SAT parm = <API key>() parm.frequency = x[1] parm.symbol_rate = x[2] parm.polarisation = x[3] parm.fec = x[4] parm.inversion = x[7] parm.orbital_position = pos parm.system = x[5] parm.modulation = x[6] parm.rolloff = x[8] parm.pilot = x[9] tlist.append(parm) def <API key>(tlist, nim): list = nimmanager.<API key>(nim) for x in list: if x[0] == 1: #CABLE parm = <API key>() parm.frequency = x[1] parm.symbol_rate = x[2] parm.modulation = x[3] parm.fec_inner = x[4] parm.inversion = x[5] parm.system = x[6] tlist.append(parm) def <API key>(tlist, region, skip_t2 = False): list = nimmanager.<API key>(region) #self.transponders[self.parsedTer].append((2,freq,bw,const,crh,crl,guard,transm,hierarchy,inv)) #def buildTerTransponder(frequency, inversion = 2, bandwidth = 3, fechigh = 6, feclow = 6, #modulation = 2, transmission = 2, guard = 4, hierarchy = 4): for x in list: if x[0] == 2: #TERRESTRIAL if skip_t2 and x[10] == <API key>.System_DVB_T2: # Should be searching on <API key>. continue parm = buildTerTransponder(x[1], x[9], x[2], x[4], x[5], x[3], x[7], x[6], x[8], x[10], x[11]) tlist.append(parm) cable_bands = { "DVBC_BAND_EU_VHF_I" : 1 << 0, "DVBC_BAND_EU_MID" : 1 << 1, "<API key>" : 1 << 2, "DVBC_BAND_EU_SUPER" : 1 << 3, "DVBC_BAND_EU_HYPER" : 1 << 4, "DVBC_BAND_EU_UHF_IV" : 1 << 5, "DVBC_BAND_EU_UHF_V" : 1 << 6, "DVBC_BAND_US_LO" : 1 << 7, "DVBC_BAND_US_MID" : 1 << 8, "DVBC_BAND_US_HI" : 1 << 9, "DVBC_BAND_US_SUPER" : 1 << 10, "DVBC_BAND_US_HYPER" : 1 << 11, } <API key> = { 'SSH108' : 'ssh108', 'TT3L10' : 'tt3l10', 'TURBO' : 'vuplus_turbo_c' } <API key> = { 'SSH108' : 'ssh108_t2_scan', 'TT3L10' : 'tt3l10_t2_scan', 'TURBO' : 'vuplus_turbo_t' } def GetDeviceId(filter, nim_idx): tuners={} device_id = 0 socket_id = 0 for nim in nimmanager.nim_slots: name_token = nim.description.split(' ') name = name_token[-1][4:-1] if name == filter: if socket_id == nim_idx: break if device_id: device_id = 0 else: device_id = 1 socket_id += 1 return device_id class <API key>: # def <API key>(self, tlist): # pass # def <API key>(self): # pass def __init__(self): pass def tryGetRawFrontend(self, feid): res_mgr = eDVBResourceManager.getInstance() if res_mgr: raw_channel = res_mgr.allocateRawChannel(self.feid) if raw_channel: frontend = raw_channel.getFrontend() if frontend: frontend.closeFrontend() # immediate close... del frontend del raw_channel return True return False def <API key>(self, *val): print "<API key>, val", val self.<API key>.appClosed.remove(self.<API key>) self.<API key>.dataAvail.remove(self.<API key>) if val and len(val): if val[0]: self.<API key>(self.__tlist) else: self.<API key>.sendCtrlC() self.<API key>(None) self.<API key> = None self.<API key> = None self.__tlist = None self.<API key>() def <API key>(self, retval): print "<API key> finished", retval self.<API key>.close(True) def <API key>(self, str): #prepend any remaining data from the previous call str = self.remainingdata + str #split in lines lines = str.split('\n') #'str' should end with '\n', so when splitting, the last line should be empty. If this is not the case, we received an incomplete line if len(lines[-1]): #remember this data for next time self.remainingdata = lines[-1] lines = lines[0:-1] else: self.remainingdata = "" for line in lines: data = line.split() if len(data): if data[0] == 'OK': print str parm = <API key>() qam = { "QAM16" : parm.Modulation_QAM16, "QAM32" : parm.Modulation_QAM32, "QAM64" : parm.Modulation_QAM64, "QAM128" : parm.Modulation_QAM128, "QAM256" : parm.Modulation_QAM256 } inv = { "INVERSION_OFF" : parm.Inversion_Off, "INVERSION_ON" : parm.Inversion_On, "INVERSION_AUTO" : parm.Inversion_Unknown } fec = { "FEC_AUTO" : parm.FEC_Auto, "FEC_1_2" : parm.FEC_1_2, "FEC_2_3" : parm.FEC_2_3, "FEC_3_4" : parm.FEC_3_4, "FEC_5_6" : parm.FEC_5_6, "FEC_7_8" : parm.FEC_7_8, "FEC_8_9" : parm.FEC_8_9, "FEC_3_5" : parm.FEC_3_5, "FEC_4_5" : parm.FEC_4_5, "FEC_9_10" : parm.FEC_9_10, "FEC_NONE" : parm.FEC_None } parm.frequency = int(data[1]) parm.symbol_rate = int(data[2]) parm.fec_inner = fec[data[3]] parm.modulation = qam[data[4]] parm.inversion = inv[data[5]] self.__tlist.append(parm) tmpstr = _("Try to find used transponders in cable network.. please wait...") tmpstr += "\n\n" tmpstr += data[1].isdigit() and "%s MHz " % (int(data[1]) / 1000.) or data[1] tmpstr += data[0] self.<API key>["text"].setText(tmpstr) def <API key>(self, nim_idx): def GetCommand(nim_idx): global <API key> try: nim_name = nimmanager.getNimName(nim_idx) if nim_name is not None and nim_name != "": device_id = "" nim_name = nim_name.split(' ')[-1][4:-1] if nim_name == 'TT3L10': try: device_id = GetDeviceId('TT3L10', nim_idx) device_id = "--device=%s" % (device_id) except Exception, err: print "GetCommand ->", err device_id = "--device=0" # print nim_idx, nim_name, <API key>[nim_name], device_id command = "%s %s" % (<API key>[nim_name], device_id) return command except Exception, err: print "GetCommand ->", err return "tda1002x" if not self.tryGetRawFrontend(nim_idx): self.session.nav.stopService() if not self.tryGetRawFrontend(nim_idx): if self.session.pipshown: self.session.infobar.showPiP() if not self.tryGetRawFrontend(nim_idx): self.<API key>() return self.__tlist = [ ] self.remainingdata = "" self.<API key> = <API key>() self.<API key>.appClosed.append(self.<API key>) self.<API key>.dataAvail.append(self.<API key>) cableConfig = config.Nims[nim_idx].cable tunername = nimmanager.getNimName(nim_idx) try: bus = nimmanager.getI2CDevice(nim_idx) if bus is None: print "ERROR: could not get I2C device for nim", nim_idx, "for cable transponder search" bus = 2 except: # older API if nim_idx < 2: if HardwareInfo().get_device_name() == "dm500hd": bus = 2 else: bus = nim_idx else: if nim_idx == 2: bus = 2 # DM8000 first nim is /dev/i2c/2 else: bus = 4 # DM8000 second num is /dev/i2c/4 bin_name = None if tunername == "CXD1981": bin_name = "CXD1981" cmd = "cxd1978 --init --scan --verbose --wakeup --inv 2 --bus %d" % bus elif tunername.startswith("Sundtek"): bin_name = "mediaclient" cmd = "/opt/bin/mediaclient --blindscan %d" % nim_idx else: bin_name = GetCommand(nim_idx) cmd = "%(BIN_NAME)s --init --scan --verbose --wakeup --inv 2 --bus %(BUS)d" % {'BIN_NAME':bin_name, 'BUS':bus} if cableConfig.scan_type.value == "bands": cmd += " --scan-bands " bands = 0 if cableConfig.scan_band_EU_VHF_I.value: bands |= cable_bands["DVBC_BAND_EU_VHF_I"] if cableConfig.scan_band_EU_MID.value: bands |= cable_bands["DVBC_BAND_EU_MID"] if cableConfig.<API key>.value: bands |= cable_bands["<API key>"] if cableConfig.scan_band_EU_UHF_IV.value: bands |= cable_bands["DVBC_BAND_EU_UHF_IV"] if cableConfig.scan_band_EU_UHF_V.value: bands |= cable_bands["DVBC_BAND_EU_UHF_V"] if cableConfig.scan_band_EU_SUPER.value: bands |= cable_bands["DVBC_BAND_EU_SUPER"] if cableConfig.scan_band_EU_HYPER.value: bands |= cable_bands["DVBC_BAND_EU_HYPER"] if cableConfig.scan_band_US_LOW.value: bands |= cable_bands["DVBC_BAND_US_LO"] if cableConfig.scan_band_US_MID.value: bands |= cable_bands["DVBC_BAND_US_MID"] if cableConfig.scan_band_US_HIGH.value: bands |= cable_bands["DVBC_BAND_US_HI"] if cableConfig.scan_band_US_SUPER.value: bands |= cable_bands["DVBC_BAND_US_SUPER"] if cableConfig.scan_band_US_HYPER.value: bands |= cable_bands["DVBC_BAND_US_HYPER"] cmd += str(bands) else: cmd += " --scan-stepsize " cmd += str(cableConfig.<API key>.value) if cableConfig.scan_mod_qam16.value: cmd += " --mod 16" if cableConfig.scan_mod_qam32.value: cmd += " --mod 32" if cableConfig.scan_mod_qam64.value: cmd += " --mod 64" if cableConfig.scan_mod_qam128.value: cmd += " --mod 128" if cableConfig.scan_mod_qam256.value: cmd += " --mod 256" if cableConfig.scan_sr_6900.value: cmd += " --sr 6900000" if cableConfig.scan_sr_6875.value: cmd += " --sr 6875000" if cableConfig.scan_sr_ext1.value > 450: cmd += " --sr " cmd += str(cableConfig.scan_sr_ext1.value) cmd += "000" if cableConfig.scan_sr_ext2.value > 450: cmd += " --sr " cmd += str(cableConfig.scan_sr_ext2.value) cmd += "000" print bin_name, " CMD is", cmd self.<API key>.execute(cmd) tmpstr = _("Try to find used transponders in cable network.. please wait...") tmpstr += "\n\n..." self.<API key> = self.session.openWithCallback(self.<API key>, MessageBox, tmpstr, MessageBox.TYPE_INFO) class <API key>: # def <API key>(self, tlist): # pass # def <API key>(self): # pass def <API key>(self, *val): print "<API key>, val", val self.<API key>.appClosed.remove(self.<API key>) self.<API key>.dataAvail.remove(self.<API key>) if val and len(val): if val[0]: self.<API key>(self.__tlist) else: self.<API key>.sendCtrlC() self.<API key>(None) self.<API key> = None self.<API key> = None self.__tlist = None self.<API key>() def <API key>(self, retval): self.<API key>() opt = self.<API key>() if opt is None: print "<API key> finished", retval self.<API key>.close(True) else: (freq, bandWidth) = opt self.<API key>(freq, bandWidth) def <API key>(self, str): self.<API key> += str def <API key>(self): print self.<API key> data = self.<API key>.split() if len(data): # print "[<API key>] data : ", data if data[0] == 'OK': # DVB-T : OK frequency bandwidth delivery system -1 # DVB-T2 : OK frequency bandwidth delivery system number_of_plp plp_id0:plp_type0 if data[3] == 1: # DVB-T parm = <API key>() parm.frequency = int(data[1]) parm.bandwidth = int(data[2]) parm.inversion = parm.Inversion_Unknown parm.code_rate_HP = parm.FEC_Auto parm.code_rate_LP = parm.FEC_Auto parm.modulation = parm.Modulation_Auto parm.transmission_mode = parm.<API key> parm.guard_interval = parm.GuardInterval_Auto parm.hierarchy = parm.Hierarchy_Auto parm.system = parm.System_DVB_T parm.plpid = 0 self.__tlist.append(parm) else: plp_list = data[5:] plp_num = int(data[4]) if len(plp_list) > plp_num: plp_list = plp_list[:plp_num] for plp in plp_list: (plp_id, plp_type) = plp.split(':') if plp_type == '0': # common PLP: continue parm = <API key>() parm.frequency = int(data[1]) parm.bandwidth = self.<API key>(int(data[2])) parm.inversion = parm.Inversion_Unknown parm.code_rate_HP = parm.FEC_Auto parm.code_rate_LP = parm.FEC_Auto parm.modulation = parm.Modulation_Auto parm.transmission_mode = parm.<API key> parm.guard_interval = parm.GuardInterval_Auto parm.hierarchy = parm.Hierarchy_Auto parm.system = parm.System_DVB_T2 parm.plpid = int(plp_id) self.__tlist.append(parm) tmpstr = _("Try to find used Transponders in terrestrial network.. please wait...") tmpstr += "\n\n" tmpstr += data[1][:-3] tmpstr += " kHz " tmpstr += data[0] self.<API key>["text"].setText(tmpstr) def <API key>(self, searchList, region): tpList = nimmanager.<API key>(region) for x in tpList: if x[0] == 2: #TERRESTRIAL freq = x[1] # frequency bandWidth = self.<API key>(x[2]) # bandWidth parm = (freq, bandWidth) searchList.append(parm) def <API key>(self, _bandWidth): bandWidth = { <API key>.Bandwidth_8MHz : 8000000, <API key>.Bandwidth_7MHz : 7000000, <API key>.Bandwidth_6MHz : 6000000, <API key>.Bandwidth_5MHz : 5000000, <API key>.Bandwidth_1_712MHz : 1712000, <API key>.Bandwidth_10MHz : 10000000, }.get(_bandWidth, 8000000) return bandWidth def <API key>(self, _bandWidth): bandWidth = { 8000000 : <API key>.Bandwidth_8MHz, 7000000 : <API key>.Bandwidth_7MHz, 6000000 : <API key>.Bandwidth_6MHz, 5000000 : <API key>.Bandwidth_5MHz, 1712000 : <API key>.Bandwidth_1_712MHz, 10000000 : <API key>.Bandwidth_10MHz, }.get(_bandWidth, <API key>.Bandwidth_8MHz) return bandWidth def <API key>(self): if len(self.<API key>) > 0: return self.<API key>.pop(0) else: return None def <API key>(self, nim_idx): global <API key> try: nim_name = nimmanager.getNimName(nim_idx) if nim_name is not None and nim_name != "": device_id = "" nim_name = nim_name.split(' ')[-1][4:-1] if nim_name == 'TT3L10': try: device_id = GetDeviceId('TT3L10', nim_idx) device_id = "--device %s" % (device_id) except Exception, err: print "<API key> ->", err device_id = "--device 0" # print nim_idx, nim_name, <API key>[nim_name], device_id command = "%s %s" % (<API key>[nim_name], device_id) return command except Exception, err: print "<API key> ->", err return "" def <API key>(self, nim_idx, region): if not self.tryGetRawFrontend(nim_idx): self.session.nav.stopService() if not self.tryGetRawFrontend(nim_idx): if self.session.pipshown: # try to disable pip self.session.pipshown = False del self.session.pip if not self.tryGetRawFrontend(nim_idx): self.<API key>() return self.__tlist = [ ] self.<API key> = <API key>() self.<API key>.appClosed.append(self.<API key>) self.<API key>.dataAvail.append(self.<API key>) self.<API key> = self.<API key>(nim_idx) self.<API key> = nimmanager.getI2CDevice(nim_idx) if self.<API key> is None: # print "ERROR: could not get I2C device for nim", nim_idx, "for terrestrial transponder search" self.<API key> = 2 self.<API key> = [] self.<API key>(self.<API key> ,region) (freq, bandWidth) = self.<API key>() self.<API key>(freq, bandWidth) tmpstr = _("Try to find used transponders in terrestrial network.. please wait...") tmpstr += "\n\n..." self.<API key> = self.session.openWithCallback(self.<API key>, MessageBox, tmpstr, MessageBox.TYPE_INFO) def <API key>(self, freq, bandWidth): self.<API key> = "" cmd = "%s --freq %d --bw %d --bus %d --ds 2" % (self.<API key>, freq, bandWidth, self.<API key>) print "SCAN CMD : ",cmd self.<API key>.execute(cmd) class ScanSetup(ConfigListScreen, Screen, <API key>, <API key>): def __init__(self, session): Screen.__init__(self, session) Screen.setTitle(self, _("Manual Scan")) self.finished_cb = None self.updateSatList() self.service = session.nav.getCurrentService() self.feinfo = None self.networkid = 0 frontendData = None if self.service is not None: self.feinfo = self.service.frontendInfo() frontendData = self.feinfo and self.feinfo.getAll(True) self.ter_channel_input = False self.ter_tnumber = None self.createConfig(frontendData) del self.feinfo del self.service self.session.postScanService = session.nav.<API key>() self["key_red"] = StaticText(_("Close")) self["key_green"] = StaticText(_("Scan")) self["actions"] = NumberActionMap(["SetupActions", "MenuActions", "ColorActions"], { "ok": self.keyGo, "save": self.keyGo, "cancel": self.keyCancel, "red": self.keyCancel, "green": self.keyGo, "menu": self.doCloseRecursive, }, -2) self.statusTimer = eTimer() self.statusTimer.callback.append(self.updateStatus) #self.statusTimer.start(5000, True) self.list = [] ConfigListScreen.__init__(self, self.list) self["header"] = Label(_("Manual Scan")) if not self.scan_nims.value == "": self.createSetup() self["introduction"] = Label(_("Press OK to start the scan")) else: self["introduction"] = Label(_("Nothing to scan!\nPlease setup your tuner settings before you start a service scan.")) def runAsync(self, finished_cb): self.finished_cb = finished_cb self.keyGo() def updateSatList(self): self.satList = [] for slot in nimmanager.nim_slots: if slot.isCompatible("DVB-S"): self.satList.append(nimmanager.getSatListForNim(slot.slot)) else: self.satList.append(None) def createSetup(self): self.list = [] self.multiscanlist = [] index_to_scan = int(self.scan_nims.value) print "ID: ", index_to_scan self.tunerEntry = getConfigListEntry(_("Tuner"), self.scan_nims) self.list.append(self.tunerEntry) if self.scan_nims == [ ]: return self.typeOfScanEntry = None self.typeOfInputEntry = None self.systemEntry = None self.modulationEntry = None self.preDefSatList = None self.<API key> = None self.<API key> = None nim = nimmanager.nim_slots[index_to_scan] if nim.isCompatible("DVB-S"): self.typeOfScanEntry = getConfigListEntry(_("Type of scan"), self.scan_type) self.list.append(self.typeOfScanEntry) elif nim.isCompatible("DVB-C"): if config.Nims[index_to_scan].cable.scan_type.value != "provider": # only show predefined transponder if in provider mode if self.scan_typecable.value == "<API key>": self.scan_typecable.value = self.cable_toggle[self.last_scan_typecable] self.last_scan_typecable = self.scan_typecable.value self.typeOfScanEntry = getConfigListEntry(_("Type of scan"), self.scan_typecable) self.list.append(self.typeOfScanEntry) elif nim.isCompatible("DVB-T"): self.typeOfScanEntry = getConfigListEntry(_("Type of scan"), self.<API key>) self.list.append(self.typeOfScanEntry) if self.<API key>.value == "single_transponder": self.typeOfInputEntry = getConfigListEntry(_("Use frequency or channel"), self.scan_input_as) if self.ter_channel_input: self.list.append(self.typeOfInputEntry) else: self.scan_input_as.value = self.scan_input_as.choices[0] self.scan_networkScan.value = False if nim.isCompatible("DVB-S"): if self.scan_type.value == "single_transponder": self.updateSatList() if nim.isCompatible("DVB-S2"): self.systemEntry = getConfigListEntry(_('System'), self.scan_sat.system) self.list.append(self.systemEntry) else: # downgrade to dvb-s, in case a -s2 config was active self.scan_sat.system.value = <API key>.System_DVB_S self.list.append(getConfigListEntry(_('Satellite'), self.scan_satselection[index_to_scan])) self.list.append(getConfigListEntry(_('Frequency'), self.scan_sat.frequency)) self.list.append(getConfigListEntry(_('Inversion'), self.scan_sat.inversion)) self.list.append(getConfigListEntry(_('Symbol rate'), self.scan_sat.symbolrate)) self.list.append(getConfigListEntry(_('Polarization'), self.scan_sat.polarization)) if self.scan_sat.system.value == <API key>.System_DVB_S: self.list.append(getConfigListEntry(_("FEC"), self.scan_sat.fec)) elif self.scan_sat.system.value == <API key>.System_DVB_S2: self.list.append(getConfigListEntry(_("FEC"), self.scan_sat.fec_s2)) self.modulationEntry = getConfigListEntry(_('Modulation'), self.scan_sat.modulation) self.list.append(self.modulationEntry) self.list.append(getConfigListEntry(_('Roll-off'), self.scan_sat.rolloff)) self.list.append(getConfigListEntry(_('Pilot'), self.scan_sat.pilot)) elif self.scan_type.value == "<API key>" and self.satList[index_to_scan]: self.updateSatList() self.preDefSatList = getConfigListEntry(_('Satellite'), self.scan_satselection[index_to_scan]) self.list.append(self.preDefSatList) sat = self.satList[index_to_scan][self.scan_satselection[index_to_scan].index] self.<API key>(sat[0]) self.list.append(getConfigListEntry(_('Transponder'), self.preDefTransponders)) elif self.scan_type.value == "single_satellite": self.updateSatList() print self.scan_satselection[index_to_scan] self.list.append(getConfigListEntry(_("Satellite"), self.scan_satselection[index_to_scan])) self.scan_networkScan.value = True elif "multisat" in self.scan_type.value: tlist = [] SatList = nimmanager.getSatListForNim(index_to_scan) for x in SatList: if self.Satexists(tlist, x[0]) == 0: tlist.append(x[0]) sat = ConfigEnableDisable(default = "_yes" in self.scan_type.value and True or False) configEntry = getConfigListEntry(nimmanager.getSatDescription(x[0]), sat) self.list.append(configEntry) self.multiscanlist.append((x[0], sat)) self.scan_networkScan.value = True elif nim.isCompatible("DVB-C"): if self.scan_typecable.value == "single_transponder": self.list.append(getConfigListEntry(_("Frequency"), self.scan_cab.frequency)) self.list.append(getConfigListEntry(_("Inversion"), self.scan_cab.inversion)) self.list.append(getConfigListEntry(_("Symbol rate"), self.scan_cab.symbolrate)) self.list.append(getConfigListEntry(_("Modulation"), self.scan_cab.modulation)) self.list.append(getConfigListEntry(_("FEC"), self.scan_cab.fec)) elif self.scan_typecable.value == "<API key>": self.<API key>() self.list.append(getConfigListEntry(_('Transponder'), self.CableTransponders)) if config.Nims[index_to_scan].cable.scan_networkid.value: self.networkid = config.Nims[index_to_scan].cable.scan_networkid.value self.scan_networkScan.value = True elif nim.isCompatible("DVB-T"): if self.<API key>.value == "single_transponder": if nim.isCompatible("DVB-T2"): self.systemEntry = getConfigListEntry(_('System'), self.scan_ter.system) self.list.append(self.systemEntry) else: self.scan_ter.system.value = <API key>.System_DVB_T if self.ter_channel_input and self.scan_input_as.value == "channel": channel = channelnumbers.getChannelNumber(self.scan_ter.frequency.value*1000, self.ter_tnumber) if channel: self.scan_ter.channel.value = int(channel.replace("+","").replace("-","")) self.list.append(getConfigListEntry(_("Channel"), self.scan_ter.channel)) else: prev_val = self.scan_ter.frequency.value self.scan_ter.frequency.value = channelnumbers.channel2frequency(self.scan_ter.channel.value, self.ter_tnumber)/1000 if self.scan_ter.frequency.value == 474000: self.scan_ter.frequency.value = prev_val self.list.append(getConfigListEntry(_("Frequency"), self.scan_ter.frequency)) self.list.append(getConfigListEntry(_("Inversion"), self.scan_ter.inversion)) self.list.append(getConfigListEntry(_("Bandwidth"), self.scan_ter.bandwidth)) self.list.append(getConfigListEntry(_("Code rate HP"), self.scan_ter.fechigh)) self.list.append(getConfigListEntry(_("Code rate LP"), self.scan_ter.feclow)) self.list.append(getConfigListEntry(_("Modulation"), self.scan_ter.modulation)) self.list.append(getConfigListEntry(_("Transmission mode"), self.scan_ter.transmission)) self.list.append(getConfigListEntry(_("Guard interval"), self.scan_ter.guard)) self.list.append(getConfigListEntry(_("Hierarchy info"), self.scan_ter.hierarchy)) if self.scan_ter.system.value == <API key>.System_DVB_T2: self.list.append(getConfigListEntry(_('PLP ID'), self.scan_ter.plp_id)) elif self.<API key>.value == "<API key>": self.TerrestrialRegion = self.<API key>[index_to_scan] self.<API key> = getConfigListEntry(_('Region'), self.TerrestrialRegion) self.list.append(self.<API key>) self.<API key>() self.list.append(getConfigListEntry(_('Transponder'), self.<API key>)) elif self.<API key>.value == "complete": self.TerrestrialRegion = self.<API key>[index_to_scan] self.<API key> = getConfigListEntry(_('Region'), self.TerrestrialRegion) self.list.append(self.<API key>) self.list.append(getConfigListEntry(_("Network scan"), self.scan_networkScan)) self.list.append(getConfigListEntry(_("Clear before scan"), self.<API key>)) self.list.append(getConfigListEntry(_("Only free scan"), self.scan_onlyfree)) self["config"].list = self.list self["config"].l.setList(self.list) def Satexists(self, tlist, pos): for x in tlist: if x == pos: return 1 return 0 def newConfig(self): cur = self["config"].getCurrent() print "cur is", cur if cur == self.typeOfScanEntry or \ cur == self.typeOfInputEntry or \ cur == self.tunerEntry or \ cur == self.systemEntry or \ cur == self.preDefSatList or \ cur == self.<API key> or \ (self.modulationEntry and self.systemEntry[1].value == <API key>.System_DVB_S2 and cur == self.modulationEntry): self.createSetup() def createConfig(self, frontendData): defaultSat = { "orbpos": 192, "system": <API key>.System_DVB_S, "frequency": 11836, "inversion": <API key>.Inversion_Unknown, "symbolrate": 27500, "polarization": <API key>.<API key>, "fec": <API key>.FEC_Auto, "fec_s2": <API key>.FEC_9_10, "modulation": <API key>.Modulation_QPSK } defaultCab = { "frequency": 466, "inversion": <API key>.Inversion_Unknown, "modulation": <API key>.Modulation_QAM64, "fec": <API key>.FEC_Auto, "symbolrate": 6900, "system": <API key>.<API key> } defaultTer = { "frequency" : 474000, "inversion" : <API key>.Inversion_Unknown, "bandwidth" : 8000000, "fechigh" : <API key>.FEC_Auto, "feclow" : <API key>.FEC_Auto, "modulation" : <API key>.Modulation_Auto, "transmission_mode" : <API key>.<API key>, "guard_interval" : <API key>.GuardInterval_Auto, "hierarchy": <API key>.Hierarchy_Auto, "system": <API key>.System_DVB_T, "plp_id": 0 } if frontendData is not None: ttype = frontendData.get("tuner_type", "UNKNOWN") if ttype == "DVB-S": defaultSat["system"] = frontendData.get("system", <API key>.System_DVB_S) defaultSat["frequency"] = frontendData.get("frequency", 0) / 1000 defaultSat["inversion"] = frontendData.get("inversion", <API key>.Inversion_Unknown) defaultSat["symbolrate"] = frontendData.get("symbol_rate", 0) / 1000 defaultSat["polarization"] = frontendData.get("polarization", <API key>.<API key>) if defaultSat["system"] == <API key>.System_DVB_S2: defaultSat["fec_s2"] = frontendData.get("fec_inner", <API key>.FEC_Auto) defaultSat["rolloff"] = frontendData.get("rolloff", <API key>.RollOff_alpha_0_35) defaultSat["pilot"] = frontendData.get("pilot", <API key>.Pilot_Unknown) else: defaultSat["fec"] = frontendData.get("fec_inner", <API key>.FEC_Auto) defaultSat["modulation"] = frontendData.get("modulation", <API key>.Modulation_QPSK) defaultSat["orbpos"] = frontendData.get("orbital_position", 0) elif ttype == "DVB-C": defaultCab["frequency"] = frontendData.get("frequency", 0) / 1000 defaultCab["symbolrate"] = frontendData.get("symbol_rate", 0) / 1000 defaultCab["inversion"] = frontendData.get("inversion", <API key>.Inversion_Unknown) defaultCab["fec"] = frontendData.get("fec_inner", <API key>.FEC_Auto) defaultCab["modulation"] = frontendData.get("modulation", <API key>.Modulation_QAM16) defaultCab["system"] = frontendData.get("system", <API key>.<API key>) elif ttype == "DVB-T": defaultTer["frequency"] = frontendData.get("frequency", 47400000) / 1000 defaultTer["inversion"] = frontendData.get("inversion", <API key>.Inversion_Unknown) defaultTer["bandwidth"] = frontendData.get("bandwidth", 8000000) defaultTer["fechigh"] = frontendData.get("code_rate_hp", <API key>.FEC_Auto) defaultTer["feclow"] = frontendData.get("code_rate_lp", <API key>.FEC_Auto) defaultTer["modulation"] = frontendData.get("constellation", <API key>.Modulation_Auto) defaultTer["transmission_mode"] = frontendData.get("transmission_mode", <API key>.<API key>) defaultTer["guard_interval"] = frontendData.get("guard_interval", <API key>.GuardInterval_Auto) defaultTer["hierarchy"] = frontendData.get("<API key>", <API key>.Hierarchy_Auto) defaultTer["system"] = frontendData.get("system", <API key>.System_DVB_T) defaultTer["plp_id"] = frontendData.get("plp_id", 0) self.scan_sat = ConfigSubsection() self.scan_cab = ConfigSubsection() self.scan_ter = ConfigSubsection() nim_list = [] # collect all nims which are *not* set to "nothing" for n in nimmanager.nim_slots: if n.config_mode == "nothing": continue if n.config_mode == "advanced" and len(nimmanager.getSatListForNim(n.slot)) < 1: continue if n.config_mode in ("loopthrough", "satposdepends"): root_id = nimmanager.sec.getRoot(n.slot_id, int(n.config.connectedTo.value)) if n.type == nimmanager.nim_slots[root_id].type: # check if connected from a DVB-S to DVB-S2 Nim or vice versa continue nim_list.append((str(n.slot), n.<API key>)) self.scan_nims = ConfigSelection(choices = nim_list) if frontendData is not None and len(nim_list) > 0: self.scan_nims.setValue(str(frontendData.get("tuner_number", nim_list[0][0]))) for slot in nimmanager.nim_slots: if slot.isCompatible("DVB-T"): self.ter_tnumber = slot.slot if self.ter_tnumber is not None: self.ter_channel_input = channelnumbers.supportedChannels(self.ter_tnumber) # status self.scan_snr = ConfigSlider() self.scan_snr.enabled = False self.scan_agc = ConfigSlider() self.scan_agc.enabled = False self.scan_ber = ConfigSlider() self.scan_ber.enabled = False # sat self.scan_sat.system = ConfigSelection(default = defaultSat["system"], choices = [ (<API key>.System_DVB_S, _("DVB-S")), (<API key>.System_DVB_S2, _("DVB-S2"))]) self.scan_sat.frequency = ConfigInteger(default = defaultSat["frequency"], limits = (1, 99999)) self.scan_sat.inversion = ConfigSelection(default = defaultSat["inversion"], choices = [ (<API key>.Inversion_Off, _("Off")), (<API key>.Inversion_On, _("On")), (<API key>.Inversion_Unknown, _("Auto"))]) self.scan_sat.symbolrate = ConfigInteger(default = defaultSat["symbolrate"], limits = (1, 99999)) self.scan_sat.polarization = ConfigSelection(default = defaultSat["polarization"], choices = [ (<API key>.<API key>, _("horizontal")), (<API key>.<API key>, _("vertical")), (<API key>.<API key>, _("circular left")), (<API key>.<API key>, _("circular right"))]) self.scan_sat.fec = ConfigSelection(default = defaultSat["fec"], choices = [ (<API key>.FEC_Auto, _("Auto")), (<API key>.FEC_1_2, "1/2"), (<API key>.FEC_2_3, "2/3"), (<API key>.FEC_3_4, "3/4"), (<API key>.FEC_5_6, "5/6"), (<API key>.FEC_7_8, "7/8"), (<API key>.FEC_None, _("None"))]) self.scan_sat.fec_s2 = ConfigSelection(default = defaultSat["fec_s2"], choices = [ (<API key>.FEC_Auto, _("Auto")), (<API key>.FEC_1_2, "1/2"), (<API key>.FEC_2_3, "2/3"), (<API key>.FEC_3_4, "3/4"), (<API key>.FEC_3_5, "3/5"), (<API key>.FEC_4_5, "4/5"), (<API key>.FEC_5_6, "5/6"), (<API key>.FEC_7_8, "7/8"), (<API key>.FEC_8_9, "8/9"), (<API key>.FEC_9_10, "9/10")]) self.scan_sat.modulation = ConfigSelection(default = defaultSat["modulation"], choices = [ (<API key>.Modulation_QPSK, "QPSK"), (<API key>.Modulation_8PSK, "8PSK")]) self.scan_sat.rolloff = ConfigSelection(default = defaultSat.get("rolloff", <API key>.RollOff_alpha_0_35), choices = [ (<API key>.RollOff_alpha_0_35, "0.35"), (<API key>.RollOff_alpha_0_25, "0.25"), (<API key>.RollOff_alpha_0_20, "0.20"), (<API key>.RollOff_auto, _("Auto"))]) self.scan_sat.pilot = ConfigSelection(default = defaultSat.get("pilot", <API key>.Pilot_Unknown), choices = [ (<API key>.Pilot_Off, _("Off")), (<API key>.Pilot_On, _("On")), (<API key>.Pilot_Unknown, _("Auto"))]) # cable self.scan_cab.frequency = ConfigInteger(default = defaultCab["frequency"], limits = (50, 999)) self.scan_cab.inversion = ConfigSelection(default = defaultCab["inversion"], choices = [ (<API key>.Inversion_Off, _("Off")), (<API key>.Inversion_On, _("On")), (<API key>.Inversion_Unknown, _("Auto"))]) self.scan_cab.modulation = ConfigSelection(default = defaultCab["modulation"], choices = [ (<API key>.Modulation_QAM16, "16-QAM"), (<API key>.Modulation_QAM32, "32-QAM"), (<API key>.Modulation_QAM64, "64-QAM"), (<API key>.Modulation_QAM128, "128-QAM"), (<API key>.Modulation_QAM256, "256-QAM")]) self.scan_cab.fec = ConfigSelection(default = defaultCab["fec"], choices = [ (<API key>.FEC_Auto, _("Auto")), (<API key>.FEC_1_2, "1/2"), (<API key>.FEC_2_3, "2/3"), (<API key>.FEC_3_4, "3/4"), (<API key>.FEC_5_6, "5/6"), (<API key>.FEC_7_8, "7/8"), (<API key>.FEC_8_9, "8/9"), (<API key>.FEC_3_5, "3/5"), (<API key>.FEC_4_5, "4/5"), (<API key>.FEC_9_10, "9/10"), (<API key>.FEC_None, _("None"))]) self.scan_cab.symbolrate = ConfigInteger(default = defaultCab["symbolrate"], limits = (1, 99999)) self.scan_cab.system = ConfigSelection(default = defaultCab["system"], choices = [ (<API key>.<API key>, _("DVB-C")), (<API key>.<API key>, _("DVB-C ANNEX C"))]) # terrestial self.scan_ter.frequency = ConfigInteger(default = defaultTer["frequency"], limits = (50000, 999000)) self.scan_ter.channel = ConfigInteger(default = 21, limits = (1, 99)) self.scan_ter.inversion = ConfigSelection(default = defaultTer["inversion"], choices = [ (<API key>.Inversion_Off, _("Off")), (<API key>.Inversion_On, _("On")), (<API key>.Inversion_Unknown, _("Auto"))]) # WORKAROUND: we can't use BW-auto self.scan_ter.bandwidth = ConfigSelection(default = defaultTer["bandwidth"], choices = [ (1712000, "1.712MHz"), (5000000, "5MHz"), (6000000, "6MHz"), (7000000, "7MHz"), (8000000, "8MHz"), (10000000, "10MHz") ]) #, (<API key>.Bandwidth_Auto, _("Auto")))) self.scan_ter.fechigh = ConfigSelection(default = defaultTer["fechigh"], choices = [ (<API key>.FEC_1_2, "1/2"), (<API key>.FEC_2_3, "2/3"), (<API key>.FEC_3_4, "3/4"), (<API key>.FEC_5_6, "5/6"), (<API key>.FEC_6_7, "6/7"), (<API key>.FEC_7_8, "7/8"), (<API key>.FEC_8_9, "8/9"), (<API key>.FEC_Auto, _("Auto"))]) self.scan_ter.feclow = ConfigSelection(default = defaultTer["feclow"], choices = [ (<API key>.FEC_1_2, "1/2"), (<API key>.FEC_2_3, "2/3"), (<API key>.FEC_3_4, "3/4"), (<API key>.FEC_5_6, "5/6"), (<API key>.FEC_6_7, "6/7"), (<API key>.FEC_7_8, "7/8"), (<API key>.FEC_8_9, "8/9"), (<API key>.FEC_Auto, _("Auto"))]) self.scan_ter.modulation = ConfigSelection(default = defaultTer["modulation"], choices = [ (<API key>.Modulation_QPSK, "QPSK"), (<API key>.Modulation_QAM16, "QAM16"), (<API key>.Modulation_QAM64, "QAM64"), (<API key>.Modulation_QAM256, "QAM256"), (<API key>.Modulation_Auto, _("Auto"))]) self.scan_ter.transmission = ConfigSelection(default = defaultTer["transmission_mode"], choices = [ (<API key>.TransmissionMode_1k, "1K"), (<API key>.TransmissionMode_2k, "2K"), (<API key>.TransmissionMode_4k, "4K"), (<API key>.TransmissionMode_8k, "8K"), (<API key>.<API key>, "16K"), (<API key>.<API key>, "32K"), (<API key>.<API key>, _("Auto"))]) self.scan_ter.guard = ConfigSelection(default = defaultTer["guard_interval"], choices = [ (<API key>.GuardInterval_1_32, "1/32"), (<API key>.GuardInterval_1_16, "1/16"), (<API key>.GuardInterval_1_8, "1/8"), (<API key>.GuardInterval_1_4, "1/4"), (<API key>.GuardInterval_1_128, "1/128"), (<API key>.<API key>, "19/128"), (<API key>.<API key>, "19/256"), (<API key>.GuardInterval_Auto, _("Auto"))]) self.scan_ter.hierarchy = ConfigSelection(default = defaultTer["hierarchy"], choices = [ (<API key>.Hierarchy_None, _("None")), (<API key>.Hierarchy_1, "1"), (<API key>.Hierarchy_2, "2"), (<API key>.Hierarchy_4, "4"), (<API key>.Hierarchy_Auto, _("Auto"))]) self.scan_ter.system = ConfigSelection(default = defaultTer["system"], choices = [ (<API key>.System_DVB_T, _("DVB-T")), (<API key>.System_DVB_T2, _("DVB-T2"))]) self.scan_ter.plp_id = ConfigInteger(default = defaultTer["plp_id"], limits = (0, 255)) self.scan_scansat = {} for sat in nimmanager.satList: #print sat[1] self.scan_scansat[sat[0]] = ConfigYesNo(default = False) self.scan_satselection = [] for slot in nimmanager.nim_slots: if slot.isCompatible("DVB-S"): self.scan_satselection.append(getConfigSatlist(defaultSat["orbpos"], self.satList[slot.slot])) else: self.scan_satselection.append(None) self.<API key> = [] for slot in nimmanager.nim_slots: if slot.isCompatible("DVB-T"): self.<API key>.append(self.<API key>(slot.slot)) else: self.<API key>.append(None) if frontendData is not None and ttype == "DVB-S" and self.<API key>(defaultSat["orbpos"]) is not None: <API key> = "<API key>" else: <API key> = "single_transponder" if frontendData is not None and ttype == "DVB-T" and self.<API key>() is not None: <API key> = "<API key>" else: <API key> = "single_transponder" if frontendData is not None and ttype == "DVB-C" and self.<API key>() is not None: <API key> = "<API key>" else: <API key> = "single_transponder" self.scan_type = ConfigSelection(default = <API key>, choices = [("single_transponder", _("User defined transponder")), ("<API key>", _("Predefined transponder")), ("single_satellite", _("Single satellite")), ("multisat", _("Multisat")), ("multisat_yes", _("Multisat all select"))]) self.scan_typecable = ConfigSelection(default = <API key>, choices = [("single_transponder", _("User defined transponder")), ("<API key>", _("Predefined transponder")), ("complete", _("Complete"))]) self.last_scan_typecable = "single_transponder" self.cable_toggle = {"single_transponder":"complete", "complete":"single_transponder"} self.<API key> = ConfigSelection(default = <API key>, choices = [("single_transponder", _("User defined transponder")), ("<API key>", _("Predefined transponder")), ("complete", _("Complete"))]) self.scan_input_as = ConfigSelection(default = "channel", choices = [("frequency", _("Frequency")), ("channel", _("Channel"))]) self.<API key> = ConfigSelection(default = "no", choices = [("no", _("no")), ("yes", _("yes")), ("yes_hold_feeds", _("yes (keep feeds)"))]) self.scan_onlyfree = ConfigYesNo(default = False) self.scan_networkScan = ConfigYesNo(default = False) return True def keyLeft(self): ConfigListScreen.keyLeft(self) self.newConfig() def keyRight(self): ConfigListScreen.keyRight(self) self.newConfig() def <API key>(self, answer): ConfigListScreen.<API key>(self, answer) self.newConfig() def updateStatus(self): print "updatestatus" def addSatTransponder(self, tlist, frequency, symbol_rate, polarisation, fec, inversion, orbital_position, system, modulation, rolloff, pilot): print "Add Sat: frequ: " + str(frequency) + " symbol: " + str(symbol_rate) + " pol: " + str(polarisation) + " fec: " + str(fec) + " inversion: " + str(inversion) + " modulation: " + str(modulation) + " system: " + str(system) + " rolloff" + str(rolloff) + " pilot" + str(pilot) print "orbpos: " + str(orbital_position) parm = <API key>() parm.modulation = modulation parm.system = system parm.frequency = frequency * 1000 parm.symbol_rate = symbol_rate * 1000 parm.polarisation = polarisation parm.fec = fec parm.inversion = inversion parm.orbital_position = orbital_position parm.rolloff = rolloff parm.pilot = pilot tlist.append(parm) def addCabTransponder(self, tlist, frequency, symbol_rate, modulation, fec, inversion): print "Add Cab: frequ: " + str(frequency) + " symbol: " + str(symbol_rate) + " pol: " + str(modulation) + " fec: " + str(fec) + " inversion: " + str(inversion) parm = <API key>() parm.frequency = frequency parm.symbol_rate = symbol_rate parm.modulation = modulation parm.fec_inner = fec parm.inversion = inversion tlist.append(parm) def addTerTransponder(self, tlist, *args, **kwargs): tlist.append(buildTerTransponder(*args, **kwargs)) def keyGo(self): infoBarInstance = InfoBar.instance if infoBarInstance: infoBarInstance.<API key>(self.<API key>) else: self.<API key>(True) def <API key>(self, answer): START_SCAN = 0 <API key> = 1 <API key> = 2 if not answer or self.scan_nims.value == "": return tlist = [] flags = None removeAll = True action = START_SCAN index_to_scan = int(self.scan_nims.value) if self.scan_nims == [ ]: self.session.open(MessageBox, _("No tuner is enabled!\nPlease setup your tuner settings before you start a service scan."), MessageBox.TYPE_ERROR) return nim = nimmanager.nim_slots[index_to_scan] print "nim", nim.slot if nim.isCompatible("DVB-S"): print "is compatible with DVB-S" if self.scan_type.value == "single_transponder": # these lists are generated for each tuner, so this has work. assert len(self.satList) > index_to_scan assert len(self.scan_satselection) > index_to_scan nimsats = self.satList[index_to_scan] selsatidx = self.scan_satselection[index_to_scan].index # however, the satList itself could be empty. in that case, "index" is 0 (for "None"). if len(nimsats): orbpos = nimsats[selsatidx][0] if self.scan_sat.system.value == <API key>.System_DVB_S: fec = self.scan_sat.fec.value else: fec = self.scan_sat.fec_s2.value print "add sat transponder" self.addSatTransponder(tlist, self.scan_sat.frequency.value, self.scan_sat.symbolrate.value, self.scan_sat.polarization.value, fec, self.scan_sat.inversion.value, orbpos, self.scan_sat.system.value, self.scan_sat.modulation.value, self.scan_sat.rolloff.value, self.scan_sat.pilot.value) removeAll = False elif self.scan_type.value == "<API key>": nimsats = self.satList[index_to_scan] selsatidx = self.scan_satselection[index_to_scan].index if len(nimsats): orbpos = nimsats[selsatidx][0] tps = nimmanager.getTransponders(orbpos) if len(tps) and len(tps) > self.preDefTransponders.index: tp = tps[self.preDefTransponders.index] self.addSatTransponder(tlist, tp[1] / 1000, tp[2] / 1000, tp[3], tp[4], tp[7], orbpos, tp[5], tp[6], tp[8], tp[9]) removeAll = False elif self.scan_type.value == "single_satellite": sat = self.satList[index_to_scan][self.scan_satselection[index_to_scan].index] <API key>(tlist, sat[0]) elif "multisat" in self.scan_type.value: SatList = nimmanager.getSatListForNim(index_to_scan) for x in self.multiscanlist: if x[1].value: print " " + str(x[0]) <API key>(tlist, x[0]) elif nim.isCompatible("DVB-C"): if self.scan_typecable.value == "single_transponder": self.addCabTransponder(tlist, self.scan_cab.frequency.value*1000, self.scan_cab.symbolrate.value*1000, self.scan_cab.modulation.value, self.scan_cab.fec.value, self.scan_cab.inversion.value) removeAll = False elif self.scan_typecable.value == "<API key>": tps = nimmanager.<API key>(index_to_scan) if len(tps) and len(tps) > self.CableTransponders.index : tp = tps[self.CableTransponders.index] # 0 transponder type, 1 freq, 2 sym, 3 mod, 4 fec, 5 inv, 6 sys self.addCabTransponder(tlist, tp[1], tp[2], tp[3], tp[4], tp[5]) removeAll = False elif self.scan_typecable.value == "complete": if config.Nims[index_to_scan].cable.scan_type.value == "provider": <API key>(tlist, index_to_scan) else: action = <API key> elif nim.isCompatible("DVB-T"): if self.<API key>.value == "single_transponder": if self.scan_input_as.value == "channel": frequency = channelnumbers.channel2frequency(self.scan_ter.channel.value, self.ter_tnumber) else: frequency = self.scan_ter.frequency.value * 1000 self.addTerTransponder(tlist, frequency, inversion = self.scan_ter.inversion.value, bandwidth = self.scan_ter.bandwidth.value, fechigh = self.scan_ter.fechigh.value, feclow = self.scan_ter.feclow.value, modulation = self.scan_ter.modulation.value, transmission = self.scan_ter.transmission.value, guard = self.scan_ter.guard.value, hierarchy = self.scan_ter.hierarchy.value, system = self.scan_ter.system.value, plpid = self.scan_ter.plp_id.value) removeAll = False elif self.<API key>.value == "<API key>": if self.<API key> is not None: region = self.<API key>[index_to_scan].value tps = nimmanager.<API key>(region) if len(tps) and len(tps) > self.<API key>.index : tp = tps[self.<API key>.index] tlist.append(buildTerTransponder(tp[1], tp[9], tp[2], tp[4], tp[5], tp[3], tp[7], tp[6], tp[8], tp[10], tp[11])) removeAll = False elif self.<API key>.value == "complete": skip_t2 = False if getMachineBrand() in ('Vu+'): skip_t2 = True if nim.isCompatible("DVB-T2"): scan_util = len(self.<API key>(nim.slot)) and True or False if scan_util: action = <API key> else: skip_t2 = False <API key>(tlist, self.TerrestrialRegion.value, skip_t2) flags = self.scan_networkScan.value and eComponentScan.scanNetworkSearch or 0 tmp = self.<API key>.value if tmp == "yes": flags |= eComponentScan.scanRemoveServices elif tmp == "yes_hold_feeds": flags |= eComponentScan.scanRemoveServices flags |= eComponentScan.scanDontRemoveFeeds if tmp != "no" and not removeAll: flags |= eComponentScan.<API key> if self.scan_onlyfree.value: flags |= eComponentScan.scanOnlyFree for x in self["config"].list: x[1].save() if action == START_SCAN: self.startScan(tlist, flags, index_to_scan, self.networkid) elif action == <API key>: self.flags = flags self.feid = index_to_scan self.tlist = [] self.<API key>(self.feid) elif action == <API key>: self.flags = flags self.feid = index_to_scan self.tlist = tlist self.<API key>(self.feid, nimmanager.<API key>(self.feid)) def <API key>(self, tlist): self.tlist = tlist def <API key>(self): if self.tlist is None: self.tlist = [] else: self.startScan(self.tlist, self.flags, self.feid) def <API key>(self, tlist): if tlist is not None: self.tlist.extend(tlist) def <API key>(self): if self.tlist is None: self.tlist = [] else: self.startScan(self.tlist, self.flags, self.feid) def <API key>(self, orbpos): default = None if orbpos is not None: list = [] if self.scan_sat.system.value == <API key>.System_DVB_S2: fec = self.scan_sat.fec_s2.value else: fec = self.scan_sat.fec.value compare = [0, self.scan_sat.frequency.value*1000, self.scan_sat.symbolrate.value*1000, self.scan_sat.polarization.value, fec] i = 0 tps = nimmanager.getTransponders(orbpos) for tp in tps: if tp[0] == 0: if default is None and self.compareTransponders(tp, compare): default = str(i) list.append((str(i), self.<API key>(tp))) i += 1 self.preDefTransponders = ConfigSelection(choices = list, default = default) return default def <API key>(self, tp): if tp[3] in range (4) and tp[4] in range (11): pol_list = ['H','V','L','R'] fec_list = ['Auto','1/2','2/3','3/4','5/6','7/8','8/9','3/5','4/5','9/10','None'] return str(tp[1] / 1000) + " " + pol_list[tp[3]] + " " + str(tp[2] / 1000) + " " + fec_list[tp[4]] return _("Invalid transponder data") def compareTransponders(self, tp, compare): frequencyTolerance = 2000 #2 MHz symbolRateTolerance = 10 return abs(tp[1] - compare[1]) <= frequencyTolerance and abs(tp[2] - compare[2]) <= symbolRateTolerance and tp[3] == compare[3] and (not tp[4] or tp[4] == compare[4]) def <API key>(self): default = None list = [] compare = [2, self.scan_ter.frequency.value*1000] i = 0 index_to_scan = int(self.scan_nims.value) channels = channelnumbers.supportedChannels(index_to_scan) region = self.<API key>[index_to_scan].value tps = nimmanager.<API key>(region) for tp in tps: if tp[0] == 2: #TERRESTRIAL channel = '' if channels: channel = _(' (Channel %s)') % (channelnumbers.getChannelNumber(tp[1], index_to_scan)) if default is None and self.<API key>(tp, compare): default = str(i) list.append((str(i), '%s MHz %s' % (str(tp[1] / 1000000), channel))) i += 1 print "channel", channel self.<API key> = ConfigSelection(choices = list, default = default) return default def <API key>(self, tp, compare): frequencyTolerance = 1000000 #1 MHz return abs(tp[1] - compare[1]) <= frequencyTolerance def <API key>(self, index_to_scan = None): default = None list = [] if index_to_scan is None: index_to_scan = int(self.scan_nims.value) defaultRegionForNIM = nimmanager.<API key>(index_to_scan) for r in nimmanager.terrestrialsList: if default is None and r[0] == defaultRegionForNIM: default = r[0] list.append((r[0], r[0][:46])) return ConfigSelection(choices = list, default = default) def <API key>(self): default = None list = [] # 0 transponder type, 1 freq, 2 sym, 3 mod, 4 fec, 5 inv, 6 sys compare = [1, self.scan_cab.frequency.value*1000, self.scan_cab.symbolrate.value*1000, self.scan_cab.modulation.value, self.scan_cab.fec.value, self.scan_cab.inversion.value, self.scan_cab.system.value] i = 0 index_to_scan = int(self.scan_nims.value) tps = nimmanager.<API key>(index_to_scan) for tp in tps: if tp[0] == 1: #CABLE if default is None and self.<API key>(tp, compare): default = str(i) list.append((str(i), self.<API key>(tp))) i += 1 self.CableTransponders = ConfigSelection(choices = list, default = default) return default def <API key>(self, tp): if tp[3] in range (7) and (tp[4] in range (10) or tp[4] == 15): mod_list = ['Auto', '16-QAM','32-QAM','64-QAM','128-QAM', '256-QAM', 'Auto'] fec_list = {0:"Auto", 1:'1/2', 2:'2/3', 3:'3/4', 4:'5/6', 5:'7/8', 6:'8/9', 7:'3/5', 8:'4/5', 9:'9/10', 15:'None'} print str(tp[1]/1000) + " MHz " + fec_list[tp[4]] + " " + str(tp[2]/1000) + " " + mod_list[tp[3]] return str(tp[1]/1000) + " MHz " + fec_list[tp[4]] + " " + str(tp[2]/1000) + " " + mod_list[tp[3]] return _("Invalid transponder data") def <API key>(self, tp, compare): frequencyTolerance = 1000000 #1 MHz symbolRateTolerance = 10 return abs(tp[1] - compare[1]) <= frequencyTolerance and abs(tp[2] - compare[2]) <= symbolRateTolerance and tp[3] == compare[3] and (not tp[4] or tp[4] == compare[4]) def startScan(self, tlist, flags, feid, networkid = 0): if len(tlist): # flags |= eComponentScan.scanSearchBAT if self.finished_cb: self.session.openWithCallback(self.finished_cb, ServiceScan, [{"transponders": tlist, "feid": feid, "flags": flags, "networkid": networkid}]) else: self.session.openWithCallback(self.startScanCallback, ServiceScan, [{"transponders": tlist, "feid": feid, "flags": flags, "networkid": networkid}]) else: if self.finished_cb: self.session.openWithCallback(self.finished_cb, MessageBox, _("Nothing to scan!\nPlease setup your tuner settings before you start a service scan."), MessageBox.TYPE_ERROR) else: self.session.open(MessageBox, _("Nothing to scan!\nPlease setup your tuner settings before you start a service scan."), MessageBox.TYPE_ERROR) def startScanCallback(self, answer=True): if answer: self.doCloseRecursive() def keyCancel(self): self.session.nav.playService(self.session.postScanService) for x in self["config"].list: x[1].cancel() self.close() def doCloseRecursive(self): self.session.nav.playService(self.session.postScanService) self.closeRecursive() class ScanSimple(ConfigListScreen, Screen, <API key>, <API key>): def getNetworksForNim(self, nim): if nim.isCompatible("DVB-S"): networks = nimmanager.getSatListForNim(nim.slot) elif nim.isCompatible("DVB-T"): networks = nimmanager.<API key>(nim.slot) elif not nim.empty: networks = [ nim.type ] else: # empty tuners provide no networks. networks = [ ] return networks def __init__(self, session): Screen.__init__(self, session) Screen.setTitle(self, _("Automatic Scan")) self["key_red"] = StaticText(_("Close")) self["key_green"] = StaticText(_("Scan")) self["actions"] = ActionMap(["SetupActions", "MenuActions", "ColorActions"], { "ok": self.keyGo, "save": self.keyGo, "cancel": self.keyCancel, "menu": self.doCloseRecursive, "red": self.keyCancel, "green": self.keyGo, }, -2) self.session.postScanService = session.nav.<API key>() self.list = [] tlist = [] known_networks = [ ] nims_to_scan = [ ] self.finished_cb = None for nim in nimmanager.nim_slots: # collect networks provided by this tuner need_scan = False networks = self.getNetworksForNim(nim) print "nim %d provides" % nim.slot, networks print "known:", known_networks # we only need to scan on the first tuner which provides a network. # this gives the first tuner for each network priority for scanning. for x in networks: if x not in known_networks: need_scan = True print x, "not in ", known_networks known_networks.append(x) # don't offer to scan nims if nothing is connected if not nimmanager.somethingConnected(nim.slot): need_scan = False if need_scan: nims_to_scan.append(nim) # we save the config elements to use them on keyGo self.nim_enable = [ ] if len(nims_to_scan): self.scan_networkScan = ConfigYesNo(default = True) self.<API key> = ConfigSelection(default = "yes", choices = [("no", _("no")), ("yes", _("yes")), ("yes_hold_feeds", _("yes (keep feeds)"))]) self.list.append(getConfigListEntry(_("Network scan"), self.scan_networkScan)) self.list.append(getConfigListEntry(_("Clear before scan"), self.<API key>)) for nim in nims_to_scan: nimconfig = ConfigYesNo(default = True) nimconfig.nim_index = nim.slot self.nim_enable.append(nimconfig) self.list.append(getConfigListEntry(_("Scan ") + nim.slot_name + " (" + nim.friendly_type + ")", nimconfig)) ConfigListScreen.__init__(self, self.list) self["header"] = Label(_("Automatic scan")) self["footer"] = Label(_("Press OK to scan")) def runAsync(self, finished_cb): self.finished_cb = finished_cb self.keyGo() def keyGo(self): InfoBarInstance = InfoBar.instance if InfoBarInstance: InfoBarInstance.<API key>(self.<API key>) else: self.<API key>(True) def <API key>(self, answer): if answer: self.scanList = [] self.known_networks = set() self.nim_iter=0 self.<API key>() def <API key>(self): # this method is called multiple times because of asynchronous stuff APPEND_NOW = 0 <API key> = 1 <API key> = 2 action = APPEND_NOW n = self.nim_iter < len(self.nim_enable) and self.nim_enable[self.nim_iter] or None self.nim_iter += 1 if n: if n.value: # check if nim is enabled flags = 0 nim = nimmanager.nim_slots[n.nim_index] networks = set(self.getNetworksForNim(nim)) networkid = 0 # don't scan anything twice networks.discard(self.known_networks) tlist = [ ] if nim.isCompatible("DVB-S"): # get initial transponders for each satellite to be scanned for sat in networks: <API key>(tlist, sat[0]) elif nim.isCompatible("DVB-C"): if config.Nims[nim.slot].cable.scan_type.value == "provider": <API key>(tlist, nim.slot) else: action = <API key> networkid = config.Nims[nim.slot].cable.scan_networkid.value elif nim.isCompatible("DVB-T"): skip_t2 = False if getMachineBrand() in ('Vu+'): skip_t2 = True if nim.isCompatible("DVB-T2"): scan_util = len(self.<API key>(nim.slot)) and True or False if scan_util: action = <API key> else: skip_t2 = False <API key>(tlist, nimmanager.<API key>(nim.slot), skip_t2) else: assert False flags = self.scan_networkScan.value and eComponentScan.scanNetworkSearch or 0 tmp = self.<API key>.value if tmp == "yes": flags |= eComponentScan.scanRemoveServices elif tmp == "yes_hold_feeds": flags |= eComponentScan.scanRemoveServices flags |= eComponentScan.scanDontRemoveFeeds if action == APPEND_NOW: self.scanList.append({"transponders": tlist, "feid": nim.slot, "flags": flags}) elif action == <API key>: self.flags = flags self.feid = nim.slot self.networkid = networkid self.<API key>(nim.slot) return elif action == <API key>: self.tlist = tlist self.flags = flags self.feid = nim.slot self.<API key>(nim.slot, nimmanager.<API key>(nim.slot)) return else: assert False self.<API key>() # recursive call of this function !!! return # when we are here, then the recursion is finished and all enabled nims are checked # so we now start the real transponder scan self.startScan(self.scanList) def startScan(self, scanList): if len(scanList): if self.finished_cb: self.session.openWithCallback(self.finished_cb, ServiceScan, scanList = scanList) else: self.session.open(ServiceScan, scanList = scanList) else: if self.finished_cb: self.session.openWithCallback(self.finished_cb, MessageBox, _("Nothing to scan!\nPlease setup your tuner settings before you start a service scan."), MessageBox.TYPE_ERROR) else: self.session.open(MessageBox, _("Nothing to scan!\nPlease setup your tuner settings before you start a service scan."), MessageBox.TYPE_ERROR) def <API key>(self, tlist): if tlist is not None: self.scanList.append({"transponders": tlist, "feid": self.feid, "flags": self.flags}) def <API key>(self): self.<API key>() def <API key>(self, tlist): if tlist is not None: self.tlist.extend(tlist) if self.tlist is not None: self.scanList.append({"transponders": self.tlist, "feid": self.feid, "flags": self.flags}) def <API key>(self): self.<API key>() def keyCancel(self): self.session.nav.playService(self.session.postScanService) self.close() def doCloseRecursive(self): self.session.nav.playService(self.session.postScanService) self.closeRecursive() def Satexists(self, tlist, pos): for x in tlist: if x == pos: return 1 return 0
// <API key> <API key> // T H E W A R B E G I N S // Stratagus - A free fantasy real time strategy game engine /**@name script_ai.cpp - The AI ccl functions. */ // and Jimmy Salmon // This program is free software; you can redistribute it and/or modify // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA // 02111-1307, USA. #include "stratagus.h" #include "ai.h" #include "ai_local.h" #include "interface.h" #include "pathfinder.h" #include "player.h" #include "script.h" #include "unit_manager.h" #include "unittype.h" #include "upgrade.h" /** ** Insert new unit-type element. ** ** @param table Table with elements. ** @param n Index to insert new into table ** @param base Base type to insert into table. */ static void AiHelperInsert(std::vector<std::vector<CUnitType *> > &table, unsigned int n, CUnitType &base) { if (n >= table.size()) { table.resize(n + 1); } // Look if already known std::vector<CUnitType *>::const_iterator it = std::find(table[n].begin(), table[n].end(), &base); if (it != table[n].end()) { return; } table[n].push_back(&base); } /** ** Transform list of unit separed with coma to a true list. */ static std::vector<CUnitType *> <API key>(const std::string &list) { std::vector<CUnitType *> res; if (list == "*") { return UnitTypes; } size_t begin = 1; size_t end = list.find(",", begin); while (end != std::string::npos) { std::string unitName = list.substr(begin, end - begin); begin = end + 1; end = list.find(",", begin); if (!unitName.empty()) { Assert(unitName[0] != ','); res.push_back(UnitTypeByIdent(unitName.c_str())); } } return res; } /** ** Get list of unittype which can be repared. */ static std::vector<CUnitType *> getReparableUnits() { std::vector<CUnitType *> res; for (std::vector<CUnitType *>::const_iterator i = UnitTypes.begin(); i != UnitTypes.end(); ++i) { CUnitType &type = **i; if (type.RepairHP > 0) { res.push_back(&type); } } return res; } /** ** Get sorted list of unittype with Supply not null. ** ** @note Better (supply / cost) first. */ static std::vector<CUnitType *> getSupplyUnits() { std::vector<CUnitType *> res; std::vector<CUnitType *> sorted_res; for (std::vector<CUnitType *>::const_iterator i = UnitTypes.begin(); i != UnitTypes.end(); ++i) { CUnitType &type = **i; if (type.Supply > 0) { res.push_back(&type); } } // Now, sort them, best first. while (!res.empty()) { float bestscore = 0; CUnitType *besttype = NULL; for (std::vector<CUnitType *>::const_iterator i = res.begin(); i != res.end(); ++i) { CUnitType &type = **i; unsigned int cost = 0; for (unsigned j = 0; j < MaxCosts; ++j) { cost += type.DefaultStat.Costs[j]; } const float score = ((float) type.Supply) / cost; if (score > bestscore) { bestscore = score; besttype = &type; } } sorted_res.push_back(besttype); for (std::vector<CUnitType *>::iterator i = res.begin(); i != res.end(); ++i) { if (*i == besttype) { i = res.erase(i); break; } } } return sorted_res; } /** ** Get sorted list of unittype with CanHarvest not null. ** ** @note Better (MaxOnBoard / cost) first. */ static std::vector<CUnitType *> getRefineryUnits() { std::vector<CUnitType *> res; for (std::vector<CUnitType *>::const_iterator i = UnitTypes.begin(); i != UnitTypes.end(); ++i) { CUnitType &type = **i; if (type.GivesResource > 0 && type.CanHarvest) { res.push_back(&type); } } #if 0 std::vector<CUnitType *> sorted_res; // Now, sort them, best first. while (!res.empty()) { float bestscore; CUnitType *besttype; bestscore = 0; for (std::vector<CUnitType *>::const_iterator i = res.begin(); i != res.end(); ++i) { CUnitType *type = *i; float score; unsigned int cost = 0; for (unsigned j = 0; j < MaxCosts; ++j) { cost += type->_Costs[j]; } score = ((float) type->MaxOnBoard) / cost; if (score > bestscore) { bestscore = score; besttype = type; } } sorted_res.push_back(besttype); for (std::vector<CUnitType *>::iterator i = res.begin(); i != res.end(); ++i) { if (*i == besttype) { i = res.erase(i); break; } } } return sorted_res; #else return res; #endif } /** ** Init AiHelper. ** ** @param aiHelper variable to initialise. ** ** @todo missing Equiv initialisation. */ static void InitAiHelper(AiHelper &aiHelper) { extern std::vector<ButtonAction *> UnitButtonTable; std::vector<CUnitType *> reparableUnits = getReparableUnits(); std::vector<CUnitType *> supplyUnits = getSupplyUnits(); std::vector<CUnitType *> mineUnits = getRefineryUnits(); for (std::vector<CUnitType *>::const_iterator i = supplyUnits.begin(); i != supplyUnits.end(); ++i) { AiHelperInsert(aiHelper.UnitLimit, 0, **i); } for (int i = 1; i < MaxCosts; ++i) { for (std::vector<CUnitType *>::const_iterator j = mineUnits.begin(); j != mineUnits.end(); ++j) { if ((*j)->GivesResource == i) { /* HACK : we can't mine TIME then use 0 as 1 */ AiHelperInsert(aiHelper.Refinery, i - 1, **j); } } for (std::vector<CUnitType *>::const_iterator d = UnitTypes.begin(); d != UnitTypes.end(); ++d) { CUnitType &type = **d; if (type.CanStore[i] > 0) { /* HACK : we can't store TIME then use 0 as 1 */ AiHelperInsert(aiHelper.Depots, i - 1, type); } } } for (size_t i = 0; i != UnitButtonTable.size(); ++i) { const ButtonAction &button = *UnitButtonTable[i]; const std::vector<CUnitType *> &unitmask = <API key>(button.UnitMask); switch (button.Action) { case ButtonRepair : for (std::vector<CUnitType *>::const_iterator j = unitmask.begin(); j != unitmask.end(); ++j) { for (std::vector<CUnitType *>::const_iterator k = reparableUnits.begin(); k != reparableUnits.end(); ++k) { AiHelperInsert(aiHelper.Repair, (*k)->Slot, **j); } } break; case ButtonBuild: { CUnitType *buildingType = UnitTypeByIdent(button.ValueStr); for (std::vector<CUnitType *>::const_iterator j = unitmask.begin(); j != unitmask.end(); ++j) { AiHelperInsert(aiHelper.Build, buildingType->Slot, (**j)); } break; } case ButtonTrain : { CUnitType *trainingType = UnitTypeByIdent(button.ValueStr); for (std::vector<CUnitType *>::const_iterator j = unitmask.begin(); j != unitmask.end(); ++j) { AiHelperInsert(aiHelper.Train, trainingType->Slot, (**j)); } break; } case ButtonUpgradeTo : { CUnitType *upgradeToType = UnitTypeByIdent(button.ValueStr); for (std::vector<CUnitType *>::const_iterator j = unitmask.begin(); j != unitmask.end(); ++j) { AiHelperInsert(aiHelper.Upgrade, upgradeToType->Slot, **j); } break; } case ButtonResearch : { int researchId = UpgradeIdByIdent(button.ValueStr); for (std::vector<CUnitType *>::const_iterator j = unitmask.begin(); j != unitmask.end(); ++j) { AiHelperInsert(aiHelper.Research, researchId, **j); } break; } default: break; } } } /** ** Define helper for AI. ** ** @param l Lua state. ** ** @todo FIXME: the first unit could be a list see ../doc/ccl/ai.html */ static int CclDefineAiHelper(lua_State *l) { InitAiHelper(AiHelpers); const int args = lua_gettop(l); for (int j = 0; j < args; ++j) { if (!lua_istable(l, j + 1)) { LuaError(l, "incorrect argument"); } const int subargs = lua_rawlen(l, j + 1); const char *value = LuaToString(l, j + 1, 1); if (!strcmp(value, "build") || !strcmp(value, "train") || !strcmp(value, "upgrade") || !strcmp(value, "research") || !strcmp(value, "unit-limit") || !strcmp(value, "repair")) { #ifdef DEBUG fprintf(stderr, "DefineAiHelper: Relation is computed from buttons, you may remove safely the block beginning with '\"%s\"'\n", value); #endif continue; } else if (!strcmp(value, "unit-equiv")) { } else { LuaError(l, "unknown tag: %s" _C_ value); } // Get the base unit type, which could handle the action. const char *baseTypeName = LuaToString(l, j + 1, 2); const CUnitType *base = UnitTypeByIdent(baseTypeName); if (!base) { LuaError(l, "unknown unittype: %s" _C_ baseTypeName); } // Get the unit types, which could be produced for (int k = 2; k < subargs; ++k) { const char *equivTypeName = LuaToString(l, j + 1, k + 1); CUnitType *type = UnitTypeByIdent(equivTypeName); if (!type) { LuaError(l, "unknown unittype: %s" _C_ equivTypeName); } AiHelperInsert(AiHelpers.Equiv, base->Slot, *type); AiNewUnitTypeEquiv(*base, *type); } } return 0; } static CAiType *GetAiTypesByName(const char *name) { for (size_t i = 0; i < AiTypes.size(); ++i) { CAiType *ait = AiTypes[i]; if (ait->Name == name) { return ait; } } return NULL; } /** ** Define an AI engine. ** ** @param l Lua state. ** ** @return FIXME: docu */ static int CclDefineAi(lua_State *l) { LuaCheckArgs(l, 4); if (!lua_isfunction(l, 4)) { LuaError(l, "incorrect argument"); } CAiType *aitype = new CAiType; // AI Name const char *aiName = LuaToString(l, 1); aitype->Name = aiName; #ifdef DEBUG if (GetAiTypesByName(aiName)) { DebugPrint("Warning two or more AI's with the same name '%s'\n" _C_ aiName); } #endif AiTypes.insert(AiTypes.begin(), aitype); // AI Race const char *value = LuaToString(l, 2); if (*value != '*') { aitype->Race = value; } else { aitype->Race.clear(); } // AI Class aitype->Class = LuaToString(l, 3); // AI Script lua_getglobal(l, "_ai_scripts_"); if (lua_isnil(l, -1)) { lua_pop(l, 1); lua_newtable(l); lua_setglobal(l, "_ai_scripts_"); lua_getglobal(l, "_ai_scripts_"); } aitype->Script = aitype->Name + aitype->Race + aitype->Class; lua_pushstring(l, aitype->Script.c_str()); lua_pushvalue(l, 4); lua_rawset(l, 5); lua_pop(l, 1); return 0; } /** ** Append unit-type to request table. ** ** @param type Unit-type to be appended. ** @param count How many unit-types to build. */ static void <API key>(CUnitType *type, int count) { AiRequestType ait; ait.Type = type; ait.Count = count; AiPlayer->UnitTypeRequests.push_back(ait); } /** ** Find unit-type in request table. ** ** @param type Unit-type to be found. */ static AiRequestType *<API key>(const CUnitType *type) { const size_t n = AiPlayer->UnitTypeRequests.size(); for (size_t i = 0; i < n; ++i) { if (AiPlayer->UnitTypeRequests[i].Type == type) { return &AiPlayer->UnitTypeRequests[i]; } } return NULL; } /** ** Find unit-type in upgrade-to table. ** ** @param type Unit-type to be found. */ static int <API key>(const CUnitType *type) { const size_t n = AiPlayer->UpgradeToRequests.size(); for (size_t i = 0; i < n; ++i) { if (AiPlayer->UpgradeToRequests[i] == type) { return 1; } } return 0; } /** ** Append unit-type to request table. ** ** @param type Unit-type to be appended. */ static void <API key>(CUnitType *type) { AiPlayer->UpgradeToRequests.push_back(type); } /** ** Append unit-type to request table. ** ** @param upgrade Upgrade to be appended. */ static void <API key>(CUpgrade *upgrade) { AiPlayer->ResearchRequests.push_back(upgrade); } /** ** Get the race of the current AI player. ** ** @param l Lua state. */ static int CclAiGetRace(lua_State *l) { LuaCheckArgs(l, 0); lua_pushstring(l, PlayerRaces.Name[AiPlayer->Player->Race].c_str()); return 1; } /** ** Get the number of cycles to sleep. ** ** @param l Lua state ** ** @return Number of return values */ static int CclAiGetSleepCycles(lua_State *l) { LuaCheckArgs(l, 0); lua_pushnumber(l, AiSleepCycles); return 1; } /** ** Set debugging flag of AI script ** ** @param l Lua state ** ** @return Number of return values */ static int CclAiDebug(lua_State *l) { LuaCheckArgs(l, 1); AiPlayer->ScriptDebug = LuaToBoolean(l, 1); return 0; } /** ** Activate AI debugging for the given player(s) ** Player can be a number for a specific player ** "self" for current human player (ai me) ** "none" to disable ** ** @param l Lua State ** ** @return Number of return values */ static int CclAiDebugPlayer(lua_State *l) { const int args = lua_gettop(l); for (int j = 0; j < args; ++j) { const char *item; if (lua_isstring(l, j + 1)) { item = LuaToString(l, j + 1); } else { item = NULL; } if (item && !strcmp(item, "none")) { for (int i = 0; i != NumPlayers; ++i) { if (!Players[i].AiEnabled || !Players[i].Ai) { continue; } Players[i].Ai->ScriptDebug = 0; } } else { int playerid; if (item && !strcmp(item, "self")) { if (!ThisPlayer) { continue; } playerid = ThisPlayer->Index; } else { playerid = LuaToNumber(l, j + 1); } if (!Players[playerid].AiEnabled || !Players[playerid].Ai) { continue; } Players[playerid].Ai->ScriptDebug = 1; } } return 0; } /** ** Need a unit. ** ** @param l Lua state. ** ** @return Number of return values */ static int CclAiNeed(lua_State *l) { LuaCheckArgs(l, 1); <API key>(CclGetUnitType(l), 1); lua_pushboolean(l, 0); return 1; } /** ** Set the number of units. ** ** @param l Lua state ** ** @return Number of return values */ static int CclAiSet(lua_State *l) { LuaCheckArgs(l, 2); lua_pushvalue(l, 1); CUnitType *type = CclGetUnitType(l); lua_pop(l, 1); AiRequestType *autt = <API key>(type); if (autt) { autt->Count = LuaToNumber(l, 2); // FIXME: 0 should remove it. } else { <API key>(type, LuaToNumber(l, 2)); } lua_pushboolean(l, 0); return 1; } /** ** Wait for a unit. ** ** @param l Lua State. ** ** @return Number of return values */ static int CclAiWait(lua_State *l) { LuaCheckArgs(l, 1); const CUnitType *type = CclGetUnitType(l); const int *unit_types_count = AiPlayer->Player->UnitTypesCount; const AiRequestType *autt = <API key>(type); if (!autt) { // Look if we have this unit-type. if (unit_types_count[type->Slot]) { lua_pushboolean(l, 0); return 1; } // Look if we have equivalent unit-types. if (type->Slot < (int)AiHelpers.Equiv.size()) { for (size_t j = 0; j < AiHelpers.Equiv[type->Slot].size(); ++j) { if (unit_types_count[AiHelpers.Equiv[type->Slot][j]->Slot]) { lua_pushboolean(l, 0); return 1; } } } // Look if we have an upgrade-to request. if (<API key>(type)) { lua_pushboolean(l, 1); return 1; } DebugPrint("Broken? waiting on %s which wasn't requested.\n" _C_ type->Ident.c_str()); lua_pushboolean(l, 0); return 1; } // Add equivalent units unsigned int n = unit_types_count[type->Slot]; if (type->Slot < (int)AiHelpers.Equiv.size()) { for (size_t j = 0; j < AiHelpers.Equiv[type->Slot].size(); ++j) { n += unit_types_count[AiHelpers.Equiv[type->Slot][j]->Slot]; } } // units available? if (n >= autt->Count) { lua_pushboolean(l, 0); return 1; } lua_pushboolean(l, 1); return 1; } /** ** Define a force, a groups of units. ** ** @param l Lua state. */ static int CclAiForce(lua_State *l) { bool resetForce = false; const int arg = lua_gettop(l); Assert(0 < arg && arg <= 3); if (!lua_istable(l, 2)) { LuaError(l, "incorrect argument"); } if (arg == 3) { resetForce = LuaToBoolean(l, 3); } int force = LuaToNumber(l, 1); if (force < 0 || force >= <API key>) { LuaError(l, "Force out of range: %d" _C_ force); } AiForce &aiforce = AiPlayer->Force[AiPlayer->Force.getScriptForce(force)]; if (resetForce) { AiForceRole role = aiforce.Role; aiforce.Reset(true); aiforce.State = <API key>; aiforce.Role = role; } int args = lua_rawlen(l, 2); for (int j = 0; j < args; ++j) { lua_rawgeti(l, 2, j + 1); CUnitType *type = CclGetUnitType(l); lua_pop(l, 1); ++j; int count = LuaToNumber(l, 2, j + 1); if (!type) { // bulletproof continue; } // Use the equivalent unittype. type = UnitTypes[UnitTypeEquivs[type->Slot]]; if (resetForce) { // Append it. AiUnitType newaiut; newaiut.Want = count; newaiut.Type = type; aiforce.UnitTypes.push_back(newaiut); } else { // Look if already in force. size_t i; for (i = 0; i < aiforce.UnitTypes.size(); ++i) { AiUnitType *aiut = &aiforce.UnitTypes[i]; if (aiut->Type->Slot == type->Slot) { // found if (count) { aiut->Want = count; } else { aiforce.UnitTypes.erase(aiforce.UnitTypes.begin() + i); } break; } } // New type append it. if (i == aiforce.UnitTypes.size()) { AiUnitType newaiut; newaiut.Want = count; newaiut.Type = type; aiforce.UnitTypes.push_back(newaiut); } } } <API key>(); lua_pushboolean(l, 0); return 1; } /** ** Define the role of a force. ** ** @param l Lua state. */ static int CclAiForceRole(lua_State *l) { LuaCheckArgs(l, 2); int force = LuaToNumber(l, 1); if (force < 0 || force >= <API key>) { LuaError(l, "Force %i out of range" _C_ force); } AiForce &aiforce = AiPlayer->Force[AiPlayer->Force.getScriptForce(force)]; const char *flag = LuaToString(l, 2); if (!strcmp(flag, "attack")) { aiforce.Role = AiForceRoleAttack; } else if (!strcmp(flag, "defend")) { aiforce.Role = AiForceRoleDefend; } else { LuaError(l, "Unknown force role '%s'" _C_ flag); } lua_pushboolean(l, 0); return 1; } /** ** Check if a force ready. ** ** @param l Lua state. */ static int CclAiCheckForce(lua_State *l) { LuaCheckArgs(l, 1); int force = LuaToNumber(l, 1); if (force < 0 || force >= <API key>) { lua_pushfstring(l, "Force out of range: %d", force); } if (AiPlayer->Force[AiPlayer->Force.getScriptForce(force)].Completed) { lua_pushboolean(l, 1); return 1; } lua_pushboolean(l, 0); return 1; } /** ** Wait for a force ready. ** ** @param l Lua state. */ static int CclAiWaitForce(lua_State *l) { LuaCheckArgs(l, 1); int force = LuaToNumber(l, 1); if (force < 0 || force >= <API key>) { lua_pushfstring(l, "Force out of range: %d", force); } if (AiPlayer->Force[AiPlayer->Force.getScriptForce(force)].Completed) { lua_pushboolean(l, 0); return 1; } #if 0 // Debuging <API key>(); Assert(!AiPlayer->Force.getScriptForce(f).Completed); #endif lua_pushboolean(l, 1); return 1; } /** ** Attack with force. ** ** @param l Lua state. */ static int <API key>(lua_State *l) { LuaCheckArgs(l, 1); int force = LuaToNumber(l, 1); if (force < 0 || force >= <API key>) { LuaError(l, "Force out of range: %d" _C_ force); } AiAttackWithForce(AiPlayer->Force.getScriptForce(force)); lua_pushboolean(l, 0); return 1; } /** ** Wait for a forces ready. ** ** @param l Lua state. */ static int CclAiWaitForces(lua_State *l) { LuaCheckArgs(l, 1); if (!lua_istable(l, 1)) { LuaError(l, "incorrect argument"); } const int args = lua_rawlen(l, 1); for (int i = 0; i < args; ++i) { const int force = LuaToNumber(l, 1, i + 1); if (force < 0 || force >= <API key>) { lua_pushfstring(l, "Force out of range: %d", force); } if (!AiPlayer->Force[AiPlayer->Force.getScriptForce(force)].Completed) { lua_pushboolean(l, 1); return 1; } } lua_pushboolean(l, 0); return 1; } /** ** Attack with forces. ** ** @param l Lua state. */ static int <API key>(lua_State *l) { int Forces[<API key> + 1]; LuaCheckArgs(l, 1); if (!lua_istable(l, 1)) { LuaError(l, "incorrect argument"); } int args = lua_rawlen(l, 1); for (int i = 0; i < args; ++i) { const int force = LuaToNumber(l, 1, i + 1); if (force < 0 || force >= <API key>) { lua_pushfstring(l, "Force out of range: %d", force); } Forces[i] = AiPlayer->Force.getScriptForce(force); } Forces[args] = -1; AiAttackWithForces(Forces); lua_pushboolean(l, 0); return 1; } /** ** Sleep n cycles. ** ** @param l Lua state. */ static int CclAiSleep(lua_State *l) { LuaCheckArgs(l, 1); int i = LuaToNumber(l, 1); if (AiPlayer->SleepCycles || i == 0) { if (AiPlayer->SleepCycles < GameCycle) { AiPlayer->SleepCycles = 0; lua_pushboolean(l, 0); return 1; } } else { AiPlayer->SleepCycles = GameCycle + i; } lua_pushboolean(l, 1); return 1; } /** ** Research an upgrade. ** ** @param l Lua state. */ static int CclAiResearch(lua_State *l) { LuaCheckArgs(l, 1); const char *str = LuaToString(l, 1); CUpgrade *upgrade; if (str) { upgrade = CUpgrade::Get(str); } else { LuaError(l, "Upgrade needed"); upgrade = NULL; } <API key>(upgrade); lua_pushboolean(l, 0); return 1; } /** ** Upgrade an unit to an new unit-type. ** ** @param l Lua state. */ static int CclAiUpgradeTo(lua_State *l) { LuaCheckArgs(l, 1); CUnitType *type = CclGetUnitType(l); <API key>(type); lua_pushboolean(l, 0); return 1; } /** ** Return the player of the running AI. ** ** @param l Lua state. ** ** @return Player number of the AI. */ static int CclAiPlayer(lua_State *l) { LuaCheckArgs(l, 0); lua_pushnumber(l, AiPlayer->Player->Index); return 1; } /** ** Set AI player resource reserve. ** ** @param l Lua state. ** ** @return Old resource vector */ static int CclAiSetReserve(lua_State *l) { LuaCheckArgs(l, 1); if (!lua_istable(l, 1)) { LuaError(l, "incorrect argument"); } lua_newtable(l); for (int i = 0; i < MaxCosts; ++i) { lua_pushnumber(l, AiPlayer->Reserve[i]); lua_rawseti(l, -2, i + 1); } for (int i = 0; i < MaxCosts; ++i) { AiPlayer->Reserve[i] = LuaToNumber(l, 1, i + 1); } return 1; } /** ** Set AI player resource collect percent. ** ** @param l Lua state. */ static int CclAiSetCollect(lua_State *l) { LuaCheckArgs(l, 1); if (!lua_istable(l, 1)) { LuaError(l, "incorrect argument"); } for (int i = 0; i < MaxCosts; ++i) { AiPlayer->Collect[i] = LuaToNumber(l, 1, i + 1); } return 0; } /** ** Dump some AI debug informations. ** ** @param l Lua state. */ static int CclAiDump(lua_State *l) { LuaCheckArgs(l, 0); for (int p = 0; p < PlayerMax - 1; ++p) { CPlayer &aip = Players[p]; if (aip.AiEnabled) { // Script printf(" for (int i = 0; i < MaxCosts; ++i) { printf("%s(%4d, %4d/%4d) ", <API key>[i].c_str(), aip.Resources[i], aip.StoredResources[i], aip.MaxResources[i]); } printf("\n"); printf("Player %d:", aip.Index); #if 0 gh_display(gh_car(AiPlayer->Script)); #endif // Requests size_t n = aip.Ai->UnitTypeRequests.size(); printf("UnitTypeRequests(%u):\n", static_cast<unsigned int>(n)); for (size_t i = 0; i < n; ++i) { printf("%s ", aip.Ai->UnitTypeRequests[i].Type->Ident.c_str()); } printf("\n"); n = aip.Ai->UpgradeToRequests.size(); printf("UpgradeToRequests(%u):\n", static_cast<unsigned int>(n)); for (size_t i = 0; i < n; ++i) { printf("%s ", aip.Ai->UpgradeToRequests[i]->Ident.c_str()); } printf("\n"); n = aip.Ai->ResearchRequests.size(); printf("ResearchRequests(%u):\n", static_cast<unsigned int>(n)); for (size_t i = 0; i < n; ++i) { printf("%s ", aip.Ai->ResearchRequests[i]->Ident.c_str()); } printf("\n"); // Building queue printf("Building queue:\n"); for (size_t i = 0; i < aip.Ai->UnitTypeBuilt.size(); ++i) { const AiBuildQueue &queue = aip.Ai->UnitTypeBuilt[i]; printf("%s(%d/%d) ", queue.Type->Ident.c_str(), queue.Made, queue.Want); } printf("\n"); // PrintForce for (size_t i = 0; i < aip.Ai->Force.Size(); ++i) { printf("Force(%u%s%s):\n", static_cast<unsigned int>(i), aip.Ai->Force[i].Completed ? ",complete" : ",recruit", aip.Ai->Force[i].Attacking ? ",attack" : ""); for (size_t j = 0; j < aip.Ai->Force[i].UnitTypes.size(); ++j) { const AiUnitType &aut = aip.Ai->Force[i].UnitTypes[j]; printf("%s(%d) ", aut.Type->Ident.c_str(), aut.Want); } printf("\n"); } printf("\n"); } } lua_pushboolean(l, 0); return 1; } /** ** Parse AiBuildQueue builing list ** ** @param l Lua state. ** @param ai PlayerAi pointer which should be filled with the data. */ static void CclParseBuildQueue(lua_State *l, PlayerAi *ai, int offset) { if (!lua_istable(l, offset)) { LuaError(l, "incorrect argument"); } Vec2i pos(-1, -1); const int args = lua_rawlen(l, offset); for (int k = 0; k < args; ++k) { const char *value = LuaToString(l, offset, k + 1); ++k; if (!strcmp(value, "onpos")) { pos.x = LuaToNumber(l, offset, k + 1); ++k; pos.y = LuaToNumber(l, offset, k + 1); } else { //ident = LuaToString(l, j + 1, k + 1); const int made = LuaToNumber(l, offset, k + 1); ++k; const int want = LuaToNumber(l, offset, k + 1); AiBuildQueue queue; queue.Type = UnitTypeByIdent(value); queue.Want = want; queue.Made = made; queue.Pos = pos; ai->UnitTypeBuilt.push_back(queue); pos.x = -1; pos.y = -1; } } } /** ** Define an AI player. ** ** @param l Lua state. */ static int CclDefineAiPlayer(lua_State *l) { const unsigned int playerIdx = LuaToNumber(l, 0 + 1); Assert(playerIdx <= PlayerMax); DebugPrint("%p %d\n" _C_(void *)Players[playerIdx].Ai _C_ Players[playerIdx].AiEnabled); // FIXME: lose this: // Assert(!Players[playerIdx].Ai && Players[playerIdx].AiEnabled); PlayerAi *ai = Players[playerIdx].Ai = new PlayerAi; ai->Player = &Players[playerIdx]; // Parse the list: (still everything could be changed!) const int args = lua_gettop(l); for (int j = 1; j < args; ++j) { const char *value = LuaToString(l, j + 1); ++j; if (!strcmp(value, "ai-type")) { const char *aiName = LuaToString(l, j + 1); CAiType *ait = GetAiTypesByName(aiName); if (ait == NULL) { LuaError(l, "ai-type not found: %s" _C_ aiName); } ai->AiType = ait; ai->Script = ait->Script; } else if (!strcmp(value, "script")) { ai->Script = LuaToString(l, j + 1); } else if (!strcmp(value, "script-debug")) { ai->ScriptDebug = LuaToBoolean(l, j + 1); } else if (!strcmp(value, "sleep-cycles")) { ai->SleepCycles = LuaToNumber(l, j + 1); } else if (!strcmp(value, "force")) { if (!lua_istable(l, j + 1)) { LuaError(l, "incorrect argument"); } const int subargs = lua_rawlen(l, j + 1); const int cclforceIdx = LuaToNumber(l, j + 1, 1); UNUSED(cclforceIdx); const int forceIdx = ai->Force.FindFreeForce(AiForceRoleDefault); for (int k = 1; k < subargs; ++k) { const char *value = LuaToString(l, j + 1, k + 1); ++k; if (!strcmp(value, "complete")) { ai->Force[forceIdx].Completed = true; --k; } else if (!strcmp(value, "recruit")) { ai->Force[forceIdx].Completed = false; --k; } else if (!strcmp(value, "attack")) { ai->Force[forceIdx].Attacking = true; --k; } else if (!strcmp(value, "defend")) { ai->Force[forceIdx].Defending = true; --k; } else if (!strcmp(value, "role")) { value = LuaToString(l, j + 1, k + 1); if (!strcmp(value, "attack")) { ai->Force[forceIdx].Role = AiForceRoleAttack; } else if (!strcmp(value, "defend")) { ai->Force[forceIdx].Role = AiForceRoleDefend; } else { LuaError(l, "Unsupported force tag: %s" _C_ value); } } else if (!strcmp(value, "types")) { lua_rawgeti(l, j + 1, k + 1); if (!lua_istable(l, -1)) { LuaError(l, "incorrect argument"); } const int subsubargs = lua_rawlen(l, -1); for (int subk = 0; subk < subsubargs; ++subk) { const int num = LuaToNumber(l, -1, subk + 1); ++subk; const char *ident = LuaToString(l, -1, subk + 1); AiUnitType queue; queue.Want = num; queue.Type = UnitTypeByIdent(ident); ai->Force[forceIdx].UnitTypes.push_back(queue); } lua_pop(l, 1); } else if (!strcmp(value, "units")) { lua_rawgeti(l, j + 1, k + 1); if (!lua_istable(l, -1)) { LuaError(l, "incorrect argument"); } const int subsubargs = lua_rawlen(l, -1); for (int subk = 0; subk < subsubargs; ++subk) { const int num = LuaToNumber(l, -1, subk + 1); ++subk; #if 0 const char *ident = LuaToString(l, -1, subk + 1); UNUSED(ident); #endif ai->Force[forceIdx].Units.Insert(&UnitManager.GetSlotUnit(num)); } lua_pop(l, 1); } else if (!strcmp(value, "state")) { ai->Force[forceIdx].State = <API key>(LuaToNumber(l, j + 1, k + 1)); } else if (!strcmp(value, "goalx")) { ai->Force[forceIdx].GoalPos.x = LuaToNumber(l, j + 1, k + 1); } else if (!strcmp(value, "goaly")) { ai->Force[forceIdx].GoalPos.y = LuaToNumber(l, j + 1, k + 1); } else if (!strcmp(value, "must-transport")) { // Keep for backward compatibility } else { LuaError(l, "Unsupported tag: %s" _C_ value); } } } else if (!strcmp(value, "reserve")) { if (!lua_istable(l, j + 1)) { LuaError(l, "incorrect argument"); } const int subargs = lua_rawlen(l, j + 1); for (int k = 0; k < subargs; ++k) { const char *type = LuaToString(l, j + 1, k + 1); ++k; int num = LuaToNumber(l, j + 1, k + 1); const int resId = GetResourceIdByName(l, type); ai->Reserve[resId] = num; } } else if (!strcmp(value, "used")) { if (!lua_istable(l, j + 1)) { LuaError(l, "incorrect argument"); } const int subargs = lua_rawlen(l, j + 1); for (int k = 0; k < subargs; ++k) { const char *type = LuaToString(l, j + 1, k + 1); ++k; const int num = LuaToNumber(l, j + 1, k + 1); const int resId = GetResourceIdByName(l, type); ai->Used[resId] = num; } } else if (!strcmp(value, "needed")) { if (!lua_istable(l, j + 1)) { LuaError(l, "incorrect argument"); } const int subargs = lua_rawlen(l, j + 1); for (int k = 0; k < subargs; ++k) { const char *type = LuaToString(l, j + 1, k + 1); ++k; const int num = LuaToNumber(l, j + 1, k + 1); const int resId = GetResourceIdByName(l, type); ai->Needed[resId] = num; } } else if (!strcmp(value, "collect")) { if (!lua_istable(l, j + 1)) { LuaError(l, "incorrect argument"); } const int subargs = lua_rawlen(l, j + 1); for (int k = 0; k < subargs; ++k) { const char *type = LuaToString(l, j + 1, k + 1); ++k; const int num = LuaToNumber(l, j + 1, k + 1); const int resId = GetResourceIdByName(l, type); ai->Collect[resId] = num; } } else if (!strcmp(value, "need-mask")) { if (!lua_istable(l, j + 1)) { LuaError(l, "incorrect argument"); } const int subargs = lua_rawlen(l, j + 1); for (int k = 0; k < subargs; ++k) { const char *type = LuaToString(l, j + 1, k + 1); const int resId = GetResourceIdByName(l, type); ai->NeededMask |= (1 << resId); } } else if (!strcmp(value, "need-supply")) { ai->NeedSupply = true; --j; } else if (!strcmp(value, "exploration")) { if (!lua_istable(l, j + 1)) { LuaError(l, "incorrect argument"); } const int subargs = lua_rawlen(l, j + 1); for (int k = 0; k < subargs; ++k) { Vec2i pos; lua_rawgeti(l, j + 1, k + 1); if (!lua_istable(l, -1) || lua_rawlen(l, -1) != 3) { LuaError(l, "incorrect argument"); } pos.x = LuaToNumber(l, -1, 1); pos.y = LuaToNumber(l, -1, 2); const int mask = LuaToNumber(l, -1, 3); lua_pop(l, 1); <API key> queue(pos, mask); ai-><API key>.push_back(queue); } } else if (!strcmp(value, "<API key>")) { ai-><API key> = LuaToNumber(l, j + 1); } else if (!strcmp(value, "<API key>")) { ai-><API key> = LuaToNumber(l, j + 1); } else if (!strcmp(value, "unit-type")) { if (!lua_istable(l, j + 1)) { LuaError(l, "incorrect argument"); } const int subargs = lua_rawlen(l, j + 1); int i = 0; if (subargs) { ai->UnitTypeRequests.resize(subargs / 2); } for (int k = 0; k < subargs; ++k) { const char *ident = LuaToString(l, j + 1, k + 1); ++k; const int count = LuaToNumber(l, j + 1, k + 1); ai->UnitTypeRequests[i].Type = UnitTypeByIdent(ident); ai->UnitTypeRequests[i].Count = count; ++i; } } else if (!strcmp(value, "upgrade")) { if (!lua_istable(l, j + 1)) { LuaError(l, "incorrect argument"); } const int subargs = lua_rawlen(l, j + 1); for (int k = 0; k < subargs; ++k) { const char *ident = LuaToString(l, j + 1, k + 1); ai->UpgradeToRequests.push_back(UnitTypeByIdent(ident)); } } else if (!strcmp(value, "research")) { if (!lua_istable(l, j + 1)) { LuaError(l, "incorrect argument"); } const int subargs = lua_rawlen(l, j + 1); for (int k = 0; k < subargs; ++k) { const char *ident = LuaToString(l, j + 1, k + 1); ai->ResearchRequests.push_back(CUpgrade::Get(ident)); } } else if (!strcmp(value, "building")) { CclParseBuildQueue(l, ai, j + 1); } else if (!strcmp(value, "repair-building")) { ai->LastRepairBuilding = LuaToNumber(l, j + 1); } else { LuaError(l, "Unsupported tag: %s" _C_ value); } } return 0; } /** ** Register CCL features for unit-type. */ void AiCclRegister() { // FIXME: Need to save memory here. // Loading all into memory isn't necessary. lua_register(Lua, "DefineAiHelper", CclDefineAiHelper); lua_register(Lua, "DefineAi", CclDefineAi); lua_register(Lua, "AiGetRace", CclAiGetRace); lua_register(Lua, "AiGetSleepCycles", CclAiGetSleepCycles); lua_register(Lua, "AiDebug", CclAiDebug); lua_register(Lua, "AiDebugPlayer", CclAiDebugPlayer); lua_register(Lua, "AiNeed", CclAiNeed); lua_register(Lua, "AiSet", CclAiSet); lua_register(Lua, "AiWait", CclAiWait); lua_register(Lua, "AiForce", CclAiForce); lua_register(Lua, "AiForceRole", CclAiForceRole); lua_register(Lua, "AiCheckForce", CclAiCheckForce); lua_register(Lua, "AiWaitForce", CclAiWaitForce); lua_register(Lua, "AiAttackWithForce", <API key>); lua_register(Lua, "AiSleep", CclAiSleep); lua_register(Lua, "AiResearch", CclAiResearch); lua_register(Lua, "AiUpgradeTo", CclAiUpgradeTo); lua_register(Lua, "AiPlayer", CclAiPlayer); lua_register(Lua, "AiSetReserve", CclAiSetReserve); lua_register(Lua, "AiSetCollect", CclAiSetCollect); lua_register(Lua, "AiDump", CclAiDump); lua_register(Lua, "DefineAiPlayer", CclDefineAiPlayer); lua_register(Lua, "AiAttackWithForces", <API key>); lua_register(Lua, "AiWaitForces", CclAiWaitForces); }
<?php defined('_JEXEC') or die(__FILE__); JFormHelper::loadFieldClass('list'); /** * Supports an HTML select list of files * * @package Joomla.Platform * @subpackage Form * @since 11.1 */ class <API key> extends JFormFieldList { /** * The form field type. * * @var string * @since 11.1 */ protected $type = 'csstextshadow'; /** * Method to get the list of files for the field options. * Specify the target directory with a directory attribute * Attributes allow an exclude mask and stripping of extensions from file name. * Default attribute may optionally be set to null (no file) or -1 (use a default). * * @return array The field option objects. * * @since 11.1 */ protected function getInput() { $options = array(); $attr .= !empty($this->class) ? ' class="' . $this->class . '"' : ''; $attr .= !empty($this->size) ? ' size="' . $this->size . '"' : ''; $attr .= $this->multiple ? ' multiple' : ''; $attr .= $this->required ? ' required aria-required="true"' : ''; $attr .= $this->autofocus ? ' autofocus' : ''; $attr .= $this->onchange ? ' onchange="'.$this->onchange.'"' : ''; $options[] = JHtml::_('select.option', '-1','None'); $border_style='auto|hidden|dotted|dashed|solid|double|groove|ridge|inset|outset|initial|inherit'; $border_style=explode('|',$border_style); foreach($border_style as $item) { $options[] = JHtml::_('select.option', $item, $item); } $options = array_merge(parent::getOptions(), $options); $html[] = JHtml::_('select.genericlist', $options, $this->name, trim($attr), 'value', 'text', $this->value, $this->id); return implode('',$html); } }
namespace Components.RoslynJit { using System; using System.Collections.Generic; public static class GeneratedContainer { public readonly struct CityInfo { public readonly string Name; public readonly string State; public const string Country = "BL"; public readonly double Latitude; public readonly double Longitude; public CityInfo( string name, in string state, double latitude, double longitude) { Name = name; State = state; Latitude = latitude; Longitude = longitude; } } public static CityInfo GetClosestCity(double lat, double lng) { double tmp; var cur = (Math.Abs(17.89618 - lat) + Math.Abs(-62.84978 - lng)); var closest = 0; switch (closest) { default: return new CityInfo("Gustavia", "00", 17.89618, -62.84978); } } } }
#include "Common.h" #include "Database/DatabaseEnv.h" #include "WorldPacket.h" #include "WorldSession.h" #include "Opcodes.h" #include "Log.h" #include "UpdateMask.h" #include "World.h" #include "ObjectMgr.h" #include "SpellMgr.h" #include "Player.h" #include "Unit.h" #include "Spell.h" #include "DynamicObject.h" #include "Group.h" #include "UpdateData.h" #include "ObjectAccessor.h" #include "Policies/Singleton.h" #include "Totem.h" #include "Creature.h" #include "Formulas.h" #include "BattleGround/BattleGround.h" #include "OutdoorPvP/OutdoorPvP.h" #include "CreatureAI.h" #include "ScriptMgr.h" #include "Util.h" #include "GridNotifiers.h" #include "GridNotifiersImpl.h" #include "Vehicle.h" #include "CellImpl.h" #include "Language.h" #include "MapManager.h" #define NULL_AURA_SLOT 0xFF /** * An array with all the different handlers for taking care of * the various aura types that are defined in AuraType. */ pAuraHandler AuraHandler[TOTAL_AURAS] = { &Aura::HandleNULL, // 0 SPELL_AURA_NONE &Aura::HandleBindSight, // 1 <API key> &Aura::HandleModPossess, // 2 <API key> &Aura::<API key>, // 3 <API key> &Aura::HandleAuraDummy, // 4 SPELL_AURA_DUMMY &Aura::HandleModConfuse, // 5 <API key> &Aura::HandleModCharm, // 6 <API key> &Aura::HandleModFear, // 7 SPELL_AURA_MOD_FEAR &Aura::HandlePeriodicHeal, // 8 <API key> &Aura::<API key>, // 9 <API key> &Aura::HandleModThreat, // 10 <API key> &Aura::HandleModTaunt, // 11 <API key> &Aura::HandleAuraModStun, // 12 SPELL_AURA_MOD_STUN &Aura::HandleModDamageDone, // 13 <API key> &Aura::<API key>, // 14 <API key> implemented in Unit::<API key> and Unit::<API key> &Aura::<API key>, // 15 <API key> implemented in Unit::DealMeleeDamage &Aura::HandleModStealth, // 16 <API key> &Aura::<API key>, // 17 <API key> implemented in Unit::<API key> &Aura::HandleInvisibility, // 18 <API key> &Aura::<API key>, // 19 <API key> &Aura::<API key>, // 20 <API key> &Aura::<API key>, // 21 <API key> &Aura::<API key>, // 22 <API key> &Aura::<API key>, // 23 <API key> &Aura::<API key>, // 24 <API key> &Aura::HandleAuraModPacify, // 25 <API key> &Aura::HandleAuraModRoot, // 26 SPELL_AURA_MOD_ROOT &Aura::<API key>, // 27 <API key> &Aura::<API key>, // 28 <API key> implement in Unit::SpellHitResult &Aura::HandleAuraModStat, // 29 SPELL_AURA_MOD_STAT &Aura::HandleAuraModSkill, // 30 <API key> &Aura::<API key>, // 31 <API key> &Aura::<API key>, // 32 <API key> &Aura::<API key>, // 33 <API key> &Aura::<API key>, // 34 <API key> &Aura::<API key>, // 35 <API key> &Aura::<API key>, // 36 <API key> &Aura::<API key>, // 37 <API key> &Aura::<API key>, // 38 <API key> &Aura::<API key>, // 39 <API key> &Aura::<API key>, // 40 <API key> &Aura::<API key>, // 41 <API key> &Aura::<API key>, // 42 <API key> implemented in Unit::<API key> and Unit::<API key> &Aura::<API key>, // 43 <API key> implemented in Unit::<API key> &Aura::<API key>, // 44 <API key> &Aura::<API key>, // 45 <API key> &Aura::HandleUnused, // 46 SPELL_AURA_46 (used in test spells 54054 and 54058, and spell 48050) (3.0.8a-3.2.2a) &Aura::<API key>, // 47 <API key> &Aura::<API key>, // 48 <API key> (Client periodic trigger spell by self (3 spells in 3.3.5a)). Implemented in pet/player cast chains. &Aura::<API key>, // 49 <API key> &Aura::<API key>, // 50 <API key> implemented in Unit::<API key> &Aura::<API key>, // 51 <API key> &Aura::<API key>, // 52 <API key> &Aura::HandlePeriodicLeech, // 53 <API key> &Aura::HandleModHitChance, // 54 <API key> &Aura::<API key>, // 55 <API key> &Aura::HandleAuraTransform, // 56 <API key> &Aura::<API key>, // 57 <API key> &Aura::<API key>, // 58 <API key> &Aura::<API key>, // 59 <API key> implemented in Unit::<API key> and Unit::<API key> &Aura::<API key>, // 60 <API key> &Aura::HandleAuraModScale, // 61 <API key> &Aura::<API key>, // 62 <API key> &Aura::HandleUnused, // 63 unused (3.0.8a-3.2.2a) old <API key> &Aura::<API key>, // 64 <API key> &Aura::<API key>, // 65 <API key> &Aura::HandleFeignDeath, // 66 <API key> &Aura::HandleAuraModDisarm, // 67 <API key> &Aura::<API key>, // 68 <API key> &Aura::HandleSchoolAbsorb, // 69 <API key> implemented in Unit::<API key> &Aura::HandleUnused, // 70 <API key> Useless, used by only one spell 41560 that has only visual effect (3.2.2a) &Aura::<API key>, // 71 <API key> &Aura::<API key>, // 72 <API key> &Aura::HandleModPowerCost, // 73 <API key> &Aura::<API key>, // 74 <API key> implemented in Unit::SpellHitResult &Aura::<API key>, // 75 <API key> implemented in WorldSession::<API key> &Aura::HandleFarSight, // 76 <API key> &Aura::<API key>, // 77 <API key> &Aura::HandleAuraMounted, // 78 SPELL_AURA_MOUNTED &Aura::<API key>, // 79 <API key> &Aura::<API key>, // 80 <API key> &Aura::<API key>, // 81 <API key> implemented in Unit::<API key> &Aura::<API key>, // 82 <API key> &Aura::<API key>, // 83 <API key> &Aura::HandleModRegen, // 84 <API key> &Aura::HandleModPowerRegen, // 85 <API key> &Aura::<API key>, // 86 <API key> &Aura::<API key>, // 87 <API key> implemented in Unit::<API key> and Unit::<API key> &Aura::<API key>, // 88 <API key> implemented in Player::RegenerateHealth &Aura::<API key>, // 89 <API key> &Aura::HandleUnused, // 90 unused (3.0.8a-3.2.2a) old <API key> &Aura::<API key>, // 91 <API key> implemented in Creature::GetAttackDistance &Aura::<API key>, // 92 <API key> &Aura::<API key>, // 93 <API key> &Aura::<API key>, // 94 <API key> implemented in Player::RegenerateAll &Aura::HandleAuraGhost, // 95 SPELL_AURA_GHOST &Aura::<API key>, // 96 <API key> implemented in Unit::SelectMagnetTarget &Aura::HandleManaShield, // 97 <API key> implemented in Unit::<API key> &Aura::HandleAuraModSkill, // 98 <API key> &Aura::<API key>, // 99 <API key> &Aura::HandleUnused, //100 <API key> obsolete 3.x? all player can see all auras now, but still have 2 spells including GM-spell (1852,2855) &Aura::<API key>, //101 <API key> &Aura::<API key>, //102 <API key> implemented in Unit::<API key> &Aura::<API key>, //103 <API key> &Aura::HandleAuraWaterWalk, //104 <API key> &Aura::<API key>, //105 <API key> &Aura::HandleAuraHover, //106 SPELL_AURA_HOVER &Aura::HandleAddModifier, //107 <API key> &Aura::HandleAddModifier, //108 <API key> &Aura::<API key>, //109 <API key> &Aura::<API key>, //110 <API key> &Aura::<API key>, //111 <API key> implemented in Unit::SelectMagnetTarget &Aura::<API key>, //112 <API key> implemented in diff functions. &Aura::<API key>, //113 <API key> implemented in Unit::<API key> &Aura::<API key>, //114 <API key> implemented in Unit::<API key> &Aura::<API key>, //115 <API key> implemented in Unit::<API key> &Aura::<API key>, //116 <API key> imppemented in Player::RegenerateAll and Player::RegenerateHealth &Aura::<API key>, //117 <API key> implemented in Unit::MagicSpellHitResult &Aura::<API key>, //118 <API key> implemented in Unit::<API key> &Aura::HandleUnused, //119 unused (3.0.8a-3.2.2a) old <API key> &Aura::<API key>, //120 <API key> &Aura::HandleAuraEmpathy, //121 SPELL_AURA_EMPATHY &Aura::<API key>, //122 <API key> &Aura::<API key>, //123 <API key> &Aura::<API key>, //124 <API key> &Aura::<API key>, //125 <API key> implemented in Unit::<API key> &Aura::<API key>, //126 <API key> implemented in Unit::<API key> &Aura::<API key>, //127 <API key> implemented in Unit::<API key> &Aura::HandleModPossessPet, //128 <API key> &Aura::<API key>, //129 <API key> &Aura::<API key>, //130 <API key> &Aura::<API key>, //131 <API key> implemented in Unit::<API key> &Aura::<API key>, //132 <API key> &Aura::<API key>, //133 <API key> &Aura::<API key>, //134 <API key> &Aura::<API key>, //135 <API key> &Aura::<API key>, //136 <API key> implemented in Unit::<API key> &Aura::<API key>, //137 <API key> &Aura::<API key>, //138 <API key> &Aura::HandleForceReaction, //139 <API key> &Aura::<API key>, //140 <API key> &Aura::<API key>, //141 <API key> &Aura::<API key>, //142 <API key> &Aura::<API key>, //143 <API key> &Aura::HandleAuraSafeFall, //144 <API key> implemented in WorldSession::<API key> &Aura::<API key>, //145 <API key> &Aura::<API key>, //146 <API key> implemented in Player::CanTameExoticPets &Aura::<API key>, //147 <API key> implemented in Unit::IsImmuneToSpell and Unit::<API key> (check part) &Aura::<API key>, //148 <API key> &Aura::<API key>, //149 <API key> implemented in Spell::Delayed and Spell::DelayedChannel &Aura::<API key>, //150 <API key> &Aura::<API key>, //151 <API key> &Aura::<API key>, //152 <API key> implemented in Creature::GetAttackDistance &Aura::<API key>, //153 <API key> implemented in Unit::<API key> &Aura::<API key>, //154 <API key> implemented in Unit::<API key> &Aura::<API key>, //155 <API key> implemented in Player::getMaxTimer &Aura::<API key>, //156 <API key> implemented in Player::<API key> &Aura::HandleUnused, //157 <API key> (single test like spell 20782, also single for 214 aura) &Aura::<API key>, //158 <API key> &Aura::<API key>, //159 <API key> implemented in Player::RewardHonor &Aura::<API key>, //160 <API key> implemented in Unit::MagicSpellHitResult &Aura::<API key>, //161 <API key> implemented in Player::RegenerateAll and Player::RegenerateHealth &Aura::HandleAuraPowerBurn, //162 <API key> &Aura::<API key>, //163 <API key> implemented in Unit::<API key> and Unit::<API key> &Aura::HandleUnused, //164 unused (3.0.8a-3.2.2a), only one test spell 10654 &Aura::<API key>, //165 <API key> implemented in Unit::<API key> &Aura::<API key>, //166 <API key> &Aura::<API key>, //167 <API key> &Aura::<API key>, //168 <API key> implemented in Unit::<API key>, Unit::<API key> &Aura::<API key>, //169 <API key> implemented in Unit::DealDamageBySchool, Unit::DoAttackDamage, Unit::SpellCriticalBonus &Aura::HandleDetectAmore, //170 <API key> different spells that ignore transformation effects &Aura::<API key>, //171 <API key> &Aura::<API key>, //172 <API key> &Aura::HandleUnused, //173 unused (3.0.8a-3.2.2a) no spells, old <API key> only for Proclaim Champion spell &Aura::<API key>, //174 <API key> implemented in Unit::<API key> &Aura::<API key>, //175 <API key> implemented in Unit::<API key> &Aura::<API key>, //176 <API key> only for Spirit of Redemption spell, die at aura end &Aura::HandleNULL, //177 <API key> (22 spells) &Aura::<API key>, //178 <API key> implemented in Unit::MagicSpellHitResult &Aura::<API key>, //179 <API key> implemented in Unit::SpellCriticalBonus &Aura::<API key>, //180 <API key> implemented in Unit::<API key> &Aura::HandleUnused, //181 unused (3.0.8a-3.2.2a) old <API key> &Aura::<API key>, //182 <API key> &Aura::<API key>, //183 <API key> only used in 28746, implemented in ThreatCalcHelper::CalcThreat &Aura::<API key>, //184 <API key> implemented in Unit::<API key> &Aura::<API key>, //185 <API key> implemented in Unit::<API key> &Aura::<API key>, //186 <API key> implemented in Unit::MagicSpellHitResult &Aura::<API key>, //187 <API key> implemented in Unit::<API key> &Aura::<API key>, //188 <API key> implemented in Unit::<API key> &Aura::HandleModRating, //189 <API key> &Aura::<API key>, //190 <API key> implemented in Player::<API key> &Aura::<API key>, //191 <API key> &Aura::<API key>, //192 <API key> &Aura::<API key>, //193 <API key> (in fact combat (any type attack) speed pct) &Aura::<API key>, //194 <API key> implement in Unit::<API key> &Aura::<API key>, //195 <API key> implement in Unit::<API key> &Aura::HandleNULL, //196 <API key> (single spell 24818 in 3.2.2a) &Aura::<API key>, //197 <API key> implemented in Unit::SpellCriticalBonus Unit::<API key> &Aura::HandleUnused, //198 unused (3.0.8a-3.2.2a) old <API key> &Aura::<API key>, //199 <API key> implemented in Unit::MagicSpellHitResult &Aura::<API key>, //200 <API key> implemented in Player::GiveXP &Aura::<API key>, //201 SPELL_AURA_FLY this aura enable flight mode... &Aura::<API key>, //202 <API key> implemented in Unit::MeleeSpellHitResult &Aura::<API key>, //203 <API key> implemented in Unit::<API key> and Unit::<API key> &Aura::<API key>, //204 <API key> implemented in Unit::<API key> and Unit::<API key> &Aura::<API key>, //205 <API key> implemented in Unit::<API key> &Aura::<API key>, //206 <API key> &Aura::<API key>, //207 <API key> &Aura::<API key>, //208 <API key> &Aura::<API key>, //209 <API key> &Aura::<API key>, //210 <API key> &Aura::<API key>, //211 <API key> &Aura::<API key>, //212 <API key> &Aura::<API key>, //213 <API key> implemented in Player::RewardRage &Aura::HandleUnused, //214 Tamed Pet Passive (single test like spell 20782, also single for 157 aura) &Aura::<API key>, //215 <API key> &Aura::<API key>, //216 <API key> &Aura::HandleUnused, //217 unused (3.0.8a-3.2.2a) &Aura::<API key>, //218 <API key> &Aura::HandleModManaRegen, //219 <API key> &Aura::<API key>, //220 <API key> &Aura::HandleNULL, //221 ignored &Aura::HandleUnused, //222 unused (3.0.8a-3.2.2a) only for spell 44586 that not used in real spell cast &Aura::HandleNULL, //223 dummy code (cast damage spell to attacker) and another dymmy (jump to another nearby raid member) &Aura::HandleUnused, //224 unused (3.0.8a-3.2.2a) &Aura::<API key>, //225 <API key> &Aura::<API key>, //226 <API key> &Aura::<API key>, //227 <API key> &Aura::<API key>, //228 <API key> &Aura::<API key>, //229 <API key> implemented in Unit::<API key> &Aura::<API key>, //230 Commanding Shout &Aura::<API key>, //231 <API key> &Aura::<API key>, //232 <API key> implement in Unit::<API key> &Aura::HandleNULL, //233 set model id to the one of the creature with id m_modifier.m_miscvalue &Aura::<API key>, //234 <API key> implement in Unit::<API key> &Aura::<API key>, //235 <API key> implement in Unit::MagicSpellHitResult &Aura::<API key>, //236 <API key> &Aura::<API key>, //237 <API key> implemented in Unit::<API key> &Aura::<API key>, //238 <API key> implemented in Unit::<API key> &Aura::HandleAuraModScale, //239 <API key> only in Noggenfogger Elixir (16595) before 2.3.0 aura 61 &Aura::<API key>, //240 <API key> &Aura::<API key>, //241 Forces the caster to move forward &Aura::HandleUnused, //242 <API key> (only 2 test spels in 3.2.2a) &Aura::<API key>, //243 <API key> &Aura::<API key>, //244 <API key> &Aura::<API key>, //245 <API key> implemented in Unit::<API key> &Aura::<API key>, //246 <API key> implemented in Unit::<API key> &Aura::<API key>, //247 <API key> target to become a clone of the caster &Aura::<API key>, //248 <API key> implemented in Unit::<API key> &Aura::<API key>, //249 <API key> &Aura::<API key>, //250 <API key> &Aura::HandleNULL, //251 <API key> &Aura::<API key>, //252 SPELL_AURA_SLOW_ALL &Aura::<API key>, //253 <API key> implemented in Unit::<API key> &Aura::HandleAuraModDisarm, //254 <API key> also disarm shield &Aura::<API key>, //255 <API key> implemented in Unit::<API key> &Aura::<API key>, //256 <API key> Use SpellClassMask for spell select &Aura::HandleNULL, //257 <API key> Use SpellClassMask for spell select &Aura::HandleNULL, //258 <API key> &Aura::<API key>, //259 <API key> implemented in Unit::SpellHealingBonus &Aura::<API key>, //260 <API key> (miscvalue = id in ScreenEffect.dbc) not required any code &Aura::HandlePhase, //261 SPELL_AURA_PHASE undetectable invisibility? implemented in Unit::<API key> &Aura::<API key>, //262 <API key> implemented in Unit::isIgnoreUnitState & Spell::CheckCast &Aura::<API key>, //263 <API key> implemented in Spell::CheckCasterAuras, lool enum IgnoreUnitState for known misc values &Aura::HandleUnused, //264 unused (3.0.8a-3.2.2a) &Aura::HandleUnused, //265 unused (3.0.8a-3.2.2a) &Aura::HandleUnused, //266 unused (3.0.8a-3.2.2a) &Aura::<API key>, //267 <API key> implemented in Unit::<API key> &Aura::<API key>, //268 <API key> &Aura::<API key>, //269 <API key> implemented in Unit::<API key> &Aura::HandleUnused, //270 <API key> (unused in 3.2.2a) &Aura::<API key>, //271 <API key> implemented in Unit::<API key> &Aura::<API key>, //272 <API key> (unclear use for aura, it used in (3.2.2a...3.3.0) in single spell 53817 that spellmode stacked and charged spell expected to be drop as stack &Aura::<API key>, //273 SPELL_AURA_X_RAY (client side implementation) &Aura::HandleNULL, //274 proc free shot? &Aura::<API key>, //275 <API key> Use SpellClassMask for spell select &Aura::HandleNULL, //276 mod damage % mechanic? &Aura::<API key>, //277 <API key> Use SpellClassMask for spell select &Aura::HandleAuraModDisarm, //278 <API key> disarm ranged weapon &Aura::HandleMirrorName, //279 <API key> target receives the casters name &Aura::<API key>, //280 <API key> &Aura::<API key>, //281 <API key> implemented in Player::RewardHonor &Aura::<API key>, //282 <API key> &Aura::<API key>, //283 <API key> implemented in Unit::<API key> &Aura::<API key>, //284 <API key> &Aura::<API key>, //285 <API key> implemented in Player::<API key> &Aura::<API key>, //286 <API key> implemented in Aura::<API key> called from Aura::PeriodicTick &Aura::<API key>, //287 <API key> implemented in Unit::MagicSpellHitResult and Unit::MeleeSpellHitResult &Aura::<API key>, //288 <API key> percent from normal parry/deflect applied to from behind attack case (single spell used 67801, also look 4.1.0 spell 97574) &Aura::HandleUnused, //289 unused (3.2.2a) &Aura::<API key>, //290 <API key> &Aura::<API key>, //291 <API key> implemented in Player::GiveXP &Aura::<API key>, //292 call stabled pet &Aura::<API key>, //293 <API key> replaces target's action bars with a predefined spellset &Aura::<API key>, //294 <API key> implemented in Player:Regenerate &Aura::HandleUnused, //295 unused (3.2.2a) &Aura::<API key>, //296 6 spells &Aura::HandleNULL, //297 1 spell (counter spell school?) &Aura::HandleUnused, //298 unused (3.2.2a) &Aura::HandleUnused, //299 unused (3.2.2a) &Aura::HandleNULL, //300 3 spells (share damage?) &Aura::HandleNULL, //301 <API key> 5 spells &Aura::HandleUnused, //302 unused (3.2.2a) &Aura::HandleNULL, //303 17 spells &Aura::<API key>, //304 <API key> &Aura::<API key>, //305 <API key> &Aura::HandleNULL, //306 1 spell &Aura::HandleNULL, //307 absorb healing? &Aura::HandleNULL, //308 new aura for hunter traps &Aura::HandleNULL, //309 absorb healing? &Aura::<API key>, //310 <API key> implemented in Unit::<API key> &Aura::HandleNULL, //311 0 spells in 3.3 &Aura::HandleNULL, //312 0 spells in 3.3 &Aura::HandleNULL, //313 0 spells in 3.3 &Aura::<API key>, //314 <API key> &Aura::HandleNULL, //315 underwater walking &Aura::HandleNULL //316 makes haste affect HOT/DOT ticks }; static AuraType const frozenAuraTypes[] = { SPELL_AURA_MOD_ROOT, SPELL_AURA_MOD_STUN, SPELL_AURA_NONE }; Aura::Aura(SpellEntry const* spellproto, SpellEffectIndex eff, int32* currentBasePoints, SpellAuraHolder* holder, Unit* target, Unit* caster, Item* castItem) : m_periodicTimer(0), m_periodicTick(0), m_removeMode(<API key>), m_effIndex(eff), m_positive(false), m_isPeriodic(false), m_isAreaAura(false), m_isPersistent(false), m_in_use(0), m_spellAuraHolder(holder) { MANGOS_ASSERT(target); MANGOS_ASSERT(spellproto && spellproto == sSpellStore.LookupEntry(spellproto->Id) && "`info` must be pointer to sSpellStore element"); m_currentBasePoints = currentBasePoints ? *currentBasePoints : spellproto-><API key>(eff); m_positive = IsPositiveEffect(spellproto, m_effIndex); m_applyTime = time(NULL); int32 damage; if (!caster) { damage = m_currentBasePoints; } else { damage = caster-><API key>(target, spellproto, m_effIndex, &m_currentBasePoints); if (!damage && castItem && castItem->GetItemSuffixFactor()) { <API key> const* item_rand_suffix = <API key>.LookupEntry(abs(castItem-><API key>())); if (item_rand_suffix) { for (int k = 0; k < 3; ++k) { <API key> const* pEnchant = <API key>.LookupEntry(item_rand_suffix->enchant_id[k]); if (pEnchant) { for (int t = 0; t < 3; ++t) { if (pEnchant->spellid[t] != spellproto->Id) continue; damage = uint32((item_rand_suffix->prefix[k] * castItem->GetItemSuffixFactor()) / 10000); break; } } if (damage) break; } } } } damage *= holder->GetStackAmount(); DEBUG_FILTER_LOG(<API key>, "Aura: construct Spellid : %u, Aura : %u Target : %d Damage : %d", spellproto->Id, spellproto->EffectApplyAuraName[eff], spellproto-><API key>[eff], damage); SetModifier(AuraType(spellproto->EffectApplyAuraName[eff]), damage, spellproto->EffectAmplitude[eff], spellproto->EffectMiscValue[eff]); Player* modOwner = caster ? caster->GetSpellModOwner() : NULL; // Apply periodic time mod if (modOwner && m_modifier.periodictime) { modOwner->ApplySpellMod(spellproto->Id, <API key>, m_modifier.periodictime); } // Start periodic on next tick or at aura apply if (!spellproto->HasAttribute(<API key>)) m_periodicTimer = m_modifier.periodictime; } Aura::~Aura() { } AreaAura::AreaAura(SpellEntry const* spellproto, SpellEffectIndex eff, int32* currentBasePoints, SpellAuraHolder* holder, Unit* target, Unit* caster, Item* castItem, uint32 originalRankSpellId) : Aura(spellproto, eff, currentBasePoints, holder, target, caster, castItem), <API key>(originalRankSpellId) { m_isAreaAura = true; // caster==NULL in constructor args if target==caster in fact Unit* caster_ptr = caster ? caster : target; m_radius = GetSpellRadius(sSpellRadiusStore.LookupEntry(spellproto->EffectRadiusIndex[m_effIndex])); if (Player* modOwner = caster_ptr->GetSpellModOwner()) { modOwner->ApplySpellMod(spellproto->Id, SPELLMOD_RADIUS, m_radius); } switch (spellproto->Effect[eff]) { case <API key>: m_areaAuraType = AREA_AURA_PARTY; break; case <API key>: m_areaAuraType = AREA_AURA_RAID; // Light's Beacon not applied to caster itself (TODO: more generic check for another similar spell if any?) if (target == caster_ptr && spellproto->Id == 53651) m_modifier.m_auraname = SPELL_AURA_NONE; break; case <API key>: m_areaAuraType = AREA_AURA_FRIEND; break; case <API key>: m_areaAuraType = AREA_AURA_ENEMY; if (target == caster_ptr) m_modifier.m_auraname = SPELL_AURA_NONE; // Do not do any effect on self break; case <API key>: m_areaAuraType = AREA_AURA_PET; break; case <API key>: m_areaAuraType = AREA_AURA_OWNER; if (target == caster_ptr) m_modifier.m_auraname = SPELL_AURA_NONE; break; default: sLog.outError("Wrong spell effect in AreaAura constructor"); MANGOS_ASSERT(false); break; } // totems are immune to any kind of area auras if (target->GetTypeId() == TYPEID_UNIT && ((Creature*)target)->IsTotem()) { m_modifier.m_auraname = SPELL_AURA_NONE; } } AreaAura::~AreaAura() { } PersistentAreaAura::PersistentAreaAura(SpellEntry const* spellproto, SpellEffectIndex eff, int32* currentBasePoints, SpellAuraHolder* holder, Unit* target, Unit* caster, Item* castItem) : Aura(spellproto, eff, currentBasePoints, holder, target, caster, castItem) { m_isPersistent = true; } PersistentAreaAura::~PersistentAreaAura() { } <API key>::<API key>(SpellEntry const* spellproto, SpellEffectIndex eff, int32* currentBasePoints, SpellAuraHolder* holder, Unit* target, Unit* caster, Item* castItem) : Aura(spellproto, eff, currentBasePoints, holder, target, caster, castItem) { if (caster) { m_castersTargetGuid = caster->GetTypeId() == TYPEID_PLAYER ? ((Player*)caster)->GetSelectionGuid() : caster->GetTargetGuid(); } } <API key>::~<API key>() { } Unit* <API key>::GetTriggerTarget() const { return sObjectAccessor.GetUnit(*(m_spellAuraHolder->GetTarget()), m_castersTargetGuid); } Aura* CreateAura(SpellEntry const* spellproto, SpellEffectIndex eff, int32* currentBasePoints, SpellAuraHolder* holder, Unit* target, Unit* caster, Item* castItem) { if (IsAreaAuraEffect(spellproto->Effect[eff])) { return new AreaAura(spellproto, eff, currentBasePoints, holder, target, caster, castItem); } uint32 triggeredSpellId = spellproto->EffectTriggerSpell[eff]; if (SpellEntry const* triggeredSpellInfo = sSpellStore.LookupEntry(triggeredSpellId)) for (int i = 0; i < MAX_EFFECT_INDEX; ++i) if (triggeredSpellInfo-><API key>[i] == TARGET_SINGLE_ENEMY) return new <API key>(spellproto, eff, currentBasePoints, holder, target, caster, castItem); return new Aura(spellproto, eff, currentBasePoints, holder, target, caster, castItem); } SpellAuraHolder* <API key>(SpellEntry const* spellproto, Unit* target, WorldObject* caster, Item* castItem) { return new SpellAuraHolder(spellproto, target, caster, castItem); } void Aura::SetModifier(AuraType t, int32 a, uint32 pt, int32 miscValue) { m_modifier.m_auraname = t; m_modifier.m_amount = a; m_modifier.m_miscvalue = miscValue; m_modifier.periodictime = pt; } void Aura::Update(uint32 diff) { if (m_isPeriodic) { m_periodicTimer -= diff; if (m_periodicTimer <= 0) // tick also at m_periodicTimer==0 to prevent lost last tick in case max m_duration == (max m_periodicTimer)*N { // update before applying (aura can be removed in TriggerSpell or PeriodicTick calls) m_periodicTimer += m_modifier.periodictime; ++m_periodicTick; // for some infinity auras in some cases can overflow and reset PeriodicTick(); } } } void AreaAura::Update(uint32 diff) { // update for the caster of the aura if (GetCasterGuid() == GetTarget()->GetObjectGuid()) { Unit* caster = GetTarget(); if (!caster->hasUnitState(UNIT_STAT_ISOLATED)) { Unit* owner = caster->GetCharmerOrOwner(); if (!owner) { owner = caster; } Spell::UnitList targets; switch (m_areaAuraType) { case AREA_AURA_PARTY: { Group* pGroup = NULL; if (owner->GetTypeId() == TYPEID_PLAYER) { pGroup = ((Player*)owner)->GetGroup(); } if (pGroup) { uint8 subgroup = ((Player*)owner)->GetSubGroup(); for (GroupReference* itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next()) { Player* Target = itr->getSource(); if (Target && Target->IsAlive() && Target->GetSubGroup() == subgroup && caster->IsFriendlyTo(Target)) { if (caster->IsWithinDistInMap(Target, m_radius)) { targets.push_back(Target); } Pet* pet = Target->GetPet(); if (pet && pet->IsAlive() && caster->IsWithinDistInMap(pet, m_radius)) { targets.push_back(pet); } } } } else { // add owner if (owner != caster && caster->IsWithinDistInMap(owner, m_radius)) { targets.push_back(owner); } // add caster's pet Unit* pet = caster->GetPet(); if (pet && caster->IsWithinDistInMap(pet, m_radius)) { targets.push_back(pet); } } break; } case AREA_AURA_RAID: { Group* pGroup = NULL; if (owner->GetTypeId() == TYPEID_PLAYER) pGroup = ((Player*)owner)->GetGroup(); if (pGroup) { for (GroupReference* itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next()) { Player* Target = itr->getSource(); if (Target && Target->IsAlive() && caster->IsFriendlyTo(Target)) { if (caster->IsWithinDistInMap(Target, m_radius)) targets.push_back(Target); Pet* pet = Target->GetPet(); if (pet && pet->IsAlive() && caster->IsWithinDistInMap(pet, m_radius)) targets.push_back(pet); } } } else { // add owner if (owner != caster && caster->IsWithinDistInMap(owner, m_radius)) targets.push_back(owner); // add caster's pet Unit* pet = caster->GetPet(); if (pet && caster->IsWithinDistInMap(pet, m_radius)) targets.push_back(pet); } break; } case AREA_AURA_FRIEND: { MaNGOS::<API key> u_check(caster, m_radius); MaNGOS::UnitListSearcher<MaNGOS::<API key>> searcher(targets, u_check); Cell::VisitAllObjects(caster, searcher, m_radius); break; } case AREA_AURA_ENEMY: { MaNGOS::<API key> u_check(caster, m_radius); // No GetCharmer in searcher MaNGOS::UnitListSearcher<MaNGOS::<API key>> searcher(targets, u_check); Cell::VisitAllObjects(caster, searcher, m_radius); break; } case AREA_AURA_OWNER: case AREA_AURA_PET: { if (owner != caster && caster->IsWithinDistInMap(owner, m_radius)) { targets.push_back(owner); } break; } } for (Spell::UnitList::iterator tIter = targets.begin(); tIter != targets.end(); ++tIter) { // flag for selection is need apply aura to current iteration target bool apply = true; SpellEntry const* actualSpellInfo; if (GetCasterGuid() == (*tIter)->GetObjectGuid()) // if caster is same as target then no need to change rank of the spell { actualSpellInfo = GetSpellProto(); } else // use spell id according level of the target { actualSpellInfo = sSpellMgr.<API key>(GetSpellProto(), (*tIter)->getLevel()); } if (!actualSpellInfo) { continue; } Unit::<API key> spair = (*tIter)-><API key>(actualSpellInfo->Id); // we need ignore present caster self applied are auras sometime // in cases if this only auras applied for spell effect for (Unit::SpellAuraHolderMap::const_iterator i = spair.first; i != spair.second; ++i) { if (i->second->IsDeleted()) { continue; } Aura* aur = i->second-><API key>(m_effIndex); if (!aur) { continue; } switch (m_areaAuraType) { case AREA_AURA_ENEMY: // non caster self-casted auras (non stacked) if (aur->GetModifier()->m_auraname != SPELL_AURA_NONE) apply = false; break; case AREA_AURA_RAID: // non caster self-casted auras (stacked from diff. casters) if (aur->GetModifier()->m_auraname != SPELL_AURA_NONE || i->second->GetCasterGuid() == GetCasterGuid()) apply = false; break; default: // in generic case not allow stacking area auras apply = false; break; } if (!apply) break; } if (!apply) { continue; } // Skip some targets (TODO: Might require better checks, also unclear how the actual caster must/can be handled) if (actualSpellInfo->HasAttribute(<API key>) && (*tIter)->GetTypeId() != TYPEID_PLAYER) { continue; } int32 actualBasePoints = m_currentBasePoints; // recalculate basepoints for lower rank (all AreaAura spell not use custom basepoints?) if (actualSpellInfo != GetSpellProto()) { actualBasePoints = actualSpellInfo-><API key>(m_effIndex); } SpellAuraHolder* holder = (*tIter)->GetSpellAuraHolder(actualSpellInfo->Id, GetCasterGuid()); bool addedToExisting = true; if (!holder) { holder = <API key>(actualSpellInfo, (*tIter), caster); addedToExisting = false; } holder->SetAuraDuration(GetAuraDuration()); AreaAura* aur = new AreaAura(actualSpellInfo, m_effIndex, &actualBasePoints, holder, (*tIter), caster, NULL, GetSpellProto()->Id); holder->AddAura(aur, m_effIndex); if (addedToExisting) { (*tIter)->AddAuraToModList(aur); holder->SetInUse(true); aur->ApplyModifier(true, true); holder->SetInUse(false); } else { (*tIter)->AddSpellAuraHolder(holder); } } } Aura::Update(diff); } else // aura at non-caster { Unit* caster = GetCaster(); Unit* target = GetTarget(); uint32 originalRankSpellId = <API key> ? <API key> : GetId(); // caster may have different spell id if target has lower level Aura::Update(diff); // remove aura if out-of-range from caster (after teleport for example) // or caster is isolated or caster no longer has the aura // or caster is (no longer) friendly bool needFriendly = (m_areaAuraType == AREA_AURA_ENEMY ? false : true); if (!caster || caster->hasUnitState(UNIT_STAT_ISOLATED) || !caster->HasAura(originalRankSpellId, GetEffIndex()) || !caster->IsWithinDistInMap(target, m_radius) || caster->IsFriendlyTo(target) != needFriendly ) { target-><API key>(GetId(), GetEffIndex(), GetCasterGuid()); } else if (m_areaAuraType == AREA_AURA_PARTY) // check if in same sub group { // not check group if target == owner or target == pet if (caster-><API key>() != target->GetObjectGuid() && caster->GetObjectGuid() != target-><API key>()) { Player* check = caster-><API key>(); Group* pGroup = check ? check->GetGroup() : NULL; if (pGroup) { Player* checkTarget = target-><API key>(); if (!checkTarget || !pGroup->SameSubGroup(check, checkTarget)) { target-><API key>(GetId(), GetEffIndex(), GetCasterGuid()); } } else { target-><API key>(GetId(), GetEffIndex(), GetCasterGuid()); } } } else if (m_areaAuraType == AREA_AURA_RAID) // Check if on same raid group { // not check group if target == owner or target == pet if (caster-><API key>() != target->GetObjectGuid() && caster->GetObjectGuid() != target-><API key>()) { Player* check = caster-><API key>(); Group* pGroup = check ? check->GetGroup() : NULL; if (pGroup) { Player* checkTarget = target-><API key>(); if (!checkTarget || !checkTarget->GetGroup() || checkTarget->GetGroup()->GetId() != pGroup->GetId()) target-><API key>(GetId(), GetEffIndex(), GetCasterGuid()); } else target-><API key>(GetId(), GetEffIndex(), GetCasterGuid()); } } else if (m_areaAuraType == AREA_AURA_PET || m_areaAuraType == AREA_AURA_OWNER) { if (target->GetObjectGuid() != caster-><API key>()) { target-><API key>(GetId(), GetEffIndex(), GetCasterGuid()); } } } } void PersistentAreaAura::Update(uint32 diff) { bool remove = false; // remove the aura if its caster or the dynamic object causing it was removed // or if the target moves too far from the dynamic object if (Unit* caster = GetCaster()) { DynamicObject* dynObj = caster->GetDynObject(GetId(), GetEffIndex()); if (dynObj) { if (!GetTarget()->IsWithinDistInMap(dynObj, dynObj->GetRadius())) { remove = true; dynObj->RemoveAffected(GetTarget()); // let later reapply if target return to range } } else { remove = true; } } else { remove = true; } Aura::Update(diff); if (remove) { GetTarget()->RemoveAura(GetId(), GetEffIndex()); } } void Aura::ApplyModifier(bool apply, bool Real) { AuraType aura = m_modifier.m_auraname; GetHolder()->SetInUse(true); SetInUse(true); if (aura < TOTAL_AURAS) { (*this.*AuraHandler [aura])(apply, Real); } SetInUse(false); GetHolder()->SetInUse(false); } bool Aura::isAffectedOnSpell(SpellEntry const* spell) const { return spell->IsFitToFamily(SpellFamily(GetSpellProto()->SpellFamilyName), <API key>()); } bool Aura::CanProcFrom(SpellEntry const* spell, uint32 /*procFlag*/, uint32 EventProcEx, uint32 procEx, bool active, bool useClassMask) const { // Check EffectClassMask ClassFamilyMask const& mask = <API key>(); // allow proc for modifier auras with charges if (<API key>(GetSpellProto(), GetEffIndex(), spell)) { if (GetHolder()->GetAuraCharges() > 0) { if (procEx != PROC_EX_CAST_END && EventProcEx == PROC_EX_NONE) return false; } } else if (EventProcEx == PROC_EX_NONE && procEx == PROC_EX_CAST_END) return false; // if no class mask defined, or spell_proc_event has SpellFamilyName=0 - allow proc if (!useClassMask || !mask) { if (!(EventProcEx & <API key>)) { // Check for extra req (if none) and hit/crit if (EventProcEx == PROC_EX_NONE) { // No extra req, so can trigger only for active (damage/healing present) and hit/crit if (((procEx & (PROC_EX_NORMAL_HIT | <API key>)) && active) || procEx == PROC_EX_CAST_END) { return true; } else { return false; } } else // Passive spells hits here only if resist/reflect/immune/evade { // Passive spells can`t trigger if need hit (exclude cases when procExtra include non-active flags) if ((EventProcEx & (PROC_EX_NORMAL_HIT | <API key>) & procEx) && !active) { return false; } } } return true; } else { // SpellFamilyName check is performed in SpellMgr::<API key> and it is done once for whole holder // note: SpellFamilyName is not checked if no spell_proc_event is defined return mask.IsFitToFamilyMask(spell->SpellFamilyFlags); } } void Aura::<API key>(Unit* target, bool owner_mode) { // we need store cast item guids for self casted spells // expected that not exist permanent auras from stackable auras from different items std::map<uint32, ObjectGuid> affectedSelf; std::set<uint32> affectedAuraCaster; for (Unit::SpellAuraHolderMap::const_iterator itr = target-><API key>().begin(); itr != target-><API key>().end(); ++itr) { // permanent passive or permanent area aura // passive spells can be affected only by own or owner spell mods) if ((itr->second->IsPermanent() && ((owner_mode && itr->second->IsPassive()) || itr->second->IsAreaAura())) && // non deleted and not same aura (any with same spell id) !itr->second->IsDeleted() && itr->second->GetId() != GetId() && // and affected by aura isAffectedOnSpell(itr->second->GetSpellProto())) { // only applied by self or aura caster if (itr->second->GetCasterGuid() == target->GetObjectGuid()) affectedSelf[itr->second->GetId()] = itr->second->GetCastItemGuid(); else if (itr->second->GetCasterGuid() == GetCasterGuid()) affectedAuraCaster.insert(itr->second->GetId()); } } if (!affectedSelf.empty()) { Player* pTarget = target->GetTypeId() == TYPEID_PLAYER ? (Player*)target : NULL; for (std::map<uint32, ObjectGuid>::const_iterator map_itr = affectedSelf.begin(); map_itr != affectedSelf.end(); ++map_itr) { Item* item = pTarget && map_itr->second ? pTarget->GetItemByGuid(map_itr->second) : NULL; target-><API key>(map_itr->first); target->CastSpell(target, map_itr->first, true, item); } } if (!affectedAuraCaster.empty()) { Unit* caster = GetCaster(); for (std::set<uint32>::const_iterator set_itr = affectedAuraCaster.begin(); set_itr != affectedAuraCaster.end(); ++set_itr) { target-><API key>(*set_itr); if (caster) caster->CastSpell(GetTarget(), *set_itr, true); } } } struct <API key> { explicit <API key>(Aura* _aura) : aura(_aura) {} void operator()(Unit* unit) const { aura-><API key>(unit, true); } Aura* aura; }; void Aura::<API key>() { // not reapply spell mods with charges (use original value because processed and at remove) if (GetSpellProto()->procCharges) { return; } // not reapply some spell mods ops (mostly speedup case) switch (m_modifier.m_miscvalue) { case SPELLMOD_DURATION: case SPELLMOD_CHARGES: case <API key>: case <API key>: case SPELLMOD_COOLDOWN: case SPELLMOD_COST: case <API key>: case <API key>: return; } // reapply talents to own passive persistent auras <API key>(GetTarget(), true); // re-apply talents/passives/area auras applied to pet/totems (it affected by player spellmods) GetTarget()-><API key>(<API key>(this), CONTROLLED_PET | CONTROLLED_TOTEMS); // re-apply talents/passives/area auras applied to group members (it affected by player spellmods) if (Group* group = ((Player*)GetTarget())->GetGroup()) for (GroupReference* itr = group->GetFirstMember(); itr != NULL; itr = itr->next()) if (Player* member = itr->getSource()) if (member != GetTarget() && member->IsInMap(GetTarget())) <API key>(member, false); } /*** BASIC AURA FUNCTION ***/ void Aura::HandleAddModifier(bool apply, bool Real) { if (GetTarget()->GetTypeId() != TYPEID_PLAYER || !Real) { return; } if (m_modifier.m_miscvalue >= MAX_SPELLMOD) { return; } if (apply) { SpellEntry const* spellProto = GetSpellProto(); // Add custom charges for some mod aura switch (spellProto->Id) { case 17941: // Shadow Trance case 22008: // Netherwind Focus case 31834: // Light's Grace case 34754: // Clearcasting case 34936: // Backlash case 44401: // Missile Barrage case 48108: // Hot Streak case 51124: // Killing Machine case 54741: // Firestarter case 57761: // Fireball! case 64823: // Elune's Wrath (Balance druid t8 set GetHolder()->SetAuraCharges(1); break; } // Everlasting Affliction, overwrite wrong data, if will need more better restore support of spell_affect table if (spellProto->SpellFamilyName == SPELLFAMILY_WARLOCK && spellProto->SpellIconID == 3169) { // Corruption and Unstable Affliction // TODO: drop when override will be possible SpellEntry* entry = const_cast<SpellEntry*>(spellProto); entry-><API key>[GetEffIndex()].Flags = UI64LIT(0x0000010000000002); } // Improved Flametongue Weapon, overwrite wrong data, maybe time re-add table else if (spellProto->Id == 37212) { // Flametongue Weapon (Passive) // TODO: drop when override will be possible SpellEntry* entry = const_cast<SpellEntry*>(spellProto); entry-><API key>[GetEffIndex()].Flags = UI64LIT(0x0000000000200000); } } ((Player*)GetTarget())->AddSpellMod(this, apply); <API key>(); } void Aura::TriggerSpell() { ObjectGuid casterGUID = GetCasterGuid(); Unit* triggerTarget = GetTriggerTarget(); if (!casterGUID || !triggerTarget) { return; } // generic casting code with custom spells and target/caster customs uint32 trigger_spell_id = GetSpellProto()->EffectTriggerSpell[m_effIndex]; SpellEntry const* triggeredSpellInfo = sSpellStore.LookupEntry(trigger_spell_id); SpellEntry const* auraSpellInfo = GetSpellProto(); uint32 auraId = auraSpellInfo->Id; Unit* target = GetTarget(); Unit* triggerCaster = triggerTarget; WorldObject* triggerTargetObject = NULL; // specific code for cases with no trigger spell provided in field if (triggeredSpellInfo == NULL) { switch (auraSpellInfo->SpellFamilyName) { case SPELLFAMILY_GENERIC: { switch (auraId) { case 812: // Periodic Mana Burn { trigger_spell_id = 25779; // Mana Burn if (GetTarget()->GetTypeId() != TYPEID_UNIT) return; triggerTarget = ((Creature*)GetTarget())-><API key>(<API key>, 0, trigger_spell_id, <API key>); if (!triggerTarget) return; break; } // // Polymorphic Ray // case 6965: break; case 9712: // Thaumaturgy Channel if (Unit* caster = GetCaster()) caster->CastSpell(caster, 21029, true); return; // // Egan's Blaster // case 17368: break; // // Haunted // case 18347: break; // // Ranshalla Waiting // case 18953: break; // // Inferno // case 19695: break; // // Frostwolf Muzzle DND // case 21794: break; // // Alterac Ram Collar DND // case 21866: break; // // Celebras Waiting // case 21916: break; case 23170: // Brood Affliction: Bronze { target->CastSpell(target, 23171, true, NULL, this); return; } case 23184: // Mark of Frost case 25041: // Mark of Nature case 37125: // Mark of Death { std::list<Player*> targets; // spells existed in 1.x.x; 23183 - mark of frost; 25042 - mark of nature; both had radius of 100.0 yards in 1.x.x DBC // spells are used by Azuregos and the Emerald dragons in order to put a stun debuff on the players which resurrect during the encounter // in order to implement the missing spells we need to make a grid search for hostile players and check their auras; if they are marked apply debuff // spell 37127 used for the Mark of Death, is used server side, so it needs to be implemented here uint32 markSpellId = 0; uint32 debuffSpellId = 0; switch (auraId) { case 23184: markSpellId = 23182; debuffSpellId = 23186; break; case 25041: markSpellId = 25040; debuffSpellId = 25043; break; case 37125: markSpellId = 37128; debuffSpellId = 37131; break; } MaNGOS::<API key> u_check(GetTarget(), 100.0f, markSpellId); MaNGOS::PlayerListSearcher<MaNGOS::<API key> > checker(targets, u_check); Cell::VisitWorldObjects(GetTarget(), checker, 100.0f); for (std::list<Player*>::iterator itr = targets.begin(); itr != targets.end(); ++itr) (*itr)->CastSpell((*itr), debuffSpellId, true, NULL, NULL, casterGUID); return; } case 23493: // Restoration { uint32 heal = triggerTarget->GetMaxHealth() / 10; uint32 absorb = 0; triggerTarget->CalculateHealAbsorb(heal, &absorb); triggerTarget->DealHeal(triggerTarget, heal - absorb, auraSpellInfo, false, absorb); if (int32 mana = triggerTarget->GetMaxPower(POWER_MANA)) { mana /= 10; triggerTarget->EnergizeBySpell(triggerTarget, 23493, mana, POWER_MANA); } return; } // // Stoneclaw Totem Passive TEST // case 23792: break; // // Axe Flurry // case 24018: break; case 24210: // Mark of Arlokk { // Replacement for (classic) spell 24211 (doesn't exist anymore) std::list<Creature*> lList; // Search for all Zulian Prowler in range MaNGOS::<API key> check(triggerTarget, 15101, 15.0f); MaNGOS::<API key><MaNGOS::<API key>> searcher(lList, check); Cell::VisitGridObjects(triggerTarget, searcher, 15.0f); for (std::list<Creature*>::const_iterator itr = lList.begin(); itr != lList.end(); ++itr) if ((*itr)->IsAlive()) (*itr)->AddThreat(triggerTarget, float(5000)); return; } // // Restoration // case 24379: break; // // Happy Pet // case 24716: break; case 24780: // Dream Fog { // Note: In 1.12 triggered spell 24781 still exists, need to script dummy effect for this spell then // Select an unfriendly enemy in 100y range and attack it if (target->GetTypeId() != TYPEID_UNIT) return; ThreatList const& tList = target->GetThreatManager().getThreatList(); for (ThreatList::const_iterator itr = tList.begin(); itr != tList.end(); ++itr) { Unit* pUnit = target->GetMap()->GetUnit((*itr)->getUnitGuid()); if (pUnit && target->GetThreatManager().getThreat(pUnit)) target->GetThreatManager().modifyThreatPercent(pUnit, -100); } if (Unit* pEnemy = target-><API key>(target->getVictim(), 100.0f)) ((Creature*)target)->AI()->AttackStart(pEnemy); return; } // // Cannon Prep // case 24832: break; case 24834: // Shadow Bolt Whirl { uint32 spellForTick[8] = { 24820, 24821, 24822, 24823, 24835, 24836, 24837, 24838 }; uint32 tick = (GetAuraTicks() + 7) % 8; // casted in left/right (but triggered spell have wide forward cone) float forward = target->GetOrientation(); if (tick <= 3) { target->SetOrientation(forward + 0.75f * M_PI_F - tick * M_PI_F / 8); } // Left else { target->SetOrientation(forward - 0.75f * M_PI_F + (8 - tick) * M_PI_F / 8); } // Right triggerTarget->CastSpell(triggerTarget, spellForTick[tick], true, NULL, this, casterGUID); target->SetOrientation(forward); return; } // // Stink Trap // case 24918: break; // // Agro Drones // case 25152: break; case 25371: // Consume { int32 bpDamage = triggerTarget->GetMaxHealth() * 10 / 100; triggerTarget->CastCustomSpell(triggerTarget, 25373, &bpDamage, NULL, NULL, true, NULL, this, casterGUID); return; } // // Pain Spike // case 25572: break; case 26009: // Rotate 360 case 26136: // Rotate -360 { float newAngle = target->GetOrientation(); if (auraId == 26009) { newAngle += M_PI_F / 40; } else { newAngle -= M_PI_F / 40; } newAngle = MapManager::<API key>(newAngle); target->SetFacingTo(newAngle); target->CastSpell(target, 26029, true); return; } // // Consume // case 26196: break; // // Berserk // case 26615: break; // // Defile // case 27177: break; // // Teleport: IF/UC // case 27601: break; // // Five Fat Finger Exploding Heart Technique // case 27673: break; // // Nitrous Boost // case 27746: break; // // Steam Tank Passive // case 27747: break; case 27808: // Frost Blast { int32 bpDamage = triggerTarget->GetMaxHealth() * 26 / 100; triggerTarget->CastCustomSpell(triggerTarget, 29879, &bpDamage, NULL, NULL, true, NULL, this, casterGUID); return; } // Detonate Mana case 27819: { // 33% Mana Burn on normal mode, 50% on heroic mode int32 bpDamage = (int32)triggerTarget->GetPower(POWER_MANA) / (triggerTarget->GetMap()->GetDifficulty() ? 2 : 3); triggerTarget->ModifyPower(POWER_MANA, -bpDamage); triggerTarget->CastCustomSpell(triggerTarget, 27820, &bpDamage, NULL, NULL, true, NULL, this, triggerTarget->GetObjectGuid()); return; } // // Controller Timer // case 28095: break; // Stalagg Chain and Feugen Chain case 28096: case 28111: { // X-Chain is casted by Tesla to X, so: caster == Tesla, target = X Unit* pCaster = GetCaster(); if (pCaster && pCaster->GetTypeId() == TYPEID_UNIT && !pCaster->IsWithinDistInMap(target, 60.0f)) { pCaster-><API key>(true); ((Creature*)pCaster)->SetInCombatWithZone(); // Stalagg Tesla Passive or Feugen Tesla Passive pCaster->CastSpell(pCaster, auraId == 28096 ? 28097 : 28109, true, NULL, NULL, target->GetObjectGuid()); } return; } // Stalagg Tesla Passive and Feugen Tesla Passive case 28097: case 28109: { // X-Tesla-Passive is casted by Tesla on Tesla with original caster X, so: caster = X, target = Tesla Unit* pCaster = GetCaster(); if (pCaster && pCaster->GetTypeId() == TYPEID_UNIT) { if (pCaster->getVictim() && !pCaster->IsWithinDistInMap(target, 60.0f)) { if (Unit* pTarget = ((Creature*)pCaster)-><API key>(<API key>, 0)) target->CastSpell(pTarget, 28099, false);// Shock } else { // "Evade" target-><API key>(auraId); target->DeleteThreatList(); target->CombatStop(true); // Recast chain (Stalagg Chain or Feugen Chain target->CastSpell(pCaster, auraId == 28097 ? 28096 : 28111, false); } } return; } // // Mark of Didier // case 28114: break; // // Communique Timer, camp // case 28346: break; // // Icebolt // case 28522: break; // // Silithyst // case 29519: break; case 29528: // Inoculate Nestlewood Owlkin // prevent error reports in case ignored player target if (triggerTarget->GetTypeId() != TYPEID_UNIT) return; break; // // Overload // case 29768: break; // // Return Fire // case 29788: break; // // Return Fire // case 29793: break; // // Return Fire // case 29794: break; // // Guardian of Icecrown Passive // case 29897: break; case 29917: // Feed Captured Animal trigger_spell_id = 29916; break; // // Flame Wreath // case 29946: break; // // Flame Wreath // case 29947: break; // // Mind Exhaustion Passive // case 30025: break; // // Nether Beam - Serenity // case 30401: break; case 30427: // Extract Gas { Unit* caster = GetCaster(); if (!caster) return; // move loot to player inventory and despawn target if (caster->GetTypeId() == TYPEID_PLAYER && triggerTarget->GetTypeId() == TYPEID_UNIT && ((Creature*)triggerTarget)->GetCreatureInfo()->CreatureType == <API key>) { Player* player = (Player*)caster; Creature* creature = (Creature*)triggerTarget; // missing lootid has been reported on startup - just return if (!creature->GetCreatureInfo()->SkinningLootId) return; player->AutoStoreLoot(creature, creature->GetCreatureInfo()->SkinningLootId, <API key>, true); creature->ForcedDespawn(); } return; } case 30576: // Quake trigger_spell_id = 30571; break; // // Burning Maul // case 30598: break; // // Regeneration // case 30799: // case 30800: // case 30801: // break; // // Despawn Self - Smoke cloud // case 31269: break; // // Time Rift Periodic // case 31320: break; // // Corrupt Medivh // case 31326: break; case 31347: // Doom { target->CastSpell(target, 31350, true); target->DealDamage(target, target->GetHealth(), NULL, DIRECT_DAMAGE, <API key>, NULL, false); return; } case 31373: // Spellcloth { // Summon Elemental after create item triggerTarget->SummonCreature(17870, 0.0f, 0.0f, 0.0f, triggerTarget->GetOrientation(), <API key>, 0); return; } // // Bloodmyst Tesla // case 31611: break; case 31944: // Doomfire { int32 damage = m_modifier.m_amount * ((GetAuraDuration() + m_modifier.periodictime) / GetAuraMaxDuration()); triggerTarget->CastCustomSpell(triggerTarget, 31969, &damage, NULL, NULL, true, NULL, this, casterGUID); return; } // // Teleport Test // case 32236: break; // // Earthquake // case 32686: break; // // Possess // case 33401: break; // // Draw Shadows // case 33563: break; // // Murmur's Touch // case 33711: break; case 34229: // Flame Quills { // cast 24 spells 34269-34289, 34314-34316 for (uint32 spell_id = 34269; spell_id != 34290; ++spell_id) triggerTarget->CastSpell(triggerTarget, spell_id, true, NULL, this, casterGUID); for (uint32 spell_id = 34314; spell_id != 34317; ++spell_id) triggerTarget->CastSpell(triggerTarget, spell_id, true, NULL, this, casterGUID); return; } // // Gravity Lapse // case 34480: break; // // Tornado // case 34683: break; // // Frostbite Rotate // case 34748: break; // // Arcane Flurry // case 34821: break; // // Interrupt Shutdown // case 35016: break; // // Interrupt Shutdown // case 35176: break; // // Inferno // case 35268: break; // // Salaadin's Tesla // case 35515: break; // // Ethereal Channel (Red) // case 35518: break; // // Nether Vapor // case 35879: break; // // Dark Portal Storm // case 36018: break; // // Burning Maul // case 36056: break; // // Living Grove Defender Lifespan // case 36061: break; // // Professor Dabiri Talks // case 36064: break; // // Kael Gaining Power // case 36091: break; // // They Must Burn Bomb Aura // case 36344: break; // // They Must Burn Bomb Aura (self) // case 36350: break; // // Stolen Ravenous Ravager Egg // case 36401: break; // // Activated Cannon // case 36410: break; // // Stolen Ravenous Ravager Egg // case 36418: break; // // Enchanted Weapons // case 36510: break; // // Cursed Scarab Periodic // case 36556: break; // // Cursed Scarab Despawn Periodic // case 36561: break; case 36573: // Vision Guide { if (GetAuraTicks() == 10 && target->GetTypeId() == TYPEID_PLAYER) { ((Player*)target)-><API key>(10525); target-><API key>(36573); } return; } // // Cannon Charging (platform) // case 36785: break; // // Cannon Charging (self) // case 36860: break; case 37027: // Remote Toy trigger_spell_id = 37029; break; // // Mark of Death // case 37125: break; // // Arcane Flurry // case 37268: break; case 37429: // Spout (left) case 37430: // Spout (right) { float newAngle = target->GetOrientation(); if (auraId == 37429) newAngle += 2 * M_PI_F / 100; else newAngle -= 2 * M_PI_F / 100; newAngle = MapManager::<API key>(newAngle); target->SetFacingTo(newAngle); target->CastSpell(target, 37433, true); return; } // // Karazhan - Chess NPC AI, Snapshot timer // case 37440: break; // // Karazhan - Chess NPC AI, action timer // case 37504: break; // // Karazhan - Chess: Is Square OCCUPIED aura (DND) // case 39400: break; // // Banish // case 37546: break; // // Shriveling Gaze // case 37589: break; // // Fake Aggro Radius (2 yd) // case 37815: break; // // Corrupt Medivh // case 37853: break; case 38495: // Eye of Grillok { target->CastSpell(target, 38530, true); return; } case 38554: // Absorb Eye of Grillok (Zezzak's Shard) { if (target->GetTypeId() != TYPEID_UNIT) return; if (Unit* caster = GetCaster()) caster->CastSpell(caster, 38495, true, NULL, this); else return; Creature* creatureTarget = (Creature*)target; creatureTarget->ForcedDespawn(); return; } // // Magic Sucker Device timer // case 38672: break; // // Tomb Guarding Charging // case 38751: break; // // Murmur's Touch // case 38794: break; case 39105: // Activate Nether-wraith Beacon (31742 Nether-wraith Beacon item) { float fX, fY, fZ; triggerTarget->GetClosePoint(fX, fY, fZ, triggerTarget-><API key>(), 20.0f); triggerTarget->SummonCreature(22408, fX, fY, fZ, triggerTarget->GetOrientation(), <API key>, 0); return; } // // Drain World Tree Visual // case 39140: break; // // Quest - Dustin's Undead Dragon Visual aura // case 39259: break; // // Hellfire - The Exorcism, Jules releases darkness, aura // case 39306: break; // // Inferno // case 39346: break; // // Enchanted Weapons // case 39489: break; // // Shadow Bolt Whirl // case 39630: break; // // Shadow Bolt Whirl // case 39634: break; // // Shadow Inferno // case 39645: break; case 39857: // Tear of Azzinoth Summon Channel - it's not really supposed to do anything,and this only prevents the console spam trigger_spell_id = 39856; break; // // Soulgrinder Ritual Visual (Smashed) // case 39974: break; // // Simon Game Pre-game timer // case 40041: break; // // Knockdown Fel Cannon: The Aggro Check Aura // case 40113: break; // // Spirit Lance // case 40157: break; case 40398: // Demon Transform 2 switch (GetAuraTicks()) { case 1: if (target->HasAura(40506)) target-><API key>(40506); else trigger_spell_id = 40506; break; case 2: trigger_spell_id = 40510; break; } break; case 40511: // Demon Transform 1 trigger_spell_id = 40398; break; // // Ancient Flames // case 40657: break; // // Ethereal Ring Cannon: Cannon Aura // case 40734: break; // // Cage Trap // case 40760: break; // // Random Periodic // case 40867: break; // // Prismatic Shield // case 40879: break; // // Aura of Desire // case 41350: break; // // Dementia // case 41404: break; // // Chaos Form // case 41629: break; // // Alert Drums // case 42177: break; // // Spout // case 42581: break; // // Spout // case 42582: break; // // Return to the Spirit Realm // case 44035: break; // // Curse of Boundless Agony // case 45050: break; // // Earthquake // case 46240: break; case 46736: // Personalized Weather trigger_spell_id = 46737; break; // // Stay Submerged // case 46981: break; // // Dragonblight Ram // case 47015: break; // // Party G.R.E.N.A.D.E. // case 51510: break; // // Horseman Abilities // case 52347: break; // // GPS (Greater drake Positioning System) // case 53389: break; // // WotLK Prologue Frozen Shade Summon Aura // case 53459: break; // // WotLK Prologue Frozen Shade Speech // case 53460: break; // // WotLK Prologue Dual-plagued Brain Summon Aura // case 54295: break; // // WotLK Prologue Dual-plagued Brain Speech // case 54299: break; // // Rotate 360 (Fast) // case 55861: break; // // Shadow Sickle // case 56702: break; // // Portal Periodic // case 58008: break; // // Destroy Door Seal // case 58040: break; // // Draw Magic // case 58185: break; case 58886: // Food { if (GetAuraTicks() != 1) return; uint32 randomBuff[5] = {57288, 57139, 57111, 57286, 57291}; trigger_spell_id = urand(0, 1) ? 58891 : randomBuff[urand(0, 4)]; break; } // // Shadow Sickle // case 59103: break; // // Time Bomb // case 59376: break; // // Whirlwind Visual // case 59551: break; // // Hearstrike // case 59783: break; // // Z Check // case 61678: break; // // IsDead Check // case 61976: break; // // Start the Engine // case 62432: break; // // Enchanted Broom // case 62571: break; // // Mulgore Hatchling // case 62586: break; case 62679: // Durotar Scorpion trigger_spell_id = auraSpellInfo-><API key>(m_effIndex); break; // // Fighting Fish // case 62833: break; // // Shield Level 1 // case 63130: break; // // Shield Level 2 // case 63131: break; // // Shield Level 3 // case 63132: break; // // Food case 64345: // Remove Player from Phase target-><API key>(SPELL_AURA_PHASE); return; // case 64445: break; // // Food // case 65418: break; // // Food // case 65419: break; // // Food // case 65420: break; // // Food // case 65421: break; // // Food // case 65422: break; // // Rolling Throw // case 67546: break; case 69012: // Explosive Barrage { // Summon an Exploding Orb for each player in combat with the caster ThreatList const& threatList = target->GetThreatManager().getThreatList(); for (ThreatList::const_iterator itr = threatList.begin(); itr != threatList.end(); ++itr) { if (Unit* expectedTarget = target->GetMap()->GetUnit((*itr)->getUnitGuid())) { if (expectedTarget->GetTypeId() == TYPEID_PLAYER) target->CastSpell(expectedTarget, 69015, true); } } return; } // // Gunship Cannon Fire // case 70017: break; // // Ice Tomb // case 70157: break; // // Mana Barrier // HANDLED IN SD3! // case 70842: break; // // Summon Timer: Suppresser // case 70912: break; // // Aura of Darkness // case 71110: break; // // Aura of Darkness // case 71111: break; // // Ball of Flames Visual // case 71706: break; // // Summon Broken Frostmourne // case 74081: break; default: break; } break; } case SPELLFAMILY_MAGE: { switch (auraId) { case 66: // Invisibility // Here need periodic trigger reducing threat spell (or do it manually) return; default: break; } break; } // case SPELLFAMILY_WARRIOR: // switch(auraId) // // Wild Magic // case 23410: break; // // Corrupted Totems // case 23425: break; // default: // break; // break; // case SPELLFAMILY_PRIEST: // switch(auraId) // // Blue Beam // case 32930: break; // // Fury of the Dreghood Elders // case 35460: break; // default: // break; // break; case SPELLFAMILY_HUNTER: { switch (auraId) { case 53302: // Sniper training case 53303: case 53304: if (triggerTarget->GetTypeId() != TYPEID_PLAYER) return; // Reset reapply counter at move if (((Player*)triggerTarget)->isMoving()) { m_modifier.m_amount = 6; return; } // We are standing at the moment if (m_modifier.m_amount > 0) { --m_modifier.m_amount; return; } // select rank of buff switch (auraId) { case 53302: trigger_spell_id = 64418; break; case 53303: trigger_spell_id = 64419; break; case 53304: trigger_spell_id = 64420; break; } // If aura is active - no need to continue if (triggerTarget->HasAura(trigger_spell_id)) return; break; default: break; } break; } case SPELLFAMILY_DRUID: { switch (auraId) { case 768: // Cat Form // trigger_spell_id not set and unknown effect triggered in this case, ignoring for while return; case 22842: // Frenzied Regeneration case 22895: case 22896: case 26999: { int32 LifePerRage = GetModifier()->m_amount; int32 lRage = target->GetPower(POWER_RAGE); if (lRage > 100) // rage stored as rage*10 { lRage = 100; } target->ModifyPower(POWER_RAGE, -lRage); int32 FRTriggerBasePoints = int32(lRage * LifePerRage / 10); target->CastCustomSpell(target, 22845, &FRTriggerBasePoints, NULL, NULL, true, NULL, this); return; } default: break; } break; } // case SPELLFAMILY_HUNTER: // switch(auraId) // // Frost Trap Aura // case 13810: // return; // // Rizzle's Frost Trap // case 39900: // return; // // Tame spells // case 19597: // Tame Ice Claw Bear // case 19676: // Tame Snow Leopard // case 19677: // Tame Large Crag Boar // case 19678: // Tame Adult Plainstrider // case 19679: // Tame Prairie Stalker // case 19680: // Tame Swoop // case 19681: // Tame Dire Mottled Boar // case 19682: // Tame Surf Crawler // case 19683: // Tame Armored Scorpid // case 19684: // Tame Webwood Lurker // case 19685: // Tame Nightsaber Stalker // case 19686: // Tame Strigid Screecher // case 30100: // Tame Crazed Dragonhawk // case 30103: // Tame Elder Springpaw // case 30104: // Tame Mistbat // case 30647: // Tame Barbed Crawler // case 30648: // Tame Greater Timberstrider // case 30652: // Tame Nightstalker // return; // default: // break; // break; case SPELLFAMILY_SHAMAN: { switch (auraId) { case 28820: // Lightning Shield (The Earthshatterer set trigger after cast Lighting Shield) { // Need remove self if Lightning Shield not active Unit::SpellAuraHolderMap const& auras = triggerTarget-><API key>(); for (Unit::SpellAuraHolderMap::const_iterator itr = auras.begin(); itr != auras.end(); ++itr) { SpellEntry const* spell = itr->second->GetSpellProto(); if (spell->SpellFamilyName == SPELLFAMILY_SHAMAN && (spell->SpellFamilyFlags & UI64LIT(0x0000000000000400))) return; } triggerTarget-><API key>(28820); return; } case 38443: // Totemic Mastery (Skyshatter Regalia (Shaman Tier 6) - bonus) { if (triggerTarget->IsAllTotemSlotsUsed()) triggerTarget->CastSpell(triggerTarget, 38437, true, NULL, this); else triggerTarget-><API key>(38437); return; } default: break; } break; } default: break; } // Reget trigger spell proto triggeredSpellInfo = sSpellStore.LookupEntry(trigger_spell_id); } else // initial triggeredSpellInfo != NULL { // for channeled spell cast applied from aura owner to channel target (persistent aura affects already applied to true target) // come periodic casts applied to targets, so need seelct proper caster (ex. 15790) if (IsChanneledSpell(GetSpellProto()) && GetSpellProto()->Effect[GetEffIndex()] != <API key>) { // interesting 2 cases: periodic aura at caster of channeled spell if (target->GetObjectGuid() == casterGUID) { triggerCaster = target; if (WorldObject* channelTarget = target->GetMap()->GetWorldObject(target-><API key>())) { if (channelTarget->isType(TYPEMASK_UNIT)) { triggerTarget = (Unit*)channelTarget; } else { triggerTargetObject = channelTarget; } } } // or periodic aura at caster channel target else if (Unit* caster = GetCaster()) { if (target->GetObjectGuid() == caster-><API key>()) { triggerCaster = caster; triggerTarget = target; } } } // Spell exist but require custom code switch (auraId) { case 9347: // Mortal Strike { if (target->GetTypeId() != TYPEID_UNIT) { return; } // expected selection current fight target triggerTarget = ((Creature*)target)-><API key>(<API key>, 0, triggeredSpellInfo); if (!triggerTarget) { return; } break; } case 1010: // Curse of Idiocy { // TODO: spell casted by result in correct way mostly // BUT: // 1) target show casting at each triggered cast: target don't must show casting animation for any triggered spell // but must show affect apply like item casting // 2) maybe aura must be replace by new with accumulative stat mods instead stacking // prevent cast by triggered auras if (casterGUID == triggerTarget->GetObjectGuid()) { return; } // stop triggering after each affected stats lost > 90 int32 intelectLoss = 0; int32 spiritLoss = 0; Unit::AuraList const& mModStat = triggerTarget->GetAurasByType(SPELL_AURA_MOD_STAT); for (Unit::AuraList::const_iterator i = mModStat.begin(); i != mModStat.end(); ++i) { if ((*i)->GetId() == 1010) { switch ((*i)->GetModifier()->m_miscvalue) { case STAT_INTELLECT: intelectLoss += (*i)->GetModifier()->m_amount; break; case STAT_SPIRIT: spiritLoss += (*i)->GetModifier()->m_amount; break; default: break; } } } if (intelectLoss <= -90 && spiritLoss <= -90) { return; } break; } case 16191: // Mana Tide { triggerTarget->CastCustomSpell(triggerTarget, trigger_spell_id, &m_modifier.m_amount, NULL, NULL, true, NULL, this); return; } case 33525: // Ground Slam triggerTarget->CastSpell(triggerTarget, trigger_spell_id, true, NULL, this, casterGUID); return; case 38736: // Rod of Purification - for quest 10839 (Veil Skith: Darkstone of Terokk) { if (Unit* caster = GetCaster()) caster->CastSpell(triggerTarget, trigger_spell_id, true, NULL, this); return; } case 43149: // Claw Rage { // Need to provide explicit target for trigger spell target combination target->CastSpell(target->getVictim(), trigger_spell_id, true, NULL, this); return; } case 44883: // Encapsulate case 56505: // Surge of Power { // Self cast spell, hence overwrite caster (only channeled spell where the triggered spell deals dmg to SELF) triggerCaster = triggerTarget; break; } case 53563: // Beacon of Light // original caster must be target (beacon) target->CastSpell(target, trigger_spell_id, true, NULL, this, target->GetObjectGuid()); return; case 56654: // Rapid Recuperation (triggered energize have baspioints == 0) case 58882: { int32 mana = target->GetMaxPower(POWER_MANA) * m_modifier.m_amount / 100; triggerTarget->CastCustomSpell(triggerTarget, trigger_spell_id, &mana, NULL, NULL, true, NULL, this); return; } } } // All ok cast by default case if (triggeredSpellInfo) { if (triggerTargetObject) triggerCaster->CastSpell(triggerTargetObject->GetPositionX(), triggerTargetObject->GetPositionY(), triggerTargetObject->GetPositionZ(), triggeredSpellInfo, true, NULL, this, casterGUID); else { triggerCaster->CastSpell(triggerTarget, triggeredSpellInfo, true, NULL, this, casterGUID); } } else { if (Unit* caster = GetCaster()) { if (triggerTarget->GetTypeId() != TYPEID_UNIT || !sScriptMgr.OnEffectDummy(caster, GetId(), GetEffIndex(), (Creature*)triggerTarget, ObjectGuid())) { sLog.outError("Aura::TriggerSpell: Spell %u have 0 in EffectTriggered[%d], not handled custom case?", GetId(), GetEffIndex()); } } } } void Aura::<API key>() { ObjectGuid casterGuid = GetCasterGuid(); Unit* target = GetTriggerTarget(); if (!casterGuid || !target) return; // generic casting code with custom spells and target/caster customs uint32 trigger_spell_id = GetSpellProto()->EffectTriggerSpell[m_effIndex]; int32 basepoints0 = GetModifier()->m_amount; target->CastCustomSpell(target, trigger_spell_id, &basepoints0, NULL, NULL, true, NULL, this, casterGuid); } /*** AURA EFFECTS ***/ void Aura::HandleAuraDummy(bool apply, bool Real) { // spells required only Real aura add/remove if (!Real) { return; } Unit* target = GetTarget(); // AT APPLY if (apply) { switch (GetSpellProto()->SpellFamilyName) { case SPELLFAMILY_GENERIC: { switch (GetId()) { case 1515: // Tame beast // FIX_ME: this is 2.0.12 threat effect replaced in 2.1.x by dummy aura, must be checked for correctness if (target->CanHaveThreatList()) if (Unit* caster = GetCaster()) target->AddThreat(caster, 10.0f, false, GetSpellSchoolMask(GetSpellProto()), GetSpellProto()); return; case 7057: // Haunting Spirits // expected to tick with 30 sec period (tick part see in Aura::PeriodicTick) m_isPeriodic = true; m_modifier.periodictime = 30 * IN_MILLISECONDS; m_periodicTimer = m_modifier.periodictime; return; case 10255: // Stoned { if (Unit* caster = GetCaster()) { if (caster->GetTypeId() != TYPEID_UNIT) { return; } caster->SetFlag(UNIT_FIELD_FLAGS, <API key>); caster->addUnitState(UNIT_STAT_ROOT); } return; } case 13139: // net-o-matic // root to self part of (root_target->charge->root_self sequence if (Unit* caster = GetCaster()) { caster->CastSpell(caster, 13138, true, NULL, this); } return; case 28832: // Mark of Korth'azz case 28833: // Mark of Blaumeux case 28834: // Mark of Rivendare case 28835: // Mark of Zeliek { int32 damage = 0; switch (GetStackAmount()) { case 1: return; case 2: damage = 500; break; case 3: damage = 1500; break; case 4: damage = 4000; break; case 5: damage = 12500; break; default: damage = 14000 + 1000 * GetStackAmount(); break; } if (Unit* caster = GetCaster()) { caster->CastCustomSpell(target, 28836, &damage, NULL, NULL, true, NULL, this); } return; } case 31606: // Stormcrow Amulet { CreatureInfo const* cInfo = ObjectMgr::GetCreatureTemplate(17970); // we must assume db or script set display id to native at ending flight (if not, target is stuck with this model) if (cInfo) target->SetDisplayId(Creature::ChooseDisplayId(cInfo)); return; } case 32045: // Soul Charge case 32051: case 32052: { // max duration is 2 minutes, but expected to be random duration // real time randomness is unclear, using max 30 seconds here // see further down for expire of this aura GetHolder()->SetAuraDuration(urand(1, 30)*IN_MILLISECONDS); return; } case 33326: // Stolen Soul Dispel { target-><API key>(32346); return; } case 36587: // Vision Guide { target->CastSpell(target, 36573, true, NULL, this); return; } // Gender spells case 38224: // Illidari Agent Illusion case 37096: // Blood Elf Illusion case 46354: // Blood Elf Illusion { uint8 gender = target->getGender(); uint32 spellId; switch (GetId()) { case 38224: spellId = (gender == GENDER_MALE ? 38225 : 38227); break; case 37096: spellId = (gender == GENDER_MALE ? 37093 : 37095); break; case 46354: spellId = (gender == GENDER_MALE ? 46355 : 46356); break; default: return; } target->CastSpell(target, spellId, true, NULL, this); return; } case 39850: // Rocket Blast if (roll_chance_i(20)) // backfire stun target->CastSpell(target, 51581, true, NULL, this); return; case 43873: // Headless Horseman Laugh target->PlayDistanceSound(11965); return; case 45963: // Call Alliance Deserter { // Escorting Alliance Deserter if (target->GetMiniPet()) target->CastSpell(target, 45957, true); return; } case 46637: // Break Ice target->CastSpell(target, 46638, true, NULL, this); return; case 46699: // Requires No Ammo if (target->GetTypeId() == TYPEID_PLAYER) // not use ammo and not allow use ((Player*)target)->RemoveAmmo(); return; case 47190: // Toalu'u's Spiritual Incense target->CastSpell(target, 47189, true, NULL, this); // allow script to process further (text) break; case 47563: // Freezing Cloud target->CastSpell(target, 47574, true, NULL, this); return; case 47593: // Freezing Cloud target->CastSpell(target, 47594, true, NULL, this); return; case 48025: // Headless Horseman's Mount Spell::<API key>(target, GetSpellProto(), 51621, 48024, 51617, 48023, 0); return; case 48143: // Forgotten Aura // See Death's Door target->CastSpell(target, 48814, true, NULL, this); return; case 51405: // Digging for Treasure target->HandleEmote(EMOTE_STATE_WORK); // Pet will be following owner, this makes him stop target->addUnitState(UNIT_STAT_STUNNED); return; case 54729: // Winged Steed of the Ebon Blade Spell::<API key>(target, GetSpellProto(), 0, 0, 54726, 54727, 0); return; case 58600: // Restricted Flight Area { if (!target || target->GetTypeId() != TYPEID_PLAYER) return; const char* text = sObjectMgr.GetMangosString(LANG_NO_FLY_ZONE, ((Player*)target)->GetSession()-><API key>()); target->MonsterWhisper(text, target, true); return; } case 61187: // Twilight Shift (single target) case 61190: // Twilight Shift (many targets) target-><API key>(57620); target->CastSpell(target, 61885, true, NULL, this); return; case 62061: // Festive Holiday Mount if (target->HasAuraType(SPELL_AURA_MOUNTED)) // Reindeer Transformation target->CastSpell(target, 25860, true, NULL, this); return; case 62109: // Tails Up: Aura target->setFaction(1990); // Ambient (hostile) target->RemoveFlag(UNIT_FIELD_FLAGS, <API key>); return; case 63122: // Clear Insane target-><API key>(GetSpellProto()-><API key>(m_effIndex)); return; case 63624: // Learn a Second Talent Specialization // Teach Learn Talent Specialization Switches, required for client triggered casts, allow after 30 sec delay if (target->GetTypeId() == TYPEID_PLAYER) ((Player*)target)->learnSpell(63680, false); return; case 63651: // Revert to One Talent Specialization // Teach Learn Talent Specialization Switches, remove if (target->GetTypeId() == TYPEID_PLAYER) ((Player*)target)->removeSpell(63680); return; case 64132: // Constrictor Tentacle if (target->GetTypeId() == TYPEID_PLAYER) target->CastSpell(target, 64133, true, NULL, this); return; case 65684: // Dark Essence target-><API key>(65686); return; case 65686: // Light Essence target-><API key>(65684); return; case 68912: // Wailing Souls if (Unit* caster = GetCaster()) { caster->SetTargetGuid(target->GetObjectGuid()); // TODO - this is confusing, it seems the boss should channel this aura, and start casting the next spell caster->CastSpell(caster, 68899, false); } return; case 70623: // Jaina's Call if (target->GetTypeId() == TYPEID_PLAYER) target->CastSpell(target, 70525, true, NULL, this); return; case 70638: // Call of Sylvanas if (target->GetTypeId() == TYPEID_PLAYER) target->CastSpell(target, 70639, true, NULL, this); return; case 71342: // Big Love Rocket Spell::<API key>(target, GetSpellProto(), 71344, 71345, 71346, 71347, 0); return; case 71563: // Deadly Precision target->CastSpell(target, 71564, true, NULL, this); return; case 72286: // Invincible Spell::<API key>(target, GetSpellProto(), 72281, 72282, 72283, 72284, 0); return; case 74856: // Blazing Hippogryph Spell::<API key>(target, GetSpellProto(), 0, 0, 74854, 74855, 0); return; case 75614: // Celestial Steed Spell::<API key>(target, GetSpellProto(), 75619, 75620, 75617, 75618, 76153); return; case 75973: // X-53 Touring Rocket Spell::<API key>(target, GetSpellProto(), 0, 0, 75957, 75972, 76154); return; } break; } case SPELLFAMILY_WARRIOR: { switch (GetId()) { case 41099: // Battle Stance { if (target->GetTypeId() != TYPEID_UNIT) return; // Stance Cooldown target->CastSpell(target, 41102, true, NULL, this); // Battle Aura target->CastSpell(target, 41106, true, NULL, this); // equipment ((Creature*)target)->SetVirtualItem(VIRTUAL_ITEM_SLOT_0, 32614); ((Creature*)target)->SetVirtualItem(VIRTUAL_ITEM_SLOT_1, 0); ((Creature*)target)->SetVirtualItem(VIRTUAL_ITEM_SLOT_2, 0); return; } case 41100: // Berserker Stance { if (target->GetTypeId() != TYPEID_UNIT) return; // Stance Cooldown target->CastSpell(target, 41102, true, NULL, this); // Berserker Aura target->CastSpell(target, 41107, true, NULL, this); // equipment ((Creature*)target)->SetVirtualItem(VIRTUAL_ITEM_SLOT_0, 32614); ((Creature*)target)->SetVirtualItem(VIRTUAL_ITEM_SLOT_1, 0); ((Creature*)target)->SetVirtualItem(VIRTUAL_ITEM_SLOT_2, 0); return; } case 41101: // Defensive Stance { if (target->GetTypeId() != TYPEID_UNIT) return; // Stance Cooldown target->CastSpell(target, 41102, true, NULL, this); // Defensive Aura target->CastSpell(target, 41105, true, NULL, this); // equipment ((Creature*)target)->SetVirtualItem(VIRTUAL_ITEM_SLOT_0, 32604); ((Creature*)target)->SetVirtualItem(VIRTUAL_ITEM_SLOT_1, 31467); ((Creature*)target)->SetVirtualItem(VIRTUAL_ITEM_SLOT_2, 0); return; } case 53790: // Defensive Stance { if (target->GetTypeId() != TYPEID_UNIT) return; // Stance Cooldown target->CastSpell(target, 59526, true, NULL, this); // Defensive Aura target->CastSpell(target, 41105, true, NULL, this); // equipment ((Creature*)target)->SetVirtualItem(VIRTUAL_ITEM_SLOT_0, 43625); ((Creature*)target)->SetVirtualItem(VIRTUAL_ITEM_SLOT_1, 39384); ((Creature*)target)->SetVirtualItem(VIRTUAL_ITEM_SLOT_2, 0); return; } case 53791: // Berserker Stance { if (target->GetTypeId() != TYPEID_UNIT) return; // Stance Cooldown target->CastSpell(target, 59526, true, NULL, this); // Berserker Aura target->CastSpell(target, 41107, true, NULL, this); // equipment ((Creature*)target)->SetVirtualItem(VIRTUAL_ITEM_SLOT_0, 43625); ((Creature*)target)->SetVirtualItem(VIRTUAL_ITEM_SLOT_1, 43625); ((Creature*)target)->SetVirtualItem(VIRTUAL_ITEM_SLOT_2, 0); return; } case 53792: // Battle Stance { if (target->GetTypeId() != TYPEID_UNIT) return; // Stance Cooldown target->CastSpell(target, 59526, true, NULL, this); // Battle Aura target->CastSpell(target, 41106, true, NULL, this); // equipment ((Creature*)target)->SetVirtualItem(VIRTUAL_ITEM_SLOT_0, 43623); ((Creature*)target)->SetVirtualItem(VIRTUAL_ITEM_SLOT_1, 0); ((Creature*)target)->SetVirtualItem(VIRTUAL_ITEM_SLOT_2, 0); return; } } // Overpower if (GetSpellProto()->SpellFamilyFlags & UI64LIT(0x0000000000000004)) { // Must be casting target if (!target-><API key>(false)) return; Unit* caster = GetCaster(); if (!caster) return; Unit::AuraList const& modifierAuras = caster->GetAurasByType(<API key>); for (Unit::AuraList::const_iterator itr = modifierAuras.begin(); itr != modifierAuras.end(); ++itr) { // Unrelenting Assault if ((*itr)->GetSpellProto()->SpellFamilyName == SPELLFAMILY_WARRIOR && (*itr)->GetSpellProto()->SpellIconID == 2775) { switch ((*itr)->GetSpellProto()->Id) { case 46859: // Unrelenting Assault, rank 1 target->CastSpell(target, 64849, true, NULL, (*itr)); break; case 46860: // Unrelenting Assault, rank 2 target->CastSpell(target, 64850, true, NULL, (*itr)); break; default: break; } break; } } return; } break; } case SPELLFAMILY_MAGE: break; case SPELLFAMILY_HUNTER: { switch (GetId()) { case 34026: // Kill Command target->CastSpell(target, 34027, true, NULL, this); return; } break; } case SPELLFAMILY_SHAMAN: { switch (GetId()) { case 55198: // Tidal Force target->CastSpell(target, 55166, true, NULL, this); return; } // Earth Shield if ((GetSpellProto()->SpellFamilyFlags & UI64LIT(0x40000000000))) { // prevent double apply bonuses if (target->GetTypeId() != TYPEID_PLAYER || !((Player*)target)->GetSession()->PlayerLoading()) { if (Unit* caster = GetCaster()) { m_modifier.m_amount = caster-><API key>(target, GetSpellProto(), m_modifier.m_amount, SPELL_DIRECT_DAMAGE); m_modifier.m_amount = target-><API key>(caster, GetSpellProto(), m_modifier.m_amount, SPELL_DIRECT_DAMAGE); } } return; } break; } } } // AT REMOVE else { if (IsQuestTameSpell(GetId()) && target->IsAlive()) { Unit* caster = GetCaster(); if (!caster || !caster->IsAlive()) { return; } uint32 finalSpellId = 0; switch (GetId()) { case 19548: finalSpellId = 19597; break; case 19674: finalSpellId = 19677; break; case 19687: finalSpellId = 19676; break; case 19688: finalSpellId = 19678; break; case 19689: finalSpellId = 19679; break; case 19692: finalSpellId = 19680; break; case 19693: finalSpellId = 19684; break; case 19694: finalSpellId = 19681; break; case 19696: finalSpellId = 19682; break; case 19697: finalSpellId = 19683; break; case 19699: finalSpellId = 19685; break; case 19700: finalSpellId = 19686; break; case 30646: finalSpellId = 30647; break; case 30653: finalSpellId = 30648; break; case 30654: finalSpellId = 30652; break; case 30099: finalSpellId = 30100; break; case 30102: finalSpellId = 30103; break; case 30105: finalSpellId = 30104; break; } if (finalSpellId) { caster->CastSpell(target, finalSpellId, true, NULL, this); } return; } switch (GetId()) { case 10255: // Stoned { if (Unit* caster = GetCaster()) { if (caster->GetTypeId() != TYPEID_UNIT) { return; } // see dummy effect of spell 10254 for removal of flags etc caster->CastSpell(caster, 10254, true); } return; } case 12479: // Hex of Jammal'an target->CastSpell(target, 12480, true, NULL, this); return; case 12774: // (DND) Belnistrasz Idol Shutdown Visual { if (m_removeMode == <API key>) { return; } // Idom Rool Camera Shake <- wtf, don't drink while making spellnames? if (Unit* caster = GetCaster()) { caster->CastSpell(caster, 12816, true); } return; } case 28169: // Mutating Injection { // Mutagen Explosion target->CastSpell(target, 28206, true, NULL, this); // Poison Cloud target->CastSpell(target, 28240, true, NULL, this); return; } case 32045: // Soul Charge { if (m_removeMode == <API key>) target->CastSpell(target, 32054, true, NULL, this); return; } case 32051: // Soul Charge { if (m_removeMode == <API key>) target->CastSpell(target, 32057, true, NULL, this); return; } case 32052: // Soul Charge { if (m_removeMode == <API key>) target->CastSpell(target, 32053, true, NULL, this); return; } case 32286: // Focus Target Visual { if (m_removeMode == <API key>) target->CastSpell(target, 32301, true, NULL, this); return; } case 35079: // Misdirection, triggered buff case 59628: // Tricks of the Trade, triggered buff { if (Unit* pCaster = GetCaster()) pCaster-><API key>().<API key>(); return; } case 36730: // Flame Strike { target->CastSpell(target, 36731, true, NULL, this); return; } case 41099: // Battle Stance { // Battle Aura target-><API key>(41106); return; } case 41100: // Berserker Stance { // Berserker Aura target-><API key>(41107); return; } case 41101: // Defensive Stance { // Defensive Aura target-><API key>(41105); return; } case 42385: // Alcaz Survey Aura { target->CastSpell(target, 42316, true, NULL, this); return; } case 42454: // Captured Totem { if (m_removeMode == <API key>) { if (target->getDeathState() != CORPSE) return; Unit* pCaster = GetCaster(); if (!pCaster) return; // Captured Totem Test Credit if (Player* pPlayer = pCaster-><API key>()) pPlayer->CastSpell(pPlayer, 42455, true); } return; } case 42517: // Beam to Zelfrax { // expecting target to be a dummy creature Creature* pSummon = target->SummonCreature(23864, 0.0f, 0.0f, 0.0f, target->GetOrientation(), <API key>, 0); Unit* pCaster = GetCaster(); if (pSummon && pCaster) pSummon->GetMotionMaster()->MovePoint(0, pCaster->GetPositionX(), pCaster->GetPositionY(), pCaster->GetPositionZ()); return; } case 43681: // Inactive { if (m_removeMode == <API key> && target->GetTypeId() == TYPEID_PLAYER) ((Player*)target)->ToggleAFK(); return; } case 43969: // Feathered Charm { // Steelfeather Quest Credit, Are there any requirements for this, like area? if (m_removeMode == <API key>) target->CastSpell(target, 43984, true); return; } case 44191: // Flame Strike { if (target->GetMap()->IsDungeon()) { uint32 spellId = target->GetMap()->IsRegularDifficulty() ? 44190 : 46163; target->CastSpell(target, spellId, true, NULL, this); } return; } case 45934: // Dark Fiend { // Kill target if dispelled if (m_removeMode == <API key>) target->DealDamage(target, target->GetHealth(), NULL, DIRECT_DAMAGE, <API key>, NULL, false); return; } case 45963: // Call Alliance Deserter { // Escorting Alliance Deserter target-><API key>(45957); return; } case 46308: // Burning Winds { // casted only at creatures at spawn target->CastSpell(target, 47287, true, NULL, this); return; } case 46637: // Break Ice { target->CastSpell(target, 47030, true, NULL, this); return; } case 48385: // Create Spirit Fount Beam { target->CastSpell(target, target->GetMap()->IsRegularDifficulty() ? 48380 : 59320, true); return; } case 50141: // Blood Oath { // Blood Oath if (m_removeMode == <API key>) target->CastSpell(target, 50001, true, NULL, this); return; } case 51405: // Digging for Treasure { const uint32 spell_list[7] = { 51441, // hare 51397, // crystal 51398, // armor 51400, // gem 51401, // platter 51402, // treasure 51443 // bug }; target->CastSpell(target, spell_list[urand(0, 6)], true); target->HandleEmote(EMOTE_STATE_NONE); target->clearUnitState(UNIT_STAT_STUNNED); return; } case 51870: // Collect Hair Sample { if (Unit* pCaster = GetCaster()) { if (m_removeMode == <API key>) pCaster->CastSpell(target, 51872, true, NULL, this); } return; } case 52098: // Charge Up { if (m_removeMode == <API key>) target->CastSpell(target, 52092, true, NULL, this); return; } case 53039: // Deploy Parachute { // Crusader Parachute target-><API key>(53031); return; } case 53790: // Defensive Stance { // Defensive Aura target-><API key>(41105); return; } case 53791: // Berserker Stance { // Berserker Aura target-><API key>(41107); return; } case 53792: // Battle Stance { // Battle Aura target-><API key>(41106); return; } case 56511: // Towers of Certain Doom: Tower Bunny Smoke Flare Effect { // Towers of Certain Doom: Skorn Cannonfire if (m_removeMode == <API key>) target->CastSpell(target, 43069, true); return; } case 58600: // Restricted Flight Area { AreaTableEntry const* area = <API key>(target->GetAreaId()); // Dalaran restricted flight zone (recheck before apply unmount) if (area && target->GetTypeId() == TYPEID_PLAYER && (area->flags & <API key>) && ((Player*)target)->IsFreeFlying() && !((Player*)target)->isGameMaster()) { target->CastSpell(target, 58601, true); // Remove Flight Auras (also triggered Parachute (45472)) } return; } case 61900: // Electrical Charge { if (m_removeMode == <API key>) target->CastSpell(target, GetSpellProto()-><API key>(EFFECT_INDEX_0), true); return; } case 62483: // Stonebark's Essence Channel case 62484: // Ironbranch's Essence Channel case 62485: // Brightleaf's Essence Channel case 65587: // Brightleaf's Essence Channel (h) case 65588: // Ironbranch's Essence Channel (h) case 65589: // Stonebark's Essence Channel (h) { if (Unit* caster = GetCaster()) { if (m_removeMode == <API key>) caster->CastSpell(caster, 62467, true); } return; } case 64398: // Summon Scrap Bot (Ulduar, Mimiron) - for Scrap Bots case 64426: // Summon Scrap Bot (Ulduar, Mimiron) - for Assault Bots case 64621: // Summon Fire Bot (Ulduar, Mimiron) { uint32 triggerSpell = 0; switch (GetId()) { case 64398: triggerSpell = 63819; break; case 64426: triggerSpell = 64427; break; case 64621: triggerSpell = 64622; break; } target->CastSpell(target, triggerSpell, false); return; } case 68839: // Corrupt Soul { // Knockdown Stun target->CastSpell(target, 68848, true, NULL, this); // Draw Corrupted Soul target->CastSpell(target, 68846, true, NULL, this); return; } } // Living Bomb if (GetSpellProto()->SpellFamilyName == SPELLFAMILY_MAGE && (GetSpellProto()->SpellFamilyFlags & UI64LIT(0x2000000000000))) { if (m_removeMode == <API key> || m_removeMode == <API key>) target->CastSpell(target, m_modifier.m_amount, true, NULL, this); return; } } // AT APPLY & REMOVE switch (GetSpellProto()->SpellFamilyName) { case SPELLFAMILY_GENERIC: { switch (GetId()) { case 6606: // Self Visual - Sleep Until Cancelled (DND) { if (apply) { target->SetStandState(<API key>); target->addUnitState(UNIT_STAT_ROOT); } else { target->clearUnitState(UNIT_STAT_ROOT); target->SetStandState(<API key>); } return; } case 11196: // Recently Bandaged target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, GetMiscValue(), apply); return; case 24658: // Unstable Power { if (apply) { Unit* caster = GetCaster(); if (!caster) { return; } caster->CastSpell(target, 24659, true, NULL, NULL, GetCasterGuid()); } else { target-><API key>(24659); } return; } case 24661: // Restless Strength { if (apply) { Unit* caster = GetCaster(); if (!caster) { return; } caster->CastSpell(target, 24662, true, NULL, NULL, GetCasterGuid()); } else { target-><API key>(24662); } return; } case 29266: // Permanent Feign Death case 31261: // Permanent Feign Death (Root) case 37493: // Feign Death case 52593: // Bloated Abomination Feign Death case 55795: // Falling Dragon Feign Death case 57626: // Feign Death case 57685: // Permanent Feign Death case 58768: // Permanent Feign Death (Freeze Jumpend) case 58806: // Permanent Feign Death (Drowned Anim) case 58951: // Permanent Feign Death case 64461: // Permanent Feign Death (No Anim) (Root) case 65985: // Permanent Feign Death (Root Silence Pacify) case 70592: // Permanent Feign Death case 70628: // Permanent Feign Death case 70630: // Frozen Aftermath - Feign Death case 71598: // Feign Death { // Unclear what the difference really is between them. // Some has effect1 that makes the difference, however not all. // Some appear to be used depending on creature location, in water, at solid ground, in air/suspended, etc // For now, just handle all the same way if (target->GetTypeId() == TYPEID_UNIT) { target->SetFeignDeath(apply); } return; } case 35356: // Spawn Feign Death case 35357: // Spawn Feign Death case 42557: // Feign Death case 51329: // Feign Death { if (target->GetTypeId() == TYPEID_UNIT) { // Flags not set like it's done in SetFeignDeath() // UNIT_DYNFLAG_DEAD does not appear with these spells. // All of the spells appear to be present at spawn and not used to feign in combat or similar. if (apply) { target->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_UNK_29); target->SetFlag(UNIT_FIELD_FLAGS_2, <API key>); target->addUnitState(UNIT_STAT_DIED); } else { target->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_UNK_29); target->RemoveFlag(UNIT_FIELD_FLAGS_2, <API key>); target->clearUnitState(UNIT_STAT_DIED); } } return; } case 40133: // Summon Fire Elemental { Unit* caster = GetCaster(); if (!caster) return; Unit* owner = caster->GetOwner(); if (owner && owner->GetTypeId() == TYPEID_PLAYER) { if (apply) owner->CastSpell(owner, 8985, true); else ((Player*)owner)->RemovePet(PET_SAVE_REAGENTS); } return; } case 40132: // Summon Earth Elemental { Unit* caster = GetCaster(); if (!caster) return; Unit* owner = caster->GetOwner(); if (owner && owner->GetTypeId() == TYPEID_PLAYER) { if (apply) owner->CastSpell(owner, 19704, true); else ((Player*)owner)->RemovePet(PET_SAVE_REAGENTS); } return; } case 40214: // Dragonmaw Illusion { if (apply) { target->CastSpell(target, 40216, true); target->CastSpell(target, 42016, true); } else { target-><API key>(40216); target-><API key>(42016); } return; } case 42515: // Jarl Beam { // aura animate dead (fainted) state for the duration, but we need to animate the death itself (correct way below?) if (Unit* pCaster = GetCaster()) pCaster->ApplyModFlag(UNIT_FIELD_FLAGS_2, <API key>, apply); // Beam to Zelfrax at remove if (!apply) target->CastSpell(target, 42517, true); return; } case 42583: // Claw Rage case 68987: // Pursuit { Unit* caster = GetCaster(); if (!caster || target->GetTypeId() != TYPEID_PLAYER) return; if (apply) caster->FixateTarget(target); else if (target->GetObjectGuid() == caster->GetFixateTargetGuid()) caster->FixateTarget(NULL); return; } case 43874: // Scourge Mur'gul Camp: Force Shield Arcane Purple x3 target->ApplyModFlag(UNIT_FIELD_FLAGS, <API key>, apply); if (apply) target->addUnitState(UNIT_STAT_ROOT); return; case 47178: // Plague Effect Self target->SetFeared(apply, GetCasterGuid(), GetId()); return; case 56422: // Nerubian Submerge // not known if there are other things todo, only flag are confirmed valid target->ApplyModFlag(UNIT_FIELD_FLAGS, <API key>, apply); return; case 58204: // LK Intro VO (1) if (target->GetTypeId() == TYPEID_PLAYER) { // Play part 1 if (apply) target->PlayDirectSound(14970, (Player*)target); // continue in 58205 else target->CastSpell(target, 58205, true); } return; case 58205: // LK Intro VO (2) if (target->GetTypeId() == TYPEID_PLAYER) { // Play part 2 if (apply) target->PlayDirectSound(14971, (Player*)target); // Play part 3 else target->PlayDirectSound(14972, (Player*)target); } return; case 27978: case 40131: if (apply) { target->m_AuraFlags |= <API key>; } else { target->m_AuraFlags &= ~<API key>; } return; } break; } case SPELLFAMILY_MAGE: break; case SPELLFAMILY_WARLOCK: { // Haunt if (GetSpellProto()->SpellIconID == 3172 && (GetSpellProto()->SpellFamilyFlags & UI64LIT(0x0004000000000000))) { // NOTE: for avoid use additional field damage stored in dummy value (replace unused 100% if (apply) m_modifier.m_amount = 0; // use value as damage counter instead redundant 100% percent else { int32 bp0 = m_modifier.m_amount; if (Unit* caster = GetCaster()) target->CastCustomSpell(caster, 48210, &bp0, NULL, NULL, true, NULL, this); } } break; } case SPELLFAMILY_DRUID: { switch (GetId()) { case 52610: // Savage Roar { if (apply) { if (target->GetShapeshiftForm() != FORM_CAT) return; target->CastSpell(target, 62071, true); } else target-><API key>(62071); return; } case 61336: // Survival Instincts { if (apply) { if (!target->IsInFeralForm()) return; int32 bp0 = int32(target->GetMaxHealth() * m_modifier.m_amount / 100); target->CastCustomSpell(target, 50322, &bp0, NULL, NULL, true); } else target-><API key>(50322); return; } } // Lifebloom if (GetSpellProto()->SpellFamilyFlags & UI64LIT(0x1000000000)) { if (apply) { if (Unit* caster = GetCaster()) { // prevent double apply bonuses if (target->GetTypeId() != TYPEID_PLAYER || !((Player*)target)->GetSession()->PlayerLoading()) { m_modifier.m_amount = caster-><API key>(target, GetSpellProto(), m_modifier.m_amount, SPELL_DIRECT_DAMAGE); m_modifier.m_amount = target-><API key>(caster, GetSpellProto(), m_modifier.m_amount, SPELL_DIRECT_DAMAGE); } } } else { // Final heal on duration end if (m_removeMode != <API key>) return; // final heal if (target->IsInWorld() && GetStackAmount() > 0) { int32 amount = m_modifier.m_amount; target->CastCustomSpell(target, 33778, &amount, NULL, NULL, true, NULL, this, GetCasterGuid()); if (Unit* caster = GetCaster()) { int32 returnmana = (GetSpellProto()->ManaCostPercentage * caster->GetCreateMana() / 100) * GetStackAmount() / 2; caster->CastCustomSpell(caster, 64372, &returnmana, NULL, NULL, true, NULL, this, GetCasterGuid()); } } } return; } // Predatory Strikes if (target->GetTypeId() == TYPEID_PLAYER && GetSpellProto()->SpellIconID == 1563) { ((Player*)target)-><API key>(); return; } // Improved Moonkin Form if (GetSpellProto()->SpellIconID == 2855) { uint32 spell_id; switch (GetId()) { case 48384: spell_id = 50170; break; // Rank 1 case 48395: spell_id = 50171; break; // Rank 2 case 48396: spell_id = 50172; break; // Rank 3 default: sLog.outError("HandleAuraDummy: Not handled rank of IMF (Spell: %u)", GetId()); return; } if (apply) { if (target->GetShapeshiftForm() != FORM_MOONKIN) return; target->CastSpell(target, spell_id, true); } else target-><API key>(spell_id); return; } break; } case SPELLFAMILY_ROGUE: switch (GetId()) { case 57934: // Tricks of the Trade, main spell { if (apply) GetHolder()->SetAuraCharges(1); // not have proper charges set in spell data else { // used for direct in code aura removes and spell proc event charges expire if (m_removeMode != <API key>) target-><API key>().<API key>(); } return; } } break; case SPELLFAMILY_HUNTER: { switch (GetId()) { case 34477: // Misdirection, main spell { if (apply) GetHolder()->SetAuraCharges(1); // not have proper charges set in spell data else { // used for direct in code aura removes and spell proc event charges expire if (m_removeMode != <API key>) target-><API key>().<API key>(); } return; } } break; } case SPELLFAMILY_PALADIN: switch (GetId()) { case 20911: // Blessing of Sanctuary case 25899: // Greater Blessing of Sanctuary { if (apply) target->CastSpell(target, 67480, true, NULL, this); else target-><API key>(67480); return; } } break; case SPELLFAMILY_SHAMAN: { switch (GetId()) { case 6495: // Sentry Totem { if (target->GetTypeId() != TYPEID_PLAYER) { return; } Totem* totem = target->GetTotem(TOTEM_SLOT_AIR); if (totem && apply) { ((Player*)target)->GetCamera().SetView(totem); } else { ((Player*)target)->GetCamera().ResetView(); } return; } } break; } } // pet auras if (PetAura const* petSpell = sSpellMgr.GetPetAura(GetId(), m_effIndex)) { if (apply) { target->AddPetAura(petSpell); } else { target->RemovePetAura(petSpell); } return; } if (target->GetTypeId() == TYPEID_PLAYER) { <API key> saBounds = sSpellMgr.<API key>(GetId()); if (saBounds.first != saBounds.second) { uint32 zone, area; target->GetZoneAndAreaId(zone, area); for (SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr) { itr->second-><API key>((Player*)target, zone, area, false); } } } // script has to "handle with care", only use where data are not ok to use in the above code. if (target->GetTypeId() == TYPEID_UNIT) { sScriptMgr.OnAuraDummy(this, apply); } } void Aura::HandleAuraMounted(bool apply, bool Real) { // only at real add/remove aura if (!Real) { return; } Unit* target = GetTarget(); if (apply) { CreatureInfo const* ci = ObjectMgr::GetCreatureTemplate(m_modifier.m_miscvalue); if (!ci) { sLog.outErrorDb("AuraMounted: `creature_template`='%u' not found in database (only need it modelid)", m_modifier.m_miscvalue); return; } uint32 display_id = Creature::ChooseDisplayId(ci); CreatureModelInfo const* minfo = sObjectMgr.<API key>(display_id); if (minfo) { display_id = minfo->modelid; } target->Mount(display_id, GetId()); if (ci->VehicleTemplateId) { target->SetVehicleId(ci->VehicleTemplateId, ci->Entry); if (target->GetTypeId() == TYPEID_PLAYER) target->SetFlag(UNIT_NPC_FLAGS, <API key>); } } else { target->Unmount(true); CreatureInfo const* ci = ObjectMgr::GetCreatureTemplate(m_modifier.m_miscvalue); if (ci && target->IsVehicle() && ci->VehicleTemplateId == target->GetVehicleInfo()->GetVehicleEntry()->m_ID) { if (target->GetTypeId() == TYPEID_PLAYER) target->RemoveFlag(UNIT_NPC_FLAGS, <API key>); target->SetVehicleId(0, 0); } } } void Aura::HandleAuraWaterWalk(bool apply, bool Real) { // only at real add/remove aura if (!Real) { return; } GetTarget()->SetWaterWalk(apply); } void Aura::<API key>(bool apply, bool Real) { // only at real add/remove aura if (!Real) { return; } GetTarget()->SetFeatherFall(apply); } void Aura::HandleAuraHover(bool apply, bool Real) { // only at real add/remove aura if (!Real) { return; } GetTarget()->SetHover(apply); } void Aura::<API key>(bool /*apply*/, bool /*Real*/) { // update timers in client if (GetTarget()->GetTypeId() == TYPEID_PLAYER) { ((Player*)GetTarget())->UpdateMirrorTimers(); } } void Aura::<API key>(bool apply, bool Real) { if (!Real) { return; } ShapeshiftForm form = ShapeshiftForm(m_modifier.m_miscvalue); <API key> const* ssEntry = <API key>.LookupEntry(form); if (!ssEntry) { sLog.outError("Unknown shapeshift form %u in spell %u", form, GetId()); return; } uint32 modelid = 0; Unit* target = GetTarget(); // remove SPELL_AURA_EMPATHY target-><API key>(SPELL_AURA_EMPATHY); if (ssEntry->modelID_A) { // i will asume that creatures will always take the defined model from the dbc // since no field in creature_templates describes wether an alliance or // horde modelid should be used at shapeshifting if (target->GetTypeId() != TYPEID_PLAYER) modelid = ssEntry->modelID_A; else { // players are a bit different since the dbc has seldomly an horde modelid if (Player::TeamForRace(target->getRace()) == HORDE) { if (ssEntry->modelID_H) modelid = ssEntry->modelID_H; // 3.2.3 only the moonkin form has this information else // get model for race modelid = sObjectMgr.GetModelForRace(ssEntry->modelID_A, target->getRaceMask()); } // nothing found in above, so use default if (!modelid) modelid = ssEntry->modelID_A; } } // remove polymorph before changing display id to keep new display id switch (form) { case FORM_CAT: case FORM_TREE: case FORM_TRAVEL: case FORM_AQUA: case FORM_BEAR: case FORM_DIREBEAR: case FORM_FLIGHT_EPIC: case FORM_FLIGHT: case FORM_MOONKIN: { // remove movement affects target-><API key>(SPELL_AURA_MOD_ROOT, GetHolder()); Unit::AuraList const& slowingAuras = target->GetAurasByType(<API key>); for (Unit::AuraList::const_iterator iter = slowingAuras.begin(); iter != slowingAuras.end();) { SpellEntry const* aurSpellInfo = (*iter)->GetSpellProto(); uint32 aurMechMask = <API key>(aurSpellInfo); // If spell that caused this aura has Croud Control or Daze effect if ((aurMechMask & <API key>) || // some Daze spells have these parameters instead of MECHANIC_DAZE (skip snare spells) (aurSpellInfo->SpellIconID == 15 && aurSpellInfo->Dispel == 0 && (aurMechMask & (1 << (MECHANIC_SNARE - 1))) == 0)) { ++iter; continue; } // All OK, remove aura now target-><API key>(aurSpellInfo->Id); iter = slowingAuras.begin(); } // and polymorphic affects if (target->IsPolymorphed()) target-><API key>(target->getTransForm()); break; } default: break; } if (apply) { Powers PowerType = POWER_MANA; // remove other shapeshift before applying a new one target-><API key>(<API key>, GetHolder()); if (modelid > 0) target->SetDisplayId(modelid); // now only powertype must be set switch (form) { case FORM_CAT: PowerType = POWER_ENERGY; break; case FORM_BEAR: case FORM_DIREBEAR: case FORM_BATTLESTANCE: case <API key>: case <API key>: PowerType = POWER_RAGE; break; default: break; } if (PowerType != POWER_MANA) { // reset power to default values only at power change if (target->GetPowerType() != PowerType) { target->SetPowerType(PowerType); } switch (form) { case FORM_CAT: case FORM_BEAR: case FORM_DIREBEAR: { // get furor proc chance int32 furorChance = 0; Unit::AuraList const& mDummy = target->GetAurasByType(SPELL_AURA_DUMMY); for (Unit::AuraList::const_iterator i = mDummy.begin(); i != mDummy.end(); ++i) { if ((*i)->GetSpellProto()->SpellIconID == 238) { furorChance = (*i)->GetModifier()->m_amount; break; } } if (m_modifier.m_miscvalue == FORM_CAT) { // Furor chance is now amount allowed to save energy for cat form // without talent it reset to 0 if ((int32)target->GetPower(POWER_ENERGY) > furorChance) { target->SetPower(POWER_ENERGY, 0); target->CastCustomSpell(target, 17099, &furorChance, NULL, NULL, true, NULL, this); } } else if (furorChance) // only if talent known { target->SetPower(POWER_RAGE, 0); if (irand(1, 100) <= furorChance) { target->CastSpell(target, 17057, true, NULL, this); } } break; } case FORM_BATTLESTANCE: case <API key>: case <API key>: { uint32 Rage_val = 0; // Stance mastery + Tactical mastery (both passive, and last have aura only in defense stance, but need apply at any stance switch) if (target->GetTypeId() == TYPEID_PLAYER) { PlayerSpellMap const& sp_list = ((Player*)target)->GetSpellMap(); for (PlayerSpellMap::const_iterator itr = sp_list.begin(); itr != sp_list.end(); ++itr) { if (itr->second.state == PLAYERSPELL_REMOVED) continue; SpellEntry const* spellInfo = sSpellStore.LookupEntry(itr->first); if (spellInfo && spellInfo->SpellFamilyName == SPELLFAMILY_WARRIOR && spellInfo->SpellIconID == 139) Rage_val += target-><API key>(target, spellInfo, EFFECT_INDEX_0) * 10; } } if (target->GetPower(POWER_RAGE) > Rage_val) { target->SetPower(POWER_RAGE, Rage_val); } break; } default: break; } } target->SetShapeshiftForm(form); // a form can give the player a new castbar with some spells.. this is a clientside process.. // serverside just needs to register the new spells so that player isn't kicked as cheater if (target->GetTypeId() == TYPEID_PLAYER) for (uint32 i = 0; i < 8; ++i) if (ssEntry->spellId[i]) ((Player*)target)->addSpell(ssEntry->spellId[i], true, false, false, false); } else { if (modelid > 0) target->SetDisplayId(target->GetNativeDisplayId()); if (target->getClass() == CLASS_DRUID) { target->SetPowerType(POWER_MANA); } target->SetShapeshiftForm(FORM_NONE); switch (form) { // Nordrassil Harness - bonus case FORM_BEAR: case FORM_DIREBEAR: case FORM_CAT: if (Aura* dummy = target->GetDummyAura(37315)) target->CastSpell(target, 37316, true, NULL, dummy); break; // Nordrassil Regalia - bonus case FORM_MOONKIN: if (Aura* dummy = target->GetDummyAura(37324)) target->CastSpell(target, 37325, true, NULL, dummy); break; default: break; } // look at the comment in apply-part if (target->GetTypeId() == TYPEID_PLAYER) for (uint32 i = 0; i < 8; ++i) if (ssEntry->spellId[i]) ((Player*)target)->removeSpell(ssEntry->spellId[i], false, false, false); } // adding/removing linked auras // add/remove the shapeshift aura's boosts <API key>(apply); if (target->GetTypeId() == TYPEID_PLAYER) { ((Player*)target)->InitDataForForm(); } } void Aura::HandleAuraTransform(bool apply, bool Real) { Unit* target = GetTarget(); if (apply) { // special case (spell specific functionality) if (m_modifier.m_miscvalue == 0) { switch (GetId()) { case 16739: // Orb of Deception { uint32 orb_model = target->GetNativeDisplayId(); switch (orb_model) { // Troll Female case 1479: target->SetDisplayId(10134); break; // Troll Male case 1478: target->SetDisplayId(10135); break; // Tauren Male case 59: target->SetDisplayId(10136); break; // Human Male case 49: target->SetDisplayId(10137); break; // Human Female case 50: target->SetDisplayId(10138); break; // Orc Male case 51: target->SetDisplayId(10139); break; // Orc Female case 52: target->SetDisplayId(10140); break; // Dwarf Male case 53: target->SetDisplayId(10141); break; // Dwarf Female case 54: target->SetDisplayId(10142); break; // NightElf Male case 55: target->SetDisplayId(10143); break; // NightElf Female case 56: target->SetDisplayId(10144); break; // Undead Female case 58: target->SetDisplayId(10145); break; // Undead Male case 57: target->SetDisplayId(10146); break; // Tauren Female case 60: target->SetDisplayId(10147); break; // Gnome Male case 1563: target->SetDisplayId(10148); break; // Gnome Female case 1564: target->SetDisplayId(10149); break; // BloodElf Female case 15475: target->SetDisplayId(17830); break; // BloodElf Male case 15476: target->SetDisplayId(17829); break; // Dranei Female case 16126: target->SetDisplayId(17828); break; // Dranei Male case 16125: target->SetDisplayId(17827); break; default: break; } break; } case 42365: // Murloc costume target->SetDisplayId(21723); break; // case 44186: // Gossip NPC Appearance - All, Brewfest // break; // case 48305: // Gossip NPC Appearance - All, Spirit of Competition // break; case 50517: // Dread Corsair case 51926: // Corsair Costume { // expected for players uint32 race = target->getRace(); switch (race) { case RACE_HUMAN: target->SetDisplayId(target->getGender() == GENDER_MALE ? 25037 : 25048); break; case RACE_ORC: target->SetDisplayId(target->getGender() == GENDER_MALE ? 25039 : 25050); break; case RACE_DWARF: target->SetDisplayId(target->getGender() == GENDER_MALE ? 25034 : 25045); break; case RACE_NIGHTELF: target->SetDisplayId(target->getGender() == GENDER_MALE ? 25038 : 25049); break; case RACE_UNDEAD: target->SetDisplayId(target->getGender() == GENDER_MALE ? 25042 : 25053); break; case RACE_TAUREN: target->SetDisplayId(target->getGender() == GENDER_MALE ? 25040 : 25051); break; case RACE_GNOME: target->SetDisplayId(target->getGender() == GENDER_MALE ? 25035 : 25046); break; case RACE_TROLL: target->SetDisplayId(target->getGender() == GENDER_MALE ? 25041 : 25052); break; case RACE_GOBLIN: // not really player race (3.x), but model exist target->SetDisplayId(target->getGender() == GENDER_MALE ? 25036 : 25047); break; case RACE_BLOODELF: target->SetDisplayId(target->getGender() == GENDER_MALE ? 25032 : 25043); break; case RACE_DRAENEI: target->SetDisplayId(target->getGender() == GENDER_MALE ? 25033 : 25044); break; } break; } // case 50531: // Gossip NPC Appearance - All, Pirate Day // break; // case 51010: // Dire Brew // break; // case 53806: // Pygmy Oil // break; // case 62847: // NPC Appearance - Valiant 02 // break; // case 62852: // NPC Appearance - Champion 01 // break; // case 63965: // NPC Appearance - Champion 02 // break; // case 63966: // NPC Appearance - Valiant 03 // break; case 65386: // Honor the Dead case 65495: { switch (target->getGender()) { case GENDER_MALE: target->SetDisplayId(29203); // Chapman break; case GENDER_FEMALE: case GENDER_NONE: target->SetDisplayId(29204); // Catrina break; } break; } // case 65511: // Gossip NPC Appearance - Brewfest // break; // case 65522: // Gossip NPC Appearance - Winter Veil // break; // case 65523: // Gossip NPC Appearance - Default // break; // case 65524: // Gossip NPC Appearance - Lunar Festival // break; // case 65525: // Gossip NPC Appearance - Hallow's End // break; // case 65526: // Gossip NPC Appearance - Midsummer // break; // case 65527: // Gossip NPC Appearance - Spirit of Competition // break; case 65528: // Gossip NPC Appearance - Pirates' Day { // expecting npc's using this spell to have models with race info. // random gender, regardless of current gender switch (target->getRace()) { case RACE_HUMAN: target->SetDisplayId(roll_chance_i(50) ? 25037 : 25048); break; case RACE_ORC: target->SetDisplayId(roll_chance_i(50) ? 25039 : 25050); break; case RACE_DWARF: target->SetDisplayId(roll_chance_i(50) ? 25034 : 25045); break; case RACE_NIGHTELF: target->SetDisplayId(roll_chance_i(50) ? 25038 : 25049); break; case RACE_UNDEAD: target->SetDisplayId(roll_chance_i(50) ? 25042 : 25053); break; case RACE_TAUREN: target->SetDisplayId(roll_chance_i(50) ? 25040 : 25051); break; case RACE_GNOME: target->SetDisplayId(roll_chance_i(50) ? 25035 : 25046); break; case RACE_TROLL: target->SetDisplayId(roll_chance_i(50) ? 25041 : 25052); break; case RACE_GOBLIN: target->SetDisplayId(roll_chance_i(50) ? 25036 : 25047); break; case RACE_BLOODELF: target->SetDisplayId(roll_chance_i(50) ? 25032 : 25043); break; case RACE_DRAENEI: target->SetDisplayId(roll_chance_i(50) ? 25033 : 25044); break; } break; } case 65529: // Gossip NPC Appearance - Day of the Dead (DotD) // random, regardless of current gender target->SetDisplayId(roll_chance_i(50) ? 29203 : 29204); break; // case 66236: // Incinerate Flesh // break; // case 69999: // [DND] Swap IDs // break; // case 70764: // Citizen Costume (note: many spells w/same name) // break; // case 71309: // [DND] Spawn Portal // break; case 71450: // Crown Parcel Service Uniform target->SetDisplayId(target->getGender() == GENDER_MALE ? 31002 : 31003); break; // case 75531: // Gnomeregan Pride // break; // case 75532: // Darkspear Pride // break; default: sLog.outError("Aura::HandleAuraTransform, spell %u does not have creature entry defined, need custom defined model.", GetId()); break; } } else // m_modifier.m_miscvalue != 0 { uint32 model_id; CreatureInfo const* ci = ObjectMgr::GetCreatureTemplate(m_modifier.m_miscvalue); if (!ci) { model_id = 16358; // pig pink ^_^ sLog.outError("Auras: unknown creature id = %d (only need its modelid) Form Spell Aura Transform in Spell ID = %d", m_modifier.m_miscvalue, GetId()); } else { model_id = Creature::ChooseDisplayId(ci); } // Will use the default model here // Polymorph (sheep/penguin case) if (GetSpellProto()->SpellFamilyName == SPELLFAMILY_MAGE && GetSpellProto()->SpellIconID == 82) if (Unit* caster = GetCaster()) if (caster->HasAura(52648)) // Glyph of the Penguin model_id = 26452; target->SetDisplayId(model_id); // creature case, need to update equipment if additional provided if (ci && target->GetTypeId() == TYPEID_UNIT) { ((Creature*)target)->LoadEquipment(ci->EquipmentTemplateId, false); } // Dragonmaw Illusion (set mount model also) if (GetId() == 42016 && target->GetMountID() && !target->GetAurasByType(<API key>).empty()) target->SetUInt32Value(<API key>, 16314); } // update active transform spell only not set or not overwriting negative by positive case if (!target->getTransForm() || !IsPositiveSpell(GetId()) || IsPositiveSpell(target->getTransForm())) target->setTransForm(GetId()); // polymorph case if (Real && target->GetTypeId() == TYPEID_PLAYER && target->IsPolymorphed()) { // for players, start regeneration after 1s (in polymorph fast regeneration case) // only if caster is Player (after patch 2.4.2) if (GetCasterGuid().IsPlayer()) ((Player*)target)->setRegenTimer(1 * IN_MILLISECONDS); // dismount polymorphed target (after patch 2.4.2) if (target->IsMounted()) target-><API key>(SPELL_AURA_MOUNTED, GetHolder()); } } else // !apply { // ApplyModifier(true) will reapply it if need target->setTransForm(0); target->SetDisplayId(target->GetNativeDisplayId()); // apply default equipment for creature case if (target->GetTypeId() == TYPEID_UNIT) { ((Creature*)target)->LoadEquipment(((Creature*)target)->GetCreatureInfo()->EquipmentTemplateId, true); } // re-apply some from still active with preference negative cases Unit::AuraList const& otherTransforms = target->GetAurasByType(<API key>); if (!otherTransforms.empty()) { // look for other transform auras Aura* handledAura = *otherTransforms.begin(); for (Unit::AuraList::const_iterator i = otherTransforms.begin(); i != otherTransforms.end(); ++i) { // negative auras are preferred if (!IsPositiveSpell((*i)->GetSpellProto()->Id)) { handledAura = *i; break; } } handledAura->ApplyModifier(true); } // Dragonmaw Illusion (restore mount model) if (GetId() == 42016 && target->GetMountID() == 16314) { if (!target->GetAurasByType(SPELL_AURA_MOUNTED).empty()) { uint32 cr_id = target->GetAurasByType(SPELL_AURA_MOUNTED).front()->GetModifier()->m_miscvalue; if (CreatureInfo const* ci = ObjectMgr::GetCreatureTemplate(cr_id)) { uint32 display_id = Creature::ChooseDisplayId(ci); CreatureModelInfo const* minfo = sObjectMgr.<API key>(display_id); if (minfo) display_id = minfo->modelid; target->SetUInt32Value(<API key>, display_id); } } } } } void Aura::HandleForceReaction(bool apply, bool Real) { if (GetTarget()->GetTypeId() != TYPEID_PLAYER) { return; } if (!Real) { return; } Player* player = (Player*)GetTarget(); uint32 faction_id = m_modifier.m_miscvalue; ReputationRank faction_rank = ReputationRank(m_modifier.m_amount); player->GetReputationMgr().ApplyForceReaction(faction_id, faction_rank, apply); player->GetReputationMgr().SendForceReactions(); // stop fighting if at apply forced rank friendly or at remove real rank friendly if ((apply && faction_rank >= REP_FRIENDLY) || (!apply && player->GetReputationRank(faction_id) >= REP_FRIENDLY)) { player->StopAttackFaction(faction_id); } } void Aura::HandleAuraModSkill(bool apply, bool /*Real*/) { if (GetTarget()->GetTypeId() != TYPEID_PLAYER) { return; } uint32 prot = GetSpellProto()->EffectMiscValue[m_effIndex]; int32 points = GetModifier()->m_amount; ((Player*)GetTarget())->ModifySkillBonus(prot, (apply ? points : -points), m_modifier.m_auraname == <API key>); if (prot == SKILL_DEFENSE) { ((Player*)GetTarget())-><API key>(); } } void Aura::<API key>(bool apply, bool Real) { if (Real && !apply) { if (m_removeMode != <API key>) { return; } // Item amount if (m_modifier.m_amount <= 0) { return; } SpellEntry const* spellInfo = GetSpellProto(); if (spellInfo->EffectItemType[m_effIndex] == 0) { return; } Unit* victim = GetTarget(); Unit* caster = GetCaster(); if (!caster || caster->GetTypeId() != TYPEID_PLAYER) { return; } // Soul Shard (target req.) if (spellInfo->EffectItemType[m_effIndex] == 6265) { // Only from non-grey units if (!((Player*)caster)->isHonorOrXPTarget(victim) || (victim->GetTypeId() == TYPEID_UNIT && !((Player*)caster)->isAllowedToLoot((Creature*)victim))) { return; } } // Adding items uint32 noSpaceForCount = 0; uint32 count = m_modifier.m_amount; ItemPosCountVec dest; InventoryResult msg = ((Player*)caster)->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, spellInfo->EffectItemType[m_effIndex], count, &noSpaceForCount); if (msg != EQUIP_ERR_OK) { count -= noSpaceForCount; ((Player*)caster)->SendEquipError(msg, NULL, NULL, spellInfo->EffectItemType[m_effIndex]); if (count == 0) { return; } } Item* newitem = ((Player*)caster)->StoreNewItem(dest, spellInfo->EffectItemType[m_effIndex], true); ((Player*)caster)->SendNewItem(newitem, count, true, true); // Soul Shard (glyph bonus) if (spellInfo->EffectItemType[m_effIndex] == 6265) { // Glyph of Soul Shard if (caster->HasAura(58070) && roll_chance_i(40)) caster->CastSpell(caster, 58068, true, NULL, this); } } } void Aura::HandleBindSight(bool apply, bool /*Real*/) { Unit* caster = GetCaster(); if (!caster || caster->GetTypeId() != TYPEID_PLAYER) { return; } Camera& camera = ((Player*)caster)->GetCamera(); if (apply) { camera.SetView(GetTarget()); } else { camera.ResetView(); } } void Aura::HandleFarSight(bool apply, bool /*Real*/) { Unit* caster = GetCaster(); if (!caster || caster->GetTypeId() != TYPEID_PLAYER) { return; } Camera& camera = ((Player*)caster)->GetCamera(); if (apply) { camera.SetView(GetTarget()); } else { camera.ResetView(); } } void Aura::<API key>(bool apply, bool /*Real*/) { if (GetTarget()->GetTypeId() != TYPEID_PLAYER) { return; } if (apply) { GetTarget()-><API key>(GetHolder()); } if (apply) { GetTarget()->SetFlag(<API key>, uint32(1) << (m_modifier.m_miscvalue - 1)); } else { GetTarget()->RemoveFlag(<API key>, uint32(1) << (m_modifier.m_miscvalue - 1)); } } void Aura::<API key>(bool apply, bool /*Real*/) { if (GetTarget()->GetTypeId() != TYPEID_PLAYER) { return; } if (apply) { GetTarget()-><API key>(GetHolder()); } if (apply) { GetTarget()->SetFlag(<API key>, uint32(1) << (m_modifier.m_miscvalue - 1)); } else { GetTarget()->RemoveFlag(<API key>, uint32(1) << (m_modifier.m_miscvalue - 1)); } } void Aura::<API key>(bool apply, bool /*Real*/) { if (GetTarget()->GetTypeId() != TYPEID_PLAYER) { return; } if (apply) { GetTarget()-><API key>(GetHolder()); } GetTarget()->ApplyModByteFlag(PLAYER_FIELD_BYTES, 0, <API key>, apply); } void Aura::HandleAuraModScale(bool apply, bool /*Real*/) { GetTarget()-><API key>(<API key>, float(m_modifier.m_amount), apply); GetTarget()->UpdateModelData(); } void Aura::HandleModPossess(bool apply, bool Real) { if (!Real) { return; } Unit* target = GetTarget(); // not possess yourself if (GetCasterGuid() == target->GetObjectGuid()) { return; } Unit* caster = GetCaster(); if (!caster || caster->GetTypeId() != TYPEID_PLAYER) { return; } Player* p_caster = (Player*)caster; Camera& camera = p_caster->GetCamera(); if (apply) { target->addUnitState(<API key>); target->SetFlag(UNIT_FIELD_FLAGS, <API key>); target->SetCharmerGuid(p_caster->GetObjectGuid()); target->setFaction(p_caster->getFaction()); // target should became visible at SetView call(if not visible before): // otherwise client\p_caster will ignore packets from the target(SetClientControl for example) camera.SetView(target); p_caster->SetCharm(target); p_caster->SetClientControl(target, 1); p_caster->SetMover(target); target->CombatStop(true); target->DeleteThreatList(); target-><API key>().deleteReferences(); if (CharmInfo* charmInfo = target->InitCharmInfo(target)) { charmInfo-><API key>(); charmInfo->SetReactState(REACT_PASSIVE); charmInfo->SetCommandState(COMMAND_STAY); } p_caster-><API key>(); if (target->GetTypeId() == TYPEID_UNIT) { ((Creature*)target)->AIM_Initialize(); } else if (target->GetTypeId() == TYPEID_PLAYER) { ((Player*)target)->SetClientControl(target, 0); } } else { p_caster->SetCharm(NULL); p_caster->SetClientControl(target, 0); p_caster->SetMover(NULL); // there is a possibility that target became invisible for client\p_caster at ResetView call: // it must be called after movement control unapplying, not before! the reason is same as at aura applying camera.ResetView(); p_caster->RemovePetActionBar(); // on delete only do caster related effects if (m_removeMode == <API key>) { return; } target->clearUnitState(<API key>); target->CombatStop(true); target->DeleteThreatList(); target-><API key>().deleteReferences(); target->RemoveFlag(UNIT_FIELD_FLAGS, <API key>); target->SetCharmerGuid(ObjectGuid()); if (target->GetTypeId() == TYPEID_PLAYER) { ((Player*)target)->setFactionForRace(target->getRace()); ((Player*)target)->SetClientControl(target, 1); } else if (target->GetTypeId() == TYPEID_UNIT) { CreatureInfo const* cinfo = ((Creature*)target)->GetCreatureInfo(); target->setFaction(cinfo->FactionAlliance); } if (target->GetTypeId() == TYPEID_UNIT) { ((Creature*)target)->AIM_Initialize(); target->AttackedBy(caster); } } } void Aura::HandleModPossessPet(bool apply, bool Real) { if (!Real) { return; } Unit* caster = GetCaster(); if (!caster || caster->GetTypeId() != TYPEID_PLAYER) { return; } Unit* target = GetTarget(); if (target->GetTypeId() != TYPEID_UNIT || !((Creature*)target)->IsPet()) { return; } Pet* pet = (Pet*)target; Player* p_caster = (Player*)caster; Camera& camera = p_caster->GetCamera(); if (apply) { pet->addUnitState(<API key>); // target should became visible at SetView call(if not visible before): // otherwise client\p_caster will ignore packets from the target(SetClientControl for example) camera.SetView(pet); p_caster->SetCharm(pet); p_caster->SetClientControl(pet, 1); ((Player*)caster)->SetMover(pet); pet->SetFlag(UNIT_FIELD_FLAGS, <API key>); pet->StopMoving(); pet->GetMotionMaster()->Clear(false); pet->GetMotionMaster()->MoveIdle(); } else { p_caster->SetCharm(NULL); p_caster->SetClientControl(pet, 0); p_caster->SetMover(NULL); // there is a possibility that target became invisible for client\p_caster at ResetView call: // it must be called after movement control unapplying, not before! the reason is same as at aura applying camera.ResetView(); // on delete only do caster related effects if (m_removeMode == <API key>) { return; } pet->clearUnitState(<API key>); pet->RemoveFlag(UNIT_FIELD_FLAGS, <API key>); pet->AttackStop(); // out of range pet dismissed if (!pet->IsWithinDistInMap(p_caster, pet->GetMap()-><API key>())) { p_caster->RemovePet(PET_SAVE_REAGENTS); } else { pet->GetMotionMaster()->MoveFollow(caster, PET_FOLLOW_DIST, PET_FOLLOW_ANGLE); } } } void Aura::<API key>(bool /*Apply*/, bool Real) { if (!Real) return; // Recalculate pet talent points if (Pet* pet = GetTarget()->GetPet()) pet->InitTalentForLevel(); } void Aura::HandleModCharm(bool apply, bool Real) { if (!Real) { return; } Unit* target = GetTarget(); // not charm yourself if (GetCasterGuid() == target->GetObjectGuid()) { return; } Unit* caster = GetCaster(); if (!caster) { return; } if (apply) { // is it really need after spell check checks? target-><API key>(<API key>, GetHolder()); target-><API key>(<API key>, GetHolder()); target->SetCharmerGuid(GetCasterGuid()); target->setFaction(caster->getFaction()); target->CastStop(target == caster ? GetId() : 0); caster->SetCharm(target); target->CombatStop(true); target->DeleteThreatList(); target-><API key>().deleteReferences(); if (target->GetTypeId() == TYPEID_UNIT) { ((Creature*)target)->AIM_Initialize(); CharmInfo* charmInfo = target->InitCharmInfo(target); charmInfo-><API key>(); charmInfo->SetReactState(REACT_DEFENSIVE); if (caster->GetTypeId() == TYPEID_PLAYER && caster->getClass() == CLASS_WARLOCK) { CreatureInfo const* cinfo = ((Creature*)target)->GetCreatureInfo(); if (cinfo && cinfo->CreatureType == CREATURE_TYPE_DEMON) { // creature with pet number expected have class set if (target->GetByteValue(UNIT_FIELD_BYTES_0, 1) == 0) { if (cinfo->UnitClass == 0) { sLog.outErrorDb("Creature (Entry: %u) have unit_class = 0 but used in charmed spell, that will be result client crash.", cinfo->Entry); } else { sLog.outError("Creature (Entry: %u) have unit_class = %u but at charming have class 0!!! that will be result client crash.", cinfo->Entry, cinfo->UnitClass); } target->SetByteValue(UNIT_FIELD_BYTES_0, 1, CLASS_MAGE); } // just to enable stat window charmInfo->SetPetNumber(sObjectMgr.GeneratePetNumber(), true); // if charmed two demons the same session, the 2nd gets the 1st one's name target->SetUInt32Value(<API key>, uint32(time(NULL))); } } } if (caster->GetTypeId() == TYPEID_PLAYER) { ((Player*)caster)-><API key>(); } } else { target->SetCharmerGuid(ObjectGuid()); if (target->GetTypeId() == TYPEID_PLAYER) { ((Player*)target)->setFactionForRace(target->getRace()); } else { CreatureInfo const* cinfo = ((Creature*)target)->GetCreatureInfo(); // restore faction if (((Creature*)target)->IsPet()) { if (Unit* owner = target->GetOwner()) { target->setFaction(owner->getFaction()); } else if (cinfo) { target->setFaction(cinfo->FactionAlliance); } } else if (cinfo) // normal creature { target->setFaction(cinfo->FactionAlliance); } // restore UNIT_FIELD_BYTES_0 if (cinfo && caster->GetTypeId() == TYPEID_PLAYER && caster->getClass() == CLASS_WARLOCK && cinfo->CreatureType == CREATURE_TYPE_DEMON) { // DB must have proper class set in field at loading, not req. restore, including workaround case at apply // m_target->SetByteValue(UNIT_FIELD_BYTES_0, 1, cinfo->unit_class); if (target->GetCharmInfo()) { target->GetCharmInfo()->SetPetNumber(0, true); } else { sLog.outError("Aura::HandleModCharm: target (GUID: %u TypeId: %u) has a charm aura but no charm info!", target->GetGUIDLow(), target->GetTypeId()); } } } caster->SetCharm(NULL); if (caster->GetTypeId() == TYPEID_PLAYER) { ((Player*)caster)->RemovePetActionBar(); } target->CombatStop(true); target->DeleteThreatList(); target-><API key>().deleteReferences(); if (target->GetTypeId() == TYPEID_UNIT) { ((Creature*)target)->AIM_Initialize(); target->AttackedBy(caster); } } } void Aura::HandleModConfuse(bool apply, bool Real) { if (!Real) { return; } GetTarget()->SetConfused(apply, GetCasterGuid(), GetId()); } void Aura::HandleModFear(bool apply, bool Real) { if (!Real) { return; } GetTarget()->SetFeared(apply, GetCasterGuid(), GetId()); } void Aura::HandleFeignDeath(bool apply, bool Real) { if (!Real) { return; } GetTarget()->SetFeignDeath(apply, GetCasterGuid()); } void Aura::HandleAuraModDisarm(bool apply, bool Real) { if (!Real) { return; } Unit* target = GetTarget(); if (!apply && target->HasAuraType(GetModifier()->m_auraname)) { return; } uint32 flags; uint32 field; WeaponAttackType attack_type; switch (GetModifier()->m_auraname) { default: case <API key>: { field = UNIT_FIELD_FLAGS; flags = UNIT_FLAG_DISARMED; attack_type = BASE_ATTACK; break; } case <API key>: { field = UNIT_FIELD_FLAGS_2; flags = <API key>; attack_type = OFF_ATTACK; break; } case <API key>: { field = UNIT_FIELD_FLAGS_2; flags = <API key>; attack_type = RANGED_ATTACK; break; } } target->ApplyModFlag(field, flags, apply); if (target->GetTypeId() != TYPEID_PLAYER) { return; } // main-hand attack speed already set to special value for feral form already and don't must change and reset at remove. if (target->IsInFeralForm()) { return; } if (apply) target->SetAttackTime(attack_type, BASE_ATTACK_TIME); else { ((Player*)target)-><API key>(); } target-><API key>(attack_type); } void Aura::HandleAuraModStun(bool apply, bool Real) { if (!Real) { return; } Unit* target = GetTarget(); if (apply) { // Frost stun aura -> freeze/unfreeze target if (GetSpellSchoolMask(GetSpellProto()) & <API key>) { target->ModifyAuraState(AURA_STATE_FROZEN, apply); } target->addUnitState(UNIT_STAT_STUNNED); target->SetTargetGuid(ObjectGuid()); target->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_STUNNED); target->CastStop(target->GetObjectGuid() == GetCasterGuid() ? GetId() : 0); // Creature specific if (target->GetTypeId() != TYPEID_PLAYER) { target->StopMoving(); } else { ((Player*)target)->m_movementInfo.SetMovementFlags(MOVEFLAG_NONE); target->SetStandState(<API key>);// in 1.5 client target->SetRoot(true); } // Summon the Naj'entus Spine GameObject on target if spell is Impaling Spine if (GetId() == 39837) { GameObject* pObj = new GameObject; if (pObj->Create(target->GetMap()-><API key>(HIGHGUID_GAMEOBJECT), 185584, target->GetMap(), target->GetPhaseMask(), target->GetPositionX(), target->GetPositionY(), target->GetPositionZ(), target->GetOrientation())) { pObj->SetRespawnTime(GetAuraDuration() / IN_MILLISECONDS); pObj->SetSpellId(GetId()); target->AddGameObject(pObj); target->GetMap()->Add(pObj); } else delete pObj; } } else { // Frost stun aura -> freeze/unfreeze target if (GetSpellSchoolMask(GetSpellProto()) & <API key>) { bool found_another = false; for (AuraType const* itr = &frozenAuraTypes[0]; *itr != SPELL_AURA_NONE; ++itr) { Unit::AuraList const& auras = target->GetAurasByType(*itr); for (Unit::AuraList::const_iterator i = auras.begin(); i != auras.end(); ++i) { if (GetSpellSchoolMask((*i)->GetSpellProto()) & <API key>) { found_another = true; break; } } if (found_another) { break; } } if (!found_another) { target->ModifyAuraState(AURA_STATE_FROZEN, apply); } } // Real remove called after current aura remove from lists, check if other similar auras active if (target->HasAuraType(SPELL_AURA_MOD_STUN)) { return; } target->clearUnitState(UNIT_STAT_STUNNED); target->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_STUNNED); if (!target->hasUnitState(UNIT_STAT_ROOT)) // prevent allow move if have also root effect { if (target->getVictim() && target->IsAlive()) { target->SetTargetGuid(target->getVictim()->GetObjectGuid()); } target->SetRoot(false); } // Wyvern Sting if (GetSpellProto()->SpellFamilyName == SPELLFAMILY_HUNTER && GetSpellProto()->SpellFamilyFlags & UI64LIT(0x0000100000000000)) { Unit* caster = GetCaster(); if (!caster || caster->GetTypeId() != TYPEID_PLAYER) { return; } uint32 spell_id = 0; switch (GetId()) { case 19386: spell_id = 24131; break; case 24132: spell_id = 24134; break; case 24133: spell_id = 24135; break; case 27068: spell_id = 27069; break; case 49011: spell_id = 49009; break; case 49012: spell_id = 49010; break; default: sLog.outError("Spell selection called for unexpected original spell %u, new spell for this spell family?", GetId()); return; } SpellEntry const* spellInfo = sSpellStore.LookupEntry(spell_id); if (!spellInfo) { return; } caster->CastSpell(target, spellInfo, true, NULL, this); return; } } } void Aura::HandleModStealth(bool apply, bool Real) { Unit* target = GetTarget(); if (apply) { // drop flag at stealth in bg target-><API key>(<API key>); // only at real aura add if (Real) { target->SetStandFlags(<API key>); if (target->GetTypeId() == TYPEID_PLAYER) target->SetByteFlag(PLAYER_FIELD_BYTES2, 3, <API key>); // apply only if not in GM invisibility (and overwrite invisibility state) if (target->GetVisibility() != VISIBILITY_OFF) { target->SetVisibility(<API key>); target->SetVisibility(<API key>); } // apply full stealth period bonuses only at first stealth aura in stack if (target->GetAurasByType(<API key>).size() <= 1) { Unit::AuraList const& mDummyAuras = target->GetAurasByType(SPELL_AURA_DUMMY); for (Unit::AuraList::const_iterator i = mDummyAuras.begin(); i != mDummyAuras.end(); ++i) { // Master of Subtlety if ((*i)->GetSpellProto()->SpellIconID == 2114 && GetSpellProto()->SpellFamilyName == SPELLFAMILY_ROGUE) { target-><API key>(31666); int32 bp = (*i)->GetModifier()->m_amount; target->CastCustomSpell(target, 31665, &bp, NULL, NULL, true); } // Overkill else if ((*i)->GetId() == 58426 && GetSpellProto()->SpellFamilyFlags & UI64LIT(0x0000000000400000)) { target->CastSpell(target, 58427, true); } } } } } else { // only at real aura remove of _last_ <API key> if (Real && !target->HasAuraType(<API key>)) { // if no GM invisibility if (target->GetVisibility() != VISIBILITY_OFF) { target->RemoveStandFlags(<API key>); if (target->GetTypeId() == TYPEID_PLAYER) target->RemoveByteFlag(PLAYER_FIELD_BYTES2, 3, <API key>); // restore invisibility if any if (target->HasAuraType(<API key>)) { target->SetVisibility(<API key>); target->SetVisibility(<API key>); } else { target->SetVisibility(VISIBILITY_ON); } } // apply delayed talent bonus remover at last stealth aura remove Unit::AuraList const& mDummyAuras = target->GetAurasByType(SPELL_AURA_DUMMY); for (Unit::AuraList::const_iterator i = mDummyAuras.begin(); i != mDummyAuras.end(); ++i) { // Master of Subtlety if ((*i)->GetSpellProto()->SpellIconID == 2114) target->CastSpell(target, 31666, true); // Overkill else if ((*i)->GetId() == 58426 && GetSpellProto()->SpellFamilyFlags & UI64LIT(0x0000000000400000)) { if (SpellAuraHolder* holder = target->GetSpellAuraHolder(58427)) { holder->SetAuraMaxDuration(20 * IN_MILLISECONDS); holder->RefreshHolder(); } } } } } } void Aura::HandleInvisibility(bool apply, bool Real) { Unit* target = GetTarget(); if (apply) { target->m_invisibilityMask |= (1 << m_modifier.m_miscvalue); target-><API key>(<API key>); if (Real && target->GetTypeId() == TYPEID_PLAYER) { // apply glow vision target->SetByteFlag(PLAYER_FIELD_BYTES2, 3, <API key>); } // apply only if not in GM invisibility and not stealth if (target->GetVisibility() == VISIBILITY_ON) { // Aura not added yet but visibility code expect temporary add aura target->SetVisibility(<API key>); target->SetVisibility(<API key>); } } else { // recalculate value at modifier remove (current aura already removed) target->m_invisibilityMask = 0; Unit::AuraList const& auras = target->GetAurasByType(<API key>); for (Unit::AuraList::const_iterator itr = auras.begin(); itr != auras.end(); ++itr) { target->m_invisibilityMask |= (1 << (*itr)->GetModifier()->m_miscvalue); } // only at real aura remove and if not have different invisibility auras. if (Real && target->m_invisibilityMask == 0) { // remove glow vision if (target->GetTypeId() == TYPEID_PLAYER) target->RemoveByteFlag(PLAYER_FIELD_BYTES2, 3, <API key>); // apply only if not in GM invisibility & not stealthed while invisible if (target->GetVisibility() != VISIBILITY_OFF) { // if have stealth aura then already have stealth visibility if (!target->HasAuraType(<API key>)) { target->SetVisibility(VISIBILITY_ON); } } } if (GetId() == 48809) // Binding Life target->CastSpell(target, GetSpellProto()-><API key>(m_effIndex), true); } } void Aura::<API key>(bool apply, bool Real) { Unit* target = GetTarget(); if (apply) { target-><API key> |= (1 << m_modifier.m_miscvalue); } else { // recalculate value at modifier remove (current aura already removed) target-><API key> = 0; Unit::AuraList const& auras = target->GetAurasByType(<API key>); for (Unit::AuraList::const_iterator itr = auras.begin(); itr != auras.end(); ++itr) { target-><API key> |= (1 << (*itr)->GetModifier()->m_miscvalue); } } if (Real && target->GetTypeId() == TYPEID_PLAYER) { ((Player*)target)->GetCamera().<API key>(); } } void Aura::HandleDetectAmore(bool apply, bool /*real*/) { GetTarget()->ApplyModByteFlag(PLAYER_FIELD_BYTES2, 3, (<API key> << m_modifier.m_amount), apply); } void Aura::HandleAuraModRoot(bool apply, bool Real) { // only at real add/remove aura if (!Real) { return; } Unit* target = GetTarget(); if (apply) { // Frost root aura -> freeze/unfreeze target if (GetSpellSchoolMask(GetSpellProto()) & <API key>) { target->ModifyAuraState(AURA_STATE_FROZEN, apply); } target->addUnitState(UNIT_STAT_ROOT); if (target->GetTypeId() == TYPEID_PLAYER) { target->SetRoot(true); // Clear unit movement flags ((Player*)target)->m_movementInfo.SetMovementFlags(MOVEFLAG_NONE); } else { target->StopMoving(); } } else { // Frost root aura -> freeze/unfreeze target if (GetSpellSchoolMask(GetSpellProto()) & <API key>) { bool found_another = false; for (AuraType const* itr = &frozenAuraTypes[0]; *itr != SPELL_AURA_NONE; ++itr) { Unit::AuraList const& auras = target->GetAurasByType(*itr); for (Unit::AuraList::const_iterator i = auras.begin(); i != auras.end(); ++i) { if (GetSpellSchoolMask((*i)->GetSpellProto()) & <API key>) { found_another = true; break; } } if (found_another) { break; } } if (!found_another) { target->ModifyAuraState(AURA_STATE_FROZEN, apply); } } // Real remove called after current aura remove from lists, check if other similar auras active if (target->HasAuraType(SPELL_AURA_MOD_ROOT)) { return; } target->clearUnitState(UNIT_STAT_ROOT); if (!target->hasUnitState(UNIT_STAT_STUNNED) && (target->GetTypeId() == TYPEID_PLAYER)) // prevent allow move if have also stun effect { target->SetRoot(false); } } } void Aura::<API key>(bool apply, bool Real) { // only at real add/remove aura if (!Real) { return; } Unit* target = GetTarget(); if (apply) { target->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SILENCED); // Stop cast only spells vs PreventionType == <API key> for (uint32 i = CURRENT_MELEE_SPELL; i < CURRENT_MAX_SPELL; ++i) if (Spell* spell = target->GetCurrentSpell(CurrentSpellTypes(i))) if (spell->m_spellInfo->PreventionType == <API key>) // Stop spells on prepare or casting state { target->InterruptSpell(CurrentSpellTypes(i), false); } } else { // Real remove called after current aura remove from lists, check if other similar auras active if (target->HasAuraType(<API key>)) { return; } target->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SILENCED); } } void Aura::HandleModThreat(bool apply, bool Real) { // only at real add/remove aura if (!Real) { return; } Unit* target = GetTarget(); if (!target->IsAlive()) { return; } int level_diff = 0; int multiplier = 0; switch (GetId()) { // Arcane Shroud case 26400: level_diff = target->getLevel() - 60; multiplier = 2; break; // The Eye of Diminution case 28862: level_diff = target->getLevel() - 60; multiplier = 1; break; } if (level_diff > 0) { m_modifier.m_amount += multiplier * level_diff; } if (target->GetTypeId() == TYPEID_PLAYER) for (int8 x = 0; x < MAX_SPELL_SCHOOL; ++x) if (m_modifier.m_miscvalue & int32(1 << x)) { <API key>(target->m_threatModifier[x], float(m_modifier.m_amount), apply); } } void Aura::<API key>(bool apply, bool Real) { // only at real add/remove aura if (!Real) { return; } Unit* target = GetTarget(); if (!target->IsAlive() || target->GetTypeId() != TYPEID_PLAYER) { return; } Unit* caster = GetCaster(); if (!caster || !caster->IsAlive()) { return; } float threatMod = apply ? float(m_modifier.m_amount) : float(-m_modifier.m_amount); target-><API key>().threatAssist(caster, threatMod, GetSpellProto()); } void Aura::HandleModTaunt(bool apply, bool Real) { // only at real add/remove aura if (!Real) { return; } Unit* target = GetTarget(); if (!target->IsAlive() || !target->CanHaveThreatList()) { return; } Unit* caster = GetCaster(); if (!caster || !caster->IsAlive()) { return; } if (apply) { target->TauntApply(caster); } else { // When taunt aura fades out, mob will switch to previous target if current has less than 1.1 * secondthreat target->TauntFadeOut(caster); } } void Aura::<API key>(bool apply, bool Real) { // all applied/removed only at real aura add/remove if (!Real) return; Unit* target = GetTarget(); if (target->GetTypeId() == TYPEID_PLAYER) { int32 point = target->GetInt32Value(<API key>); point += (apply ? 1 : -1) * GetBasePoints(); target->SetInt32Value(<API key>, point); } target-><API key>(); } /*** MODIFY SPEED ***/ void Aura::<API key>(bool /*apply*/, bool Real) { // all applied/removed only at real aura add/remove if (!Real) { return; } GetTarget()->UpdateSpeed(MOVE_RUN, true); } void Aura::<API key>(bool apply, bool Real) { // all applied/removed only at real aura add/remove if (!Real) { return; } Unit* target = GetTarget(); target->UpdateSpeed(MOVE_RUN, true); // Festive Holiday Mount if (apply && GetSpellProto()->SpellIconID != 1794 && target->HasAura(62061)) // Reindeer Transformation target->CastSpell(target, 25860, true, NULL, this); } void Aura::<API key>(bool apply, bool Real) { // all applied/removed only at real aura add/remove if (!Real) return; Unit* target = GetTarget(); // Enable Fly mode for flying mounts if (m_modifier.m_auraname == <API key>) { target->SetCanFly(apply); // Players on flying mounts must be immune to polymorph if (target->GetTypeId() == TYPEID_PLAYER) target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_POLYMORPH, apply); // Dragonmaw Illusion (overwrite mount model, mounted aura already applied) if (apply && target->HasAura(42016, EFFECT_INDEX_0) && target->GetMountID()) target->SetUInt32Value(<API key>, 16314); // Festive Holiday Mount if (apply && GetSpellProto()->SpellIconID != 1794 && target->HasAura(62061)) // Reindeer Transformation target->CastSpell(target, 25860, true, NULL, this); } // Swift Flight Form check for higher speed flying mounts if (apply && target->GetTypeId() == TYPEID_PLAYER && GetSpellProto()->Id == 40121) { for (PlayerSpellMap::const_iterator iter = ((Player*)target)->GetSpellMap().begin(); iter != ((Player*)target)->GetSpellMap().end(); ++iter) { if (iter->second.state != PLAYERSPELL_REMOVED) { bool changedSpeed = false; SpellEntry const* spellInfo = sSpellStore.LookupEntry(iter->first); for (int i = 0; i < MAX_EFFECT_INDEX; ++i) { if (spellInfo->EffectApplyAuraName[i] == <API key>) { int32 mountSpeed = spellInfo-><API key>(SpellEffectIndex(i)); if (mountSpeed > m_modifier.m_amount) { m_modifier.m_amount = mountSpeed; changedSpeed = true; break; } } } if (changedSpeed) break; } } } target->UpdateSpeed(MOVE_FLIGHT, true); } void Aura::<API key>(bool /*apply*/, bool Real) { // all applied/removed only at real aura add/remove if (!Real) { return; } GetTarget()->UpdateSpeed(MOVE_SWIM, true); } void Aura::<API key>(bool apply, bool Real) { // all applied/removed only at real aura add/remove if (!Real) { return; } Unit* target = GetTarget(); if (apply) { // Gronn Lord's Grasp, becomes stoned if (GetId() == 33572) { if (GetStackAmount() >= 5 && !target->HasAura(33652)) target->CastSpell(target, 33652, true); } } target->UpdateSpeed(MOVE_RUN, true); target->UpdateSpeed(MOVE_SWIM, true); target->UpdateSpeed(MOVE_FLIGHT, true); } void Aura::<API key>(bool /*apply*/, bool Real) { // all applied/removed only at real aura add/remove if (!Real) { return; } Unit* target = GetTarget(); target->UpdateSpeed(MOVE_RUN, true); target->UpdateSpeed(MOVE_SWIM, true); target->UpdateSpeed(MOVE_FLIGHT, true); } /*** IMMUNITY ***/ void Aura::<API key>(bool apply, bool /*Real*/) { uint32 misc = m_modifier.m_miscvalue; // Forbearance // in DBC wrong mechanic immune since 3.0.x if (GetId() == 25771) misc = <API key>; Unit* target = GetTarget(); if (apply && GetSpellProto()->HasAttribute(<API key>)) { uint32 mechanic = 1 << (misc - 1); // immune movement impairment and loss of control (spell data have special structure for mark this case) if (<API key>(GetSpellProto())) mechanic = <API key>; target-><API key>(mechanic, GetId()); } target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, misc, apply); // Bestial Wrath if (GetSpellProto()->SpellFamilyName == SPELLFAMILY_HUNTER && GetSpellProto()->SpellIconID == 1680) { // The Beast Within cast on owner if talent present if (Unit* owner = target->GetOwner()) { // Search talent The Beast Within Unit::AuraList const& dummyAuras = owner->GetAurasByType(<API key>); for (Unit::AuraList::const_iterator i = dummyAuras.begin(); i != dummyAuras.end(); ++i) { if ((*i)->GetSpellProto()->SpellIconID == 2229) { if (apply) owner->CastSpell(owner, 34471, true, NULL, this); else owner-><API key>(34471); break; } } } } // Heroic Fury (Intercept cooldown remove) else if (apply && GetSpellProto()->Id == 60970 && target->GetTypeId() == TYPEID_PLAYER) ((Player*)target)->RemoveSpellCooldown(20252, true); } void Aura::<API key>(bool apply, bool /*Real*/) { uint32 mechanic = m_modifier.m_miscvalue; if (apply && GetSpellProto()->HasAttribute(<API key>)) { GetTarget()-><API key>(mechanic, GetId()); } // check implemented in Unit::IsImmuneToSpell and Unit::<API key> } // this method is called whenever we add / remove aura which gives m_target some imunity to some spell effect void Aura::<API key>(bool apply, bool /*Real*/) { Unit* target = GetTarget(); // when removing flag aura, handle flag drop if (!apply && target->GetTypeId() == TYPEID_PLAYER && (GetSpellProto()->AuraInterruptFlags & <API key>)) { Player* player = (Player*)target; if (BattleGround* bg = player->GetBattleGround()) { bg-><API key>(player); } else if (OutdoorPvP* outdoorPvP = sOutdoorPvPMgr.GetScript(player->GetCachedZoneId())) { outdoorPvP->HandleDropFlag(player, GetSpellProto()->Id); } } target->ApplySpellImmune(GetId(), IMMUNITY_EFFECT, m_modifier.m_miscvalue, apply); } void Aura::<API key>(bool apply, bool Real) { if (apply && Real && GetSpellProto()->HasAttribute(<API key>)) { Unit::AuraList const& auraList = GetTarget()->GetAurasByType(AuraType(m_modifier.m_miscvalue)); for (Unit::AuraList::const_iterator itr = auraList.begin(); itr != auraList.end();) { if (auraList.front() != this) // skip itself aura (it already added) { GetTarget()-><API key>(auraList.front()->GetId()); itr = auraList.begin(); } else { ++itr; } } } GetTarget()->ApplySpellImmune(GetId(), IMMUNITY_STATE, m_modifier.m_miscvalue, apply); } void Aura::<API key>(bool apply, bool Real) { Unit* target = GetTarget(); target->ApplySpellImmune(GetId(), IMMUNITY_SCHOOL, m_modifier.m_miscvalue, apply); // remove all flag auras (they are positive, but they must be removed when you are immune) if (GetSpellProto()->HasAttribute(<API key>) && GetSpellProto()->HasAttribute(<API key>)) { target-><API key>(<API key>); } // TODO: optimalize this cycle - use <API key> call or something else if (Real && apply && GetSpellProto()->HasAttribute(<API key>) && IsPositiveSpell(GetId())) // Only positive immunity removes auras { uint32 school_mask = m_modifier.m_miscvalue; Unit::SpellAuraHolderMap& Auras = target-><API key>(); for (Unit::SpellAuraHolderMap::iterator iter = Auras.begin(), next; iter != Auras.end(); iter = next) { next = iter; ++next; SpellEntry const* spell = iter->second->GetSpellProto(); if ((GetSpellSchoolMask(spell) & school_mask) // Check for school mask && !spell->HasAttribute(<API key>) // Spells unaffected by invulnerability && !iter->second->IsPositive() // Don't remove positive spells && spell->Id != GetId()) // Don't remove self { target-><API key>(spell->Id); if (Auras.empty()) { break; } else { next = Auras.begin(); } } } } if (Real && GetSpellProto()->Mechanic == MECHANIC_BANISH) { if (apply) { target->addUnitState(UNIT_STAT_ISOLATED); } else { target->clearUnitState(UNIT_STAT_ISOLATED); } } } void Aura::<API key>(bool apply, bool /*Real*/) { GetTarget()->ApplySpellImmune(GetId(), IMMUNITY_DAMAGE, m_modifier.m_miscvalue, apply); } void Aura::<API key>(bool apply, bool Real) { // all applied/removed only at real aura add/remove if (!Real) { return; } GetTarget()-><API key>(GetSpellProto(), DispelType(m_modifier.m_miscvalue), apply); } void Aura::<API key>(bool apply, bool Real) { if (!Real) { return; } Unit* target = GetTarget(); switch (GetId()) { // some spell have charges by functionality not have its in spell data case 28200: // Ascendance (Talisman of Ascendance trinket) if (apply) { GetHolder()->SetAuraCharges(6); } break; case 50720: // Vigilance (threat transfering) if (apply) { if (Unit* caster = GetCaster()) target->CastSpell(caster, 59665, true); } else target-><API key>().<API key>(); break; default: break; } } void Aura::<API key>(bool apply, bool /*Real*/) { // used by spells: Hunter's Mark, Mind Vision, Syndicate Tracker (MURP) DND if (apply) { GetTarget()->SetFlag(UNIT_DYNAMIC_FLAGS, <API key>); } else { GetTarget()->RemoveFlag(UNIT_DYNAMIC_FLAGS, <API key>); } } /*** PERIODIC ***/ void Aura::<API key>(bool apply, bool /*Real*/) { m_isPeriodic = apply; Unit* target = GetTarget(); if (!apply) { switch (GetId()) { case 66: // Invisibility if (m_removeMode == <API key>) target->CastSpell(target, 32612, true, NULL, this); return; case 42783: // Wrath of the Astrom... if (m_removeMode == <API key> && GetEffIndex() + 1 < MAX_EFFECT_INDEX) target->CastSpell(target, GetSpellProto()-><API key>(SpellEffectIndex(GetEffIndex() + 1)), true); return; case 46221: // Animal Blood if (target->GetTypeId() == TYPEID_PLAYER && m_removeMode == <API key> && target->IsInWater()) { float position_z = target->GetTerrain()->GetWaterLevel(target->GetPositionX(), target->GetPositionY(), target->GetPositionZ()); // Spawn Blood Pool target->CastSpell(target->GetPositionX(), target->GetPositionY(), position_z, 63471, true); } return; case 51912: // Ultra-Advanced Proto-Typical Shortening Blaster if (m_removeMode == <API key>) { if (Unit* pCaster = GetCaster()) pCaster->CastSpell(target, GetSpellProto()->EffectTriggerSpell[GetEffIndex()], true, NULL, this); } return; default: break; } } } void Aura::<API key>(bool apply, bool /*Real*/) { m_isPeriodic = apply; } void Aura::<API key>(bool apply, bool Real) { if (!Real) return; Unit* target = GetTarget(); // For prevent double apply bonuses bool loading = (target->GetTypeId() == TYPEID_PLAYER && ((Player*)target)->GetSession()->PlayerLoading()); if (apply && !loading) { switch (GetId()) { case 54833: // Glyph of Innervate (value%/2 of casters base mana) { if (Unit* caster = GetCaster()) m_modifier.m_amount = int32(caster->GetCreateMana() * GetBasePoints() / (200 * GetAuraMaxTicks())); break; } case 29166: // Innervate (value% of casters base mana) { if (Unit* caster = GetCaster()) { // Glyph of Innervate if (caster->HasAura(54832)) caster->CastSpell(caster, 54833, true, NULL, this); m_modifier.m_amount = int32(caster->GetCreateMana() * GetBasePoints() / (100 * GetAuraMaxTicks())); } break; } case 48391: // Owlkin Frenzy 2% base mana m_modifier.m_amount = target->GetCreateMana() * 2 / 100; break; case 57669: // Replenishment (0.2% from max) case 61782: // Infinite Replenishment m_modifier.m_amount = target->GetMaxPower(POWER_MANA) * 2 / 1000; break; default: break; } } m_isPeriodic = apply; } void Aura::HandleAuraPowerBurn(bool apply, bool /*Real*/) { m_isPeriodic = apply; } void Aura::<API key>(bool apply, bool Real) { // spells required only Real aura add/remove if (!Real) return; Unit* target = GetTarget(); // For prevent double apply bonuses bool loading = (target->GetTypeId() == TYPEID_PLAYER && ((Player*)target)->GetSession()->PlayerLoading()); SpellEntry const* spell = GetSpellProto(); switch (spell->SpellFamilyName) { case SPELLFAMILY_ROGUE: { switch (spell->Id) { // Master of Subtlety case 31666: { if (apply) { // for make duration visible if (SpellAuraHolder* holder = target->GetSpellAuraHolder(31665)) { holder->SetAuraMaxDuration(GetHolder()->GetAuraDuration()); holder->RefreshHolder(); } } else target-><API key>(31665); break; } } break; } case SPELLFAMILY_HUNTER: { Unit* caster = GetCaster(); // Explosive Shot if (apply && !loading && caster) m_modifier.m_amount += int32(caster-><API key>(RANGED_ATTACK) * 14 / 100); break; } } m_isPeriodic = apply; } void Aura::HandlePeriodicHeal(bool apply, bool /*Real*/) { m_isPeriodic = apply; Unit* target = GetTarget(); // For prevent double apply bonuses bool loading = (target->GetTypeId() == TYPEID_PLAYER && ((Player*)target)->GetSession()->PlayerLoading()); // Custom damage calculation after if (apply) { if (loading) { return; } Unit* caster = GetCaster(); if (!caster) { return; } // Gift of the Naaru (have diff spellfamilies) if (GetSpellProto()->SpellIconID == 329 && GetSpellProto()->SpellVisual[0] == 7625) { int32 ap = int32(0.22f * caster-><API key>(BASE_ATTACK)); int32 holy = caster-><API key>(GetSpellSchoolMask(GetSpellProto())); if (holy < 0) holy = 0; holy = int32(holy * 377 / 1000); m_modifier.m_amount += ap > holy ? ap : holy; } // Lifeblood else if (GetSpellProto()->SpellIconID == 3088 && GetSpellProto()->SpellVisual[0] == 8145) { int32 healthBonus = int32(0.0032f * caster->GetMaxHealth()); m_modifier.m_amount += healthBonus; } m_modifier.m_amount = caster-><API key>(target, GetSpellProto(), m_modifier.m_amount, DOT, GetStackAmount()); // Rejuvenation if (GetSpellProto()->IsFitToFamily(SPELLFAMILY_DRUID, UI64LIT(0x0000000000000010))) if (caster->HasAura(64760)) // Item - Druid T8 Restoration 4P Bonus caster->CastCustomSpell(target, 64801, &m_modifier.m_amount, NULL, NULL, true, NULL); } } void Aura::<API key>(bool apply, bool Real) { m_isPeriodic = apply; Unit* target = GetTarget(); if (!Real) return; // For prevent double apply bonuses bool loading = (target->GetTypeId() == TYPEID_PLAYER && ((Player*)target)->GetSession()->PlayerLoading()); if (apply) { if (loading) return; // Hand of Salvation (only it have this aura and mask) if (GetSpellProto()->IsFitToFamily(SPELLFAMILY_PALADIN, UI64LIT(0x0000000000000100))) { // Glyph of Salvation if (target->GetObjectGuid() == GetCasterGuid()) if (Aura* aur = target->GetAura(63225, EFFECT_INDEX_0)) m_modifier.m_amount -= aur->GetModifier()->m_amount; } } } void Aura::<API key>(bool apply, bool Real) { // spells required only Real aura add/remove if (!Real) { return; } m_isPeriodic = apply; Unit* target = GetTarget(); SpellEntry const* spellProto = GetSpellProto(); // For prevent double apply bonuses bool loading = (target->GetTypeId() == TYPEID_PLAYER && ((Player*)target)->GetSession()->PlayerLoading()); // Custom damage calculation after if (apply) { if (loading) { return; } Unit* caster = GetCaster(); if (!caster) { return; } switch (spellProto->SpellFamilyName) { case SPELLFAMILY_WARRIOR: { // Rend if (spellProto->SpellFamilyFlags & UI64LIT(0x0000000000000020)) { // $0.2*(($MWB+$mwb)/2+$AP/14*$MWS) bonus per tick float ap = caster-><API key>(BASE_ATTACK); int32 mws = caster->GetAttackTime(BASE_ATTACK); float mwb_min = caster-><API key>(BASE_ATTACK, MINDAMAGE); float mwb_max = caster-><API key>(BASE_ATTACK, MAXDAMAGE); m_modifier.m_amount += int32(((mwb_min + mwb_max) / 2 + ap * mws / 14000) * 0.2f); // If used while target is above 75% health, Rend does 35% more damage if (spellProto-><API key>(EFFECT_INDEX_1) != 0 && target->GetHealth() > target->GetMaxHealth() * spellProto-><API key>(EFFECT_INDEX_1) / 100) m_modifier.m_amount += m_modifier.m_amount * spellProto-><API key>(EFFECT_INDEX_2) / 100; } break; } case SPELLFAMILY_DRUID: { // Rip if (spellProto->SpellFamilyFlags & UI64LIT(<API key>)) { if (caster->GetTypeId() != TYPEID_PLAYER) break; // 0.01*$AP*cp uint8 cp = ((Player*)caster)->GetComboPoints(); // Idol of Feral Shadows. Cant be handled as SpellMod in SpellAura:Dummy due its dependency from CPs Unit::AuraList const& dummyAuras = caster->GetAurasByType(SPELL_AURA_DUMMY); for (Unit::AuraList::const_iterator itr = dummyAuras.begin(); itr != dummyAuras.end(); ++itr) { if ((*itr)->GetId() == 34241) { m_modifier.m_amount += cp * (*itr)->GetModifier()->m_amount; break; } } m_modifier.m_amount += int32(caster-><API key>(BASE_ATTACK) * cp / 100); } break; } case SPELLFAMILY_ROGUE: { // Rupture if (spellProto->SpellFamilyFlags & UI64LIT(<API key>)) { if (caster->GetTypeId() != TYPEID_PLAYER) { break; } // 1 point : ${($m1+$b1*1+0.015*$AP)*4} damage over 8 secs // 2 points: ${($m1+$b1*2+0.024*$AP)*5} damage over 10 secs // 3 points: ${($m1+$b1*3+0.03*$AP)*6} damage over 12 secs // 4 points: ${($m1+$b1*4+0.03428571*$AP)*7} damage over 14 secs // 5 points: ${($m1+$b1*5+0.0375*$AP)*8} damage over 16 secs float AP_per_combo[6] = {0.0f, 0.015f, 0.024f, 0.03f, 0.03428571f, 0.0375f}; uint8 cp = ((Player*)caster)->GetComboPoints(); if (cp > 5) cp = 5; m_modifier.m_amount += int32(caster-><API key>(BASE_ATTACK) * AP_per_combo[cp]); } break; } case SPELLFAMILY_PALADIN: { // Holy Vengeance / Blood Corruption if (spellProto->SpellFamilyFlags & UI64LIT(0x0000080000000000) && spellProto->SpellVisual[0] == 7902) { // AP * 0.025 + SPH * 0.013 bonus per tick float ap = caster-><API key>(BASE_ATTACK); int32 holy = caster-><API key>(GetSpellSchoolMask(spellProto)); if (holy < 0) holy = 0; m_modifier.m_amount += int32(GetStackAmount()) * (int32(ap * 0.025f) + int32(holy * 13 / 1000)); } break; } default: break; } if (m_modifier.m_auraname == <API key>) { // <API key> for magic spells if (spellProto->DmgClass == <API key> || spellProto->DmgClass == <API key>) { m_modifier.m_amount = caster-><API key>(target, GetSpellProto(), m_modifier.m_amount, DOT, GetStackAmount()); } // <API key> for weapon based spells else { WeaponAttackType attackType = GetWeaponAttackType(GetSpellProto()); m_modifier.m_amount = caster-><API key>(target, m_modifier.m_amount, attackType, GetSpellProto(), DOT, GetStackAmount()); } } } // remove time effects else { // Parasitic Shadowfiend - handle summoning of two Shadowfiends on DoT expire if (spellProto->Id == 41917) target->CastSpell(target, 41915, true); } } void Aura::<API key>(bool apply, bool /*Real*/) { m_isPeriodic = apply; } void Aura::HandlePeriodicLeech(bool apply, bool /*Real*/) { m_isPeriodic = apply; // For prevent double apply bonuses bool loading = (GetTarget()->GetTypeId() == TYPEID_PLAYER && ((Player*)GetTarget())->GetSession()->PlayerLoading()); // Custom damage calculation after if (apply) { if (loading) { return; } Unit* caster = GetCaster(); if (!caster) { return; } m_modifier.m_amount = caster-><API key>(GetTarget(), GetSpellProto(), m_modifier.m_amount, DOT, GetStackAmount()); } } void Aura::<API key>(bool apply, bool /*Real*/) { m_isPeriodic = apply; } void Aura::<API key>(bool apply, bool /*Real*/) { m_isPeriodic = apply; // For prevent double apply bonuses bool loading = (GetTarget()->GetTypeId() == TYPEID_PLAYER && ((Player*)GetTarget())->GetSession()->PlayerLoading()); // Custom damage calculation after if (apply) { if (loading) { return; } Unit* caster = GetCaster(); if (!caster) { return; } m_modifier.m_amount = caster-><API key>(GetTarget(), GetSpellProto(), m_modifier.m_amount, DOT, GetStackAmount()); } } /*** MODIFY STATS ***/ /*** RESISTANCE ***/ void Aura::<API key>(bool apply, bool /*Real*/) { for (int8 x = SPELL_SCHOOL_NORMAL; x < MAX_SPELL_SCHOOL; ++x) { if (m_modifier.m_miscvalue & int32(1 << x)) { GetTarget()->HandleStatModifier(UnitMods(<API key> + x), BASE_VALUE, float(m_modifier.m_amount), apply); if (GetTarget()->GetTypeId() == TYPEID_PLAYER) { ((Player*)GetTarget())-><API key>(SpellSchools(x), m_positive, float(m_modifier.m_amount), apply); } } } } void Aura::<API key>(bool apply, bool /*Real*/) { for (int8 x = SPELL_SCHOOL_NORMAL; x < MAX_SPELL_SCHOOL; ++x) { if (m_modifier.m_miscvalue & int32(1 << x)) { GetTarget()->HandleStatModifier(UnitMods(<API key> + x), TOTAL_VALUE, float(m_modifier.m_amount), apply); if (GetTarget()->GetTypeId() == TYPEID_PLAYER || ((Creature*)GetTarget())->IsPet()) GetTarget()-><API key>(SpellSchools(x), m_positive, float(m_modifier.m_amount), apply); } } } void Aura::<API key>(bool apply, bool /*Real*/) { // only players have base stats if (GetTarget()->GetTypeId() != TYPEID_PLAYER) { // pets only have base armor if (((Creature*)GetTarget())->IsPet() && (m_modifier.m_miscvalue & <API key>)) { GetTarget()->HandleStatModifier(UNIT_MOD_ARMOR, BASE_PCT, float(m_modifier.m_amount), apply); } } else { for (int8 x = SPELL_SCHOOL_NORMAL; x < MAX_SPELL_SCHOOL; ++x) { if (m_modifier.m_miscvalue & int32(1 << x)) { GetTarget()->HandleStatModifier(UnitMods(<API key> + x), BASE_PCT, float(m_modifier.m_amount), apply); } } } } void Aura::<API key>(bool apply, bool /*Real*/) { Unit* target = GetTarget(); for (int8 i = SPELL_SCHOOL_NORMAL; i < MAX_SPELL_SCHOOL; ++i) { if (m_modifier.m_miscvalue & int32(1 << i)) { target->HandleStatModifier(UnitMods(<API key> + i), TOTAL_PCT, float(m_modifier.m_amount), apply); if (target->GetTypeId() == TYPEID_PLAYER || ((Creature*)target)->IsPet()) { ((Player*)target)-><API key>(SpellSchools(i), true, float(m_modifier.m_amount), apply); ((Player*)target)-><API key>(SpellSchools(i), false, float(m_modifier.m_amount), apply); } } } } void Aura::<API key>(bool apply, bool /*Real*/) { // only players have base stats if (GetTarget()->GetTypeId() != TYPEID_PLAYER) { // only pets have base stats if (((Creature*)GetTarget())->IsPet() && (m_modifier.m_miscvalue & <API key>)) { GetTarget()->HandleStatModifier(UNIT_MOD_ARMOR, TOTAL_VALUE, float(m_modifier.m_amount), apply); } } else { for (int i = SPELL_SCHOOL_NORMAL; i < MAX_SPELL_SCHOOL; ++i) if (m_modifier.m_miscvalue & (1 << i)) { GetTarget()->HandleStatModifier(UnitMods(<API key> + i), TOTAL_VALUE, float(m_modifier.m_amount), apply); } } } /*** STAT ***/ void Aura::HandleAuraModStat(bool apply, bool /*Real*/) { if (m_modifier.m_miscvalue < -2 || m_modifier.m_miscvalue > 4) { sLog.outError("WARNING: Spell %u effect %u have unsupported misc value (%i) for SPELL_AURA_MOD_STAT ", GetId(), GetEffIndex(), m_modifier.m_miscvalue); return; } for (int32 i = STAT_STRENGTH; i < MAX_STATS; ++i) { // -1 or -2 is all stats ( misc < -2 checked in function beginning ) if (m_modifier.m_miscvalue < 0 || m_modifier.m_miscvalue == i) { // m_target->ApplyStatMod(Stats(i), m_modifier.m_amount,apply); GetTarget()->HandleStatModifier(UnitMods(UNIT_MOD_STAT_START + i), TOTAL_VALUE, float(m_modifier.m_amount), apply); if (GetTarget()->GetTypeId() == TYPEID_PLAYER || ((Creature*)GetTarget())->IsPet()) { ((Player*)GetTarget())->ApplyStatBuffMod(Stats(i), float(m_modifier.m_amount), apply); } } } } void Aura::<API key>(bool apply, bool /*Real*/) { if (m_modifier.m_miscvalue < -1 || m_modifier.m_miscvalue > 4) { sLog.outError("WARNING: Misc Value for <API key> not valid"); return; } // only players have base stats if (GetTarget()->GetTypeId() != TYPEID_PLAYER) { return; } for (int32 i = STAT_STRENGTH; i < MAX_STATS; ++i) { if (m_modifier.m_miscvalue == i || m_modifier.m_miscvalue == -1) { GetTarget()->HandleStatModifier(UnitMods(UNIT_MOD_STAT_START + i), BASE_PCT, float(m_modifier.m_amount), apply); } } } void Aura::<API key>(bool /*apply*/, bool /*Real*/) { if (GetTarget()->GetTypeId() != TYPEID_PLAYER) { return; } // Magic damage modifiers implemented in Unit::<API key> // This information for client side use only // Recalculate bonus ((Player*)GetTarget())-><API key>(); } void Aura::<API key>(bool /*apply*/, bool /*Real*/) { if (GetTarget()->GetTypeId() != TYPEID_PLAYER) { return; } // Recalculate bonus ((Player*)GetTarget())-><API key>(); } void Aura::<API key>(bool apply, bool Real) { if (!Real || !apply) return; if (GetId() == 33206) GetTarget()->CastSpell(GetTarget(), 44416, true, NULL, this, GetCasterGuid()); } void Aura::<API key>(bool /*apply*/, bool /*Real*/) { if (GetTarget()->GetTypeId() != TYPEID_PLAYER) return; // Magic damage modifiers implemented in Unit::<API key> // This information for client side use only // Recalculate bonus ((Player*)GetTarget())-><API key>(); } void Aura::<API key>(bool /*apply*/, bool /*Real*/) { if (GetTarget()->GetTypeId() != TYPEID_PLAYER) return; // Recalculate bonus ((Player*)GetTarget())-><API key>(); } void Aura::<API key>(bool /*apply*/, bool /*Real*/) { if (GetTarget()->GetTypeId() != TYPEID_PLAYER) { return; } // implemented in Unit::<API key> // this information is for client side only ((Player*)GetTarget())-><API key>(); } void Aura::<API key>(bool apply, bool /*Real*/) { if (m_modifier.m_miscvalue < -1 || m_modifier.m_miscvalue > 4) { sLog.outError("WARNING: Misc Value for <API key> not valid"); return; } Unit* target = GetTarget(); // save current and max HP before applying aura uint32 curHPValue = target->GetHealth(); uint32 maxHPValue = target->GetMaxHealth(); for (int32 i = STAT_STRENGTH; i < MAX_STATS; ++i) { if (m_modifier.m_miscvalue == i || m_modifier.m_miscvalue == -1) { target->HandleStatModifier(UnitMods(UNIT_MOD_STAT_START + i), TOTAL_PCT, float(m_modifier.m_amount), apply); if (target->GetTypeId() == TYPEID_PLAYER || ((Creature*)target)->IsPet()) { ((Player*)target)-><API key>(Stats(i), float(m_modifier.m_amount), apply); } } } // recalculate current HP/MP after applying aura modifications (only for spells with 0x10 flag) if (m_modifier.m_miscvalue == STAT_STAMINA && maxHPValue > 0 && GetSpellProto()->HasAttribute(SPELL_ATTR_UNK4)) { // newHP = (curHP / maxHP) * newMaxHP = (newMaxHP * curHP) / maxHP -> which is better because no int -> double -> int conversion is needed uint32 newHPValue = (target->GetMaxHealth() * curHPValue) / maxHPValue; target->SetHealth(newHPValue); } } void Aura::<API key>(bool /*apply*/, bool /*Real*/) { if (GetTarget()->GetTypeId() != TYPEID_PLAYER) { return; } if (m_modifier.m_miscvalue != <API key>) { // support required adding replace UpdateArmor by loop by UpdateResistence at intellect update // and include in UpdateResistence same code as in UpdateArmor for aura mod apply. sLog.outError("Aura <API key>(182) need adding support for non-armor resistances!"); return; } // Recalculate Armor GetTarget()->UpdateArmor(); } /*** HEAL & ENERGIZE ***/ void Aura::<API key>(bool apply, bool /*Real*/) { m_isPeriodic = apply; } void Aura::<API key>(bool apply, bool /*Real*/) { if (m_modifier.periodictime == 0) { m_modifier.periodictime = 1000; } m_periodicTimer = m_modifier.periodictime; m_isPeriodic = apply; } void Aura::HandleModRegen(bool apply, bool /*Real*/) // eating { if (m_modifier.periodictime == 0) { m_modifier.periodictime = 5000; } m_periodicTimer = 5000; m_isPeriodic = apply; } void Aura::HandleModPowerRegen(bool apply, bool Real) // drinking { if (!Real) { return; } Powers powerType = GetTarget()->GetPowerType(); if (m_modifier.periodictime == 0) { // Anger Management (only spell use this aura for rage) if (powerType == POWER_RAGE) { m_modifier.periodictime = 3000; } else { m_modifier.periodictime = 2000; } } m_periodicTimer = 5000; if (GetTarget()->GetTypeId() == TYPEID_PLAYER && m_modifier.m_miscvalue == POWER_MANA) { ((Player*)GetTarget())->UpdateManaRegen(); } m_isPeriodic = apply; } void Aura::<API key>(bool /*apply*/, bool Real) { // spells required only Real aura add/remove if (!Real) { return; } if (GetTarget()->GetTypeId() != TYPEID_PLAYER) { return; } // Update manaregen value if (m_modifier.m_miscvalue == POWER_MANA) { ((Player*)GetTarget())->UpdateManaRegen(); } } void Aura::HandleModManaRegen(bool /*apply*/, bool Real) { // spells required only Real aura add/remove if (!Real) return; if (GetTarget()->GetTypeId() != TYPEID_PLAYER) return; // Note: an increase in regen does NOT cause threat. ((Player*)GetTarget())->UpdateManaRegen(); } void Aura::<API key>(bool apply, bool /*Real*/) { if (apply) GetTarget()->SetFlag(UNIT_FIELD_FLAGS_2, <API key>); else GetTarget()->RemoveFlag(UNIT_FIELD_FLAGS_2, <API key>); } void Aura::<API key>(bool apply, bool Real) { Unit* target = GetTarget(); switch (GetId()) { // Special case with temporary increase max/current health // Cases where we need to manually calculate the amount for the spell (by percentage) // recalculate to full amount at apply for proper remove case 54443: // Demonic Empowerment (Voidwalker) case 55233: // Vampiric Blood case 61254: // Will of Sartharion (Obsidian Sanctum) if (Real && apply) m_modifier.m_amount = target->GetMaxHealth() * m_modifier.m_amount / 100; // no break here // Cases where m_amount already has the correct value (spells cast with CastCustomSpell or absolute values) case 12976: // Warrior Last Stand triggered spell (Cast with percentage-value by CastCustomSpell) case 28726: // Nightmare Seed case 31616: // Nature's Guardian (Cast with percentage-value by CastCustomSpell) case 34511: // Valor (Bulwark of Kings, Bulwark of the Ancient Kings) case 44055: case 55915: case 55917: case 67596: // Tremendous Fortitude (Battlemaster's Alacrity) case 50322: // Survival Instincts (Cast with percentage-value by CastCustomSpell) case 53479: // Hunter pet - Last Stand (Cast with percentage-value by CastCustomSpell) case 59465: // Brood Rage (Ahn'Kahet) { if (Real) { if (apply) { target->HandleStatModifier(UNIT_MOD_HEALTH, TOTAL_VALUE, float(m_modifier.m_amount), apply); target->ModifyHealth(m_modifier.m_amount); } else { if (int32(target->GetHealth()) > m_modifier.m_amount) { target->ModifyHealth(-m_modifier.m_amount); } else { target->SetHealth(1); } target->HandleStatModifier(UNIT_MOD_HEALTH, TOTAL_VALUE, float(m_modifier.m_amount), apply); } } return; } // generic case default: target->HandleStatModifier(UNIT_MOD_HEALTH, TOTAL_VALUE, float(m_modifier.m_amount), apply); } } void Aura::<API key>(bool apply, bool /*Real*/) { Unit* target = GetTarget(); uint32 oldhealth = target->GetHealth(); double healthPercentage = (double)oldhealth / (double)target->GetMaxHealth(); target->HandleStatModifier(UNIT_MOD_HEALTH, TOTAL_VALUE, float(m_modifier.m_amount), apply); // refresh percentage if (oldhealth > 0) { uint32 newhealth = uint32(ceil((double)target->GetMaxHealth() * healthPercentage)); if (newhealth == 0) newhealth = 1; target->SetHealth(newhealth); } } void Aura::<API key>(bool apply, bool Real) { Unit* target = GetTarget(); Powers powerType = target->GetPowerType(); if (int32(powerType) != m_modifier.m_miscvalue) { return; } UnitMods unitMod = UnitMods(<API key> + powerType); // Special case with temporary increase max/current power (percent) if (GetId() == 64904) // Hymn of Hope { if (Real) { uint32 val = target->GetPower(powerType); target->HandleStatModifier(unitMod, TOTAL_PCT, float(m_modifier.m_amount), apply); target->SetPower(powerType, apply ? val * (100 + m_modifier.m_amount) / 100 : val * 100 / (100 + m_modifier.m_amount)); } return; } // generic flat case target->HandleStatModifier(unitMod, TOTAL_VALUE, float(m_modifier.m_amount), apply); } void Aura::<API key>(bool apply, bool /*Real*/) { Powers powerType = GetTarget()->GetPowerType(); if (int32(powerType) != m_modifier.m_miscvalue) { return; } UnitMods unitMod = UnitMods(<API key> + powerType); GetTarget()->HandleStatModifier(unitMod, TOTAL_PCT, float(m_modifier.m_amount), apply); } void Aura::<API key>(bool apply, bool /*Real*/) { Unit* target = GetTarget(); target->HandleStatModifier(UNIT_MOD_HEALTH, TOTAL_PCT, float(m_modifier.m_amount), apply); // spell special cases when current health set to max value at apply switch (GetId()) { case 60430: // Molten Fury case 64193: // Heartbreak case 65737: // Heartbreak target->SetHealth(target->GetMaxHealth()); break; default: break; } } void Aura::<API key>(bool apply, bool /*Real*/) { GetTarget()->HandleStatModifier(UNIT_MOD_HEALTH, BASE_PCT, float(m_modifier.m_amount), apply); } /*** FIGHT ***/ void Aura::<API key>(bool /*apply*/, bool /*Real*/) { if (GetTarget()->GetTypeId() != TYPEID_PLAYER) { return; } ((Player*)GetTarget())-><API key>(); } void Aura::<API key>(bool /*apply*/, bool /*Real*/) { if (GetTarget()->GetTypeId() != TYPEID_PLAYER) { return; } ((Player*)GetTarget())-><API key>(); // sLog.outError("BONUS DODGE CHANCE: + %f", float(m_modifier.m_amount)); } void Aura::<API key>(bool /*apply*/, bool /*Real*/) { if (GetTarget()->GetTypeId() != TYPEID_PLAYER) { return; } ((Player*)GetTarget())-><API key>(); // sLog.outError("BONUS BLOCK CHANCE: + %f", float(m_modifier.m_amount)); } void Aura::<API key>(bool /*apply*/, bool Real) { // spells required only Real aura add/remove if (!Real) { return; } if (GetTarget()->GetTypeId() != TYPEID_PLAYER) { return; } ((Player*)GetTarget())->UpdateManaRegen(); } void Aura::<API key>(bool apply, bool Real) { Unit* target = GetTarget(); if (target->GetTypeId() != TYPEID_PLAYER) { return; } // apply item specific bonuses for already equipped weapon if (Real) { for (int i = 0; i < MAX_ATTACK; ++i) if (Item* pItem = ((Player*)target)->GetWeaponForAttack(WeaponAttackType(i), true, false)) { ((Player*)target)-><API key>(pItem, WeaponAttackType(i), this, apply); } } // mods must be applied base at equipped weapon class and subclass comparison // with spell->EquippedItemClass and <API key> and <API key> // m_modifier.m_miscvalue comparison with item generated damage types if (GetSpellProto()->EquippedItemClass == -1) { ((Player*)target)->HandleBaseModValue(CRIT_PERCENTAGE, FLAT_MOD, float(m_modifier.m_amount), apply); ((Player*)target)->HandleBaseModValue(<API key>, FLAT_MOD, float(m_modifier.m_amount), apply); ((Player*)target)->HandleBaseModValue(<API key>, FLAT_MOD, float(m_modifier.m_amount), apply); } else { // done in Player::<API key> } } void Aura::HandleModHitChance(bool apply, bool /*Real*/) { Unit* target = GetTarget(); if (target->GetTypeId() == TYPEID_PLAYER) { ((Player*)target)-><API key>(); ((Player*)target)-><API key>(); } else { target->m_modMeleeHitChance += apply ? m_modifier.m_amount : (-m_modifier.m_amount); target-><API key> += apply ? m_modifier.m_amount : (-m_modifier.m_amount); } } void Aura::<API key>(bool apply, bool /*Real*/) { if (GetTarget()->GetTypeId() == TYPEID_PLAYER) { ((Player*)GetTarget())-><API key>(); } else { GetTarget()->m_modSpellHitChance += apply ? m_modifier.m_amount : (-m_modifier.m_amount); } } void Aura::<API key>(bool apply, bool Real) { // spells required only Real aura add/remove if (!Real) { return; } if (GetTarget()->GetTypeId() == TYPEID_PLAYER) { ((Player*)GetTarget())-><API key>(); } else { GetTarget()-><API key> += apply ? m_modifier.m_amount : (-m_modifier.m_amount); } } void Aura::<API key>(bool /*apply*/, bool Real) { // spells required only Real aura add/remove if (!Real) { return; } if (GetTarget()->GetTypeId() != TYPEID_PLAYER) { return; } for (int school = SPELL_SCHOOL_NORMAL; school < MAX_SPELL_SCHOOL; ++school) if (m_modifier.m_miscvalue & (1 << school)) { ((Player*)GetTarget())-><API key>(school); } } /*** ATTACK SPEED ***/ void Aura::<API key>(bool apply, bool /*Real*/) { GetTarget()-><API key>(float(m_modifier.m_amount), apply); } void Aura::<API key>(bool apply, bool /*Real*/) { Unit* target = GetTarget(); target-><API key>(BASE_ATTACK, float(m_modifier.m_amount), apply); target-><API key>(OFF_ATTACK, float(m_modifier.m_amount), apply); target-><API key>(RANGED_ATTACK, float(m_modifier.m_amount), apply); } void Aura::<API key>(bool apply, bool /*Real*/) { Unit* target = GetTarget(); target-><API key>(float(m_modifier.m_amount), apply); target-><API key>(BASE_ATTACK, float(m_modifier.m_amount), apply); target-><API key>(OFF_ATTACK, float(m_modifier.m_amount), apply); target-><API key>(RANGED_ATTACK, float(m_modifier.m_amount), apply); } void Aura::<API key>(bool apply, bool /*Real*/) { GetTarget()-><API key>(BASE_ATTACK, float(m_modifier.m_amount), apply); } void Aura::<API key>(bool apply, bool /*Real*/) { Unit* target = GetTarget(); target-><API key>(BASE_ATTACK, float(m_modifier.m_amount), apply); target-><API key>(OFF_ATTACK, float(m_modifier.m_amount), apply); } void Aura::<API key>(bool apply, bool /*Real*/) { GetTarget()-><API key>(RANGED_ATTACK, float(m_modifier.m_amount), apply); } void Aura::<API key>(bool apply, bool /*Real*/) { if (GetTarget()->GetTypeId() != TYPEID_PLAYER) return; GetTarget()-><API key>(RANGED_ATTACK, float(m_modifier.m_amount), apply); } /*** ATTACK POWER ***/ void Aura::<API key>(bool apply, bool /*Real*/) { GetTarget()->HandleStatModifier(<API key>, TOTAL_VALUE, float(m_modifier.m_amount), apply); } void Aura::<API key>(bool apply, bool /*Real*/) { if ((GetTarget()->getClassMask() & <API key>) != 0) return; GetTarget()->HandleStatModifier(<API key>, TOTAL_VALUE, float(m_modifier.m_amount), apply); } void Aura::<API key>(bool apply, bool /*Real*/) { // <API key> = multiplier - 1 GetTarget()->HandleStatModifier(<API key>, TOTAL_PCT, float(m_modifier.m_amount), apply); } void Aura::<API key>(bool apply, bool /*Real*/) { if ((GetTarget()->getClassMask() & <API key>) != 0) return; // <API key> = multiplier - 1 GetTarget()->HandleStatModifier(<API key>, TOTAL_PCT, float(m_modifier.m_amount), apply); } void Aura::<API key>(bool /*apply*/, bool Real) { // spells required only Real aura add/remove if (!Real) return; // Recalculate bonus if (GetTarget()->GetTypeId() == TYPEID_PLAYER && !(GetTarget()->getClassMask() & <API key>)) ((Player*)GetTarget())-><API key>(true); } void Aura::<API key>(bool /*apply*/, bool Real) { // spells required only Real aura add/remove if (!Real) return; // Recalculate bonus if (GetTarget()->GetTypeId() == TYPEID_PLAYER) ((Player*)GetTarget())-><API key>(false); } void Aura::<API key>(bool /*apply*/, bool Real) { // spells required only Real aura add/remove if (!Real) return; // Recalculate bonus if (GetTarget()->GetTypeId() == TYPEID_PLAYER) ((Player*)GetTarget())-><API key>(false); } /*** DAMAGE BONUS ***/ void Aura::HandleModDamageDone(bool apply, bool Real) { Unit* target = GetTarget(); // apply item specific bonuses for already equipped weapon if (Real && target->GetTypeId() == TYPEID_PLAYER) { for (int i = 0; i < MAX_ATTACK; ++i) if (Item* pItem = ((Player*)target)->GetWeaponForAttack(WeaponAttackType(i), true, false)) { ((Player*)target)-><API key>(pItem, WeaponAttackType(i), this, apply); } } // m_modifier.m_miscvalue is bitmask of spell schools // 1 ( 0-bit ) - normal school damage (<API key>) // 126 - full bitmask all magic damages (<API key>) including wands // 127 - full bitmask any damages // mods must be applied base at equipped weapon class and subclass comparison // with spell->EquippedItemClass and <API key> and <API key> // m_modifier.m_miscvalue comparison with item generated damage types if ((m_modifier.m_miscvalue & <API key>) != 0) { // apply generic physical damage bonuses including wand case if (GetSpellProto()->EquippedItemClass == -1 || target->GetTypeId() != TYPEID_PLAYER) { target->HandleStatModifier(<API key>, TOTAL_VALUE, float(m_modifier.m_amount), apply); target->HandleStatModifier(<API key>, TOTAL_VALUE, float(m_modifier.m_amount), apply); target->HandleStatModifier(<API key>, TOTAL_VALUE, float(m_modifier.m_amount), apply); } else { // done in Player::<API key> } if (target->GetTypeId() == TYPEID_PLAYER) { if (m_positive) { target->ApplyModUInt32Value(<API key>, m_modifier.m_amount, apply); } else { target->ApplyModUInt32Value(<API key>, m_modifier.m_amount, apply); } } } // Skip non magic case for speedup if ((m_modifier.m_miscvalue & <API key>) == 0) { return; } if (GetSpellProto()->EquippedItemClass != -1 || GetSpellProto()-><API key> != 0) { // wand magic case (skip generic to all item spell bonuses) // done in Player::<API key> // Skip item specific requirements for not wand magic damage return; } // Magic damage modifiers implemented in Unit::<API key> // This information for client side use only if (target->GetTypeId() == TYPEID_PLAYER) { if (m_positive) { for (int i = SPELL_SCHOOL_HOLY; i < MAX_SPELL_SCHOOL; ++i) { if ((m_modifier.m_miscvalue & (1 << i)) != 0) { target->ApplyModUInt32Value(<API key> + i, m_modifier.m_amount, apply); } } } else { for (int i = SPELL_SCHOOL_HOLY; i < MAX_SPELL_SCHOOL; ++i) { if ((m_modifier.m_miscvalue & (1 << i)) != 0) { target->ApplyModUInt32Value(<API key> + i, m_modifier.m_amount, apply); } } } Pet* pet = target->GetPet(); if (pet) { pet-><API key>(); } } } void Aura::<API key>(bool apply, bool Real) { DEBUG_FILTER_LOG(<API key>, "AURA MOD DAMAGE type:%u negative:%u", m_modifier.m_miscvalue, m_positive ? 0 : 1); Unit* target = GetTarget(); // apply item specific bonuses for already equipped weapon if (Real && target->GetTypeId() == TYPEID_PLAYER) { for (int i = 0; i < MAX_ATTACK; ++i) if (Item* pItem = ((Player*)target)->GetWeaponForAttack(WeaponAttackType(i), true, false)) { ((Player*)target)-><API key>(pItem, WeaponAttackType(i), this, apply); } } // m_modifier.m_miscvalue is bitmask of spell schools // 1 ( 0-bit ) - normal school damage (<API key>) // 126 - full bitmask all magic damages (<API key>) including wand // 127 - full bitmask any damages // mods must be applied base at equipped weapon class and subclass comparison // with spell->EquippedItemClass and <API key> and <API key> // m_modifier.m_miscvalue comparison with item generated damage types if ((m_modifier.m_miscvalue & <API key>) != 0) { // apply generic physical damage bonuses including wand case if (GetSpellProto()->EquippedItemClass == -1 || target->GetTypeId() != TYPEID_PLAYER) { target->HandleStatModifier(<API key>, TOTAL_PCT, float(m_modifier.m_amount), apply); target->HandleStatModifier(<API key>, TOTAL_PCT, float(m_modifier.m_amount), apply); target->HandleStatModifier(<API key>, TOTAL_PCT, float(m_modifier.m_amount), apply); } else { // done in Player::<API key> } // For show in client if (target->GetTypeId() == TYPEID_PLAYER) { target-><API key>(<API key>, m_modifier.m_amount / 100.0f, apply); } } // Skip non magic case for speedup if ((m_modifier.m_miscvalue & <API key>) == 0) { return; } if (GetSpellProto()->EquippedItemClass != -1 || GetSpellProto()-><API key> != 0) { // wand magic case (skip generic to all item spell bonuses) // done in Player::<API key> // Skip item specific requirements for not wand magic damage return; } // Magic damage percent modifiers implemented in Unit::<API key> // Send info to client if (target->GetTypeId() == TYPEID_PLAYER) for (int i = SPELL_SCHOOL_HOLY; i < MAX_SPELL_SCHOOL; ++i) { target-><API key>(<API key> + i, m_modifier.m_amount / 100.0f, apply); } } void Aura::<API key>(bool apply, bool Real) { // spells required only Real aura add/remove if (!Real) { return; } DEBUG_FILTER_LOG(<API key>, "AURA MOD OFFHAND DAMAGE"); GetTarget()->HandleStatModifier(<API key>, TOTAL_PCT, float(m_modifier.m_amount), apply); } /*** POWER COST ***/ void Aura::<API key>(bool apply, bool Real) { // spells required only Real aura add/remove if (!Real) { return; } float amount = m_modifier.m_amount / 100.0f; for (int i = 0; i < MAX_SPELL_SCHOOL; ++i) if (m_modifier.m_miscvalue & (1 << i)) { GetTarget()-><API key>(<API key> + i, amount, apply); } } void Aura::HandleModPowerCost(bool apply, bool Real) { // spells required only Real aura add/remove if (!Real) { return; } for (int i = 0; i < MAX_SPELL_SCHOOL; ++i) if (m_modifier.m_miscvalue & (1 << i)) { GetTarget()->ApplyModInt32Value(<API key> + i, m_modifier.m_amount, apply); } } void Aura::<API key>(bool /*Apply*/, bool Real) { // spells required only Real aura add/remove if (!Real) return; Unit* target = GetTarget(); if (target->GetTypeId() != TYPEID_PLAYER) return; ClassFamilyMask mask; Unit::AuraList const& noReagent = target->GetAurasByType(<API key>); for (Unit::AuraList::const_iterator i = noReagent.begin(); i != noReagent.end(); ++i) mask |= (*i)-><API key>(); target->SetUInt64Value(<API key> + 0, mask.Flags); target->SetUInt32Value(<API key> + 2, mask.Flags2); } /*** OTHERS ***/ void Aura::<API key>(bool apply) { uint32 spellId1 = 0; uint32 spellId2 = 0; uint32 HotWSpellId = 0; uint32 MasterShaperSpellId = 0; ShapeshiftForm form = ShapeshiftForm(GetModifier()->m_miscvalue); Unit* target = GetTarget(); switch (form) { case FORM_CAT: spellId1 = 3025; HotWSpellId = 24900; MasterShaperSpellId = 48420; break; case FORM_TREE: spellId1 = 5420; spellId2 = 34123; MasterShaperSpellId = 48422; break; case FORM_TRAVEL: spellId1 = 5419; break; case FORM_AQUA: spellId1 = 5421; break; case FORM_BEAR: spellId1 = 1178; spellId2 = 21178; HotWSpellId = 24899; MasterShaperSpellId = 48418; break; case FORM_DIREBEAR: spellId1 = 9635; spellId2 = 21178; HotWSpellId = 24899; MasterShaperSpellId = 48418; break; case FORM_BATTLESTANCE: spellId1 = 21156; break; case <API key>: spellId1 = 7376; break; case <API key>: spellId1 = 7381; break; case FORM_MOONKIN: spellId1 = 24905; spellId2 = 69366; MasterShaperSpellId = 48421; break; case FORM_FLIGHT: spellId1 = 33948; spellId2 = 34764; break; case FORM_FLIGHT_EPIC: spellId1 = 40122; spellId2 = 40121; break; case FORM_METAMORPHOSIS: spellId1 = 54817; spellId2 = 54879; break; case <API key>: spellId1 = 27792; spellId2 = 27795; // must be second, this important at aura remove to prevent to early iterator invalidation. break; case FORM_SHADOW: spellId1 = 49868; if (target->GetTypeId() == TYPEID_PLAYER) // Spell 49868 have same category as main form spell and share cooldown ((Player*)target)->RemoveSpellCooldown(49868); break; case FORM_GHOSTWOLF: spellId1 = 67116; break; case FORM_AMBIENT: case FORM_GHOUL: case FORM_STEALTH: case FORM_CREATURECAT: case FORM_CREATUREBEAR: case FORM_STEVES_GHOUL: case <API key>: case <API key>: case FORM_BLB_PLAYER: case FORM_SHADOW_DANCE: case FORM_TEST: case FORM_ZOMBIE: case FORM_UNDEAD: case FORM_FRENZY: case FORM_NONE: break; } if (apply) { if (spellId1) { target->CastSpell(target, spellId1, true, NULL, this); } if (spellId2) { target->CastSpell(target, spellId2, true, NULL, this); } if (target->GetTypeId() == TYPEID_PLAYER) { const PlayerSpellMap& sp_list = ((Player*)target)->GetSpellMap(); for (PlayerSpellMap::const_iterator itr = sp_list.begin(); itr != sp_list.end(); ++itr) { if (itr->second.state == PLAYERSPELL_REMOVED) { continue; } if (itr->first == spellId1 || itr->first == spellId2) { continue; } SpellEntry const* spellInfo = sSpellStore.LookupEntry(itr->first); if (!spellInfo || !<API key>(spellInfo, form)) { continue; } target->CastSpell(target, itr->first, true, NULL, this); } // remove auras that do not require shapeshift, but are not active in this specific form (like Improved Barkskin) Unit::SpellAuraHolderMap& tAuras = target-><API key>(); for (Unit::SpellAuraHolderMap::iterator itr = tAuras.begin(); itr != tAuras.end();) { SpellEntry const* spellInfo = itr->second->GetSpellProto(); if (itr->second->IsPassive() && spellInfo->HasAttribute(<API key>) && (spellInfo->StancesNot & (1 << (form - 1)))) { target-><API key>(itr->second->GetId()); itr = tAuras.begin(); } else ++itr; } // Master Shapeshifter if (MasterShaperSpellId) { Unit::AuraList const& ShapeShifterAuras = target->GetAurasByType(SPELL_AURA_DUMMY); for (Unit::AuraList::const_iterator i = ShapeShifterAuras.begin(); i != ShapeShifterAuras.end(); ++i) { if ((*i)->GetSpellProto()->SpellIconID == 2851) { int32 ShiftMod = (*i)->GetModifier()->m_amount; target->CastCustomSpell(target, MasterShaperSpellId, &ShiftMod, NULL, NULL, true); break; } } } // Leader of the Pack if (((Player*)target)->HasSpell(17007)) { SpellEntry const* spellInfo = sSpellStore.LookupEntry(24932); if (spellInfo && spellInfo->Stances & (1 << (form - 1))) { target->CastSpell(target, 24932, true, NULL, this); } } // Savage Roar if (form == FORM_CAT && ((Player*)target)->HasAura(52610)) target->CastSpell(target, 62071, true); // Survival of the Fittest (Armor part) if (form == FORM_BEAR || form == FORM_DIREBEAR) { Unit::AuraList const& modAuras = target->GetAurasByType(<API key>); for (Unit::AuraList::const_iterator i = modAuras.begin(); i != modAuras.end(); ++i) { if ((*i)->GetSpellProto()->SpellFamilyName == SPELLFAMILY_DRUID && (*i)->GetSpellProto()->SpellIconID == 961) { int32 bp = (*i)->GetSpellProto()-><API key>(EFFECT_INDEX_2); if (bp) target->CastCustomSpell(target, 62069, &bp, NULL, NULL, true, NULL, this); break; } } } // Improved Moonkin Form if (form == FORM_MOONKIN) { Unit::AuraList const& dummyAuras = target->GetAurasByType(SPELL_AURA_DUMMY); for (Unit::AuraList::const_iterator i = dummyAuras.begin(); i != dummyAuras.end(); ++i) { if ((*i)->GetSpellProto()->SpellFamilyName == SPELLFAMILY_DRUID && (*i)->GetSpellProto()->SpellIconID == 2855) { uint32 spell_id = 0; switch ((*i)->GetId()) { case 48384: spell_id = 50170; break; // Rank 1 case 48395: spell_id = 50171; break; // Rank 2 case 48396: spell_id = 50172; break; // Rank 3 default: sLog.outError("Aura::<API key>: Not handled rank of IMF (Spell: %u)", (*i)->GetId()); break; } if (spell_id) target->CastSpell(target, spell_id, true, NULL, this); break; } } } // Heart of the Wild if (HotWSpellId) { Unit::AuraList const& mModTotalStatPct = target->GetAurasByType(<API key>); for (Unit::AuraList::const_iterator i = mModTotalStatPct.begin(); i != mModTotalStatPct.end(); ++i) { if ((*i)->GetSpellProto()->SpellIconID == 240 && (*i)->GetModifier()->m_miscvalue == 3) { int32 HotWMod = (*i)->GetModifier()->m_amount; if (GetModifier()->m_miscvalue == FORM_CAT) HotWMod /= 2; target->CastCustomSpell(target, HotWSpellId, &HotWMod, NULL, NULL, true, NULL, this); break; } } } } } else { if (spellId1) { target-><API key>(spellId1); } if (spellId2) { target-><API key>(spellId2); } if (MasterShaperSpellId) target-><API key>(MasterShaperSpellId); if (target->GetTypeId() == TYPEID_PLAYER) { // re-apply passive spells that don't need shapeshift but were inactive in current form: const PlayerSpellMap& sp_list = ((Player*)target)->GetSpellMap(); for (PlayerSpellMap::const_iterator itr = sp_list.begin(); itr != sp_list.end(); ++itr) { if (itr->second.state == PLAYERSPELL_REMOVED) continue; if (itr->first == spellId1 || itr->first == spellId2) continue; SpellEntry const* spellInfo = sSpellStore.LookupEntry(itr->first); if (!spellInfo || !IsPassiveSpell(spellInfo)) continue; if (spellInfo->HasAttribute(<API key>) && (spellInfo->StancesNot & (1 << (form - 1)))) target->CastSpell(target, itr->first, true, NULL, this); } } Unit::SpellAuraHolderMap& tAuras = target-><API key>(); for (Unit::SpellAuraHolderMap::iterator itr = tAuras.begin(); itr != tAuras.end();) { if (itr->second-><API key>()) { target-><API key>(itr->second->GetId()); itr = tAuras.begin(); } else { ++itr; } } } } void Aura::HandleAuraEmpathy(bool apply, bool /*Real*/) { Unit* target = GetTarget(); // This aura is expected to only work with CREATURE_TYPE_BEAST or players CreatureInfo const* ci = ObjectMgr::GetCreatureTemplate(target->GetEntry()); if (target->GetTypeId() == TYPEID_PLAYER || (target->GetTypeId() == TYPEID_UNIT && ci && ci->CreatureType == CREATURE_TYPE_BEAST)) { target->ApplyModUInt32Value(UNIT_DYNAMIC_FLAGS, <API key>, apply); } } void Aura::<API key>(bool apply, bool /*Real*/) { if (apply) { GetTarget()->SetByteFlag(UNIT_FIELD_BYTES_1, 3, <API key>); } else { GetTarget()->RemoveByteFlag(UNIT_FIELD_BYTES_1, 3, <API key>); } } void Aura::HandleAuraModPacify(bool apply, bool /*Real*/) { if (apply) { GetTarget()->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PACIFIED); } else { GetTarget()->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PACIFIED); } } void Aura::<API key>(bool apply, bool Real) { HandleAuraModPacify(apply, Real); <API key>(apply, Real); } void Aura::HandleAuraGhost(bool apply, bool /*Real*/) { if (GetTarget()->GetTypeId() != TYPEID_PLAYER) { return; } if (apply) { GetTarget()->SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST); } else { GetTarget()->RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST); } } void Aura::<API key>(bool apply, bool Real) { // all applied/removed only at real aura add/remove if (!Real) return; GetTarget()->SetCanFly(apply); } void Aura::HandleModRating(bool apply, bool Real) { // spells required only Real aura add/remove if (!Real) return; if (GetTarget()->GetTypeId() != TYPEID_PLAYER) return; for (uint32 rating = 0; rating < MAX_COMBAT_RATING; ++rating) if (m_modifier.m_miscvalue & (1 << rating)) ((Player*)GetTarget())->ApplyRatingMod(CombatRating(rating), m_modifier.m_amount, apply); } void Aura::<API key>(bool apply, bool Real) { // spells required only Real aura add/remove if (!Real) return; if (GetTarget()->GetTypeId() != TYPEID_PLAYER) return; // Just recalculate ratings for (uint32 rating = 0; rating < MAX_COMBAT_RATING; ++rating) if (m_modifier.m_miscvalue & (1 << rating)) ((Player*)GetTarget())->ApplyRatingMod(CombatRating(rating), 0, apply); } void Aura::<API key>(bool apply, bool Real) { if (!Real) return; if (apply) GetTarget()->SetFlag(UNIT_FIELD_FLAGS_2, <API key>); else GetTarget()->RemoveFlag(UNIT_FIELD_FLAGS_2, <API key>); } void Aura::<API key>(bool /*apply*/, bool /*Real*/) { if (GetTarget()->GetTypeId() != TYPEID_PLAYER) return; ((Player*)GetTarget())->UpdateExpertise(BASE_ATTACK); ((Player*)GetTarget())->UpdateExpertise(OFF_ATTACK); } void Aura::<API key>(bool apply, bool Real) { // spells required only Real aura add/remove if (!Real) return; Unit* target = GetTarget(); // applied to damage as <API key> in Unit::<API key> and Unit::<API key> // show armor penetration if (target->GetTypeId() == TYPEID_PLAYER && (m_modifier.m_miscvalue & <API key>)) target->ApplyModInt32Value(<API key>, m_modifier.m_amount, apply); // show as spell penetration only full spell penetration bonuses (all resistances except armor and holy if (target->GetTypeId() == TYPEID_PLAYER && (m_modifier.m_miscvalue & <API key>) == <API key>) target->ApplyModInt32Value(<API key>, m_modifier.m_amount, apply); } void Aura::<API key>(bool apply, bool /*Real*/) { BaseModType modType = FLAT_MOD; if (m_modifier.m_auraname == <API key>) { modType = PCT_MOD; } if (GetTarget()->GetTypeId() == TYPEID_PLAYER) { ((Player*)GetTarget())->HandleBaseModValue(SHIELD_BLOCK_VALUE, modType, float(m_modifier.m_amount), apply); } } void Aura::<API key>(bool apply, bool Real) { // spells required only Real aura add/remove if (!Real) { return; } if (GetTarget()->GetTypeId() != TYPEID_PLAYER) { return; } Player* target = (Player*)GetTarget(); // combo points was added in <API key> handler // remove only if aura expire by time (in case combo points amount change aura removed without combo points lost) if (!apply && m_removeMode == <API key> && target->GetComboTargetGuid()) if (Unit* unit = sObjectAccessor.GetUnit(*GetTarget(), target->GetComboTargetGuid())) { target->AddComboPoints(unit, -m_modifier.m_amount); } } void Aura::<API key>(bool Apply, bool Real) { if (Real && Apply) { GetTarget()->CombatStop(); GetTarget()-><API key>(<API key>); } GetTarget()->ApplyModFlag(UNIT_FIELD_FLAGS, <API key>, Apply); } void Aura::<API key>(bool apply, bool Real) { // spells required only Real aura add/remove if (!Real) { return; } Unit* target = GetTarget(); // prepare spirit state if (apply) { if (target->GetTypeId() == TYPEID_PLAYER) { // disable breath/etc timers ((Player*)target)->StopMirrorTimers(); // set stand state (expected in this form) if (!target->IsStandState()) { target->SetStandState(<API key>); } } target->SetHealth(1); } // die at aura end else { target->DealDamage(target, target->GetHealth(), NULL, DIRECT_DAMAGE, <API key>, GetSpellProto(), false); } } void Aura::HandleSchoolAbsorb(bool apply, bool Real) { if (!Real) { return; } Unit* caster = GetCaster(); if (!caster) { return; } Unit* target = GetTarget(); SpellEntry const* spellProto = GetSpellProto(); if (apply) { // prevent double apply bonuses if (target->GetTypeId() != TYPEID_PLAYER || !((Player*)target)->GetSession()->PlayerLoading()) { float DoneActualBenefit = 0.0f; switch (spellProto->SpellFamilyName) { case SPELLFAMILY_GENERIC: // Stoicism if (spellProto->Id == 70845) DoneActualBenefit = caster->GetMaxHealth() * 0.20f; break; case SPELLFAMILY_PRIEST: // Power Word: Shield if (spellProto->SpellFamilyFlags & UI64LIT(0x0000000000000001)) { //+80.68% from +spell bonus DoneActualBenefit = caster-><API key>(GetSpellSchoolMask(spellProto)) * 0.8068f; // Borrowed Time Unit::AuraList const& borrowedTime = caster->GetAurasByType(SPELL_AURA_DUMMY); for (Unit::AuraList::const_iterator itr = borrowedTime.begin(); itr != borrowedTime.end(); ++itr) { SpellEntry const* i_spell = (*itr)->GetSpellProto(); if (i_spell->SpellFamilyName == SPELLFAMILY_PRIEST && i_spell->SpellIconID == 2899 && i_spell->EffectMiscValue[(*itr)->GetEffIndex()] == 24) { DoneActualBenefit += DoneActualBenefit * (*itr)->GetModifier()->m_amount / 100; break; } } } break; case SPELLFAMILY_MAGE: // Frost Ward, Fire Ward if (spellProto->IsFitToFamilyMask(UI64LIT(0x0000000000000108))) //+10% from +spell bonus { DoneActualBenefit = caster-><API key>(GetSpellSchoolMask(spellProto)) * 0.1f; } // Ice Barrier else if (spellProto->IsFitToFamilyMask(UI64LIT(0x0000000100000000))) //+80.67% from +spell bonus DoneActualBenefit = caster-><API key>(GetSpellSchoolMask(spellProto)) * 0.8067f; break; case SPELLFAMILY_WARLOCK: // Shadow Ward if (spellProto->IsFitToFamilyMask(UI64LIT(0x0000000000000000), 0x00000040)) //+30% from +spell bonus DoneActualBenefit = caster-><API key>(GetSpellSchoolMask(spellProto)) * 0.30f; break; case SPELLFAMILY_PALADIN: // Sacred Shield // (check not strictly needed, only Sacred Shield has <API key> in SPELLFAMILY_PALADIN at this time) if (spellProto->IsFitToFamilyMask(UI64LIT(0x0008000000000000))) { // +75% from spell power DoneActualBenefit = caster-><API key>(GetSpellSchoolMask(spellProto)) * 0.75f; } break; default: break; } DoneActualBenefit *= caster-><API key>(GetSpellProto()); m_modifier.m_amount += (int32)DoneActualBenefit; } } else { if (caster && // Power Word: Shield spellProto->SpellFamilyName == SPELLFAMILY_PRIEST && spellProto->Mechanic == MECHANIC_SHIELD && (spellProto->SpellFamilyFlags & UI64LIT(0x0000000000000001)) && // completely absorbed or dispelled (m_removeMode == <API key> || m_removeMode == <API key>)) { Unit::AuraList const& vDummyAuras = caster->GetAurasByType(SPELL_AURA_DUMMY); for (Unit::AuraList::const_iterator itr = vDummyAuras.begin(); itr != vDummyAuras.end(); ++itr) { SpellEntry const* vSpell = (*itr)->GetSpellProto(); // Rapture (main spell) if (vSpell->SpellFamilyName == SPELLFAMILY_PRIEST && vSpell->SpellIconID == 2894 && vSpell->Effect[EFFECT_INDEX_1]) { switch ((*itr)->GetEffIndex()) { case EFFECT_INDEX_0: { // energize caster int32 manapct1000 = 5 * ((*itr)->GetModifier()->m_amount + sSpellMgr.GetSpellRank(vSpell->Id)); int32 basepoints0 = caster->GetMaxPower(POWER_MANA) * manapct1000 / 1000; caster->CastCustomSpell(caster, 47755, &basepoints0, NULL, NULL, true); break; } case EFFECT_INDEX_1: { // energize target if (!roll_chance_i((*itr)->GetModifier()->m_amount) || caster->HasAura(63853)) break; switch (target->GetPowerType()) { case POWER_RUNIC_POWER: target->CastSpell(target, 63652, true, NULL, NULL, GetCasterGuid()); break; case POWER_RAGE: target->CastSpell(target, 63653, true, NULL, NULL, GetCasterGuid()); break; case POWER_MANA: { int32 basepoints0 = target->GetMaxPower(POWER_MANA) * 2 / 100; target->CastCustomSpell(target, 63654, &basepoints0, NULL, NULL, true); break; } case POWER_ENERGY: target->CastSpell(target, 63655, true, NULL, NULL, GetCasterGuid()); break; default: break; } // cooldown aura caster->CastSpell(caster, 63853, true); break; } default: sLog.outError("Changes in R-dummy spell???: effect 3"); break; } } } } } } void Aura::PeriodicTick() { Unit* target = GetTarget(); SpellEntry const* spellProto = GetSpellProto(); switch (m_modifier.m_auraname) { case <API key>: case <API key>: { // don't damage target if not alive, possible death persistent effects if (!target->IsAlive()) { return; } Unit* pCaster = GetCaster(); if (!pCaster) { return; } if (spellProto->Effect[GetEffIndex()] == <API key> && pCaster->SpellHitResult(target, spellProto, false) != SPELL_MISS_NONE) { return; } // Check for immune (not use charges) if (target->IsImmunedToDamage(GetSpellSchoolMask(spellProto))) { return; } // some auras remove at specific health level or more if (m_modifier.m_auraname == <API key>) { switch (GetId()) { case 43093: case 31956: case 38801: case 35321: case 38363: case 39215: case 48920: { if (target->GetHealth() == target->GetMaxHealth()) { target-><API key>(GetId()); return; } break; } case 38772: { uint32 percent = GetEffIndex() < EFFECT_INDEX_2 && spellProto->Effect[GetEffIndex()] == SPELL_EFFECT_DUMMY ? pCaster-><API key>(target, spellProto, SpellEffectIndex(GetEffIndex() + 1)) : 100; if (target->GetHealth() * 100 >= target->GetMaxHealth() * percent) { target-><API key>(GetId()); return; } break; } default: break; } } uint32 absorb = 0; uint32 resist = 0; CleanDamage cleanDamage = CleanDamage(0, BASE_ATTACK, MELEE_HIT_NORMAL); // ignore non positive values (can be result apply spellmods to aura damage uint32 amount = m_modifier.m_amount > 0 ? m_modifier.m_amount : 0; uint32 pdamage; if (m_modifier.m_auraname == <API key>) { pdamage = amount; } else { pdamage = uint32(target->GetMaxHealth() * amount / 100); } // SpellDamageBonus for magic spells if (spellProto->DmgClass == <API key> || spellProto->DmgClass == <API key>) { pdamage = target-><API key>(pCaster, spellProto, pdamage, DOT, GetStackAmount()); } // MeleeDamagebonus for weapon based spells else { WeaponAttackType attackType = GetWeaponAttackType(spellProto); pdamage = target-><API key>(pCaster, pdamage, attackType, spellProto, DOT, GetStackAmount()); } // Calculate armor mitigation if it is a physical spell // But not for bleed mechanic spells if (GetSpellSchoolMask(spellProto) & <API key> && GetEffectMechanic(spellProto, m_effIndex) != MECHANIC_BLEED) { uint32 <API key> = pCaster-><API key>(target, pdamage); cleanDamage.damage += pdamage - <API key>; pdamage = <API key>; } // Curse of Agony damage-per-tick calculation if (spellProto->SpellFamilyName == SPELLFAMILY_WARLOCK && (spellProto->SpellFamilyFlags & UI64LIT(0x0000000000000400)) && spellProto->SpellIconID == 544) { // 1..4 ticks, 1/2 from normal tick damage if (GetAuraTicks() <= 4) { pdamage = pdamage / 2; } // 9..12 ticks, 3/2 from normal tick damage else if (GetAuraTicks() >= 9) { pdamage += (pdamage + 1) / 2; } // +1 prevent 0.5 damage possible lost at 1..4 ticks // 5..8 ticks have normal tick damage } // This method can modify pdamage bool isCrit = <API key>(pCaster, pdamage); // send critical in hit info for threat calculation if (isCrit) { cleanDamage.hitOutCome = MELEE_HIT_CRIT; // Resilience - reduce crit damage pdamage -= target-><API key>(pdamage); } // only from players // FIXME: need use SpellDamageBonus instead? if (pCaster->GetTypeId() == TYPEID_PLAYER) pdamage -= target-><API key>(pdamage); target-><API key>(pCaster, GetSpellSchoolMask(spellProto), DOT, pdamage, &absorb, &resist, !GetSpellProto()->HasAttribute(<API key>)); DETAIL_FILTER_LOG(<API key>, "PeriodicTick: %s attacked %s for %u dmg inflicted by %u abs is %u", GetCasterGuid().GetString().c_str(), target->GetGuidStr().c_str(), pdamage, GetId(), absorb); pCaster->DealDamageMods(target, pdamage, &absorb); // Set trigger flag uint32 procAttacker = <API key>; // | <API key>; uint32 procVictim = <API key>;// | <API key>; uint32 procEx = isCrit ? <API key> : PROC_EX_NORMAL_HIT; pdamage = (pdamage <= absorb + resist) ? 0 : (pdamage - absorb - resist); uint32 overkill = pdamage > target->GetHealth() ? pdamage - target->GetHealth() : 0; <API key> pInfo(this, pdamage, overkill, absorb, resist, 0.0f, isCrit); target->SendPeriodicAuraLog(&pInfo); if (pdamage) { procVictim |= <API key>; } pCaster->ProcDamageAndSpell(target, procAttacker, procVictim, procEx, pdamage, BASE_ATTACK, spellProto); pCaster->DealDamage(target, pdamage, &cleanDamage, DOT, GetSpellSchoolMask(spellProto), spellProto, true); // Drain Soul (chance soul shard) if (pCaster->GetTypeId() == TYPEID_PLAYER && spellProto->SpellFamilyName == SPELLFAMILY_WARLOCK && spellProto->SpellFamilyFlags & UI64LIT(0x0000000000004000)) { // Only from non-grey units if (roll_chance_i(10) && // 1-2 from drain with final and without glyph, 0-1 from damage ((Player*)pCaster)->isHonorOrXPTarget(target) && (target->GetTypeId() != TYPEID_UNIT || ((Player*)pCaster)->isAllowedToLoot((Creature*)target))) { pCaster->CastSpell(pCaster, 43836, true, NULL, this); } } break; } case <API key>: case <API key>: { // don't damage target if not alive, possible death persistent effects if (!target->IsAlive()) { return; } Unit* pCaster = GetCaster(); if (!pCaster) { return; } if (!pCaster->IsAlive()) { return; } if (spellProto->Effect[GetEffIndex()] == <API key> && pCaster->SpellHitResult(target, spellProto, false) != SPELL_MISS_NONE) { return; } // Check for immune if (target->IsImmunedToDamage(GetSpellSchoolMask(spellProto))) { return; } uint32 absorb = 0; uint32 resist = 0; CleanDamage cleanDamage = CleanDamage(0, BASE_ATTACK, MELEE_HIT_NORMAL); uint32 pdamage = m_modifier.m_amount > 0 ? m_modifier.m_amount : 0; // Calculate armor mitigation if it is a physical spell if (GetSpellSchoolMask(spellProto) & <API key>) { uint32 <API key> = pCaster-><API key>(target, pdamage); cleanDamage.damage += pdamage - <API key>; pdamage = <API key>; } pdamage = target-><API key>(pCaster, spellProto, pdamage, DOT, GetStackAmount()); bool isCrit = <API key>(pCaster, pdamage); // send critical in hit info for threat calculation if (isCrit) { cleanDamage.hitOutCome = MELEE_HIT_CRIT; // Resilience - reduce crit damage pdamage -= target-><API key>(pdamage); } // only from players // FIXME: need use SpellDamageBonus instead? if (GetCasterGuid().IsPlayer()) pdamage -= target-><API key>(pdamage); target-><API key>(pCaster, GetSpellSchoolMask(spellProto), DOT, pdamage, &absorb, &resist, !spellProto->HasAttribute(<API key>)); DETAIL_FILTER_LOG(<API key>, "PeriodicTick: %s health leech of %s for %u dmg inflicted by %u abs is %u", GetCasterGuid().GetString().c_str(), target->GetGuidStr().c_str(), pdamage, GetId(), absorb); pCaster->DealDamageMods(target, pdamage, &absorb); pCaster-><API key>(target, GetId(), pdamage, GetSpellSchoolMask(spellProto), absorb, resist, false, 0, isCrit); float multiplier = spellProto->EffectMultipleValue[GetEffIndex()] > 0 ? spellProto->EffectMultipleValue[GetEffIndex()] : 1; // Set trigger flag uint32 procAttacker = <API key>; // | <API key>; uint32 procVictim = <API key>;// | <API key>; uint32 procEx = isCrit ? <API key> : PROC_EX_NORMAL_HIT; pdamage = (pdamage <= absorb + resist) ? 0 : (pdamage - absorb - resist); if (pdamage) { procVictim |= <API key>; } pCaster->ProcDamageAndSpell(target, procAttacker, procVictim, procEx, pdamage, BASE_ATTACK, spellProto); int32 new_damage = pCaster->DealDamage(target, pdamage, &cleanDamage, DOT, GetSpellSchoolMask(spellProto), spellProto, false); if (!target->IsAlive() && pCaster-><API key>(false)) for (uint32 i = <API key>; i < CURRENT_MAX_SPELL; ++i) if (Spell* spell = pCaster->GetCurrentSpell(CurrentSpellTypes(i))) if (spell->m_spellInfo->Id == GetId()) { spell->cancel(); } if (Player* modOwner = pCaster->GetSpellModOwner()) { modOwner->ApplySpellMod(GetId(), <API key>, multiplier); } int32 heal = pCaster-><API key>(pCaster, spellProto, int32(new_damage * multiplier), DOT, GetStackAmount()); uint32 absorbHeal = 0; pCaster->CalculateHealAbsorb(heal, &absorbHeal); int32 gain = pCaster->DealHeal(pCaster, heal - absorbHeal, spellProto, false, absorbHeal); pCaster-><API key>().threatAssist(pCaster, gain * 0.5f * sSpellMgr.<API key>(spellProto), spellProto); break; } case <API key>: case <API key>: { // don't heal target if not alive, mostly death persistent effects from items if (!target->IsAlive()) { return; } Unit* pCaster = GetCaster(); if (!pCaster) return; // Don't heal target if it is already at max health if (target->GetHealth() != target->GetMaxHealth()) { // heal for caster damage (must be alive) if (target != pCaster && spellProto->SpellVisual[0] == 163 && !pCaster->IsAlive()) { return; } // ignore non positive values (can be result apply spellmods to aura damage uint32 amount = m_modifier.m_amount > 0 ? m_modifier.m_amount : 0; uint32 pdamage; if (m_modifier.m_auraname == <API key>) { pdamage = uint32(target->GetMaxHealth() * amount / 100); } else { pdamage = amount; // Wild Growth (1/7 - 6 + 2*ramainTicks) % if (spellProto->SpellFamilyName == SPELLFAMILY_DRUID && spellProto->SpellIconID == 2864) { int32 ticks = GetAuraMaxTicks(); int32 remainingTicks = ticks - GetAuraTicks(); int32 addition = int32(amount) * ticks * (-6 + 2 * remainingTicks) / 100; if (GetAuraTicks() != 1) // Item - Druid T10 Restoration 2P Bonus if (Aura* aura = pCaster->GetAura(70658, EFFECT_INDEX_0)) addition += abs(int32((addition * aura->GetModifier()->m_amount) / ((ticks - 1) * 100))); pdamage = int32(pdamage) + addition; } } pdamage = target-><API key>(pCaster, spellProto, pdamage, DOT, GetStackAmount()); // This method can modify pdamage bool isCrit = <API key>(pCaster, pdamage); uint32 absorbHeal = 0; pCaster->CalculateHealAbsorb(pdamage, &absorbHeal); pdamage -= absorbHeal; DETAIL_FILTER_LOG(<API key>, "PeriodicTick: %s heal of %s for %u health (absorbed %u) inflicted by %u", GetCasterGuid().GetString().c_str(), target->GetGuidStr().c_str(), pdamage, absorbHeal, GetId()); int32 gain = target->ModifyHealth(pdamage); <API key> pInfo(this, pdamage, (pdamage - uint32(gain)), absorbHeal, 0, 0.0f, isCrit); target->SendPeriodicAuraLog(&pInfo); // Set trigger flag uint32 procAttacker = <API key>; uint32 procVictim = <API key>; uint32 procEx = <API key> | (isCrit ? <API key> : PROC_EX_NORMAL_HIT); pCaster->ProcDamageAndSpell(target, procAttacker, procVictim, procEx, gain, BASE_ATTACK, spellProto); // add HoTs to amount healed in bgs if (pCaster->GetTypeId() == TYPEID_PLAYER) if (BattleGround* bg = ((Player*)pCaster)->GetBattleGround()) bg->UpdatePlayerScore(((Player*)pCaster), SCORE_HEALING_DONE, gain); target-><API key>().threatAssist(pCaster, float(gain) * 0.5f * sSpellMgr.<API key>(spellProto), spellProto); // heal for caster damage if (target != pCaster && spellProto->SpellVisual[0] == 163) { uint32 dmg = spellProto->manaPerSecond; if (pCaster->GetHealth() <= dmg && pCaster->GetTypeId() == TYPEID_PLAYER) { pCaster-><API key>(GetId()); // finish current generic/channeling spells, don't affect autorepeat pCaster->FinishSpell(<API key>); pCaster->FinishSpell(<API key>); } else { uint32 damage = gain; uint32 absorb = 0; pCaster->DealDamageMods(pCaster, damage, &absorb); pCaster-><API key>(pCaster, GetId(), damage, GetSpellSchoolMask(spellProto), absorb, 0, false, 0, false); CleanDamage cleanDamage = CleanDamage(0, BASE_ATTACK, MELEE_HIT_NORMAL); pCaster->DealDamage(pCaster, damage, &cleanDamage, NODAMAGE, GetSpellSchoolMask(spellProto), spellProto, true); } } } // Apply Well Fed buffs from non-standard spells if (GetAuraTicks() == 10) { switch (spellProto->Id) { case 24869: // Apple Bobber case 61874: // Noblegarden Chocolate case 71068: // Sweet Surprise case 71071: // Very Berry Cream case 71073: // Dark Desire case 71074: // Buttermilk Delight pCaster->CastSpell(pCaster, 24870, true); break; default: break; } } break; } case <API key>: { // don't damage target if not alive, possible death persistent effects if (!target->IsAlive()) { return; } if (m_modifier.m_miscvalue < 0 || m_modifier.m_miscvalue >= MAX_POWERS) { return; } Powers power = Powers(m_modifier.m_miscvalue); // power type might have changed between aura applying and tick (druid's shapeshift) if (target->GetPowerType() != power) { return; } Unit* pCaster = GetCaster(); if (!pCaster) { return; } if (!pCaster->IsAlive()) { return; } if (GetSpellProto()->Effect[GetEffIndex()] == <API key> && pCaster->SpellHitResult(target, spellProto, false) != SPELL_MISS_NONE) { return; } // Check for immune (not use charges) if (target->IsImmunedToDamage(GetSpellSchoolMask(spellProto))) { return; } // ignore non positive values (can be result apply spellmods to aura damage uint32 pdamage = m_modifier.m_amount > 0 ? m_modifier.m_amount : 0; // Special case: draining x% of mana (up to a maximum of 2*x% of the caster's maximum mana) // It's mana percent cost spells, m_modifier.m_amount is percent drain from target if (spellProto->ManaCostPercentage) { // max value uint32 maxmana = pCaster->GetMaxPower(power) * pdamage * 2 / 100; pdamage = target->GetMaxPower(power) * pdamage / 100; if (pdamage > maxmana) pdamage = maxmana; } DETAIL_FILTER_LOG(<API key>, "PeriodicTick: %s power leech of %s for %u dmg inflicted by %u", GetCasterGuid().GetString().c_str(), target->GetGuidStr().c_str(), pdamage, GetId()); int32 drain_amount = target->GetPower(power) > pdamage ? pdamage : target->GetPower(power); // resilience reduce mana draining effect at spell crit damage reduction (added in 2.4) if (power == POWER_MANA) drain_amount -= target-><API key>(drain_amount); target->ModifyPower(power, -drain_amount); float gain_multiplier = 0.0f; if (pCaster->GetMaxPower(power) > 0) { gain_multiplier = spellProto->EffectMultipleValue[GetEffIndex()]; if (Player* modOwner = pCaster->GetSpellModOwner()) { modOwner->ApplySpellMod(GetId(), <API key>, gain_multiplier); } } <API key> pInfo(this, drain_amount, 0, 0, 0, gain_multiplier); target->SendPeriodicAuraLog(&pInfo); if (int32 gain_amount = int32(drain_amount * gain_multiplier)) { int32 gain = pCaster->ModifyPower(power, gain_amount); if (GetId() == 5138) // Drain Mana if (Aura* petPart = GetHolder()-><API key>(EFFECT_INDEX_1)) if (int pet_gain = gain_amount * petPart->GetModifier()->m_amount / 100) pCaster->CastCustomSpell(pCaster, 32554, &pet_gain, NULL, NULL, true); target->AddThreat(pCaster, float(gain) * 0.5f, pInfo.critical, GetSpellSchoolMask(spellProto), spellProto); } // Some special cases switch (GetId()) { case 32960: // Mark of Kazzak { if (target->GetTypeId() == TYPEID_PLAYER && target->GetPowerType() == POWER_MANA) { // Drain 5% of target's mana pdamage = target->GetMaxPower(POWER_MANA) * 5 / 100; drain_amount = target->GetPower(POWER_MANA) > pdamage ? pdamage : target->GetPower(POWER_MANA); target->ModifyPower(POWER_MANA, -drain_amount); <API key> pInfo(this, drain_amount, 0, 0, 0, 0.0f); target->SendPeriodicAuraLog(&pInfo); } // no break here } case 21056: // Mark of Kazzak case 31447: // Mark of Kaz'rogal { uint32 triggerSpell = 0; switch (GetId()) { case 21056: triggerSpell = 21058; break; case 31447: triggerSpell = 31463; break; case 32960: triggerSpell = 32961; break; } if (target->GetTypeId() == TYPEID_PLAYER && target->GetPower(power) == 0) { target->CastSpell(target, triggerSpell, true, NULL, this); target-><API key>(GetId()); } break; } } break; } case <API key>: { // don't energize target if not alive, possible death persistent effects if (!target->IsAlive()) { return; } // ignore non positive values (can be result apply spellmods to aura damage uint32 pdamage = m_modifier.m_amount > 0 ? m_modifier.m_amount : 0; DETAIL_FILTER_LOG(<API key>, "PeriodicTick: %s energize %s for %u dmg inflicted by %u", GetCasterGuid().GetString().c_str(), target->GetGuidStr().c_str(), pdamage, GetId()); if (m_modifier.m_miscvalue < 0 || m_modifier.m_miscvalue >= MAX_POWERS) { break; } Powers power = Powers(m_modifier.m_miscvalue); if (target->GetMaxPower(power) == 0) { break; } <API key> pInfo(this, pdamage, 0, 0, 0, 0.0f); target->SendPeriodicAuraLog(&pInfo); int32 gain = target->ModifyPower(power, pdamage); if (Unit* pCaster = GetCaster()) { target-><API key>().threatAssist(pCaster, float(gain) * 0.5f * sSpellMgr.<API key>(spellProto), spellProto); } break; } case <API key>: { // don't energize target if not alive, possible death persistent effects if (!target->IsAlive()) { return; } // ignore non positive values (can be result apply spellmods to aura damage uint32 amount = m_modifier.m_amount > 0 ? m_modifier.m_amount : 0; uint32 pdamage = uint32(target->GetMaxPower(POWER_MANA) * amount / 100); DETAIL_FILTER_LOG(<API key>, "PeriodicTick: %s energize %s for %u mana inflicted by %u", GetCasterGuid().GetString().c_str(), target->GetGuidStr().c_str(), pdamage, GetId()); if (target->GetMaxPower(POWER_MANA) == 0) { break; } <API key> pInfo(this, pdamage, 0, 0, 0, 0.0f); target->SendPeriodicAuraLog(&pInfo); int32 gain = target->ModifyPower(POWER_MANA, pdamage); if (Unit* pCaster = GetCaster()) { target-><API key>().threatAssist(pCaster, float(gain) * 0.5f * sSpellMgr.<API key>(spellProto), spellProto); } break; } case <API key>: { // don't mana burn target if not alive, possible death persistent effects if (!target->IsAlive()) { return; } Unit* pCaster = GetCaster(); if (!pCaster) { return; } // Check for immune (not use charges) if (target->IsImmunedToDamage(GetSpellSchoolMask(spellProto))) { return; } int32 pdamage = m_modifier.m_amount > 0 ? m_modifier.m_amount : 0; Powers powerType = Powers(m_modifier.m_miscvalue); if (!target->IsAlive() || target->GetPowerType() != powerType) { return; } // resilience reduce mana draining effect at spell crit damage reduction (added in 2.4) if (powerType == POWER_MANA) pdamage -= ((Player*)target)-><API key>(pdamage); uint32 gain = uint32(-target->ModifyPower(powerType, -pdamage)); gain = uint32(gain * spellProto->EffectMultipleValue[GetEffIndex()]); // maybe has to be sent different to client, but not by <API key> SpellNonMeleeDamage damageInfo(pCaster, target, spellProto->Id, SpellSchoolMask(spellProto->SchoolMask)); pCaster-><API key>(&damageInfo, gain, spellProto); damageInfo.target-><API key>(pCaster, &damageInfo, spellProto); pCaster->DealDamageMods(damageInfo.target, damageInfo.damage, &damageInfo.absorb); pCaster-><API key>(&damageInfo); // Set trigger flag uint32 procAttacker = <API key>; // | <API key>; uint32 procVictim = <API key>;// | <API key>; uint32 procEx = <API key>(&damageInfo, SPELL_MISS_NONE); if (damageInfo.damage) { procVictim |= <API key>; } pCaster->ProcDamageAndSpell(damageInfo.target, procAttacker, procVictim, procEx, damageInfo.damage, BASE_ATTACK, spellProto); pCaster->DealSpellDamage(&damageInfo, true); break; } case <API key>: { // don't heal target if not alive, possible death persistent effects if (!target->IsAlive()) { return; } int32 gain = target->ModifyHealth(m_modifier.m_amount); if (Unit* caster = GetCaster()) { target-><API key>().threatAssist(caster, float(gain) * 0.5f * sSpellMgr.<API key>(spellProto), spellProto); } break; } case <API key>: { // don't energize target if not alive, possible death persistent effects if (!target->IsAlive()) { return; } Powers powerType = target->GetPowerType(); if (int32(powerType) != m_modifier.m_miscvalue) { return; } if (spellProto->AuraInterruptFlags & <API key>) { // eating anim target->HandleEmoteCommand(EMOTE_ONESHOT_EAT); } else if (GetId() == 20577) { // cannibalize anim target->HandleEmoteCommand(<API key>); } // Anger Management // amount = 1+ 16 = 17 = 3,4*5 = 10,2*5/3 // so 17 is rounded amount for 5 sec tick grow ~ 1 range grow in 3 sec if (powerType == POWER_RAGE) target->ModifyPower(powerType, m_modifier.m_amount * 3 / 5); break; } // Here tick dummy auras case SPELL_AURA_DUMMY: // some spells have dummy aura case <API key>: { PeriodicDummyTick(); break; } case <API key>: { TriggerSpell(); break; } case <API key>: { <API key>(); break; } default: break; } } void Aura::PeriodicDummyTick() { SpellEntry const* spell = GetSpellProto(); Unit* target = GetTarget(); switch (spell->SpellFamilyName) { case SPELLFAMILY_GENERIC: { switch (spell->Id) { // Forsaken Skills case 7054: { // Possibly need cast one of them (but // 7038 Forsaken Skill: Swords // 7039 Forsaken Skill: Axes // 7040 Forsaken Skill: Daggers // 7041 Forsaken Skill: Maces // 7042 Forsaken Skill: Staves // 7043 Forsaken Skill: Bows // 7044 Forsaken Skill: Guns // 7045 Forsaken Skill: 2H Axes // 7046 Forsaken Skill: 2H Maces // 7047 Forsaken Skill: 2H Swords // 7048 Forsaken Skill: Defense // 7049 Forsaken Skill: Fire // 7050 Forsaken Skill: Frost // 7051 Forsaken Skill: Holy // 7053 Forsaken Skill: Shadow return; } case 7057: // Haunting Spirits if (roll_chance_i(33)) { target->CastSpell(target, m_modifier.m_amount, true, NULL, this); } return; // // Panda // case 19230: break; case 30019: // Control Piece { if (target->GetTypeId() != TYPEID_PLAYER) return; Unit* chessPiece = target->GetCharm(); if (!chessPiece) { target->CastSpell(target, 30529, true); target-><API key>(30019); } return; } // // Gossip NPC Periodic - Talk // case 33208: break; // // Gossip NPC Periodic - Despawn // case 33209: break; // // Steal Weapon // case 36207: break; // // Simon Game START timer, (DND) // case 39993: break; // // Knockdown Fel Cannon: break; The Aggro Burst // case 40119: break; // // Old Mount Spell // case 40154: break; // // Magnetic Pull // case 40581: break; // // Ethereal Ring: break; The Bolt Burst // case 40801: break; // // Crystal Prison // case 40846: break; // // Copy Weapon // case 41054: break; // // Dementia // case 41404: break; // // Ethereal Ring Visual, Lightning Aura // case 41477: break; // // Ethereal Ring Visual, Lightning Aura (Fork) // case 41525: break; // // Ethereal Ring Visual, Lightning Jumper Aura // case 41567: break; // // No Man's Land // case 41955: break; // // Headless Horseman - Fire // case 42074: break; // // Headless Horseman - Visual - Large Fire // case 42075: break; // // Headless Horseman - Start Fire, Periodic Aura // case 42140: break; // // Ram Speed Boost // case 42152: break; // // Headless Horseman - Fires Out Victory Aura // case 42235: break; // // Pumpkin Life Cycle // case 42280: break; // // Brewfest Request Chick Chuck Mug Aura // case 42537: break; // // Squashling // case 42596: break; // // Headless Horseman Climax, Head: Periodic // case 42603: break; case 42621: // Fire Bomb { // Cast the summon spells (42622 to 42627) with increasing chance uint32 rand = urand(0, 99); for (uint32 i = 1; i <= 6; ++i) { if (rand < i * (i + 1) / 2 * 5) { target->CastSpell(target, spell->Id + i, true); break; } } break; } // // Headless Horseman - Conflagrate, Periodic Aura // case 42637: break; // // Headless Horseman - Create Pumpkin Treats Aura // case 42774: break; // // Headless Horseman Climax - Summoning Rhyme Aura // case 42879: break; // // Tricky Treat // case 42919: break; // // Giddyup! // case 42924: break; // // Ram - Trot // case 42992: break; // // Ram - Canter // case 42993: break; // // Ram - Gallop // case 42994: break; // // Ram Level - Neutral // case 43310: break; // // Headless Horseman - Maniacal Laugh, Maniacal, Delayed 17 // case 43884: break; // // Wretched! // case 43963: break; // // Headless Horseman - Maniacal Laugh, Maniacal, other, Delayed 17 // case 44000: break; // // Energy Feedback // case 44328: break; // // Romantic Picnic // case 45102: break; // // Romantic Picnic // case 45123: break; // // Looking for Love // case 45124: break; // // Kite - Lightning Strike Kite Aura // case 45197: break; // // Rocket Chicken // case 45202: break; // // Copy Offhand Weapon // case 45205: break; // // Upper Deck - Kite - Lightning Periodic Aura // case 45207: break; // // Kite -Sky Lightning Strike Kite Aura // case 45251: break; // // Ribbon Pole Dancer Check Aura // case 45390: break; // // Holiday - Midsummer, Ribbon Pole Periodic Visual // case 45406: break; // // Parachute // case 45472: break; // // Alliance Flag, Extra Damage Debuff // case 45898: break; // // Horde Flag, Extra Damage Debuff // case 45899: break; // // Ahune - Summoning Rhyme Aura // case 45926: break; // // Ahune - Slippery Floor // case 45945: break; // // Ahune's Shield // case 45954: break; // // Nether Vapor Lightning // case 45960: break; // // Darkness // case 45996: break; case 46041: // Summon Blood Elves Periodic target->CastSpell(target, 46037, true, NULL, this); target->CastSpell(target, roll_chance_i(50) ? 46038 : 46039, true, NULL, this); target->CastSpell(target, 46040, true, NULL, this); return; // // Transform Visual Missile Periodic // case 46205: break; // // Find Opening Beam End // case 46333: break; case 46371: // Ice Spear Control Aura target->CastSpell(target, 46372, true, NULL, this); return; // // Hailstone Chill // case 46458: break; // // Hailstone Chill, Internal // case 46465: break; // // Chill, Internal Shifter // case 46549: break; // // Summon Ice Spear Knockback Delayer // case 46878: break; // // Burninate Effect // case 47214: break; // // Fizzcrank Practice Parachute // case 47228: break; // // Send Mug Control Aura // case 47369: break; // // Direbrew's Disarm (precast) // case 47407: break; // // Mole Machine Port Schedule // case 47489: break; // case 47941: break; // Crystal Spike // case 48200: break; // Healer Aura case 48630: // Summon Gauntlet Mobs Periodic case 59275: // Below may need some adjustment, pattern for amount of summon and where is not verified 100% (except for odd/even tick) { bool chance = roll_chance_i(50); target->CastSpell(target, chance ? 48631 : 48632, true, NULL, this); if (GetAuraTicks() % 2) // which doctor at odd tick target->CastSpell(target, chance ? 48636 : 48635, true, NULL, this); else // or harponeer, at even tick target->CastSpell(target, chance ? 48634 : 48633, true, NULL, this); return; } // case 49313: break; // Proximity Mine Area Aura // // Mole Machine Portal Schedule // case 49466: break; case 49555: // Corpse Explode (Drak'tharon Keep - Trollgore) case 59807: // Corpse Explode (heroic) { if (GetAuraTicks() == 3 && target->GetTypeId() == TYPEID_UNIT) ((Creature*)target)->ForcedDespawn(); if (GetAuraTicks() != 2) return; if (Unit* pCaster = GetCaster()) pCaster->CastSpell(target, spell->Id == 49555 ? 49618 : 59809, true); return; } // case 49592: break; // Temporal Rift // case 49957: break; // Cutting Laser // case 50085: break; // Slow Fall // // Listening to Music // case 50493: break; // // Love Rocket Barrage // case 50530: break; case 50789: // Summon iron dwarf (left or right) case 59860: target->CastSpell(target, roll_chance_i(50) ? 50790 : 50791, true, NULL, this); return; case 50792: // Summon iron trogg (left or right) case 59859: target->CastSpell(target, roll_chance_i(50) ? 50793 : 50794, true, NULL, this); return; case 50801: // Summon malformed ooze (left or right) case 59858: target->CastSpell(target, roll_chance_i(50) ? 50802 : 50803, true, NULL, this); return; case 50824: // Summon earthen dwarf target->CastSpell(target, roll_chance_i(50) ? 50825 : 50826, true, NULL, this); return; case 52441: // Cool Down target->CastSpell(target, 52443, true); return; case 53035: // Summon Anub'ar Champion Periodic (Azjol Nerub) case 53036: // Summon Anub'ar Necromancer Periodic (Azjol Nerub) case 53037: // Summon Anub'ar Crypt Fiend Periodic (Azjol Nerub) { uint32 summonSpells[3][3] = { {53090, 53014, 53064}, // Summon Anub'ar Champion {53092, 53015, 53066}, // Summon Anub'ar Necromancer {53091, 53016, 53065} // Summon Anub'ar Crypt Fiend }; // Cast different spell depending on trigger position // This will summon a different npc entry on each location - each of those has individual movement patern if (target->GetPositionZ() < 750.0f) target->CastSpell(target, summonSpells[spell->Id - 53035][0], true, NULL, this); else if (target->GetPositionX() > 500.0f) target->CastSpell(target, summonSpells[spell->Id - 53035][1], true, NULL, this); else target->CastSpell(target, summonSpells[spell->Id - 53035][2], true, NULL, this); return; } case 53520: // Carrion Beetles target->CastSpell(target, 53521, true, NULL, this); target->CastSpell(target, 53521, true, NULL, this); return; case 55592: // Clean switch (urand(0, 2)) { case 0: target->CastSpell(target, 55731, true); break; case 1: target->CastSpell(target, 55738, true); break; case 2: target->CastSpell(target, 55739, true); break; } return; case 61968: // Flash Freeze { if (GetAuraTicks() == 1 && !target->HasAura(62464)) target->CastSpell(target, 61970, true, NULL, this); return; } case 62018: // Collapse { // lose 1% of health every second target->DealDamage(target, target->GetMaxHealth() * .01, NULL, DIRECT_DAMAGE, <API key>, NULL, false); return; } case 62019: // Rune of Summoning { target->CastSpell(target, 62020, true, NULL, this); return; } case 62038: // Biting Cold { if (target->GetTypeId() != TYPEID_PLAYER) return; // if player is moving remove one aura stack if (((Player*)target)->isMoving()) target-><API key>(62039); // otherwise add one aura stack each 3 seconds else if (GetAuraTicks() % 3 && !target->HasAura(62821)) target->CastSpell(target, 62039, true, NULL, this); return; } case 62039: // Biting Cold { target->CastSpell(target, 62188, true); return; } case 62566: // Healthy Spore Summon Periodic { target->CastSpell(target, 62582, true); target->CastSpell(target, 62591, true); target->CastSpell(target, 62592, true); target->CastSpell(target, 62593, true); return; } case 62717: // Slag Pot { target->CastSpell(target, target->GetMap()->IsRegularDifficulty() ? 65722 : 65723, true, NULL, this); // cast Slag Imbued if the target survives up to the last tick if (GetAuraTicks() == 10) target->CastSpell(target, 63536, true, NULL, this); return; } case 63050: // Sanity { if (GetHolder()->GetStackAmount() <= 25 && !target->HasAura(63752)) target->CastSpell(target, 63752, true); else if (GetHolder()->GetStackAmount() > 25 && target->HasAura(63752)) target-><API key>(63752); return; } case 63382: // Rapid Burst { if (GetAuraTicks() % 2) target->CastSpell(target, target->GetMap()->IsRegularDifficulty() ? 64019 : 64532, true); else target->CastSpell(target, target->GetMap()->IsRegularDifficulty() ? 63387 : 64531, true); return; } case 64101: // Defend { target->CastSpell(target, 62719, true); target->CastSpell(target, 64192, true); return; } case 64217: // Overcharged { if (GetHolder()->GetStackAmount() >= 10) { target->CastSpell(target, 64219, true); target->DealDamage(target, target->GetHealth(), NULL, DIRECT_DAMAGE, <API key>, NULL, false); } return; } case 64412: // Phase Punch { if (SpellAuraHolder* phaseAura = target->GetSpellAuraHolder(64412)) { uint32 uiAuraId = 0; switch (phaseAura->GetStackAmount()) { case 1: uiAuraId = 64435; break; case 2: uiAuraId = 64434; break; case 3: uiAuraId = 64428; break; case 4: uiAuraId = 64421; break; case 5: uiAuraId = 64417; break; } if (uiAuraId && !target->HasAura(uiAuraId)) { target->CastSpell(target, uiAuraId, true, NULL, this); // remove original aura if phased if (uiAuraId == 64417) { target-><API key>(64412); target->CastSpell(target, 62169, true, NULL, this); } } } return; } case 65272: // Shatter Chest { target->CastSpell(target, 62501, true, NULL, this); return; } case 66118: // Leeching Swarm case 67630: // Leeching Swarm case 68646: // Leeching Swarm case 68647: // Leeching Swarm { Unit* caster = GetCaster(); if (!caster) return; int32 lifeLeeched = int32(target->GetHealth() * m_modifier.m_amount * 0.01f); if (lifeLeeched < 250) lifeLeeched = 250; // Leeching swarm damage caster->CastCustomSpell(target, 66240, &lifeLeeched, NULL, NULL, true, NULL, this); // Leeching swarm heal target->CastCustomSpell(caster, 66125, &lifeLeeched, NULL, NULL, true, NULL, this); return; } case 68875: // Wailing Souls case 68876: // Wailing Souls { // Sweep around float newAngle = target->GetOrientation(); if (spell->Id == 68875) newAngle += 0.09f; else newAngle -= 0.09f; newAngle = MapManager::<API key>(newAngle); target->SetFacingTo(newAngle); // Should actually be SMSG_SPELL_START, too target->CastSpell(target, 68873, true); return; } // Exist more after, need add later default: break; } // Drink (item drink spells) if (GetEffIndex() > EFFECT_INDEX_0 && spell->EffectApplyAuraName[GetEffIndex()-1] == <API key>) { if (target->GetTypeId() != TYPEID_PLAYER) return; // Search <API key> aura for this spell and add bonus if (Aura* aura = GetHolder()-><API key>(SpellEffectIndex(GetEffIndex() - 1))) { aura->GetModifier()->m_amount = m_modifier.m_amount; ((Player*)target)->UpdateManaRegen(); // Disable continue m_isPeriodic = false; return; } return; } // Prey on the Weak if (spell->SpellIconID == 2983) { Unit* victim = target->getVictim(); if (victim && (target->GetHealth() * 100 / target->GetMaxHealth() > victim->GetHealth() * 100 / victim->GetMaxHealth())) { if (!target->HasAura(58670)) { int32 basepoints = GetBasePoints(); target->CastCustomSpell(target, 58670, &basepoints, 0, 0, true); } } else target-><API key>(58670); } break; } case SPELLFAMILY_MAGE: { switch (spell->Id) { case 55342: // Mirror Image { if (GetAuraTicks() != 1) return; if (Unit* pCaster = GetCaster()) pCaster->CastSpell(pCaster, spell->EffectTriggerSpell[GetEffIndex()], true, NULL, this); return; } default: break; } break; } case SPELLFAMILY_DRUID: { switch (spell->Id) { // Frenzied Regeneration case 22842: { // Converts up to 10 rage per second into health for $d. Each point of rage is converted into ${$m2/10}.1% of max health. // Should be manauser if (target->GetPowerType() != POWER_RAGE) return; uint32 rage = target->GetPower(POWER_RAGE); // Nothing todo if (rage == 0) return; int32 mod = (rage < 100) ? rage : 100; int32 points = target-><API key>(target, spell, EFFECT_INDEX_1); int32 regen = target->GetMaxHealth() * (mod * points / 10) / 1000; target->CastCustomSpell(target, 22845, &regen, NULL, NULL, true, NULL, this); target->SetPower(POWER_RAGE, rage - mod); return; } // Force of Nature case 33831: return; default: break; } break; } case SPELLFAMILY_ROGUE: { switch (spell->Id) { // Killing Spree case 51690: { if (target->hasUnitState(UNIT_STAT_STUNNED) || target->isFeared()) return; Spell::UnitList targets; { // eff_radius ==0 float radius = GetSpellMaxRange(sSpellRangeStore.LookupEntry(spell->rangeIndex)); MaNGOS::<API key> u_check(target, target, radius); MaNGOS::UnitListSearcher<MaNGOS::<API key>> checker(targets, u_check); Cell::VisitAllObjects(target, checker, radius); } if (targets.empty()) return; Spell::UnitList::const_iterator itr = targets.begin(); std::advance(itr, rand() % targets.size()); Unit* victim = *itr; target->CastSpell(victim, 57840, true); target->CastSpell(victim, 57841, true); return; } default: break; } break; } case SPELLFAMILY_HUNTER: { // Explosive Shot if (spell->SpellFamilyFlags & UI64LIT(0x8000000000000000)) { target->CastCustomSpell(target, 53352, &m_modifier.m_amount, 0, 0, true, 0, this, GetCasterGuid()); return; } switch (spell->Id) { // Harpooner's Mark // case 40084: // return; // Feeding Frenzy Rank 1 & 2 case 53511: case 53512: { Unit* victim = target->getVictim(); if (victim && victim->GetHealth() * 100 < victim->GetMaxHealth() * 35) target->CastSpell(target, spell->Id == 53511 ? 60096 : 60097, true, NULL, this); return; } default: break; } break; } case SPELLFAMILY_SHAMAN: { // Astral Shift if (spell->Id == 52179) { // Periodic need for remove visual on stun/fear/silence lost if (!target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_STUNNED | UNIT_FLAG_FLEEING | UNIT_FLAG_SILENCED)) target-><API key>(52179); return; } break; } case <API key>: { // Death and Decay if (spell->SpellFamilyFlags & UI64LIT(0x0000000000000020)) { if (Unit* caster = GetCaster()) caster->CastCustomSpell(target, 52212, &m_modifier.m_amount, NULL, NULL, true, NULL, this); return; } // Raise Dead // if (spell->SpellFamilyFlags & UI64LIT(0x0000000000001000)) // return; // Chains of Ice if (spell->SpellFamilyFlags & UI64LIT(0x0000400000000000)) { // Get 0 effect aura Aura* slow = target->GetAura(GetId(), EFFECT_INDEX_0); if (slow) { slow->ApplyModifier(false, true); Modifier* mod = slow->GetModifier(); mod->m_amount += m_modifier.m_amount; if (mod->m_amount > 0) mod->m_amount = 0; slow->ApplyModifier(true, true); } return; } // Summon Gargoyle // if (spell->SpellFamilyFlags & UI64LIT(0x0000008000000000)) // return; // Death Rune Mastery // if (spell->SpellFamilyFlags & UI64LIT(0x0000000000004000)) // return; // Bladed Armor if (spell->SpellIconID == 2653) { // Increases your attack power by $s1 for every $s2 armor value you have. // Calculate AP bonus (from 1 efect of this spell) int32 apBonus = m_modifier.m_amount * target->GetArmor() / target-><API key>(target, spell, EFFECT_INDEX_1); target->CastCustomSpell(target, 61217, &apBonus, &apBonus, NULL, true, NULL, this); return; } // Reaping // if (spell->SpellIconID == 22) // return; // Blood of the North // if (spell->SpellIconID == 30412) // return; // Hysteria if (spell->SpellFamilyFlags & UI64LIT(0x0000000020000000)) { // damage not expected to be show in logs, not any damage spell related to damage apply uint32 deal = m_modifier.m_amount * target->GetMaxHealth() / 100; target->DealDamage(target, deal, NULL, DIRECT_DAMAGE, <API key>, NULL, false); return; } break; } default: break; } if (Unit* caster = GetCaster()) { if (target && target->GetTypeId() == TYPEID_UNIT) { sScriptMgr.OnEffectDummy(caster, GetId(), GetEffIndex(), (Creature*)target, ObjectGuid()); } } } void Aura::<API key>(bool apply, bool Real) { if (!Real) { return; } Unit::AuraList const& fearAuras = GetTarget()->GetAurasByType(SPELL_AURA_MOD_FEAR); if (!fearAuras.empty()) { if (apply) { GetTarget()->SetFeared(false, fearAuras.front()->GetCasterGuid()); } else { GetTarget()->SetFeared(true); } } } void Aura::HandleManaShield(bool apply, bool Real) { if (!Real) { return; } // prevent double apply bonuses if (apply && (GetTarget()->GetTypeId() != TYPEID_PLAYER || !((Player*)GetTarget())->GetSession()->PlayerLoading())) { if (Unit* caster = GetCaster()) { float DoneActualBenefit = 0.0f; switch (GetSpellProto()->SpellFamilyName) { case SPELLFAMILY_MAGE: if (GetSpellProto()->SpellFamilyFlags & UI64LIT(0x0000000000008000)) { // Mana Shield // +50% from +spd bonus DoneActualBenefit = caster-><API key>(GetSpellSchoolMask(GetSpellProto())) * 0.5f; break; } break; default: break; } DoneActualBenefit *= caster-><API key>(GetSpellProto()); m_modifier.m_amount += (int32)DoneActualBenefit; } } } void Aura::<API key>(bool apply, bool Real) { if (!Real) return; Unit* target = GetTarget(); target->ApplyModFlag(UNIT_FIELD_FLAGS, <API key>, apply); if (apply) { // max regen powers at start preparation target->SetHealth(target->GetMaxHealth()); target->SetPower(POWER_MANA, target->GetMaxPower(POWER_MANA)); target->SetPower(POWER_ENERGY, target->GetMaxPower(POWER_ENERGY)); } else { // reset originally 0 powers at start/leave target->SetPower(POWER_RAGE, 0); target->SetPower(POWER_RUNIC_POWER, 0); } } /* * Such auras are applied from a caster(=player) to a vehicle. * This has been verified using spell #49256 */ void Aura::<API key>(bool apply, bool Real) { if (!Real) return; Unit* target = GetTarget(); if (!target->IsVehicle()) return; Unit* caster = GetCaster(); if (!caster) return; if (apply) { target->GetVehicleInfo()->Board(caster, GetBasePoints() - 1); } else target->GetVehicleInfo()->UnBoard(caster, m_removeMode == <API key>); } void Aura::<API key>(bool apply, bool Real) { if (!Real) return; Unit* target = GetTarget(); if (!target || target->GetTypeId() != TYPEID_PLAYER) // only players should be affected by this aura return; uint16 i_OverrideSetId = GetMiscValue(); const <API key>* spellSet = <API key>.LookupEntry(i_OverrideSetId); if (!spellSet) return; if (apply) { // spell give the player a new castbar with some spells.. this is a clientside process.. // serverside just needs to register the new spells so that player isn't kicked as cheater for (int i = 0; i < MAX_OVERRIDE_SPELLS; ++i) if (uint32 spellId = spellSet->Spells[i]) static_cast<Player*>(target)->addSpell(spellId, true, false, false, false); target->SetUInt16Value(PLAYER_FIELD_BYTES2, 0, i_OverrideSetId); } else { target->SetUInt16Value(PLAYER_FIELD_BYTES2, 0, 0); for (int i = 0; i < MAX_OVERRIDE_SPELLS; ++i) if (uint32 spellId = spellSet->Spells[i]) static_cast<Player*>(target)->removeSpell(spellId, false , false, false); } } void Aura::<API key>(bool apply, bool Real) { if (!Real || GetTarget()->GetTypeId() != TYPEID_PLAYER || !GetTarget()->IsInWorld()) return; Player* player = (Player*)GetTarget(); if (apply) player->GetSession()->SendStablePet(player->GetObjectGuid()); // client auto close stable dialog at !apply aura } void Aura::<API key>(bool apply, bool Real) { if (!Real) return; // Target of aura should always be creature (ref Spell::CheckCast) Creature* pCreature = (Creature*)GetTarget(); if (apply) { // Caster can be player or creature, the unit who pCreature will become an clone of. Unit* caster = GetCaster(); if (caster->GetTypeId() == TYPEID_PLAYER) // TODO - Verify! Does it take a 'pseudo-race' (from display-id) for creature-mirroring, and what is sent in <API key> pCreature->SetByteValue(UNIT_FIELD_BYTES_0, 0, caster->getRace()); pCreature->SetByteValue(UNIT_FIELD_BYTES_0, 1, caster->getClass()); pCreature->SetByteValue(UNIT_FIELD_BYTES_0, 2, caster->getGender()); pCreature->SetByteValue(UNIT_FIELD_BYTES_0, 3, caster->GetPowerType()); pCreature->SetFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_CLONED); pCreature->SetDisplayId(caster->GetNativeDisplayId()); } else { const CreatureInfo* cinfo = pCreature->GetCreatureInfo(); const CreatureModelInfo* minfo = sObjectMgr.<API key>(pCreature->GetNativeDisplayId()); pCreature->SetByteValue(UNIT_FIELD_BYTES_0, 0, 0); pCreature->SetByteValue(UNIT_FIELD_BYTES_0, 1, cinfo->UnitClass); pCreature->SetByteValue(UNIT_FIELD_BYTES_0, 2, minfo->gender); pCreature->SetByteValue(UNIT_FIELD_BYTES_0, 3, 0); pCreature->RemoveFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_CLONED); pCreature->SetDisplayId(pCreature->GetNativeDisplayId()); } } void Aura::HandleMirrorName(bool apply, bool Real) { if (!Real) return; Unit* caster = GetCaster(); Unit* target = GetTarget(); if (!target || !caster || target->GetTypeId() != TYPEID_UNIT) return; if (apply) target->SetName(caster->GetName()); else { CreatureInfo const* cinfo = ((Creature*)target)->GetCreatureInfo(); if (!cinfo) return; target->SetName(cinfo->Name); } } void Aura::<API key>(bool apply, bool Real) { if (!Real) return; if (GetTarget()->GetTypeId() != TYPEID_PLAYER) return; Player* plr = (Player*)GetTarget(); if (plr->getClass() != CLASS_DEATH_KNIGHT) return; RuneType runeFrom = RuneType(GetSpellProto()->EffectMiscValue[m_effIndex]); RuneType runeTo = RuneType(GetSpellProto()->EffectMiscValueB[m_effIndex]); if (apply) { for (uint32 i = 0; i < MAX_RUNES; ++i) { if (plr->GetCurrentRune(i) == runeFrom && !plr->GetRuneCooldown(i)) { plr->ConvertRune(i, runeTo); break; } } } else { for (uint32 i = 0; i < MAX_RUNES; ++i) { if (plr->GetCurrentRune(i) == runeTo && plr->GetBaseRune(i) == runeFrom) { plr->ConvertRune(i, runeFrom); break; } } } } void Aura::HandlePhase(bool apply, bool Real) { if (!Real) return; Unit* target = GetTarget(); // always non stackable if (apply) { Unit::AuraList const& phases = target->GetAurasByType(SPELL_AURA_PHASE); if (!phases.empty()) target-><API key>(phases.front()->GetId(), GetHolder()); } target->SetPhaseMask(apply ? GetMiscValue() : uint32(PHASEMASK_NORMAL), true); // no-phase is also phase state so same code for apply and remove if (target->GetTypeId() == TYPEID_PLAYER) { <API key> saBounds = sSpellMgr.<API key>(GetId()); if (saBounds.first != saBounds.second) { uint32 zone, area; target->GetZoneAndAreaId(zone, area); for (SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr) itr->second-><API key>((Player*)target, zone, area, false); } } } void Aura::HandleAuraSafeFall(bool Apply, bool Real) { // implemented in WorldSession::<API key> // only special case if (Apply && Real && GetId() == 32474 && GetTarget()->GetTypeId() == TYPEID_PLAYER) ((Player*)GetTarget())->ActivateTaxiPathTo(506, GetId()); } bool Aura::<API key>(Unit* caster, uint32& damage) { if (!GetSpellProto()->IsFitToFamily(SPELLFAMILY_ROGUE, UI64LIT(0x100000)) && // Rupture !caster->HasAffectedAura(<API key>, GetSpellProto())) return false; if (caster->IsSpellCrit(GetTarget(), GetSpellProto(), GetSpellSchoolMask(GetSpellProto()))) { damage = caster-><API key>(GetSpellProto(), damage, GetTarget()); return true; } return false; } void Aura::<API key>(bool /*apply*/, bool /*Real*/) { if (GetTarget()->GetTypeId() != TYPEID_PLAYER) return; ((Player*)GetTarget())-><API key>(); } void Aura::<API key>(bool apply, bool Real) { // spells required only Real aura add/remove if (!Real) return; Unit* target = GetTarget(); if (target->GetTypeId() != TYPEID_PLAYER) return; ((Player*)target)->HandleBaseModValue(CRIT_PERCENTAGE, FLAT_MOD, float(m_modifier.m_amount), apply); ((Player*)target)->HandleBaseModValue(<API key>, FLAT_MOD, float(m_modifier.m_amount), apply); ((Player*)target)->HandleBaseModValue(<API key>, FLAT_MOD, float(m_modifier.m_amount), apply); // included in Player::<API key> calculation ((Player*)target)-><API key>(); } void Aura::<API key>(bool apply, bool Real) { if (!Real) return; GetTarget()->ApplyModFlag(UNIT_FIELD_FLAGS_2, <API key>, !apply && !GetTarget()-><API key>()); } void Aura::<API key>(bool apply, bool Real) { if (!Real) return; GetTarget()->SetVehicleId(apply ? GetMiscValue() : 0, 0); } void Aura::<API key>(bool apply, bool Real) { if (!Real) return; Unit* target = GetTarget(); if (!target || target->GetTypeId() != TYPEID_PLAYER) return; if (apply) target->RemoveByteFlag(PLAYER_FIELD_BYTES, 0, <API key>); else if (!target->GetMap()->Instanceable()) target->SetByteFlag(PLAYER_FIELD_BYTES, 0, <API key>); } void Aura::<API key>(bool apply, bool Real) { if (!Real) return; Unit* target = GetTarget(); if (!target || !<API key>.LookupEntry(GetMiscValue())) return; if (apply) target->setFaction(GetMiscValue()); else target-><API key>(); } void Aura::<API key>(bool apply, bool Real) { if (!Real) return; uint32 linkedSpell = GetSpellProto()->EffectTriggerSpell[m_effIndex]; SpellEntry const* spellInfo = sSpellStore.LookupEntry(linkedSpell); if (!spellInfo) { sLog.outError("Aura::<API key> for spell %u effect %u triggering unknown spell id %u", GetSpellProto()->Id, m_effIndex, linkedSpell); return; } Unit* target = GetTarget(); if (apply) { // ToDo: handle various cases where base points need to be applied! target->CastSpell(target, spellInfo, true, NULL, this); } else target-><API key>(linkedSpell, GetCasterGuid()); } bool Aura::IsLastAuraOnHolder() { for (int32 i = 0; i < MAX_EFFECT_INDEX; ++i) if (i != GetEffIndex() && GetHolder()->m_auras[i]) { return false; } return true; } bool Aura::HasMechanic(uint32 mechanic) const { return GetSpellProto()->Mechanic == mechanic || GetSpellProto()->EffectMechanic[m_effIndex] == mechanic; } SpellAuraHolder::SpellAuraHolder(SpellEntry const* spellproto, Unit* target, WorldObject* caster, Item* castItem) : m_spellProto(spellproto), m_target(target), m_castItemGuid(castItem ? castItem->GetObjectGuid() : ObjectGuid()), m_auraSlot(MAX_AURAS), m_auraFlags(AFLAG_NONE), m_auraLevel(1), m_procCharges(0), m_stackAmount(1), m_timeCla(1000), m_removeMode(<API key>), m_AuraDRGroup(DIMINISHING_NONE), m_permanent(false), <API key>(true), m_deleted(false), m_in_use(0) { MANGOS_ASSERT(target); MANGOS_ASSERT(spellproto && spellproto == sSpellStore.LookupEntry(spellproto->Id) && "`info` must be pointer to sSpellStore element"); if (!caster) { m_casterGuid = target->GetObjectGuid(); } else { // remove this assert when not unit casters will be supported MANGOS_ASSERT(caster->isType(TYPEMASK_UNIT)) m_casterGuid = caster->GetObjectGuid(); } m_applyTime = time(NULL); m_isPassive = IsPassiveSpell(spellproto); m_isDeathPersist = <API key>(spellproto); m_trackedAuraType= IsSingleTargetSpell(spellproto) ? <API key> : IsSpellHaveAura(spellproto, <API key>) ? <API key> : <API key>; m_procCharges = spellproto->procCharges; <API key> = (GetCasterGuid() == m_target->GetObjectGuid() && m_spellProto->Stances && !m_spellProto->HasAttribute(<API key>) && !m_spellProto->HasAttribute(<API key>)); Unit* unitCaster = caster && caster->isType(TYPEMASK_UNIT) ? (Unit*)caster : NULL; m_duration = m_maxDuration = <API key>(spellproto, unitCaster); if (m_maxDuration == -1 || (m_isPassive && spellproto->DurationIndex == 0)) { m_permanent = true; } if (unitCaster) { if (Player* modOwner = unitCaster->GetSpellModOwner()) { modOwner->ApplySpellMod(GetId(), SPELLMOD_CHARGES, m_procCharges); } } // some custom stack values at aura holder create switch (m_spellProto->Id) { // some auras applied with max stack case 24575: // Brittle Armor case 24659: // Unstable Power case 24662: // Restless Strength case 26464: // Mercurial Shield case 34027: // Kill Command case 55166: // Tidal Force case 58914: // Kill Command (pet part) case 62519: // Attuned to Nature case 63050: // Sanity case 64455: // Feral Essence case 65294: // Empowered case 71564: // Deadly Precision case 74396: // Fingers of Frost m_stackAmount = m_spellProto->StackAmount; break; } for (int32 i = 0; i < MAX_EFFECT_INDEX; ++i) { m_auras[i] = NULL; } } void SpellAuraHolder::AddAura(Aura* aura, SpellEffectIndex index) { m_auras[index] = aura; m_auraFlags |= (1 << index); } void SpellAuraHolder::RemoveAura(SpellEffectIndex index) { m_auras[index] = NULL; m_auraFlags &= ~(1 << index); } void SpellAuraHolder::ApplyAuraModifiers(bool apply, bool real) { for (int32 i = 0; i < MAX_EFFECT_INDEX && !IsDeleted(); ++i) if (Aura* aur = <API key>(SpellEffectIndex(i))) { aur->ApplyModifier(apply, real); } } void SpellAuraHolder::_AddSpellAuraHolder() { if (!GetId()) { return; } if (!m_target) { return; } // Try find slot for aura uint8 slot = NULL_AURA_SLOT; // Lookup free slot if (m_target-><API key>() < MAX_AURAS) { Unit::VisibleAuraMap const& visibleAuras = m_target->GetVisibleAuras(); for (uint8 i = 0; i < MAX_AURAS; ++i) { Unit::VisibleAuraMap::const_iterator itr = visibleAuras.find(i); if (itr == visibleAuras.end()) { slot = i; // update for out of range group members (on 1 slot use) m_target->UpdateAuraForGroup(slot); break; } } } Unit* caster = GetCaster(); // set infinity cooldown state for spells if (caster && caster->GetTypeId() == TYPEID_PLAYER) { if (m_spellProto->HasAttribute(<API key>)) { Item* castItem = m_castItemGuid ? ((Player*)caster)->GetItemByGuid(m_castItemGuid) : NULL; ((Player*)caster)-><API key>(m_spellProto, castItem ? castItem->GetEntry() : 0, NULL, true); } } uint8 flags = 0; for (int32 i = 0; i < MAX_EFFECT_INDEX; ++i) { if (m_auras[i]) flags |= (1 << i); } flags |= ((GetCasterGuid() == GetTarget()->GetObjectGuid()) ? AFLAG_NOT_CASTER : AFLAG_NONE) | ((GetSpellMaxDuration(m_spellProto) > 0) ? AFLAG_DURATION : AFLAG_NONE) | (IsPositive() ? AFLAG_POSITIVE : AFLAG_NEGATIVE); SetAuraFlags(flags); SetAuraLevel(caster ? caster->getLevel() : sWorld.getConfig(<API key>)); if (IsNeedVisibleSlot(caster)) { SetAuraSlot(slot); if (slot < MAX_AURAS) // slot found send data to client { SetVisibleAura(false); SendAuraUpdate(false); }
using Framework; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace <API key> { public class <API key> : IPopularityFinder { public void SetSearchTerms(string[] terms) { throw new <API key>(); } public void SetSearchTerms(List<string> terms) { throw new <API key>(); } public string GetResult() { throw new <API key>(); } public string <API key>() { throw new <API key>(); } } }
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab #ifndef <API key> #define <API key> #include "include/int_types.h" static const uint8_t OBJECT_NONEXISTENT = 0; static const uint8_t OBJECT_EXISTS = 1; static const uint8_t OBJECT_PENDING = 2; static const uint8_t OBJECT_EXISTS_CLEAN = 3; #endif // <API key>
//metodo main public class WeatherStation { public static void main(String[] args) { // instanciando classes WeatherData weatherData = new WeatherData(); CurrentConditions currentDisplay = new CurrentConditions(weatherData); StatisticsDisplay statisticsDisplay = new StatisticsDisplay(weatherData); ForecastDisplay forecastDisplay = new ForecastDisplay(weatherData); weatherData.setMeasurements(80, 45, 23); weatherData.setMeasurements(70, 50, 14); weatherData.setMeasurements(45, 23, 56); } }
package de.konqi.fitapi.rest.webapi.resource; import com.google.appengine.api.blobstore.BlobKey; import de.konqi.fitapi.Utils; import javax.annotation.security.PermitAll; import javax.servlet.http.HttpServletResponse; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; import java.io.IOException; /** * Resource class for blob related functionality * * @author konqi */ @Path("/img") @PermitAll public class BlobResource { /** * Endpoint to serve a blob from Google's blob storage * @param blobKey * @param response * @return * @throws IOException */ @GET @Path("/{id}") public Response getBlob(@PathParam("id") String blobKey, @Context HttpServletResponse response) throws IOException { Utils.blobstoreService.serve(new BlobKey(blobKey), response); return Response.ok().build(); } }
<?php /* Register new post type */ add_action('init', '<API key>'); function <API key>() { $labels = array( 'name' => _x('News', 'post type general name', 'codeus'), 'singular_name' => _x('News', 'post type singular name', 'codeus'), 'add_new' => _x('Add New News', 'book', 'codeus'), 'add_new_item' => __('Add New News', 'codeus'), 'edit_item' => __('Edit News', 'codeus'), 'new_item' => __('New News', 'codeus'), 'view_item' => __('View News', 'codeus'), 'search_items' => __('Search News', 'codeus'), 'not_found' => __('No News found', 'codeus'), 'not_found_in_trash' => __('No News found in Trash', 'codeus'), 'parent_item_colon' => '' ); $args = array( 'labels' => $labels, 'public' => true, 'publicly_queryable' => true, 'show_ui' => true, 'query_var' => true, 'rewrite' => array('slug' => 'news', 'with_front' => false), 'capability_type' => 'post', 'hierarchical' => false, 'menu_position' => null, 'supports' => array('title', 'editor', 'excerpt', 'thumbnail'), ); register_post_type('codeus_news', $args); } /* News block for home page */ function codeus_news_block($params = NULL) { $block_class = 'fullwidth'; if(isset($params->news_layout) && $params->news_layout == 'with_sidebar') { $block_class = 'center'; } $news_count = isset($params->news_count) && $params->news_count > 0 ? $params->news_count : 4; $news = get_posts(array('numberposts' => $news_count, 'post_type' => 'codeus_news', 'suppress_filters' => false)); ?> <?php if($block_class == 'center') : ?> <div class="panel clearfix"> <?php endif; ?> <div class="<?php echo $block_class; ?>"> <h2><?php _e('News', 'codeus'); ?></h2> <div class="news_list lazy-loading clearfix" data-ll-item-delay="0"> <?php if(!count($news)) : ?> <div class="empty"><?php _e('No News found', 'codeus'); ?></div> <?php endif; ?> <?php foreach($news as $news_item) : ?> <?php $image = <API key>( <API key>( $news_item->ID ), 'codeus_post_list' ); ?> <div class="news_item lazy-loading-item clearfix" data-ll-effect="fading"> <div class="left-col"> <a href="<?php echo get_permalink($news_item->ID); ?>" class="image"> <?php if ($image[0]): ?> <img src="<?php echo $image[0]; ?>" alt="" /> <?php else: ?> <span class="empty"></span> <?php endif; ?> </a> <span class="date"><?php echo apply_filters('get_the_date', mysql2date('d M Y', $news_item->post_date), 'd M Y'); ?></span> </div> <div class="news-content"> <div class="title"><a href="<?php echo get_permalink($news_item->ID); ?>"><?php echo apply_filters('the_title', $news_item->post_title); ?></a></div> <div class="text"><?php echo apply_filters('the_excerpt', $news_item->post_excerpt); ?></div> </div> </div> <?php endforeach; ?> <div class="all-news lazy-loading-item" data-ll-effect="fading"><a href="<?php echo isset($params->news_link) ? $params->news_link : '#'; ?>"><?php _e('Read all news', 'codeus'); ?></a></div> </div> </div> <?php if($block_class == 'center') : ?> <div class="sidebar"> <?php if(isset($params->news_sidebar_header)) : ?> <h3 class="widget-title"><?php echo $params->news_sidebar_header; ?></h3> <?php endif; ?> <?php if(isset($params->news_sidebar_html)) : ?> <div><?php echo apply_filters('widget_text', $params->news_sidebar_html); ?></div> <?php endif; ?> </div> </div><!-- .panel --> <?php endif; ?> <?php } // Shortcode function <API key>($news_atts) { extract(shortcode_atts(array( 'items_per_page' => 4, ), $news_atts)); $page = (get_query_var('paged')) ? get_query_var('paged') : 1; $news = get_posts(array('post_type' => 'codeus_news', 'numberposts' => $items_per_page, 'offset' => ($page-1)*$items_per_page, 'suppress_filters' => false)); $pages = ceil(wp_count_posts('codeus_news')->publish/$items_per_page); ob_start(); ?> <?php if(!count($news)) : ?> <div class="empty"><?php _e('No News found', 'codeus'); ?></div> <?php else: ?> <ul class="newslist styled"> <?php foreach($news as $news_item) : ?> <?php $image = <API key>( <API key>( $news_item->ID ), 'codeus_post_list' ); ?> <li> <div class="news-info"> <div class="datetime"> <div class="day"><?php echo apply_filters('get_the_date', mysql2date('d M Y', $news_item->post_date), 'd M Y'); ?></div> <h2 class="time"><?php echo apply_filters('get_the_date', mysql2date('H:i', $news_item->post_date), 'H:i'); ?></h2> </div> <div class="thumbnail"> <a href="<?php echo get_permalink($news_item->ID); ?>"> <?php if ($image[0]): ?> <img src="<?php echo $image[0]; ?>" alt="" /> <?php else: ?> <span class="empty"></span> <?php endif; ?> </a> </div> </div> <div class="text"> <h3><a href="<?php echo get_permalink($news_item->ID); ?>"><?php echo apply_filters('the_title', $news_item->post_title); ?></a></h3> <?php echo apply_filters('the_excerpt', $news_item->post_excerpt); ?> </div> </li> <?php endforeach; ?> </ul> <?php codeus_pagination($page, $pages); ?> <?php endif; ?> <?php $news_content = trim(preg_replace('/\s\s+/', '', ob_get_clean())); return $news_content; } ?>
CREATE TABLE hydropower (County text, Crest_Elevation real, Crest_Length real, Latitude real, Longitude real, Name text, Organization text, State text, Structural_Height real, Watercourse text, Year integer); CREATE INDEX State_idx ON hydropower (State); CREATE INDEX Year_idx ON hydropower (Year); INSERT INTO hydropower VALUES ('Jackson', 1520.0, 3800.0, 42.4155, -122.7723, 'Agate Dam', 'Rogue River Basin', 'Oregon', 86.0, 'Dry Creek', 1965); INSERT INTO hydropower VALUES ('Malheur', 3348.0, 1850.0, 43.9117446, -118.154354, 'Agency Valley Dam', 'Vale', 'Oregon', 110.0, 'North Fork of the Malheur River', 1934); INSERT INTO hydropower VALUES ('Natrona', 5510.0, 76300.0, 42.5483, -106.7194, 'Alcova Dam', 'Kendrick', 'Wyoming', 265.0, 'North Platte River', 1935); INSERT INTO hydropower VALUES ('Norton', 2172.5, 2784.18, 39.76667, -100.10041, 'Almena Diversion Dam', 'PSMBP - Almena', 'Kansas', 132.17, 'Prairie Dog Creek', 1967); INSERT INTO hydropower VALUES ('Greer/Kiowa', 1564.0, 1104.0, 34.8833, -99.3, 'Altus Dam', 'W. C. Austin', 'Oklahoma', 110.0, 'North Fork, Red River', 1941); INSERT INTO hydropower VALUES ('Dona Ana, NM; El Paso, Tx', 3684.0, 2784.18, 36.2780790199, -97.501892793, 'American Diversion Dam', 'Rio Grande', 'New Mexico', 18.0, 'Rio Grande', 1938); INSERT INTO hydropower VALUES ('Power', 4366.5, 5277.0, 42.7787, -112.8748, 'American Falls Dam', 'Minidoka', 'Idaho', 104.0, 'Snake River', 1925); INSERT INTO hydropower VALUES ('Hot Springs', 6452.5, 660.0, 43.6833, -108.8167, 'Anchor Dam', 'Owl Creek', 'Wyoming', 208.0, 'South Fork, Owl Creek', 1957); INSERT INTO hydropower VALUES ('Elmore', 4206.0, 1350.0, 43.3595096, -115.4501724, 'Anderson Ranch Dam', 'Boise', 'Idaho', 456.0, 'South Fork of the Boise River', 1941); INSERT INTO hydropower VALUES ('Klamath', 4064.0, 324.0, 42.0098746, -121.5811049, 'Anderson-Rose Diversion Dam', 'Klamath', 'Oregon', 23.0, 'Lost River', 1921); INSERT INTO hydropower VALUES ('Fall River', 3199.0, 2030.0, 43.3431, -103.4378, 'Angostura Dam', 'PSMBP - Angostura', 'South Dakota', 193.0, 'Cheyenne River', 1946); INSERT INTO hydropower VALUES ('Sandoval', 5083.0, 800.0, 36.2780790199, -97.501892793, 'Angostura Diversion Dam', 'Middle Rio Grande', 'New Mexico', 17.0, 'Unknown', 1934); INSERT INTO hydropower VALUES ('Yellowstone', 3010.0, 1050.0, 45.9334311513, -108.00075531, 'Anita Dam', 'Huntley', 'Montana', 42.0, 'Yellowstone River (offstream)', 1933); INSERT INTO hydropower VALUES ('Murray', 920.0, 1890.0, 34.431389, -97.027778, 'Arbuckle Dam', 'Arbuckle', 'Oklahoma', 150.0, 'Rock creek', 1964); INSERT INTO hydropower VALUES ('Boise/Elmore', 3216.0, 1150.0, 43.5952, -115.923, 'Arrowrock Dam', 'Boise', 'Idaho', 350.0, 'Boise River', 1911); INSERT INTO hydropower VALUES ('Crook', 3270.0, 800.0, 44.11125, -120.78738, 'Arthur R Bowman Dam', 'Crooked River', 'Oregon', 240.0, 'Crooked River', 1958); INSERT INTO hydropower VALUES ('Weber', 4235.0, 76665.0, 41.4055270841, -112.090930939, 'Arthur V Watkins Dam', 'Weber Basin', 'Utah', 36.0, 'offstream Storage', 1957); INSERT INTO hydropower VALUES ('Eddy', 3194.0, 1025.0, 32.4908, -104.2553, 'Avalon Dam', 'Carlsbad', 'New Mexico', 60.0, 'Pecos River', 1907); INSERT INTO hydropower VALUES ('Merced', 554.0, 18600.0, 37.0583, -121.075, 'B F Sisk Dam', 'Central Valley', 'California', 382.0, 'San Luis Creek', 1963); INSERT INTO hydropower VALUES ('Beaverhead', 5255.0, 1720.0, 45.1302, -112.7403, 'Barretts Diversion Dam', 'East Bench Unit, Pick-Sloan Missouri Basin Program', 'Montana', 11.0, 'Beaverhead River', 1963); INSERT INTO hydropower VALUES ('Maricopa', 1821.0, 823.0, 33.81825, -111.631856, 'Bartlett Dam', 'Salt River', 'Arizona', 308.5, 'Verde River', 1936); INSERT INTO hydropower VALUES ('Unknown', 4141.1, 2784.18, 40.22509, -100.38695, 'Bartley Diversion Dam', 'PSMBP - Frenchman', 'Nebraska', 27.0, 'Republican River', 1954); INSERT INTO hydropower VALUES ('Butte', 4141.1, 2784.18, 44.7367, -103.67, 'Belle Fourche Dam', 'Belle Fourche', 'South Dakota', 132.17, 'Belle Fourch River', 0); INSERT INTO hydropower VALUES ('Butte', 2998.0, 2523.0, 44.69057, -103.83068, 'Belle Fourche Diversion Dam', 'Belle Fourche', 'South Dakota', 36.0, 'Belle Fourch River', 1907); INSERT INTO hydropower VALUES ('Sweetwater', 6769.0, 2350.0, 42.2492329071, -109.428634644, 'Big Sandy Dam', 'Eden', 'Wyoming', 85.0, 'Big Sandy Creek', 1941); INSERT INTO hydropower VALUES ('Gem', 2500.0, 2784.18, 43.9314, -116.43756, 'Black Canyon Diversion Dam', 'Boise', 'Idaho', 183.0, 'Payette River', 1922); INSERT INTO hydropower VALUES ('Gunnison', 7528.0, 785.0, 38.4533, -107.3333, 'Blue Mesa Dam', 'Colorado River Storage', 'Colorado', 502.0, 'Gunnison', 1962); INSERT INTO hydropower VALUES ('Nevada', 5615.0, 1629.0, 36.2780790199, -97.501892793, 'Boca Dam', 'Truckee Storage', 'California', 93.0, 'Little Truckee River', 1937); INSERT INTO hydropower VALUES ('Ada', 2829.84, 500.0, 43.5383, -116.0933, 'Boise River Diversion Dam', 'Boise', 'Idaho', 68.0, 'Boise River', 1906); INSERT INTO hydropower VALUES ('Yuma', 3742.0, 9200.0, 39.6233, -102.1733, 'Bonny Dam', 'PSMBP - Armel Unit', 'Colorado', 158.0, 'SF Republican R.', 1948); INSERT INTO hydropower VALUES ('Daws', 4024.0, 5508.0, 42.4583, -103.0847, 'Box Butte Dam', 'Mirage Flats', 'Nebraska', 87.0, 'Niobrara River', 1941); INSERT INTO hydropower VALUES ('Fremont', 4758.0, 1143.0, 43.2456, -108.104, 'Boysen Dam', 'Boysen Unit, Pick-Sloan Missouri River Basin Program', 'Wyoming', 220.0, 'Wind River', 1947); INSERT INTO hydropower VALUES ('Santa Barbara', 766.0, 2784.18, 34.5833, -119.9833, 'Bradbury Dam', 'Cachuma', 'California', 279.0, 'Santa Ynex River', 1950); INSERT INTO hydropower VALUES ('Eddy', 3308.5, 20850.0, 32.5968662147, -104.349517822, 'Brantley Dam', 'Brantley', 'New Mexico', 158.5, 'Pecos River', 1984); INSERT INTO hydropower VALUES ('Kiowa', 4141.1, 2784.18, 34.93663, -99.1097, 'Bretch Diversion Dam', 'Mountain Park', 'Oklahoma', 132.17, 'Elk Creek', 1975); INSERT INTO hydropower VALUES ('Summit', 8198.0, 28.0, 36.2780790199, -97.501892793, 'Broadhead Diversion Dam', 'Provo River', 'Utah', 8.0, 'Boadhead Creek', 1953); INSERT INTO hydropower VALUES ('Trinity', 2815.0, 700.0, 36.2780790199, -97.501892793, 'Buckhorn Dam', 'Central Valley', 'California', 90.0, 'Grass Valley Creek', 1988); INSERT INTO hydropower VALUES ('Park', 5395.0, 200.0, 44.3002, -109.11, 'Buffalo Bill Dam', 'Shoshone', 'Wyoming', 350.0, 'Shoshone River', 1905); INSERT INTO hydropower VALUES ('Fremont', 5813.0, 3456.0, 43.2097, -109.0583, 'Bull Lake Dam', 'PSMBP - Riverton Unit', 'Wyoming', 68.0, 'Bull Lake Creek', 1936); INSERT INTO hydropower VALUES ('Malheur', 2529.0, 3070.0, 44.0147313, -117.396898, 'Bully Creek Dam', 'Vale', 'Oregon', 121.0, 'Bully Creek', 1962); INSERT INTO hydropower VALUES ('Yakima', 3435.0, 3425.0, 46.8712, -121.29936, 'Bumping Lake Dam', 'Yakima', 'Washington', 61.0, 'Bumping River', 1909); INSERT INTO hydropower VALUES ('Coconino', 6720.0, 492.0, 34.5550265, -111.1840252, 'C.C. Cragin', 'Salt River', 'Arizona', 187.0, 'East Clear Creek', 1964); INSERT INTO hydropower VALUES ('Sierra', 4190.0, 4590.0, 32.8964, -107.2917, 'Caballo Dam', 'Rio Grande', 'New Mexico', 96.0, 'Rio Grande', 1936); INSERT INTO hydropower VALUES ('Unknown', 4141.1, 2784.18, 40.28511, -100.12054, 'Cambridge Diversion Dam', 'PSMBP - Frenchman', 'Nebraska', 132.17, 'Republican River', 1949); INSERT INTO hydropower VALUES ('El Dorado', 3558.0, 119.0, 36.2780790199, -97.501892793, 'Camp Creek Diversion Dam', 'CVP - Sly Park', 'California', 20.0, 'Camp Creek', 1953); INSERT INTO hydropower VALUES ('Maricopa', 1445.0, 872.0, 33.8378, -112.2705, 'Camp Dyer Diversion Dam', 'Central Arizona', 'Arizona', 79.0, 'Agua Fria River', 1926); INSERT INTO hydropower VALUES ('Lewis and Clark', 3808.5, 1000.0, 46.6479710152, -111.727867126, 'Canyon Ferry Dam', 'Canyon Ferry Unit, Pick-Sloan Missouri Basin Program', 'Montana', 225.0, 'Missouri River', 1949); INSERT INTO hydropower VALUES ('Santa Brbara', 385.25, 2784.18, 34.4067, -119.485, 'Carpinteria Dam', 'Cachuma', 'California', 31.0, 'offstream Storage', 1951); INSERT INTO hydropower VALUES ('Churchill', 4024.0, 241.0, 36.2780790199, -97.501892793, 'Carson River Diversion Dam', 'Newlands', 'Nevada', 23.0, 'Carson River', 1905); INSERT INTO hydropower VALUES ('Eagle', 10133.75, 46.0, 39.21593, -106.32372, 'Carter Creek Diversion Dam', 'Fryingpan-Arkansas', 'Colorado', 8.75, 'Carter Creek', 1976); INSERT INTO hydropower VALUES ('Grand', 5769.0, 1235.0, 40.325, -105.2117, 'Carter Lake Dam', 'Colorado-Big Thompson', 'Colorado', 214.0, 'offstream Storage', 1950); INSERT INTO hydropower VALUES ('Valley', 4840.0, 785.0, 44.524997, -116.050279, 'Cascade Dam', 'Boise', 'Idaho', 107.0, 'North Fork Payette River', 1946); INSERT INTO hydropower VALUES ('Ventura', 585.0, 2000.0, 34.37, -119.3361, 'Casitas Dam', 'Ventura River', 'California', 334.0, 'Coyote Creek', 1956); INSERT INTO hydropower VALUES ('Weber', 5704.0, 845.0, 41.2901899559, -111.582984924, 'Causey Dam', 'Weber Basin', 'Utah', 217.5, 'SF Ogden River', 1962); INSERT INTO hydropower VALUES ('Trego', 2198.0, 12560.0, 38.7917, -99.725, 'Cedar Bluff Dam', 'PSMBP-Cedar Bluff', 'Kansas', 202.0, 'Smoky Hill River', 1949); INSERT INTO hydropower VALUES ('Pitkin', 10045.0, 131.0, 39.3163756, -106.640589, 'Chapman Diversion Dam', 'Fryingpan-Arkansas', 'Colorado', 15.0, 'Chapman Gulch', 1965); INSERT INTO hydropower VALUES ('Reno, Kingman, Sedgwick', 1454.0, 24458.0, 37.7306, -97.793, 'Cheney Dam', 'Wichita', 'Kansas', 126.2, 'NF of Ninnescah R.', 1962); INSERT INTO hydropower VALUES ('Live Oak', 241.14, 18471.0, 28.3125, -98.2458, 'Choke Canyon Dam', 'Nueces River', 'Texas', 141.96, 'Frio River', 1981); INSERT INTO hydropower VALUES ('Beaverhead', 5578.0, 2950.0, 45.0004154063, -112.858343124, 'Clark Canyon Dam', 'East Bench Unit, Pick-Sloan Missouri Basin Program', 'Montana', 147.5, 'Beaverhead River', 1961); INSERT INTO hydropower VALUES ('Kittitas', 2250.0, 1800.0, 47.2469, -121.073112, 'Cle Elum Dam', 'Yakima', 'Washington', 165.0, 'Cle Elum River', 1931); INSERT INTO hydropower VALUES ('Yakima', 3016.0, 404.0, 46.6278934, -121.270915, 'Clear Creek Dam', 'Yakima', 'Washington', 83.0, 'Tieton River', 1914); INSERT INTO hydropower VALUES ('Modoc', 4552.0, 840.0, 45.1767, -121.6883, 'Clear Lake Dam', 'Klamath', 'California', 42.0, 'Lost River', 1908); INSERT INTO hydropower VALUES ('Umatilla', 629.9, 3450.0, 45.8592328, -119.173679, 'Cold Springs Dam', 'Umatilla Basin', 'Oregon', 115.0, 'Off-stream', 1908); INSERT INTO hydropower VALUES ('Ravalli', 4249.0, 2550.0, 46.0617, -114.2333, 'Como Dam', 'Bitter Root', 'Montana', 85.0, 'Rock Creek', 1908); INSERT INTO hydropower VALUES ('Okanogan', 2301.0, 1075.0, 48.5370932, -119.7486774, 'Conconully Dam', 'Okanogan', 'Washington', 72.0, 'Salmon Creek', 1910); INSERT INTO hydropower VALUES ('Contra Costa', 217.0, 1050.0, 37.9772, -121.8231, 'Contra Loma Dam', 'Central Valey', 'California', 107.0, 'offstream storage', 1966); INSERT INTO hydropower VALUES ('Park', 46255.0, 938.0, 44.58953, -108.95428, 'Corbett Diversion Dam', 'Shoshone', 'Wyoming', 18.0, 'Shoshone River', 1908); INSERT INTO hydropower VALUES ('Deschutes', 4455.0, 285.0, 43.755, -121.785, 'Crane Prairie Dam', 'Deschutes', 'Oregon', 36.0, 'Deschutes River', 1939); INSERT INTO hydropower VALUES ('Delta', 6578.0, 580.0, 38.6907354482, -107.608165741, 'Crawford Dam', 'Smith Fork', 'Colorado', 162.0, 'Iron Creek', 1960); INSERT INTO hydropower VALUES ('Montrose', 6772.0, 620.0, 38.4535887089, -107.33505249, 'Crystal Dam', 'Colorado River Storage', 'Colorado', 323.0, 'Gunnison River', 1972); INSERT INTO hydropower VALUES ('Hayes', 2744.0, 150.0, 40.36186, -101.10267, 'Culbertson Diversion Dam', '<API key>', 'Nebraska', 17.0, 'Frenchman', 1959); INSERT INTO hydropower VALUES ('Wasatch', 7692.0, 1600.0, 40.3321512355, -111.051864624, 'Currant Creek Dam', 'CUP - Bonneville Unit', 'Utah', 164.0, 'Currant Creek', 1974); INSERT INTO hydropower VALUES ('Sherman', 2094.0, 2900.0, 41.41568, -98.74793, 'Davis Creek Dam', 'PSMBP-North Loup', 'Nebraska', 153.0, 'Tributary to Davis Creek', 19); INSERT INTO hydropower VALUES ('Mohave (AZ), Clark (NV)', 655.0, 1600.0, 35.1967, -114.5683, 'Davis Dam', 'Parker-Davis', 'Arizona and Nevada', 200.0, 'Colorado River', 1942); INSERT INTO hydropower VALUES ('Valley', 5340.0, 749.0, 44.2932322, -115.6459458, 'Deadwood Dam', 'Boise', 'Idaho', 165.0, 'Deadwood River', 1929); INSERT INTO hydropower VALUES ('Park', 4309.0, 13000.0, 44.901, -108.63707, 'Deaver Dam', 'Shoshone', 'Wyoming', 14.0, 'Offstream', 1918); INSERT INTO hydropower VALUES ('Wasatch', 5425.0, 1304.0, 40.406667, -111.527, 'Deer Creek Dam', 'Provo River', 'Utah', 235.0, 'Provo River', 1938); INSERT INTO hydropower VALUES ('Valley', 2536.0, 3806.0, 43.515568, -116.589317, 'Deer Flat East Dike Dam', 'Boise', 'Idaho', 132.17, 'Offstream Storage', 1906); INSERT INTO hydropower VALUES ('Canyon', 2539.0, 7270.0, 43.58247, -116.73703, 'Deer Flat Lower Embankment', 'Boise', 'Idaho', 49.0, 'Offstream Storage', 1906); INSERT INTO hydropower VALUES ('Canyon', 2536.0, 750.0, 43.595746, -116.7178916, 'Deer Flat Middle Embankment', 'Boise', 'Idaho', 26.0, 'Offstream Storage', 1906); INSERT INTO hydropower VALUES ('Canyon', 2538.4, 4164.0, 43.56007, -116.6543, 'Deer Flat Upper Embankment', 'Boise', 'Idaho', 73.0, 'Offstream Storage', 1906); INSERT INTO hydropower VALUES ('Pennington', 5958.0, 1125.0, 44.03, -103.7867, 'Deerfield Dam', 'Rapid Valley', 'South Dakota', 171.0, 'Castle Creek', 1942); INSERT INTO hydropower VALUES ('Storey, Washoe', 4219.16, 1331.0, 36.2780790199, -97.501892793, 'Derby Diversion Dam', 'Newlands', 'Nevada', 31.0, 'Truckee Rier', 1905); INSERT INTO hydropower VALUES ('Stark', 2436.6, 2275.0, 46.8697, -102.8269, 'Dickinson Dam', 'PSMBP-Dickinson', 'North Dakota', 62.0, 'Heart River', 1950); INSERT INTO hydropower VALUES ('Larimer', 5500.0, 90.0, 40.4041, -105.14096, 'Dille Diversion Dam', 'Colorado-Big Thompson', 'Colorado', 35.0, 'Big Thompson River', 1950); INSERT INTO hydropower VALUES ('Larimer', 5443.0, 1840.0, 40.5533, -105.14, 'Dixon Canyon Dam', 'Colorado-Big Thompson', 'Colorado', 155.0, 'Offstream Storage', 1946); INSERT INTO hydropower VALUES ('Phillips', 2280.0, 8154.0, 48.4121, -108.3077, 'Dodson Diversion Dam', 'Milk River', 'Montana', 26.0, 'Milk River', 1910); INSERT INTO hydropower VALUES ('Unknown', 4141.1, 2784.18, 36.2780790199, -97.501892793, 'Dressler Diversion Dam', 'Washoe', 'Nevada', 132.17, 'Unknown', 0); INSERT INTO hydropower VALUES ('Delta', 5619.5, 36.0, 36.2780790199, -97.501892793, 'Dry Creek Diversion Dam', 'Fruitgrowers', 'Colorado', 13.0, 'Dry Creek', 1940); INSERT INTO hydropower VALUES ('Grant', 1580.0, 9800.0, 47.622595, -119.31787, 'Dry Falls Dam', 'Columbia Basin', 'Washington', 123.0, 'Offstream Storage', 1946); INSERT INTO hydropower VALUES ('Scotts Bluff', 3996.0, 255.0, 41.93825, -103.92492, 'Dry Spotted Tail Diversion Dam', 'North Platte', 'Nebraska', 14.5, 'Dry Spotted Tail Creek', 1954); INSERT INTO hydropower VALUES ('Dawes', 3873.3, 2784.18, 42.46225, -102.92388, 'Dunlap Diversion Dam', 'Mirage Flats', 'Nebraska', 12.6, 'Niobrara', 1945); INSERT INTO hydropower VALUES ('Morgan', 5715.0, 436.0, 40.920533533, -111.600859165, 'East Canyon Dam', 'Weber Basin', 'Utah', 259.8, 'East Canyon Creek', 1964); INSERT INTO hydropower VALUES ('Colusa', 1198.68, 266.0, 39.3567, -122.515, 'East Park Dam', 'Orland', 'California', 139.0, 'Little Stony Creek', 1908); INSERT INTO hydropower VALUES ('Larimer', 8265.0, 245.0, 40.32788, -105.57857, 'East Portal Diversion Dam', 'Colorado-Big Thompson', 'Colorado', 76.0, 'Wind River', 1947); INSERT INTO hydropower VALUES ('Kittitas', 2184.5, 248.0, 47.24154, -121.1880397, 'Easton Diversion Dam', 'Yakima', 'Washington', 66.0, 'Yakima River', 1928); INSERT INTO hydropower VALUES ('Unknown', 5570.0, 1887.0, 40.9648634537, -111.431965828, 'Echo Dam', 'Weber Basin', 'Utah', 158.0, 'Weber Basin', 1927); INSERT INTO hydropower VALUES ('Sweetwater', 6720.0, 3500.0, 42.2181252478, -109.36653614, 'Eden Dam', 'Eden', 'Wyoming', 27.0, 'OS Little Sandy Creek', 1910); INSERT INTO hydropower VALUES ('Unknown', 6914.5, 1326.0, 36.5940301739, -106.732521057, 'El Vado Dam', 'Middle Rio Grande', 'New Mexico', 229.5, 'Rio chama', 1933); INSERT INTO hydropower VALUES ('Sierra', 4414.0, 1674.0, 33.1534871924, -107.191178799, 'Elephant Butte Dam', 'Rio Grande', 'New Mexico', 301.0, 'Rio Grande', 1912); INSERT INTO hydropower VALUES ('Jackson', 2254.0, 4750.0, 42.16206, -122.605233, 'Emigrant Dam', 'Rogue River Basin', 'Oregon', 204.0, 'Emigrant Creek', 1924); INSERT INTO hydropower VALUES ('Chase', 3137.5, 2603.0, 40.4208, -101.5175, 'Enders Dam', '<API key>', 'Nebraska', 134.0, 'Frenchman River', 1947); INSERT INTO hydropower VALUES ('Jackson', 4649.0, 960.0, 42.3781, -122.348, 'Fish Lake Dam', 'Rogue River Basin', 'Oregon', 50.0, 'North Fork Little Butte Creek', 1902); INSERT INTO hydropower VALUES ('Daggett', 6047.0, 1285.0, 40.9149922278, -109.421934485, 'Flaming Gorge Dam', 'Colorado River Storage', 'Utah', 502.0, 'Green River', 1958); INSERT INTO hydropower VALUES ('Larimer', 5486.0, 1725.0, 40.3683, -105.2233, 'Flatiron Afterbay Dam', 'Colorado-Big Thompson', 'Colorado', 86.0, 'Chimney Hollow Creek', 1951); INSERT INTO hydropower VALUES ('Sacramento', 480.5, 1400.0, 38.7083, -121.1528, 'Folsom Dam', 'CVP-Auburn-Folsom', 'California', 340.0, 'American River', 1948); INSERT INTO hydropower VALUES ('Lincoln. Sweetwater', 6519.0, 5421.0, 42.0283, -110.0606, 'Fontenelle Dam', 'Seedskadee', 'Wyoming', 139.0, 'Green River', 1961); INSERT INTO hydropower VALUES ('Caddo', 1380.0, 9900.0, 35.1667, -98.45, 'Fort Cobb Dam', 'Washita Basin', 'Oklahoma', 122.0, 'Cobb Creek', 1958); INSERT INTO hydropower VALUES ('Caddo', 1697.0, 18130.0, 35.55, -99.1833, 'Foss Dam', 'Washita basin', 'Oklahoma', 142.0, 'Washita River', 1958); INSERT INTO hydropower VALUES ('Yakima', 2170.0, 1150.0, 46.7114132, -120.7922959, 'French Canyon Dam', 'Yakima', 'Washington', 74.0, 'Cowiche Creek', 1983); INSERT INTO hydropower VALUES ('County Hill', 2596.1, 2070.0, 48.6019, -109.9456, 'Fresno Dam', 'Milk River', 'Montana', 110.0, 'Milk River', 1937); INSERT INTO hydropower VALUES ('Fresno', 581.25, 3488.0, 36.2780790199, -97.501892793, 'Friant Dam', 'CVP-Friant', 'California', 319.0, 'San Joaquin River', 1939); INSERT INTO hydropower VALUES ('Delta', 5493.0, 1520.0, 38.8266699234, -107.9545784, 'Fruitgrowers Dam', 'Fruitgrowers', 'Colorado', 55.0, 'Alfalfa Run', 1938); INSERT INTO hydropower VALUES ('Pitkin', 9961.9, 25.0, 39.14447, -106.3146, 'Fryingpan Diversion Dam', 'Fryingpan-Arkansas', 'Colorado', 9.0, 'Fryingpan River', 1965); INSERT INTO hydropower VALUES ('Colusa', 4141.1, 1460.0, 36.2780790199, -97.501892793, 'Funks Dam', 'CVP-Sacramento Canals', 'California', 80.0, 'Funks Creek', 19); INSERT INTO hydropower VALUES ('Delta', 5170.0, 75.0, 36.2780790199, -97.501892793, 'Garnet Diversion Dam', 'Uncompahgre', 'Colorado', 8.0, 'Uncompahgre River', 0); INSERT INTO hydropower VALUES ('Klamath', 4841.9, 485.0, 42.2017, -121.1283, 'Gerber Dam', 'Klamath', 'Oregon', 88.0, 'Miller Crek', 1924); INSERT INTO hydropower VALUES ('Teton, Lewis and Clark', 4725.5, 960.0, 47.6013, -112.7614, 'Gibson Dam', 'Sun River', 'Montana', 199.0, 'North Fork of Sun River', 1926); INSERT INTO hydropower VALUES ('Santa Barbara', 402.0, 2784.18, 34.4708, -119.9125, 'Glen Anne Dam', 'Cachuma', 'California', 135.0, 'WE of Glen Anne Canyon', 1950); INSERT INTO hydropower VALUES ('Coconino', 3715.0, 1560.0, 36.9375441211, -111.483764648, 'Glen Canyon Dam', 'Colorado River Storage', 'Arizona', 710.0, 'Colorado River Storage', 1956); INSERT INTO hydropower VALUES ('Mitchell', 1500.0, 15275.0, 39.4967, -98.3133, 'Glen Elder Dam', 'PSMBP - Glen Elder', 'Kansas', 142.0, 'Solomon River', 1963); INSERT INTO hydropower VALUES ('Casso', 4675.0, 2784.18, 42.4833, -104.9833, 'Glendo Dam', 'PSMBP-Glendo Unit', 'Wyoming', 190.0, 'North Platte River', 1955); INSERT INTO hydropower VALUES ('Grand', 8290.0, 861.0, 40.165, -105.8633, 'Granby Dam', 'Colorado-Big Thompson', 'Colorado', 298.0, 'Colorado River', 1941); INSERT INTO hydropower VALUES ('Grant, Okanogan', 1311.1, 5223.0, 47.955, -118.9833, 'Grand Coulee Dam', 'Columbia Basin', 'Washington', 550.0, 'Columbia River', 1933); INSERT INTO hydropower VALUES ('Unknown', 4141.1, 2784.18, 39.15397, -106.33482, 'Granite Creek Diversion Dam', 'Fryingpan-Arkansas', 'Colorado', 132.17, 'Unknown', 0); INSERT INTO hydropower VALUES ('Maricopa', 1310.0, 1128.0, 33.513233, -111.69228, 'Granite Reef Diversion Dam', 'Salt River', 'Arizona', 29.0, 'Salt River', 1906); INSERT INTO hydropower VALUES ('Teton', 7218.0, 1170.0, 44.13, -110.8183, 'Grassy Lake Dam', 'Minidoka', 'Wyoming', 118.0, 'Grassy Creek', 1937); INSERT INTO hydropower VALUES ('Natrona', 5338.0, 650.0, 42.56529, -106.7017, 'Gray Reef Dam', 'PSMBP-Glendo Unit', 'Wyoming', 36.0, 'North Platte River', 1959); INSERT INTO hydropower VALUES ('Summit', 7960.0, 1150.0, 39.8783, -106.33, 'Green Mountain Dam', 'Colorado-Big Thompson', 'Colorado', 309.0, 'Blue River', 1938); INSERT INTO hydropower VALUES ('Platte', 4430.0, 560.0, 42.2903, -104.7631, 'Guernsey Dam', 'North Platte', 'Wyoming', 135.0, 'North Platte River', 1925); INSERT INTO hydropower VALUES ('Lake', 9715.5, 50.0, 39.18573, -106.38352, 'Halfmoon Diversion Dam', 'Fryingpan-Arkansas', 'Colorado', 15.0, 'Halfmoon Creek', 1977); INSERT INTO hydropower VALUES ('Washakie', 4190.75, 250.0, 43.95874, -108.00087, 'Hanover Diversion Dam', 'PSMBP-Hanover-Bluff', 'Wyoming', 8.25, 'Bighorn river', 1910); INSERT INTO hydropower VALUES ('Cook, Deschutes, Jefferson', 2853.0, 1200.0, 44.4991378, -121.15525, 'Haystack Dam', 'Deschutes', 'Oregon', 105.0, 'Off stream - unnamed internittent creek', 1956); INSERT INTO hydropower VALUES ('Grant', 2124.0, 1850.0, 46.5967, -101.8167, 'Heart Butte Dam', 'PSMBP-Heart Butte', 'North Dakota', 142.0, 'Heart River', 1948); INSERT INTO hydropower VALUES ('Lewis and Clark', 3828.0, 2650.0, 46.64182, -111.883233, 'Helena Valley Dam', 'Helena Valley Unit, Pick-Sloan Missouri Basin Program', 'Montana', 94.0, 'Tenmile Creek Tributary', 1957); INSERT INTO hydropower VALUES ('Rio Arriba', 7199.0, 1220.0, 36.6657339086, -106.70548439, 'Heron Dam', 'San Juan-Chama', 'New Mexico', 269.0, 'Willow Creek', 1967); INSERT INTO hydropower VALUES ('Clark (NV), Mohave (AZ)', 1232.0, 1244.0, 36.0163, -114.7372, 'Hoover Dam', 'Boulder Canyon', 'Nevada and Arizona', 726.4, 'Colorado River', 1931); INSERT INTO hydropower VALUES ('Goshen', 4122.0, 720.0, 41.98356, -104.060008, 'Horse Creek Diversion Dam', 'North Platte', 'Wyoming', 17.0, 'Horse Creek', 1923); INSERT INTO hydropower VALUES ('Maricopa', 1915.0, 660.0, 33.5908, -111.3438, 'Horse Mesa Dam', 'Salt River', 'Arizona', 305.0, 'Salt River', 1924); INSERT INTO hydropower VALUES ('Maricopa', 2052.0, 1652.0, 33.9834, -111.708939, 'Horseshoe Dam', 'Salt River', 'Arizona', 202.0, 'Verde River', 1944); INSERT INTO hydropower VALUES ('Larimer', 5443.0, 1840.0, 40.6, -105.1683, 'Horsetooth Dam', 'Colorado-Big Thompson', 'Colorado', 155.0, 'Offstream Storage', 1946); INSERT INTO hydropower VALUES ('Unknown', 4539.0, 1040.0, 42.2168, -122.377, 'Howard Prairie Dam', 'Rogue River Basin', 'Oregon', 100.0, 'Jenny Creek', 1957); INSERT INTO hydropower VALUES ('Ada', 2780.0, 2784.18, 43.5123, -116.3594, 'Hubbard Dam', 'Boise', 'Idaho', 23.0, 'Offstream Storage', 1902); INSERT INTO hydropower VALUES ('Flathead', 3548.0, 2115.0, 48.3413, -114.013023376, 'Hungry Horse Dam', 'Hungry Horse', 'Montana', 564.0, 'South Fork of Flathead River', 1948); INSERT INTO hydropower VALUES ('Pitkin', 10179.0, 60.0, 39.1226, -106.4046, 'Hunter Creek Diversion Dam', 'Fryingpan-Arkansas', 'Colorado', 52.0, 'Hunter Creek', 1976); INSERT INTO hydropower VALUES ('Emery', 5845.0, 2897.0, 39.341732343, -110.947494507, 'Huntington North Dam', 'Emery County', 'Utah', 85.0, 'Huntington Creek', 1964); INSERT INTO hydropower VALUES ('Unknown', 5025.0, 775.0, 42.171737, -122.46829, 'Hyatt Dam', 'Rogue River Basin', 'Oregon', 53.0, 'Keene Creek', 1922); INSERT INTO hydropower VALUES ('Cache', 4680.0, 540.0, 41.6266307649, -111.871708632, 'Hyrum Dam', 'Hyrum', 'Utah', 116.0, 'Little Bear Water', 1934); INSERT INTO hydropower VALUES ('Imperial, CA; Yuma, AZ', 196.25, 3475.0, 32.8831, -114.4669, 'Imperial Diversion Dam', 'Boulder Canyon', 'California and Arizona', 85.0, 'Colorado River', 1936); INSERT INTO hydropower VALUES ('Imperial, CA; Yuma, AZ', 196.25, 3475.0, 32.8831, -114.4669, 'Imperial Diversion Dam', 'Boulder Canyon', 'California and Arizona', 85.0, 'Colorado River', 1936); INSERT INTO hydropower VALUES ('Imperial, CA; Yuma, AZ', 196.25, 3475.0, 32.8831, -114.4669, 'Imperial Diversion Dam', 'Boulder Canyon', 'California and Arizona', 85.0, 'Colorado River', 1936); INSERT INTO hydropower VALUES ('Fremont', 6312.0, 9500.0, 44.4188389, -111.396324, 'Island Park Dam', 'Minidoka', 'Idaho', 94.0, 'Henrys Fork', 1937); INSERT INTO hydropower VALUES ('Bernalillo', 4886.6, 674.0, 36.2780790199, -97.501892793, 'Isleta Diversion Dam', 'Middle Rio Grande', 'New Mexico', 21.0, 'Rio Grande', 1934); INSERT INTO hydropower VALUES ('Pitkin', 10015.25, 83.0, 39.17139, -106.33309, 'Ivanhoe Diversion Dam', 'Fryingpan-Arkansas', 'Colorado', 19.75, 'Ivanhoe Creek', 1973); INSERT INTO hydropower VALUES ('Montezuma', 7831.0, 1900.0, 37.3984599462, -108.274083138, 'Jackson Gulch Dam', 'Mancos', 'Colorado', 180.0, 'Offstream', 1942); INSERT INTO hydropower VALUES ('Teton', 6774.5, 4920.0, 43.8574396, -110.5899305, 'Jackson Lake Dam', 'Minidoka', 'Wyoming', 65.5, 'Snake River', 1912); INSERT INTO hydropower VALUES ('Beadle', 4141.1, 2784.18, 44.59737, -98.23891, 'James Diversion Dam', 'PSMBP-James Diversion Dam', 'South Dakota', 132.17, 'James River', 1963); INSERT INTO hydropower VALUES ('Stutsman', 1471.0, 1418.0, 46.9333, -98.71, 'Jamestown Dam', 'PSMBP-Jamestown', 'North Dakota', 110.0, 'James River', 1952); INSERT INTO hydropower VALUES ('Emery', 7004.0, 750.0, 39.288475614, -111.269359589, 'Joes Valley Dam', 'Emery County', 'Utah', 192.0, 'Seely Creek', 1963); INSERT INTO hydropower VALUES ('Madera', 4141.1, 263.0, 36.2780790199, -97.501892793, 'John Franchi Diversion Dam', 'CVP-Friant', 'California', 15.0, 'Fresno River', 1964); INSERT INTO hydropower VALUES ('Wasatch', 6185.0, 3700.0, 40.4072874894, -111.528139114, 'Jordanelle Dam', 'CUP - Bonneville Unit', 'Utah', 345.0, 'Provo', 1987); INSERT INTO hydropower VALUES ('Kittitas', 2268.0, 1400.0, 47.2646, -121.20254, 'Kachess Dam', 'Yakima', 'Washington', 115.0, 'Kachess River', 1910); INSERT INTO hydropower VALUES ('Kittitas', 2525.0, 6550.0, 47.32212, -121.34056, 'Keechelus Dam', 'Yakima', 'Washington', 128.0, 'Yakima River', 1913); INSERT INTO hydropower VALUES ('Jackson', 4412.5, 558.0, 42.129277, -122.478911, 'Keene Creek Dam', 'Rogue River Basin', 'Oregon', 78.0, 'Keene Creek', 1957); INSERT INTO hydropower VALUES ('Loup', 2213.0, 101.0, 41.76136, -99.2678, 'Kent Diversion Dam', 'PSMBP-North Loup', 'Nebraska', 8.0, 'North Loup', 1076); INSERT INTO hydropower VALUES ('Shasta', 595.5, 1046.0, 40.615, -122.4528, 'Keswick Dam', 'CVP-Shasta/Trinity', 'California', 157.0, 'Sacramento river', 1941); INSERT INTO hydropower VALUES ('Crook', 4134.0, 2784.18, 44.3819, -104.7792, 'Keyhole Dam', 'PSMBP-Keyhole', 'Wyoming', 168.0, 'Offstream', 1950); INSERT INTO hydropower VALUES ('Phillips', 1779.0, 960.0, 39.65, -99.1222, 'Kirwin Dam', 'PSMBP-Kirwin', 'Kansas', 169.0, 'NF Solomon Rivr', 1952); INSERT INTO hydropower VALUES ('Carbon', 6169.0, 440.0, 42.17392, -106.881002, 'Kortes Dam', 'PSMBP-Kortes', 'Wyoming', 244.0, 'North Platte River', 1946); INSERT INTO hydropower VALUES ('Yuma, Ariz and Imperial, Calif', 151.0, 4780.0, 32.8233, -114.4972, 'Laguna Diversion Dam', 'Yuma', 'Arizona and California', 43.0, 'Colorado River', 1905); INSERT INTO hydropower VALUES ('Churchill', 4174.0, 1325.0, 36.2780790199, -97.501892793, 'Lahontan Dam', 'Newlands', 'Nevada', 162.0, 'Carson River', 1911); INSERT INTO hydropower VALUES ('Scotts Bluff', 4192.0, 3100.0, 41.9728, -103.6286, 'Lake Alice No 1 Dam', 'North Platte', 'Nebraska', 44.0, 'Interstate Canal', 1910); INSERT INTO hydropower VALUES ('Scotts Bluff', 4192.0, 2550.0, 41.9828, -103.597, 'Lake Alice No 1and 1 Half Dam', 'North Platte', 'Nebraska', 33.0, 'Interstate Canal', 1910); INSERT INTO hydropower VALUES ('Scotts Bluff', 4139.5, 750.0, 41.9623003, -103.57258, 'Lake Alice No 2 Dam', 'North Platte', 'Nebraska', 11.0, 'Lake Alice Feeder Canal', 1908); INSERT INTO hydropower VALUES ('Glacier', 4816.5, 1224.0, 48.8285, -113.5213, 'Lake Sherburne Dam', 'Milk River', 'Montana', 116.5, 'Swiftcurrent Creek', 1914); INSERT INTO hydropower VALUES ('Placer', 6233.2, 109.0, 36.2780790199, -97.501892793, 'Lake Tahoe Dam', 'Newlands', 'California', 18.2, 'Truckee River', 1909); INSERT INTO hydropower VALUES ('Santa Barbara', 567.0, 2784.18, 34.4542, -119.7264, 'Lauro Dam', 'Cachuma', 'California', 137.0, 'Diablo Creek', 1951); INSERT INTO hydropower VALUES ('La Plata', 8167.0, 1360.0, 37.3817097523, -107.660704851, 'Lemon Dam', 'Florida', 'Colorado', 284.0, 'Florida River', 1961); INSERT INTO hydropower VALUES ('Trinity', 1910.0, 745.0, 36.2780790199, -97.501892793, 'Lewiston Dam', 'CVP-Shasta/Trinity', 'California', 91.0, 'Trinity River', 1960); INSERT INTO hydropower VALUES ('Pitkin', 10207.0, 2784.18, 39.15299, -106.32115, 'Lily Pad Diversion Inlet Dam', 'Fryingpan-Arkansas', 'Colorado', 132.17, 'Ivanhoe Cr (Nast Tunnel)', 1970); INSERT INTO hydropower VALUES ('Unknown', 4145.0, 435.0, 36.2780790199, -97.501892793, 'Link River Diversion Dam', 'Unknown', 'Unknown', 22.0, 'Unknown', 0); INSERT INTO hydropower VALUES ('Larimer', 6640.0, 220.0, 40.3636, -105.32461, 'Little Hell Creek Diversion Dam', 'Colorado-Big thompson', 'Colorado', 43.0, 'Little Hell Creek', 1952); INSERT INTO hydropower VALUES ('Unknown', 676.0, 2784.18, 36.2780790199, -97.501892793, 'Little Panoche Detention Dam', 'Unknown', 'Unknown', 151.0, 'Little Panoche Creek', 0); INSERT INTO hydropower VALUES ('Blaine', 5249.0, 3100.0, 43.4249051, -114.0292001, 'Little Wood River Dam', 'Little Wood River', 'Idaho', 129.0, 'Little Wood River', 1936); INSERT INTO hydropower VALUES ('Merced', 384.0, 1370.0, 36.99, -120.0317, 'Los Banos Creek Detention Dam', 'Central Valley', 'California', 167.0, 'Los Banos Creek', 1964); INSERT INTO hydropower VALUES ('Morgan', 6022.0, 1078.0, 41.1841690802, -111.399189234, 'Lost Creek Dam', 'Weber Basin', 'Utah', 248.4, 'Lost Creek', 1963); INSERT INTO hydropower VALUES ('Klamath', 4094.5, 300.0, 36.2780790199, -97.501892793, 'Lost River Diversion Dam', 'Klamath', 'Oregon', 26.0, 'Lost River', 1912); INSERT INTO hydropower VALUES ('Jewell', 1616.0, 8500.0, 39.885, -98.0283, 'Lovewell Dam', 'PSMBP-Bostwick', 'Kansas', 93.0, 'White Rock Creek', 1955); INSERT INTO hydropower VALUES ('Dawson', 1981.0, 700.0, 47.2801, -104.5294, 'Lower Yellowstone Diversion Dam', 'Lower Yellowstone', 'Montana', 12.0, 'Yellowstone', 1910); INSERT INTO hydropower VALUES ('Klamath', 4141.1, 2784.18, 36.2780790199, -97.501892793, 'Malone Diversion Dam', 'Klamath', 'Oregon', 132.17, 'Lost River', 1923); INSERT INTO hydropower VALUES ('Washington', 2903.0, 1176.0, 44.392349, -116.895389, 'Mann Creek Dam', 'Mann Creek', 'Idaho', 148.0, 'Mann Creek', 1965); INSERT INTO hydropower VALUES ('Storey', 3866.0, 1622.0, 36.2780790199, -97.501892793, 'Marble Bluff Dam', 'Washoe', 'Nevada', 35.0, 'Little Truckee R.', 1975); INSERT INTO hydropower VALUES ('Contra Costa', 72.0, 1200.0, 38.0117, -122.11, 'Martinez Dam', 'CVP-Delta', 'California', 62.0, 'Offstream storage', 1946); INSERT INTO hydropower VALUES ('Larimer', 8050.0, 820.0, 40.34397, -105.53351, 'Marys Lake Dike Dam', 'Colorado-Big Thompson', 'Colorado', 29.0, 'Offstream', 0); INSERT INTO hydropower VALUES ('Baker', 4082.0, 895.0, 44.67335287, -118.00003, 'Mason Dam', 'Baker', 'Oregon', 173.0, 'Powder River', 1965); INSERT INTO hydropower VALUES ('Unknown', 613.5, 30.0, 34.3331, -95.9151, 'McGee Creek Dam', 'McGee Creek', 'Oklahoma', 161.0, 'McGee Creek', 1981); INSERT INTO hydropower VALUES ('Umatilla, Morrow', 1330.0, 2700.0, 45.605406, -118.7957668, 'McKay Dam', 'Umatilla Basin', 'Oregon', 165.0, 'McKay Creek', 1923); INSERT INTO hydropower VALUES ('Montezuma', 6936.0, 1370.0, 37.5765124705, -108.572387695, 'McPhee Dam', 'Dolores', 'Colorado', 295.0, 'Dolores', 1983); INSERT INTO hydropower VALUES ('Frontier', 2415.0, 5665.0, 40.3783, -100.2167, 'Medicine Creek Dam', '<API key>', 'Nebraska', 165.0, 'Medicine Creek', 1948); INSERT INTO hydropower VALUES ('Unita', 8706.0, 3162.0, 41.0253288642, -110.579795837, 'Meeks Cabin Dam', 'Lyman', 'Wyoming', 185.0, 'Blacks Fork River', 1966); INSERT INTO hydropower VALUES ('Cherry', 2956.0, 3222.0, 42.63282, -100.86936, 'Merritt Dam', 'PSMBP-Ainsworth', 'Nebraska', 132.17, 'Snake River', 1961); INSERT INTO hydropower VALUES ('Pitkin', 10055.0, 43.0, 39.1945, -106.332, 'Middle Cunningham Creek Diversion Dam', 'Fryingpan-Arkansas', 'Colorado', 10.0, 'Cunningham Creek', 1976); INSERT INTO hydropower VALUES ('Duschene', 5268.0, 663.0, 40.1852832182, -110.164568424, 'Midview Dam', 'Moon Lake', 'Utah', 54.0, 'Offstream', 1935); INSERT INTO hydropower VALUES ('Pitkin', 10190.2, 50.0, 39.1147, -106.4123, 'Midway Creek Diversion Dam', 'Fryingpan-Arkansas', 'Colorado', 12.0, 'Midway Creek', 1976); INSERT INTO hydropower VALUES ('Klamath', 4227.0, 290.0, 36.2780790199, -97.501892793, 'Miller Diversion Dam', 'Klamath', 'Oregon', 10.0, 'Miller Creek', 1924); INSERT INTO hydropower VALUES ('Scotts Bluff', 4140.0, 3760.0, 41.9183, -103.4925, 'Minatare Dam', 'North Platte', 'Nebraska', 114.0, 'Minatare Supply Canal', 1912); INSERT INTO hydropower VALUES ('Minidoka & Cassia', 4250.0, 4475.0, 42.66907, -113.484177, 'Minidoka Dam', 'Minidoka', 'Idaho', 86.0, 'Snake River', 1904); INSERT INTO hydropower VALUES ('Yolo', 456.0, 1023.0, 38.513335, -122.104272, 'Monticello Dam', 'Solano', 'California', 304.0, 'Putah Creek', 1953); INSERT INTO hydropower VALUES ('Duchesne', 8145.0, 1108.0, 40.5605929553, -110.488986969, 'Moon Lake Dam', 'Moon Lake', 'Utah', 101.0, 'Lake Fork River', 1935); INSERT INTO hydropower VALUES ('Pitkin', 10098.0, 41.0, 39.21193, -106.3269, 'Mormon Creek Diversion Dam', 'Fryingpan-Arkansas', 'Colorado', 10.0, 'Mormon Creek', 1976); INSERT INTO hydropower VALUES ('Maricopa', 1666.0, 380.0, 33.5534, -111.443, 'Mormon Flat Dam', 'Salt River', 'Arizona', 224.0, 'Salt River', 1923); INSERT INTO hydropower VALUES ('Sacramento', 4141.1, 4820.0, 38.7081, -121.1222, 'Mormon Island Auxilliary Dam', 'CVP-Folsom Sly Park', 'California', 110.0, 'Blue Ravine', 1956); INSERT INTO hydropower VALUES ('Montrose', 7165.0, 724.0, 38.4517985259, -107.538127899, 'Morrow Point Dam', 'Colorado River Storage', 'Colorado', 468.0, 'Gunnison River', 1963); INSERT INTO hydropower VALUES ('Kiowa', 1423.0, 535.0, 34.7386, -98.9875, 'Mountain Park Dam', 'Mountain Park', 'Oklahoma', 133.0, 'West Otter Creek', 1973); INSERT INTO hydropower VALUES ('Lake', 9652.0, 2600.0, 39.0833, -106.455, 'Mt Elbert Forebay Dam', 'Fryingpan-Arkansas', 'Colorado', 92.0, 'Offstream', 1977); INSERT INTO hydropower VALUES ('Sante Fe', 6840.0, 1021.0, 35.8453318601, -105.905810595, 'Nambe Falls Dam', 'San Juan-Chama', 'New Mexico', 150.0, 'Rio Nambe', 1974); INSERT INTO hydropower VALUES ('SanJuan, Rio Arriba', 6108.0, 3648.0, 36.8023689686, -107.61297226, 'Navajo Dam', 'Colorado River Storage', 'New Mexico', 402.0, 'San Juan River', 1957); INSERT INTO hydropower VALUES ('Phillip', 2228.0, 9900.0, 48.5334, -107.5221, 'Nelson Dam', 'Milk River', 'Montana', 28.0, 'Offstream Storage', 1914); INSERT INTO hydropower VALUES ('Calaveras', 1135.0, 578.0, 37.9528, -120.5167, 'New Melones Dam', 'CVP-New Melones', 'California', 132.17, 'Stanislaus River', 1966); INSERT INTO hydropower VALUES ('Maricopa', 1728.0, 4900.0, 33.8437, -112.266, 'New Waddell Dam', 'Central Arizona', 'Arizona', 440.0, 'Agua Fria', 1987); INSERT INTO hydropower VALUES ('Cache', 4781.0, 3340.0, 41.8954646744, -111.97385788, 'Newton Dam', 'Newton', 'Utah', 101.0, 'Clarkson Creek', 1941); INSERT INTO hydropower VALUES ('Sacramento', 132.0, 1093.0, 38.6367, -121.2233, 'Nimbus Dam', 'CVP-Folsom', 'California', 87.0, 'American River', 1952); INSERT INTO hydropower VALUES ('Pitkin', 10170.5, 26.0, 39.1119, -106.433, 'No Name Creek Diversion Dam', 'Fryingpan-Arkansas', 'Colorado', 13.0, 'No Name Creek', 1976); INSERT INTO hydropower VALUES ('Clevelandand Oklahoma', 1071.0, 7220.0, 35.2208, -97.2181, 'Norman Dam', 'Norman', 'Oklahoma', 144.0, 'Little River', 1962); INSERT INTO hydropower VALUES ('Pitkin', 10087.5, 38.6, 39.20128, -106.32352, 'North Cunningham Creek Diversion Dam', 'Fryingpan-Arkansas', 'Colorado', 132.17, 'Cunningham Creek', 1976); INSERT INTO hydropower VALUES ('Grant', 1580.0, 1450.0, 47.9404295, -119.0172442, 'North Dam', 'Columbia Basin', 'Washington', 145.0, 'Offstream', 1946); INSERT INTO hydropower VALUES ('Eagle', 10217.5, 36.0, 39.21585, -106.32362, 'North Fork Diversion Dam', 'Fryingpan-Arkansas', 'Colorado', 132.17, 'North Fork Creek', 0); INSERT INTO hydropower VALUES ('Tehama', 1329.9, 375.0, 36.2780790199, -97.501892793, 'Northside Diversion Dam', 'Orland', 'California', 15.0, 'Stony Creek', 1913); INSERT INTO hydropower VALUES ('Norton', 2347.0, 6450.0, 39.8067, -99.935, 'Norton Dam', 'PSMBP-Almena', 'Kansas', 150.5, 'Prairie Dog Creek', 1961); INSERT INTO hydropower VALUES ('Merced', 233.0, 14300.0, 37.1167, -121.05, 'O`Neill Dam', 'Central Valley', 'California', 87.5, 'San Luis Creek', 1963); INSERT INTO hydropower VALUES ('Grant', 1061.0, 19000.0, 46.9806, -119.27, 'O`Sullivan Dam', 'Columbia Basin', 'Washington', 200.0, 'Lower Crab Creek', 1947); INSERT INTO hydropower VALUES ('Crook', 3143.0, 1300.0, 44.29903, -120.72506, 'Ochoco Dam', 'Crooked River', 'Oregon', 152.0, 'Ochoco Creek', 1918); INSERT INTO hydropower VALUES ('Larimer', 7481.0, 320.0, 40.375, -105.4883, 'Olympus Dam', 'Colorado-Big Thompson', 'Colorado', 70.0, 'Big Thompson River', 1947); INSERT INTO hydropower VALUES ('Santa Barbara', 460.85, 2784.18, 34.4317, -119.5917, 'Ortega Dam', 'Cachuma', 'California', 131.0, 'Offstream Storage', 1953); INSERT INTO hydropower VALUES ('Malheur', 2675.0, 833.0, 43.6422, -117.2430896, 'Owyhee Dam', 'Owyhee', 'Oregon', 417.0, 'Owyhee River', 1928); INSERT INTO hydropower VALUES ('Pennington', 4655.0, 2236.0, 44.0717, -103.4883, 'Pactola Dam', 'PSMBP-Rapid Valley Unit', 'South Dakota', 245.0, 'Rapid Creek', 1952); INSERT INTO hydropower VALUES ('Bonneville', 5630.0, 2100.0, 43.332498, -111.202626, 'Palisades Dam', 'Palisades', 'Idaho', 270.0, 'SF of Snake River', 1951); INSERT INTO hydropower VALUES ('La Paz, AZ; Riverside, CA', 296.0, 150.0, 33.7325, -114.5107, 'Palo Verde Diversion Dam', 'Palo Verde Diversion', 'Arizona and California', 50.0, 'Colorado River', 1957); INSERT INTO hydropower VALUES ('Gunnison', 6460.0, 770.0, 38.9417446391, -107.353248596, 'Paonia Dam', 'Paonia', 'Colorado', 199.0, 'Muddy Creek', 1959); INSERT INTO hydropower VALUES ('Blaine', 2401.5, 570.0, 48.5663, -109.1901, 'Paradise Diversion Dam', 'Milk River', 'Montana', 20.0, 'Milk River', 1966); INSERT INTO hydropower VALUES ('LaPaz, AZ; San Bernardino, CA', 455.0, 856.0, 34.2966, -114.1394, 'Parker Dam', 'Parker-Davis', 'Arizona and California', 320.0, 'Colorado River', 1934); INSERT INTO hydropower VALUES ('Natrona', 5858.1, 432.0, 42.4683, -106.8533, 'Pathfinder Dam', 'North Platte', 'Wyoming', 214.0, 'North Platte River', 1905); INSERT INTO hydropower VALUES ('Natrona', 5868.1, 1650.0, 42.8075, -106.855, 'Pathfinder Dike Dam', 'North Platte', 'Wyoming', 38.0, 'North Platte River', 1909); INSERT INTO hydropower VALUES ('Fremont', 5467.0, 55.0, 43.197, -108.7531, 'Pilot Butte Dam', 'PSMBP-Riverton', 'Wyoming', 64.0, 'Offstream', 1926); INSERT INTO hydropower VALUES ('Weber', 4908.0, 600.0, 41.2540240125, -111.842708588, 'Pineview Dam', 'Ogden River', 'Utah', 137.0, 'Ogden River', 1934); INSERT INTO hydropower VALUES ('Grant', 1351.0, 1900.0, 47.4483, -119.2533, 'Pinto Dam', 'Columbia Basin', 'Washington', 130.0, 'Offstream Storage', 1946); INSERT INTO hydropower VALUES ('Teton', 4380.0, 9050.0, 47.6818, -112.5058, 'Pishkun Dikes', 'Sun River', 'Montana', 12.0, 'Offstream Storage', 1930); INSERT INTO hydropower VALUES ('Conejos', 10048.0, 1475.0, 37.3507391783, -106.5483284, 'Platoro Dam', 'San Luis Valley', 'Colorado', 165.0, 'Conejos River', 1949); INSERT INTO hydropower VALUES ('Larimer', 6597.25, 220.0, 40.36642, -105.33156, 'Pole Hill Afterbay Dam', 'Colorado-Big Thompson', 'Colorado', 32.0, 'Little Hell Creek', 1953); INSERT INTO hydropower VALUES ('Placer', 5761.0, 1830.0, 36.2780790199, -97.501892793, 'Prosser Creek Dam', 'Washoe', 'California', 163.0, 'Prosser Creek', 1959); INSERT INTO hydropower VALUES ('Pueblo', 4925.0, 10230.0, 38.2839, -104.73, 'Pueblo Dam', 'Fryingpan-Arkansas', 'Colorado', 250.0, 'Arkansas River', 1970); INSERT INTO hydropower VALUES ('Yolo', 4141.1, 2784.18, 36.2780790199, -97.501892793, 'Putah Dam', 'Solano', 'California', 132.17, 'Putah Creek', 1957); INSERT INTO hydropower VALUES ('Colusa', 1289.0, 271.0, 36.2780790199, -97.501892793, 'Rainbow Diversion Dam', 'Orland', 'California', 44.0, 'Stony Creek', 1914); INSERT INTO hydropower VALUES ('Unknown', 4599.0, 2220.0, 44.72639, -108.86416, 'Ralston Dam', 'Shoshone', 'Wyoming', 35.0, 'Garland Canal', 1908); INSERT INTO hydropower VALUES ('Larimer', 6595.0, 1951.0, 40.3708, -105.2889, 'Rattlesnake Dam', 'Colorado-Big thompson', 'Colorado', 130.0, 'Rattlesnake Creek', 1951); INSERT INTO hydropower VALUES ('Tehama', 4141.1, 2784.18, 36.2780790199, -97.501892793, 'Red Bluff Diversion Dam', 'CVP-Sacramento Canals', 'California', 132.17, 'Sacramento River', 1964); INSERT INTO hydropower VALUES ('Uintah', 5627.0, 1670.0, 40.5802826272, -109.442195892, 'Red Fleet Dam', 'CUP-Jensen Unit', 'Utah', 175.0, 'Big Bush Creek', 1977); INSERT INTO hydropower VALUES ('Red Willow', 4141.1, 2784.18, 40.28167, -100.54177, 'Red Willow Creek Diversion Dam', '<API key>', 'Nebraska', 132.17, 'Red Willow Creek', 1963); INSERT INTO hydropower VALUES ('Frontier', 2634.0, 3159.0, 40.3639, -100.6656, 'Red Willow Dam', 'French-Cambridge (PSMBP)', 'Nebraska', 126.0, 'Red Willow Creek', 1960); INSERT INTO hydropower VALUES ('Nez Perce', 1813.0, 2200.0, 46.371998, -116.8574309, 'Reservoir A Dam', 'Lewiston Orchards', 'Idaho', 60.0, 'Offstream Storage - Lindsey Creek', 1907); INSERT INTO hydropower VALUES ('Ouray', 6888.5, 2465.0, 38.1991823038, -107.742061615, 'Ridgway Dam', 'Dallas Creek', 'Colorado', 332.9, 'Uncompahgre River', 1978); INSERT INTO hydropower VALUES ('Garfield', 5978.0, 1450.0, 39.6272007639, -107.760257721, 'Rifle Gap Dam', 'Silt', 'Colorado', 157.0, 'Rifle Creek', 1964); INSERT INTO hydropower VALUES ('Bonneville', 5128.0, 1070.0, 43.5833, -111.7425, 'Ririe Dam', 'Ririe', 'Idaho', 253.0, 'Willow Creek', 1970); INSERT INTO hydropower VALUES ('Ventura', 765.0, 530.0, 36.2780790199, -97.501892793, 'Robles Dam', 'Ventura River', 'California', 24.0, 'Ventura River', 1958); INSERT INTO hydropower VALUES ('Kittitas', 1205.0, 486.0, 46.74923, -120.4658, 'Roza Diversion Dam', 'Yakima', 'Washington', 67.0, 'Yakima River', 1939); INSERT INTO hydropower VALUES ('Eagle & Pitkin', 7788.0, 1042.0, 39.3631, -106.8181, 'Ruedi Dam', 'Fryingpan-Arkansas', 'Colorado', 285.0, 'Fryingpan River', 1964); INSERT INTO hydropower VALUES ('Pershing', 4144.0, 1074.0, 40.4617, -118.3083, 'Rye Patch Dam', 'Humboldt', 'Nevada', 78.0, 'Humboldt River', 1935); INSERT INTO hydropower VALUES ('Okanogan', 2325.5, 1260.0, 48.56036, -119.74496, 'Salmon Lake Dam', 'Okanogan', 'Washington', 54.0, 'Offstream Storage', 1919); INSERT INTO hydropower VALUES ('Socorro', 4668.5, 700.0, 36.2780790199, -97.501892793, 'San Acacia Diversion Dam', 'Middle Rio Grande', 'New Mexico', 17.0, 'Rio Grande', 1934); INSERT INTO hydropower VALUES ('San Benito', 508.5, 1115.0, 36.2780790199, -97.501892793, 'San Justo Dam', 'CVP-San Felipe Division', 'California', 135.0, 'Offtream Storage', 1987); INSERT INTO hydropower VALUES ('Hutchinson', 3011.0, 2784.18, 35.71367, -101.55251, 'Sanford Dam', 'Canadian River', 'Texas', 228.0, 'Canadian River', 1962); INSERT INTO hydropower VALUES ('Larimer', 5443.0, 328.0, 40.59957, -105.17569, 'Satanka Dike Dam', 'Colorado-Big Thompson', 'Colorado', 30.0, 'Offstream Storage', 1946); INSERT INTO hydropower VALUES ('Pitkin', 10084.5, 20.0, 39.15564, -106.38123, 'Sawyer Diversion Dam', 'Fryingpan-Arkansas', 'Colorado', 6.0, 'Sawyer Creek', 1970); INSERT INTO hydropower VALUES ('Carbon', 7636.0, 575.0, 39.786204926, -111.119499207, 'Scofield Dam', 'Scofield', 'Utah', 96.0, 'Price River', 1943); INSERT INTO hydropower VALUES ('Washington', 313.0, 2700.0, 45.4724, -123.19965, 'Scoggins Dam', 'Tualatin', 'Oregon', 151.0, 'Scoggins Creek', 1972); INSERT INTO hydropower VALUES ('Carbon', 6361.0, 530.0, 42.1569, -106.9083, 'Seminoe Dam', 'Kendrick', 'Wyoming', 295.0, 'North Platte River', 1936); INSERT INTO hydropower VALUES ('Imperial', 265.0, 2342.0, 32.91, -114.4783, 'Senator Wash Dam', 'Colorado River Front Work & Levee System', 'California', 93.6, 'Offstream', 1964); INSERT INTO hydropower VALUES ('Perkins', 2318.0, 12843.0, 45.7533, -102.2033, 'Shadehill Dam', 'PSMBP-Shadehill', 'South Dakota', 145.0, 'Grand River', 1949); INSERT INTO hydropower VALUES ('Grand', 8375.0, 3077.0, 40.20785, -105.84102, 'Shadow Mountain Dam', 'Colorado-Big Thompson', 'Colorado', 63.0, 'Colorado River', 1944); INSERT INTO hydropower VALUES ('Shasta', 1077.5, 3460.0, 36.2780790199, -97.501892793, 'Shasta Dam', 'CVP-Shasta/Trinity', 'California', 602.0, 'Sacramento River', 1938); INSERT INTO hydropower VALUES ('Gunnison', 8939.0, 1050.0, 38.2320697941, -107.543106079, 'Silver Jack Dam', 'Bostwick Park', 'Colorado', 173.9, 'Cimarron Creek', 1966); INSERT INTO hydropower VALUES ('El Dorado', 3482.0, 760.0, 38.7208, -120.56, 'Sly Park Dam', 'CVP-Folsom Sly Park', 'California', 190.0, 'Sly Park Creek', 1953); INSERT INTO hydropower VALUES ('Larimer', 5443.0, 1438.0, 40.5883, -105.1033, 'Soldier Canyon Dam', 'Colorado-Big Thompson', 'Colorado', 226.0, 'Offstream Storage', 1946); INSERT INTO hydropower VALUES ('Wasatch', 7612.0, 1290.0, 40.1357992386, -111.026287079, 'Soldier Creek Dam', 'CUP - Bonneville Unit', 'Utah', 272.0, 'Strawberry River', 1970); INSERT INTO hydropower VALUES ('NezPerce', 4529.0, 630.0, 46.16727, -116.7367, 'Soldiers Meadow Dam', 'Lewiston Orchards', 'Idaho', 69.0, 'Webb Creek', 1923); INSERT INTO hydropower VALUES ('Pitkin', 10539.0, 20.0, 39.19271, -106.33298, 'South Cunningham Creek Diversion Dam', 'Fryingpan-Arkansas', 'Colorado', 132.17, 'Cunningham Creek', 1976); INSERT INTO hydropower VALUES ('Pitkin', 10003.0, 20.0, 39.14158, -106.35222, 'South Fork Diversion Dam', 'Fryingpan-Arkansas', 'Colorado', 13.0, 'Fryingpan-Arkansas', 1965); INSERT INTO hydropower VALUES ('Larimer', 5443.0, 1840.0, 40.53, -105.135, 'Spring Canyon Dam', 'Colorado-Big Thompson', 'Colorado', 155.0, 'Offstream Storage', 1946); INSERT INTO hydropower VALUES ('Shasta', 816.0, 1110.0, 36.2780790199, -97.501892793, 'Spring Creek Debris Dam', 'CVP-Shasta/Trinity', 'California', 196.0, 'Spring Creek', 1961); INSERT INTO hydropower VALUES ('Glacier', 4457.5, 198.0, 48.8521, -113.4169, 'St. Mary Diversion Dam', 'Milk River', 'Montana', 6.0, 'St. Mary River', 1915); INSERT INTO hydropower VALUES ('Sierra', 5974.0, 1511.0, 39.1078, -120.11, 'Stampede Dam', 'Washoe', 'California', 239.0, 'Little Truckee R.', 1966); INSERT INTO hydropower VALUES ('Duchesne', 5725.0, 3070.0, 40.1887573191, -110.44418335, 'Starvation Dam', 'CUP-Bonneville Unit', 'Utah', 200.3, 'Strawberry River', 1970); INSERT INTO hydropower VALUES ('Summit', 9176.0, 2800.0, 40.99, -110.39, 'Stateline Dam', 'Lyman', 'Utah', 143.0, 'East Fork of Smiths Fork', 1977); INSERT INTO hydropower VALUES ('Uintah', 5527.0, 1997.0, 40.5056659954, -109.530944824, 'Steinaker Dam', 'CUP-Vernal Unit', 'Utah', 162.2, 'Offstream', 1959); INSERT INTO hydropower VALUES ('Maricopa', 1533.0, 1260.0, 33.5666, -111.5361, 'Stewart Mountain Dam', 'Salt River', 'Arizona', 207.0, 'Salt River', 1928); INSERT INTO hydropower VALUES ('Glenn', 847.0, 868.0, 36.2780790199, -97.501892793, 'Stony Gorge Dam', 'Orland', 'California', 139.0, 'Stony Creek', 1926); INSERT INTO hydropower VALUES ('Lake', 9879.0, 2020.0, 39.2517, -106.3733, 'Sugar Loaf Dam', 'Fryingpan-Arkansas', 'Colorado', 135.0, 'Lake Fork of the Arkansas', 1965); INSERT INTO hydropower VALUES ('De Baca', 4301.0, 3675.0, 34.6071684, -104.387583733, 'Sumner Dam', 'Carlsbad', 'New Mexico', 164.0, 'Pecos River', 1936); INSERT INTO hydropower VALUES ('Teton, Lewis and Clark', 4474.0, 261.0, 47.6211, -112.7066, 'Sun River Diversion Dam', 'Sun River', 'Montana', 132.0, 'North Fork Sun River', 1915); INSERT INTO hydropower VALUES ('Webster', 4141.1, 2784.18, 40.06759, -98.37712, 'Superior Courtland Diversion Dam', 'PSMBP-Bostwick', 'Nebraska', 132.17, 'Republican River', 1950); INSERT INTO hydropower VALUES ('Glacier', 4485.0, 4800.0, 48.5107, -113.2501, 'Swift Current Dike', 'Milk River', 'Montana', 13.0, 'St. Mary River', 1915); INSERT INTO hydropower VALUES ('Gunnison', 9343.0, 675.0, 38.818001324, -106.606521606, 'Taylor Park Dam', 'Uncompahgre', 'Colorado', 206.8, 'Taylor River', 1935); INSERT INTO hydropower VALUES ('Solano', 90.0, 870.0, 36.2780790199, -97.501892793, 'Terminal Dam', 'Solano', 'California', 24.0, 'Offstream Storage', 1959); INSERT INTO hydropower VALUES ('Maricopa, Gila', 2218.0, 1210.0, 33.6718, -111.1613, 'Theodore Roosevelt Dam', 'Salt River', 'Arizona', 357.0, 'Salt River', 1903); INSERT INTO hydropower VALUES ('Baker, Union', 3143.0, 390.0, 45.012996, -117.7810764, 'Thief Valley Dam', 'Baker, Union', 'Oregon', 73.0, 'Powder River', 1931); INSERT INTO hydropower VALUES ('Umatilla', 404.3, 915.0, 45.882972, -119.3245482, 'Three Mile Falls Diversion Dam', 'Umatilla Basin', 'Oregon', 24.0, 'Umatilla River', 1914); INSERT INTO hydropower VALUES ('Liberty', 3026.0, 4300.0, 48.3222, -111.0969, 'Tiber Dam', 'Lower Marias', 'Montana', 211.0, 'Marias River', 1952); INSERT INTO hydropower VALUES ('Yakina', 2935.0, 920.0, 46.657198, -121.12808, 'Tieton Dam', 'Yakima', 'Washington', 319.0, 'Tieton river', 1917); INSERT INTO hydropower VALUES ('Hitchcock', 2793.0, 8600.0, 40.17, -101.06, 'Trenton Dam', '<API key>', 'Nebraska', 144.0, 'Republican River', 1949); INSERT INTO hydropower VALUES ('Trinity', 2395.0, 2450.0, 36.2780790199, -97.501892793, 'Trinity Dam', 'CVP-ShastaTrinity', 'California', 538.0, 'Trinity River', 1957); INSERT INTO hydropower VALUES ('Scotts Bluff', 4000.0, 205.0, 41.85086, -103.68886, 'Tub Springs Creek Diversion Dam', 'North Platte', 'Nebraska', 11.0, 'Tub springs Creek', 0); INSERT INTO hydropower VALUES ('Tom Green', 1991.0, 42460.0, 31.3767, -100.5333, 'Twin Buttes Dam', 'San Angelo', 'Texas', 134.0, 'Spring Creek', 1960); INSERT INTO hydropower VALUES ('Lake', 9210.0, 3150.0, 39.0833, -106.4617, 'Twin Lakes Dam', 'Fryingpan-Arkansas', 'Colorado', 132.17, 'Lake Creek', 1978); INSERT INTO hydropower VALUES ('San Luis Obispo', 692.0, 1804.0, 34.9778, -120.3167, 'Twitchell Dam', 'Santa Maria', 'California', 241.0, 'Cuyama River', 1956); INSERT INTO hydropower VALUES ('Baker', 3827.3, 694.0, 44.5042, -118.1806, 'Unity Dam', 'Burnt River', 'Oregon', 82.0, 'Burnt River', 1936); INSERT INTO hydropower VALUES ('Lander', 4560.0, 88.0, 36.2780790199, -97.501892793, 'Upper Slaven Diversion Dam', 'Humboldt', 'Nevada', 18.0, 'Humboldt', 1958); INSERT INTO hydropower VALUES ('Duchesne', 8180.0, 2660.0, 40.56, -110.6992, 'Upper Stillwater Dam', 'CUP-Bonneville Unit', 'Utah', 310.0, 'Rock Creek', 1983); INSERT INTO hydropower VALUES ('La Plata', 7673.0, 4010.0, 37.3777533758, -107.575378418, 'Vallecito Dam', 'Pine River', 'Colorado', 162.0, 'Pine River (Los Pinos)', 1938); INSERT INTO hydropower VALUES ('Valley', 2116.0, 2350.0, 48.3727, -106.9749, 'Vandalia Diversion Dam', 'Milk River', 'Montana', 32.0, 'Milk River', 1917); INSERT INTO hydropower VALUES ('Mesa', 7997.0, 2100.0, 39.2229902749, -107.810811996, 'Vega Dam', 'Collbran', 'Colorado', 162.0, 'Plateau Creek', 1957); INSERT INTO hydropower VALUES ('Garfield and Loup', 2259.0, 147.0, 41.8333, -99.2, 'Virginia Smith Dam', 'PSMBP-North Loup', 'Nebraska', 96.0, 'Calamus River', 1985); INSERT INTO hydropower VALUES ('Summit', 6055.0, 2015.0, 40.78855885, -111.405487061, 'Wanship Dam', 'Weber Basin', 'Utah', 175.0, 'Weber River', 1954); INSERT INTO hydropower VALUES ('Malheur', 3409.0, 469.0, 43.58505, -118.2092857, 'Warm Springs Dam', 'Vale', 'Oregon', 106.0, 'Middle Fork of the Malheur River', 1918); INSERT INTO hydropower VALUES ('Wasco', 3526.0, 415.0, 45.1748403, -121.6895197, 'Wasco Dam', 'Wapinitia', 'Oregon', 59.0, 'Clear Creek', 1958); INSERT INTO hydropower VALUES ('Rooks', 1944.0, 1944.0, 39.4083, -99.4217, 'Webster Dam', 'PSMBP-Webster', 'Kansas', 154.0, 'SF of Solomon Rive', 1953); INSERT INTO hydropower VALUES ('Goshen', 4292.0, 2460.0, 42.24766, -104.62908, 'Whalen Diversion Dam', 'North Platte', 'Wyoming', 35.0, 'North Platte River', 1909); INSERT INTO hydropower VALUES ('Shasta', 1228.0, 4000.0, 36.2780790199, -97.501892793, 'Whiskeytown Dam', 'CVP-Shasta/Trinity', 'California', 282.0, 'Clear Creek', 1960); INSERT INTO hydropower VALUES ('Deschutes', 4347.0, 13860.0, 43.6953977, -121.7039162, 'Wickiup Dam', 'Deschutes', 'Oregon', 100.0, 'Deschutes River', 1939); INSERT INTO hydropower VALUES ('Grand', 8140.0, 1100.0, 40.1467, -105.9417, 'Willow Creek Co Dam', 'Colorado-Big Thompson', 'Colorado', 127.0, 'Willow Creek', 1951); INSERT INTO hydropower VALUES ('Lewis and Clark', 4154.0, 650.0, 45.7138, -111.6998, 'Willow Creek Dam', 'Sun River', 'Montana', 93.0, 'Willow Creek', 1907); INSERT INTO hydropower VALUES ('Park', 4514.0, 476.0, 44.67157, -108.90976, 'Willwood Diversion Dam', 'Shoshone', 'Wyoming', 70.0, 'Shoshone River', 1924); INSERT INTO hydropower VALUES ('Fremont', 5581.25, 2464.0, 43.22476, -108.95534, 'Wind River Diversion Dam', 'PSMBP - Riverton Unit', 'Wyoming', 37.0, 'Wind River', 1921); INSERT INTO hydropower VALUES ('Rooks', 1700.0, 151.0, 39.4486, -99.1331, 'Woodston Diversion Dam', 'PSMBP-Webster', 'Kansas', 30.0, 'Solomon River', 1957); INSERT INTO hydropower VALUES ('Yellowstone', 3004.0, 325.0, 45.8745467319, -108.348659277, 'Yellowstone River Diversion Dam', 'Huntley', 'Montana', 10.5, 'Yellowstone River', 1934); INSERT INTO hydropower VALUES ('Big Horn', 3197.5, 1360.0, 45.3162053382, -107.921319008, 'Yellowtail Afterbay Dam', 'Yellowtail Unit, Pick-Sloan Missouri River Basin Program', 'Montana', 72.0, 'Bighorn River', 1964); INSERT INTO hydropower VALUES ('Big Horn', 3660.0, 1480.0, 45.3068700744, -107.957754135, 'Yellowtail Dam', 'Yellowtail Unit, Pick-Sloan Missouri River Basin Program', 'Montana', 525.0, 'Bighorn River', 1963);
/* NoSound Driver to demonstrate how to use the SoundDriver interface */ #pragma once #include "common.h" #include "SoundDriver.h" #if !defined(_WIN32) && !defined(_XBOX) typedef union _LARGE_INTEGER { #if defined(<API key>) struct { u32 LowPart; s32 HighPart; }; /* ...but Microsoft uses them anyway. */ #endif struct { u32 LowPart; s32 HighPart; } u; s64 QuadPart; } LARGE_INTEGER; #endif class NoSoundDriver : public SoundDriver { public: NoSoundDriver() {}; ~NoSoundDriver() {}; // Setup and Teardown Functions Boolean Initialize(); void DeInitialize(); // Management functions void AiUpdate(Boolean Wait); void StopAudio(); void StartAudio(); void SetFrequency(u32 Frequency); static <API key>* CreateSoundDriver() { return new NoSoundDriver(); } protected: bool dllInitialized; /* LARGE_INTEGER perfTimer; LARGE_INTEGER perfFreq; LARGE_INTEGER perfLast; LARGE_INTEGER countsPerSample; */ bool isPlaying; };
\section{analyzerbase.cpp File Reference} \label{analyzerbase_8cpp}\index{analyzerbase.cpp@{analyzerbase.cpp}} {\tt \#include \char`\"{}analyzerbase.h\char`\"{}}\par {\tt \#include \char`\"{}enginebase.h\char`\"{}}\par {\tt \#include \char`\"{}enginecontroller.h\char`\"{}}\par {\tt \#include $<$math.h$>$}\par {\tt \#include $<$qevent.h$>$}\par {\tt \#include \char`\"{}analyzerbase.moc\char`\"{}}\par Include dependency graph for analyzerbase.cpp:\begin{figure}[H] \begin{center} \leavevmode \includegraphics[width=382pt]{<API key>} \end{center} \end{figure}
<!DOCTYPE HTML PUBLIC "- <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_67) on Wed Oct 08 14:54:44 CDT 2014 --> <title>A-Index</title> <meta name="date" content="2014-10-08"> <link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><! if (location.href.indexOf('is-external=true') == -1) { parent.document.title="A-Index"; } </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <div class="topNav"><a name="navbar_top"> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> </a> <ul class="navList" title="Navigation"> <li><a href="../overview-summary.html">Overview</a></li> <li>Package</li> <li>Class</li> <li>Use</li> <li><a href="../overview-tree.html">Tree</a></li> <li><a href="../deprecated-list.html">Deprecated</a></li> <li class="navBarCell1Rev">Index</li> <li><a href="../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev Letter</li> <li><a href="index-2.html">Next Letter</a></li> </ul> <ul class="navList"> <li><a href="../index.html?index-filesindex-1.html" target="_top">Frames</a></li> <li><a href="index-1.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <a name="skip-navbar_top"> </a></div> <div class="contentContainer"><a href="index-1.html">A</a>&nbsp;<a href="index-2.html">C</a>&nbsp;<a href="index-3.html">D</a>&nbsp;<a href="index-4.html">E</a>&nbsp;<a href="index-5.html">F</a>&nbsp;<a href="index-6.html">G</a>&nbsp;<a href="index-7.html">H</a>&nbsp;<a href="index-8.html">I</a>&nbsp;<a href="index-9.html">K</a>&nbsp;<a href="index-10.html">L</a>&nbsp;<a href="index-11.html">M</a>&nbsp;<a href="index-12.html">O</a>&nbsp;<a href="index-13.html">P</a>&nbsp;<a href="index-14.html">R</a>&nbsp;<a href="index-15.html">S</a>&nbsp;<a href="index-16.html">T</a>&nbsp;<a href="index-17.html">U</a>&nbsp;<a href="index-18.html">V</a>&nbsp;<a href="index-19.html">W</a>&nbsp;<a name="_A_"> </a> <h2 class="title">A</h2> <dl> <dt><span class="strong"><a href="../com/flamingOctoIronman/math/matrix/MatrixMath.html#addMatrices(com.flamingOctoIronman.library.math.matrix.Matrix,%20com.flamingOctoIronman.math.matrix.Matrix)">addMatrices(Matrix, Matrix)</a></span> - Static method in class com.flamingOctoIronman.math.matrix.<a href="../com/flamingOctoIronman/math/matrix/MatrixMath.html" title="class in com.flamingOctoIronman.math.matrix">MatrixMath</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="../com/flamingOctoIronman/debugging/StreamManager.html#addStreamToOutput(java.io.PrintStream)">addStreamToOutput(PrintStream)</a></span> - Method in class com.flamingOctoIronman.debugging.<a href="../com/flamingOctoIronman/debugging/StreamManager.html" title="class in com.flamingOctoIronman.debugging">StreamManager</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="../com/flamingOctoIronman/math/matrix/MatrixMath.html#<API key>(com.flamingOctoIronman.library.math.matrix.Matrix)"><API key>(Matrix)</a></span> - Static method in class com.flamingOctoIronman.math.matrix.<a href="../com/flamingOctoIronman/math/matrix/MatrixMath.html" title="class in com.flamingOctoIronman.math.matrix">MatrixMath</a></dt> <dd>&nbsp;</dd> </dl> <a href="index-1.html">A</a>&nbsp;<a href="index-2.html">C</a>&nbsp;<a href="index-3.html">D</a>&nbsp;<a href="index-4.html">E</a>&nbsp;<a href="index-5.html">F</a>&nbsp;<a href="index-6.html">G</a>&nbsp;<a href="index-7.html">H</a>&nbsp;<a href="index-8.html">I</a>&nbsp;<a href="index-9.html">K</a>&nbsp;<a href="index-10.html">L</a>&nbsp;<a href="index-11.html">M</a>&nbsp;<a href="index-12.html">O</a>&nbsp;<a href="index-13.html">P</a>&nbsp;<a href="index-14.html">R</a>&nbsp;<a href="index-15.html">S</a>&nbsp;<a href="index-16.html">T</a>&nbsp;<a href="index-17.html">U</a>&nbsp;<a href="index-18.html">V</a>&nbsp;<a href="index-19.html">W</a>&nbsp;</div> <div class="bottomNav"><a name="navbar_bottom"> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="<API key>"> </a> <ul class="navList" title="Navigation"> <li><a href="../overview-summary.html">Overview</a></li> <li>Package</li> <li>Class</li> <li>Use</li> <li><a href="../overview-tree.html">Tree</a></li> <li><a href="../deprecated-list.html">Deprecated</a></li> <li class="navBarCell1Rev">Index</li> <li><a href="../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev Letter</li> <li><a href="index-2.html">Next Letter</a></li> </ul> <ul class="navList"> <li><a href="../index.html?index-filesindex-1.html" target="_top">Frames</a></li> <li><a href="index-1.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <a name="skip-navbar_bottom"> </a></div> </body> </html>
.book-navigation .menu { border-top: 1px solid #888; padding: 1em 0 0 3em; /* LTR */ } .book-navigation .page-links { border-top: 1px solid #888; border-bottom: 1px solid #888; text-align: center; padding: 0.5em; } .book-navigation .page-previous { text-align: left; width: 42%; display: block; float: left; /* LTR */ } .book-navigation .page-up { margin: 0 5%; width: 4%; display: block; float: left; /* LTR */ } .book-navigation .page-next { text-align: right; width: 42%; display: block; float: right; } #book-outline { min-width: 56em; } .book-outline-form .form-item { margin-top: 0; margin-bottom: 0; } html.js #edit-book-pick-book { display: none; } .form-item-book-bid .description { clear: both; } #book-admin-edit select { margin-right: 24px; } #book-admin-edit select.progress-disabled { margin-right: 0; } #book-admin-edit tr.ajax-new-content { background-color: #ffd; } #book-admin-edit .form-item { float: left; }
<?php // No direct access defined('_JEXEC') or die; class TableReplacement extends JTable { /** * @param database A database connector object */ public function __construct($db) { parent::__construct('#__csvi_replacements', 'id', $db ); } }
/* Easy Slider */ #slider ul, #slider li, #slider2 ul, #slider2 li{ margin:0; padding:0; list-style:none; } .slider img { border:1px solid #dddddd; } .slider { background-color:#fff; margin-bottom:10px; } #slider2{margin-top:1em;} #slider li, #slider2 li{ /* define width and height of list item (slide) entire slider area will adjust according to the parameters provided here */ width:300px; height:190px; overflow:hidden; } #prevBtn a, #nextBtn a,#slider1next a, #slider1prev a { float:right; border:none; font-weight:bold; font-family:Arial, Helvetica, sans-serif; color:#fff; background:transparent; font-size:0.88em; text-decoration:none; background:transparent url('images/arrow-next.png') no-repeat scroll top left; height:25px; width:25px; display:block; } #nextBtn a, #slider1next a { background-image:url('images/arrow-prev.png'); margin-right:5px; } /* numeric controls */ ol#controls{ margin:1em 0; padding:0; height:28px; } ol#controls li{ margin:0 10px 0 0; padding:0; float:left; list-style:none; height:28px; line-height:28px; } ol#controls li a{ float:left; height:28px; line-height:28px; border:1px solid #ccc; background:#DAF3F8; color:#555; padding:0 10px; text-decoration:none; } ol#controls li.current a{ background:#5DC9E1; color:#fff; } ol#controls li a:focus, #prevBtn a:focus, #nextBtn a:focus{outline:none;} /* // Easy Slider */
<!DOCTYPE html PUBLIC "- <html xmlns="http: <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <title>Luayats: src/rstp/p2p.h Source File</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <link href="doxygen.css" rel="stylesheet" type="text/css"/> </head> <body> <!-- Generated by Doxygen 1.6.1 --> <div class="navigation" id="top"> <div class="tabs"> <ul> <li><a href="index.html"><span>Main&nbsp;Page</span></a></li> <li><a href="annotated.html"><span>Classes</span></a></li> <li class="current"><a href="files.html"><span>Files</span></a></li> </ul> </div> <div class="tabs"> <ul> <li><a href="files.html"><span>File&nbsp;List</span></a></li> <li><a href="globals.html"><span>File&nbsp;Members</span></a></li> </ul> </div> <a name="l00022"></a>00022 <a name="l00023"></a>00023 <span class="comment">/* Point To Point MAC mode selection machine : 6.4.3, 6.5.1 */</span> <a name="l00024"></a>00024 <a name="l00025"></a>00025 <span class="preprocessor">#ifndef _STP_P2P_H__</span> <a name="l00026"></a>00026 <span class="preprocessor"></span><span class="preprocessor">#define _STP_P2P_H__</span> <a name="l00027"></a>00027 <span class="preprocessor"></span> <a name="l00028"></a>00028 <span class="keywordtype">void</span> <a class="code" href="p2p_8c.html#<API key>">STP_p2p_enter_state</a> (<a class="code" href="<API key>.html">STATE_MACH_T</a>* s); <a name="l00029"></a>00029 <a class="code" href="base_8h.html#<API key>">Bool</a> <a class="code" href="p2p_8c.html#<API key>"><API key></a> (<a class="code" href="<API key>.html">STATE_MACH_T</a>* s); <a name="l00030"></a>00030 <span class="keywordtype">char</span>* <a class="code" href="p2p_8h.html#<API key>"><API key></a> (<span class="keywordtype">int</span> state); <a name="l00031"></a>00031 <a name="l00032"></a>00032 <span class="preprocessor">#endif </span><span class="comment">/* _STP_P2P_H__ */</span> </pre></div></div> <hr size="1"/><address style="text-align: right;"><small>Generated on Sun Feb 14 12:31:42 2010 for Luayats by&nbsp; <a href="http: <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.6.1 </small></address> </body> </html>
package optfine; import com.google.gson.JsonElement; import com.google.gson.JsonParser; public class <API key> implements <API key> { private String player = null; public <API key>(String p_i64_1_) { this.player = p_i64_1_; } public void <API key>(String <API key>, byte[] <API key>, Throwable <API key>) { if (<API key> != null) { try { String s = new String(<API key>, "ASCII"); JsonParser jsonparser = new JsonParser(); JsonElement jsonelement = jsonparser.parse(s); <API key> <API key> = new <API key>(this.player); PlayerConfiguration playerconfiguration = <API key>.<API key>(jsonelement); if (playerconfiguration != null) { playerconfiguration.setInitialized(true); <API key>.<API key>(this.player, playerconfiguration); } } catch (Exception exception) { Config.dbg("Error parsing configuration: " + <API key> + ", " + exception.getClass().getName() + ": " + exception.getMessage()); } } } }
set :exec_path, File.expand_path(File.dirname(__FILE__) + "/..") set :scm, :git set :<API key>, 1 set :copy_compression, :gzip set :deploy_via, :remote_cache set :runner, :user set :use_sudo, false set(:run_method) { use_sudo ? :sudo : :run } set :stages, %w( production ) set :keep_releases, 10 default_run_options[:pty] = true role :web, "#{domainname}" role :app, "#{domainname}" ssh_options[:user] = "web1" ssh_options[:compression] = false ssh_options[:forward_agent] = true #dont remove gitfiles, so we can resync from server #set :copy_exclude, [ '.git' ]
<?php /** * transport class for sending/receiving data via HTTP and HTTPS * NOTE: PHP must be compiled with the CURL extension for HTTPS support * * @author Dietrich Ayala <dietrich@ganx4.com> * @version $Id: class.soap_transport_http.php,v 1.4 2013-04-11 08:26:39 mbertin Exp $ * @access public */ class soap_transport_http extends nusoap_base { var $url = ''; var $uri = ''; var $digest_uri = ''; var $scheme = ''; var $host = ''; var $port = ''; var $path = ''; var $request_method = 'POST'; var $protocol_version = '1.0'; var $encoding = ''; var $outgoing_headers = array(); var $incoming_headers = array(); var $incoming_cookies = array(); var $outgoing_payload = ''; var $incoming_payload = ''; var $useSOAPAction = true; var $<API key> = false; var $ch = false; // cURL handle var $username = ''; var $password = ''; var $authtype = ''; var $digestRequest = array(); var $certRequest = array(); // keys must be cainfofile (optional), sslcertfile, sslkeyfile, passphrase, verifypeer (optional), verifyhost (optional) // cainfofile: certificate authority file, e.g. '$pathToPemFiles/rootca.pem' // sslcertfile: SSL certificate file, e.g. '$pathToPemFiles/mycert.pem' // sslkeyfile: SSL key file, e.g. '$pathToPemFiles/mykey.pem' // passphrase: SSL key password/passphrase // verifypeer: default is 1 // verifyhost: default is 1 /** * constructor */ function soap_transport_http($url){ parent::nusoap_base(); $this->setURL($url); ereg('\$Revisio' . 'n: ([^ ]+)', $this->revision, $rev); $this->outgoing_headers['User-Agent'] = $this->title.'/'.$this->version.' ('.$rev[1].')'; $this->debug('set User-Agent: ' . $this->outgoing_headers['User-Agent']); } function setURL($url) { $this->url = $url; $u = parse_url($url); foreach($u as $k => $v){ $this->debug("$k = $v"); $this->$k = $v; } // add any GET params to path if(isset($u['query']) && $u['query'] != ''){ $this->path .= '?' . $u['query']; } // set default port if(!isset($u['port'])){ if($u['scheme'] == 'https'){ $this->port = 443; } else { $this->port = 80; } } $this->uri = $this->path; $this->digest_uri = $this->uri; // build headers if (!isset($u['port'])) { $this->outgoing_headers['Host'] = $this->host; } else { $this->outgoing_headers['Host'] = $this->host.':'.$this->port; } $this->debug('set Host: ' . $this->outgoing_headers['Host']); if (isset($u['user']) && $u['user'] != '') { $this->setCredentials(urldecode($u['user']), isset($u['pass']) ? urldecode($u['pass']) : ''); } } function connect($connection_timeout=0,$response_timeout=30){ // For PHP 4.3 with OpenSSL, change https scheme to ssl, then treat like // "regular" socket. // TODO: disabled for now because OpenSSL must be *compiled* in (not just // loaded), and until PHP5 stream_get_wrappers is not available. // if ($this->scheme == 'https') { // if (version_compare(phpversion(), '4.3.0') >= 0) { // if (extension_loaded('openssl')) { // $this->scheme = 'ssl'; // $this->debug('Using SSL over OpenSSL'); $this->debug("connect connection_timeout $connection_timeout, response_timeout $response_timeout, scheme $this->scheme, host $this->host, port $this->port"); if ($this->scheme == 'http' || $this->scheme == 'ssl') { // use persistent connection if($this-><API key> && isset($this->fp) && is_resource($this->fp)){ if (!feof($this->fp)) { $this->debug('Re-use persistent connection'); return true; } fclose($this->fp); $this->debug('Closed persistent connection at EOF'); } // munge host if using OpenSSL if ($this->scheme == 'ssl') { $host = 'ssl://' . $this->host; } else { $host = $this->host; } $this->debug('calling fsockopen with host ' . $host . ' connection_timeout ' . $connection_timeout); // open socket if($connection_timeout > 0){ $this->fp = @fsockopen( $host, $this->port, $this->errno, $this->error_str, $connection_timeout); } else { $this->fp = @fsockopen( $host, $this->port, $this->errno, $this->error_str); } // test pointer if(!$this->fp) { $msg = 'Couldn\'t open socket connection to server ' . $this->url; if ($this->errno) { $msg .= ', Error ('.$this->errno.'): '.$this->error_str; } else { $msg .= ' prior to connect(). This is often a problem looking up the host name.'; } $this->debug($msg); $this->setError($msg); return false; } // set response timeout $this->debug('set response timeout to ' . $response_timeout); socket_set_timeout( $this->fp, $response_timeout); $this->debug('socket connected'); return true; } else if ($this->scheme == 'https') { if (!extension_loaded('curl')) { $this->setError('CURL Extension, or OpenSSL extension w/ PHP version >= 4.3 is required for HTTPS'); return false; } $this->debug('connect using https'); // init CURL $this->ch = curl_init(); // set url $hostURL = ($this->port != '') ? "https: // add path $hostURL .= $this->path; curl_setopt($this->ch, CURLOPT_URL, $hostURL); // follow location headers (re-directs) curl_setopt($this->ch, <API key>, 1); // ask for headers in the response output curl_setopt($this->ch, CURLOPT_HEADER, 1); // ask for the response output as the return value curl_setopt($this->ch, <API key>, 1); // encode // We manage this ourselves through headers and encoding // if(function_exists('gzuncompress')){ // curl_setopt($this->ch, CURLOPT_ENCODING, 'deflate'); // persistent connection if ($this-><API key>) { // The way we send data, we cannot use persistent connections, since // there will be some "junk" at the end of our request. //curl_setopt($this->ch, <API key>, true); $this-><API key> = false; $this->outgoing_headers['Connection'] = 'close'; $this->debug('set Connection: ' . $this->outgoing_headers['Connection']); } // set timeout if ($connection_timeout != 0) { curl_setopt($this->ch, CURLOPT_TIMEOUT, $connection_timeout); } // TODO: cURL has added a connection timeout separate from the response timeout //if ($connection_timeout != 0) { // curl_setopt($this->ch, <API key>, $connection_timeout); //if ($response_timeout != 0) { // curl_setopt($this->ch, CURLOPT_TIMEOUT, $response_timeout); // recent versions of cURL turn on peer/host checking by default, // while PHP binaries are not compiled with a default location for the // CA cert bundle, so disable peer/host checking. //curl_setopt($this->ch, CURLOPT_CAINFO, 'f:\php-4.3.2-win32\extensions\curl-ca-bundle.crt'); curl_setopt($this->ch, <API key>, 0); curl_setopt($this->ch, <API key>, 0); // support client certificates (thanks Tobias Boes, Doug Anarino, Eryan Ariobowo) if ($this->authtype == 'certificate') { if (isset($this->certRequest['cainfofile'])) { curl_setopt($this->ch, CURLOPT_CAINFO, $this->certRequest['cainfofile']); } if (isset($this->certRequest['verifypeer'])) { curl_setopt($this->ch, <API key>, $this->certRequest['verifypeer']); } else { curl_setopt($this->ch, <API key>, 1); } if (isset($this->certRequest['verifyhost'])) { curl_setopt($this->ch, <API key>, $this->certRequest['verifyhost']); } else { curl_setopt($this->ch, <API key>, 1); } if (isset($this->certRequest['sslcertfile'])) { curl_setopt($this->ch, CURLOPT_SSLCERT, $this->certRequest['sslcertfile']); } if (isset($this->certRequest['sslkeyfile'])) { curl_setopt($this->ch, CURLOPT_SSLKEY, $this->certRequest['sslkeyfile']); } if (isset($this->certRequest['passphrase'])) { curl_setopt($this->ch, <API key> , $this->certRequest['passphrase']); } } $this->debug('cURL connection set up'); return true; } else { $this->setError('Unknown scheme ' . $this->scheme); $this->debug('Unknown scheme ' . $this->scheme); return false; } } /** * send the SOAP message via HTTP * * @param string $data message data * @param integer $timeout set connection timeout in seconds * @param integer $response_timeout set response timeout in seconds * @param array $cookies cookies to send * @return string data * @access public */ function send($data, $timeout=0, $response_timeout=30, $cookies=NULL) { $this->debug('entered send() with data of length: '.strlen($data)); $this->tryagain = true; $tries = 0; while ($this->tryagain) { $this->tryagain = false; if ($tries++ < 2) { // make connnection if (!$this->connect($timeout, $response_timeout)){ return false; } // send request if (!$this->sendRequest($data, $cookies)){ return false; } // get response $respdata = $this->getResponse(); } else { $this->setError('Too many tries to get an OK response'); } } $this->debug('end of send()'); return $respdata; } /** * send the SOAP message via HTTPS 1.0 using CURL * * @param string $msg message data * @param integer $timeout set connection timeout in seconds * @param integer $response_timeout set response timeout in seconds * @param array $cookies cookies to send * @return string data * @access public */ function sendHTTPS($data, $timeout=0, $response_timeout=30, $cookies) { return $this->send($data, $timeout, $response_timeout, $cookies); } /** * if authenticating, set user credentials here * * @param string $username * @param string $password * @param string $authtype (basic, digest, certificate) * @param array $digestRequest (keys must be nonce, nc, realm, qop) * @param array $certRequest (keys must be cainfofile (optional), sslcertfile, sslkeyfile, passphrase, verifypeer (optional), verifyhost (optional): see corresponding options in cURL docs) * @access public */ function setCredentials($username, $password, $authtype = 'basic', $digestRequest = array(), $certRequest = array()) { $this->debug("Set credentials for authtype $authtype"); // cf. RFC 2617 if ($authtype == 'basic') { $this->outgoing_headers['Authorization'] = 'Basic '.base64_encode(str_replace(':','',$username).':'.$password); } elseif ($authtype == 'digest') { if (isset($digestRequest['nonce'])) { $digestRequest['nc'] = isset($digestRequest['nc']) ? $digestRequest['nc']++ : 1; // A1 = unq(username-value) ":" unq(realm-value) ":" passwd $A1 = $username. ':' . (isset($digestRequest['realm']) ? $digestRequest['realm'] : '') . ':' . $password; // H(A1) = MD5(A1) $HA1 = md5($A1); // A2 = Method ":" digest-uri-value $A2 = 'POST:' . $this->digest_uri; // H(A2) $HA2 = md5($A2); // KD(secret, data) = H(concat(secret, ":", data)) // if qop == auth: // request-digest = <"> < KD ( H(A1), unq(nonce-value) // ":" nc-value // ":" unq(cnonce-value) // ":" unq(qop-value) // ":" H(A2) // if qop is missing, // request-digest = <"> < KD ( H(A1), unq(nonce-value) ":" H(A2) ) > <"> $unhashedDigest = ''; $nonce = isset($digestRequest['nonce']) ? $digestRequest['nonce'] : ''; $cnonce = $nonce; if ($digestRequest['qop'] != '') { $unhashedDigest = $HA1 . ':' . $nonce . ':' . sprintf("%08d", $digestRequest['nc']) . ':' . $cnonce . ':' . $digestRequest['qop'] . ':' . $HA2; } else { $unhashedDigest = $HA1 . ':' . $nonce . ':' . $HA2; } $hashedDigest = md5($unhashedDigest); $this->outgoing_headers['Authorization'] = 'Digest username="' . $username . '", realm="' . $digestRequest['realm'] . '", nonce="' . $nonce . '", uri="' . $this->digest_uri . '", cnonce="' . $cnonce . '", nc=' . sprintf("%08x", $digestRequest['nc']) . ', qop="' . $digestRequest['qop'] . '", response="' . $hashedDigest . '"'; } } elseif ($authtype == 'certificate') { $this->certRequest = $certRequest; } $this->username = $username; $this->password = $password; $this->authtype = $authtype; $this->digestRequest = $digestRequest; if (isset($this->outgoing_headers['Authorization'])) { $this->debug('set Authorization: ' . substr($this->outgoing_headers['Authorization'], 0, 12) . '...'); } else { $this->debug('Authorization header not set'); } } /** * set the soapaction value * * @param string $soapaction * @access public */ function setSOAPAction($soapaction) { $this->outgoing_headers['SOAPAction'] = '"' . $soapaction . '"'; $this->debug('set SOAPAction: ' . $this->outgoing_headers['SOAPAction']); } /** * use http encoding * * @param string $enc encoding style. supported values: gzip, deflate, or both * @access public */ function setEncoding($enc='gzip, deflate') { if (function_exists('gzdeflate')) { $this->protocol_version = '1.1'; $this->outgoing_headers['Accept-Encoding'] = $enc; $this->debug('set Accept-Encoding: ' . $this->outgoing_headers['Accept-Encoding']); if (!isset($this->outgoing_headers['Connection'])) { $this->outgoing_headers['Connection'] = 'close'; $this-><API key> = false; $this->debug('set Connection: ' . $this->outgoing_headers['Connection']); } $magic_quotes = <API key>(); if($magic_quotes){ ini_set('<API key>', 0); } // deprecated $this->encoding = $enc; } } /** * set proxy info here * * @param string $proxyhost * @param string $proxyport * @param string $proxyusername * @param string $proxypassword * @access public */ function setProxy($proxyhost, $proxyport, $proxyusername = '', $proxypassword = '') { $this->uri = $this->url; $this->host = $proxyhost; $this->port = $proxyport; if ($proxyusername != '' && $proxypassword != '') { $this->outgoing_headers['Proxy-Authorization'] = ' Basic '.base64_encode($proxyusername.':'.$proxypassword); $this->debug('set Proxy-Authorization: ' . $this->outgoing_headers['Proxy-Authorization']); } } /** * decode a string that is encoded w/ "chunked' transfer encoding * as defined in RFC2068 19.4.6 * * @param string $buffer * @param string $lb * @returns string * @access public * @deprecated */ function decodeChunked($buffer, $lb){ // length := 0 $length = 0; $new = ''; // read chunk-size, chunk-extension (if any) and CRLF // get the position of the linebreak $chunkend = strpos($buffer, $lb); if ($chunkend == FALSE) { $this->debug('no linebreak found in decodeChunked'); return $new; } $temp = substr($buffer,0,$chunkend); $chunk_size = hexdec( trim($temp) ); $chunkstart = $chunkend + strlen($lb); // while (chunk-size > 0) { while ($chunk_size > 0) { $this->debug("chunkstart: $chunkstart chunk_size: $chunk_size"); $chunkend = strpos( $buffer, $lb, $chunkstart + $chunk_size); // Just in case we got a broken connection if ($chunkend == FALSE) { $chunk = substr($buffer,$chunkstart); // append chunk-data to entity-body $new .= $chunk; $length += strlen($chunk); break; } // read chunk-data and CRLF $chunk = substr($buffer,$chunkstart,$chunkend-$chunkstart); // append chunk-data to entity-body $new .= $chunk; // length := length + chunk-size $length += strlen($chunk); // read chunk-size and CRLF $chunkstart = $chunkend + strlen($lb); $chunkend = strpos($buffer, $lb, $chunkstart) + strlen($lb); if ($chunkend == FALSE) { break; //Just in case we got a broken connection } $temp = substr($buffer,$chunkstart,$chunkend-$chunkstart); $chunk_size = hexdec( trim($temp) ); $chunkstart = $chunkend; } return $new; } /* * Writes payload, including HTTP headers, to $this->outgoing_payload. */ function buildPayload($data, $cookie_str = '') { // add content-length header $this->outgoing_headers['Content-Length'] = strlen($data); $this->debug('set Content-Length: ' . $this->outgoing_headers['Content-Length']); // start building outgoing payload: $req = "$this->request_method $this->uri HTTP/$this->protocol_version"; $this->debug("HTTP request: $req"); $this->outgoing_payload = "$req\r\n"; // loop thru headers, serializing foreach($this->outgoing_headers as $k => $v){ $hdr = $k.': '.$v; $this->debug("HTTP header: $hdr"); $this->outgoing_payload .= "$hdr\r\n"; } // add any cookies if ($cookie_str != '') { $hdr = 'Cookie: '.$cookie_str; $this->debug("HTTP header: $hdr"); $this->outgoing_payload .= "$hdr\r\n"; } // header/body separator $this->outgoing_payload .= "\r\n"; // add data $this->outgoing_payload .= $data; } function sendRequest($data, $cookies = NULL) { // build cookie string $cookie_str = $this-><API key>($cookies, (($this->scheme == 'ssl') || ($this->scheme == 'https'))); // build payload $this->buildPayload($data, $cookie_str); if ($this->scheme == 'http' || $this->scheme == 'ssl') { // send payload if(!fputs($this->fp, $this->outgoing_payload, strlen($this->outgoing_payload))) { $this->setError('couldn\'t write message data to socket'); $this->debug('couldn\'t write message data to socket'); return false; } $this->debug('wrote data to socket, length = ' . strlen($this->outgoing_payload)); return true; } else if ($this->scheme == 'https') { // set payload // TODO: cURL does say this should only be the verb, and in fact it // turns out that the URI and HTTP version are appended to this, which // some servers refuse to work with //curl_setopt($this->ch, <API key>, $this->outgoing_payload); foreach($this->outgoing_headers as $k => $v){ $curl_headers[] = "$k: $v"; } if ($cookie_str != '') { $curl_headers[] = 'Cookie: ' . $cookie_str; } curl_setopt($this->ch, CURLOPT_HTTPHEADER, $curl_headers); if ($this->request_method == "POST") { curl_setopt($this->ch, CURLOPT_POST, 1); curl_setopt($this->ch, CURLOPT_POSTFIELDS, $data); } else { } $this->debug('set cURL payload'); return true; } } function getResponse(){ $this->incoming_payload = ''; if ($this->scheme == 'http' || $this->scheme == 'ssl') { // loop until headers have been retrieved $data = ''; while (!isset($lb)){ // We might EOF during header read. if(feof($this->fp)) { $this->incoming_payload = $data; $this->debug('found no headers before EOF after length ' . strlen($data)); $this->debug("received before EOF:\n" . $data); $this->setError('server failed to send headers'); return false; } $tmp = fgets($this->fp, 256); $tmplen = strlen($tmp); $this->debug("read line of $tmplen bytes: " . trim($tmp)); if ($tmplen == 0) { $this->incoming_payload = $data; $this->debug('socket read of headers timed out after length ' . strlen($data)); $this->debug("read before timeout: " . $data); $this->setError('socket read of headers timed out'); return false; } $data .= $tmp; $pos = strpos($data,"\r\n\r\n"); if($pos > 1){ $lb = "\r\n"; } else { $pos = strpos($data,"\n\n"); if($pos > 1){ $lb = "\n"; } } // remove 100 header if(isset($lb) && ereg('^HTTP/1.1 100',$data)){ unset($lb); $data = ''; } } // store header data $this->incoming_payload .= $data; $this->debug('found end of headers after length ' . strlen($data)); // process headers $header_data = trim(substr($data,0,$pos)); $header_array = explode($lb,$header_data); $this->incoming_headers = array(); $this->incoming_cookies = array(); foreach($header_array as $header_line){ $arr = explode(':',$header_line, 2); if(count($arr) > 1){ $header_name = strtolower(trim($arr[0])); $this->incoming_headers[$header_name] = trim($arr[1]); if ($header_name == 'set-cookie') { // TODO: allow multiple cookies from parseCookie $cookie = $this->parseCookie(trim($arr[1])); if ($cookie) { $this->incoming_cookies[] = $cookie; $this->debug('found cookie: ' . $cookie['name'] . ' = ' . $cookie['value']); } else { $this->debug('did not find cookie in ' . trim($arr[1])); } } } else if (isset($header_name)) { // append continuation line to previous header $this->incoming_headers[$header_name] .= $lb . ' ' . $header_line; } } // loop until msg has been received if (isset($this->incoming_headers['transfer-encoding']) && strtolower($this->incoming_headers['transfer-encoding']) == 'chunked') { $content_length = 2147483647; // ignore any content-length header $chunked = true; $this->debug("want to read chunked content"); } elseif (isset($this->incoming_headers['content-length'])) { $content_length = $this->incoming_headers['content-length']; $chunked = false; $this->debug("want to read content of length $content_length"); } else { $content_length = 2147483647; $chunked = false; $this->debug("want to read content to EOF"); } $data = ''; do { if ($chunked) { $tmp = fgets($this->fp, 256); $tmplen = strlen($tmp); $this->debug("read chunk line of $tmplen bytes"); if ($tmplen == 0) { $this->incoming_payload = $data; $this->debug('socket read of chunk length timed out after length ' . strlen($data)); $this->debug("read before timeout:\n" . $data); $this->setError('socket read of chunk length timed out'); return false; } $content_length = hexdec(trim($tmp)); $this->debug("chunk length $content_length"); } $strlen = 0; while (($strlen < $content_length) && (!feof($this->fp))) { $readlen = min(8192, $content_length - $strlen); $tmp = fread($this->fp, $readlen); $tmplen = strlen($tmp); $this->debug("read buffer of $tmplen bytes"); if (($tmplen == 0) && (!feof($this->fp))) { $this->incoming_payload = $data; $this->debug('socket read of body timed out after length ' . strlen($data)); $this->debug("read before timeout:\n" . $data); $this->setError('socket read of body timed out'); return false; } $strlen += $tmplen; $data .= $tmp; } if ($chunked && ($content_length > 0)) { $tmp = fgets($this->fp, 256); $tmplen = strlen($tmp); $this->debug("read chunk terminator of $tmplen bytes"); if ($tmplen == 0) { $this->incoming_payload = $data; $this->debug('socket read of chunk terminator timed out after length ' . strlen($data)); $this->debug("read before timeout:\n" . $data); $this->setError('socket read of chunk terminator timed out'); return false; } } } while ($chunked && ($content_length > 0) && (!feof($this->fp))); if (feof($this->fp)) { $this->debug('read to EOF'); } $this->debug('read body of length ' . strlen($data)); $this->incoming_payload .= $data; $this->debug('received a total of '.strlen($this->incoming_payload).' bytes of data from server'); // close filepointer if( (isset($this->incoming_headers['connection']) && strtolower($this->incoming_headers['connection']) == 'close') || (! $this-><API key>) || feof($this->fp)){ fclose($this->fp); $this->fp = false; $this->debug('closed socket'); } // connection was closed unexpectedly if($this->incoming_payload == ''){ $this->setError('no response from server'); return false; } // decode transfer-encoding // if(isset($this->incoming_headers['transfer-encoding']) && strtolower($this->incoming_headers['transfer-encoding']) == 'chunked'){ // if(!$data = $this->decodeChunked($data, $lb)){ // $this->setError('Decoding of chunked data failed'); // return false; // set decoded payload // $this->incoming_payload = $header_data.$lb.$lb.$data; } else if ($this->scheme == 'https') { // send and receive $this->debug('send and receive with cURL'); $this->incoming_payload = curl_exec($this->ch); $data = $this->incoming_payload; $cErr = curl_error($this->ch); if ($cErr != '') { $err = 'cURL ERROR: '.curl_errno($this->ch).': '.$cErr.'<br />'; // TODO: there is a PHP bug that can cause this to SEGV for <API key> foreach(curl_getinfo($this->ch) as $k => $v){ $err .= "$k: $v<br />"; } $this->debug($err); $this->setError($err); curl_close($this->ch); return false; } else { //echo '<pre>'; //var_dump(curl_getinfo($this->ch)); //echo '</pre>'; } // close curl $this->debug('No cURL error, closing cURL'); curl_close($this->ch); // remove 100 header(s) while (ereg('^HTTP/1.1 100',$data)) { if ($pos = strpos($data,"\r\n\r\n")) { $data = ltrim(substr($data,$pos)); } elseif($pos = strpos($data,"\n\n") ) { $data = ltrim(substr($data,$pos)); } } // separate content from HTTP headers if ($pos = strpos($data,"\r\n\r\n")) { $lb = "\r\n"; } elseif( $pos = strpos($data,"\n\n")) { $lb = "\n"; } else { $this->debug('no proper separation of headers and document'); $this->setError('no proper separation of headers and document'); return false; } $header_data = trim(substr($data,0,$pos)); $header_array = explode($lb,$header_data); $data = ltrim(substr($data,$pos)); $this->debug('found proper separation of headers and document'); $this->debug('cleaned data, stringlen: '.strlen($data)); // clean headers foreach ($header_array as $header_line) { $arr = explode(':',$header_line,2); if(count($arr) > 1){ $header_name = strtolower(trim($arr[0])); $this->incoming_headers[$header_name] = trim($arr[1]); if ($header_name == 'set-cookie') { // TODO: allow multiple cookies from parseCookie $cookie = $this->parseCookie(trim($arr[1])); if ($cookie) { $this->incoming_cookies[] = $cookie; $this->debug('found cookie: ' . $cookie['name'] . ' = ' . $cookie['value']); } else { $this->debug('did not find cookie in ' . trim($arr[1])); } } } else if (isset($header_name)) { // append continuation line to previous header $this->incoming_headers[$header_name] .= $lb . ' ' . $header_line; } } } $arr = explode(' ', $header_array[0], 3); $http_version = $arr[0]; $http_status = intval($arr[1]); $http_reason = count($arr) > 2 ? $arr[2] : ''; // see if we need to resend the request with http digest authentication if (isset($this->incoming_headers['location']) && $http_status == 301) { $this->debug("Got 301 $http_reason with Location: " . $this->incoming_headers['location']); $this->setURL($this->incoming_headers['location']); $this->tryagain = true; return false; } // see if we need to resend the request with http digest authentication if (isset($this->incoming_headers['www-authenticate']) && $http_status == 401) { $this->debug("Got 401 $http_reason with WWW-Authenticate: " . $this->incoming_headers['www-authenticate']); if (strstr($this->incoming_headers['www-authenticate'], "Digest ")) { $this->debug('Server wants digest authentication'); // remove "Digest " from our elements $digestString = str_replace('Digest ', '', $this->incoming_headers['www-authenticate']); // parse elements into array $digestElements = explode(',', $digestString); foreach ($digestElements as $val) { $tempElement = explode('=', trim($val), 2); $digestRequest[$tempElement[0]] = str_replace("\"", '', $tempElement[1]); } // should have (at least) qop, realm, nonce if (isset($digestRequest['nonce'])) { $this->setCredentials($this->username, $this->password, 'digest', $digestRequest); $this->tryagain = true; return false; } } $this->debug('HTTP authentication failed'); $this->setError('HTTP authentication failed'); return false; } if ( ($http_status >= 300 && $http_status <= 307) || ($http_status >= 400 && $http_status <= 417) || ($http_status >= 501 && $http_status <= 505) ) { $this->setError("Unsupported HTTP response status $http_status $http_reason (soapclient->response has contents of the response)"); return false; } // decode content-encoding if(isset($this->incoming_headers['content-encoding']) && $this->incoming_headers['content-encoding'] != ''){ if(strtolower($this->incoming_headers['content-encoding']) == 'deflate' || strtolower($this->incoming_headers['content-encoding']) == 'gzip'){ // if decoding works, use it. else assume data wasn't gzencoded if(function_exists('gzinflate')){ //$timer->setMarker('starting decoding of gzip/deflated content'); // IIS 5 requires gzinflate instead of gzuncompress (similar to IE 5 and gzdeflate v. gzcompress) // this means there are no Zlib headers, although there should be $this->debug('The gzinflate function exists'); $datalen = strlen($data); if ($this->incoming_headers['content-encoding'] == 'deflate') { if ($degzdata = @gzinflate($data)) { $data = $degzdata; $this->debug('The payload has been inflated to ' . strlen($data) . ' bytes'); if (strlen($data) < $datalen) { // test for the case that the payload has been compressed twice $this->debug('The inflated payload is smaller than the gzipped one; try again'); if ($degzdata = @gzinflate($data)) { $data = $degzdata; $this->debug('The payload has been inflated again to ' . strlen($data) . ' bytes'); } } } else { $this->debug('Error using gzinflate to inflate the payload'); $this->setError('Error using gzinflate to inflate the payload'); } } elseif ($this->incoming_headers['content-encoding'] == 'gzip') { if ($degzdata = @gzinflate(substr($data, 10))) { // do our best $data = $degzdata; $this->debug('The payload has been un-gzipped to ' . strlen($data) . ' bytes'); if (strlen($data) < $datalen) { // test for the case that the payload has been compressed twice $this->debug('The un-gzipped payload is smaller than the gzipped one; try again'); if ($degzdata = @gzinflate(substr($data, 10))) { $data = $degzdata; $this->debug('The payload has been un-gzipped again to ' . strlen($data) . ' bytes'); } } } else { $this->debug('Error using gzinflate to un-gzip the payload'); $this->setError('Error using gzinflate to un-gzip the payload'); } } //$timer->setMarker('finished decoding of gzip/deflated content'); // set decoded payload $this->incoming_payload = $header_data.$lb.$lb.$data; } else { $this->debug('The server sent compressed data. Your php install must have the Zlib extension compiled in to support this.'); $this->setError('The server sent compressed data. Your php install must have the Zlib extension compiled in to support this.'); } } else { $this->debug('Unsupported Content-Encoding ' . $this->incoming_headers['content-encoding']); $this->setError('Unsupported Content-Encoding ' . $this->incoming_headers['content-encoding']); } } else { $this->debug('No Content-Encoding header'); } if(strlen($data) == 0){ $this->debug('no data after headers!'); $this->setError('no data present after HTTP headers'); return false; } return $data; } function setContentType($type, $charset = false) { $this->outgoing_headers['Content-Type'] = $type . ($charset ? '; charset=' . $charset : ''); $this->debug('set Content-Type: ' . $this->outgoing_headers['Content-Type']); } function <API key>(){ if (isset($this->outgoing_headers['Accept-Encoding'])) { return false; } $this->protocol_version = '1.1'; $this-><API key> = true; $this->outgoing_headers['Connection'] = 'Keep-Alive'; $this->debug('set Connection: ' . $this->outgoing_headers['Connection']); return true; } /** * parse an incoming Cookie into it's parts * * @param string $cookie_str content of cookie * @return array with data of that cookie * @access private */ /* * TODO: allow a Set-Cookie string to be parsed into multiple cookies */ function parseCookie($cookie_str) { $cookie_str = str_replace('; ', ';', $cookie_str) . ';'; $data = explode(';', $cookie_str); $value_str = $data[0]; $cookie_param = 'domain='; $start = strpos($cookie_str, $cookie_param); if ($start > 0) { $domain = substr($cookie_str, $start + strlen($cookie_param)); $domain = substr($domain, 0, strpos($domain, ';')); } else { $domain = ''; } $cookie_param = 'expires='; $start = strpos($cookie_str, $cookie_param); if ($start > 0) { $expires = substr($cookie_str, $start + strlen($cookie_param)); $expires = substr($expires, 0, strpos($expires, ';')); } else { $expires = ''; } $cookie_param = 'path='; $start = strpos($cookie_str, $cookie_param); if ( $start > 0 ) { $path = substr($cookie_str, $start + strlen($cookie_param)); $path = substr($path, 0, strpos($path, ';')); } else { $path = '/'; } $cookie_param = ';secure;'; if (strpos($cookie_str, $cookie_param) !== FALSE) { $secure = true; } else { $secure = false; } $sep_pos = strpos($value_str, '='); if ($sep_pos) { $name = substr($value_str, 0, $sep_pos); $value = substr($value_str, $sep_pos + 1); $cookie= array( 'name' => $name, 'value' => $value, 'domain' => $domain, 'path' => $path, 'expires' => $expires, 'secure' => $secure ); return $cookie; } return false; } /** * sort out cookies for the current request * * @param array $cookies array with all cookies * @param boolean $secure is the send-content secure or not? * @return string for Cookie-HTTP-Header * @access private */ function <API key>($cookies, $secure=false) { $cookie_str = ''; if ((! is_null($cookies)) && (is_array($cookies))) { foreach ($cookies as $cookie) { if (! is_array($cookie)) { continue; } $this->debug("check cookie for validity: ".$cookie['name'].'='.$cookie['value']); if ((isset($cookie['expires'])) && (! empty($cookie['expires']))) { if (strtotime($cookie['expires']) <= time()) { $this->debug('cookie has expired'); continue; } } if ((isset($cookie['domain'])) && (! empty($cookie['domain']))) { $domain = preg_quote($cookie['domain']); if (! preg_match("'.*$domain$'i", $this->host)) { $this->debug('cookie has different domain'); continue; } } if ((isset($cookie['path'])) && (! empty($cookie['path']))) { $path = preg_quote($cookie['path']); if (! preg_match("'^$path.*'i", $this->path)) { $this->debug('cookie is for a different path'); continue; } } if ((! $secure) && (isset($cookie['secure'])) && ($cookie['secure'])) { $this->debug('cookie is secure, transport is not'); continue; } $cookie_str .= $cookie['name'] . '=' . $cookie['value'] . '; '; $this->debug('add cookie to Cookie-String: ' . $cookie['name'] . '=' . $cookie['value']); } } return $cookie_str; } } ?>
Imports System Imports System.Runtime.Serialization Imports System.Collections Imports System.Xml Imports System.IO Namespace QueryObjects <Serializable()> Public Class SalesOrderQuery Implements IQuery Const _BusinessObject As String = "SORQID" #Region "Private Object Members" Private _xmlData As String Private _xmlOut As String Private _ActionType As CommonEnums.ActionType_Query #End Region #Region "Public Object Properties" Public ReadOnly Property BusinessObject() As String Implements IQuery.BusinessObject Get Return _BusinessObject End Get End Property Public ReadOnly Property xmlData() As String Implements IQuery.xmlData Get Return ConstructXML() End Get End Property Public ReadOnly Property xmlOut() As String Implements IQuery.xmlOut Get Return _xmlOut End Get End Property Public Property ActionType() As CommonEnums.ActionType_Query Implements IQuery.ActionType Get Return _ActionType End Get Set(ByVal value As CommonEnums.ActionType_Query) _ActionType = value End Set End Property #End Region #Region "Private Data Members" Dim _xQuery As String = String.Empty Dim _xOption As String = String.Empty Dim _Reprint As <API key> = <API key>.Reprint_Upper_Y Dim _DocumentType As <API key> = <API key>.<API key> Dim _IncludeForms As <API key> = <API key>.<API key> Dim <API key> As <API key> = <API key>.<API key> Dim _IncludeStockForms As <API key> = <API key>.<API key> Dim _IncludeDetailForms As <API key> = <API key>.<API key> Dim _IncludeNotes As <API key> = <API key>.<API key> Dim _IgnorePrintStatus As <API key> = <API key>.<API key> Dim _RoundMass As <API key> = <API key>.RoundMass_Upper_O Dim _RoundMassDecs As String = String.Empty Dim _RoundVolume As <API key> = <API key>.RoundVolume_Upper_O Dim _RoundVolumeDecs As String = String.Empty Dim _XslStylesheet As String = String.Empty Dim _Filter As String = String.Empty Dim _Branch As String = String.Empty Dim _Branch_FilterType As <API key> = <API key>.<API key> Dim _Branch_FilterValue As String = String.Empty Dim _Customer As String = String.Empty Dim <API key> As <API key> = <API key>.<API key> Dim <API key> As String = String.Empty Dim _SourceWarehouse As String = String.Empty Dim <API key> As <API key> = <API key>.<API key> Dim <API key> As String = String.Empty Dim _TargetWarehouse As String = String.Empty Dim <API key> As <API key> = <API key>.<API key> Dim <API key> As String = String.Empty Dim _OrderType As String = String.Empty Dim <API key> As <API key> = <API key>.<API key> Dim <API key> As String = String.Empty Dim _CustomerPo As String = String.Empty Dim <API key> As <API key> = <API key>.<API key> Dim <API key> As <API key> Dim _InvoiceNumber As String = String.Empty Dim <API key> As <API key> = <API key>.<API key> Dim <API key> As String = String.Empty Dim _GtrReference As String = String.Empty Dim <API key> As <API key> = <API key>.<API key> Dim <API key> As String = String.Empty Dim _SalesOrder As String = String.Empty Dim <API key> As <API key> = <API key>.<API key> Dim <API key> As String = String.Empty Dim _InvoiceDate As String = String.Empty Dim <API key> As <API key> = <API key>.<API key> Dim <API key> As String = String.Empty Dim _xOperator As String = String.Empty Dim <API key> As <API key> = <API key>.<API key> Dim <API key> As String = String.Empty Dim _GeographicArea As String = String.Empty Dim <API key> As <API key> = <API key>.<API key> #End Region #Region "Public Properties" ''' <summary> ''' This is the root element. ''' </summary> ''' <returns></returns> ''' <remarks></remarks> Public Property xQuery() As String Get Return _xQuery End Get Set(ByVal Value As String) _xQuery = Value End Set End Property ''' <summary> ''' List of options. ''' </summary> ''' <returns></returns> ''' <remarks></remarks> Public Property xOption() As String Get Return _xOption End Get Set(ByVal Value As String) _xOption = Value End Set End Property ''' <summary> ''' This indicates if an original document is to be returned, or one which has already been printed or presented as XML. Valid entries are 'N' and 'Y'. Default is 'Y'. ''' </summary> ''' <returns></returns> ''' <remarks></remarks> Public Property Reprint() As <API key> Get Return _Reprint End Get Set(ByVal Value As <API key>) _Reprint = Value End Set End Property ''' <summary> ''' The type of document to be returned - 'I- Invoice, C- Credit Note, D - Debit Note, G - Goods in Transit Supply Chain Transfer - default is 'I' ''' </summary> ''' <returns></returns> ''' <remarks></remarks> Public Property DocumentType() As <API key> Get Return _DocumentType End Get Set(ByVal Value As <API key>) _DocumentType = Value End Set End Property ''' <summary> ''' This element determines whether custom form information attached to the sales order should be returned. Valid entries are 'N' - no, and 'Y' - yes. The default is 'N'. ''' </summary> ''' <returns></returns> ''' <remarks></remarks> Public Property IncludeForms() As <API key> Get Return _IncludeForms End Get Set(ByVal Value As <API key>) _IncludeForms = Value End Set End Property ''' <summary> ''' This element determines whether custom form information for the invoice customer should be returned. Valid entries are 'N' - no, and 'Y' - yes. The default is 'N'. ''' </summary> ''' <returns></returns> ''' <remarks></remarks> Public Property <API key>() As <API key> Get Return <API key> End Get Set(ByVal Value As <API key>) <API key> = Value End Set End Property ''' <summary> ''' This element determines whether custom form information for the stock code on a detail stocked merchandise line should be returned. Valid entries are 'N' - no, and 'Y' - yes. The default is 'N'. ''' </summary> ''' <returns></returns> ''' <remarks></remarks> Public Property IncludeStockForms() As <API key> Get Return _IncludeStockForms End Get Set(ByVal Value As <API key>) _IncludeStockForms = Value End Set End Property ''' <summary> ''' This element determines whether custom form information for the detail merchandise line should be returned. Valid entries are 'N' - no, and 'Y' - yes. The default is 'N'. ''' </summary> ''' <returns></returns> ''' <remarks></remarks> Public Property IncludeDetailForms() As <API key> Get Return _IncludeDetailForms End Get Set(ByVal Value As <API key>) _IncludeDetailForms = Value End Set End Property ''' <summary> ''' This element determines whether notepad information attached to the invoice sales order should be returned. Valid entries are 'N' - no, and 'Y' - yes. The default is 'N'. ''' </summary> ''' <returns></returns> ''' <remarks></remarks> Public Property IncludeNotes() As <API key> Get Return _IncludeNotes End Get Set(ByVal Value As <API key>) _IncludeNotes = Value End Set End Property ''' <summary> ''' If this element is set to 'Y', it will over-ride the contents of the 'Reprint' option. Any invoices selected through other criteria will be returned, regardless of the print status for the document. ''' </summary> ''' <returns></returns> ''' <remarks></remarks> Public Property IgnorePrintStatus() As <API key> Get Return _IgnorePrintStatus End Get Set(ByVal Value As <API key>) _IgnorePrintStatus = Value End Set End Property ''' <summary> ''' This element controls the rounding of the mass on individual merchandise lines. The rounded figure is added to the total mass for the document. The number of decimals is controlled by the 'RoundMassDecs' option. The rounding is O - 'off', 'U' - up, or 'D' down. ''' </summary> ''' <returns></returns> ''' <remarks></remarks> Public Property RoundMass() As <API key> Get Return _RoundMass End Get Set(ByVal Value As <API key>) _RoundMass = Value End Set End Property ''' <summary> ''' This controls the number of decimals used in the rounding of mass as described in 'RoundMass'. A single digit in the range 0 to 6 must be provided. If this element is not used, then the number of decimal places in the mass (currently 6) is used. ''' </summary> ''' <returns></returns> ''' <remarks></remarks> Public Property RoundMassDecs() As String Get Return _RoundMassDecs End Get Set(ByVal Value As String) _RoundMassDecs = Value End Set End Property ''' <summary> ''' This element controls the rounding of the volume on individual merchandise lines. The rounded figure is added to the total volume for the document. The number of decimals is controlled by the 'RoundVolumeDecs' option. The rounding is 'O' - off, 'U' - up, or 'D' down. ''' </summary> ''' <returns></returns> ''' <remarks></remarks> Public Property RoundVolume() As <API key> Get Return _RoundVolume End Get Set(ByVal Value As <API key>) _RoundVolume = Value End Set End Property ''' <summary> ''' This controls the number of decimals used in the rounding of volume as described in 'RoundVolume'. A single digit in the range 0 to 6 must be provided. If this element is not used, then the number of decimal places in the volume (currently 6) is used. ''' </summary> ''' <returns></returns> ''' <remarks></remarks> Public Property RoundVolumeDecs() As String Get Return _RoundVolumeDecs End Get Set(ByVal Value As String) _RoundVolumeDecs = Value End Set End Property ''' <summary> ''' The XSL Stylesheet to be used ''' </summary> ''' <returns></returns> ''' <remarks></remarks> Public Property XslStylesheet() As String Get Return _XslStylesheet End Get Set(ByVal Value As String) _XslStylesheet = Value End Set End Property ''' <summary> ''' This contains one or more filters to restrict the number of documents returned. ''' </summary> ''' <returns></returns> ''' <remarks></remarks> Public Property Filter() As String Get Return _Filter End Get Set(ByVal Value As String) _Filter = Value End Set End Property ''' <summary> ''' Branch to be selected (FilterType of A - All, R - Range or S - Single branch, FilterValue contains a range of branches separated by commas if FilterType is R or a single branch if S). ''' </summary> ''' <returns></returns> ''' <remarks></remarks> Public Property Branch() As String Get Return _Branch End Get Set(ByVal Value As String) _Branch = Value End Set End Property ''' <summary> ''' </summary> ''' <returns></returns> ''' <remarks></remarks> Public Property Branch_FilterType() As <API key> Get Return _Branch_FilterType End Get Set(ByVal Value As <API key>) _Branch_FilterType = Value End Set End Property ''' <summary> ''' </summary> ''' <returns></returns> ''' <remarks></remarks> Public Property Branch_FilterValue() As String Get Return _Branch_FilterValue End Get Set(ByVal Value As String) _Branch_FilterValue = Value End Set End Property ''' <summary> ''' Customer to be selected (FilterType of A - All, R - Range or L - List of customers, FilterValue contains a range or list of customers separated by commas if FilterType is R or L). ''' </summary> ''' <returns></returns> ''' <remarks></remarks> Public Property Customer() As String Get Return _Customer End Get Set(ByVal Value As String) _Customer = Value End Set End Property ''' <summary> ''' </summary> ''' <returns></returns> ''' <remarks></remarks> Public Property Customer_FilterType() As <API key> Get Return <API key> End Get Set(ByVal Value As <API key>) <API key> = Value End Set End Property ''' <summary> ''' </summary> ''' <returns></returns> ''' <remarks></remarks> Public Property <API key>() As String Get Return <API key> End Get Set(ByVal Value As String) <API key> = Value End Set End Property ''' <summary> ''' Warehouse to be selected (FilterType of A - All, R - Range or L - List of warehouses, FilterValue contains a range or list of warehouses separated by commas if FilterType is R or L). This only applies to a Goods in Transit transfer, and is applied to the source warehouse ''' </summary> ''' <returns></returns> ''' <remarks></remarks> Public Property SourceWarehouse() As String Get Return _SourceWarehouse End Get Set(ByVal Value As String) _SourceWarehouse = Value End Set End Property ''' <summary> ''' </summary> ''' <returns></returns> ''' <remarks></remarks> Public Property <API key>() As <API key> Get Return <API key> End Get Set(ByVal Value As <API key>) <API key> = Value End Set End Property ''' <summary> ''' </summary> ''' <returns></returns> ''' <remarks></remarks> Public Property <API key>() As String Get Return <API key> End Get Set(ByVal Value As String) <API key> = Value End Set End Property ''' <summary> ''' Warehouse to be selected (FilterType of A - All, R - Range or L - List of warehouses, FilterValue contains a range or list of warehouses separated by commas if FilterType is R or L). This only applies to a Goods in Transit transfer, and is applied to the target warehouse ''' </summary> ''' <returns></returns> ''' <remarks></remarks> Public Property TargetWarehouse() As String Get Return _TargetWarehouse End Get Set(ByVal Value As String) _TargetWarehouse = Value End Set End Property ''' <summary> ''' </summary> ''' <returns></returns> ''' <remarks></remarks> Public Property <API key>() As <API key> Get Return <API key> End Get Set(ByVal Value As <API key>) <API key> = Value End Set End Property ''' <summary> ''' </summary> ''' <returns></returns> ''' <remarks></remarks> Public Property <API key>() As String Get Return <API key> End Get Set(ByVal Value As String) <API key> = Value End Set End Property ''' <summary> ''' Order type to be selected (FilterType of A - All, R - Range or S - Single order types, FilterValue contains a range of order types separated by commas if FilterType is R or a single order type if S). ''' </summary> ''' <returns></returns> ''' <remarks></remarks> Public Property OrderType() As String Get Return _OrderType End Get Set(ByVal Value As String) _OrderType = Value End Set End Property ''' <summary> ''' </summary> ''' <returns></returns> ''' <remarks></remarks> Public Property <API key>() As <API key> Get Return <API key> End Get Set(ByVal Value As <API key>) <API key> = Value End Set End Property ''' <summary> ''' </summary> ''' <returns></returns> ''' <remarks></remarks> Public Property <API key>() As String Get Return <API key> End Get Set(ByVal Value As String) <API key> = Value End Set End Property ''' <summary> ''' Customer purchase order number to be selected (FilterType of A - All, S - Single p/o number, FilterValue contains the selected p/o number if FilterType is S). ''' </summary> ''' <returns></returns> ''' <remarks></remarks> Public Property CustomerPo() As String Get Return _CustomerPo End Get Set(ByVal Value As String) _CustomerPo = Value End Set End Property ''' <summary> ''' </summary> ''' <returns></returns> ''' <remarks></remarks> Public Property <API key>() As <API key> Get Return <API key> End Get Set(ByVal Value As <API key>) <API key> = Value End Set End Property ''' <summary> ''' </summary> ''' <returns></returns> ''' <remarks></remarks> Public Property <API key>() As <API key> Get Return <API key> End Get Set(ByVal Value As <API key>) <API key> = Value End Set End Property ''' <summary> ''' Invoice to be selected (FilterType of A - All, R - Range or L - List of invoice numbers, FilterValue contains a range or list of invoice numbers separated by commas if FilterType is R or L). ''' </summary> ''' <returns></returns> ''' <remarks></remarks> Public Property InvoiceNumber() As String Get Return _InvoiceNumber End Get Set(ByVal Value As String) _InvoiceNumber = Value End Set End Property ''' <summary> ''' </summary> ''' <returns></returns> ''' <remarks></remarks> Public Property <API key>() As <API key> Get Return <API key> End Get Set(ByVal Value As <API key>) <API key> = Value End Set End Property ''' <summary> ''' </summary> ''' <returns></returns> ''' <remarks></remarks> Public Property <API key>() As String Get Return <API key> End Get Set(ByVal Value As String) <API key> = Value End Set End Property ''' <summary> ''' Goods in transit number to be selected (FilterType of A - All, R - Range or L - List of numbers, FilterValue contains a range or list of numbers separated by commas if FilterType is R or L). This is only used if Document Type is 'S' - Supply Chain Transfer ''' </summary> ''' <returns></returns> ''' <remarks></remarks> Public Property GtrReference() As String Get Return _GtrReference End Get Set(ByVal Value As String) _GtrReference = Value End Set End Property ''' <summary> ''' </summary> ''' <returns></returns> ''' <remarks></remarks> Public Property <API key>() As <API key> Get Return <API key> End Get Set(ByVal Value As <API key>) <API key> = Value End Set End Property ''' <summary> ''' </summary> ''' <returns></returns> ''' <remarks></remarks> Public Property <API key>() As String Get Return <API key> End Get Set(ByVal Value As String) <API key> = Value End Set End Property ''' <summary> ''' Sales order to be selected (FilterType of A - All, R - Range or L - List of sales orders, FilterValue contains a range or list of sales orders separated by commas if FilterType is R or L). ''' </summary> ''' <returns></returns> ''' <remarks></remarks> Public Property SalesOrder() As String Get Return _SalesOrder End Get Set(ByVal Value As String) _SalesOrder = Value End Set End Property ''' <summary> ''' </summary> ''' <returns></returns> ''' <remarks></remarks> Public Property <API key>() As <API key> Get Return <API key> End Get Set(ByVal Value As <API key>) <API key> = Value End Set End Property ''' <summary> ''' </summary> ''' <returns></returns> ''' <remarks></remarks> Public Property <API key>() As String Get Return <API key> End Get Set(ByVal Value As String) <API key> = Value End Set End Property ''' <summary> ''' Invoice date to be selected (FilterType of A - All, R - Range or S - Single invoice date, FilterValue contains a range of invoice dates separated by commas if FilterType is R or a single sales order date if S). ''' </summary> ''' <returns></returns> ''' <remarks></remarks> Public Property InvoiceDate() As String Get Return _InvoiceDate End Get Set(ByVal Value As String) _InvoiceDate = Value End Set End Property ''' <summary> ''' </summary> ''' <returns></returns> ''' <remarks></remarks> Public Property <API key>() As <API key> Get Return <API key> End Get Set(ByVal Value As <API key>) <API key> = Value End Set End Property ''' <summary> ''' </summary> ''' <returns></returns> ''' <remarks></remarks> Public Property <API key>() As String Get Return <API key> End Get Set(ByVal Value As String) <API key> = Value End Set End Property ''' <summary> ''' Operator to be selected (FilterType of A - All, S - Single operator, FilterValue contains the selected operator if FilterType is S). ''' </summary> ''' <returns></returns> ''' <remarks></remarks> Public Property xOperator() As String Get Return _xOperator End Get Set(ByVal Value As String) _xOperator = Value End Set End Property ''' <summary> ''' </summary> ''' <returns></returns> ''' <remarks></remarks> Public Property <API key>() As <API key> Get Return <API key> End Get Set(ByVal Value As <API key>) <API key> = Value End Set End Property ''' <summary> ''' </summary> ''' <returns></returns> ''' <remarks></remarks> Public Property <API key>() As String Get Return <API key> End Get Set(ByVal Value As String) <API key> = Value End Set End Property ''' <summary> ''' Geographic area to be selected (FilterType of A - All, S - Single geographic area, FilterValue contains the selected geographic area if FilterType is S) ''' </summary> ''' <returns></returns> ''' <remarks></remarks> Public Property GeographicArea() As String Get Return _GeographicArea End Get Set(ByVal Value As String) _GeographicArea = Value End Set End Property ''' <summary> ''' </summary> ''' <returns></returns> ''' <remarks></remarks> Public Property <API key>() As <API key> Get Return <API key> End Get Set(ByVal Value As <API key>) <API key> = Value End Set End Property #End Region #Region "XML String Constructor" Private Function ConstructXML() As String Dim xmlDoc As New System.Xml.XmlDocument 'Root Element Appended to xmlDoc Dim Query As System.Xml.XmlElement = xmlDoc.CreateElement("Query") xmlDoc.AppendChild(Query) Dim xOption As System.Xml.XmlElement = xmlDoc.CreateElement("Option") Dim Reprint As System.Xml.XmlElement = xmlDoc.CreateElement("Reprint") Dim DocumentType As System.Xml.XmlElement = xmlDoc.CreateElement("DocumentType") Dim IncludeForms As System.Xml.XmlElement = xmlDoc.CreateElement("IncludeForms") Dim <API key> As System.Xml.XmlElement = xmlDoc.CreateElement("<API key>") Dim IncludeStockForms As System.Xml.XmlElement = xmlDoc.CreateElement("IncludeStockForms") Dim IncludeDetailForms As System.Xml.XmlElement = xmlDoc.CreateElement("IncludeDetailForms") Dim IncludeNotes As System.Xml.XmlElement = xmlDoc.CreateElement("IncludeNotes") Dim IgnorePrintStatus As System.Xml.XmlElement = xmlDoc.CreateElement("IgnorePrintStatus") Dim RoundMass As System.Xml.XmlElement = xmlDoc.CreateElement("RoundMass") Dim RoundMassDecs As System.Xml.XmlElement = xmlDoc.CreateElement("RoundMassDecs") Dim RoundVolume As System.Xml.XmlElement = xmlDoc.CreateElement("RoundVolume") Dim RoundVolumeDecs As System.Xml.XmlElement = xmlDoc.CreateElement("RoundVolumeDecs") Dim XslStylesheet As System.Xml.XmlElement = xmlDoc.CreateElement("XslStylesheet") Dim Filter As System.Xml.XmlElement = xmlDoc.CreateElement("Filter") Dim Branch As System.Xml.XmlElement = xmlDoc.CreateElement("Branch") Dim Branch_FilterType As System.Xml.XmlElement = xmlDoc.CreateElement("Branch_FilterType") Dim Branch_FilterValue As System.Xml.XmlElement = xmlDoc.CreateElement("Branch_FilterValue") Dim Customer As System.Xml.XmlElement = xmlDoc.CreateElement("Customer") Dim Customer_FilterType As System.Xml.XmlElement = xmlDoc.CreateElement("Customer_FilterType") Dim <API key> As System.Xml.XmlElement = xmlDoc.CreateElement("<API key>") Dim SourceWarehouse As System.Xml.XmlElement = xmlDoc.CreateElement("SourceWarehouse") Dim <API key> As System.Xml.XmlElement = xmlDoc.CreateElement("<API key>") Dim <API key> As System.Xml.XmlElement = xmlDoc.CreateElement("<API key>") Dim TargetWarehouse As System.Xml.XmlElement = xmlDoc.CreateElement("TargetWarehouse") Dim <API key> As System.Xml.XmlElement = xmlDoc.CreateElement("<API key>") Dim <API key> As System.Xml.XmlElement = xmlDoc.CreateElement("<API key>") Dim OrderType As System.Xml.XmlElement = xmlDoc.CreateElement("OrderType") Dim <API key> As System.Xml.XmlElement = xmlDoc.CreateElement("<API key>") Dim <API key> As System.Xml.XmlElement = xmlDoc.CreateElement("<API key>") Dim CustomerPo As System.Xml.XmlElement = xmlDoc.CreateElement("CustomerPo") Dim <API key> As System.Xml.XmlElement = xmlDoc.CreateElement("<API key>") Dim <API key> As System.Xml.XmlElement = xmlDoc.CreateElement("<API key>") Dim InvoiceNumber As System.Xml.XmlElement = xmlDoc.CreateElement("InvoiceNumber") Dim <API key> As System.Xml.XmlElement = xmlDoc.CreateElement("<API key>") Dim <API key> As System.Xml.XmlElement = xmlDoc.CreateElement("<API key>") Dim GtrReference As System.Xml.XmlElement = xmlDoc.CreateElement("GtrReference") Dim <API key> As System.Xml.XmlElement = xmlDoc.CreateElement("<API key>") Dim <API key> As System.Xml.XmlElement = xmlDoc.CreateElement("<API key>") Dim SalesOrder As System.Xml.XmlElement = xmlDoc.CreateElement("SalesOrder") Dim <API key> As System.Xml.XmlElement = xmlDoc.CreateElement("<API key>") Dim <API key> As System.Xml.XmlElement = xmlDoc.CreateElement("<API key>") Dim InvoiceDate As System.Xml.XmlElement = xmlDoc.CreateElement("InvoiceDate") Dim <API key> As System.Xml.XmlElement = xmlDoc.CreateElement("<API key>") Dim <API key> As System.Xml.XmlElement = xmlDoc.CreateElement("<API key>") Dim xOperator As System.Xml.XmlElement = xmlDoc.CreateElement("Operator") Dim <API key> As System.Xml.XmlElement = xmlDoc.CreateElement("Operator_FilterType") Dim <API key> As System.Xml.XmlElement = xmlDoc.CreateElement("<API key>") Dim GeographicArea As System.Xml.XmlElement = xmlDoc.CreateElement("GeographicArea") Dim <API key> As System.Xml.XmlElement = xmlDoc.CreateElement("<API key>") '**OPTION Common.SysproUtilities.AppendXMLElement(Query, xOption, _xOption.ToString) Common.SysproUtilities.AppendXMLElement(xOption, Reprint, Common.SysproUtilities.GetEnumValue(_Reprint.ToString)) Common.SysproUtilities.AppendXMLElement(xOption, DocumentType, Common.SysproUtilities.GetEnumValue(_DocumentType.ToString)) Common.SysproUtilities.AppendXMLElement(xOption, IncludeForms, Common.SysproUtilities.GetEnumValue(_IncludeForms.ToString)) Common.SysproUtilities.AppendXMLElement(xOption, <API key>, Common.SysproUtilities.GetEnumValue(<API key>.ToString)) Common.SysproUtilities.AppendXMLElement(xOption, IncludeStockForms, Common.SysproUtilities.GetEnumValue(_IncludeStockForms.ToString)) Common.SysproUtilities.AppendXMLElement(xOption, IncludeDetailForms, Common.SysproUtilities.GetEnumValue(_IncludeDetailForms.ToString)) Common.SysproUtilities.AppendXMLElement(xOption, IncludeNotes, Common.SysproUtilities.GetEnumValue(_IncludeNotes.ToString)) Common.SysproUtilities.AppendXMLElement(xOption, IgnorePrintStatus, Common.SysproUtilities.GetEnumValue(_IgnorePrintStatus.ToString)) Common.SysproUtilities.AppendXMLElement(xOption, RoundMass, Common.SysproUtilities.GetEnumValue(_RoundMass.ToString)) Common.SysproUtilities.AppendXMLElement(xOption, RoundMassDecs, _RoundMassDecs.ToString) Common.SysproUtilities.AppendXMLElement(xOption, RoundVolume, Common.SysproUtilities.GetEnumValue(_RoundVolume.ToString)) Common.SysproUtilities.AppendXMLElement(xOption, RoundVolumeDecs, _RoundVolumeDecs.ToString) Common.SysproUtilities.AppendXMLElement(xOption, XslStylesheet, _XslStylesheet.ToString) '**FILTER Common.SysproUtilities.AppendXMLElement(Query, Filter, _Filter.ToString) '**Filter's Children '***Branch Common.SysproUtilities.AppendXMLElement(Filter, Branch, _Branch.ToString) Common.SysproUtilities.AppendAttributes(Branch, _Branch_FilterType, _Branch_FilterValue) '***Customer Common.SysproUtilities.AppendXMLElement(Filter, Customer, _Customer.ToString) Common.SysproUtilities.AppendAttributes(Customer, <API key>, <API key>) '***SourceWarehouse Common.SysproUtilities.AppendXMLElement(Filter, SourceWarehouse, _SourceWarehouse.ToString) Common.SysproUtilities.AppendAttributes(SourceWarehouse, <API key>, <API key>) '***TargetWarehouse Common.SysproUtilities.AppendXMLElement(Filter, TargetWarehouse, _TargetWarehouse.ToString) Common.SysproUtilities.AppendAttributes(TargetWarehouse, <API key>, <API key>) '***OrderType Common.SysproUtilities.AppendXMLElement(Filter, OrderType, _OrderType.ToString) Common.SysproUtilities.AppendAttributes(OrderType, <API key>, <API key>) '**CustomerPo Common.SysproUtilities.AppendXMLElement(Filter, CustomerPo, _CustomerPo.ToString) Common.SysproUtilities.AppendAttributes(CustomerPo, <API key>, <API key>) '**InvoiceNumber Common.SysproUtilities.AppendXMLElement(Filter, InvoiceNumber, _InvoiceNumber.ToString) Common.SysproUtilities.AppendAttributes(InvoiceNumber, <API key>, <API key>) '**GtrReference Common.SysproUtilities.AppendXMLElement(Filter, GtrReference, _GtrReference.ToString) Common.SysproUtilities.AppendAttributes(GtrReference, <API key>, <API key>) '**SalesOrder Common.SysproUtilities.AppendXMLElement(Filter, SalesOrder, _SalesOrder.ToString) Common.SysproUtilities.AppendAttributes(SalesOrder, <API key>, <API key>) '**InvoiceDate Common.SysproUtilities.AppendXMLElement(Filter, InvoiceDate, _InvoiceDate.ToString) Common.SysproUtilities.AppendAttributes(InvoiceDate, <API key>, <API key>) '**xOperator Common.SysproUtilities.AppendXMLElement(Filter, xOperator, _xOperator.ToString) Common.SysproUtilities.AppendAttributes(xOperator, <API key>, <API key>) '**GeographicArea Common.SysproUtilities.AppendXMLElement(Filter, GeographicArea, _GeographicArea.ToString) Common.SysproUtilities.AppendAttributes(GeographicArea, <API key>, "") Return xmlDoc.OuterXml End Function #End Region #Region "Post Sub" Public Sub Post() Implements IQuery.Post Select Case _ActionType Case CommonEnums.ActionType_Query.Query _xmlOut = Query.Query(Me) Case CommonEnums.ActionType_Query.Fetch _xmlOut = Query.Fetch(Me) Case CommonEnums.ActionType_Query.Browse _xmlOut = Query.Browse(Me) Case CommonEnums.ActionType_Query.NextKey _xmlOut = Query.NextKey(Me) Case CommonEnums.ActionType_Query.PreviousKey _xmlOut = Query.PreviousKey(Me) End Select End Sub #End Region #Region "Enumerations" Public Enum <API key> Reprint_Upper_Y Reprint_Upper_N End Enum Public Enum <API key> <API key> <API key> <API key> <API key> End Enum Public Enum <API key> <API key> <API key> IncludeForms_Upper_ End Enum Public Enum <API key> <API key> <API key> <API key> End Enum Public Enum <API key> <API key> <API key> <API key> End Enum Public Enum <API key> <API key> <API key> <API key> End Enum Public Enum <API key> <API key> <API key> IncludeNotes_Upper_ End Enum Public Enum <API key> <API key> <API key> <API key> End Enum Public Enum <API key> RoundMass_Upper_O RoundMass_Upper_U RoundMass_Upper_D End Enum Public Enum <API key> RoundVolume_Upper_O RoundVolume_Upper_U RoundVolume_Upper_D End Enum Public Enum <API key> <API key> <API key> <API key> <API key> End Enum Public Enum <API key> <API key> <API key> <API key> <API key> End Enum Public Enum <API key> <API key> <API key> <API key> End Enum Public Enum <API key> <API key> <API key> <API key> End Enum Public Enum <API key> <API key> <API key> <API key> <API key> End Enum Public Enum <API key> <API key> <API key> End Enum Public Enum <API key> <API key> <API key> <API key> End Enum Public Enum <API key> <API key> <API key> <API key> End Enum Public Enum <API key> <API key> <API key> <API key> End Enum Public Enum <API key> <API key> <API key> <API key> <API key> End Enum Public Enum <API key> <API key> <API key> <API key> <API key> End Enum Public Enum <API key> <API key> <API key> <API key> End Enum Public Enum <API key> <API key> <API key> <API key> End Enum #End Region End Class End Namespace
<?php /** * File: PieceFault.php * Project: DHL API * * @author Al-Fallouji Bashar * @version 0.1 */ namespace DHL\Datatype\AM; use DHL\Datatype\Base; /** * PieceFault Request model for DHL API */ class PieceFault extends Base { /** * Is this object a subobject * @var boolean */ protected $_isSubobject = true; /** * Parameters of the datatype * @var array */ protected $_params = array( 'PieceID' => array( 'type' => 'TrackingPieceID', 'required' => true, 'subobject' => false, 'comment' => 'Piece ID', 'minLength' => '1', 'maxLength' => '35', ), 'ConditionCode' => array( 'type' => 'string', 'required' => true, 'subobject' => false, ), 'ConditionData' => array( 'type' => 'string', 'required' => true, 'subobject' => false, ), ); }
<?php defined('_JEXEC') or die; /* * none (output raw module content) */ function modChrome_none($module, &$params, &$attribs) { echo $module->content; } /* * html5 (chosen html5 tag and font headder tags) */ function modChrome_html5($module, &$params, &$attribs) { $moduleTag = $params->get('module_tag', 'div'); $headerTag = htmlspecialchars($params->get('header_tag', 'h3')); $bootstrapSize = (int) $params->get('bootstrap_size', 0); $moduleClass = $bootstrapSize != 0 ? ' span' . $bootstrapSize : ''; // Temporarily store header class in variable $headerClass = $params->get('header_class'); $headerClass = !empty($headerClass) ? ' class="' . htmlspecialchars($headerClass) . '"' : ''; if(!empty($module->content)) : ?> <<?php echo $moduleTag; ?> class="moduletable<?php echo htmlspecialchars($params->get('moduleclass_sfx')) . $moduleClass; ?>"> <?php if((bool) $module->showtitle) : ?> <<?php echo $headerTag . $headerClass . '>' . $module->title; ?></<?php echo $headerTag; ?>> <?php endif; ?> <?php echo $module->content; ?> </<?php echo $moduleTag; ?>> <?php endif; } /* * Module chrome that wraps the module in a table */ function modChrome_table($module, &$params, &$attribs) { ?> <table cellpadding="0" cellspacing="0" class="moduletable<?php echo htmlspecialchars($params->get('moduleclass_sfx')); ?>"> <?php if((bool) $module->showtitle) : ?> <tr> <th> <?php echo $module->title; ?> </th> </tr> <?php endif; ?> <tr> <td> <?php echo $module->content; ?> </td> </tr> </table> <?php } /* * Module chrome that wraps the tabled module output in a <td> tag of another table */ function modChrome_horz($module, &$params, &$attribs) { ?> <table cellspacing="1" cellpadding="0" width="100%"> <tr> <td> <?php modChrome_table($module, $params, $attribs); ?> </td> </tr> </table> <?php } /* * xhtml (divs and font headder tags) */ function modChrome_xhtml($module, &$params, &$attribs) { if(!empty($module->content)) : ?> <div class="moduletable<?php echo htmlspecialchars($params->get('moduleclass_sfx')); ?>"> <?php if((bool) $module->showtitle) : ?> <h3><?php echo $module->title; ?></h3> <?php endif; ?> <?php echo $module->content; ?> </div> <?php endif; } /* * Module chrome that allows for rounded corners by wrapping in nested div tags */ function modChrome_rounded($module, &$params, &$attribs) { ?> <div class="module<?php echo htmlspecialchars($params->get('moduleclass_sfx')); ?>"> <div> <div> <div> <?php if((bool) $module->showtitle) : ?> <h3><?php echo $module->title; ?></h3> <?php endif; ?> <?php echo $module->content; ?> </div> </div> </div> </div> <?php } /* * Module chrome that add preview information to the module */ function modChrome_outline($module, &$params, &$attribs) { static $css = false; if(!$css) { $css = true; $doc = JFactory::getDocument(); $doc->addStyleDeclaration(".mod-preview-info { padding: 2px 4px 2px 4px; border: 1px solid black; position: absolute; background-color: white; color: red;}"); $doc->addStyleDeclaration(".mod-preview-wrapper { background-color:#eee; border: 1px dotted black; color:#700;}"); } ?> <div class="mod-preview"> <div class="mod-preview-info"><?php echo 'Position: ' . $module->position . ' [ Style: ' . $module->style . ']'; ?></div> <div class="mod-preview-wrapper"> <?php echo $module->content; ?> </div> </div> <?php }
package docker_test import ( "fmt" "testing" "github.com/lotreal/docker-pods/src/docker" "github.com/lotreal/docker-pods/src/sh" ) var busybox = (func() string { cmd := sh.Command{"docker run -d -it busybox sh"} return cmd.Ok()[0:12] })() func TestInit(t *testing.T) { t.Logf("%s", docker.Ps()) t.Logf("%s", busybox) } func TestIp(t *testing.T) { t.Log(docker.InspectIp(busybox)) } func TestPort(t *testing.T) { t.Log(docker.InspectPorts(busybox)) } func TestState(t *testing.T) { t.Log(docker.InspectPorts(busybox)) } func TestRm(t *testing.T) { script := fmt.Sprintf("docker rm -f %s", busybox) cmd := sh.Command{script} t.Log(cmd.Ok()) }
#include "tooltipfiller.h" // Qt includes #include <QDateTime> #include <QLocale> // KDE includes #include <klocalizedstring.h> // Local includes #include "digikam_debug.h" #include "albummanager.h" #include "collectionlocation.h" #include "collectionmanager.h" #include "applicationsettings.h" #include "album.h" #include "<API key>.h" #include "dimgfiltermanager.h" #include "ditemtooltip.h" #include "filteraction.h" #include "imageinfo.h" #include "imagepropertiestab.h" #include "colorlabelwidget.h" #include "picklabelwidget.h" #include "<API key>.h" #include "thumbnailsize.h" namespace Digikam { QString ToolTipFiller::<API key>(const ImageInfo& info) { QString str; ApplicationSettings* const settings = ApplicationSettings::instance(); DToolTipStyleSheet cnt(settings->getToolTipsFont()); <API key> commonInfo = info.<API key>(); <API key> photoInfo = info.<API key>(); <API key> videoInfo = info.<API key>(); QString tip = cnt.tipHeader; if (settings-><API key>() || settings-><API key>() || settings-><API key>() || settings-><API key>() || settings-><API key>() || settings-><API key>()) { tip += cnt.headBeg + i18n("File Properties") + cnt.headEnd; if (settings-><API key>()) { tip += cnt.cellBeg + i18nc("filename", "Name:") + cnt.cellMid; tip += commonInfo.fileName + cnt.cellEnd; } if (settings-><API key>()) { QDateTime modifiedDate = commonInfo.<API key>; str = QLocale().toString(modifiedDate, QLocale::ShortFormat); tip += cnt.cellBeg + i18n("Date:") + cnt.cellMid + str + cnt.cellEnd; } if (settings-><API key>()) { tip += cnt.cellBeg + i18n("Size:") + cnt.cellMid; QString localeFileSize = QLocale().toString(commonInfo.fileSize); str = i18n("%1 (%2)", ImagePropertiesTab::<API key>(commonInfo.fileSize), localeFileSize); tip += str + cnt.cellEnd; } QSize dims; if (settings-><API key>()) { tip += cnt.cellBeg + i18n("Type:") + cnt.cellMid + commonInfo.format + cnt.cellEnd; } if (settings-><API key>()) { if (commonInfo.width == 0 || commonInfo.height == 0) { str = i18nc("unknown / invalid image dimension", "Unknown"); } else { QString mpixels; mpixels.setNum(commonInfo.width*commonInfo.height/1000000.0, 'f', 2); str = i18nc("width x height (megapixels Mpx)", "%1x%2 (%3Mpx)", commonInfo.width, commonInfo.height, mpixels); } tip += cnt.cellBeg + i18n("Dimensions:") + cnt.cellMid + str + cnt.cellEnd; } if (settings-><API key>()) { if (!ImagePropertiesTab::aspectRatioToString(commonInfo.width, commonInfo.height, str)) { str = i18nc("unknown / invalid image aspect ratio", "Unknown"); } tip += cnt.cellBeg + i18n("Aspect Ratio:") + cnt.cellMid + str + cnt.cellEnd; } } if (settings-><API key>() || settings-><API key>() || settings-><API key>() || settings-><API key>() || settings-><API key>() || settings-><API key>() || settings-><API key>()) { if (!photoInfo.allFieldsNull) { QString metaStr; tip += cnt.headBeg + i18n("Photograph Properties") + cnt.headEnd; if (settings-><API key>()) { ImagePropertiesTab::shortenedMakeInfo(photoInfo.make); ImagePropertiesTab::shortenedModelInfo(photoInfo.model); str = QString::fromUtf8("%1 / %2").arg(photoInfo.make.isEmpty() ? cnt.unavailable : photoInfo.make) .arg(photoInfo.model.isEmpty() ? cnt.unavailable : photoInfo.model); if (str.length() > cnt.maxStringLength) { str = str.left(cnt.maxStringLength-3) + QLatin1String("..."); } metaStr += cnt.cellBeg + i18n("Make/Model:") + cnt.cellMid + str.toHtmlEscaped() + cnt.cellEnd; } if (settings-><API key>()) { if (commonInfo.creationDate.isValid()) { str = QLocale().toString(commonInfo.creationDate, QLocale::ShortFormat); if (str.length() > cnt.maxStringLength) { str = str.left(cnt.maxStringLength-3) + QLatin1String("..."); } metaStr += cnt.cellBeg + i18nc("creation date of the image", "Created:") + cnt.cellMid + str.toHtmlEscaped() + cnt.cellEnd; } else { metaStr += cnt.cellBeg + i18nc("creation date of the image", "Created:") + cnt.cellMid + cnt.unavailable.toHtmlEscaped() + cnt.cellEnd; } } if (settings-><API key>()) { str = photoInfo.aperture.isEmpty() ? cnt.unavailable : photoInfo.aperture; if (photoInfo.focalLength35.isEmpty()) { str += QString::fromUtf8(" / %1").arg(photoInfo.focalLength.isEmpty() ? cnt.unavailable : photoInfo.focalLength); } else { str += QString::fromUtf8(" / %1").arg(i18n("%1 (%2)",photoInfo.focalLength,photoInfo.focalLength35)); } if (str.length() > cnt.maxStringLength) { str = str.left(cnt.maxStringLength-3) + QLatin1String("..."); } metaStr += cnt.cellBeg + i18n("Aperture/Focal:") + cnt.cellMid + str.toHtmlEscaped() + cnt.cellEnd; } if (settings-><API key>()) { str = QString::fromUtf8("%1 / %2").arg(photoInfo.exposureTime.isEmpty() ? cnt.unavailable : photoInfo.exposureTime) .arg(photoInfo.sensitivity.isEmpty() ? cnt.unavailable : i18n("%1 ISO",photoInfo.sensitivity)); if (str.length() > cnt.maxStringLength) { str = str.left(cnt.maxStringLength-3) + QLatin1String("..."); } metaStr += cnt.cellBeg + i18n("Exposure/Sensitivity:") + cnt.cellMid + str.toHtmlEscaped() + cnt.cellEnd; } if (settings-><API key>()) { if (photoInfo.exposureMode.isEmpty() && photoInfo.exposureProgram.isEmpty()) { str = cnt.unavailable; } else if (!photoInfo.exposureMode.isEmpty() && photoInfo.exposureProgram.isEmpty()) { str = photoInfo.exposureMode; } else if (photoInfo.exposureMode.isEmpty() && !photoInfo.exposureProgram.isEmpty()) { str = photoInfo.exposureProgram; } else { str = QString::fromUtf8("%1 / %2").arg(photoInfo.exposureMode).arg(photoInfo.exposureProgram); } if (str.length() > cnt.maxStringLength) { str = str.left(cnt.maxStringLength-3) + QLatin1String("..."); } metaStr += cnt.cellBeg + i18n("Mode/Program:") + cnt.cellMid + str.toHtmlEscaped() + cnt.cellEnd; } if (settings-><API key>()) { str = photoInfo.flashMode.isEmpty() ? cnt.unavailable : photoInfo.flashMode; if (str.length() > cnt.maxStringLength) { str = str.left(cnt.maxStringLength-3) + QLatin1String("..."); } metaStr += cnt.cellBeg + i18nc("camera flash settings", "Flash:") + cnt.cellMid + str.toHtmlEscaped() + cnt.cellEnd; } if (settings-><API key>()) { str = photoInfo.whiteBalance.isEmpty() ? cnt.unavailable : photoInfo.whiteBalance; if (str.length() > cnt.maxStringLength) { str = str.left(cnt.maxStringLength-3) + QLatin1String("..."); } metaStr += cnt.cellBeg + i18n("White Balance:") + cnt.cellMid + str.toHtmlEscaped() + cnt.cellEnd; } tip += metaStr; } } if (settings-><API key>() || settings-><API key>() || settings-><API key>() || settings-><API key>() || settings-><API key>() || settings-><API key>() || settings-><API key>()) { if (!videoInfo.allFieldsNull) { QString metaStr; tip += cnt.headBeg + i18n("Video Properties") + cnt.headEnd; if (settings-><API key>()) { str = videoInfo.aspectRatio.isEmpty() ? cnt.unavailable : videoInfo.aspectRatio; if (str.length() > cnt.maxStringLength) { str = str.left(cnt.maxStringLength-3) + QLatin1String("..."); } metaStr += cnt.cellBeg + i18n("Aspect Ratio:") + cnt.cellMid + str.toHtmlEscaped() + cnt.cellEnd; } if (settings-><API key>()) { QString durationString; bool ok; const double durationDouble = videoInfo.duration.toDouble(&ok); if (ok) { const QTime durationTime = QTime().addMSecs(durationDouble); durationString = QLocale().toString(durationTime, QLocale::ShortFormat); } str = videoInfo.duration.isEmpty() ? cnt.unavailable : durationString; if (str.length() > cnt.maxStringLength) { str = str.left(cnt.maxStringLength-3) + QLatin1String("..."); } metaStr += cnt.cellBeg + i18n("Duration:") + cnt.cellMid + str.toHtmlEscaped() + cnt.cellEnd; } if (settings-><API key>()) { QString frameRateString; bool ok; const double frameRateDouble = videoInfo.frameRate.toDouble(&ok); if (ok) { frameRateString = QLocale().toString(frameRateDouble); } str = videoInfo.frameRate.isEmpty() ? cnt.unavailable : frameRateString; if (str.length() > cnt.maxStringLength) { str = str.left(cnt.maxStringLength-3) + QLatin1String("..."); } metaStr += cnt.cellBeg + i18n("Frame Rate:") + cnt.cellMid + str.toHtmlEscaped() + i18n("fps") + cnt.cellEnd; } if (settings-><API key>()) { str = videoInfo.videoCodec.isEmpty() ? cnt.unavailable : videoInfo.videoCodec; if (str.length() > cnt.maxStringLength) { str = str.left(cnt.maxStringLength-3) + QLatin1String("..."); } metaStr += cnt.cellBeg + i18n("Video Codec:") + cnt.cellMid + str.toHtmlEscaped() + cnt.cellEnd; } if (settings-><API key>()) { QString audioBitRateString = str; bool ok; const int audioBitRateInt = videoInfo.audioBitRate.toInt(&ok); if (ok) { audioBitRateString = QLocale().toString(audioBitRateInt); } str = videoInfo.audioBitRate.isEmpty() ? cnt.unavailable : audioBitRateString; if (str.length() > cnt.maxStringLength) { str = str.left(cnt.maxStringLength-3) + QLatin1String("..."); } metaStr += cnt.cellBeg + i18n("Audio Bit Rate:") + cnt.cellMid + str.toHtmlEscaped() + cnt.cellEnd; } if (settings-><API key>()) { str = videoInfo.audioChannelType.isEmpty() ? cnt.unavailable : videoInfo.audioChannelType; if (str.length() > cnt.maxStringLength) { str = str.left(cnt.maxStringLength-3) + QLatin1String("..."); } metaStr += cnt.cellBeg + i18n("Audio Channel Type:") + cnt.cellMid + str.toHtmlEscaped() + cnt.cellEnd; } if (settings-><API key>()) { str = videoInfo.audioCompressor.isEmpty() ? cnt.unavailable : videoInfo.audioCompressor; if (str.length() > cnt.maxStringLength) { str = str.left(cnt.maxStringLength-3) + QLatin1String("..."); } metaStr += cnt.cellBeg + i18n("Audio Compressor:") + cnt.cellMid + str.toHtmlEscaped() + cnt.cellEnd; } tip += metaStr; } } if (settings-><API key>() || settings-><API key>() || settings-><API key>() || settings->getToolTipsShowTags() || settings-><API key>()) { tip += cnt.headBeg + i18n("digiKam Properties") + cnt.headEnd; if (settings-><API key>()) { PAlbum* const album = AlbumManager::instance()->findPAlbum(info.albumId()); if (album) { tip += cnt.cellSpecBeg + i18n("Album:") + cnt.cellSpecMid + album->albumPath().remove(0, 1) + cnt.cellSpecEnd; } } if (settings-><API key>()) { str = info.title(); if (str.isEmpty()) { str = QLatin1String(" } tip += cnt.cellSpecBeg + i18nc("title of the file", "Title:") + cnt.cellSpecMid + cnt.breakString(str) + cnt.cellSpecEnd; } if (settings-><API key>()) { str = info.comment(); if (str.isEmpty()) { str = QLatin1String(" } tip += cnt.cellSpecBeg + i18nc("caption of the file", "Caption:") + cnt.cellSpecMid + cnt.breakString(str) + cnt.cellSpecEnd; } if (settings->getToolTipsShowTags()) { QStringList tagPaths = AlbumManager::instance()->tagPaths(info.tagIds(), false); tagPaths.sort(); QStringList tagNames = AlbumManager::instance()->tagNames(info.tagIds()); tagNames.sort(); QString tags(i18n("Tags:")); if (tagPaths.isEmpty()) { tip += cnt.cellSpecBeg + tags + cnt.cellSpecMid + QLatin1String("---") + cnt.cellSpecEnd; } else { QString title = tags; QString tagText; for (int i = 0; i<tagPaths.size(); ++i) { tagText = tagPaths.at(i); if (tagText.size() > cnt.maxStringLength) { tagText = tagNames.at(i); } if (tagText.size() > cnt.maxStringLength) { tagText = cnt.elidedText(tagPaths.at(i), Qt::ElideLeft); } tip += cnt.cellSpecBeg + title + cnt.cellSpecMid + tagText + cnt.cellSpecEnd; title.clear(); } } } if (settings-><API key>()) { str = PickLabelWidget::labelPickName((PickLabel)info.pickLabel()); str += QLatin1String(" / "); str += ColorLabelWidget::labelColorName((ColorLabel)info.colorLabel()); str += QLatin1String(" / "); int rating = info.rating(); if (rating > RatingMin && rating <= RatingMax) { for (int i=0; i<rating; ++i) { str += QChar(0x2730); str += QLatin1Char(' '); } } else { str += QLatin1String(" } tip += cnt.cellSpecBeg + i18n("Labels:") + cnt.cellSpecMid + str + cnt.cellSpecEnd; } } tip += cnt.tipFooter; return tip; } QString ToolTipFiller::albumTipContents(PAlbum* const album, int count) { if (!album) { return QString(); } QString str; ApplicationSettings* const settings = ApplicationSettings::instance(); DToolTipStyleSheet cnt(settings->getToolTipsFont()); QString tip = cnt.tipHeader; if (settings-><API key>() || settings-><API key>() || settings-><API key>() || settings-><API key>() || settings-><API key>()) { tip += cnt.headBeg + i18n("Album Properties") + cnt.headEnd; if (settings-><API key>()) { tip += cnt.cellBeg + i18n("Name:") + cnt.cellMid; tip += album->title() + cnt.cellEnd; } if (settings-><API key>()) { tip += cnt.cellBeg + i18n("Items:") + cnt.cellMid; tip += QString::number(count) + cnt.cellEnd; } if (settings-><API key>()) { tip += cnt.cellBeg + i18n("Collection:") + cnt.cellMid; CollectionLocation col = CollectionManager::instance()-><API key>(album->albumRootId()); tip += !col.isNull() ? col.label() : QString() + cnt.cellEnd; } if (settings-><API key>()) { QDate date = album->date(); str = QLocale().toString(date, QLocale::ShortFormat); tip += cnt.cellBeg + i18n("Date:") + cnt.cellMid + str + cnt.cellEnd; } if (settings-><API key>()) { str = album->category(); if (str.isEmpty()) { str = QLatin1String(" } tip += cnt.cellSpecBeg + i18n("Category:") + cnt.cellSpecMid + cnt.breakString(str) + cnt.cellSpecEnd; } if (settings-><API key>()) { str = album->caption(); if (str.isEmpty()) { str = QLatin1String(" } tip += cnt.cellSpecBeg + i18n("Caption:") + cnt.cellSpecMid + cnt.breakString(str) + cnt.cellSpecEnd; } if (settings-><API key>()) { tip += cnt.cellSpecBeg + i18n("Preview:") + cnt.cellSpecMid + cnt.imageAsBase64(<API key>::instance()-><API key>(album).toImage()) + //cnt.imageAsBase64(<API key>::instance()-><API key>(album, ThumbnailSize::Medium)) + cnt.cellSpecEnd; } } tip += cnt.tipFooter; return tip; } QString ToolTipFiller::<API key>(const FilterAction& action) { if (action.isNull()) { return QString(); } QString str; DToolTipStyleSheet cnt(ApplicationSettings::instance()->getToolTipsFont()); QString tip = cnt.tipHeader; tip += cnt.headBeg + i18n("Filter") + cnt.headEnd; // Displayable name tip += cnt.cellBeg + i18n("Name:") + cnt.cellMid + DImgFilterManager::instance()->i18nDisplayableName(action) + cnt.cellEnd; // Category QString reproducible = QLatin1String(" switch (action.category()) { case FilterAction::ReproducibleFilter: reproducible = i18nc("Image filter reproducible: Yes", "Yes"); break; case FilterAction::ComplexFilter: reproducible = i18nc("Image filter reproducible: Partially", "Partially"); break; case FilterAction::DocumentedHistory: reproducible = i18nc("Image filter reproducible: No", "No"); break; default: break; }; tip += cnt.cellBeg + i18n("Reproducible:") + cnt.cellMid + reproducible + cnt.cellEnd; // Description str = action.description(); if (str.isEmpty()) { str = QLatin1String(" } tip += cnt.cellSpecBeg + i18nc("Image filter description", "Description:") + cnt.cellSpecMid + cnt.breakString(str) + cnt.cellSpecEnd; // Identifier + version tip += cnt.cellBeg + i18n("Identifier:") + cnt.cellMid + action.identifier() + QLatin1String(" (v") + QString::number(action.version()) + QLatin1String(") ") + cnt.cellEnd; if (action.hasParameters()) { tip += cnt.headBeg + i18n("Technical Parameters") + cnt.headEnd; const QHash<QString, QVariant>& params = action.parameters(); QList<QString> keys = params.keys(); qSort(keys); foreach(const QString& key, keys) { QHash<QString, QVariant>::const_iterator it; for (it = params.find(key); it != params.end() && it.key() == key; ++it) { if (it.key().isEmpty() || !it.value().isValid()) { continue; } if (it.key().startsWith(QLatin1String("curveData"))) { str = i18n("<i>Binary Data</i>"); } else { str = it.value().toString(); } if (str.length() > cnt.maxStringLength) { str = cnt.elidedText(str, Qt::ElideRight); } QString key = it.key(); QChar first = key.at(0); if (first.isLower()) { key.replace(0, 1, first.toUpper()); } tip += cnt.cellBeg + key + cnt.cellMid + str + cnt.cellEnd; } } } tip += cnt.tipFooter; return tip; } } // namespace Digikam
/* * geany.conf preferences file loading and saving. */ /* * Session file format: * filename_xx=pos;filetype UID;read only;Eencoding;use_tabs;auto_indent;line_wrapping;filename */ #include <stdlib.h> #include <string.h> #include <ctype.h> #include "geany.h" #ifdef HAVE_VTE #include <pwd.h> #include <sys/types.h> #include <unistd.h> #endif #include "support.h" #include "keyfile.h" #include "prefs.h" #include "ui_utils.h" #include "utils.h" #include "document.h" #include "filetypes.h" #include "sciwrappers.h" #include "encodings.h" #include "vte.h" #include "main.h" #include "msgwindow.h" #include "search.h" #include "project.h" #include "editor.h" #include "printing.h" #include "templates.h" #include "toolbar.h" #include "stash.h" #include "callbacks.h" #include "sidebar.h" /* some default settings which are used at the very first start of Geany to fill * the configuration file */ #define <API key> 10 #define <API key> 4 #define GEANY_MSGWIN_HEIGHT 208 #define <API key> 30 #define <API key> "make" #ifdef G_OS_WIN32 #define <API key> "cmd.exe /Q /C %c" #else #define <API key> "xterm -e \"/bin/sh %c\"" #endif #ifdef __arm__ #define <API key> "epiphany-browser" #else #define <API key> "firefox" #endif #define <API key> "lpr" #define <API key> "grep" #define <API key> 10 #ifdef __APPLE__ #define <API key> "Helvetica 12" #define <API key> "Helvetica 12" #define <API key> "Courier 12" #else #define <API key> "Sans 9" #define <API key> "Sans 9" #define <API key> "Monospace 10" #endif #define GEANY_TOGGLE_MARK "~ " #define <API key> 30 #define <API key> 250 #define <API key> "-\\*-\\s*([^\\s]+)\\s*-\\*-" static gchar *scribble_text = NULL; static gint scribble_pos = -1; static GPtrArray *session_files = NULL; static gint <API key>; static gint hpan_position; static gint vpan_position; static const gchar <API key>[] = "<API key>"; static GPtrArray *keyfile_groups = NULL; GPtrArray *pref_groups = NULL; static struct { gint <API key>; gint <API key>; gint <API key>; } build_menu_prefs; /* The group will be free'd on quitting. * @param for_prefs_dialog is whether the group also has Prefs dialog items. */ void <API key>(struct StashGroup *group, gboolean for_prefs_dialog) { g_ptr_array_add(keyfile_groups, group); if (for_prefs_dialog) g_ptr_array_add(pref_groups, group); } /* The group will be free'd on quitting. */ void <API key>(struct StashGroup *group) { <API key>(group, TRUE); <API key>(group, TRUE); } static void init_pref_groups(void) { StashGroup *group; group = stash_group_new(PACKAGE); <API key>(group, TRUE); <API key>(group, &prefs.default_open_path, "default_open_path", "", "startup_path_entry"); <API key>(group, &file_prefs.cmdline_new_files, "cmdline_new_files", TRUE, "<API key>"); <API key>(group, &interface_prefs.<API key>, "<API key>", FALSE, "<API key>"); <API key>(group, &file_prefs.<API key>, "<API key>", FALSE, "<API key>"); <API key>(group, &interface_prefs.tab_pos_sidebar, "tab_pos_sidebar", GTK_POS_TOP); <API key>(group, &interface_prefs.sidebar_pos, "sidebar_pos", GTK_POS_LEFT, "radio_sidebar_left", GTK_POS_LEFT, "radio_sidebar_right", GTK_POS_RIGHT, NULL); <API key>(group, &interface_prefs.msgwin_orientation, "msgwin_orientation", <API key>, "<API key>", <API key>, "<API key>", <API key>, NULL); /* editor display */ <API key>(group, &interface_prefs.<API key>, "<API key>", FALSE, "<API key>"); <API key>(group, &search_prefs.use_current_word, "<API key>", TRUE, "<API key>"); /* editor */ //<API key>(group, &editor_prefs.indentation->detect_type, "check_detect_indent", FALSE, "<API key>"); //<API key>(group, &editor_prefs.indentation->detect_width, "detect_indent_width", FALSE, "<API key>"); <API key>(group, &editor_prefs.use_tab_to_indent, "use_tab_to_indent", TRUE, "<API key>"); <API key>(group, &editor_prefs.indentation->width, "<API key>", 4, "spin_indent_width"); <API key>(group, (gint*)(void*)&editor_prefs.indentation->auto_indent_mode, "indent_mode", <API key>, "<API key>"); <API key>(group, (gint*)(void*)&editor_prefs.indentation->type, "indent_type", <API key>, "radio_indent_spaces", <API key>, "radio_indent_tabs", <API key>, "radio_indent_both", <API key>, NULL); <API key>(group, (gint*)(void*)&editor_prefs.show_virtual_space, "virtualspace", <API key>, "<API key>", <API key>, "<API key>", <API key>, "<API key>", <API key>, NULL); <API key>(group, &editor_prefs.<API key>, "<API key>", FALSE, "<API key>"); <API key>(group, &editor_prefs.<API key>, "<API key>", FALSE, "<API key>"); <API key>(group, (gint*)&editor_prefs.<API key>, "<API key>", <API key>, "<API key>"); <API key>(group, (gint*)&editor_prefs.<API key>, "<API key>", <API key>, "<API key>"); <API key>(group, &editor_prefs.color_scheme, "color_scheme", NULL); /* files */ <API key>(group, (gint*)&file_prefs.mru_length, "mru_length", <API key>, "spin_mru"); <API key>(group, &file_prefs.disk_check_timeout, "disk_check_timeout", <API key>, "spin_disk_check"); /* various geany prefs */ group = stash_group_new(PACKAGE); <API key>(group); <API key>(group, &editor_prefs.show_scrollbars, "<API key>", TRUE); <API key>(group, &editor_prefs.brace_match_ltgt, "brace_match_ltgt", FALSE); <API key>(group, &editor_prefs.<API key>, "<API key>", TRUE); <API key>(group, &editor_prefs.<API key>, "<API key>", FALSE); <API key>(group, &file_prefs.<API key>, <API key>, FALSE); <API key>(group, &file_prefs.<API key>, "<API key>", FALSE); <API key>(group, &file_prefs.<API key>, "<API key>", TRUE); /* for <API key> */ <API key>(group, &editor_prefs.indentation->hard_tab_width, "<API key>", 8); <API key>(group, (gint*)&search_prefs.find_selection_type, "find_selection_type", <API key>); <API key>(group, &file_prefs.<API key>, "<API key>", <API key>); /* Note: Interface-related various prefs are in ui_init_prefs() */ /* various build-menu prefs */ group = stash_group_new("build-menu"); <API key>(group); <API key>(group, &build_menu_prefs.<API key>, "<API key>", 0); <API key>(group, &build_menu_prefs.<API key>, "<API key>", 0); <API key>(group, &build_menu_prefs.<API key>, "<API key>", 0); } typedef enum SettingAction { SETTING_READ, SETTING_WRITE } SettingAction; static void settings_action(GKeyFile *config, SettingAction action) { guint i; StashGroup *group; foreach_ptr_array(group, i, keyfile_groups) { switch (action) { case SETTING_READ: <API key>(group, config); break; case SETTING_WRITE: <API key>(group, config); break; } } } static void save_recent_files(GKeyFile *config, GQueue *queue, gchar const *key) { gchar **recent_files = g_new0(gchar*, file_prefs.mru_length + 1); guint i; for (i = 0; i < file_prefs.mru_length; i++) { if (! g_queue_is_empty(queue)) { /* copy the values, this is necessary when this function is called from the * preferences dialog or when quitting is canceled to keep the queue intact */ recent_files[i] = g_strdup(g_queue_peek_nth(queue, i)); } else { recent_files[i] = NULL; break; } } /* There is a bug in GTK 2.6 <API key>, we must NULL terminate. */ recent_files[file_prefs.mru_length] = NULL; <API key>(config, "files", key, (const gchar**)recent_files, file_prefs.mru_length); g_strfreev(recent_files); } static gchar *<API key>(GeanyDocument *doc) { gchar *fname; gchar *locale_filename; gchar *escaped_filename; GeanyFiletype *ft = doc->file_type; if (ft == NULL) /* can happen when saving a new file when quitting */ ft = filetypes[<API key>]; locale_filename = <API key>(doc->file_name); escaped_filename = g_uri_escape_string(locale_filename, NULL, TRUE); fname = g_strdup_printf("%d;%s;%d;E%s;%d;%d;%d;%s;%d;%d", <API key>(doc->editor->sci), ft->name, doc->readonly, doc->encoding, doc->editor->indent_type, doc->editor->auto_indent, doc->editor->line_wrapping, escaped_filename, doc->editor->line_breaking, doc->editor->indent_width); g_free(escaped_filename); g_free(locale_filename); return fname; } void <API key>(GKeyFile *config) { gint npage; gchar *tmp; gchar entry[30]; guint i = 0, j = 0, max; for ( i = 0; i < projects_array->len; i++ ) { if ( !projects[i]->is_valid ) continue; gchar *fname; g_snprintf(entry, sizeof(entry), "PROJECT_FILE_NAME_%d", j); gchar* path = g_build_filename( projects[i]->base_path, projects[i]->name, NULL ); SETPTR( path, g_strconcat( path, ".agk", NULL ) ); gchar* utf8_filename = <API key>(path); gchar* escaped_filename = g_uri_escape_string(utf8_filename, NULL, TRUE); gint current = 0; if ( projects[i] == app->project ) current = 1; fname = g_strdup_printf( "%d;%s", current, escaped_filename ); <API key>(config, "projects", entry, fname); g_free(fname); g_free(path); g_free(escaped_filename); g_free(utf8_filename); j++; } /* if open filenames less than saved session files, delete existing entries in the list */ i = j; while (TRUE) { g_snprintf(entry, sizeof(entry), "PROJECT_FILE_NAME_%d", i); tmp = <API key>(config, "projects", entry, NULL); if (G_UNLIKELY(tmp == NULL)) { break; } else { <API key>(config, "projects", entry, NULL); g_free(tmp); i++; } } } void <API key>(GKeyFile *config, GeanyProject *project) { gint npage; gchar *tmp; gchar entry[16]; guint i = 0, j = 0, max; GeanyDocument *doc, *curr_doc = <API key>(); //npage = <API key>(GTK_NOTEBOOK(main_widgets.notebook)); //<API key>(config, "files", "current_page", npage); /* store the filenames in the notebook tab order to reopen them the next time */ /* max = <API key>(GTK_NOTEBOOK(main_widgets.notebook)); for (i = 0; i < max; i++) { doc = <API key>(i); */ for ( i = 0; i < project->project_files->len; i++ ) { if ( !project_files_index(project,i)->is_valid ) continue; GeanyDocument *doc = <API key>( project_files_index(project,i)->file_name ); if (doc != NULL && doc->is_valid) { gchar *fname; g_snprintf(entry, sizeof(entry), "FILE_NAME_%d", j); gchar* relative_path = <API key>( project->base_path, doc->real_path ); <API key>( relative_path, '\\', '/' ); gchar* utf8_filename = <API key>(relative_path); gchar* escaped_filename = g_uri_escape_string(utf8_filename, NULL, TRUE); gint current = 0; if ( doc == curr_doc ) current = 1; fname = g_strdup_printf( "%d;%s;%d;%d", current, escaped_filename, <API key>(doc->editor->sci), <API key>(doc) ); <API key>(config, "files", entry, fname); g_free(fname); g_free(escaped_filename); g_free(utf8_filename); g_free(relative_path); j++; } } /* if open filenames less than saved session files, delete existing entries in the list */ i = j; while (TRUE) { g_snprintf(entry, sizeof(entry), "FILE_NAME_%d", i); tmp = <API key>(config, "files", entry, NULL); if (G_UNLIKELY(tmp == NULL)) { break; } else { <API key>(config, "files", entry, NULL); g_free(tmp); i++; } } #ifdef HAVE_VTE if (vte_info.have_vte) { <API key>(); /* refresh vte_info.dir */ <API key>(config, "VTE", "last_dir", vte_info.dir); } #endif } void <API key>(GKeyFile *config, GeanyProject *project) { gint npage; gchar *tmp; gchar entry[16]; guint i = 0, j = 0; gint *groupIndex = g_new0(gint, project->project_groups->len); // save project groups for (i = 0; i < project->project_groups->len; i++) { GeanyProjectGroup *group = project->project_groups->pdata[i]; if (group != NULL && group->is_valid) { gchar *fname; groupIndex[ i ] = j; gint parent = -1; if ( group->pParent ) parent = groupIndex[ group->pParent->index ]; g_snprintf(entry, sizeof(entry), "GROUP_%d", j); fname = g_strdup_printf( "%s;%d", group->group_name, parent); <API key>(config, "projectgroups", entry, fname); g_free(fname); j++; } } j = 0; for (i = 0; i < project->project_files->len; i++) { GeanyProjectFile *file = project->project_files->pdata[i]; if (file != NULL && file->is_valid) { gchar *fname; g_snprintf(entry, sizeof(entry), "FILE_%d", j); gchar* relative_path = <API key>( project->base_path, file->file_name ); <API key>( relative_path, '\\', '/' ); gchar* utf8_filename = <API key>(relative_path); gchar* escaped_filename = g_uri_escape_string(utf8_filename, NULL, TRUE); gint parent = -1; if ( file->pParent ) parent = groupIndex[ file->pParent->index ]; fname = g_strdup_printf( "%s;%d", escaped_filename, parent); <API key>(config, "projectfiles", entry, fname); g_free(fname); g_free(escaped_filename); g_free(utf8_filename); g_free(relative_path); j++; } } g_free(groupIndex); /* if open filenames less than saved session files, delete existing entries in the list */ i = j; while (TRUE) { g_snprintf(entry, sizeof(entry), "FILE_%d", i); tmp = <API key>(config, "projectfiles", entry, NULL); if (G_UNLIKELY(tmp == NULL)) { break; } else { <API key>(config, "projectfiles", entry, NULL); g_free(tmp); i++; } } #ifdef HAVE_VTE if (vte_info.have_vte) { <API key>(); /* refresh vte_info.dir */ <API key>(config, "VTE", "last_dir", vte_info.dir); } #endif } static void save_install_prefs(GKeyFile *config) { <API key>(config, "AGKInstall", "projects_folder", FALLBACK(install_prefs.projects_folder,"")); <API key>(config, "AGKInstall", "projects_update", install_prefs.<API key>); <API key>(config, "AGKInstall", "libraries_folder", FALLBACK(install_prefs.tier2_folder,"")); <API key>(config, "AGKInstall", "libraries_update", install_prefs.update_tier2_mode); } static void save_dialog_prefs(GKeyFile *config) { /* new settings should be added in init_pref_groups() */ settings_action(config, SETTING_WRITE); /* Some of the key names are not consistent, but this is for backwards compatibility */ /* general */ //<API key>(config, PACKAGE, "<API key>", prefs.load_session); //<API key>(config, PACKAGE, "<API key>", project_prefs.project_session); //<API key>(config, PACKAGE, "<API key>", project_prefs.<API key>); <API key>(config, PACKAGE, "<API key>", prefs.save_winpos); <API key>(config, PACKAGE, "<API key>", prefs.confirm_exit); <API key>(config, PACKAGE, "<API key>", prefs.remember_projects); <API key>(config, PACKAGE, "<API key>", prefs.<API key>); <API key>(config, PACKAGE, "switch_msgwin_pages", prefs.switch_to_status); <API key>(config, PACKAGE, "beep_on_errors", prefs.beep_on_errors); <API key>(config, PACKAGE, "auto_focus", prefs.auto_focus); <API key>(config, PACKAGE, "IDE_version_int", AGK_VERSION_INT); /* interface */ <API key>(config, PACKAGE, "<API key>", interface_prefs.<API key>); <API key>(config, PACKAGE, "<API key>", interface_prefs.<API key>); <API key>(config, PACKAGE, "editor_font", interface_prefs.editor_font); <API key>(config, PACKAGE, "tagbar_font", interface_prefs.tagbar_font); <API key>(config, PACKAGE, "msgwin_font", interface_prefs.msgwin_font); <API key>(config, PACKAGE, "show_notebook_tabs", interface_prefs.show_notebook_tabs); <API key>(config, PACKAGE, "show_tab_cross", file_prefs.show_tab_cross); <API key>(config, PACKAGE, "tab_order_ltr", file_prefs.tab_order_ltr); <API key>(config, PACKAGE, "tab_order_beside", file_prefs.tab_order_beside); <API key>(config, PACKAGE, "tab_pos_editor", interface_prefs.tab_pos_editor); <API key>(config, PACKAGE, "tab_pos_msgwin", interface_prefs.tab_pos_msgwin); <API key>(config, PACKAGE, "<API key>", interface_prefs.<API key>); /* display */ <API key>(config, PACKAGE, "show_indent_guide", editor_prefs.show_indent_guide); <API key>(config, PACKAGE, "show_white_space", editor_prefs.show_white_space); <API key>(config, PACKAGE, "show_line_endings", editor_prefs.show_line_endings); <API key>(config, PACKAGE, "show_markers_margin", editor_prefs.show_markers_margin); <API key>(config, PACKAGE, "<API key>", editor_prefs.<API key>); <API key>(config, PACKAGE, "long_line_enabled", editor_prefs.long_line_enabled); <API key>(config, PACKAGE, "long_line_type", editor_prefs.long_line_type); <API key>(config, PACKAGE, "long_line_column", editor_prefs.long_line_column); <API key>(config, PACKAGE, "long_line_color", editor_prefs.long_line_color); /* editor */ <API key>(config, PACKAGE, "<API key>", editor_prefs.<API key>); <API key>(config, PACKAGE, "<API key>", editor_prefs.<API key>); <API key>(config, PACKAGE, "use_folding", editor_prefs.folding); <API key>(config, PACKAGE, "unfold_all_children", editor_prefs.unfold_all_children); <API key>(config, PACKAGE, "use_indicators", editor_prefs.use_indicators); <API key>(config, PACKAGE, "line_wrapping", editor_prefs.line_wrapping); <API key>(config, PACKAGE, "auto_close_xml_tags", editor_prefs.auto_close_xml_tags); <API key>(config, PACKAGE, "complete_snippets", editor_prefs.complete_snippets); <API key>(config, PACKAGE, "<API key>", editor_prefs.<API key>); <API key>(config, PACKAGE, "<API key>", editor_prefs.disable_dnd); <API key>(config, PACKAGE, "<API key>", editor_prefs.smart_home_key); <API key>(config, PACKAGE, "<API key>", editor_prefs.newline_strip); <API key>(config, PACKAGE, "<API key>", editor_prefs.highlight_selection); <API key>(config, PACKAGE, "line_break_column", editor_prefs.line_break_column); <API key>(config, PACKAGE, "<API key>", editor_prefs.<API key>); <API key>(config, PACKAGE, "comment_toggle_mark", editor_prefs.comment_toggle_mark); <API key>(config, PACKAGE, "<API key>", editor_prefs.<API key>); <API key>(config, PACKAGE, "autoclose_chars", editor_prefs.autoclose_chars); /* files */ <API key>(config, PACKAGE, "<API key>", encodings[file_prefs.<API key>].charset); if (file_prefs.<API key> == -1) <API key>(config, PACKAGE, "<API key>", "none"); else <API key>(config, PACKAGE, "<API key>", encodings[file_prefs.<API key>].charset); <API key>(config, PACKAGE, "<API key>", file_prefs.<API key>); <API key>(config, PACKAGE, "<API key>", file_prefs.final_new_line); <API key>(config, PACKAGE, "<API key>", file_prefs.<API key>); <API key>(config, PACKAGE, "<API key>", file_prefs.replace_tabs); <API key>(config, PACKAGE, "<API key>", file_prefs.<API key>); /* toolbar */ <API key>(config, PACKAGE, "pref_toolbar_show", toolbar_prefs.visible); <API key>(config, PACKAGE, "<API key>", toolbar_prefs.append_to_menu); <API key>(config, PACKAGE, "<API key>", toolbar_prefs.<API key>); <API key>(config, PACKAGE, "<API key>", toolbar_prefs.<API key>); <API key>(config, PACKAGE, "<API key>", toolbar_prefs.icon_style); <API key>(config, PACKAGE, "<API key>", toolbar_prefs.icon_size); /* templates */ <API key>(config, PACKAGE, "<API key>", template_prefs.developer); <API key>(config, PACKAGE, "<API key>", template_prefs.company); <API key>(config, PACKAGE, "pref_template_mail", template_prefs.mail); <API key>(config, PACKAGE, "<API key>", template_prefs.initials); <API key>(config, PACKAGE, "<API key>", template_prefs.version); <API key>(config, PACKAGE, "pref_template_year", template_prefs.year_format); <API key>(config, PACKAGE, "pref_template_date", template_prefs.date_format); <API key>(config, PACKAGE, "<API key>", template_prefs.datetime_format); /* tools settings */ <API key>(config, "tools", "terminal_cmd", tool_prefs.term_cmd ? tool_prefs.term_cmd : ""); <API key>(config, "tools", "browser_cmd", tool_prefs.browser_cmd ? tool_prefs.browser_cmd : ""); <API key>(config, "tools", "grep_cmd", tool_prefs.grep_cmd ? tool_prefs.grep_cmd : ""); <API key>(config, PACKAGE, "context_action_cmd", tool_prefs.context_action_cmd); /* build menu */ build_save_menu(config, NULL, GEANY_BCS_PREF); /* printing */ <API key>(config, "printing", "print_cmd", printing_prefs.external_print_cmd ? printing_prefs.external_print_cmd : ""); <API key>(config, "printing", "use_gtk_printing", printing_prefs.use_gtk_printing); <API key>(config, "printing", "print_line_numbers", printing_prefs.print_line_numbers); <API key>(config, "printing", "print_page_numbers", printing_prefs.print_page_numbers); <API key>(config, "printing", "print_page_header", printing_prefs.print_page_header); <API key>(config, "printing", "<API key>", printing_prefs.<API key>); <API key>(config, "printing", "page_header_datefmt", printing_prefs.page_header_datefmt); /* VTE */ #ifdef HAVE_VTE <API key>(config, "VTE", "load_vte", vte_info.load_vte); if (vte_info.have_vte) { gchar *tmp_string; if (!g_key_file_has_key(config, "VTE", "emulation", NULL)) /* hidden */ <API key>(config, "VTE", "emulation", vc->emulation); if (!g_key_file_has_key(config, "VTE", "<API key>", NULL)) /* hidden */ <API key>(config, "VTE", "<API key>", vc-><API key>); if (!g_key_file_has_key(config, "VTE", "send_cmd_prefix", NULL)) /* hidden */ <API key>(config, "VTE", "send_cmd_prefix", vc->send_cmd_prefix); <API key>(config, "VTE", "font", vc->font); <API key>(config, "VTE", "scroll_on_key", vc->scroll_on_key); <API key>(config, "VTE", "scroll_on_out", vc->scroll_on_out); <API key>(config, "VTE", "enable_bash_keys", vc->enable_bash_keys); <API key>(config, "VTE", "<API key>", vc-><API key>); <API key>(config, "VTE", "follow_path", vc->follow_path); <API key>(config, "VTE", "run_in_vte", vc->run_in_vte); <API key>(config, "VTE", "skip_run_script", vc->skip_run_script); <API key>(config, "VTE", "cursor_blinks", vc->cursor_blinks); <API key>(config, "VTE", "scrollback_lines", vc->scrollback_lines); <API key>(config, "VTE", "font", vc->font); <API key>(config, "VTE", "image", vc->image); <API key>(config, "VTE", "shell", vc->shell); tmp_string = <API key>(&vc->colour_fore); <API key>(config, "VTE", "colour_fore", tmp_string); g_free(tmp_string); tmp_string = <API key>(&vc->colour_back); <API key>(config, "VTE", "colour_back", tmp_string); g_free(tmp_string); } #endif } static void save_ui_prefs(GKeyFile *config) { <API key>(config, PACKAGE, "sidebar_visible", ui_prefs.sidebar_visible); <API key>(config, PACKAGE, "statusbar_visible", interface_prefs.statusbar_visible); <API key>(config, PACKAGE, "msgwindow_visible", ui_prefs.msgwindow_visible); <API key>(config, PACKAGE, "fullscreen", ui_prefs.fullscreen); <API key>(config, PACKAGE, "<API key>", interface_prefs.<API key>); /* get the text from the scribble textview */ { GtkTextBuffer *buffer; GtkTextIter start, end, iter; GtkTextMark *mark; buffer = <API key>(GTK_TEXT_VIEW(msgwindow.scribble)); <API key>(buffer, &start, &end); scribble_text = <API key>(buffer, &start, &end, FALSE); <API key>(config, PACKAGE, "scribble_text", scribble_text); g_free(scribble_text); mark = <API key>(buffer); <API key>(buffer, &iter, mark); scribble_pos = <API key>(&iter); <API key>(config, PACKAGE, "scribble_pos", scribble_pos); } if (prefs.save_winpos) { GdkWindowState wstate; <API key>(config, PACKAGE, "treeview_position", <API key>(GTK_PANED(ui_lookup_widget(main_widgets.window, "hpaned1")))); //<API key>(config, PACKAGE, "msgwindow_position", // <API key>(GTK_PANED(ui_lookup_widget(main_widgets.window, "vpaned2")))); <API key>(config, PACKAGE, "msgwindow_position", <API key>() ); <API key>(GTK_WINDOW(main_widgets.window), &ui_prefs.geometry[0], &ui_prefs.geometry[1]); gtk_window_get_size(GTK_WINDOW(main_widgets.window), &ui_prefs.geometry[2], &ui_prefs.geometry[3]); wstate = <API key>(<API key>(main_widgets.window)); ui_prefs.geometry[4] = (wstate & <API key>) ? 1 : 0; <API key>(config, PACKAGE, "geometry", ui_prefs.geometry, 5); } <API key>(config, PACKAGE, "custom_date_format", ui_prefs.custom_date_format); if (ui_prefs.custom_commands != NULL) { <API key>(config, PACKAGE, "custom_commands", (const gchar**) ui_prefs.custom_commands, g_strv_length(ui_prefs.custom_commands)); <API key>(config, PACKAGE, "<API key>", (const gchar**) ui_prefs.<API key>, g_strv_length(ui_prefs.<API key>)); } } void configuration_save(void) { GKeyFile *config = g_key_file_new(); gchar *configfile = g_build_filename(app->configdir, "geany.conf", NULL); gchar *data; <API key>(config, configfile, G_KEY_FILE_NONE, NULL); /* this signal can be used e.g. to prepare any settings before Stash code reads them below */ <API key>(geany_object, "save-settings", config); save_dialog_prefs(config); save_ui_prefs(config); save_install_prefs(config); build_save_prefs(config); project_save_prefs(config); /* save project filename, etc. */ save_recent_files(config, ui_prefs.recent_queue, "recent_files"); save_recent_files(config, ui_prefs.<API key>, "recent_projects"); if ( prefs.remember_projects ) <API key>(config); /* if (cl_options.load_session) <API key>(config); #ifdef HAVE_VTE else if (vte_info.have_vte) { <API key>(); // refresh vte_info.dir <API key>(config, "VTE", "last_dir", vte_info.dir); } #endif */ /* write the file */ data = g_key_file_to_data(config, NULL, NULL); utils_write_file(configfile, data); g_free(data); g_key_file_free(config); g_free(configfile); } static void load_recent_files(GKeyFile *config, GQueue *queue, const gchar *key) { gchar **recent_files; gsize i, len = 0; recent_files = <API key>(config, "files", key, &len, NULL); if (recent_files != NULL) { for (i = 0; (i < len) && (i < file_prefs.mru_length); i++) { gchar *filename = g_strdup(recent_files[i]); g_queue_push_tail(queue, filename); } g_strfreev(recent_files); } } void <API key>(GKeyFile *config) { load_recent_files(config, ui_prefs.recent_queue, "recent_files"); load_recent_files(config, ui_prefs.<API key>, "recent_projects"); } void <API key>(GKeyFile *config) { guint i; gboolean have_session_files; gchar entry[30]; gchar **tmp_array; GError *error = NULL; have_session_files = TRUE; i = 0; while (have_session_files) { g_snprintf(entry, sizeof(entry), "PROJECT_FILE_NAME_%d", i); tmp_array = <API key>(config, "projects", entry, NULL, &error); if (! tmp_array || error) { g_error_free(error); error = NULL; have_session_files = FALSE; } else { gchar* unescaped_filename = <API key>(tmp_array[1], NULL); gchar* locale_filename = <API key>(unescaped_filename); GeanyProject *curr_project = app->project; project_load_file(locale_filename); if ( atoi(tmp_array[0]) == 0 ) app->project = curr_project; g_free(locale_filename); g_free(unescaped_filename); g_strfreev(tmp_array); } i++; } if ( app->project == NULL ) app->project = <API key>(); project_update_list(); } /* * Load session list from the given keyfile, and store it in the global * session_files variable for later file loading * */ void <API key>(GKeyFile *config, GeanyProject *project) { guint i; gboolean have_session_files; gchar entry[16]; gchar **tmp_array; GError *error = NULL; //<API key> = <API key>(config, "files", "current_page", -1); /* the project may load another list than the main setting */ if (session_files != NULL) g_ptr_array_free(session_files, TRUE); session_files = g_ptr_array_new(); have_session_files = TRUE; i = 0; while (have_session_files) { g_snprintf(entry, sizeof(entry), "FILE_NAME_%d", i); tmp_array = <API key>(config, "files", entry, NULL, &error); if (! tmp_array || error) { g_error_free(error); error = NULL; have_session_files = FALSE; } g_ptr_array_add(session_files, tmp_array); i++; } #ifdef HAVE_VTE /* BUG: after loading project at startup, closing project doesn't restore old VTE path */ if (vte_info.have_vte) { gchar *tmp_string = <API key>(config, "VTE", "last_dir", NULL); vte_cwd(tmp_string,TRUE); g_free(tmp_string); } #endif // open the files straight away, we're not going to overwrite the list <API key>( project ); } void <API key>(GKeyFile *config, GeanyProject *project) { guint i, j; gchar entry[16]; gchar **tmp_array; GError *error = NULL; /* the project may load another list than the main setting */ if (project->project_groups != NULL) g_ptr_array_free(project->project_groups, TRUE); if (project->project_files != NULL) g_ptr_array_free(project->project_files, TRUE); project->project_groups = g_ptr_array_new(); project->project_files = g_ptr_array_new(); i = 0; while (1) { g_snprintf(entry, sizeof(entry), "GROUP_%d", i); tmp_array = <API key>(config, "projectgroups", entry, NULL, &error); if (! tmp_array || error) { g_error_free(error); error = NULL; break; } gint new_idx = <API key>( project ); if (new_idx == -1) /* expand the array, no free places */ { GeanyProjectGroup *group = g_new0(GeanyProjectGroup, 1); new_idx = project->project_groups->len; g_ptr_array_add(project->project_groups, group); } GeanyProjectGroup *group = project->project_groups->pdata[new_idx]; group->is_valid = TRUE; group->group_name = g_strdup( tmp_array[0] ); group->index = new_idx; group->pProject = project; group->pParent = 0; gint index = atoi( tmp_array[1] ); if ( index > 0 && index < project->project_groups->len ) group->pParent = project->project_groups->pdata[index]; g_strfreev(tmp_array); i++; } i = 0; while (1) { g_snprintf(entry, sizeof(entry), "FILE_%d", i); tmp_array = <API key>(config, "projectfiles", entry, NULL, &error); if (! tmp_array || error) { g_error_free(error); error = NULL; break; } gint new_idx = <API key>( project ); if (new_idx == -1) /* expand the array, no free places */ { GeanyProjectFile *file = g_new0(GeanyProjectFile, 1); new_idx = project->project_files->len; g_ptr_array_add(project->project_files, file); } gchar* unescaped_filename = <API key>(tmp_array[0], NULL); gchar* locale_filename = <API key>(unescaped_filename); GeanyProjectFile *file = project->project_files->pdata[new_idx]; if ( !g_path_is_absolute(locale_filename) ) { file->file_name = g_build_filename( project->base_path, locale_filename, NULL ); //file->file_name = utils_get_real_path( full_path ); utils_tidy_path( file->file_name ); //g_free(full_path); } else file->file_name = g_strdup( locale_filename ); gboolean bFound = FALSE; for (j = 0; j < project->project_files->len; j++) { GeanyProjectFile *file2 = project->project_files->pdata[j]; if (file2 != NULL && file2->is_valid) { if ( strcmp( file2->file_name, file->file_name ) == 0 ) { g_free(file->file_name); file->file_name = 0; bFound = TRUE; break; } } } if ( bFound ) { i++; g_free(locale_filename); g_free(unescaped_filename); g_strfreev(tmp_array); continue; } file->is_valid = TRUE; gint index = atoi( tmp_array[1] ); if ( index > 0 && index < project->project_groups->len ) file->pParent = project->project_groups->pdata[index]; g_free(locale_filename); g_free(unescaped_filename); g_strfreev(tmp_array); i++; } } #ifdef HAVE_VTE static void get_setting_color(GKeyFile *config, const gchar *section, const gchar *key, GdkColor *color, const gchar *default_color) { gchar *str = <API key>(config, section, key, NULL); if (str == NULL || ! utils_parse_color(str, color)) utils_parse_color(default_color, color); g_free(str); } #endif static void load_install_prefs(GKeyFile *config) { install_prefs.projects_folder = <API key>(config, "AGKInstall", "projects_folder", NULL); install_prefs.<API key> = <API key>(config, "AGKInstall", "projects_update", -1); install_prefs.tier2_folder = <API key>(config, "AGKInstall", "libraries_folder", NULL); install_prefs.update_tier2_mode = <API key>(config, "AGKInstall", "libraries_update", -1); } /* note: new settings should be added in init_pref_groups() */ static void load_dialog_prefs(GKeyFile *config) { gchar *tmp_string, *tmp_string2; const gchar *default_charset = NULL; gchar *cmd; /* compatibility with Geany 0.20 */ if (!g_key_file_has_key(config, PACKAGE, <API key>, NULL)) { <API key>(config, PACKAGE, <API key>, <API key>(config, PACKAGE, "<API key>", FALSE)); } /* compatibility with Geany 0.21 */ { gboolean <API key> = <API key>(config, PACKAGE, "<API key>", FALSE); if (!g_key_file_has_key(config, "search", "<API key>", NULL)) <API key>(config, "search", "<API key>", <API key>); if (!g_key_file_has_key(config, "search", "<API key>", NULL)) <API key>(config, "search", "<API key>", <API key>); } /* read stash prefs */ settings_action(config, SETTING_READ); /* general */ prefs.confirm_exit = <API key>(config, PACKAGE, "<API key>", FALSE); prefs.remember_projects = <API key>(config, PACKAGE, "<API key>", TRUE); prefs.<API key> = <API key>(config, PACKAGE, "<API key>", FALSE); //prefs.load_session = <API key>(config, PACKAGE, "<API key>", TRUE); prefs.load_session = FALSE; //project_prefs.project_session = <API key>(config, PACKAGE, "<API key>", TRUE); //project_prefs.<API key> = <API key>(config, PACKAGE, "<API key>", FALSE); project_prefs.project_session = TRUE; project_prefs.<API key> = TRUE; prefs.save_winpos = <API key>(config, PACKAGE, "<API key>", TRUE); prefs.beep_on_errors = <API key>(config, PACKAGE, "beep_on_errors", TRUE); prefs.switch_to_status = <API key>(config, PACKAGE, "switch_msgwin_pages", FALSE); prefs.auto_focus = <API key>(config, PACKAGE, "auto_focus", FALSE); /* interface */ interface_prefs.tab_pos_editor = <API key>(config, PACKAGE, "tab_pos_editor", GTK_POS_TOP); interface_prefs.tab_pos_msgwin = <API key>(config, PACKAGE, "tab_pos_msgwin",GTK_POS_LEFT); interface_prefs.<API key> = <API key>(config, PACKAGE, "<API key>", TRUE); interface_prefs.<API key> = <API key>(config, PACKAGE, "<API key>", TRUE); interface_prefs.statusbar_visible = <API key>(config, PACKAGE, "statusbar_visible", TRUE); interface_prefs.<API key> = <API key>(config, PACKAGE, "<API key>", TRUE); file_prefs.tab_order_ltr = <API key>(config, PACKAGE, "tab_order_ltr", TRUE); file_prefs.tab_order_beside = <API key>(config, PACKAGE, "tab_order_beside", FALSE); interface_prefs.show_notebook_tabs = <API key>(config, PACKAGE, "show_notebook_tabs", TRUE); file_prefs.show_tab_cross = <API key>(config, PACKAGE, "show_tab_cross", TRUE); interface_prefs.editor_font = <API key>(config, PACKAGE, "editor_font", <API key>); interface_prefs.tagbar_font = <API key>(config, PACKAGE, "tagbar_font", <API key>); interface_prefs.msgwin_font = <API key>(config, PACKAGE, "msgwin_font", <API key>); interface_prefs.<API key> = <API key>(config, PACKAGE, "<API key>", TRUE); if ( interface_prefs.<API key> ) interface_prefs.tab_pos_msgwin = GTK_POS_TOP; /* display, editor */ editor_prefs.long_line_enabled = <API key>(config, PACKAGE, "long_line_enabled", FALSE); editor_prefs.long_line_type = <API key>(config, PACKAGE, "long_line_type", 0); if (editor_prefs.long_line_type == 2) /* backward compatibility */ { editor_prefs.long_line_type = 0; editor_prefs.long_line_enabled = FALSE; } editor_prefs.long_line_color = <API key>(config, PACKAGE, "long_line_color", "#C2EBC2"); editor_prefs.long_line_column = <API key>(config, PACKAGE, "long_line_column", 72); editor_prefs.<API key> = <API key>(config, PACKAGE, "<API key>", <API key>); editor_prefs.<API key> = <API key>(config, PACKAGE, "<API key>", <API key>); editor_prefs.line_wrapping = <API key>(config, PACKAGE, "line_wrapping", FALSE); /* default is off for better performance */ editor_prefs.use_indicators = <API key>(config, PACKAGE, "use_indicators", TRUE); editor_prefs.show_indent_guide = <API key>(config, PACKAGE, "show_indent_guide", FALSE); editor_prefs.show_white_space = <API key>(config, PACKAGE, "show_white_space", FALSE); editor_prefs.show_line_endings = <API key>(config, PACKAGE, "show_line_endings", FALSE); editor_prefs.<API key> = <API key>(config, PACKAGE, "<API key>", FALSE); editor_prefs.IDE_version = <API key>(config, PACKAGE, "IDE_version_int", 0); if ( editor_prefs.IDE_version < 1 ) editor_prefs.<API key> = FALSE; editor_prefs.auto_close_xml_tags = <API key>(config, PACKAGE, "auto_close_xml_tags", TRUE); editor_prefs.complete_snippets = <API key>(config, PACKAGE, "complete_snippets", TRUE); editor_prefs.<API key> = <API key>(config, PACKAGE, "<API key>", TRUE); editor_prefs.folding = <API key>(config, PACKAGE, "use_folding", TRUE); editor_prefs.unfold_all_children = <API key>(config, PACKAGE, "unfold_all_children", FALSE); editor_prefs.show_markers_margin = <API key>(config, PACKAGE, "show_markers_margin", TRUE); editor_prefs.<API key> = <API key>(config, PACKAGE, "<API key>", TRUE); editor_prefs.disable_dnd = <API key>(config, PACKAGE, "<API key>", FALSE); editor_prefs.smart_home_key = <API key>(config, PACKAGE, "<API key>", TRUE); editor_prefs.newline_strip = <API key>(config, PACKAGE, "<API key>", FALSE); editor_prefs.highlight_selection = <API key>(config, PACKAGE, "<API key>", TRUE); editor_prefs.line_break_column = <API key>(config, PACKAGE, "line_break_column", 72); editor_prefs.<API key> = <API key>(config, PACKAGE, "<API key>", TRUE); editor_prefs.comment_toggle_mark = <API key>(config, PACKAGE, "comment_toggle_mark", GEANY_TOGGLE_MARK); editor_prefs.autoclose_chars = <API key>(config, PACKAGE, "autoclose_chars", 0); /* Files * use current locale encoding as default for new files (should be UTF-8 in most cases) */ g_get_charset(&default_charset); //tmp_string = <API key>(config, PACKAGE, "<API key>", "UTF-8"); // from version 21 default is UTF-8 tmp_string = g_strdup("UTF-8"); if (tmp_string) { const GeanyEncoding *enc = <API key>(tmp_string); if (enc != NULL) file_prefs.<API key> = enc->idx; else file_prefs.<API key> = <API key>; g_free(tmp_string); } //tmp_string = <API key>(config, PACKAGE, "<API key>", "UTF-8"); // from version 21 default is UTF-8 tmp_string = g_strdup("UTF-8"); if (tmp_string) { const GeanyEncoding *enc = <API key>(tmp_string); if (enc != NULL) file_prefs.<API key> = enc->idx; else file_prefs.<API key> = -1; g_free(tmp_string); } file_prefs.<API key> = <API key>(config, PACKAGE, "<API key>", <API key>); file_prefs.replace_tabs = <API key>(config, PACKAGE, "<API key>", FALSE); file_prefs.<API key> = <API key>(config, PACKAGE, "<API key>", FALSE); file_prefs.final_new_line = <API key>(config, PACKAGE, "<API key>", TRUE); file_prefs.<API key> = <API key>(config, PACKAGE, "<API key>", FALSE); /* toolbar */ toolbar_prefs.visible = <API key>(config, PACKAGE, "pref_toolbar_show", TRUE); toolbar_prefs.append_to_menu = <API key>(config, PACKAGE, "<API key>", FALSE); { toolbar_prefs.<API key> = <API key>(config, PACKAGE, "<API key>", FALSE); if (! toolbar_prefs.<API key>) toolbar_prefs.icon_style = <API key>(config, PACKAGE, "<API key>", GTK_TOOLBAR_BOTH); toolbar_prefs.<API key> = <API key>(config, PACKAGE, "<API key>", FALSE); if (! toolbar_prefs.<API key>) toolbar_prefs.icon_size = <API key>(config, PACKAGE, "<API key>", <API key>); } /* VTE */ #ifdef HAVE_VTE vte_info.load_vte = <API key>(config, "VTE", "load_vte", TRUE); if (vte_info.load_vte) { struct passwd *pw = getpwuid(getuid()); const gchar *shell = (pw != NULL) ? pw->pw_shell : "/bin/sh"; vc = g_new0(VteConfig, 1); vte_info.dir = <API key>(config, "VTE", "last_dir", NULL); if ((vte_info.dir == NULL || utils_str_equal(vte_info.dir, "")) && pw != NULL) /* last dir is not set, fallback to user's home directory */ SETPTR(vte_info.dir, g_strdup(pw->pw_dir)); else if (vte_info.dir == NULL && pw == NULL) /* fallback to root */ vte_info.dir = g_strdup("/"); vc->emulation = <API key>(config, "VTE", "emulation", "xterm"); vc-><API key> = <API key>(config, "VTE", "<API key>", FALSE); vc->image = <API key>(config, "VTE", "image", ""); vc->shell = <API key>(config, "VTE", "shell", shell); vc->font = <API key>(config, "VTE", "font", "Monospace 10"); vc->scroll_on_key = <API key>(config, "VTE", "scroll_on_key", TRUE); vc->scroll_on_out = <API key>(config, "VTE", "scroll_on_out", TRUE); vc->enable_bash_keys = <API key>(config, "VTE", "enable_bash_keys", TRUE); vc-><API key> = <API key>(config, "VTE", "<API key>", FALSE); vc->follow_path = <API key>(config, "VTE", "follow_path", FALSE); vc->send_cmd_prefix = <API key>(config, "VTE", "send_cmd_prefix", ""); vc->run_in_vte = <API key>(config, "VTE", "run_in_vte", FALSE); vc->skip_run_script = <API key>(config, "VTE", "skip_run_script", FALSE); vc->cursor_blinks = <API key>(config, "VTE", "cursor_blinks", FALSE); vc->scrollback_lines = <API key>(config, "VTE", "scrollback_lines", 500); get_setting_color(config, "VTE", "colour_fore", &vc->colour_fore, "#ffffff"); get_setting_color(config, "VTE", "colour_back", &vc->colour_back, "#000000"); } #endif /* templates */ template_prefs.developer = <API key>(config, PACKAGE, "<API key>", g_get_real_name()); template_prefs.company = <API key>(config, PACKAGE, "<API key>", ""); tmp_string = utils_get_initials(template_prefs.developer); template_prefs.initials = <API key>(config, PACKAGE, "<API key>", tmp_string); g_free(tmp_string); template_prefs.version = <API key>(config, PACKAGE, "<API key>", "1.0"); tmp_string = g_strdup_printf("%s@%s", g_get_user_name(), g_get_host_name()); template_prefs.mail = <API key>(config, PACKAGE, "pref_template_mail", tmp_string); g_free(tmp_string); template_prefs.year_format = <API key>(config, PACKAGE, "pref_template_year", <API key>); template_prefs.date_format = <API key>(config, PACKAGE, "pref_template_date", <API key>); template_prefs.datetime_format = <API key>(config, PACKAGE, "<API key>", <API key>); /* tools */ cmd = <API key>(config, "tools", "terminal_cmd", ""); if (EMPTY(cmd)) { SETPTR(cmd, <API key>(config, "tools", "term_cmd", "")); if (!EMPTY(cmd)) { tmp_string = cmd; #ifdef G_OS_WIN32 if (strstr(cmd, "cmd.exe")) cmd = g_strconcat(cmd, " /Q /C %c", NULL); else cmd = g_strconcat(cmd, " %c", NULL); #else cmd = g_strconcat(cmd, " -e \"/bin/sh %c\"", NULL); #endif g_free(tmp_string); } else SETPTR(cmd, g_strdup(<API key>)); } tool_prefs.term_cmd = cmd; tool_prefs.browser_cmd = <API key>(config, "tools", "browser_cmd", <API key>); tool_prefs.grep_cmd = <API key>(config, "tools", "grep_cmd", <API key>); tool_prefs.context_action_cmd = <API key>(config, PACKAGE, "context_action_cmd", ""); /* build menu */ <API key>(GEANY_GBG_FT, build_menu_prefs.<API key>); <API key>(GEANY_GBG_NON_FT, build_menu_prefs.<API key>); <API key>(GEANY_GBG_EXEC, build_menu_prefs.<API key>); build_load_menu(config, GEANY_BCS_PREF, NULL); /* printing */ tmp_string2 = <API key>(<API key>); #ifdef G_OS_WIN32 if (!EMPTY(tmp_string2)) { /* single quote paths on Win32 for <API key> */ tmp_string = g_strconcat("'", tmp_string2, "' '%f'", NULL); } else { tmp_string = g_strdup(""); } #else tmp_string = g_strconcat(tmp_string2, " %f", NULL); #endif printing_prefs.external_print_cmd = <API key>(config, "printing", "print_cmd", tmp_string); g_free(tmp_string); g_free(tmp_string2); printing_prefs.use_gtk_printing = <API key>(config, "printing", "use_gtk_printing", TRUE); printing_prefs.print_line_numbers = <API key>(config, "printing", "print_line_numbers", TRUE); printing_prefs.print_page_numbers = <API key>(config, "printing", "print_page_numbers", TRUE); printing_prefs.print_page_header = <API key>(config, "printing", "print_page_header", TRUE); printing_prefs.<API key> = <API key>(config, "printing", "<API key>", FALSE); printing_prefs.page_header_datefmt = <API key>(config, "printing", "page_header_datefmt", "%c"); } static void load_ui_prefs(GKeyFile *config) { gint *geo; gsize geo_len; ui_prefs.sidebar_visible = <API key>(config, PACKAGE, "sidebar_visible", TRUE); ui_prefs.msgwindow_visible = <API key>(config, PACKAGE, "msgwindow_visible", TRUE); ui_prefs.fullscreen = <API key>(config, PACKAGE, "fullscreen", FALSE); ui_prefs.custom_date_format = <API key>(config, PACKAGE, "custom_date_format", ""); ui_prefs.custom_commands = <API key>(config, PACKAGE, "custom_commands", NULL, NULL); ui_prefs.<API key> = <API key>(config, PACKAGE, "<API key>", NULL, NULL); /* sanitize custom commands labels */ if (ui_prefs.custom_commands || ui_prefs.<API key>) { guint i; guint cc_len = ui_prefs.custom_commands ? g_strv_length(ui_prefs.custom_commands) : 0; guint cc_labels_len = ui_prefs.<API key> ? g_strv_length(ui_prefs.<API key>) : 0; /* not enough items, resize and fill */ if (cc_labels_len < cc_len) { ui_prefs.<API key> = g_realloc(ui_prefs.<API key>, (cc_len + 1) * sizeof *ui_prefs.<API key>); for (i = cc_labels_len; i < cc_len; i++) ui_prefs.<API key>[i] = g_strdup(""); ui_prefs.<API key>[cc_len] = NULL; } /* too many items, cut off */ else if (cc_labels_len > cc_len) { for (i = cc_len; i < cc_labels_len; i++) { g_free(ui_prefs.<API key>[i]); ui_prefs.<API key>[i] = NULL; } } } scribble_text = <API key>(config, PACKAGE, "scribble_text", _("Type here what you want, use it as a notice/scratch board")); scribble_pos = <API key>(config, PACKAGE, "scribble_pos", -1); geo = <API key>(config, PACKAGE, "geometry", &geo_len, NULL); if (! geo || geo_len < 5) { ui_prefs.geometry[0] = -1; ui_prefs.geometry[1] = -1; ui_prefs.geometry[2] = -1; ui_prefs.geometry[3] = -1; ui_prefs.geometry[4] = 0; } else { /* don't use insane values but when main windows was maximized last time, pos might be * negative (due to differences in root window and window decorations) */ /* quitting when minimized can make pos -32000, -32000 on Windows! */ ui_prefs.geometry[0] = MAX(-1, geo[0]); ui_prefs.geometry[1] = MAX(-1, geo[1]); ui_prefs.geometry[2] = MAX(-1, geo[2]); ui_prefs.geometry[3] = MAX(-1, geo[3]); ui_prefs.geometry[4] = geo[4] != 0; } hpan_position = <API key>(config, PACKAGE, "treeview_position", 156); vpan_position = <API key>(config, PACKAGE, "msgwindow_position", 200); g_free(geo); } /* * Save current session in default configuration file */ void <API key>(void) { // only project files should load other files return; /* gchar *configfile = g_build_filename(app->configdir, "geany.conf", NULL); gchar *data; GKeyFile *config = g_key_file_new(); <API key>(config, configfile, G_KEY_FILE_NONE, NULL); if (cl_options.load_session) <API key>(config); // write the file data = g_key_file_to_data(config, NULL, NULL); utils_write_file(configfile, data); g_free(data); g_key_file_free(config); g_free(configfile); */ } /* * Only reload the session part of the default configuration */ void <API key>(void) { /* gchar *configfile = g_build_filename(app->configdir, "geany.conf", NULL); GKeyFile *config = g_key_file_new(); <API key>(config, configfile, G_KEY_FILE_NONE, NULL); g_free(configfile); <API key>(config, FALSE); g_key_file_free(config); */ } gboolean configuration_load(void) { gchar *configfile = g_build_filename(app->configdir, "geany.conf", NULL); GKeyFile *config = g_key_file_new(); if (! g_file_test(configfile, <API key>)) { /* config file does not (yet) exist, so try to load a global config file which may be */ geany_debug("No user config file found, trying to use global configuration."); SETPTR(configfile, g_build_filename(app->datadir, "geany.conf", NULL)); } <API key>(config, configfile, G_KEY_FILE_NONE, NULL); g_free(configfile); load_dialog_prefs(config); load_ui_prefs(config); load_install_prefs(config); project_load_prefs(config); build_load_prefs(config); <API key>(config); /* this signal can be used e.g. to delay building UI elements until settings have been read */ <API key>(geany_object, "load-settings", config); g_key_file_free(config); return TRUE; } gboolean <API key>(void) { if ( !prefs.remember_projects ) return TRUE; gchar *configfile = g_build_filename(app->configdir, "geany.conf", NULL); GKeyFile *config = g_key_file_new(); if (! g_file_test(configfile, <API key>)) { /* config file does not (yet) exist, so try to load a global config file which may be */ geany_debug("No user config file found, trying to use global configuration."); SETPTR(configfile, g_build_filename(app->datadir, "geany.conf", NULL)); } <API key>(config, configfile, G_KEY_FILE_NONE, NULL); g_free(configfile); <API key>(config); g_key_file_free(config); return TRUE; } static gboolean open_session_file(gchar **tmp, guint len) { guint pos; const gchar *ft_name; gchar *locale_filename; gchar *unescaped_filename; const gchar *encoding; gint indent_type; gboolean ro, auto_indent, line_wrapping; /** TODO when we have a global pref for line breaking, use its value */ gboolean line_breaking = FALSE; gboolean ret = FALSE; pos = atoi(tmp[0]); ft_name = tmp[1]; ro = atoi(tmp[2]); if (isdigit(tmp[3][0])) { encoding = <API key>(atoi(tmp[3])); } else { encoding = &(tmp[3][1]); } /* try to get the locale equivalent for the filename */ unescaped_filename = <API key>(tmp[7], NULL); locale_filename = <API key>(unescaped_filename); if ( !g_path_is_absolute(locale_filename) ) { // todo build absolute path from relative path } if (g_file_test(locale_filename, <API key>)) { GeanyFiletype *ft = <API key>(ft_name); GeanyDocument *doc = <API key>( NULL, locale_filename, pos, ro, ft, encoding ); } else { geany_debug("Could not find file '%s'.", tmp[7]); } g_free(locale_filename); g_free(unescaped_filename); return ret; } static gint <API key>(gconstpointer a, gconstpointer b) { gchar **tmpA = *((gchar***) a); gchar **tmpB = *((gchar***) b); int orderA = 0; int orderB = 0; if ( tmpA && g_strv_length(tmpA) > 3 ) orderA = atoi(tmpA[3]); if ( tmpB && g_strv_length(tmpB) > 3 ) orderB = atoi(tmpB[3]); if ( orderA < orderB ) return -1; else if ( orderA > orderB ) return 1; else return 0; } /* Open session files * Note: notebook page switch handler and adding to recent files list is always disabled * for all files opened within this function */ void <API key>(GeanyProject *project) { gint i; gboolean failure = FALSE; /* necessary to set it to TRUE for project session support */ main_status.<API key> = TRUE; GeanyDocument *set_curr_doc = NULL; g_ptr_array_sort( session_files, <API key> ); i = file_prefs.tab_order_ltr ? 0 : (session_files->len - 1); while (TRUE) { gchar **tmp = g_ptr_array_index(session_files, i); guint len; if (tmp != NULL && g_strv_length(tmp) >= 2) { gchar* unescaped_filename = <API key>(tmp[1], NULL); gchar* locale_filename = <API key>(unescaped_filename); if ( !g_path_is_absolute(locale_filename) ) { SETPTR(locale_filename, g_build_filename( project->base_path, locale_filename, NULL )); utils_tidy_path( locale_filename ); } if (g_file_test(locale_filename, <API key>)) { GeanyDocument *doc = <API key>( NULL, locale_filename, 0, FALSE, NULL, NULL ); if ( !doc ) failure = TRUE; else { if ( g_strv_length(tmp) > 2 ) editor_goto_pos(doc->editor, atoi(tmp[2]), FALSE); if ( atoi(tmp[0]) == 1 ) set_curr_doc = doc; } } else failure = TRUE; g_free(locale_filename); g_free(unescaped_filename); } g_strfreev(tmp); if (file_prefs.tab_order_ltr) { i++; if (i >= (gint)session_files->len) break; } else { i if (i < 0) break; } } g_ptr_array_free(session_files, TRUE); session_files = NULL; if (failure) ui_set_statusbar(TRUE, _("Failed to load one or more session files.")); else if (<API key> >= 0) { /* explicitly allow notebook switch page callback to be called for window title, * encoding settings and so other things */ main_status.<API key> = FALSE; /** TODO if <API key> is equal to the current notebook tab(the last opened) ** the notebook switch page callback isn't triggered and e.g. menu items are not updated */ //<API key>(GTK_NOTEBOOK(main_widgets.notebook), <API key>); } main_status.<API key> = FALSE; if ( set_curr_doc ) { gint page = <API key>(set_curr_doc); <API key>( GTK_NOTEBOOK(main_widgets.notebook), page ); //document_grab_focus(set_curr_doc); } <API key>(<API key>(), FALSE); } /* set some settings which are already read from the config file, but need other things, like the * realisation of the main window */ void <API key>(void) { if (scribble_text) { /* update the scribble widget, because now it's realized */ GtkTextIter iter; GtkTextBuffer *buffer = <API key>(GTK_TEXT_VIEW(msgwindow.scribble)); <API key>(buffer, scribble_text, -1); <API key>(buffer, &iter, scribble_pos); <API key>(buffer, &iter); } g_free(scribble_text); /* set the position of the hpaned and vpaned */ if (prefs.save_winpos) { <API key>(GTK_PANED(ui_lookup_widget(main_widgets.window, "hpaned1")), hpan_position); //<API key>(GTK_PANED(ui_lookup_widget(main_widgets.window, "vpaned2")), vpan_position); <API key>(vpan_position); <API key>(); } /* set fullscreen after initial draw so that returning to normal view is the right size. * fullscreen mode is disabled by default, so act only if it is true */ if (ui_prefs.fullscreen) { <API key>(GTK_CHECK_MENU_ITEM(ui_lookup_widget(main_widgets.window, "menu_fullscreen1")), TRUE); ui_prefs.fullscreen = TRUE; ui_set_fullscreen(); } <API key>(); } void configuration_init(void) { keyfile_groups = g_ptr_array_new(); pref_groups = g_ptr_array_new(); init_pref_groups(); } void <API key>(void) { guint i; StashGroup *group; foreach_ptr_array(group, i, keyfile_groups) stash_group_free(group); g_ptr_array_free(keyfile_groups, TRUE); g_ptr_array_free(pref_groups, TRUE); }
#define BOOST_TEST_DYN_LINK #define BOOST_TEST_NO_MAIN #include <boost/test/unit_test.hpp> #include "arguments.hh" #include "base32.hh" #include "dnssecinfra.hh" #include "dnsseckeeper.hh" #include "lua-recursor4.hh" #include "namespaces.hh" #include "rec-lua-conf.hh" #include "root-dnssec.hh" #include "syncres.hh" #include "test-common.hh" #include "utility.hh" #include "validate-recursor.hh" RecursorStats g_stats; GlobalStateHolder<LuaConfigItems> g_luaconfs; thread_local std::unique_ptr<MemRecursorCache> t_RC{nullptr}; unsigned int g_numThreads = 1; bool g_lowercaseOutgoing = false; /* Fake some required functions we didn't want the trouble to link with */ ArgvMap &arg() { static ArgvMap theArg; return theArg; } int getMTaskerTID() { return 0; } bool RecursorLua4::preoutquery(const ComboAddress& ns, const ComboAddress& requestor, const DNSName& query, const QType& qtype, bool isTcp, vector<DNSRecord>& res, int& ret) { return false; } int asyncresolve(const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { return 0; } /* primeHints() is only here for now because it was way too much trouble to link with the real one. We should fix this, empty functions are one thing, but this is bad. */ #include "root-addresses.hh" void primeHints(void) { vector<DNSRecord> nsset; if(!t_RC) t_RC = std::unique_ptr<MemRecursorCache>(new MemRecursorCache()); DNSRecord arr, aaaarr, nsrr; nsrr.d_name=g_rootdnsname; arr.d_type=QType::A; aaaarr.d_type=QType::AAAA; nsrr.d_type=QType::NS; arr.d_ttl=aaaarr.d_ttl=nsrr.d_ttl=time(nullptr)+3600000; for(char c='a';c<='m';++c) { char templ[40]; strncpy(templ,"a.root-servers.net.", sizeof(templ) - 1); templ[sizeof(templ)-1] = '\0'; *templ=c; aaaarr.d_name=arr.d_name=DNSName(templ); nsrr.d_content=std::make_shared<NSRecordContent>(DNSName(templ)); arr.d_content=std::make_shared<ARecordContent>(ComboAddress(rootIps4[c-'a'])); vector<DNSRecord> aset; aset.push_back(arr); t_RC->replace(time(nullptr), DNSName(templ), QType(QType::A), aset, vector<std::shared_ptr<RRSIGRecordContent>>(), vector<std::shared_ptr<DNSRecord>>(), true); // auth, nuke it all if (rootIps6[c-'a'] != NULL) { aaaarr.d_content=std::make_shared<AAAARecordContent>(ComboAddress(rootIps6[c-'a'])); vector<DNSRecord> aaaaset; aaaaset.push_back(aaaarr); t_RC->replace(time(nullptr), DNSName(templ), QType(QType::AAAA), aaaaset, vector<std::shared_ptr<RRSIGRecordContent>>(), vector<std::shared_ptr<DNSRecord>>(), true); } nsset.push_back(nsrr); } t_RC->replace(time(nullptr), g_rootdnsname, QType(QType::NS), nsset, vector<std::shared_ptr<RRSIGRecordContent>>(), vector<std::shared_ptr<DNSRecord>>(), false); // and stuff in the cache } LuaConfigItems::LuaConfigItems() { for (const auto &dsRecord : rootDSs) { auto ds=unique_ptr<DSRecordContent>(dynamic_cast<DSRecordContent*>(DSRecordContent::make(dsRecord))); dsAnchors[g_rootdnsname].insert(*ds); } } /* Some helpers functions */ static void init(bool debug=false) { L.setName("test"); L.disableSyslog(true); if (debug) { L.setLoglevel((Logger::Urgency)(6)); // info and up L.toConsole(Logger::Info); } else { L.setLoglevel(Logger::None); L.toConsole(Logger::Error); } seedRandom("/dev/urandom"); reportAllTypes(); t_RC = std::unique_ptr<MemRecursorCache>(new MemRecursorCache()); SyncRes::s_maxqperq = 50; SyncRes::s_maxtotusec = 1000*7000; SyncRes::s_maxdepth = 40; SyncRes::s_maxnegttl = 3600; SyncRes::s_maxcachettl = 86400; SyncRes::s_packetcachettl = 3600; SyncRes::<API key> = 60; SyncRes::<API key> = 64; SyncRes::<API key> = 60; SyncRes::s_doIPv6 = true; SyncRes::s_ecsipv4limit = 24; SyncRes::s_ecsipv6limit = 56; SyncRes::s_rootNXTrust = true; SyncRes::s_minimumTTL = 0; SyncRes::s_serverID = "PowerDNS Unit Tests Server ID"; SyncRes::<API key>(); SyncRes::addEDNSLocalSubnet("0.0.0.0/0"); SyncRes::addEDNSLocalSubnet("::/0"); SyncRes::<API key>(); SyncRes::clearEDNSDomains(); SyncRes::clearDelegationOnly(); SyncRes::clearDontQuery(); SyncRes::<API key>(Netmask("127.0.0.1/32")); SyncRes::clearNSSpeeds(); BOOST_CHECK_EQUAL(SyncRes::getNSSpeedsSize(), 0); SyncRes::clearEDNSStatuses(); BOOST_CHECK_EQUAL(SyncRes::getEDNSStatusesSize(), 0); SyncRes::clearThrottle(); BOOST_CHECK_EQUAL(SyncRes::<API key>(), 0); SyncRes::clearFailedServers(); BOOST_CHECK_EQUAL(SyncRes::<API key>(), 0); auto luaconfsCopy = g_luaconfs.getCopy(); luaconfsCopy.dfe.clear(); luaconfsCopy.dsAnchors.clear(); for (const auto &dsRecord : rootDSs) { auto ds=unique_ptr<DSRecordContent>(dynamic_cast<DSRecordContent*>(DSRecordContent::make(dsRecord))); luaconfsCopy.dsAnchors[g_rootdnsname].insert(*ds); } luaconfsCopy.negAnchors.clear(); g_luaconfs.setState(luaconfsCopy); g_dnssecmode = DNSSECMode::Off; g_dnssecLOG = debug; <API key> = 2500; ::arg().set("version-string", "string reported on version.pdns or version.bind")="PowerDNS Unit Tests"; } static void initSR(std::unique_ptr<SyncRes>& sr, bool dnssec=false, bool debug=false, time_t fakeNow=0) { struct timeval now; if (fakeNow > 0) { now.tv_sec = fakeNow; now.tv_usec = 0; } else { Utility::gettimeofday(&now, 0); } init(debug); sr = std::unique_ptr<SyncRes>(new SyncRes(now)); sr->setDoEDNS0(true); if (dnssec) { sr->setDoDNSSEC(dnssec); } sr->setLogMode(debug == false ? SyncRes::LogNone : SyncRes::Log); SyncRes::setDomainMap(std::make_shared<SyncRes::domainmap_t>()); SyncRes::clearNegCache(); } static void setDNSSECValidation(std::unique_ptr<SyncRes>& sr, const DNSSECMode& mode) { sr-><API key>(true); g_dnssecmode = mode; } static void setLWResult(LWResult* res, int rcode, bool aa=false, bool tc=false, bool edns=false) { res->d_rcode = rcode; res->d_aabit = aa; res->d_tcbit = tc; res->d_haveEDNS = edns; } static void addRecordToLW(LWResult* res, const DNSName& name, uint16_t type, const std::string& content, DNSResourceRecord::Place place=DNSResourceRecord::ANSWER, uint32_t ttl=60) { addRecordToList(res->d_records, name, type, content, place, ttl); } static void addRecordToLW(LWResult* res, const std::string& name, uint16_t type, const std::string& content, DNSResourceRecord::Place place=DNSResourceRecord::ANSWER, uint32_t ttl=60) { addRecordToLW(res, DNSName(name), type, content, place, ttl); } static bool isRootServer(const ComboAddress& ip) { if (ip.isIPv4()) { for (size_t idx = 0; idx < rootIps4Count; idx++) { if (ip.toString() == rootIps4[idx]) { return true; } } } else { for (size_t idx = 0; idx < rootIps6Count; idx++) { if (ip.toString() == rootIps6[idx]) { return true; } } } return false; } static void computeRRSIG(const DNSSECPrivateKey& dpk, const DNSName& signer, const DNSName& signQName, uint16_t signQType, uint32_t signTTL, uint32_t sigValidity, RRSIGRecordContent& rrc, vector<shared_ptr<DNSRecordContent> >& toSign, boost::optional<uint8_t> algo=boost::none, boost::optional<uint32_t> inception=boost::none) { time_t now = time(nullptr); DNSKEYRecordContent drc = dpk.getDNSKEY(); const std::shared_ptr<DNSCryptoKeyEngine> rc = dpk.getKey(); rrc.d_type = signQType; rrc.d_labels = signQName.countLabels() - signQName.isWildcard(); rrc.d_originalttl = signTTL; rrc.d_siginception = inception ? *inception : (now - 10); rrc.d_sigexpire = now + sigValidity; rrc.d_signer = signer; rrc.d_tag = 0; rrc.d_tag = drc.getTag(); rrc.d_algorithm = algo ? *algo : drc.d_algorithm; std::string msg = getMessageForRRSET(signQName, rrc, toSign); rrc.d_signature = rc->sign(msg); } typedef std::unordered_map<DNSName, std::pair<DNSSECPrivateKey, DSRecordContent> > testkeysset_t; static bool addRRSIG(const testkeysset_t& keys, std::vector<DNSRecord>& records, const DNSName& signer, uint32_t sigValidity, bool broken=false, boost::optional<uint8_t> algo=boost::none, boost::optional<DNSName> wildcard=boost::none) { if (records.empty()) { return false; } const auto it = keys.find(signer); if (it == keys.cend()) { throw std::runtime_error("No DNSKEY found for " + signer.toLogString() + ", unable to compute the requested RRSIG"); } size_t recordsCount = records.size(); const DNSName& name = records[recordsCount-1].d_name; const uint16_t type = records[recordsCount-1].d_type; std::vector<std::shared_ptr<DNSRecordContent> > recordcontents; for (const auto record : records) { if (record.d_name == name && record.d_type == type) { recordcontents.push_back(record.d_content); } } RRSIGRecordContent rrc; computeRRSIG(it->second.first, signer, wildcard ? *wildcard : records[recordsCount-1].d_name, records[recordsCount-1].d_type, records[recordsCount-1].d_ttl, sigValidity, rrc, recordcontents, algo); if (broken) { rrc.d_signature[0] ^= 42; } DNSRecord rec; rec.d_type = QType::RRSIG; rec.d_place = records[recordsCount-1].d_place; rec.d_name = records[recordsCount-1].d_name; rec.d_ttl = records[recordsCount-1].d_ttl; rec.d_content = std::make_shared<RRSIGRecordContent>(rrc); records.push_back(rec); return true; } static void addDNSKEY(const testkeysset_t& keys, const DNSName& signer, uint32_t ttl, std::vector<DNSRecord>& records) { const auto it = keys.find(signer); if (it == keys.cend()) { throw std::runtime_error("No DNSKEY found for " + signer.toLogString()); } DNSRecord rec; rec.d_place = DNSResourceRecord::ANSWER; rec.d_name = signer; rec.d_type = QType::DNSKEY; rec.d_ttl = ttl; rec.d_content = std::make_shared<DNSKEYRecordContent>(it->second.first.getDNSKEY()); records.push_back(rec); } static bool addDS(const DNSName& domain, uint32_t ttl, std::vector<DNSRecord>& records, const testkeysset_t& keys, DNSResourceRecord::Place place=DNSResourceRecord::AUTHORITY) { const auto it = keys.find(domain); if (it == keys.cend()) { return false; } DNSRecord rec; rec.d_name = domain; rec.d_type = QType::DS; rec.d_place = place; rec.d_ttl = ttl; rec.d_content = std::make_shared<DSRecordContent>(it->second.second); records.push_back(rec); return true; } static void addNSECRecordToLW(const DNSName& domain, const DNSName& next, const std::set<uint16_t>& types, uint32_t ttl, std::vector<DNSRecord>& records) { NSECRecordContent nrc; nrc.d_next = next; nrc.d_set = types; DNSRecord rec; rec.d_name = domain; rec.d_ttl = ttl; rec.d_type = QType::NSEC; rec.d_content = std::make_shared<NSECRecordContent>(nrc); rec.d_place = DNSResourceRecord::AUTHORITY; records.push_back(rec); } static void addNSEC3RecordToLW(const DNSName& hashedName, const std::string& hashedNext, const std::string& salt, unsigned int iterations, const std::set<uint16_t>& types, uint32_t ttl, std::vector<DNSRecord>& records) { NSEC3RecordContent nrc; nrc.d_algorithm = 1; nrc.d_flags = 0; nrc.d_iterations = iterations; nrc.d_salt = salt; nrc.d_nexthash = hashedNext; nrc.d_set = types; DNSRecord rec; rec.d_name = hashedName; rec.d_ttl = ttl; rec.d_type = QType::NSEC3; rec.d_content = std::make_shared<NSEC3RecordContent>(nrc); rec.d_place = DNSResourceRecord::AUTHORITY; records.push_back(rec); } static void <API key>(const DNSName& domain, const DNSName& zone, const std::string& next, const std::set<uint16_t>& types, uint32_t ttl, std::vector<DNSRecord>& records, unsigned int iterations=10) { static const std::string salt = "deadbeef"; std::string hashed = hashQNameWithSalt(salt, iterations, domain); addNSEC3RecordToLW(DNSName(toBase32Hex(hashed)) + zone, next, salt, iterations, types, ttl, records); } static void <API key>(const DNSName& domain, const DNSName& zone, const std::set<uint16_t>& types, uint32_t ttl, std::vector<DNSRecord>& records, unsigned int iterations=10) { static const std::string salt = "deadbeef"; std::string hashed = hashQNameWithSalt(salt, iterations, domain); std::string hashedNext(hashed); incrementHash(hashedNext); decrementHash(hashed); addNSEC3RecordToLW(DNSName(toBase32Hex(hashed)) + zone, hashedNext, salt, iterations, types, ttl, records); } static void generateKeyMaterial(const DNSName& name, unsigned int algo, uint8_t digest, testkeysset_t& keys) { auto dcke = std::shared_ptr<DNSCryptoKeyEngine>(DNSCryptoKeyEngine::make(algo)); dcke->create((algo <= 10) ? 2048 : dcke->getBits()); DNSSECPrivateKey dpk; dpk.d_flags = 256; dpk.setKey(dcke); DSRecordContent ds = makeDSFromDNSKey(name, dpk.getDNSKEY(), digest); keys[name] = std::pair<DNSSECPrivateKey,DSRecordContent>(dpk,ds); } static void generateKeyMaterial(const DNSName& name, unsigned int algo, uint8_t digest, testkeysset_t& keys, map<DNSName,dsmap_t>& dsAnchors) { generateKeyMaterial(name, algo, digest, keys); dsAnchors[name].insert(keys[name].second); } static int <API key>(LWResult* res, const DNSName& domain, DNSName auth, int type, const testkeysset_t& keys, bool proveCut=true) { if (type == QType::DS) { auth.chopOff(); setLWResult(res, 0, true, false, true); if (addDS(domain, 300, res->d_records, keys, DNSResourceRecord::ANSWER)) { addRRSIG(keys, res->d_records, auth, 300); } else { addRecordToLW(res, auth, QType::SOA, "foo. bar. 2017032800 1800 900 604800 86400", DNSResourceRecord::AUTHORITY, 86400); /* if the auth zone is signed, we need to provide a secure denial */ const auto it = keys.find(auth); if (it != keys.cend()) { /* sign the SOA */ addRRSIG(keys, res->d_records, auth, 300); /* add a NSEC denying the DS */ std::set<uint16_t> types = { QType::NSEC }; if (proveCut) { types.insert(QType::NS); } addNSECRecordToLW(domain, DNSName("z") + domain, types, 600, res->d_records); addRRSIG(keys, res->d_records, auth, 300); } } return 1; } if (type == QType::DNSKEY) { setLWResult(res, 0, true, false, true); addDNSKEY(keys, domain, 300, res->d_records); addRRSIG(keys, res->d_records, domain, 300); return 1; } return 0; } /* Real tests */ <API key>(syncres_cc) <API key>(test_root_primed) { std::unique_ptr<SyncRes> sr; initSR(sr); primeHints(); const DNSName target("a.root-servers.net."); /* we are primed, we should be able to resolve A a.root-servers.net. without any query */ vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_REQUIRE_EQUAL(ret.size(), 1); BOOST_CHECK(ret[0].d_type == QType::A); BOOST_CHECK_EQUAL(ret[0].d_name, target); ret.clear(); res = sr->beginResolve(target, QType(QType::AAAA), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Indeterminate); BOOST_REQUIRE_EQUAL(ret.size(), 1); BOOST_CHECK(ret[0].d_type == QType::AAAA); BOOST_CHECK_EQUAL(ret[0].d_name, target); } <API key>(test_root_primed_ns) { std::unique_ptr<SyncRes> sr; initSR(sr); primeHints(); const DNSName target("."); /* we are primed, but we should not be able to NS . without any query because the . NS entry is not stored as authoritative */ size_t queriesCount = 0; sr->setAsyncCallback([target,&queriesCount](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { queriesCount++; if (domain == target && type == QType::NS) { setLWResult(res, 0, true, false, true); char addr[] = "a.root-servers.net."; for (char idx = 'a'; idx <= 'm'; idx++) { addr[0] = idx; addRecordToLW(res, g_rootdnsname, QType::NS, std::string(addr), DNSResourceRecord::ANSWER, 3600); } addRecordToLW(res, "a.root-servers.net.", QType::A, "198.41.0.4", DNSResourceRecord::ADDITIONAL, 3600); addRecordToLW(res, "a.root-servers.net.", QType::AAAA, "2001:503:ba3e::2:30", DNSResourceRecord::ADDITIONAL, 3600); return 1; } return 0; }); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::NS), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_REQUIRE_EQUAL(ret.size(), 13); BOOST_CHECK_EQUAL(queriesCount, 1); } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr); size_t queriesCount = 0; sr->setAsyncCallback([&queriesCount](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { queriesCount++; if (domain == g_rootdnsname && type == QType::NS) { setLWResult(res, 0, true, false, true); addRecordToLW(res, g_rootdnsname, QType::NS, "a.root-servers.net.", DNSResourceRecord::ANSWER, 3600); addRecordToLW(res, "a.root-servers.net.", QType::A, "198.41.0.4", DNSResourceRecord::ADDITIONAL, 3600); addRecordToLW(res, "a.root-servers.net.", QType::AAAA, "2001:503:ba3e::2:30", DNSResourceRecord::ADDITIONAL, 3600); return 1; } return 0; }); /* we are not primed yet, so SyncRes will have to call primeHints() then call getRootNS(), for which at least one of the root servers needs to answer */ vector<DNSRecord> ret; int res = sr->beginResolve(DNSName("."), QType(QType::NS), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(ret.size(), 1); BOOST_CHECK_EQUAL(queriesCount, 2); } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr); std::set<ComboAddress> downServers; /* we are not primed yet, so SyncRes will have to call primeHints() then call getRootNS(), for which at least one of the root servers needs to answer. None will, so it should ServFail. */ sr->setAsyncCallback([&downServers](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { downServers.insert(ip); return 0; }); vector<DNSRecord> ret; int res = sr->beginResolve(DNSName("."), QType(QType::NS), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::ServFail); BOOST_CHECK_EQUAL(ret.size(), 0); BOOST_CHECK(downServers.size() > 0); /* we explicitly refuse to mark the root servers down */ for (const auto& server : downServers) { BOOST_CHECK_EQUAL(SyncRes::getServerFailsCount(server), 0); } } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr); ComboAddress noEDNSServer; size_t queriesWithEDNS = 0; size_t queriesWithoutEDNS = 0; sr->setAsyncCallback([&queriesWithEDNS, &queriesWithoutEDNS, &noEDNSServer](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { if (EDNS0Level != 0) { queriesWithEDNS++; noEDNSServer = ip; setLWResult(res, RCode::FormErr); return 1; } queriesWithoutEDNS++; if (domain == DNSName("powerdns.com") && type == QType::A && !doTCP) { setLWResult(res, 0, true, false, false); addRecordToLW(res, domain, QType::A, "192.0.2.1"); return 1; } return 0; }); primeHints(); /* fake that the root NS doesn't handle EDNS, check that we fallback */ vector<DNSRecord> ret; int res = sr->beginResolve(DNSName("powerdns.com."), QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(ret.size(), 1); BOOST_CHECK_EQUAL(queriesWithEDNS, 1); BOOST_CHECK_EQUAL(queriesWithoutEDNS, 1); BOOST_CHECK_EQUAL(SyncRes::getEDNSStatusesSize(), 1); BOOST_CHECK_EQUAL(SyncRes::getEDNSStatus(noEDNSServer), SyncRes::EDNSStatus::NOEDNS); } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr); size_t queriesWithEDNS = 0; size_t queriesWithoutEDNS = 0; sr->setAsyncCallback([&queriesWithEDNS, &queriesWithoutEDNS](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { if (EDNS0Level != 0) { queriesWithEDNS++; setLWResult(res, RCode::NotImp); return 1; } queriesWithoutEDNS++; if (domain == DNSName("powerdns.com") && type == QType::A && !doTCP) { setLWResult(res, 0, true, false, false); addRecordToLW(res, domain, QType::A, "192.0.2.1"); return 1; } return 0; }); primeHints(); /* fake that the NS doesn't handle EDNS, check that we fallback */ vector<DNSRecord> ret; int res = sr->beginResolve(DNSName("powerdns.com."), QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(ret.size(), 1); BOOST_CHECK_EQUAL(queriesWithEDNS, 1); BOOST_CHECK_EQUAL(queriesWithoutEDNS, 1); } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr); sr->setAsyncCallback([](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { if (!doTCP) { setLWResult(res, 0, false, true, false); return 1; } if (domain == DNSName("powerdns.com") && type == QType::A && doTCP) { setLWResult(res, 0, true, false, false); addRecordToLW(res, domain, QType::A, "192.0.2.1"); return 1; } return 0; }); primeHints(); /* fake that the NS truncates every request over UDP, we should fallback to TCP */ vector<DNSRecord> ret; int res = sr->beginResolve(DNSName("powerdns.com."), QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); } <API key>(test_tc_over_tcp) { std::unique_ptr<SyncRes> sr; initSR(sr); size_t tcpQueriesCount = 0; sr->setAsyncCallback([&tcpQueriesCount](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { if (!doTCP) { setLWResult(res, 0, true, true, false); return 1; } /* first TCP query is answered with a TC response */ tcpQueriesCount++; if (tcpQueriesCount == 1) { setLWResult(res, 0, true, true, false); } else { setLWResult(res, 0, true, false, false); } addRecordToLW(res, domain, QType::A, "192.0.2.1"); return 1; }); primeHints(); vector<DNSRecord> ret; int res = sr->beginResolve(DNSName("powerdns.com."), QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(tcpQueriesCount, 2); } <API key>(test_all_nss_down) { std::unique_ptr<SyncRes> sr; initSR(sr); std::set<ComboAddress> downServers; primeHints(); sr->setAsyncCallback([&downServers](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { if (isRootServer(ip)) { setLWResult(res, 0, false, false, true); addRecordToLW(res, "com.", QType::NS, "a.gtld-servers.net.", DNSResourceRecord::AUTHORITY, 172800); addRecordToLW(res, "a.gtld-servers.net.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); addRecordToLW(res, "a.gtld-servers.net.", QType::AAAA, "2001:DB8::1", DNSResourceRecord::ADDITIONAL, 3600); return 1; } else if (ip == ComboAddress("192.0.2.1:53") || ip == ComboAddress("[2001:DB8::1]:53")) { setLWResult(res, 0, false, false, true); addRecordToLW(res, "powerdns.com.", QType::NS, "pdns-public-ns1.powerdns.com.", DNSResourceRecord::AUTHORITY, 172800); addRecordToLW(res, "powerdns.com.", QType::NS, "pdns-public-ns2.powerdns.com.", DNSResourceRecord::AUTHORITY, 172800); addRecordToLW(res, "pdns-public-ns1.powerdns.com.", QType::A, "192.0.2.2", DNSResourceRecord::ADDITIONAL, 172800); addRecordToLW(res, "pdns-public-ns1.powerdns.com.", QType::AAAA, "2001:DB8::2", DNSResourceRecord::ADDITIONAL, 172800); addRecordToLW(res, "pdns-public-ns2.powerdns.com.", QType::A, "192.0.2.3", DNSResourceRecord::ADDITIONAL, 172800); addRecordToLW(res, "pdns-public-ns2.powerdns.com.", QType::AAAA, "2001:DB8::3", DNSResourceRecord::ADDITIONAL, 172800); return 1; } else { downServers.insert(ip); return 0; } }); DNSName target("powerdns.com."); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::ServFail); BOOST_CHECK_EQUAL(ret.size(), 0); BOOST_CHECK_EQUAL(downServers.size(), 4); time_t now = sr->getNow().tv_sec; for (const auto& server : downServers) { BOOST_CHECK_EQUAL(SyncRes::getServerFailsCount(server), 1); BOOST_CHECK(SyncRes::isThrottled(now, server, target, QType::A)); } } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr); std::set<ComboAddress> downServers; primeHints(); sr->setAsyncCallback([&downServers](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { if (isRootServer(ip)) { setLWResult(res, 0, false, false, true); addRecordToLW(res, "com.", QType::NS, "a.gtld-servers.net.", DNSResourceRecord::AUTHORITY, 172800); addRecordToLW(res, "a.gtld-servers.net.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); addRecordToLW(res, "a.gtld-servers.net.", QType::AAAA, "2001:DB8::1", DNSResourceRecord::ADDITIONAL, 3600); return 1; } else if (ip == ComboAddress("192.0.2.1:53") || ip == ComboAddress("[2001:DB8::1]:53")) { setLWResult(res, 0, false, false, true); addRecordToLW(res, "powerdns.com.", QType::NS, "pdns-public-ns1.powerdns.com.", DNSResourceRecord::AUTHORITY, 172800); addRecordToLW(res, "powerdns.com.", QType::NS, "pdns-public-ns2.powerdns.com.", DNSResourceRecord::AUTHORITY, 172800); addRecordToLW(res, "pdns-public-ns1.powerdns.com.", QType::A, "192.0.2.2", DNSResourceRecord::ADDITIONAL, 172800); addRecordToLW(res, "pdns-public-ns1.powerdns.com.", QType::AAAA, "2001:DB8::2", DNSResourceRecord::ADDITIONAL, 172800); addRecordToLW(res, "pdns-public-ns2.powerdns.com.", QType::A, "192.0.2.3", DNSResourceRecord::ADDITIONAL, 172800); addRecordToLW(res, "pdns-public-ns2.powerdns.com.", QType::AAAA, "2001:DB8::3", DNSResourceRecord::ADDITIONAL, 172800); return 1; } else { downServers.insert(ip); return 0; } }); /* exact same test than the previous one, except instead of a time out we fake a network error */ DNSName target("powerdns.com."); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::ServFail); BOOST_CHECK_EQUAL(ret.size(), 0); BOOST_CHECK_EQUAL(downServers.size(), 4); time_t now = sr->getNow().tv_sec; for (const auto& server : downServers) { BOOST_CHECK_EQUAL(SyncRes::getServerFailsCount(server), 1); BOOST_CHECK(SyncRes::isThrottled(now, server, target, QType::A)); } } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr); primeHints(); DNSName target("www.powerdns.com."); sr->setAsyncCallback([target](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { if (isRootServer(ip)) { setLWResult(res, 0, false, false, true); if (domain == target) { addRecordToLW(res, "powerdns.com.", QType::NS, "pdns-public-ns1.powerdns.com.", DNSResourceRecord::AUTHORITY, 172800); addRecordToLW(res, "powerdns.com.", QType::NS, "pdns-public-ns2.powerdns.net.", DNSResourceRecord::AUTHORITY, 172800); addRecordToLW(res, "pdns-public-ns1.powerdns.com.", QType::A, "192.0.2.2", DNSResourceRecord::ADDITIONAL, 172800); addRecordToLW(res, "pdns-public-ns1.powerdns.com.", QType::AAAA, "2001:DB8::2", DNSResourceRecord::ADDITIONAL, 172800); } else if (domain == DNSName("pdns-public-ns2.powerdns.net.")) { addRecordToLW(res, "powerdns.net.", QType::NS, "pdns-public-ns2.powerdns.net.", DNSResourceRecord::AUTHORITY, 172800); addRecordToLW(res, "powerdns.net.", QType::NS, "pdns-public-ns1.powerdns.com.", DNSResourceRecord::AUTHORITY, 172800); addRecordToLW(res, "pdns-public-ns2.powerdns.net.", QType::A, "192.0.2.3", DNSResourceRecord::ADDITIONAL, 172800); addRecordToLW(res, "pdns-public-ns2.powerdns.net.", QType::AAAA, "2001:DB8::3", DNSResourceRecord::ADDITIONAL, 172800); } return 1; } else if (ip == ComboAddress("192.0.2.3:53")) { setLWResult(res, 0, true, false, true); if (domain == DNSName("pdns-public-ns2.powerdns.net.")) { if (type == QType::A) { addRecordToLW(res, "pdns-public-ns2.powerdns.net.", QType::A, "192.0.2.3"); } else if (type == QType::AAAA) { addRecordToLW(res, "pdns-public-ns2.powerdns.net.", QType::AAAA, "2001:DB8::3"); } } else if (domain == target) { if (type == QType::A) { addRecordToLW(res, domain, QType::A, "192.0.2.1"); } else if (type == QType::AAAA) { addRecordToLW(res, domain, QType::AAAA, "2001:DB8::1"); } } return 1; } return 0; }); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(ret.size(), 1); } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr); std::set<ComboAddress> downServers; primeHints(); sr->setAsyncCallback([&downServers](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { if (isRootServer(ip)) { setLWResult(res, 0, false, false, true); addRecordToLW(res, "com.", QType::NS, "a.gtld-servers.net.", DNSResourceRecord::AUTHORITY, 172800); addRecordToLW(res, "a.gtld-servers.net.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); addRecordToLW(res, "a.gtld-servers.net.", QType::AAAA, "2001:DB8::1", DNSResourceRecord::ADDITIONAL, 3600); return 1; } else if (ip == ComboAddress("192.0.2.1:53") || ip == ComboAddress("[2001:DB8::1]:53")) { setLWResult(res, 0, false, false, true); addRecordToLW(res, "powerdns.com.", QType::NS, "pdns-public-ns1.powerdns.com.", DNSResourceRecord::AUTHORITY, 172800); addRecordToLW(res, "powerdns.com.", QType::NS, "pdns-public-ns2.powerdns.com.", DNSResourceRecord::AUTHORITY, 172800); addRecordToLW(res, "pdns-public-ns1.powerdns.com.", QType::A, "192.0.2.2", DNSResourceRecord::ADDITIONAL, 172800); addRecordToLW(res, "pdns-public-ns1.powerdns.com.", QType::AAAA, "2001:DB8::2", DNSResourceRecord::ADDITIONAL, 172800); addRecordToLW(res, "pdns-public-ns2.powerdns.com.", QType::A, "192.0.2.3", DNSResourceRecord::ADDITIONAL, 172800); addRecordToLW(res, "pdns-public-ns2.powerdns.com.", QType::AAAA, "2001:DB8::3", DNSResourceRecord::ADDITIONAL, 172800); return 1; } else { if (downServers.size() < 3) { /* only the last one will answer */ downServers.insert(ip); return -2; } else { setLWResult(res, 0, true, false, true); addRecordToLW(res, "powerdns.com.", QType::A, "192.0.2.42"); return 1; } } }); DNSName target("powerdns.com."); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(ret.size(), 1); BOOST_CHECK_EQUAL(downServers.size(), 3); /* Error is reported as "OS limit error" (-2) so the servers should _NOT_ be marked down */ time_t now = sr->getNow().tv_sec; for (const auto& server : downServers) { BOOST_CHECK_EQUAL(SyncRes::getServerFailsCount(server), 0); BOOST_CHECK(!SyncRes::isThrottled(now, server, target, QType::A)); } } <API key>(test_glued_referral) { std::unique_ptr<SyncRes> sr; initSR(sr); primeHints(); const DNSName target("powerdns.com."); sr->setAsyncCallback([target](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { /* this will cause issue with qname minimization if we ever implement it */ if (domain != target) { return 0; } if (isRootServer(ip)) { setLWResult(res, 0, false, false, true); addRecordToLW(res, "com.", QType::NS, "a.gtld-servers.net.", DNSResourceRecord::AUTHORITY, 172800); addRecordToLW(res, "a.gtld-servers.net.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); addRecordToLW(res, "a.gtld-servers.net.", QType::AAAA, "2001:DB8::1", DNSResourceRecord::ADDITIONAL, 3600); return 1; } else if (ip == ComboAddress("192.0.2.1:53") || ip == ComboAddress("[2001:DB8::1]:53")) { setLWResult(res, 0, false, false, true); addRecordToLW(res, "powerdns.com.", QType::NS, "pdns-public-ns1.powerdns.com.", DNSResourceRecord::AUTHORITY, 172800); addRecordToLW(res, "powerdns.com.", QType::NS, "pdns-public-ns2.powerdns.com.", DNSResourceRecord::AUTHORITY, 172800); addRecordToLW(res, "pdns-public-ns1.powerdns.com.", QType::A, "192.0.2.2", DNSResourceRecord::ADDITIONAL, 172800); addRecordToLW(res, "pdns-public-ns1.powerdns.com.", QType::AAAA, "2001:DB8::2", DNSResourceRecord::ADDITIONAL, 172800); addRecordToLW(res, "pdns-public-ns2.powerdns.com.", QType::A, "192.0.2.3", DNSResourceRecord::ADDITIONAL, 172800); addRecordToLW(res, "pdns-public-ns2.powerdns.com.", QType::AAAA, "2001:DB8::3", DNSResourceRecord::ADDITIONAL, 172800); return 1; } else if (ip == ComboAddress("192.0.2.2:53") || ip == ComboAddress("192.0.2.3:53") || ip == ComboAddress("[2001:DB8::2]:53") || ip == ComboAddress("[2001:DB8::3]:53")) { setLWResult(res, 0, true, false, true); addRecordToLW(res, target, QType::A, "192.0.2.4"); return 1; } else { return 0; } }); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_REQUIRE_EQUAL(ret.size(), 1); BOOST_CHECK(ret[0].d_type == QType::A); BOOST_CHECK_EQUAL(ret[0].d_name, target); } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr); primeHints(); const DNSName target("powerdns.com."); sr->setAsyncCallback([target](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { if (isRootServer(ip)) { setLWResult(res, 0, false, false, true); if (domain.isPartOf(DNSName("com."))) { addRecordToLW(res, "com.", QType::NS, "a.gtld-servers.net.", DNSResourceRecord::AUTHORITY, 172800); } else if (domain.isPartOf(DNSName("org."))) { addRecordToLW(res, "org.", QType::NS, "a.gtld-servers.net.", DNSResourceRecord::AUTHORITY, 172800); } else { setLWResult(res, RCode::NXDomain, false, false, true); return 1; } addRecordToLW(res, "a.gtld-servers.net.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); addRecordToLW(res, "a.gtld-servers.net.", QType::AAAA, "2001:DB8::1", DNSResourceRecord::ADDITIONAL, 3600); return 1; } else if (ip == ComboAddress("192.0.2.1:53") || ip == ComboAddress("[2001:DB8::1]:53")) { if (domain == target) { setLWResult(res, 0, false, false, true); addRecordToLW(res, "powerdns.com.", QType::NS, "pdns-public-ns1.powerdns.org.", DNSResourceRecord::AUTHORITY, 172800); addRecordToLW(res, "powerdns.com.", QType::NS, "pdns-public-ns2.powerdns.org.", DNSResourceRecord::AUTHORITY, 172800); return 1; } else if (domain == DNSName("pdns-public-ns1.powerdns.org.")) { setLWResult(res, 0, true, false, true); addRecordToLW(res, "pdns-public-ns1.powerdns.org.", QType::A, "192.0.2.2"); addRecordToLW(res, "pdns-public-ns1.powerdns.org.", QType::AAAA, "2001:DB8::2"); return 1; } else if (domain == DNSName("pdns-public-ns2.powerdns.org.")) { setLWResult(res, 0, true, false, true); addRecordToLW(res, "pdns-public-ns2.powerdns.org.", QType::A, "192.0.2.3"); addRecordToLW(res, "pdns-public-ns2.powerdns.org.", QType::AAAA, "2001:DB8::3"); return 1; } setLWResult(res, RCode::NXDomain, false, false, true); return 1; } else if (ip == ComboAddress("192.0.2.2:53") || ip == ComboAddress("192.0.2.3:53") || ip == ComboAddress("[2001:DB8::2]:53") || ip == ComboAddress("[2001:DB8::3]:53")) { setLWResult(res, 0, true, false, true); addRecordToLW(res, target, QType::A, "192.0.2.4"); return 1; } else { return 0; } }); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_REQUIRE_EQUAL(ret.size(), 1); BOOST_CHECK(ret[0].d_type == QType::A); BOOST_CHECK_EQUAL(ret[0].d_name, target); } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr); primeHints(); const DNSName target("powerdns.com."); SyncRes::addEDNSDomain(target); EDNSSubnetOpts incomingECS; incomingECS.source = Netmask("192.0.2.128/32"); sr->setQuerySource(ComboAddress(), boost::optional<const EDNSSubnetOpts&>(incomingECS)); sr->setAsyncCallback([target](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { BOOST_REQUIRE(srcmask); BOOST_CHECK_EQUAL(srcmask->toString(), "192.0.2.0/24"); return 0; }); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::ServFail); } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr); primeHints(); const DNSName target("powerdns.com."); SyncRes::addEDNSRemoteSubnet("192.0.2.1/32"); EDNSSubnetOpts incomingECS; incomingECS.source = Netmask("2001:DB8::FF/128"); sr->setQuerySource(ComboAddress(), boost::optional<const EDNSSubnetOpts&>(incomingECS)); sr->setAsyncCallback([target](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { if (isRootServer(ip)) { BOOST_REQUIRE(!srcmask); setLWResult(res, 0, false, false, true); addRecordToLW(res, domain, QType::NS, "a.gtld-servers.net.", DNSResourceRecord::AUTHORITY, 172800); addRecordToLW(res, "a.gtld-servers.net.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); return 1; } else if (ip == ComboAddress("192.0.2.1:53")) { BOOST_REQUIRE(srcmask); BOOST_CHECK_EQUAL(srcmask->toString(), "2001:db8::/56"); setLWResult(res, 0, true, false, false); addRecordToLW(res, domain, QType::A, "192.0.2.2"); return 1; } return 0; }); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_REQUIRE_EQUAL(ret.size(), 1); BOOST_CHECK(ret[0].d_type == QType::A); BOOST_CHECK_EQUAL(ret[0].d_name, target); } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr); primeHints(); const DNSName target("powerdns.com."); SyncRes::addEDNSRemoteSubnet("192.0.2.1/32"); // No incoming ECS data sr->setQuerySource(ComboAddress("192.0.2.127"), boost::none); sr->setAsyncCallback([target](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { if (isRootServer(ip)) { BOOST_REQUIRE(!srcmask); setLWResult(res, 0, false, false, true); addRecordToLW(res, domain, QType::NS, "a.gtld-servers.net.", DNSResourceRecord::AUTHORITY, 172800); addRecordToLW(res, "a.gtld-servers.net.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); return 1; } else if (ip == ComboAddress("192.0.2.1:53")) { BOOST_REQUIRE(srcmask); BOOST_CHECK_EQUAL(srcmask->toString(), "192.0.2.0/24"); setLWResult(res, 0, true, false, false); addRecordToLW(res, domain, QType::A, "192.0.2.2"); return 1; } return 0; }); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_REQUIRE_EQUAL(ret.size(), 1); BOOST_CHECK(ret[0].d_type == QType::A); BOOST_CHECK_EQUAL(ret[0].d_name, target); } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr); primeHints(); const DNSName target("powerdns.com."); SyncRes::addEDNSRemoteSubnet("192.0.2.1/32"); SyncRes::<API key>(); SyncRes::addEDNSLocalSubnet("192.0.2.254/32"); // No incoming ECS data, Requestor IP not in ecs-add-for sr->setQuerySource(ComboAddress("192.0.2.127"), boost::none); sr->setAsyncCallback([target](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { if (isRootServer(ip)) { BOOST_REQUIRE(!srcmask); setLWResult(res, 0, false, false, true); addRecordToLW(res, domain, QType::NS, "a.gtld-servers.net.", DNSResourceRecord::AUTHORITY, 172800); addRecordToLW(res, "a.gtld-servers.net.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); return 1; } else if (ip == ComboAddress("192.0.2.1:53")) { BOOST_REQUIRE(srcmask); BOOST_CHECK_EQUAL(srcmask->toString(), "127.0.0.1/32"); setLWResult(res, 0, true, false, false); addRecordToLW(res, domain, QType::A, "192.0.2.2"); return 1; } return 0; }); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_REQUIRE_EQUAL(ret.size(), 1); BOOST_CHECK(ret[0].d_type == QType::A); BOOST_CHECK_EQUAL(ret[0].d_name, target); } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr); primeHints(); const DNSName target("powerdns.com."); SyncRes::addEDNSRemoteSubnet("192.0.2.1/32"); SyncRes::<API key>(); SyncRes::addEDNSLocalSubnet("192.0.2.254/32"); EDNSSubnetOpts incomingECS; incomingECS.source = Netmask("192.0.0.0/16"); sr->setQuerySource(ComboAddress("192.0.2.127"), boost::optional<const EDNSSubnetOpts&>(incomingECS)); sr->setAsyncCallback([target](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { if (isRootServer(ip)) { BOOST_REQUIRE(!srcmask); setLWResult(res, 0, false, false, true); addRecordToLW(res, domain, QType::NS, "a.gtld-servers.net.", DNSResourceRecord::AUTHORITY, 172800); addRecordToLW(res, "a.gtld-servers.net.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); return 1; } else if (ip == ComboAddress("192.0.2.1:53")) { BOOST_REQUIRE(srcmask); BOOST_CHECK_EQUAL(srcmask->toString(), "192.0.0.0/16"); setLWResult(res, 0, true, false, false); addRecordToLW(res, domain, QType::A, "192.0.2.2"); return 1; } return 0; }); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_REQUIRE_EQUAL(ret.size(), 1); BOOST_CHECK(ret[0].d_type == QType::A); BOOST_CHECK_EQUAL(ret[0].d_name, target); } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr); primeHints(); const DNSName target("powerdns.com."); SyncRes::addEDNSRemoteSubnet("192.0.2.1/32"); SyncRes::<API key>(); SyncRes::addEDNSLocalSubnet("192.0.2.254/32"); EDNSSubnetOpts incomingECS; incomingECS.source = Netmask("0.0.0.0/0"); sr->setQuerySource(ComboAddress("192.0.2.127"), boost::optional<const EDNSSubnetOpts&>(incomingECS)); sr->setAsyncCallback([target](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { if (isRootServer(ip)) { BOOST_REQUIRE(!srcmask); setLWResult(res, 0, false, false, true); addRecordToLW(res, domain, QType::NS, "a.gtld-servers.net.", DNSResourceRecord::AUTHORITY, 172800); addRecordToLW(res, "a.gtld-servers.net.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); return 1; } else if (ip == ComboAddress("192.0.2.1:53")) { BOOST_REQUIRE(srcmask); BOOST_CHECK_EQUAL(srcmask->toString(), "127.0.0.1/32"); setLWResult(res, 0, true, false, false); addRecordToLW(res, domain, QType::A, "192.0.2.2"); return 1; } return 0; }); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_REQUIRE_EQUAL(ret.size(), 1); BOOST_CHECK(ret[0].d_type == QType::A); BOOST_CHECK_EQUAL(ret[0].d_name, target); } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr); primeHints(); const DNSName target("cname.powerdns.com."); const DNSName cnameTarget("cname-target.powerdns.com"); sr->setAsyncCallback([target, cnameTarget](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { if (isRootServer(ip)) { setLWResult(res, 0, false, false, true); addRecordToLW(res, domain, QType::NS, "a.gtld-servers.net.", DNSResourceRecord::AUTHORITY, 172800); addRecordToLW(res, "a.gtld-servers.net.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); return 1; } else if (ip == ComboAddress("192.0.2.1:53")) { if (domain == target) { setLWResult(res, 0, true, false, false); addRecordToLW(res, domain, QType::CNAME, cnameTarget.toString()); return 1; } else if (domain == cnameTarget) { setLWResult(res, 0, true, false, false); addRecordToLW(res, domain, QType::A, "192.0.2.2"); } return 1; } return 0; }); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_REQUIRE_EQUAL(ret.size(), 2); BOOST_CHECK(ret[0].d_type == QType::CNAME); BOOST_CHECK_EQUAL(ret[0].d_name, target); BOOST_CHECK(ret[1].d_type == QType::A); BOOST_CHECK_EQUAL(ret[1].d_name, cnameTarget); } <API key>(test_cname_nxdomain) { std::unique_ptr<SyncRes> sr; initSR(sr); primeHints(); const DNSName target("cname.powerdns.com."); const DNSName cnameTarget("cname-target.powerdns.com"); sr->setAsyncCallback([target, cnameTarget](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { if (isRootServer(ip)) { setLWResult(res, 0, false, false, true); addRecordToLW(res, "powerdns.com.", QType::NS, "a.gtld-servers.net.", DNSResourceRecord::AUTHORITY, 172800); addRecordToLW(res, "a.gtld-servers.net.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); return 1; } else if (ip == ComboAddress("192.0.2.1:53")) { if (domain == target) { setLWResult(res, RCode::NXDomain, true, false, false); addRecordToLW(res, domain, QType::CNAME, cnameTarget.toString()); addRecordToLW(res, "powerdns.com.", QType::SOA, "a.powerdns.com. nstld.verisign-grs.com. 2017032800 1800 900 604800 86400", DNSResourceRecord::AUTHORITY, 86400); } else if (domain == cnameTarget) { setLWResult(res, RCode::NXDomain, true, false, false); addRecordToLW(res, "powerdns.com.", QType::SOA, "a.powerdns.com. nstld.verisign-grs.com. 2017032800 1800 900 604800 86400", DNSResourceRecord::AUTHORITY, 86400); return 1; } return 1; } return 0; }); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NXDomain); BOOST_REQUIRE_EQUAL(ret.size(), 2); BOOST_CHECK(ret[0].d_type == QType::CNAME); BOOST_CHECK_EQUAL(ret[0].d_name, target); BOOST_CHECK(ret[1].d_type == QType::SOA); /* a second time, to check the cache */ ret.clear(); res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NXDomain); BOOST_REQUIRE_EQUAL(ret.size(), 2); BOOST_CHECK(ret[0].d_type == QType::CNAME); BOOST_CHECK_EQUAL(ret[0].d_name, target); BOOST_CHECK(ret[1].d_type == QType::SOA); } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr); primeHints(); /* In this test we directly get the NS server for cname.powerdns.com., and we don't know whether it's also authoritative for cname-target.powerdns.com or powerdns.com, so we shouldn't accept the additional A record for cname-target.powerdns.com. */ const DNSName target("cname.powerdns.com."); const DNSName cnameTarget("cname-target.powerdns.com"); sr->setAsyncCallback([target, cnameTarget](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { if (isRootServer(ip)) { setLWResult(res, 0, false, false, true); addRecordToLW(res, domain, QType::NS, "a.gtld-servers.net.", DNSResourceRecord::AUTHORITY, 172800); addRecordToLW(res, "a.gtld-servers.net.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); return 1; } else if (ip == ComboAddress("192.0.2.1:53")) { if (domain == target) { setLWResult(res, 0, true, false, false); addRecordToLW(res, domain, QType::CNAME, cnameTarget.toString()); addRecordToLW(res, cnameTarget, QType::A, "192.0.2.2", DNSResourceRecord::ADDITIONAL); return 1; } else if (domain == cnameTarget) { setLWResult(res, 0, true, false, false); addRecordToLW(res, cnameTarget, QType::A, "192.0.2.3"); return 1; } return 1; } return 0; }); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_REQUIRE_EQUAL(ret.size(), 2); BOOST_REQUIRE(ret[0].d_type == QType::CNAME); BOOST_CHECK_EQUAL(ret[0].d_name, target); BOOST_CHECK_EQUAL(getRR<CNAMERecordContent>(ret[0])->getTarget(), cnameTarget); BOOST_REQUIRE(ret[1].d_type == QType::A); BOOST_CHECK_EQUAL(ret[1].d_name, cnameTarget); BOOST_CHECK(getRR<ARecordContent>(ret[1])->getCA() == ComboAddress("192.0.2.3")); } <API key>(test_cname_loop) { std::unique_ptr<SyncRes> sr; initSR(sr); primeHints(); size_t count = 0; const DNSName target("cname.powerdns.com."); sr->setAsyncCallback([target,&count](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { count++; if (isRootServer(ip)) { setLWResult(res, 0, false, false, true); addRecordToLW(res, domain, QType::NS, "a.gtld-servers.net.", DNSResourceRecord::AUTHORITY, 172800); addRecordToLW(res, "a.gtld-servers.net.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); return 1; } else if (ip == ComboAddress("192.0.2.1:53")) { if (domain == target) { setLWResult(res, 0, true, false, false); addRecordToLW(res, domain, QType::CNAME, domain.toString()); return 1; } return 1; } return 0; }); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::ServFail); BOOST_CHECK_GT(ret.size(), 0); BOOST_CHECK_EQUAL(count, 2); } <API key>(test_cname_depth) { std::unique_ptr<SyncRes> sr; initSR(sr); primeHints(); size_t depth = 0; const DNSName target("cname.powerdns.com."); sr->setAsyncCallback([target,&depth](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { if (isRootServer(ip)) { setLWResult(res, 0, false, false, true); addRecordToLW(res, domain, QType::NS, "a.gtld-servers.net.", DNSResourceRecord::AUTHORITY, 172800); addRecordToLW(res, "a.gtld-servers.net.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); return 1; } else if (ip == ComboAddress("192.0.2.1:53")) { setLWResult(res, 0, true, false, false); addRecordToLW(res, domain, QType::CNAME, std::to_string(depth) + "-cname.powerdns.com"); depth++; return 1; } return 0; }); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::ServFail); BOOST_CHECK_EQUAL(ret.size(), depth); /* we have an arbitrary limit at 10 when following a CNAME chain */ BOOST_CHECK_EQUAL(depth, 10 + 2); } <API key>(test_time_limit) { std::unique_ptr<SyncRes> sr; initSR(sr); primeHints(); size_t queries = 0; const DNSName target("cname.powerdns.com."); sr->setAsyncCallback([target,&queries](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { queries++; if (isRootServer(ip)) { setLWResult(res, 0, false, false, true); /* Pretend that this query took 2000 ms */ res->d_usec = 2000; addRecordToLW(res, domain, QType::NS, "a.gtld-servers.net.", DNSResourceRecord::AUTHORITY, 172800); addRecordToLW(res, "a.gtld-servers.net.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); return 1; } else if (ip == ComboAddress("192.0.2.1:53")) { setLWResult(res, 0, true, false, false); addRecordToLW(res, domain, QType::A, "192.0.2.2"); return 1; } return 0; }); /* Set the maximum time to 1 ms */ SyncRes::s_maxtotusec = 1000; try { vector<DNSRecord> ret; sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK(false); } catch(const <API key>& e) { } BOOST_CHECK_EQUAL(queries, 1); } <API key>(test_referral_depth) { std::unique_ptr<SyncRes> sr; initSR(sr); primeHints(); size_t queries = 0; const DNSName target("www.powerdns.com."); sr->setAsyncCallback([target,&queries](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { queries++; if (isRootServer(ip)) { setLWResult(res, 0, false, false, true); if (domain == DNSName("www.powerdns.com.")) { addRecordToLW(res, domain, QType::NS, "ns.powerdns.com.", DNSResourceRecord::AUTHORITY, 172800); } else if (domain == DNSName("ns.powerdns.com.")) { addRecordToLW(res, domain, QType::NS, "ns1.powerdns.org.", DNSResourceRecord::AUTHORITY, 172800); } else if (domain == DNSName("ns1.powerdns.org.")) { addRecordToLW(res, domain, QType::NS, "ns2.powerdns.org.", DNSResourceRecord::AUTHORITY, 172800); } else if (domain == DNSName("ns2.powerdns.org.")) { addRecordToLW(res, domain, QType::NS, "ns3.powerdns.org.", DNSResourceRecord::AUTHORITY, 172800); } else if (domain == DNSName("ns3.powerdns.org.")) { addRecordToLW(res, domain, QType::NS, "ns4.powerdns.org.", DNSResourceRecord::AUTHORITY, 172800); } else if (domain == DNSName("ns4.powerdns.org.")) { addRecordToLW(res, domain, QType::NS, "ns5.powerdns.org.", DNSResourceRecord::AUTHORITY, 172800); addRecordToLW(res, domain, QType::A, "192.0.2.1", DNSResourceRecord::AUTHORITY, 172800); } return 1; } else if (ip == ComboAddress("192.0.2.1:53")) { setLWResult(res, 0, true, false, false); addRecordToLW(res, domain, QType::A, "192.0.2.2"); return 1; } return 0; }); /* Set the maximum depth low */ SyncRes::s_maxdepth = 10; try { vector<DNSRecord> ret; sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK(false); } catch(const <API key>& e) { } } <API key>(test_cname_qperq) { std::unique_ptr<SyncRes> sr; initSR(sr); primeHints(); size_t queries = 0; const DNSName target("cname.powerdns.com."); sr->setAsyncCallback([target,&queries](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { queries++; if (isRootServer(ip)) { setLWResult(res, 0, false, false, true); addRecordToLW(res, domain, QType::NS, "a.gtld-servers.net.", DNSResourceRecord::AUTHORITY, 172800); addRecordToLW(res, "a.gtld-servers.net.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); return 1; } else if (ip == ComboAddress("192.0.2.1:53")) { setLWResult(res, 0, true, false, false); addRecordToLW(res, domain, QType::CNAME, std::to_string(queries) + "-cname.powerdns.com"); return 1; } return 0; }); /* Set the maximum number of questions very low */ SyncRes::s_maxqperq = 5; try { vector<DNSRecord> ret; sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK(false); } catch(const <API key>& e) { BOOST_CHECK_EQUAL(queries, SyncRes::s_maxqperq); } } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr); primeHints(); const DNSName target("throttled.powerdns.com."); const ComboAddress ns("192.0.2.1:53"); size_t queriesToNS = 0; sr->setAsyncCallback([target,ns,&queriesToNS](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { if (isRootServer(ip)) { setLWResult(res, 0, false, false, true); addRecordToLW(res, domain, QType::NS, "a.gtld-servers.net.", DNSResourceRecord::AUTHORITY, 172800); addRecordToLW(res, "a.gtld-servers.net.", QType::A, ns.toString(), DNSResourceRecord::ADDITIONAL, 3600); return 1; } else if (ip == ns) { queriesToNS++; setLWResult(res, 0, true, false, false); addRecordToLW(res, domain, QType::A, "192.0.2.2"); return 1; } return 0; }); /* mark ns as down */ time_t now = sr->getNow().tv_sec; SyncRes::doThrottle(now, ns, SyncRes::<API key>, 10000); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::ServFail); BOOST_CHECK_EQUAL(ret.size(), 0); /* we should not have sent any queries to ns */ BOOST_CHECK_EQUAL(queriesToNS, 0); } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr); primeHints(); const ComboAddress ns("192.0.2.1:53"); const size_t blocks = 10; /* mark ns as down for 'blocks' queries */ time_t now = sr->getNow().tv_sec; SyncRes::doThrottle(now, ns, SyncRes::<API key>, blocks); for (size_t idx = 0; idx < blocks; idx++) { BOOST_CHECK(SyncRes::isThrottled(now, ns)); } /* we have been throttled 'blocks' times, we should not be throttled anymore */ BOOST_CHECK(!SyncRes::isThrottled(now, ns)); } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr); primeHints(); const ComboAddress ns("192.0.2.1:53"); const size_t seconds = 1; /* mark ns as down for 'seconds' seconds */ time_t now = sr->getNow().tv_sec; SyncRes::doThrottle(now, ns, seconds, 10000); BOOST_CHECK(SyncRes::isThrottled(now, ns)); /* we should not be throttled anymore */ BOOST_CHECK(!SyncRes::isThrottled(now + 2, ns)); } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr); primeHints(); const DNSName target("throttled.powerdns.com."); const ComboAddress ns("192.0.2.1:53"); size_t queriesToNS = 0; sr->setAsyncCallback([target,ns,&queriesToNS](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { if (isRootServer(ip)) { setLWResult(res, 0, false, false, true); addRecordToLW(res, domain, QType::NS, "a.gtld-servers.net.", DNSResourceRecord::AUTHORITY, 172800); addRecordToLW(res, "a.gtld-servers.net.", QType::A, ns.toString(), DNSResourceRecord::ADDITIONAL, 3600); return 1; } else if (ip == ns) { queriesToNS++; setLWResult(res, 0, true, false, false); addRecordToLW(res, domain, QType::A, "192.0.2.2"); return 1; } return 0; }); /* prevent querying this NS */ SyncRes::addDontQuery(Netmask(ns)); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::ServFail); BOOST_CHECK_EQUAL(ret.size(), 0); /* we should not have sent any queries to ns */ BOOST_CHECK_EQUAL(queriesToNS, 0); } <API key>(test_root_nx_trust) { std::unique_ptr<SyncRes> sr; initSR(sr); primeHints(); const DNSName target1("powerdns.com."); const DNSName target2("notpowerdns.com."); const ComboAddress ns("192.0.2.1:53"); size_t queriesCount = 0; sr->setAsyncCallback([target1, target2, ns, &queriesCount](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { queriesCount++; if (isRootServer(ip)) { if (domain == target1) { setLWResult(res, RCode::NXDomain, true, false, true); addRecordToLW(res, ".", QType::SOA, "a.root-servers.net. nstld.verisign-grs.com. 2017032800 1800 900 604800 86400", DNSResourceRecord::AUTHORITY, 86400); } else { setLWResult(res, 0, true, false, true); addRecordToLW(res, domain, QType::NS, "a.gtld-servers.net.", DNSResourceRecord::AUTHORITY, 172800); addRecordToLW(res, "a.gtld-servers.net.", QType::A, ns.toString(), DNSResourceRecord::ADDITIONAL, 3600); } return 1; } else if (ip == ns) { setLWResult(res, 0, true, false, false); addRecordToLW(res, domain, QType::A, "192.0.2.2"); return 1; } return 0; }); vector<DNSRecord> ret; int res = sr->beginResolve(target1, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NXDomain); BOOST_CHECK_EQUAL(ret.size(), 1); /* one for target1 and one for the entire TLD */ BOOST_CHECK_EQUAL(SyncRes::getNegCacheSize(), 2); ret.clear(); res = sr->beginResolve(target2, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NXDomain); BOOST_CHECK_EQUAL(ret.size(), 1); /* one for target1 and one for the entire TLD */ BOOST_CHECK_EQUAL(SyncRes::getNegCacheSize(), 2); /* we should have sent only one query */ BOOST_CHECK_EQUAL(queriesCount, 1); } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; init(); initSR(sr, true, false); primeHints(); const DNSName target1("powerdns.com."); const DNSName target2("notpowerdns.com."); const ComboAddress ns("192.0.2.1:53"); size_t queriesCount = 0; /* This time the root denies target1 with a "com." SOA instead of a "." one. We should add target1 to the negcache, but not "com.". */ sr->setAsyncCallback([target1, target2, ns, &queriesCount](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { queriesCount++; if (isRootServer(ip)) { if (domain == target1) { setLWResult(res, RCode::NXDomain, true, false, true); addRecordToLW(res, "com.", QType::SOA, "a.root-servers.net. nstld.verisign-grs.com. 2017032800 1800 900 604800 86400", DNSResourceRecord::AUTHORITY, 86400); } else { setLWResult(res, 0, true, false, true); addRecordToLW(res, domain, QType::NS, "a.gtld-servers.net.", DNSResourceRecord::AUTHORITY, 172800); addRecordToLW(res, "a.gtld-servers.net.", QType::A, ns.toString(), DNSResourceRecord::ADDITIONAL, 3600); } return 1; } else if (ip == ns) { setLWResult(res, 0, true, false, false); addRecordToLW(res, domain, QType::A, "192.0.2.2"); return 1; } return 0; }); vector<DNSRecord> ret; int res = sr->beginResolve(target1, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NXDomain); BOOST_CHECK_EQUAL(ret.size(), 1); /* even with root-nx-trust on and a NX answer from the root, we should not have cached the entire TLD this time. */ BOOST_CHECK_EQUAL(SyncRes::t_sstorage.negcache.size(), 1); ret.clear(); res = sr->beginResolve(target2, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_REQUIRE_EQUAL(ret.size(), 1); BOOST_REQUIRE(ret[0].d_type == QType::A); BOOST_CHECK_EQUAL(ret[0].d_name, target2); BOOST_CHECK(getRR<ARecordContent>(ret[0])->getCA() == ComboAddress("192.0.2.2")); BOOST_CHECK_EQUAL(SyncRes::t_sstorage.negcache.size(), 1); BOOST_CHECK_EQUAL(queriesCount, 3); } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr); primeHints(); const DNSName target1("powerdns.com."); const DNSName target2("notpowerdns.com."); const ComboAddress ns("192.0.2.1:53"); size_t queriesCount = 0; sr->setAsyncCallback([target1, target2, ns, &queriesCount](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { queriesCount++; if (isRootServer(ip)) { if (domain == target1) { setLWResult(res, RCode::NXDomain, true, false, true); addRecordToLW(res, ".", QType::SOA, "a.root-servers.net. nstld.verisign-grs.com. 2017032800 1800 900 604800 86400", DNSResourceRecord::AUTHORITY, 86400); } else { setLWResult(res, 0, true, false, true); addRecordToLW(res, domain, QType::NS, "a.gtld-servers.net.", DNSResourceRecord::AUTHORITY, 172800); addRecordToLW(res, "a.gtld-servers.net.", QType::A, ns.toString(), DNSResourceRecord::ADDITIONAL, 3600); } return 1; } else if (ip == ns) { setLWResult(res, 0, true, false, false); addRecordToLW(res, domain, QType::A, "192.0.2.2"); return 1; } return 0; }); SyncRes::s_rootNXTrust = false; vector<DNSRecord> ret; int res = sr->beginResolve(target1, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NXDomain); BOOST_CHECK_EQUAL(ret.size(), 1); /* one for target1 */ BOOST_CHECK_EQUAL(SyncRes::getNegCacheSize(), 1); ret.clear(); res = sr->beginResolve(target2, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(ret.size(), 1); /* one for target1 */ BOOST_CHECK_EQUAL(SyncRes::getNegCacheSize(), 1); /* we should have sent three queries */ BOOST_CHECK_EQUAL(queriesCount, 3); } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr); primeHints(); const DNSName target("www.powerdns.com."); const DNSName cnameTarget("cname.powerdns.com."); SyncRes::addEDNSDomain(DNSName("powerdns.com.")); EDNSSubnetOpts incomingECS; incomingECS.source = Netmask("192.0.2.128/32"); sr->setQuerySource(ComboAddress(), boost::optional<const EDNSSubnetOpts&>(incomingECS)); sr->setAsyncCallback([target,cnameTarget](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { BOOST_REQUIRE(srcmask); BOOST_CHECK_EQUAL(srcmask->toString(), "192.0.2.0/24"); if (isRootServer(ip)) { setLWResult(res, 0, false, false, true); addRecordToLW(res, "powerdns.com.", QType::NS, "pdns-public-ns1.powerdns.com.", DNSResourceRecord::AUTHORITY, 172800); addRecordToLW(res, "pdns-public-ns1.powerdns.com.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); return 1; } else if (ip == ComboAddress("192.0.2.1:53")) { if (domain == target) { /* Type 2 NXDOMAIN (rfc2308 section-2.1) */ setLWResult(res, RCode::NXDomain, true, false, true); addRecordToLW(res, domain, QType::CNAME, cnameTarget.toString()); addRecordToLW(res, "powerdns.com", QType::SOA, "pdns-public-ns1.powerdns.com. pieter\\.lexis.powerdns.com. 2017032301 10800 3600 604800 3600", DNSResourceRecord::AUTHORITY, 3600); } else if (domain == cnameTarget) { /* we shouldn't get there since the Type NXDOMAIN should have been enough, but we might if we still chase the CNAME. */ setLWResult(res, RCode::NXDomain, true, false, true); addRecordToLW(res, "powerdns.com", QType::SOA, "pdns-public-ns1.powerdns.com. pieter\\.lexis.powerdns.com. 2017032301 10800 3600 604800 3600", DNSResourceRecord::AUTHORITY, 3600); } return 1; } return 0; }); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NXDomain); BOOST_CHECK_EQUAL(ret.size(), 2); /* no negative cache entry because the response was variable */ BOOST_CHECK_EQUAL(SyncRes::getNegCacheSize(), 0); } <API key>(test_ns_speed) { std::unique_ptr<SyncRes> sr; initSR(sr); primeHints(); const DNSName target("powerdns.com."); std::map<ComboAddress, uint64_t> nsCounts; sr->setAsyncCallback([target,&nsCounts](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { if (isRootServer(ip)) { setLWResult(res, 0, false, false, true); addRecordToLW(res, domain, QType::NS, "pdns-public-ns1.powerdns.com.", DNSResourceRecord::AUTHORITY, 172800); addRecordToLW(res, domain, QType::NS, "pdns-public-ns2.powerdns.com.", DNSResourceRecord::AUTHORITY, 172800); addRecordToLW(res, domain, QType::NS, "pdns-public-ns3.powerdns.com.", DNSResourceRecord::AUTHORITY, 172800); addRecordToLW(res, "pdns-public-ns1.powerdns.com.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); addRecordToLW(res, "pdns-public-ns1.powerdns.com.", QType::AAAA, "2001:DB8::1", DNSResourceRecord::ADDITIONAL, 3600); addRecordToLW(res, "pdns-public-ns2.powerdns.com.", QType::A, "192.0.2.2", DNSResourceRecord::ADDITIONAL, 3600); addRecordToLW(res, "pdns-public-ns2.powerdns.com.", QType::AAAA, "2001:DB8::2", DNSResourceRecord::ADDITIONAL, 3600); addRecordToLW(res, "pdns-public-ns3.powerdns.com.", QType::A, "192.0.2.3", DNSResourceRecord::ADDITIONAL, 3600); addRecordToLW(res, "pdns-public-ns3.powerdns.com.", QType::AAAA, "2001:DB8::3", DNSResourceRecord::ADDITIONAL, 3600); return 1; } else { nsCounts[ip]++; if (ip == ComboAddress("[2001:DB8::2]:53") || ip == ComboAddress("192.0.2.2:53")) { BOOST_CHECK_LT(nsCounts.size(), 3); /* let's time out on pdns-public-ns2.powerdns.com. */ return 0; } else if (ip == ComboAddress("192.0.2.1:53")) { BOOST_CHECK_EQUAL(nsCounts.size(), 3); setLWResult(res, 0, true, false, true); addRecordToLW(res, domain, QType::A, "192.0.2.254"); return 1; } return 0; } return 0; }); struct timeval now = sr->getNow(); /* make pdns-public-ns2.powerdns.com. the fastest NS, with its IPv6 address faster than the IPV4 one, then pdns-public-ns1.powerdns.com. on IPv4 */ SyncRes::submitNSSpeed(DNSName("pdns-public-ns1.powerdns.com."), ComboAddress("192.0.2.1:53"), 100, &now); SyncRes::submitNSSpeed(DNSName("pdns-public-ns1.powerdns.com."), ComboAddress("[2001:DB8::1]:53"), 10000, &now); SyncRes::submitNSSpeed(DNSName("pdns-public-ns2.powerdns.com."), ComboAddress("192.0.2.2:53"), 10, &now); SyncRes::submitNSSpeed(DNSName("pdns-public-ns2.powerdns.com."), ComboAddress("[2001:DB8::2]:53"), 1, &now); SyncRes::submitNSSpeed(DNSName("pdns-public-ns3.powerdns.com."), ComboAddress("192.0.2.3:53"), 10000, &now); SyncRes::submitNSSpeed(DNSName("pdns-public-ns3.powerdns.com."), ComboAddress("[2001:DB8::3]:53"), 10000, &now); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(ret.size(), 1); BOOST_CHECK_EQUAL(nsCounts.size(), 3); BOOST_CHECK_EQUAL(nsCounts[ComboAddress("192.0.2.1:53")], 1); BOOST_CHECK_EQUAL(nsCounts[ComboAddress("192.0.2.2:53")], 1); BOOST_CHECK_EQUAL(nsCounts[ComboAddress("[2001:DB8::2]:53")], 1); } <API key>(test_flawed_nsset) { std::unique_ptr<SyncRes> sr; initSR(sr); primeHints(); const DNSName target("powerdns.com."); sr->setAsyncCallback([target](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { if (isRootServer(ip)) { setLWResult(res, 0, false, false, true); addRecordToLW(res, domain, QType::NS, "pdns-public-ns1.powerdns.com.", DNSResourceRecord::AUTHORITY, 172800); addRecordToLW(res, "pdns-public-ns1.powerdns.com.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); return 1; } else if (ip == ComboAddress("192.0.2.1:53")) { setLWResult(res, 0, true, false, true); addRecordToLW(res, domain, QType::A, "192.0.2.254"); return 1; } return 0; }); /* we populate the cache with a flawed NSset, i.e. there is a NS entry but no corresponding glue */ time_t now = sr->getNow().tv_sec; std::vector<DNSRecord> records; std::vector<shared_ptr<RRSIGRecordContent> > sigs; addRecordToList(records, target, QType::NS, "pdns-public-ns1.powerdns.com.", DNSResourceRecord::AUTHORITY, now + 3600); t_RC->replace(now, target, QType(QType::NS), records, sigs, vector<std::shared_ptr<DNSRecord>>(), true, boost::optional<Netmask>()); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(ret.size(), 1); } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr); primeHints(); const DNSName target("powerdns.com."); size_t queriesCount = 0; sr->setAsyncCallback([&queriesCount,target](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { queriesCount++; if (isRootServer(ip) && domain == target) { setLWResult(res, 0, false, false, true); addRecordToLW(res, domain, QType::NS, "pdns-public-ns2.powerdns.com.", DNSResourceRecord::AUTHORITY, 172800); addRecordToLW(res, domain, QType::NS, "pdns-public-ns3.powerdns.com.", DNSResourceRecord::AUTHORITY, 172800); return 1; } else if (domain == DNSName("pdns-public-ns2.powerdns.com.") || domain == DNSName("pdns-public-ns3.powerdns.com.")){ setLWResult(res, 0, true, false, true); addRecordToLW(res, ".", QType::SOA, "a.root-servers.net. nstld.verisign-grs.com. 2017032800 1800 900 604800 86400", DNSResourceRecord::AUTHORITY, 86400); return 1; } return 0; }); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::ServFail); BOOST_CHECK_EQUAL(ret.size(), 0); /* one query to get NSs, then A and AAAA for each NS */ BOOST_CHECK_EQUAL(queriesCount, 5); } <API key>(test_cache_hit) { std::unique_ptr<SyncRes> sr; initSR(sr); primeHints(); const DNSName target("powerdns.com."); sr->setAsyncCallback([target](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { return 0; }); /* we populate the cache with eveything we need */ time_t now = sr->getNow().tv_sec; std::vector<DNSRecord> records; std::vector<shared_ptr<RRSIGRecordContent> > sigs; addRecordToList(records, target, QType::A, "192.0.2.1", DNSResourceRecord::ANSWER, now + 3600); t_RC->replace(now, target , QType(QType::A), records, sigs, vector<std::shared_ptr<DNSRecord>>(), true, boost::optional<Netmask>()); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(ret.size(), 1); } <API key>(test_no_rd) { std::unique_ptr<SyncRes> sr; initSR(sr); primeHints(); const DNSName target("powerdns.com."); size_t queriesCount = 0; sr->setCacheOnly(); sr->setAsyncCallback([target,&queriesCount](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { queriesCount++; return 0; }); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(ret.size(), 0); BOOST_CHECK_EQUAL(queriesCount, 0); } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr); primeHints(); const DNSName target("cachettl.powerdns.com."); const ComboAddress ns("192.0.2.1:53"); sr->setAsyncCallback([target,ns](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { if (isRootServer(ip)) { setLWResult(res, 0, false, false, true); addRecordToLW(res, domain, QType::NS, "a.gtld-servers.net.", DNSResourceRecord::AUTHORITY, 172800); addRecordToLW(res, "a.gtld-servers.net.", QType::A, ns.toString(), DNSResourceRecord::ADDITIONAL, 7200); return 1; } else if (ip == ns) { setLWResult(res, 0, true, false, false); addRecordToLW(res, domain, QType::A, "192.0.2.2", DNSResourceRecord::ANSWER, 10); return 1; } return 0; }); const time_t now = sr->getNow().tv_sec; SyncRes::s_minimumTTL = 60; SyncRes::s_maxcachettl = 3600; vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_REQUIRE_EQUAL(ret.size(), 1); BOOST_CHECK_EQUAL(ret[0].d_ttl, SyncRes::s_minimumTTL); const ComboAddress who; vector<DNSRecord> cached; BOOST_REQUIRE_GT(t_RC->get(now, target, QType(QType::A), true, &cached, who), 0); BOOST_REQUIRE_EQUAL(cached.size(), 1); BOOST_REQUIRE_GT(cached[0].d_ttl, now); BOOST_CHECK_EQUAL((cached[0].d_ttl - now), SyncRes::s_minimumTTL); cached.clear(); BOOST_REQUIRE_GT(t_RC->get(now, target, QType(QType::NS), false, &cached, who), 0); BOOST_REQUIRE_EQUAL(cached.size(), 1); BOOST_REQUIRE_GT(cached[0].d_ttl, now); BOOST_CHECK_LE((cached[0].d_ttl - now), SyncRes::s_maxcachettl); } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr); primeHints(); const DNSName target("powerdns.com."); sr->setAsyncCallback([target](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { if (isRootServer(ip)) { setLWResult(res, 0, false, false, true); addRecordToLW(res, domain, QType::NS, "pdns-public-ns1.powerdns.com.", DNSResourceRecord::AUTHORITY, 172800); addRecordToLW(res, "pdns-public-ns1.powerdns.com.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); return 1; } else if (ip == ComboAddress("192.0.2.1:53")) { setLWResult(res, 0, true, false, true); addRecordToLW(res, domain, QType::A, "192.0.2.2"); return 1; } return 0; }); /* we populate the cache with entries that expired 60s ago*/ const time_t now = sr->getNow().tv_sec; std::vector<DNSRecord> records; std::vector<shared_ptr<RRSIGRecordContent> > sigs; addRecordToList(records, target, QType::A, "192.0.2.42", DNSResourceRecord::ANSWER, now - 60); t_RC->replace(now - 3600, target, QType(QType::A), records, sigs, vector<std::shared_ptr<DNSRecord>>(), true, boost::optional<Netmask>()); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_REQUIRE_EQUAL(ret.size(), 1); BOOST_REQUIRE(ret[0].d_type == QType::A); BOOST_CHECK_EQUAL(getRR<ARecordContent>(ret[0])->getCA().toStringWithPort(), ComboAddress("192.0.2.2").toStringWithPort()); } <API key>(test_cache_auth) { std::unique_ptr<SyncRes> sr; initSR(sr); primeHints(); /* the auth server is sending the same answer in answer and additional, check that we only return one result, and we only cache one too. */ const DNSName target("cache-auth.powerdns.com."); sr->setAsyncCallback([target](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { setLWResult(res, 0, true, false, true); addRecordToLW(res, domain, QType::A, "192.0.2.2", DNSResourceRecord::ANSWER, 10); addRecordToLW(res, domain, QType::A, "192.0.2.2", DNSResourceRecord::ADDITIONAL, 10); return 1; }); const time_t now = sr->getNow().tv_sec; vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_REQUIRE_EQUAL(ret.size(), 1); BOOST_REQUIRE_EQUAL(QType(ret.at(0).d_type).getName(), QType(QType::A).getName()); BOOST_CHECK_EQUAL(getRR<ARecordContent>(ret.at(0))->getCA().toString(), ComboAddress("192.0.2.2").toString()); /* check that we correctly cached only the answer entry, not the additional one */ const ComboAddress who; vector<DNSRecord> cached; BOOST_REQUIRE_GT(t_RC->get(now, target, QType(QType::A), true, &cached, who), 0); BOOST_REQUIRE_EQUAL(cached.size(), 1); BOOST_REQUIRE_EQUAL(QType(cached.at(0).d_type).getName(), QType(QType::A).getName()); BOOST_CHECK_EQUAL(getRR<ARecordContent>(cached.at(0))->getCA().toString(), ComboAddress("192.0.2.2").toString()); } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr); primeHints(); /* Thanks, Verisign */ SyncRes::addDelegationOnly(DNSName("com.")); SyncRes::addDelegationOnly(DNSName("net.")); const DNSName target("nx-powerdns.com."); sr->setAsyncCallback([target](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { if (isRootServer(ip)) { setLWResult(res, 0, false, false, true); addRecordToLW(res, "com.", QType::NS, "a.gtld-servers.net.", DNSResourceRecord::AUTHORITY, 172800); addRecordToLW(res, "a.gtld-servers.net.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); return 1; } else if (ip == ComboAddress("192.0.2.1:53")) { setLWResult(res, 0, true, false, true); addRecordToLW(res, domain, QType::A, "192.0.2.42"); return 1; } return 0; }); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NXDomain); BOOST_CHECK_EQUAL(ret.size(), 0); } <API key>(test_unauth_any) { std::unique_ptr<SyncRes> sr; initSR(sr); primeHints(); const DNSName target("powerdns.com."); sr->setAsyncCallback([target](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { if (isRootServer(ip)) { setLWResult(res, 0, false, false, true); addRecordToLW(res, "com.", QType::NS, "a.gtld-servers.net.", DNSResourceRecord::AUTHORITY, 172800); addRecordToLW(res, "a.gtld-servers.net.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); return 1; } else if (ip == ComboAddress("192.0.2.1:53")) { setLWResult(res, 0, false, false, true); addRecordToLW(res, domain, QType::A, "192.0.2.42"); return 1; } return 0; }); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::ANY), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::ServFail); BOOST_CHECK_EQUAL(ret.size(), 0); } <API key>(test_no_data) { std::unique_ptr<SyncRes> sr; initSR(sr); primeHints(); const DNSName target("powerdns.com."); sr->setAsyncCallback([target](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { setLWResult(res, 0, true, false, true); return 1; }); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(ret.size(), 0); } <API key>(test_skip_opt_any) { std::unique_ptr<SyncRes> sr; initSR(sr); primeHints(); const DNSName target("powerdns.com."); sr->setAsyncCallback([target](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { setLWResult(res, 0, true, false, true); addRecordToLW(res, domain, QType::A, "192.0.2.42"); addRecordToLW(res, domain, QType::ANY, "0 0"); addRecordToLW(res, domain, QType::OPT, ""); return 1; }); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(ret.size(), 1); } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr); primeHints(); const DNSName target("powerdns.com."); sr->setAsyncCallback([target](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { setLWResult(res, 0, true, false, true); addRecordToLW(res, domain, QType::SOA, "pdns-public-ns1.powerdns.com. pieter\\.lexis.powerdns.com. 2017032301 10800 3600 604800 3600", DNSResourceRecord::AUTHORITY, 3600); /* the NSEC and RRSIG contents are complete garbage, please ignore them */ addRecordToLW(res, domain, QType::NSEC, "deadbeef", DNSResourceRecord::AUTHORITY); addRecordToLW(res, domain, QType::RRSIG, "NSEC 5 2 600 2100010100000000 2100010100000000 24567 dummy data", DNSResourceRecord::AUTHORITY); addRecordToLW(res, domain, QType::RRSIG, "SOA 5 3 600 2100010100000000 2100010100000000 24567 dummy data", DNSResourceRecord::AUTHORITY); return 1; }); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(ret.size(), 1); } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr, true); primeHints(); const DNSName target("powerdns.com."); sr->setAsyncCallback([target](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { setLWResult(res, 0, true, false, true); addRecordToLW(res, domain, QType::SOA, "pdns-public-ns1.powerdns.com. pieter\\.lexis.powerdns.com. 2017032301 10800 3600 604800 3600", DNSResourceRecord::AUTHORITY, 3600); /* the NSEC and RRSIG contents are complete garbage, please ignore them */ addRecordToLW(res, domain, QType::NSEC, "deadbeef", DNSResourceRecord::AUTHORITY); addRecordToLW(res, domain, QType::RRSIG, "NSEC 5 2 600 2100010100000000 2100010100000000 24567 dummy data", DNSResourceRecord::AUTHORITY); addRecordToLW(res, domain, QType::RRSIG, "SOA 5 3 600 2100010100000000 2100010100000000 24567 dummy data", DNSResourceRecord::AUTHORITY); return 1; }); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(ret.size(), 4); } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr); primeHints(); const DNSName target("powerdns.com."); sr->setAsyncCallback([target](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { setLWResult(res, RCode::NXDomain, true, false, true); addRecordToLW(res, domain, QType::SOA, "pdns-public-ns1.powerdns.com. pieter\\.lexis.powerdns.com. 2017032301 10800 3600 604800 3600", DNSResourceRecord::AUTHORITY, 3600); /* the NSEC and RRSIG contents are complete garbage, please ignore them */ addRecordToLW(res, domain, QType::NSEC, "deadbeef", DNSResourceRecord::AUTHORITY); addRecordToLW(res, domain, QType::RRSIG, "NSEC 5 2 600 2100010100000000 2100010100000000 24567 dummy data", DNSResourceRecord::AUTHORITY); addRecordToLW(res, domain, QType::RRSIG, "SOA 5 3 600 2100010100000000 2100010100000000 24567 dummy data", DNSResourceRecord::AUTHORITY); return 1; }); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NXDomain); BOOST_CHECK_EQUAL(ret.size(), 1); } <API key>(test_nx_nsec_dnssec) { std::unique_ptr<SyncRes> sr; initSR(sr, true); primeHints(); const DNSName target("powerdns.com."); sr->setAsyncCallback([target](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { setLWResult(res, RCode::NXDomain, true, false, true); addRecordToLW(res, domain, QType::SOA, "pdns-public-ns1.powerdns.com. pieter\\.lexis.powerdns.com. 2017032301 10800 3600 604800 3600", DNSResourceRecord::AUTHORITY, 3600); /* the NSEC and RRSIG contents are complete garbage, please ignore them */ addRecordToLW(res, domain, QType::NSEC, "deadbeef", DNSResourceRecord::AUTHORITY); addRecordToLW(res, domain, QType::RRSIG, "NSEC 5 2 600 2100010100000000 2100010100000000 24567 dummy data", DNSResourceRecord::AUTHORITY); addRecordToLW(res, domain, QType::RRSIG, "SOA 5 3 600 2100010100000000 2100010100000000 24567 dummy data", DNSResourceRecord::AUTHORITY); return 1; }); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NXDomain); BOOST_CHECK_EQUAL(ret.size(), 4); } <API key>(test_qclass_none) { std::unique_ptr<SyncRes> sr; initSR(sr); primeHints(); /* apart from special names and QClass::ANY, anything else than QClass::IN should be rejected right away */ size_t queriesCount = 0; sr->setAsyncCallback([&queriesCount](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { queriesCount++; return 0; }); const DNSName target("powerdns.com."); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::NONE, ret); BOOST_CHECK_EQUAL(res, -1); BOOST_CHECK_EQUAL(ret.size(), 0); BOOST_CHECK_EQUAL(queriesCount, 0); } <API key>(test_special_types) { std::unique_ptr<SyncRes> sr; initSR(sr); primeHints(); /* {A,I}XFR, RRSIG and NSEC3 should be rejected right away */ size_t queriesCount = 0; sr->setAsyncCallback([&queriesCount](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { cerr<<"asyncresolve called to ask "<<ip.toStringWithPort()<<" about "<<domain.toString()<<" / "<<QType(type).getName()<<" over "<<(doTCP ? "TCP" : "UDP")<<" (rd: "<<sendRDQuery<<", EDNS0 level: "<<EDNS0Level<<")"<<endl; queriesCount++; return 0; }); const DNSName target("powerdns.com."); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::AXFR), QClass::IN, ret); BOOST_CHECK_EQUAL(res, -1); BOOST_CHECK_EQUAL(ret.size(), 0); BOOST_CHECK_EQUAL(queriesCount, 0); res = sr->beginResolve(target, QType(QType::IXFR), QClass::IN, ret); BOOST_CHECK_EQUAL(res, -1); BOOST_CHECK_EQUAL(ret.size(), 0); BOOST_CHECK_EQUAL(queriesCount, 0); res = sr->beginResolve(target, QType(QType::RRSIG), QClass::IN, ret); BOOST_CHECK_EQUAL(res, -1); BOOST_CHECK_EQUAL(ret.size(), 0); BOOST_CHECK_EQUAL(queriesCount, 0); res = sr->beginResolve(target, QType(QType::NSEC3), QClass::IN, ret); BOOST_CHECK_EQUAL(res, -1); BOOST_CHECK_EQUAL(ret.size(), 0); BOOST_CHECK_EQUAL(queriesCount, 0); } <API key>(test_special_names) { std::unique_ptr<SyncRes> sr; initSR(sr); primeHints(); /* special names should be handled internally */ size_t queriesCount = 0; sr->setAsyncCallback([&queriesCount](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { queriesCount++; return 0; }); vector<DNSRecord> ret; int res = sr->beginResolve(DNSName("1.0.0.127.in-addr.arpa."), QType(QType::PTR), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_REQUIRE_EQUAL(ret.size(), 1); BOOST_CHECK(ret[0].d_type == QType::PTR); BOOST_CHECK_EQUAL(queriesCount, 0); ret.clear(); res = sr->beginResolve(DNSName("1.0.0.127.in-addr.arpa."), QType(QType::ANY), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_REQUIRE_EQUAL(ret.size(), 1); BOOST_CHECK(ret[0].d_type == QType::PTR); BOOST_CHECK_EQUAL(queriesCount, 0); ret.clear(); res = sr->beginResolve(DNSName("1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.ip6.arpa."), QType(QType::PTR), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_REQUIRE_EQUAL(ret.size(), 1); BOOST_CHECK(ret[0].d_type == QType::PTR); BOOST_CHECK_EQUAL(queriesCount, 0); ret.clear(); res = sr->beginResolve(DNSName("1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.ip6.arpa."), QType(QType::ANY), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_REQUIRE_EQUAL(ret.size(), 1); BOOST_CHECK(ret[0].d_type == QType::PTR); BOOST_CHECK_EQUAL(queriesCount, 0); ret.clear(); res = sr->beginResolve(DNSName("localhost."), QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_REQUIRE_EQUAL(ret.size(), 1); BOOST_CHECK(ret[0].d_type == QType::A); BOOST_CHECK_EQUAL(getRR<ARecordContent>(ret[0])->getCA().toString(), "127.0.0.1"); BOOST_CHECK_EQUAL(queriesCount, 0); ret.clear(); res = sr->beginResolve(DNSName("localhost."), QType(QType::AAAA), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_REQUIRE_EQUAL(ret.size(), 1); BOOST_CHECK(ret[0].d_type == QType::AAAA); BOOST_CHECK_EQUAL(getRR<AAAARecordContent>(ret[0])->getCA().toString(), "::1"); BOOST_CHECK_EQUAL(queriesCount, 0); ret.clear(); res = sr->beginResolve(DNSName("localhost."), QType(QType::ANY), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_REQUIRE_EQUAL(ret.size(), 2); for (const auto& rec : ret) { BOOST_REQUIRE((rec.d_type == QType::A) || rec.d_type == QType::AAAA); if (rec.d_type == QType::A) { BOOST_CHECK_EQUAL(getRR<ARecordContent>(rec)->getCA().toString(), "127.0.0.1"); } else { BOOST_CHECK_EQUAL(getRR<AAAARecordContent>(rec)->getCA().toString(), "::1"); } } BOOST_CHECK_EQUAL(queriesCount, 0); ret.clear(); res = sr->beginResolve(DNSName("version.bind."), QType(QType::TXT), QClass::CHAOS, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_REQUIRE_EQUAL(ret.size(), 1); BOOST_CHECK(ret[0].d_type == QType::TXT); BOOST_CHECK_EQUAL(getRR<TXTRecordContent>(ret[0])->d_text, "\"PowerDNS Unit Tests\""); BOOST_CHECK_EQUAL(queriesCount, 0); ret.clear(); res = sr->beginResolve(DNSName("version.bind."), QType(QType::ANY), QClass::CHAOS, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_REQUIRE_EQUAL(ret.size(), 1); BOOST_CHECK(ret[0].d_type == QType::TXT); BOOST_CHECK_EQUAL(getRR<TXTRecordContent>(ret[0])->d_text, "\"PowerDNS Unit Tests\""); BOOST_CHECK_EQUAL(queriesCount, 0); ret.clear(); res = sr->beginResolve(DNSName("version.pdns."), QType(QType::TXT), QClass::CHAOS, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_REQUIRE_EQUAL(ret.size(), 1); BOOST_CHECK(ret[0].d_type == QType::TXT); BOOST_CHECK_EQUAL(getRR<TXTRecordContent>(ret[0])->d_text, "\"PowerDNS Unit Tests\""); BOOST_CHECK_EQUAL(queriesCount, 0); ret.clear(); res = sr->beginResolve(DNSName("version.pdns."), QType(QType::ANY), QClass::CHAOS, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_REQUIRE_EQUAL(ret.size(), 1); BOOST_CHECK(ret[0].d_type == QType::TXT); BOOST_CHECK_EQUAL(getRR<TXTRecordContent>(ret[0])->d_text, "\"PowerDNS Unit Tests\""); BOOST_CHECK_EQUAL(queriesCount, 0); ret.clear(); res = sr->beginResolve(DNSName("id.server."), QType(QType::TXT), QClass::CHAOS, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_REQUIRE_EQUAL(ret.size(), 1); BOOST_CHECK(ret[0].d_type == QType::TXT); BOOST_CHECK_EQUAL(getRR<TXTRecordContent>(ret[0])->d_text, "\"PowerDNS Unit Tests Server ID\""); BOOST_CHECK_EQUAL(queriesCount, 0); ret.clear(); res = sr->beginResolve(DNSName("id.server."), QType(QType::ANY), QClass::CHAOS, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_REQUIRE_EQUAL(ret.size(), 1); BOOST_CHECK(ret[0].d_type == QType::TXT); BOOST_CHECK_EQUAL(getRR<TXTRecordContent>(ret[0])->d_text, "\"PowerDNS Unit Tests Server ID\""); BOOST_CHECK_EQUAL(queriesCount, 0); } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr); primeHints(); const DNSName target("rpz.powerdns.com."); const ComboAddress ns("192.0.2.1:53"); sr->setAsyncCallback([target,ns](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { if (isRootServer(ip)) { setLWResult(res, false, true, false, true); addRecordToLW(res, "com.", QType::NS, "a.gtld-servers.net.", DNSResourceRecord::AUTHORITY, 172800); addRecordToLW(res, "a.gtld-servers.net.", QType::A, ns.toString(), DNSResourceRecord::ADDITIONAL, 3600); return 1; } else if (ip == ns) { setLWResult(res, 0, true, false, true); addRecordToLW(res, domain, QType::A, "192.0.2.42"); return 1; } return 0; }); DNSFilterEngine::Policy pol; pol.d_kind = DNSFilterEngine::PolicyKind::Drop; std::shared_ptr<DNSFilterEngine::Zone> zone = std::make_shared<DNSFilterEngine::Zone>(); zone->setName("Unit test policy 0"); zone->addNSIPTrigger(Netmask(ns, 32), pol); auto luaconfsCopy = g_luaconfs.getCopy(); luaconfsCopy.dfe.addZone(zone); g_luaconfs.setState(luaconfsCopy); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, -2); BOOST_CHECK_EQUAL(ret.size(), 0); } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr); primeHints(); const DNSName target("rpz.powerdns.com."); const ComboAddress ns("[2001:DB8::42]:53"); sr->setAsyncCallback([target,ns](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { if (isRootServer(ip)) { setLWResult(res, 0, false, false, true); addRecordToLW(res, "com.", QType::NS, "a.gtld-servers.net.", DNSResourceRecord::AUTHORITY, 172800); addRecordToLW(res, "a.gtld-servers.net.", QType::AAAA, ns.toString(), DNSResourceRecord::ADDITIONAL, 3600); return 1; } else if (ip == ns) { setLWResult(res, 0, true, false, true); addRecordToLW(res, domain, QType::A, "192.0.2.42"); return 1; } return 0; }); DNSFilterEngine::Policy pol; pol.d_kind = DNSFilterEngine::PolicyKind::Drop; std::shared_ptr<DNSFilterEngine::Zone> zone = std::make_shared<DNSFilterEngine::Zone>(); zone->setName("Unit test policy 0"); zone->addNSIPTrigger(Netmask(ns, 128), pol); auto luaconfsCopy = g_luaconfs.getCopy(); luaconfsCopy.dfe.addZone(zone); g_luaconfs.setState(luaconfsCopy); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, -2); BOOST_CHECK_EQUAL(ret.size(), 0); } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr); primeHints(); const DNSName target("rpz.powerdns.com."); const ComboAddress ns("192.0.2.1:53"); const DNSName nsName("ns1.powerdns.com."); sr->setAsyncCallback([target,ns,nsName](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { if (isRootServer(ip)) { setLWResult(res, 0, false, false, true); addRecordToLW(res, domain, QType::NS, nsName.toString(), DNSResourceRecord::AUTHORITY, 172800); addRecordToLW(res, nsName, QType::A, ns.toString(), DNSResourceRecord::ADDITIONAL, 3600); return 1; } else if (ip == ns) { setLWResult(res, 0, true, false, true); addRecordToLW(res, domain, QType::A, "192.0.2.42"); return 1; } return 0; }); DNSFilterEngine::Policy pol; pol.d_kind = DNSFilterEngine::PolicyKind::Drop; std::shared_ptr<DNSFilterEngine::Zone> zone = std::make_shared<DNSFilterEngine::Zone>(); zone->setName("Unit test policy 0"); zone->addNSTrigger(nsName, pol); auto luaconfsCopy = g_luaconfs.getCopy(); luaconfsCopy.dfe.addZone(zone); g_luaconfs.setState(luaconfsCopy); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, -2); BOOST_CHECK_EQUAL(ret.size(), 0); } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr); primeHints(); const DNSName target("rpz.powerdns.com."); const ComboAddress ns("192.0.2.1:53"); const DNSName nsName("ns1.powerdns.com."); sr->setAsyncCallback([target,ns,nsName](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { if (isRootServer(ip)) { setLWResult(res, 0, false, false, true); addRecordToLW(res, domain, QType::NS, nsName.toString(), DNSResourceRecord::AUTHORITY, 172800); addRecordToLW(res, nsName, QType::A, ns.toString(), DNSResourceRecord::ADDITIONAL, 3600); return 1; } else if (ip == ns) { setLWResult(res, 0, true, false, true); addRecordToLW(res, domain, QType::A, "192.0.2.42"); return 1; } return 0; }); DNSFilterEngine::Policy pol; pol.d_kind = DNSFilterEngine::PolicyKind::Drop; std::shared_ptr<DNSFilterEngine::Zone> zone = std::make_shared<DNSFilterEngine::Zone>(); zone->setName("Unit test policy 0"); zone->addNSIPTrigger(Netmask(ns, 128), pol); zone->addNSTrigger(nsName, pol); auto luaconfsCopy = g_luaconfs.getCopy(); luaconfsCopy.dfe.addZone(zone); g_luaconfs.setState(luaconfsCopy); /* RPZ is disabled for this query, we should not be blocked */ sr->setWantsRPZ(false); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(ret.size(), 1); } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr); primeHints(); const DNSName target("powerdns.com."); const ComboAddress ns("192.0.2.1:53"); const ComboAddress forwardedNS("192.0.2.42:53"); SyncRes::AuthDomain ad; ad.d_rdForward = false; ad.d_servers.push_back(forwardedNS); (*SyncRes::t_sstorage.domainmap)[target] = ad; sr->setAsyncCallback([forwardedNS](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { if (ip == forwardedNS) { BOOST_CHECK_EQUAL(sendRDQuery, false); setLWResult(res, 0, true, false, true); addRecordToLW(res, domain, QType::A, "192.0.2.42"); return 1; } return 0; }); /* simulate a no-RD query */ sr->setCacheOnly(); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(ret.size(), 1); } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr); primeHints(); const DNSName target("powerdns.com."); const ComboAddress ns("192.0.2.1:53"); const ComboAddress forwardedNS("192.0.2.42:53"); SyncRes::AuthDomain ad; ad.d_rdForward = false; ad.d_servers.push_back(forwardedNS); (*SyncRes::t_sstorage.domainmap)[target] = ad; sr->setAsyncCallback([forwardedNS](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { if (ip == forwardedNS) { BOOST_CHECK_EQUAL(sendRDQuery, false); setLWResult(res, 0, true, false, true); addRecordToLW(res, domain, QType::A, "192.0.2.42"); return 1; } return 0; }); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(ret.size(), 1); } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr); primeHints(); const DNSName target("powerdns.com."); const ComboAddress ns("192.0.2.1:53"); const ComboAddress forwardedNS("192.0.2.42:53"); SyncRes::AuthDomain ad; ad.d_rdForward = true; ad.d_servers.push_back(forwardedNS); (*SyncRes::t_sstorage.domainmap)[target] = ad; sr->setAsyncCallback([forwardedNS](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { if (ip == forwardedNS) { BOOST_CHECK_EQUAL(sendRDQuery, false); setLWResult(res, 0, true, false, true); addRecordToLW(res, domain, QType::A, "192.0.2.42"); return 1; } return 0; }); /* simulate a no-RD query */ sr->setCacheOnly(); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(ret.size(), 1); } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr); primeHints(); const DNSName target("powerdns.com."); const ComboAddress ns("192.0.2.1:53"); const ComboAddress forwardedNS("192.0.2.42:53"); SyncRes::AuthDomain ad; ad.d_rdForward = true; ad.d_servers.push_back(forwardedNS); (*SyncRes::t_sstorage.domainmap)[target] = ad; sr->setAsyncCallback([forwardedNS](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { if (ip == forwardedNS) { BOOST_CHECK_EQUAL(sendRDQuery, true); setLWResult(res, 0, true, false, true); addRecordToLW(res, domain, QType::A, "192.0.2.42"); return 1; } return 0; }); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(ret.size(), 1); } <API key>(test_auth_zone_oob) { std::unique_ptr<SyncRes> sr; initSR(sr, true); primeHints(); size_t queriesCount = 0; const DNSName target("test.xx."); const ComboAddress targetAddr("127.0.0.1"); const DNSName authZone("test.xx"); SyncRes::AuthDomain ad; DNSRecord dr; dr.d_place = DNSResourceRecord::ANSWER; dr.d_name = target; dr.d_type = QType::A; dr.d_ttl = 1800; dr.d_content = std::make_shared<ARecordContent>(targetAddr); ad.d_records.insert(dr); (*SyncRes::t_sstorage.domainmap)[authZone] = ad; sr->setAsyncCallback([&queriesCount](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { queriesCount++; return 0; }); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, 0); BOOST_REQUIRE_EQUAL(ret.size(), 1); BOOST_CHECK(ret[0].d_type == QType::A); BOOST_CHECK_EQUAL(queriesCount, 0); BOOST_CHECK(sr->wasOutOfBand()); BOOST_CHECK_EQUAL(sr->getValidationState(), Indeterminate); /* a second time, to check that the OOB flag is set when the query cache is used */ ret.clear(); res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, 0); BOOST_REQUIRE_EQUAL(ret.size(), 1); BOOST_CHECK(ret[0].d_type == QType::A); BOOST_CHECK_EQUAL(queriesCount, 0); BOOST_CHECK(sr->wasOutOfBand()); BOOST_CHECK_EQUAL(sr->getValidationState(), Indeterminate); /* a third time, to check that the validation is disabled when the OOB flag is set */ ret.clear(); sr-><API key>(true); res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, 0); BOOST_REQUIRE_EQUAL(ret.size(), 1); BOOST_CHECK(ret[0].d_type == QType::A); BOOST_CHECK_EQUAL(queriesCount, 0); BOOST_CHECK(sr->wasOutOfBand()); BOOST_CHECK_EQUAL(sr->getValidationState(), Indeterminate); } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr, true); primeHints(); size_t queriesCount = 0; const DNSName target("cname.test.xx."); const DNSName targetCname("cname-target.test.xx."); const ComboAddress targetCnameAddr("127.0.0.1"); const DNSName authZone("test.xx"); SyncRes::AuthDomain ad; DNSRecord dr; dr.d_place = DNSResourceRecord::ANSWER; dr.d_name = target; dr.d_type = QType::CNAME; dr.d_ttl = 1800; dr.d_content = std::make_shared<CNAMERecordContent>(targetCname); ad.d_records.insert(dr); dr.d_place = DNSResourceRecord::ANSWER; dr.d_name = targetCname; dr.d_type = QType::A; dr.d_ttl = 1800; dr.d_content = std::make_shared<ARecordContent>(targetCnameAddr); ad.d_records.insert(dr); (*SyncRes::t_sstorage.domainmap)[authZone] = ad; sr->setAsyncCallback([&queriesCount](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { queriesCount++; return 0; }); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, 0); BOOST_REQUIRE_EQUAL(ret.size(), 2); BOOST_CHECK(ret[0].d_type == QType::CNAME); BOOST_CHECK(ret[1].d_type == QType::A); BOOST_CHECK_EQUAL(queriesCount, 0); BOOST_CHECK(sr->wasOutOfBand()); BOOST_CHECK_EQUAL(sr->getValidationState(), Indeterminate); /* a second time, to check that the OOB flag is set when the query cache is used */ ret.clear(); res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, 0); BOOST_REQUIRE_EQUAL(ret.size(), 2); BOOST_CHECK(ret[0].d_type == QType::CNAME); BOOST_CHECK(ret[1].d_type == QType::A); BOOST_CHECK_EQUAL(queriesCount, 0); BOOST_CHECK(sr->wasOutOfBand()); BOOST_CHECK_EQUAL(sr->getValidationState(), Indeterminate); /* a third time, to check that the validation is disabled when the OOB flag is set */ ret.clear(); sr-><API key>(true); res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, 0); BOOST_REQUIRE_EQUAL(ret.size(), 2); BOOST_CHECK(ret[0].d_type == QType::CNAME); BOOST_CHECK(ret[1].d_type == QType::A); BOOST_CHECK_EQUAL(queriesCount, 0); BOOST_CHECK(sr->wasOutOfBand()); BOOST_CHECK_EQUAL(sr->getValidationState(), Indeterminate); } <API key>(test_auth_zone) { std::unique_ptr<SyncRes> sr; initSR(sr); primeHints(); size_t queriesCount = 0; const DNSName target("powerdns.com."); const ComboAddress addr("192.0.2.5"); SyncRes::AuthDomain ad; ad.d_name = target; DNSRecord dr; dr.d_place = DNSResourceRecord::ANSWER; dr.d_name = target; dr.d_type = QType::SOA; dr.d_ttl = 3600; dr.d_content = std::make_shared<SOARecordContent>("pdns-public-ns1.powerdns.com. pieter\\.lexis.powerdns.com. 2017032301 10800 3600 604800 3600"); ad.d_records.insert(dr); dr.d_place = DNSResourceRecord::ANSWER; dr.d_name = target; dr.d_type = QType::A; dr.d_ttl = 3600; dr.d_content = std::make_shared<ARecordContent>(addr); ad.d_records.insert(dr); auto map = std::make_shared<SyncRes::domainmap_t>(); (*map)[target] = ad; SyncRes::setDomainMap(map); sr->setAsyncCallback([&queriesCount](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { queriesCount++; setLWResult(res, 0, true, false, true); addRecordToLW(res, domain, QType::A, "192.0.2.42"); return 1; }); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(ret.size(), 1); BOOST_CHECK(ret[0].d_type == QType::A); BOOST_CHECK_EQUAL(getRR<ARecordContent>(ret[0])->getCA().toString(), addr.toString()); BOOST_CHECK_EQUAL(queriesCount, 0); } <API key>(test_<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr); primeHints(); size_t queriesCount = 0; const DNSName target("powerdns.com."); const DNSName authZone("internal.powerdns.com."); const ComboAddress addr("192.0.2.5"); SyncRes::AuthDomain ad; ad.d_name = authZone; DNSRecord dr; dr.d_place = DNSResourceRecord::ANSWER; dr.d_name = authZone; dr.d_type = QType::SOA; dr.d_ttl = 3600; dr.d_content = std::make_shared<SOARecordContent>("pdns-public-ns1.powerdns.com. pieter\\.lexis.powerdns.com. 2017032301 10800 3600 604800 3600"); ad.d_records.insert(dr); dr.d_place = DNSResourceRecord::ANSWER; dr.d_name = authZone; dr.d_type = QType::A; dr.d_ttl = 3600; dr.d_content = std::make_shared<ARecordContent>(addr); ad.d_records.insert(dr); auto map = std::make_shared<SyncRes::domainmap_t>(); (*map)[authZone] = ad; SyncRes::setDomainMap(map); sr->setAsyncCallback([&queriesCount,target,authZone](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { queriesCount++; if (domain == target) { setLWResult(res, 0, true, false, true); addRecordToLW(res, target, QType::CNAME, authZone.toString(), DNSResourceRecord::ANSWER, 3600); return 1; } return 0; }); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(ret.size(), 2); BOOST_CHECK(ret[0].d_type == QType::CNAME); BOOST_CHECK_EQUAL(getRR<CNAMERecordContent>(ret[0])->getTarget().toString(), authZone.toString()); BOOST_CHECK(ret[1].d_type == QType::A); BOOST_CHECK_EQUAL(getRR<ARecordContent>(ret[1])->getCA().toString(), addr.toString()); BOOST_CHECK_EQUAL(queriesCount, 1); } <API key>(test_<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr); primeHints(); size_t queriesCount = 0; const DNSName target("powerdns.com."); const DNSName externalCNAME("www.open-xchange.com."); const ComboAddress addr("192.0.2.5"); SyncRes::AuthDomain ad; ad.d_name = target; DNSRecord dr; dr.d_place = DNSResourceRecord::ANSWER; dr.d_name = target; dr.d_type = QType::SOA; dr.d_ttl = 3600; dr.d_content = std::make_shared<SOARecordContent>("pdns-public-ns1.powerdns.com. pieter\\.lexis.powerdns.com. 2017032301 10800 3600 604800 3600"); ad.d_records.insert(dr); dr.d_place = DNSResourceRecord::ANSWER; dr.d_name = target; dr.d_type = QType::CNAME; dr.d_ttl = 3600; dr.d_content = std::make_shared<CNAMERecordContent>(externalCNAME); ad.d_records.insert(dr); auto map = std::make_shared<SyncRes::domainmap_t>(); (*map)[target] = ad; SyncRes::setDomainMap(map); sr->setAsyncCallback([&queriesCount,externalCNAME,addr](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { queriesCount++; if (domain == externalCNAME) { setLWResult(res, 0, true, false, true); addRecordToLW(res, externalCNAME, QType::A, addr.toString(), DNSResourceRecord::ANSWER, 3600); return 1; } return 0; }); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(ret.size(), 2); BOOST_CHECK(ret[0].d_type == QType::CNAME); BOOST_CHECK_EQUAL(getRR<CNAMERecordContent>(ret[0])->getTarget().toString(), externalCNAME.toString()); BOOST_CHECK(ret[1].d_type == QType::A); BOOST_CHECK_EQUAL(getRR<ARecordContent>(ret[1])->getCA().toString(), addr.toString()); BOOST_CHECK_EQUAL(queriesCount, 1); } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr); primeHints(); size_t queriesCount = 0; const DNSName target("nodata.powerdns.com."); const DNSName authZone("powerdns.com"); SyncRes::AuthDomain ad; ad.d_name = authZone; DNSRecord dr; dr.d_place = DNSResourceRecord::ANSWER; dr.d_name = target; dr.d_type = QType::A; dr.d_ttl = 3600; dr.d_content = std::make_shared<ARecordContent>(ComboAddress("192.0.2.1")); ad.d_records.insert(dr); dr.d_place = DNSResourceRecord::ANSWER; dr.d_name = authZone; dr.d_type = QType::SOA; dr.d_ttl = 3600; dr.d_content = std::make_shared<SOARecordContent>("pdns-public-ns1.powerdns.com. pieter\\.lexis.powerdns.com. 2017032301 10800 3600 604800 3600"); ad.d_records.insert(dr); auto map = std::make_shared<SyncRes::domainmap_t>(); (*map)[authZone] = ad; SyncRes::setDomainMap(map); sr->setAsyncCallback([&queriesCount](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { queriesCount++; return 0; }); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::AAAA), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_REQUIRE_EQUAL(ret.size(), 1); BOOST_CHECK(ret[0].d_type == QType::SOA); BOOST_CHECK_EQUAL(queriesCount, 0); } <API key>(test_auth_zone_nx) { std::unique_ptr<SyncRes> sr; initSR(sr); primeHints(); size_t queriesCount = 0; const DNSName target("nx.powerdns.com."); const DNSName authZone("powerdns.com"); SyncRes::AuthDomain ad; ad.d_name = authZone; DNSRecord dr; dr.d_place = DNSResourceRecord::ANSWER; dr.d_name = DNSName("powerdns.com."); dr.d_type = QType::SOA; dr.d_ttl = 3600; dr.d_content = std::make_shared<SOARecordContent>("pdns-public-ns1.powerdns.com. pieter\\.lexis.powerdns.com. 2017032301 10800 3600 604800 3600"); ad.d_records.insert(dr); auto map = std::make_shared<SyncRes::domainmap_t>(); (*map)[authZone] = ad; SyncRes::setDomainMap(map); sr->setAsyncCallback([&queriesCount](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { queriesCount++; return 0; }); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NXDomain); BOOST_REQUIRE_EQUAL(ret.size(), 1); BOOST_CHECK(ret[0].d_type == QType::SOA); BOOST_CHECK_EQUAL(queriesCount, 0); } <API key>(test_<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr, true, false); primeHints(); size_t queriesCount = 0; const DNSName target("www.test.powerdns.com."); const ComboAddress targetAddr("192.0.2.2"); const DNSName ns("ns1.test.powerdns.com."); const ComboAddress nsAddr("192.0.2.1"); const DNSName authZone("powerdns.com"); SyncRes::AuthDomain ad; ad.d_name = authZone; DNSRecord dr; dr.d_place = DNSResourceRecord::ANSWER; dr.d_name = authZone; dr.d_type = QType::SOA; dr.d_ttl = 3600; dr.d_content = std::make_shared<SOARecordContent>("pdns-public-ns1.powerdns.com. pieter\\.lexis.powerdns.com. 2017032301 10800 3600 604800 3600"); ad.d_records.insert(dr); dr.d_place = DNSResourceRecord::ANSWER; dr.d_name = DNSName("test.powerdns.com."); dr.d_type = QType::NS; dr.d_ttl = 3600; dr.d_content = std::make_shared<NSRecordContent>(ns); ad.d_records.insert(dr); dr.d_place = DNSResourceRecord::ANSWER; dr.d_name = ns; dr.d_type = QType::A; dr.d_ttl = 3600; dr.d_content = std::make_shared<ARecordContent>(nsAddr); ad.d_records.insert(dr); auto map = std::make_shared<SyncRes::domainmap_t>(); (*map)[authZone] = ad; SyncRes::setDomainMap(map); testkeysset_t keys; auto luaconfsCopy = g_luaconfs.getCopy(); luaconfsCopy.dsAnchors.clear(); generateKeyMaterial(g_rootdnsname, DNSSECKeeper::RSASHA512, DNSSECKeeper::SHA384, keys, luaconfsCopy.dsAnchors); g_luaconfs.setState(luaconfsCopy); sr->setAsyncCallback([&queriesCount,target,targetAddr,nsAddr,authZone,keys](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { queriesCount++; if (type == QType::DS || type == QType::DNSKEY) { return <API key>(res, domain, DNSName("."), type, keys, domain == authZone); } if (ip == ComboAddress(nsAddr.toString(), 53) && domain == target) { setLWResult(res, 0, true, false, true); addRecordToLW(res, domain, QType::A, targetAddr.toString(), DNSResourceRecord::ANSWER, 3600); return 1; } return 0; }); sr-><API key>(true); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_REQUIRE_EQUAL(ret.size(), 1); BOOST_CHECK(ret[0].d_type == QType::A); BOOST_CHECK_EQUAL(queriesCount, 4); BOOST_CHECK_EQUAL(sr->getValidationState(), Indeterminate); } <API key>(test_<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr); primeHints(); size_t queriesCount = 0; const DNSName target("test.powerdns.com."); const ComboAddress targetAddr("192.0.2.2"); const DNSName ns("ns1.test.powerdns.com."); const ComboAddress nsAddr("192.0.2.1"); const DNSName authZone("powerdns.com"); SyncRes::AuthDomain ad; ad.d_name = authZone; DNSRecord dr; dr.d_place = DNSResourceRecord::ANSWER; dr.d_name = authZone; dr.d_type = QType::SOA; dr.d_ttl = 3600; dr.d_content = std::make_shared<SOARecordContent>("pdns-public-ns1.powerdns.com. pieter\\.lexis.powerdns.com. 2017032301 10800 3600 604800 3600"); ad.d_records.insert(dr); dr.d_place = DNSResourceRecord::ANSWER; dr.d_name = DNSName("test.powerdns.com."); dr.d_type = QType::NS; dr.d_ttl = 3600; dr.d_content = std::make_shared<NSRecordContent>(ns); ad.d_records.insert(dr); dr.d_place = DNSResourceRecord::ANSWER; dr.d_name = ns; dr.d_type = QType::A; dr.d_ttl = 3600; dr.d_content = std::make_shared<ARecordContent>(nsAddr); ad.d_records.insert(dr); auto map = std::make_shared<SyncRes::domainmap_t>(); (*map)[authZone] = ad; SyncRes::setDomainMap(map); sr->setAsyncCallback([&queriesCount,nsAddr,target,targetAddr](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { queriesCount++; if (ip == ComboAddress(nsAddr.toString(), 53) && domain == target) { setLWResult(res, 0, true, false, true); addRecordToLW(res, domain, QType::A, targetAddr.toString(), DNSResourceRecord::ANSWER, 3600); return 1; } return 0; }); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_REQUIRE_EQUAL(ret.size(), 1); BOOST_CHECK(ret[0].d_type == QType::A); BOOST_CHECK_EQUAL(queriesCount, 1); } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr); primeHints(); size_t queriesCount = 0; const DNSName target("test.powerdns.com."); const ComboAddress targetAddr("192.0.2.2"); const DNSName authZone("powerdns.com"); SyncRes::AuthDomain ad; ad.d_name = authZone; DNSRecord dr; dr.d_place = DNSResourceRecord::ANSWER; dr.d_name = authZone; dr.d_type = QType::SOA; dr.d_ttl = 3600; dr.d_content = std::make_shared<SOARecordContent>("pdns-public-ns1.powerdns.com. pieter\\.lexis.powerdns.com. 2017032301 10800 3600 604800 3600"); ad.d_records.insert(dr); dr.d_place = DNSResourceRecord::ANSWER; dr.d_name = DNSName("*.powerdns.com."); dr.d_type = QType::A; dr.d_ttl = 3600; dr.d_content = std::make_shared<ARecordContent>(targetAddr); ad.d_records.insert(dr); auto map = std::make_shared<SyncRes::domainmap_t>(); (*map)[authZone] = ad; SyncRes::setDomainMap(map); sr->setAsyncCallback([&queriesCount](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { queriesCount++; return 0; }); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_REQUIRE_EQUAL(ret.size(), 1); BOOST_CHECK(ret[0].d_type == QType::A); BOOST_CHECK_EQUAL(queriesCount, 0); } <API key>(test_<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr); primeHints(); size_t queriesCount = 0; const DNSName target("test.powerdns.com."); const ComboAddress targetAddr("192.0.2.2"); const DNSName authZone("powerdns.com"); SyncRes::AuthDomain ad; ad.d_name = authZone; DNSRecord dr; dr.d_place = DNSResourceRecord::ANSWER; dr.d_name = authZone; dr.d_type = QType::SOA; dr.d_ttl = 3600; dr.d_content = std::make_shared<SOARecordContent>("pdns-public-ns1.powerdns.com. pieter\\.lexis.powerdns.com. 2017032301 10800 3600 604800 3600"); ad.d_records.insert(dr); dr.d_place = DNSResourceRecord::ANSWER; dr.d_name = DNSName("*.powerdns.com."); dr.d_type = QType::A; dr.d_ttl = 3600; dr.d_content = std::make_shared<ARecordContent>(targetAddr); ad.d_records.insert(dr); auto map = std::make_shared<SyncRes::domainmap_t>(); (*map)[authZone] = ad; SyncRes::setDomainMap(map); sr->setAsyncCallback([&queriesCount](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { queriesCount++; return 0; }); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::AAAA), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_REQUIRE_EQUAL(ret.size(), 1); BOOST_CHECK(ret[0].d_type == QType::SOA); BOOST_CHECK_EQUAL(queriesCount, 0); } <API key>(test_<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr); primeHints(); size_t queriesCount = 0; const DNSName target("powerdns.com."); const ComboAddress addr("192.0.2.5"); SyncRes::AuthDomain ad; ad.d_name = target; DNSRecord dr; dr.d_place = DNSResourceRecord::ANSWER; dr.d_name = target; dr.d_type = QType::SOA; dr.d_ttl = 3600; dr.d_content = std::make_shared<SOARecordContent>("pdns-public-ns1.powerdns.com. pieter\\.lexis.powerdns.com. 2017032301 10800 3600 604800 3600"); ad.d_records.insert(dr); dr.d_place = DNSResourceRecord::ANSWER; dr.d_name = target; dr.d_type = QType::A; dr.d_ttl = 3600; dr.d_content = std::make_shared<ARecordContent>(addr); ad.d_records.insert(dr); auto map = std::make_shared<SyncRes::domainmap_t>(); (*map)[target] = ad; SyncRes::setDomainMap(map); sr->setAsyncCallback([&queriesCount](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { queriesCount++; setLWResult(res, 0, true, false, true); addRecordToLW(res, domain, QType::A, "192.0.2.42"); return 1; }); /* simulate a no-RD query */ sr->setCacheOnly(); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(ret.size(), 1); BOOST_CHECK(ret[0].d_type == QType::A); BOOST_CHECK_EQUAL(getRR<ARecordContent>(ret[0])->getCA().toString(), addr.toString()); BOOST_CHECK_EQUAL(queriesCount, 0); } <API key>(test_dnssec_rrsig) { init(); auto dcke = std::shared_ptr<DNSCryptoKeyEngine>(DNSCryptoKeyEngine::make(DNSSECKeeper::ECDSA256)); dcke->create(dcke->getBits()); // cerr<<dcke->convertToISC()<<endl; DNSSECPrivateKey dpk; dpk.d_flags = 256; dpk.setKey(dcke); std::vector<std::shared_ptr<DNSRecordContent> > recordcontents; recordcontents.push_back(getRecordContent(QType::A, "192.0.2.1")); DNSName qname("powerdns.com."); time_t now = time(nullptr); RRSIGRecordContent rrc; /* this RRSIG is valid for the current second only */ computeRRSIG(dpk, qname, qname, QType::A, 600, 0, rrc, recordcontents, boost::none, now); skeyset_t keyset; keyset.insert(std::make_shared<DNSKEYRecordContent>(dpk.getDNSKEY())); std::vector<std::shared_ptr<RRSIGRecordContent> > sigs; sigs.push_back(std::make_shared<RRSIGRecordContent>(rrc)); BOOST_CHECK(validateWithKeySet(now, qname, recordcontents, sigs, keyset)); } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr, true); setDNSSECValidation(sr, DNSSECMode::ValidateAll); primeHints(); const DNSName target("."); testkeysset_t keys; auto luaconfsCopy = g_luaconfs.getCopy(); luaconfsCopy.dsAnchors.clear(); generateKeyMaterial(target, DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys, luaconfsCopy.dsAnchors); g_luaconfs.setState(luaconfsCopy); size_t queriesCount = 0; sr->setAsyncCallback([target,&queriesCount,keys](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { queriesCount++; if (domain == target && type == QType::NS) { setLWResult(res, 0, true, false, true); char addr[] = "a.root-servers.net."; for (char idx = 'a'; idx <= 'm'; idx++) { addr[0] = idx; addRecordToLW(res, domain, QType::NS, std::string(addr), DNSResourceRecord::ANSWER, 3600); } addRRSIG(keys, res->d_records, domain, 300); addRecordToLW(res, "a.root-servers.net.", QType::A, "198.41.0.4", DNSResourceRecord::ADDITIONAL, 3600); addRecordToLW(res, "a.root-servers.net.", QType::AAAA, "2001:503:ba3e::2:30", DNSResourceRecord::ADDITIONAL, 3600); return 1; } else if (domain == target && type == QType::DNSKEY) { setLWResult(res, 0, true, false, true); addDNSKEY(keys, domain, 300, res->d_records); addRRSIG(keys, res->d_records, domain, 300); return 1; } return 0; }); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::NS), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Secure); /* 13 NS + 1 RRSIG */ BOOST_REQUIRE_EQUAL(ret.size(), 14); BOOST_CHECK_EQUAL(queriesCount, 2); /* again, to test the cache */ ret.clear(); res = sr->beginResolve(target, QType(QType::NS), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Secure); BOOST_REQUIRE_EQUAL(ret.size(), 14); BOOST_CHECK_EQUAL(queriesCount, 2); } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr, true); setDNSSECValidation(sr, DNSSECMode::ValidateAll); primeHints(); const DNSName target("."); testkeysset_t zskeys; testkeysset_t kskeys; /* Generate key material for "." */ auto dckeZ = std::shared_ptr<DNSCryptoKeyEngine>(DNSCryptoKeyEngine::make(DNSSECKeeper::ECDSA256)); dckeZ->create(dckeZ->getBits()); DNSSECPrivateKey ksk; ksk.d_flags = 257; ksk.setKey(dckeZ); DSRecordContent kskds = makeDSFromDNSKey(target, ksk.getDNSKEY(), DNSSECKeeper::SHA256); auto dckeK = std::shared_ptr<DNSCryptoKeyEngine>(DNSCryptoKeyEngine::make(DNSSECKeeper::ECDSA256)); dckeK->create(dckeK->getBits()); DNSSECPrivateKey zsk; zsk.d_flags = 256; zsk.setKey(dckeK); DSRecordContent zskds = makeDSFromDNSKey(target, zsk.getDNSKEY(), DNSSECKeeper::SHA256); kskeys[target] = std::pair<DNSSECPrivateKey,DSRecordContent>(ksk, kskds); zskeys[target] = std::pair<DNSSECPrivateKey,DSRecordContent>(zsk, zskds); /* Set the root DS */ auto luaconfsCopy = g_luaconfs.getCopy(); luaconfsCopy.dsAnchors.clear(); luaconfsCopy.dsAnchors[g_rootdnsname].insert(kskds); g_luaconfs.setState(luaconfsCopy); size_t queriesCount = 0; sr->setAsyncCallback([target,&queriesCount,zskeys,kskeys](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { queriesCount++; if (domain == target && type == QType::NS) { setLWResult(res, 0, true, false, true); char addr[] = "a.root-servers.net."; for (char idx = 'a'; idx <= 'm'; idx++) { addr[0] = idx; addRecordToLW(res, domain, QType::NS, std::string(addr), DNSResourceRecord::ANSWER, 3600); } addRRSIG(zskeys, res->d_records, domain, 300); addRecordToLW(res, "a.root-servers.net.", QType::A, "198.41.0.4", DNSResourceRecord::ADDITIONAL, 3600); addRecordToLW(res, "a.root-servers.net.", QType::AAAA, "2001:503:ba3e::2:30", DNSResourceRecord::ADDITIONAL, 3600); return 1; } else if (domain == target && type == QType::DNSKEY) { setLWResult(res, 0, true, false, true); addDNSKEY(kskeys, domain, 300, res->d_records); addDNSKEY(zskeys, domain, 300, res->d_records); addRRSIG(kskeys, res->d_records, domain, 300); return 1; } return 0; }); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::NS), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Secure); /* 13 NS + 1 RRSIG */ BOOST_REQUIRE_EQUAL(ret.size(), 14); BOOST_CHECK_EQUAL(queriesCount, 2); /* again, to test the cache */ ret.clear(); res = sr->beginResolve(target, QType(QType::NS), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Secure); BOOST_REQUIRE_EQUAL(ret.size(), 14); BOOST_CHECK_EQUAL(queriesCount, 2); } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr, true); setDNSSECValidation(sr, DNSSECMode::ValidateAll); primeHints(); const DNSName target("."); testkeysset_t keys; auto luaconfsCopy = g_luaconfs.getCopy(); luaconfsCopy.dsAnchors.clear(); generateKeyMaterial(target, DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys, luaconfsCopy.dsAnchors); g_luaconfs.setState(luaconfsCopy); size_t queriesCount = 0; sr->setAsyncCallback([target,&queriesCount,keys](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { queriesCount++; if (domain == target && type == QType::NS) { setLWResult(res, 0, true, false, true); char addr[] = "a.root-servers.net."; for (char idx = 'a'; idx <= 'm'; idx++) { addr[0] = idx; addRecordToLW(res, domain, QType::NS, std::string(addr), DNSResourceRecord::ANSWER, 3600); } addRRSIG(keys, res->d_records, domain, 300); addRecordToLW(res, "a.root-servers.net.", QType::A, "198.41.0.4", DNSResourceRecord::ADDITIONAL, 3600); addRecordToLW(res, "a.root-servers.net.", QType::AAAA, "2001:503:ba3e::2:30", DNSResourceRecord::ADDITIONAL, 3600); return 1; } else if (domain == target && type == QType::DNSKEY) { setLWResult(res, 0, true, false, true); /* No DNSKEY */ return 1; } return 0; }); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::NS), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Bogus); /* 13 NS + 1 RRSIG */ BOOST_REQUIRE_EQUAL(ret.size(), 14); BOOST_CHECK_EQUAL(queriesCount, 2); /* again, to test the cache */ ret.clear(); res = sr->beginResolve(target, QType(QType::NS), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Bogus); BOOST_REQUIRE_EQUAL(ret.size(), 14); BOOST_CHECK_EQUAL(queriesCount, 2); } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr, true); setDNSSECValidation(sr, DNSSECMode::ValidateAll); primeHints(); const DNSName target("."); testkeysset_t dskeys; testkeysset_t keys; /* Generate key material for "." */ auto dckeDS = std::shared_ptr<DNSCryptoKeyEngine>(DNSCryptoKeyEngine::make(DNSSECKeeper::ECDSA256)); dckeDS->create(dckeDS->getBits()); DNSSECPrivateKey dskey; dskey.d_flags = 257; dskey.setKey(dckeDS); DSRecordContent drc = makeDSFromDNSKey(target, dskey.getDNSKEY(), DNSSECKeeper::SHA256); auto dcke = std::shared_ptr<DNSCryptoKeyEngine>(DNSCryptoKeyEngine::make(DNSSECKeeper::ECDSA256)); dcke->create(dcke->getBits()); DNSSECPrivateKey dpk; dpk.d_flags = 256; dpk.setKey(dcke); DSRecordContent uselessdrc = makeDSFromDNSKey(target, dpk.getDNSKEY(), DNSSECKeeper::SHA256); dskeys[target] = std::pair<DNSSECPrivateKey,DSRecordContent>(dskey, drc); keys[target] = std::pair<DNSSECPrivateKey,DSRecordContent>(dpk, uselessdrc); /* Set the root DS */ auto luaconfsCopy = g_luaconfs.getCopy(); luaconfsCopy.dsAnchors.clear(); luaconfsCopy.dsAnchors[g_rootdnsname].insert(drc); g_luaconfs.setState(luaconfsCopy); size_t queriesCount = 0; sr->setAsyncCallback([target,&queriesCount,keys](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { queriesCount++; if (domain == target && type == QType::NS) { setLWResult(res, 0, true, false, true); char addr[] = "a.root-servers.net."; for (char idx = 'a'; idx <= 'm'; idx++) { addr[0] = idx; addRecordToLW(res, domain, QType::NS, std::string(addr), DNSResourceRecord::ANSWER, 3600); } addRRSIG(keys, res->d_records, domain, 300); addRecordToLW(res, "a.root-servers.net.", QType::A, "198.41.0.4", DNSResourceRecord::ADDITIONAL, 3600); addRecordToLW(res, "a.root-servers.net.", QType::AAAA, "2001:503:ba3e::2:30", DNSResourceRecord::ADDITIONAL, 3600); return 1; } else if (domain == target && type == QType::DNSKEY) { setLWResult(res, 0, true, false, true); addDNSKEY(keys, domain, 300, res->d_records); addRRSIG(keys, res->d_records, domain, 300); return 1; } return 0; }); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::NS), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Bogus); /* 13 NS + 1 RRSIG */ BOOST_REQUIRE_EQUAL(ret.size(), 14); BOOST_CHECK_EQUAL(queriesCount, 2); /* again, to test the cache */ ret.clear(); res = sr->beginResolve(target, QType(QType::NS), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Bogus); BOOST_REQUIRE_EQUAL(ret.size(), 14); BOOST_CHECK_EQUAL(queriesCount, 2); } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr, true); setDNSSECValidation(sr, DNSSECMode::ValidateAll); primeHints(); const DNSName target("."); testkeysset_t keys; testkeysset_t rrsigkeys; auto luaconfsCopy = g_luaconfs.getCopy(); luaconfsCopy.dsAnchors.clear(); generateKeyMaterial(target, DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys, luaconfsCopy.dsAnchors); g_luaconfs.setState(luaconfsCopy); auto dckeRRSIG = std::shared_ptr<DNSCryptoKeyEngine>(DNSCryptoKeyEngine::make(DNSSECKeeper::ECDSA256)); dckeRRSIG->create(dckeRRSIG->getBits()); DNSSECPrivateKey rrsigkey; rrsigkey.d_flags = 257; rrsigkey.setKey(dckeRRSIG); DSRecordContent rrsigds = makeDSFromDNSKey(target, rrsigkey.getDNSKEY(), DNSSECKeeper::SHA256); rrsigkeys[target] = std::pair<DNSSECPrivateKey,DSRecordContent>(rrsigkey, rrsigds); size_t queriesCount = 0; sr->setAsyncCallback([target,&queriesCount,keys,rrsigkeys](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { queriesCount++; if (domain == target && type == QType::NS) { setLWResult(res, 0, true, false, true); char addr[] = "a.root-servers.net."; for (char idx = 'a'; idx <= 'm'; idx++) { addr[0] = idx; addRecordToLW(res, domain, QType::NS, std::string(addr), DNSResourceRecord::ANSWER, 3600); } addRRSIG(rrsigkeys, res->d_records, domain, 300); addRecordToLW(res, "a.root-servers.net.", QType::A, "198.41.0.4", DNSResourceRecord::ADDITIONAL, 3600); addRecordToLW(res, "a.root-servers.net.", QType::AAAA, "2001:503:ba3e::2:30", DNSResourceRecord::ADDITIONAL, 3600); return 1; } else if (domain == target && type == QType::DNSKEY) { setLWResult(res, 0, true, false, true); addDNSKEY(keys, domain, 300, res->d_records); addRRSIG(rrsigkeys, res->d_records, domain, 300); return 1; } return 0; }); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::NS), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Bogus); /* 13 NS + 1 RRSIG */ BOOST_REQUIRE_EQUAL(ret.size(), 14); BOOST_CHECK_EQUAL(queriesCount, 2); /* again, to test the cache */ ret.clear(); res = sr->beginResolve(target, QType(QType::NS), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Bogus); BOOST_REQUIRE_EQUAL(ret.size(), 14); BOOST_CHECK_EQUAL(queriesCount, 2); } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr, true); setDNSSECValidation(sr, DNSSECMode::ValidateAll); primeHints(); const DNSName target("."); testkeysset_t keys; auto luaconfsCopy = g_luaconfs.getCopy(); luaconfsCopy.dsAnchors.clear(); generateKeyMaterial(target, DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys, luaconfsCopy.dsAnchors); g_luaconfs.setState(luaconfsCopy); size_t queriesCount = 0; sr->setAsyncCallback([target,&queriesCount,keys](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { queriesCount++; if (domain == target && type == QType::NS) { setLWResult(res, 0, true, false, true); char addr[] = "a.root-servers.net."; for (char idx = 'a'; idx <= 'm'; idx++) { addr[0] = idx; addRecordToLW(res, domain, QType::NS, std::string(addr), DNSResourceRecord::ANSWER, 3600); } /* No RRSIG */ addRecordToLW(res, "a.root-servers.net.", QType::A, "198.41.0.4", DNSResourceRecord::ADDITIONAL, 3600); addRecordToLW(res, "a.root-servers.net.", QType::AAAA, "2001:503:ba3e::2:30", DNSResourceRecord::ADDITIONAL, 3600); return 1; } else if (domain == target && type == QType::DNSKEY) { setLWResult(res, 0, true, false, true); addDNSKEY(keys, domain, 300, res->d_records); addRRSIG(keys, res->d_records, domain, 300); return 1; } return 0; }); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::NS), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Bogus); /* 13 NS + 0 RRSIG */ BOOST_REQUIRE_EQUAL(ret.size(), 13); /* no RRSIG so no query for DNSKEYs */ BOOST_CHECK_EQUAL(queriesCount, 1); /* again, to test the cache */ ret.clear(); res = sr->beginResolve(target, QType(QType::NS), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Bogus); BOOST_REQUIRE_EQUAL(ret.size(), 13); BOOST_CHECK_EQUAL(queriesCount, 1); } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr, true); setDNSSECValidation(sr, DNSSECMode::ValidateAll); primeHints(); const DNSName target("."); testkeysset_t keys; /* Generate key material for "." */ auto dcke = std::shared_ptr<DNSCryptoKeyEngine>(DNSCryptoKeyEngine::make(DNSSECKeeper::ECDSA256)); dcke->create(dcke->getBits()); DNSSECPrivateKey dpk; dpk.d_flags = 256; dpk.setKey(dcke); /* Fake algorithm number (private) */ dpk.d_algorithm = 253; DSRecordContent drc = makeDSFromDNSKey(target, dpk.getDNSKEY(), DNSSECKeeper::SHA256); keys[target] = std::pair<DNSSECPrivateKey,DSRecordContent>(dpk, drc); /* Fake algorithm number (private) */ drc.d_algorithm = 253; /* Set the root DS */ auto luaconfsCopy = g_luaconfs.getCopy(); luaconfsCopy.dsAnchors.clear(); luaconfsCopy.dsAnchors[g_rootdnsname].insert(drc); g_luaconfs.setState(luaconfsCopy); size_t queriesCount = 0; sr->setAsyncCallback([target,&queriesCount,keys](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { queriesCount++; if (domain == target && type == QType::NS) { setLWResult(res, 0, true, false, true); char addr[] = "a.root-servers.net."; for (char idx = 'a'; idx <= 'm'; idx++) { addr[0] = idx; addRecordToLW(res, domain, QType::NS, std::string(addr), DNSResourceRecord::ANSWER, 3600); } addRRSIG(keys, res->d_records, domain, 300); addRecordToLW(res, "a.root-servers.net.", QType::A, "198.41.0.4", DNSResourceRecord::ADDITIONAL, 3600); addRecordToLW(res, "a.root-servers.net.", QType::AAAA, "2001:503:ba3e::2:30", DNSResourceRecord::ADDITIONAL, 3600); return 1; } else if (domain == target && type == QType::DNSKEY) { setLWResult(res, 0, true, false, true); addDNSKEY(keys, domain, 300, res->d_records); addRRSIG(keys, res->d_records, domain, 300); return 1; } return 0; }); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::NS), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Insecure); /* 13 NS + 1 RRSIG */ BOOST_REQUIRE_EQUAL(ret.size(), 14); /* no supported DS so no query for DNSKEYs */ BOOST_CHECK_EQUAL(queriesCount, 1); /* again, to test the cache */ ret.clear(); res = sr->beginResolve(target, QType(QType::NS), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Insecure); BOOST_REQUIRE_EQUAL(ret.size(), 14); BOOST_CHECK_EQUAL(queriesCount, 1); } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr, true); setDNSSECValidation(sr, DNSSECMode::ValidateAll); primeHints(); const DNSName target("."); testkeysset_t keys; /* Generate key material for "." */ auto dcke = std::shared_ptr<DNSCryptoKeyEngine>(DNSCryptoKeyEngine::make(DNSSECKeeper::ECDSA256)); dcke->create(dcke->getBits()); DNSSECPrivateKey dpk; dpk.d_flags = 256; dpk.setKey(dcke); DSRecordContent drc = makeDSFromDNSKey(target, dpk.getDNSKEY(), DNSSECKeeper::SHA256); /* Fake digest number (reserved) */ drc.d_digesttype = 0; keys[target] = std::pair<DNSSECPrivateKey, DSRecordContent>(dpk, drc); /* Set the root DS */ auto luaconfsCopy = g_luaconfs.getCopy(); luaconfsCopy.dsAnchors.clear(); luaconfsCopy.dsAnchors[g_rootdnsname].insert(drc); g_luaconfs.setState(luaconfsCopy); size_t queriesCount = 0; sr->setAsyncCallback([target,&queriesCount,keys](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { queriesCount++; if (domain == target && type == QType::NS) { setLWResult(res, 0, true, false, true); char addr[] = "a.root-servers.net."; for (char idx = 'a'; idx <= 'm'; idx++) { addr[0] = idx; addRecordToLW(res, domain, QType::NS, std::string(addr), DNSResourceRecord::ANSWER, 3600); } addRRSIG(keys, res->d_records, domain, 300); addRecordToLW(res, "a.root-servers.net.", QType::A, "198.41.0.4", DNSResourceRecord::ADDITIONAL, 3600); addRecordToLW(res, "a.root-servers.net.", QType::AAAA, "2001:503:ba3e::2:30", DNSResourceRecord::ADDITIONAL, 3600); return 1; } else if (domain == target && type == QType::DNSKEY) { setLWResult(res, 0, true, false, true); addDNSKEY(keys, domain, 300, res->d_records); addRRSIG(keys, res->d_records, domain, 300); return 1; } return 0; }); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::NS), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Insecure); /* 13 NS + 1 RRSIG */ BOOST_REQUIRE_EQUAL(ret.size(), 14); /* no supported DS so no query for DNSKEYs */ BOOST_CHECK_EQUAL(queriesCount, 1); /* again, to test the cache */ ret.clear(); res = sr->beginResolve(target, QType(QType::NS), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Insecure); BOOST_REQUIRE_EQUAL(ret.size(), 14); BOOST_CHECK_EQUAL(queriesCount, 1); } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr, true); setDNSSECValidation(sr, DNSSECMode::ValidateAll); primeHints(); const DNSName target("."); testkeysset_t keys; auto luaconfsCopy = g_luaconfs.getCopy(); luaconfsCopy.dsAnchors.clear(); generateKeyMaterial(g_rootdnsname, DNSSECKeeper::RSASHA512, DNSSECKeeper::SHA384, keys, luaconfsCopy.dsAnchors); g_luaconfs.setState(luaconfsCopy); size_t queriesCount = 0; sr->setAsyncCallback([target,&queriesCount,keys](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { queriesCount++; if (domain == target && type == QType::NS) { setLWResult(res, 0, true, false, true); char addr[] = "a.root-servers.net."; for (char idx = 'a'; idx <= 'm'; idx++) { addr[0] = idx; addRecordToLW(res, domain, QType::NS, std::string(addr), DNSResourceRecord::ANSWER, 3600); } addRRSIG(keys, res->d_records, domain, 300, true); addRecordToLW(res, "a.root-servers.net.", QType::A, "198.41.0.4", DNSResourceRecord::ADDITIONAL, 3600); addRecordToLW(res, "a.root-servers.net.", QType::AAAA, "2001:503:ba3e::2:30", DNSResourceRecord::ADDITIONAL, 3600); return 1; } else if (domain == target && type == QType::DNSKEY) { setLWResult(res, 0, true, false, true); addDNSKEY(keys, domain, 300, res->d_records); addRRSIG(keys, res->d_records, domain, 300); return 1; } return 0; }); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::NS), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Bogus); /* 13 NS + 1 RRSIG */ BOOST_REQUIRE_EQUAL(ret.size(), 14); BOOST_CHECK_EQUAL(queriesCount, 2); /* again, to test the cache */ ret.clear(); res = sr->beginResolve(target, QType(QType::NS), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Bogus); BOOST_REQUIRE_EQUAL(ret.size(), 14); BOOST_CHECK_EQUAL(queriesCount, 2); } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr, true); setDNSSECValidation(sr, DNSSECMode::ValidateAll); primeHints(); const DNSName target("."); testkeysset_t keys; auto luaconfsCopy = g_luaconfs.getCopy(); luaconfsCopy.dsAnchors.clear(); generateKeyMaterial(g_rootdnsname, DNSSECKeeper::RSASHA512, DNSSECKeeper::SHA384, keys, luaconfsCopy.dsAnchors); g_luaconfs.setState(luaconfsCopy); size_t queriesCount = 0; sr->setAsyncCallback([target,&queriesCount,keys](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { queriesCount++; if (domain == target && type == QType::NS) { setLWResult(res, 0, true, false, true); char addr[] = "a.root-servers.net."; for (char idx = 'a'; idx <= 'm'; idx++) { addr[0] = idx; addRecordToLW(res, domain, QType::NS, std::string(addr), DNSResourceRecord::ANSWER, 3600); } /* FORCE WRONG ALGO */ addRRSIG(keys, res->d_records, domain, 300, false, DNSSECKeeper::RSASHA256); addRecordToLW(res, "a.root-servers.net.", QType::A, "198.41.0.4", DNSResourceRecord::ADDITIONAL, 3600); addRecordToLW(res, "a.root-servers.net.", QType::AAAA, "2001:503:ba3e::2:30", DNSResourceRecord::ADDITIONAL, 3600); return 1; } else if (domain == target && type == QType::DNSKEY) { setLWResult(res, 0, true, false, true); addDNSKEY(keys, domain, 300, res->d_records); addRRSIG(keys, res->d_records, domain, 300); return 1; } return 0; }); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::NS), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Bogus); /* 13 NS + 1 RRSIG */ BOOST_REQUIRE_EQUAL(ret.size(), 14); BOOST_CHECK_EQUAL(queriesCount, 2); /* again, to test the cache */ ret.clear(); res = sr->beginResolve(target, QType(QType::NS), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Bogus); BOOST_REQUIRE_EQUAL(ret.size(), 14); BOOST_CHECK_EQUAL(queriesCount, 2); } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr, true); setDNSSECValidation(sr, DNSSECMode::ValidateAll); primeHints(); const DNSName target("com."); const ComboAddress targetAddr("192.0.2.42"); testkeysset_t keys; auto luaconfsCopy = g_luaconfs.getCopy(); luaconfsCopy.dsAnchors.clear(); generateKeyMaterial(g_rootdnsname, DNSSECKeeper::RSASHA512, DNSSECKeeper::SHA384, keys, luaconfsCopy.dsAnchors); generateKeyMaterial(DNSName("com."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); g_luaconfs.setState(luaconfsCopy); size_t queriesCount = 0; sr->setAsyncCallback([target,targetAddr,&queriesCount,keys](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { queriesCount++; DNSName auth = domain; if (type == QType::DS || type == QType::DNSKEY) { if (<API key>(res, domain, auth, type, keys) == 0) { return 0; } if (type == QType::DS && domain == target) { /* remove the last record, which is the DS's RRSIG */ res->d_records.pop_back(); } return 1; } if (isRootServer(ip)) { setLWResult(res, 0, false, false, true); addRecordToLW(res, "com.", QType::NS, "a.gtld-servers.com.", DNSResourceRecord::AUTHORITY, 3600); /* Include the DS but omit the RRSIG*/ addDS(DNSName("com."), 300, res->d_records, keys); addRecordToLW(res, "a.gtld-servers.com.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); return 1; } if (ip == ComboAddress("192.0.2.1:53")) { setLWResult(res, RCode::NoError, true, false, true); addRecordToLW(res, domain, QType::A, targetAddr.toString(), DNSResourceRecord::ANSWER, 3600); addRRSIG(keys, res->d_records, auth, 300); return 1; } return 0; }); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Bogus); BOOST_REQUIRE_EQUAL(ret.size(), 2); BOOST_CHECK_EQUAL(queriesCount, 4); /* again, to test the cache */ ret.clear(); res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Bogus); BOOST_REQUIRE_EQUAL(ret.size(), 2); BOOST_CHECK_EQUAL(queriesCount, 4); /* now we ask directly for the DS */ ret.clear(); res = sr->beginResolve(DNSName("com."), QType(QType::DS), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Bogus); BOOST_REQUIRE_EQUAL(ret.size(), 1); BOOST_CHECK_EQUAL(queriesCount, 4); } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr, true); setDNSSECValidation(sr, DNSSECMode::ValidateAll); primeHints(); const DNSName target("com."); testkeysset_t keys; auto luaconfsCopy = g_luaconfs.getCopy(); luaconfsCopy.dsAnchors.clear(); generateKeyMaterial(g_rootdnsname, DNSSECKeeper::RSASHA512, DNSSECKeeper::SHA384, keys, luaconfsCopy.dsAnchors); generateKeyMaterial(DNSName("com."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); g_luaconfs.setState(luaconfsCopy); size_t queriesCount = 0; sr->setAsyncCallback([target,&queriesCount,keys](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { queriesCount++; DNSName auth = domain; if (type == QType::DS || type == QType::DNSKEY) { if (<API key>(res, domain, auth, type, keys) == 0) { return 0; } if (type == QType::DS && domain == target) { /* remove the last record, which is the DS's RRSIG */ res->d_records.pop_back(); } return 1; } if (isRootServer(ip)) { setLWResult(res, 0, false, false, true); addRecordToLW(res, "com.", QType::NS, "a.gtld-servers.com.", DNSResourceRecord::AUTHORITY, 3600); /* Include the DS but omit the RRSIG*/ addDS(DNSName("com."), 300, res->d_records, keys); addRecordToLW(res, "a.gtld-servers.com.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); return 1; } return 0; }); vector<DNSRecord> ret; int res = sr->beginResolve(DNSName("com."), QType(QType::DS), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Bogus); BOOST_REQUIRE_EQUAL(ret.size(), 1); BOOST_CHECK_EQUAL(queriesCount, 1); } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr, true); setDNSSECValidation(sr, DNSSECMode::ValidateAll); primeHints(); const DNSName target("powerdns.com."); const ComboAddress targetAddr("192.0.2.42"); testkeysset_t keys; auto luaconfsCopy = g_luaconfs.getCopy(); luaconfsCopy.dsAnchors.clear(); generateKeyMaterial(g_rootdnsname, DNSSECKeeper::RSASHA512, DNSSECKeeper::SHA384, keys, luaconfsCopy.dsAnchors); generateKeyMaterial(DNSName("com."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); generateKeyMaterial(DNSName("powerdns.com."), DNSSECKeeper::ECDSA384, DNSSECKeeper::SHA384, keys); g_luaconfs.setState(luaconfsCopy); size_t queriesCount = 0; sr->setAsyncCallback([target,targetAddr,&queriesCount,keys](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { queriesCount++; DNSName auth = domain; if (domain == target) { auth = DNSName("powerdns.com."); } if (type == QType::DS || type == QType::DNSKEY) { return <API key>(res, domain, auth, type, keys); } if (isRootServer(ip)) { setLWResult(res, 0, false, false, true); addRecordToLW(res, "com.", QType::NS, "a.gtld-servers.com.", DNSResourceRecord::AUTHORITY, 3600); addDS(DNSName("com."), 300, res->d_records, keys); addRRSIG(keys, res->d_records, DNSName("."), 300); addRecordToLW(res, "a.gtld-servers.com.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); return 1; } if (ip == ComboAddress("192.0.2.1:53")) { if (domain == DNSName("com.")) { setLWResult(res, 0, true, false, true); addRecordToLW(res, domain, QType::NS, "a.gtld-servers.com."); addRRSIG(keys, res->d_records, domain, 300); addRecordToLW(res, "a.gtld-servers.com.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); addRRSIG(keys, res->d_records, domain, 300); } else { setLWResult(res, 0, false, false, true); addRecordToLW(res, auth, QType::NS, "ns1.powerdns.com.", DNSResourceRecord::AUTHORITY, 3600); addDS(auth, 300, res->d_records, keys); addRRSIG(keys, res->d_records, DNSName("com."), 300); addRecordToLW(res, "ns1.powerdns.com.", QType::A, "192.0.2.2", DNSResourceRecord::ADDITIONAL, 3600); } return 1; } if (ip == ComboAddress("192.0.2.2:53")) { if (type == QType::NS) { setLWResult(res, 0, true, false, true); addRecordToLW(res, domain, QType::NS, "ns1.powerdns.com."); addRRSIG(keys, res->d_records, auth, 300); addRecordToLW(res, "ns1.powerdns.com.", QType::A, "192.0.2.2", DNSResourceRecord::ADDITIONAL, 3600); addRRSIG(keys, res->d_records, auth, 300); } else { setLWResult(res, RCode::NoError, true, false, true); addRecordToLW(res, domain, QType::A, targetAddr.toString(), DNSResourceRecord::ANSWER, 3600); addRRSIG(keys, res->d_records, auth, 300); } return 1; } return 0; }); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Secure); BOOST_REQUIRE_EQUAL(ret.size(), 2); BOOST_CHECK_EQUAL(queriesCount, 8); /* again, to test the cache */ ret.clear(); res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Secure); BOOST_REQUIRE_EQUAL(ret.size(), 2); BOOST_CHECK_EQUAL(queriesCount, 8); } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr, true); setDNSSECValidation(sr, DNSSECMode::ValidateAll); primeHints(); const DNSName target("powerdns.com."); const ComboAddress targetAddr("192.0.2.42"); testkeysset_t keys; auto luaconfsCopy = g_luaconfs.getCopy(); luaconfsCopy.dsAnchors.clear(); generateKeyMaterial(g_rootdnsname, DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys, luaconfsCopy.dsAnchors); generateKeyMaterial(DNSName("com."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); generateKeyMaterial(DNSName("powerdns.com."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); g_luaconfs.setState(luaconfsCopy); size_t queriesCount = 0; sr->setAsyncCallback([target,targetAddr,&queriesCount,keys](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { queriesCount++; DNSName auth = domain; if (domain == target) { auth = DNSName("powerdns.com."); } if (type == QType::DS || type == QType::DNSKEY) { return <API key>(res, domain, auth, type, keys); } if (isRootServer(ip)) { setLWResult(res, 0, false, false, true); addRecordToLW(res, "com.", QType::NS, "a.gtld-servers.com.", DNSResourceRecord::AUTHORITY, 3600); addDS(DNSName("com."), 300, res->d_records, keys); addRRSIG(keys, res->d_records, DNSName("."), 300); addRecordToLW(res, "a.gtld-servers.com.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); return 1; } if (ip == ComboAddress("192.0.2.1:53")) { if (domain == DNSName("com.")) { setLWResult(res, 0, true, false, true); addRecordToLW(res, domain, QType::NS, "a.gtld-servers.com."); addRRSIG(keys, res->d_records, domain, 300); addRecordToLW(res, "a.gtld-servers.com.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); addRRSIG(keys, res->d_records, domain, 300); } else { setLWResult(res, 0, false, false, true); addRecordToLW(res, auth, QType::NS, "ns1.powerdns.com.", DNSResourceRecord::AUTHORITY, 3600); addDS(auth, 300, res->d_records, keys); addRRSIG(keys, res->d_records, DNSName("com."), 300); addRecordToLW(res, "ns1.powerdns.com.", QType::A, "192.0.2.2", DNSResourceRecord::ADDITIONAL, 3600); } return 1; } if (ip == ComboAddress("192.0.2.2:53")) { if (type == QType::NS) { setLWResult(res, 0, true, false, true); addRecordToLW(res, domain, QType::NS, "ns1.powerdns.com."); addRRSIG(keys, res->d_records, auth, 300); addRecordToLW(res, "ns1.powerdns.com.", QType::A, "192.0.2.2", DNSResourceRecord::ADDITIONAL, 3600); addRRSIG(keys, res->d_records, auth, 300); } else { setLWResult(res, RCode::NoError, true, false, true); addRecordToLW(res, domain, QType::A, targetAddr.toString(), DNSResourceRecord::ANSWER, 3600); addRRSIG(keys, res->d_records, auth, 300); } return 1; } return 0; }); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Secure); BOOST_REQUIRE_EQUAL(ret.size(), 2); BOOST_CHECK_EQUAL(queriesCount, 8); /* again, to test the cache */ ret.clear(); res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Secure); BOOST_REQUIRE_EQUAL(ret.size(), 2); BOOST_CHECK_EQUAL(queriesCount, 8); /* this time we ask for the NS that should be in the cache, to check the validation status */ ret.clear(); res = sr->beginResolve(target, QType(QType::NS), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Secure); BOOST_REQUIRE_EQUAL(ret.size(), 2); BOOST_CHECK_EQUAL(queriesCount, 9); } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr, true); setDNSSECValidation(sr, DNSSECMode::ValidateAll); primeHints(); const DNSName target("powerdns.com."); const ComboAddress targetAddr("192.0.2.42"); testkeysset_t keys; auto luaconfsCopy = g_luaconfs.getCopy(); luaconfsCopy.dsAnchors.clear(); generateKeyMaterial(g_rootdnsname, DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys, luaconfsCopy.dsAnchors); generateKeyMaterial(DNSName("com."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); g_luaconfs.setState(luaconfsCopy); size_t queriesCount = 0; sr->setAsyncCallback([target,targetAddr,&queriesCount,keys](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { queriesCount++; DNSName auth = domain; if (domain == target) { auth = DNSName("powerdns.com."); } if (type == QType::DS || type == QType::DNSKEY) { return <API key>(res, domain, auth, type, keys); } if (isRootServer(ip)) { setLWResult(res, 0, false, false, true); addRecordToLW(res, "com.", QType::NS, "a.gtld-servers.com.", DNSResourceRecord::AUTHORITY, 3600); addDS(DNSName("com."), 300, res->d_records, keys); addRRSIG(keys, res->d_records, DNSName("."), 300); addRecordToLW(res, "a.gtld-servers.com.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); return 1; } if (ip == ComboAddress("192.0.2.1:53")) { if (domain == DNSName("com.")) { setLWResult(res, 0, true, false, true); addRecordToLW(res, domain, QType::NS, "a.gtld-servers.com."); addRRSIG(keys, res->d_records, domain, 300); addRecordToLW(res, "a.gtld-servers.com.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); addRRSIG(keys, res->d_records, domain, 300); } else { setLWResult(res, 0, false, false, true); addRecordToLW(res, auth, QType::NS, "ns1.powerdns.com.", DNSResourceRecord::AUTHORITY, 3600); /* no DS */ addNSECRecordToLW(domain, DNSName("z.powerdns.com."), { QType::NS }, 600, res->d_records); addRRSIG(keys, res->d_records, DNSName("com."), 300); addRecordToLW(res, "ns1.powerdns.com.", QType::A, "192.0.2.2", DNSResourceRecord::ADDITIONAL, 3600); } return 1; } if (ip == ComboAddress("192.0.2.2:53")) { if (type == QType::NS) { setLWResult(res, 0, true, false, true); addRecordToLW(res, domain, QType::NS, "ns1.powerdns.com."); addRecordToLW(res, "ns1.powerdns.com.", QType::A, "192.0.2.2", DNSResourceRecord::ADDITIONAL, 3600); } else { setLWResult(res, RCode::NoError, true, false, true); addRecordToLW(res, domain, QType::A, targetAddr.toString(), DNSResourceRecord::ANSWER, 3600); } return 1; } return 0; }); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Insecure); BOOST_REQUIRE_EQUAL(ret.size(), 1); BOOST_CHECK_EQUAL(queriesCount, 7); /* again, to test the cache */ ret.clear(); res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Insecure); BOOST_REQUIRE_EQUAL(ret.size(), 1); BOOST_CHECK_EQUAL(queriesCount, 7); /* this time we ask for the NS that should be in the cache, to check the validation status */ ret.clear(); res = sr->beginResolve(target, QType(QType::NS), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Insecure); BOOST_REQUIRE_EQUAL(ret.size(), 1); BOOST_CHECK_EQUAL(queriesCount, 8); } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr, true); setDNSSECValidation(sr, DNSSECMode::ValidateAll); primeHints(); const DNSName target("powerdns.com."); const ComboAddress targetAddr("192.0.2.42"); testkeysset_t keys; auto luaconfsCopy = g_luaconfs.getCopy(); luaconfsCopy.dsAnchors.clear(); generateKeyMaterial(g_rootdnsname, DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys, luaconfsCopy.dsAnchors); generateKeyMaterial(DNSName("com."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); generateKeyMaterial(DNSName("powerdns.com."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); /* Add a NTA for "powerdns.com" */ luaconfsCopy.negAnchors[target] = "NTA for PowerDNS.com"; g_luaconfs.setState(luaconfsCopy); size_t queriesCount = 0; sr->setAsyncCallback([target,targetAddr,&queriesCount,keys](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { queriesCount++; DNSName auth = domain; if (domain == target) { auth = DNSName("powerdns.com."); } if (type == QType::DS || type == QType::DNSKEY) { return <API key>(res, domain, auth, type, keys); } if (isRootServer(ip)) { setLWResult(res, 0, false, false, true); addRecordToLW(res, "com.", QType::NS, "a.gtld-servers.com.", DNSResourceRecord::AUTHORITY, 3600); addDS(DNSName("com."), 300, res->d_records, keys); addRRSIG(keys, res->d_records, DNSName("."), 300); addRecordToLW(res, "a.gtld-servers.com.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); return 1; } if (ip == ComboAddress("192.0.2.1:53")) { if (domain == DNSName("com.")) { setLWResult(res, 0, true, false, true); addRecordToLW(res, domain, QType::NS, "a.gtld-servers.com."); addRRSIG(keys, res->d_records, domain, 300); addRecordToLW(res, "a.gtld-servers.com.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); addRRSIG(keys, res->d_records, domain, 300); } else { setLWResult(res, 0, false, false, true); addRecordToLW(res, auth, QType::NS, "ns1.powerdns.com.", DNSResourceRecord::AUTHORITY, 3600); addDS(auth, 300, res->d_records, keys); addRRSIG(keys, res->d_records, DNSName("com."), 300); addRecordToLW(res, "ns1.powerdns.com.", QType::A, "192.0.2.2", DNSResourceRecord::ADDITIONAL, 3600); } return 1; } if (ip == ComboAddress("192.0.2.2:53")) { if (type == QType::NS) { setLWResult(res, 0, true, false, true); addRecordToLW(res, domain, QType::NS, "ns1.powerdns.com."); addRRSIG(keys, res->d_records, auth, 300); addRecordToLW(res, "ns1.powerdns.com.", QType::A, "192.0.2.2", DNSResourceRecord::ADDITIONAL, 3600); addRRSIG(keys, res->d_records, auth, 300); } else { setLWResult(res, RCode::NoError, true, false, true); addRecordToLW(res, domain, QType::A, targetAddr.toString(), DNSResourceRecord::ANSWER, 3600); addRRSIG(keys, res->d_records, auth, 300); } return 1; } return 0; }); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); /* Should be insecure because of the NTA */ BOOST_CHECK_EQUAL(sr->getValidationState(), Insecure); BOOST_REQUIRE_EQUAL(ret.size(), 2); BOOST_CHECK_EQUAL(queriesCount, 5); /* again, to test the cache */ ret.clear(); res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); /* Should be insecure because of the NTA */ BOOST_CHECK_EQUAL(sr->getValidationState(), Insecure); BOOST_REQUIRE_EQUAL(ret.size(), 2); BOOST_CHECK_EQUAL(queriesCount, 5); } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr, true); setDNSSECValidation(sr, DNSSECMode::ValidateAll); primeHints(); const DNSName target("powerdns.com."); const ComboAddress targetAddr("192.0.2.42"); testkeysset_t keys; auto luaconfsCopy = g_luaconfs.getCopy(); luaconfsCopy.dsAnchors.clear(); generateKeyMaterial(g_rootdnsname, DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys, luaconfsCopy.dsAnchors); generateKeyMaterial(DNSName("com."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); generateKeyMaterial(DNSName("powerdns.com."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); /* Add a NTA for "powerdns.com" */ luaconfsCopy.negAnchors[target] = "NTA for PowerDNS.com"; g_luaconfs.setState(luaconfsCopy); size_t queriesCount = 0; sr->setAsyncCallback([target,targetAddr,&queriesCount,keys](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { queriesCount++; if (type == QType::DS || type == QType::DNSKEY) { setLWResult(res, 0, false, false, true); addRecordToLW(res, domain, QType::SOA, "pdns-public-ns1.powerdns.com. pieter\\.lexis.powerdns.com. 2017032301 10800 3600 604800 3600", DNSResourceRecord::AUTHORITY, 3600); return 1; } else { if (isRootServer(ip)) { setLWResult(res, 0, false, false, true); addRecordToLW(res, "com.", QType::NS, "a.gtld-servers.com.", DNSResourceRecord::AUTHORITY, 3600); addRecordToLW(res, "a.gtld-servers.com.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); return 1; } else if (ip == ComboAddress("192.0.2.1:53")) { if (domain == DNSName("com.")) { setLWResult(res, 0, true, false, true); addRecordToLW(res, domain, QType::NS, "a.gtld-servers.com."); addRecordToLW(res, "a.gtld-servers.com.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); } else { setLWResult(res, 0, false, false, true); addRecordToLW(res, domain, QType::NS, "ns1.powerdns.com.", DNSResourceRecord::AUTHORITY, 3600); addRecordToLW(res, "ns1.powerdns.com.", QType::A, "192.0.2.2", DNSResourceRecord::ADDITIONAL, 3600); } return 1; } else if (ip == ComboAddress("192.0.2.2:53")) { if (type == QType::NS) { setLWResult(res, 0, true, false, true); addRecordToLW(res, domain, QType::NS, "ns1.powerdns.com."); addRecordToLW(res, "ns1.powerdns.com.", QType::A, "192.0.2.2", DNSResourceRecord::ADDITIONAL, 3600); } else { setLWResult(res, RCode::NoError, true, false, true); addRecordToLW(res, domain, QType::A, targetAddr.toString(), DNSResourceRecord::ANSWER, 3600); } return 1; } } return 0; }); /* There is TA for root but no DS/DNSKEY/RRSIG, should be Bogus, but.. */ vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); /* Should be insecure because of the NTA */ BOOST_CHECK_EQUAL(sr->getValidationState(), Insecure); BOOST_REQUIRE_EQUAL(ret.size(), 1); BOOST_CHECK_EQUAL(queriesCount, 4); /* again, to test the cache */ ret.clear(); res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Insecure); BOOST_REQUIRE_EQUAL(ret.size(), 1); BOOST_CHECK_EQUAL(queriesCount, 4); } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr, true); setDNSSECValidation(sr, DNSSECMode::ValidateAll); primeHints(); const DNSName target("powerdns.com."); testkeysset_t keys; auto luaconfsCopy = g_luaconfs.getCopy(); luaconfsCopy.dsAnchors.clear(); generateKeyMaterial(g_rootdnsname, DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys, luaconfsCopy.dsAnchors); generateKeyMaterial(DNSName("com."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); generateKeyMaterial(DNSName("powerdns.com."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); g_luaconfs.setState(luaconfsCopy); size_t queriesCount = 0; sr->setAsyncCallback([target,&queriesCount,keys](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { queriesCount++; if (type == QType::DS || type == QType::DNSKEY) { return <API key>(res, domain, domain, type, keys); } else { if (isRootServer(ip)) { setLWResult(res, 0, false, false, true); addRecordToLW(res, "com.", QType::NS, "a.gtld-servers.com.", DNSResourceRecord::AUTHORITY, 3600); addDS(DNSName("com."), 300, res->d_records, keys); addRRSIG(keys, res->d_records, DNSName("."), 300); addRecordToLW(res, "a.gtld-servers.com.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); return 1; } else if (ip == ComboAddress("192.0.2.1:53")) { if (domain == DNSName("com.")) { setLWResult(res, 0, true, false, true); addRecordToLW(res, domain, QType::NS, "a.gtld-servers.com."); addRRSIG(keys, res->d_records, domain, 300); addRecordToLW(res, "a.gtld-servers.com.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); addRRSIG(keys, res->d_records, domain, 300); } else { setLWResult(res, 0, false, false, true); addRecordToLW(res, domain, QType::NS, "ns1.powerdns.com.", DNSResourceRecord::AUTHORITY, 3600); addDS(domain, 300, res->d_records, keys); addRRSIG(keys, res->d_records, DNSName("com."), 300); addRecordToLW(res, "ns1.powerdns.com.", QType::A, "192.0.2.2", DNSResourceRecord::ADDITIONAL, 3600); } return 1; } else if (ip == ComboAddress("192.0.2.2:53")) { if (type == QType::NS) { setLWResult(res, 0, true, false, true); addRecordToLW(res, domain, QType::NS, "ns1.powerdns.com."); addRRSIG(keys, res->d_records, DNSName("powerdns.com"), 300); addRecordToLW(res, "ns1.powerdns.com.", QType::A, "192.0.2.2", DNSResourceRecord::ADDITIONAL, 3600); addRRSIG(keys, res->d_records, DNSName("powerdns.com"), 300); } else { setLWResult(res, 0, true, false, true); addRecordToLW(res, domain, QType::SOA, "pdns-public-ns1.powerdns.com. pieter\\.lexis.powerdns.com. 2017032301 10800 3600 604800 3600", DNSResourceRecord::AUTHORITY, 3600); addRRSIG(keys, res->d_records, domain, 300); addNSECRecordToLW(domain, DNSName("z.powerdns.com."), { QType::NS, QType::DNSKEY }, 600, res->d_records); addRRSIG(keys, res->d_records, domain, 300); } return 1; } } return 0; }); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Secure); BOOST_REQUIRE_EQUAL(ret.size(), 4); BOOST_CHECK_EQUAL(queriesCount, 8); /* again, to test the cache */ ret.clear(); res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Secure); BOOST_REQUIRE_EQUAL(ret.size(), 4); BOOST_CHECK_EQUAL(queriesCount, 8); } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr, true); setDNSSECValidation(sr, DNSSECMode::ValidateAll); primeHints(); const DNSName target("nx.powerdns.com."); testkeysset_t keys; auto luaconfsCopy = g_luaconfs.getCopy(); luaconfsCopy.dsAnchors.clear(); generateKeyMaterial(g_rootdnsname, DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys, luaconfsCopy.dsAnchors); generateKeyMaterial(DNSName("com."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); generateKeyMaterial(DNSName("powerdns.com."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); g_luaconfs.setState(luaconfsCopy); size_t queriesCount = 0; sr->setAsyncCallback([target,&queriesCount,keys](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { queriesCount++; DNSName auth = domain; if (domain == target) { auth = DNSName("powerdns.com."); } if (type == QType::DS || type == QType::DNSKEY) { if (type == QType::DS && domain == target) { setLWResult(res, RCode::NXDomain, true, false, true); addRecordToLW(res, DNSName("powerdns.com."), QType::SOA, "pdns-public-ns1.powerdns.com. pieter\\.lexis.powerdns.com. 2017032301 10800 3600 604800 3600", DNSResourceRecord::AUTHORITY, 3600); addRRSIG(keys, res->d_records, auth, 300); addNSECRecordToLW(DNSName("nw.powerdns.com."), DNSName("ny.powerdns.com."), { QType::RRSIG, QType::NSEC }, 600, res->d_records); addRRSIG(keys, res->d_records, auth, 300); return 1; } else { return <API key>(res, domain, auth, type, keys); } } else { if (isRootServer(ip)) { setLWResult(res, 0, false, false, true); addRecordToLW(res, "com.", QType::NS, "a.gtld-servers.com.", DNSResourceRecord::AUTHORITY, 3600); addDS(DNSName("com."), 300, res->d_records, keys); addRRSIG(keys, res->d_records, DNSName("."), 300); addRecordToLW(res, "a.gtld-servers.com.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); return 1; } else if (ip == ComboAddress("192.0.2.1:53")) { if (domain == DNSName("com.")) { setLWResult(res, 0, true, false, true); addRecordToLW(res, domain, QType::NS, "a.gtld-servers.com."); addRRSIG(keys, res->d_records, domain, 300); addRecordToLW(res, "a.gtld-servers.com.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); addRRSIG(keys, res->d_records, domain, 300); } else { setLWResult(res, 0, false, false, true); addRecordToLW(res, auth, QType::NS, "ns1.powerdns.com.", DNSResourceRecord::AUTHORITY, 3600); addDS(auth, 300, res->d_records, keys); addRRSIG(keys, res->d_records, DNSName("com."), 300); addRecordToLW(res, "ns1.powerdns.com.", QType::A, "192.0.2.2", DNSResourceRecord::ADDITIONAL, 3600); } return 1; } else if (ip == ComboAddress("192.0.2.2:53")) { if (type == QType::NS) { setLWResult(res, 0, true, false, true); if (domain == DNSName("powerdns.com.")) { addRecordToLW(res, domain, QType::NS, "ns1.powerdns.com."); addRRSIG(keys, res->d_records, DNSName("powerdns.com"), 300); addRecordToLW(res, "ns1.powerdns.com.", QType::A, "192.0.2.2", DNSResourceRecord::ADDITIONAL, 3600); addRRSIG(keys, res->d_records, DNSName("powerdns.com"), 300); } else { addRecordToLW(res, domain, QType::SOA, "pdns-public-ns1.powerdns.com. pieter\\.lexis.powerdns.com. 2017032301 10800 3600 604800 3600", DNSResourceRecord::AUTHORITY, 3600); addRRSIG(keys, res->d_records, DNSName("powerdns.com"), 300); addNSECRecordToLW(DNSName("nx.powerdns.com."), DNSName("nz.powerdns.com."), { QType::A, QType::NSEC, QType::RRSIG }, 600, res->d_records); addRRSIG(keys, res->d_records, DNSName("powerdns.com"), 300); } } else { setLWResult(res, RCode::NXDomain, true, false, true); addRecordToLW(res, DNSName("powerdns.com."), QType::SOA, "pdns-public-ns1.powerdns.com. pieter\\.lexis.powerdns.com. 2017032301 10800 3600 604800 3600", DNSResourceRecord::AUTHORITY, 3600); addRRSIG(keys, res->d_records, auth, 300); addNSECRecordToLW(DNSName("nw.powerdns.com."), DNSName("ny.powerdns.com."), { QType::RRSIG, QType::NSEC }, 600, res->d_records); addRRSIG(keys, res->d_records, auth, 300); /* add wildcard denial */ addNSECRecordToLW(DNSName("powerdns.com."), DNSName("a.powerdns.com."), { QType::RRSIG, QType::NSEC }, 600, res->d_records); addRRSIG(keys, res->d_records, auth, 300); } return 1; } } return 0; }); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NXDomain); BOOST_CHECK_EQUAL(sr->getValidationState(), Secure); BOOST_REQUIRE_EQUAL(ret.size(), 6); BOOST_CHECK_EQUAL(queriesCount, 9); /* again, to test the cache */ ret.clear(); res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NXDomain); BOOST_CHECK_EQUAL(sr->getValidationState(), Secure); BOOST_REQUIRE_EQUAL(ret.size(), 6); BOOST_CHECK_EQUAL(queriesCount, 9); } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr, true); setDNSSECValidation(sr, DNSSECMode::ValidateAll); primeHints(); const DNSName target("www.powerdns.com."); testkeysset_t keys; auto luaconfsCopy = g_luaconfs.getCopy(); luaconfsCopy.dsAnchors.clear(); generateKeyMaterial(g_rootdnsname, DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys, luaconfsCopy.dsAnchors); generateKeyMaterial(DNSName("com."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); generateKeyMaterial(DNSName("powerdns.com."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); g_luaconfs.setState(luaconfsCopy); size_t queriesCount = 0; sr->setAsyncCallback([target,&queriesCount,keys](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { queriesCount++; if (type == QType::DS || type == QType::DNSKEY) { if (type == QType::DS && domain == target) { setLWResult(res, RCode::NoError, true, false, true); addRecordToLW(res, DNSName("powerdns.com."), QType::SOA, "pdns-public-ns1.powerdns.com. pieter\\.lexis.powerdns.com. 2017032301 10800 3600 604800 3600", DNSResourceRecord::AUTHORITY, 3600); addRRSIG(keys, res->d_records, DNSName("powerdns.com."), 300); addNSECRecordToLW(DNSName("www.powerdns.com."), DNSName("wwz.powerdns.com."), { QType::A, QType::NSEC, QType::RRSIG }, 600, res->d_records); addRRSIG(keys, res->d_records, DNSName("powerdns.com"), 300); return 1; } else { return <API key>(res, domain, domain, type, keys); } } else { if (isRootServer(ip)) { setLWResult(res, 0, false, false, true); addRecordToLW(res, "com.", QType::NS, "a.gtld-servers.com.", DNSResourceRecord::AUTHORITY, 3600); addDS(DNSName("com."), 300, res->d_records, keys); addRRSIG(keys, res->d_records, DNSName("."), 300); addRecordToLW(res, "a.gtld-servers.com.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); return 1; } else if (ip == ComboAddress("192.0.2.1:53")) { if (domain == DNSName("com.")) { setLWResult(res, 0, true, false, true); addRecordToLW(res, domain, QType::NS, "a.gtld-servers.com."); addRRSIG(keys, res->d_records, domain, 300); addRecordToLW(res, "a.gtld-servers.com.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); addRRSIG(keys, res->d_records, domain, 300); } else { setLWResult(res, 0, false, false, true); addRecordToLW(res, "powerdns.com.", QType::NS, "ns1.powerdns.com.", DNSResourceRecord::AUTHORITY, 3600); addDS(DNSName("powerdns.com."), 300, res->d_records, keys); addRRSIG(keys, res->d_records, DNSName("com."), 300); addRecordToLW(res, "ns1.powerdns.com.", QType::A, "192.0.2.2", DNSResourceRecord::ADDITIONAL, 3600); } return 1; } else if (ip == ComboAddress("192.0.2.2:53")) { setLWResult(res, 0, true, false, true); if (type == QType::NS) { if (domain == DNSName("powerdns.com.")) { addRecordToLW(res, domain, QType::NS, "ns1.powerdns.com."); addRRSIG(keys, res->d_records, DNSName("powerdns.com"), 300); addRecordToLW(res, "ns1.powerdns.com.", QType::A, "192.0.2.2", DNSResourceRecord::ADDITIONAL, 3600); addRRSIG(keys, res->d_records, DNSName("powerdns.com"), 300); } else { addRecordToLW(res, domain, QType::SOA, "pdns-public-ns1.powerdns.com. pieter\\.lexis.powerdns.com. 2017032301 10800 3600 604800 3600", DNSResourceRecord::AUTHORITY, 3600); addRRSIG(keys, res->d_records, DNSName("powerdns.com"), 300); addNSECRecordToLW(DNSName("www.powerdns.com."), DNSName("wwz.powerdns.com."), { QType::A, QType::NSEC, QType::RRSIG }, 600, res->d_records); addRRSIG(keys, res->d_records, DNSName("powerdns.com"), 300); } } else { addRecordToLW(res, domain, QType::A, "192.0.2.42"); addRRSIG(keys, res->d_records, DNSName("powerdns.com"), 300, false, boost::none, DNSName("*.powerdns.com")); /* we need to add the proof that this name does not exist, so the wildcard may apply */ addNSECRecordToLW(DNSName("a.powerdns.com."), DNSName("wwz.powerdns.com."), { QType::A, QType::NSEC, QType::RRSIG }, 600, res->d_records); addRRSIG(keys, res->d_records, DNSName("powerdns.com"), 300); } return 1; } } return 0; }); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Secure); BOOST_REQUIRE_EQUAL(ret.size(), 4); BOOST_CHECK_EQUAL(queriesCount, 9); /* again, to test the cache */ ret.clear(); res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Secure); BOOST_REQUIRE_EQUAL(ret.size(), 4); BOOST_CHECK_EQUAL(queriesCount, 9); } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr, true); setDNSSECValidation(sr, DNSSECMode::ValidateAll); primeHints(); const DNSName target("www.com."); testkeysset_t keys; auto luaconfsCopy = g_luaconfs.getCopy(); luaconfsCopy.dsAnchors.clear(); generateKeyMaterial(g_rootdnsname, DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys, luaconfsCopy.dsAnchors); generateKeyMaterial(DNSName("com."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); g_luaconfs.setState(luaconfsCopy); size_t queriesCount = 0; sr->setAsyncCallback([target,&queriesCount,keys](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { queriesCount++; if (type == QType::DS || type == QType::DNSKEY) { if (type == QType::DS && domain == target) { DNSName auth("com."); setLWResult(res, 0, true, false, true); addRecordToLW(res, auth, QType::SOA, "foo. bar. 2017032800 1800 900 604800 86400", DNSResourceRecord::AUTHORITY, 86400); addRRSIG(keys, res->d_records, auth, 300); /* add a NSEC denying the DS AND the existence of a cut (no NS) */ addNSECRecordToLW(domain, DNSName("z") + domain, { QType::NSEC }, 600, res->d_records); addRRSIG(keys, res->d_records, auth, 300); return 1; } return <API key>(res, domain, domain, type, keys); } else { if (isRootServer(ip)) { setLWResult(res, 0, false, false, true); addRecordToLW(res, "com.", QType::NS, "a.gtld-servers.com.", DNSResourceRecord::AUTHORITY, 3600); addDS(DNSName("com."), 300, res->d_records, keys); addRRSIG(keys, res->d_records, DNSName("."), 300); addRecordToLW(res, "a.gtld-servers.com.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); return 1; } else if (ip == ComboAddress("192.0.2.1:53")) { setLWResult(res, 0, true, false, true); /* no data */ addRecordToLW(res, DNSName("com."), QType::SOA, "com. com. 2017032301 10800 3600 604800 3600", DNSResourceRecord::AUTHORITY, 3600); addRRSIG(keys, res->d_records, DNSName("com."), 300); /* no record for this name */ addNSECRecordToLW(DNSName("wwv.com."), DNSName("wwx.com."), { QType::NSEC, QType::RRSIG }, 600, res->d_records); addRRSIG(keys, res->d_records, DNSName("com."), 300); /* a wildcard matches but has no record for this type */ addNSECRecordToLW(DNSName("*.com."), DNSName("com."), { QType::AAAA, QType::NSEC, QType::RRSIG }, 600, res->d_records); addRRSIG(keys, res->d_records, DNSName("com"), 300, false, boost::none, DNSName("*.com")); return 1; } } return 0; }); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Secure); BOOST_REQUIRE_EQUAL(ret.size(), 6); BOOST_CHECK_EQUAL(queriesCount, 6); /* again, to test the cache */ ret.clear(); res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Secure); BOOST_REQUIRE_EQUAL(ret.size(), 6); BOOST_CHECK_EQUAL(queriesCount, 6); } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr, true); setDNSSECValidation(sr, DNSSECMode::ValidateAll); primeHints(); const DNSName target("www.com."); testkeysset_t keys; auto luaconfsCopy = g_luaconfs.getCopy(); luaconfsCopy.dsAnchors.clear(); generateKeyMaterial(g_rootdnsname, DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys, luaconfsCopy.dsAnchors); generateKeyMaterial(DNSName("com."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); g_luaconfs.setState(luaconfsCopy); size_t queriesCount = 0; sr->setAsyncCallback([target,&queriesCount,keys](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { queriesCount++; if (type == QType::DS || type == QType::DNSKEY) { if (type == QType::DS && domain == target) { DNSName auth("com."); setLWResult(res, 0, true, false, true); addRecordToLW(res, auth, QType::SOA, "foo. bar. 2017032800 1800 900 604800 86400", DNSResourceRecord::AUTHORITY, 86400); addRRSIG(keys, res->d_records, auth, 300); /* add a NSEC3 denying the DS AND the existence of a cut (no NS) */ /* first the closest encloser */ <API key>(DNSName("com."), auth, "whatever", { QType::A, QType::TXT, QType::RRSIG, QType::NSEC }, 600, res->d_records); addRRSIG(keys, res->d_records, auth, 300); /* then the next closer */ <API key>(domain, DNSName("com."), { QType::RRSIG, QType::NSEC }, 600, res->d_records); addRRSIG(keys, res->d_records, auth, 300); /* a wildcard matches but has no record for this type */ <API key>(DNSName("*.com."), DNSName("com."), "whatever", { QType::AAAA, QType::NSEC, QType::RRSIG }, 600, res->d_records); addRRSIG(keys, res->d_records, DNSName("com"), 300, false, boost::none, DNSName("*.com")); return 1; } return <API key>(res, domain, domain, type, keys); } else { if (isRootServer(ip)) { setLWResult(res, 0, false, false, true); addRecordToLW(res, "com.", QType::NS, "a.gtld-servers.com.", DNSResourceRecord::AUTHORITY, 3600); addDS(DNSName("com."), 300, res->d_records, keys); addRRSIG(keys, res->d_records, DNSName("."), 300); addRecordToLW(res, "a.gtld-servers.com.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); return 1; } else if (ip == ComboAddress("192.0.2.1:53")) { setLWResult(res, 0, true, false, true); /* no data */ addRecordToLW(res, DNSName("com."), QType::SOA, "com. com. 2017032301 10800 3600 604800 3600", DNSResourceRecord::AUTHORITY, 3600); addRRSIG(keys, res->d_records, DNSName("com."), 300); /* no record for this name */ /* first the closest encloser */ <API key>(DNSName("com."), DNSName("com."), "whatever", { QType::A, QType::TXT, QType::RRSIG, QType::NSEC }, 600, res->d_records); addRRSIG(keys, res->d_records, DNSName("com."), 300); /* then the next closer */ <API key>(domain, DNSName("com."), { QType::RRSIG, QType::NSEC }, 600, res->d_records); addRRSIG(keys, res->d_records, DNSName("com."), 300); /* a wildcard matches but has no record for this type */ <API key>(DNSName("*.com."), DNSName("com."), "whatever", { QType::AAAA, QType::NSEC, QType::RRSIG }, 600, res->d_records); addRRSIG(keys, res->d_records, DNSName("com"), 300, false, boost::none, DNSName("*.com")); return 1; } } return 0; }); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Secure); BOOST_REQUIRE_EQUAL(ret.size(), 8); BOOST_CHECK_EQUAL(queriesCount, 6); /* again, to test the cache */ ret.clear(); res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Secure); BOOST_REQUIRE_EQUAL(ret.size(), 8); BOOST_CHECK_EQUAL(queriesCount, 6); } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr, true); setDNSSECValidation(sr, DNSSECMode::ValidateAll); primeHints(); const DNSName target("www.com."); testkeysset_t keys; auto luaconfsCopy = g_luaconfs.getCopy(); luaconfsCopy.dsAnchors.clear(); generateKeyMaterial(g_rootdnsname, DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys, luaconfsCopy.dsAnchors); generateKeyMaterial(DNSName("com."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); g_luaconfs.setState(luaconfsCopy); size_t queriesCount = 0; sr->setAsyncCallback([target,&queriesCount,keys](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { queriesCount++; if (type == QType::DS || type == QType::DNSKEY) { if (type == QType::DS && domain == target) { DNSName auth("com."); setLWResult(res, 0, true, false, true); addRecordToLW(res, auth, QType::SOA, "foo. bar. 2017032800 1800 900 604800 86400", DNSResourceRecord::AUTHORITY, 86400); addRRSIG(keys, res->d_records, auth, 300); /* add a NSEC3 denying the DS AND the existence of a cut (no NS) */ /* first the closest encloser */ <API key>(DNSName("com."), auth, "whatever", { QType::A, QType::TXT, QType::RRSIG, QType::NSEC }, 600, res->d_records, <API key> + 100); addRRSIG(keys, res->d_records, auth, 300); /* then the next closer */ <API key>(domain, DNSName("com."), { QType::RRSIG, QType::NSEC }, 600, res->d_records, <API key> + 100); addRRSIG(keys, res->d_records, auth, 300); /* a wildcard matches but has no record for this type */ <API key>(DNSName("*.com."), DNSName("com."), "whatever", { QType::AAAA, QType::NSEC, QType::RRSIG }, 600, res->d_records, <API key> + 100); addRRSIG(keys, res->d_records, DNSName("com"), 300, false, boost::none, DNSName("*.com")); return 1; } return <API key>(res, domain, domain, type, keys); } else { if (isRootServer(ip)) { setLWResult(res, 0, false, false, true); addRecordToLW(res, "com.", QType::NS, "a.gtld-servers.com.", DNSResourceRecord::AUTHORITY, 3600); addDS(DNSName("com."), 300, res->d_records, keys); addRRSIG(keys, res->d_records, DNSName("."), 300); addRecordToLW(res, "a.gtld-servers.com.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); return 1; } else if (ip == ComboAddress("192.0.2.1:53")) { setLWResult(res, 0, true, false, true); /* no data */ addRecordToLW(res, DNSName("com."), QType::SOA, "com. com. 2017032301 10800 3600 604800 3600", DNSResourceRecord::AUTHORITY, 3600); addRRSIG(keys, res->d_records, DNSName("com."), 300); /* no record for this name */ /* first the closest encloser */ <API key>(DNSName("com."), DNSName("com."), "whatever", { QType::A, QType::TXT, QType::RRSIG, QType::NSEC }, 600, res->d_records, <API key> + 100); addRRSIG(keys, res->d_records, DNSName("com."), 300); /* then the next closer */ <API key>(domain, DNSName("com."), { QType::RRSIG, QType::NSEC }, 600, res->d_records, <API key> + 100); addRRSIG(keys, res->d_records, DNSName("com."), 300); /* a wildcard matches but has no record for this type */ <API key>(DNSName("*.com."), DNSName("com."), "whatever", { QType::AAAA, QType::NSEC, QType::RRSIG }, 600, res->d_records, <API key> + 100); addRRSIG(keys, res->d_records, DNSName("com"), 300, false, boost::none, DNSName("*.com")); return 1; } } return 0; }); /* we are generating NSEC3 with more iterations than we allow, so we should go Insecure */ vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Insecure); BOOST_REQUIRE_EQUAL(ret.size(), 8); BOOST_CHECK_EQUAL(queriesCount, 6); /* again, to test the cache */ ret.clear(); res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Insecure); BOOST_REQUIRE_EQUAL(ret.size(), 8); BOOST_CHECK_EQUAL(queriesCount, 6); } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr, true); setDNSSECValidation(sr, DNSSECMode::ValidateAll); primeHints(); const DNSName target("www.sub.powerdns.com."); testkeysset_t keys; auto luaconfsCopy = g_luaconfs.getCopy(); luaconfsCopy.dsAnchors.clear(); generateKeyMaterial(g_rootdnsname, DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys, luaconfsCopy.dsAnchors); generateKeyMaterial(DNSName("com."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); generateKeyMaterial(DNSName("powerdns.com."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); g_luaconfs.setState(luaconfsCopy); size_t queriesCount = 0; sr->setAsyncCallback([target,&queriesCount,keys](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { queriesCount++; if (type == QType::DS || type == QType::DNSKEY) { if (type == QType::DS && domain.isPartOf(DNSName("sub.powerdns.com"))) { setLWResult(res, RCode::NoError, true, false, true); addRecordToLW(res, DNSName("powerdns.com."), QType::SOA, "pdns-public-ns1.powerdns.com. pieter\\.lexis.powerdns.com. 2017032301 10800 3600 604800 3600", DNSResourceRecord::AUTHORITY, 3600); addRRSIG(keys, res->d_records, DNSName("powerdns.com."), 300); if (domain == DNSName("sub.powerdns.com")) { addNSECRecordToLW(DNSName("sub.powerdns.com."), DNSName("sud.powerdns.com."), { QType::A, QType::NSEC, QType::RRSIG }, 600, res->d_records); } else if (domain == target) { addNSECRecordToLW(DNSName("www.sub.powerdns.com."), DNSName("wwz.sub.powerdns.com."), { QType::A, QType::NSEC, QType::RRSIG }, 600, res->d_records); } addRRSIG(keys, res->d_records, DNSName("powerdns.com"), 300); return 1; } else { return <API key>(res, domain, domain, type, keys); } } else { if (isRootServer(ip)) { setLWResult(res, 0, false, false, true); addRecordToLW(res, "com.", QType::NS, "a.gtld-servers.com.", DNSResourceRecord::AUTHORITY, 3600); addDS(DNSName("com."), 300, res->d_records, keys); addRRSIG(keys, res->d_records, DNSName("."), 300); addRecordToLW(res, "a.gtld-servers.com.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); return 1; } else if (ip == ComboAddress("192.0.2.1:53")) { if (domain == DNSName("com.")) { setLWResult(res, 0, true, false, true); addRecordToLW(res, domain, QType::NS, "a.gtld-servers.com."); addRRSIG(keys, res->d_records, domain, 300); addRecordToLW(res, "a.gtld-servers.com.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); addRRSIG(keys, res->d_records, domain, 300); } else { setLWResult(res, 0, false, false, true); addRecordToLW(res, "powerdns.com.", QType::NS, "ns1.powerdns.com.", DNSResourceRecord::AUTHORITY, 3600); addDS(DNSName("powerdns.com."), 300, res->d_records, keys); addRRSIG(keys, res->d_records, DNSName("com."), 300); addRecordToLW(res, "ns1.powerdns.com.", QType::A, "192.0.2.2", DNSResourceRecord::ADDITIONAL, 3600); } return 1; } else if (ip == ComboAddress("192.0.2.2:53")) { setLWResult(res, 0, true, false, true); if (type == QType::NS) { if (domain == DNSName("powerdns.com.")) { addRecordToLW(res, domain, QType::NS, "ns1.powerdns.com."); addRRSIG(keys, res->d_records, DNSName("powerdns.com"), 300); addRecordToLW(res, "ns1.powerdns.com.", QType::A, "192.0.2.2", DNSResourceRecord::ADDITIONAL, 3600); addRRSIG(keys, res->d_records, DNSName("powerdns.com"), 300); } else { addRecordToLW(res, domain, QType::SOA, "pdns-public-ns1.powerdns.com. pieter\\.lexis.powerdns.com. 2017032301 10800 3600 604800 3600", DNSResourceRecord::AUTHORITY, 3600); addRRSIG(keys, res->d_records, DNSName("powerdns.com"), 300); addNSECRecordToLW(DNSName("www.powerdns.com."), DNSName("wwz.powerdns.com."), { QType::A, QType::NSEC, QType::RRSIG }, 600, res->d_records); addRRSIG(keys, res->d_records, DNSName("powerdns.com"), 300); } } else { addRecordToLW(res, domain, QType::A, "192.0.2.42"); addRRSIG(keys, res->d_records, DNSName("powerdns.com"), 300, false, boost::none, DNSName("*.powerdns.com")); /* we need to add the proof that this name does not exist, so the wildcard may apply */ /* first the closest encloser */ <API key>(DNSName("powerdns.com."), DNSName("powerdns.com."), "whatever", { QType::A, QType::TXT, QType::RRSIG, QType::NSEC }, 600, res->d_records); addRRSIG(keys, res->d_records, DNSName("powerdns.com."), 300); /* then the next closer */ <API key>(DNSName("sub.powerdns.com."), DNSName("powerdns.com."), { QType::A, QType::TXT, QType::RRSIG, QType::NSEC }, 600, res->d_records); addRRSIG(keys, res->d_records, DNSName("powerdns.com."), 300); } return 1; } } return 0; }); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Secure); BOOST_REQUIRE_EQUAL(ret.size(), 6); BOOST_CHECK_EQUAL(queriesCount, 10); /* again, to test the cache */ ret.clear(); res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Secure); BOOST_REQUIRE_EQUAL(ret.size(), 6); BOOST_CHECK_EQUAL(queriesCount, 10); } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr, true); setDNSSECValidation(sr, DNSSECMode::ValidateAll); primeHints(); const DNSName target("www.powerdns.com."); testkeysset_t keys; auto luaconfsCopy = g_luaconfs.getCopy(); luaconfsCopy.dsAnchors.clear(); generateKeyMaterial(g_rootdnsname, DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys, luaconfsCopy.dsAnchors); generateKeyMaterial(DNSName("com."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); generateKeyMaterial(DNSName("powerdns.com."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); g_luaconfs.setState(luaconfsCopy); size_t queriesCount = 0; sr->setAsyncCallback([target,&queriesCount,keys](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { queriesCount++; if (type == QType::DS || type == QType::DNSKEY) { if (type == QType::DS && domain == target) { setLWResult(res, RCode::NoError, true, false, true); addRecordToLW(res, DNSName("powerdns.com."), QType::SOA, "pdns-public-ns1.powerdns.com. pieter\\.lexis.powerdns.com. 2017032301 10800 3600 604800 3600", DNSResourceRecord::AUTHORITY, 3600); addRRSIG(keys, res->d_records, DNSName("powerdns.com."), 300); addNSECRecordToLW(DNSName("www.powerdns.com."), DNSName("wwz.powerdns.com."), { QType::A, QType::NSEC, QType::RRSIG }, 600, res->d_records); addRRSIG(keys, res->d_records, DNSName("powerdns.com"), 300); return 1; } else { return <API key>(res, domain, domain, type, keys); } } else { if (isRootServer(ip)) { setLWResult(res, 0, false, false, true); addRecordToLW(res, "com.", QType::NS, "a.gtld-servers.com.", DNSResourceRecord::AUTHORITY, 3600); addDS(DNSName("com."), 300, res->d_records, keys); addRRSIG(keys, res->d_records, DNSName("."), 300); addRecordToLW(res, "a.gtld-servers.com.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); return 1; } else if (ip == ComboAddress("192.0.2.1:53")) { if (domain == DNSName("com.")) { setLWResult(res, 0, true, false, true); addRecordToLW(res, domain, QType::NS, "a.gtld-servers.com."); addRRSIG(keys, res->d_records, domain, 300); addRecordToLW(res, "a.gtld-servers.com.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); addRRSIG(keys, res->d_records, domain, 300); } else { setLWResult(res, 0, false, false, true); addRecordToLW(res, "powerdns.com.", QType::NS, "ns1.powerdns.com.", DNSResourceRecord::AUTHORITY, 3600); addDS(DNSName("powerdns.com."), 300, res->d_records, keys); addRRSIG(keys, res->d_records, DNSName("com."), 300); addRecordToLW(res, "ns1.powerdns.com.", QType::A, "192.0.2.2", DNSResourceRecord::ADDITIONAL, 3600); } return 1; } else if (ip == ComboAddress("192.0.2.2:53")) { setLWResult(res, 0, true, false, true); if (type == QType::NS) { if (domain == DNSName("powerdns.com.")) { addRecordToLW(res, domain, QType::NS, "ns1.powerdns.com."); addRRSIG(keys, res->d_records, DNSName("powerdns.com"), 300); addRecordToLW(res, "ns1.powerdns.com.", QType::A, "192.0.2.2", DNSResourceRecord::ADDITIONAL, 3600); addRRSIG(keys, res->d_records, DNSName("powerdns.com"), 300); } else { addRecordToLW(res, domain, QType::SOA, "pdns-public-ns1.powerdns.com. pieter\\.lexis.powerdns.com. 2017032301 10800 3600 604800 3600", DNSResourceRecord::AUTHORITY, 3600); addRRSIG(keys, res->d_records, DNSName("powerdns.com"), 300); addNSECRecordToLW(DNSName("www.powerdns.com."), DNSName("wwz.powerdns.com."), { QType::A, QType::NSEC, QType::RRSIG }, 600, res->d_records); addRRSIG(keys, res->d_records, DNSName("powerdns.com"), 300); } } else { addRecordToLW(res, domain, QType::A, "192.0.2.42"); addRRSIG(keys, res->d_records, DNSName("powerdns.com"), 300, false, boost::none, DNSName("*.powerdns.com")); /* we need to add the proof that this name does not exist, so the wildcard may apply */ /* first the closest encloser */ <API key>(DNSName("powerdns.com."), DNSName("powerdns.com."), "whatever", { QType::A, QType::TXT, QType::RRSIG, QType::NSEC }, 600, res->d_records); addRRSIG(keys, res->d_records, DNSName("powerdns.com."), 300); /* then the next closer */ <API key>(DNSName("www.powerdns.com."), DNSName("powerdns.com."), { QType::A, QType::TXT, QType::RRSIG, QType::NSEC }, 600, res->d_records, <API key> + 100); addRRSIG(keys, res->d_records, DNSName("powerdns.com."), 300); } return 1; } } return 0; }); /* the NSEC3 providing the denial of existence proof for the next closer has too many iterations, we should end up Insecure */ vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Insecure); BOOST_REQUIRE_EQUAL(ret.size(), 6); BOOST_CHECK_EQUAL(queriesCount, 9); /* again, to test the cache */ ret.clear(); res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Insecure); BOOST_REQUIRE_EQUAL(ret.size(), 6); BOOST_CHECK_EQUAL(queriesCount, 9); } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr, true); setDNSSECValidation(sr, DNSSECMode::ValidateAll); primeHints(); const DNSName target("www.powerdns.com."); testkeysset_t keys; auto luaconfsCopy = g_luaconfs.getCopy(); luaconfsCopy.dsAnchors.clear(); generateKeyMaterial(g_rootdnsname, DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys, luaconfsCopy.dsAnchors); generateKeyMaterial(DNSName("com."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); generateKeyMaterial(DNSName("powerdns.com."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); g_luaconfs.setState(luaconfsCopy); size_t queriesCount = 0; sr->setAsyncCallback([target,&queriesCount,keys](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { queriesCount++; if (type == QType::DS || type == QType::DNSKEY) { if (type == QType::DS && domain == target) { setLWResult(res, RCode::NoError, true, false, true); addRecordToLW(res, DNSName("powerdns.com."), QType::SOA, "pdns-public-ns1.powerdns.com. pieter\\.lexis.powerdns.com. 2017032301 10800 3600 604800 3600", DNSResourceRecord::AUTHORITY, 3600); addRRSIG(keys, res->d_records, DNSName("powerdns.com."), 300); addNSECRecordToLW(DNSName("www.powerdns.com."), DNSName("wwz.powerdns.com."), { QType::A, QType::NSEC, QType::RRSIG }, 600, res->d_records); addRRSIG(keys, res->d_records, DNSName("powerdns.com"), 300); return 1; } else { return <API key>(res, domain, domain, type, keys); } } else { if (isRootServer(ip)) { setLWResult(res, 0, false, false, true); addRecordToLW(res, "com.", QType::NS, "a.gtld-servers.com.", DNSResourceRecord::AUTHORITY, 3600); addDS(DNSName("com."), 300, res->d_records, keys); addRRSIG(keys, res->d_records, DNSName("."), 300); addRecordToLW(res, "a.gtld-servers.com.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); return 1; } else if (ip == ComboAddress("192.0.2.1:53")) { if (domain == DNSName("com.")) { setLWResult(res, 0, true, false, true); addRecordToLW(res, domain, QType::NS, "a.gtld-servers.com."); addRRSIG(keys, res->d_records, domain, 300); addRecordToLW(res, "a.gtld-servers.com.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); addRRSIG(keys, res->d_records, domain, 300); } else { setLWResult(res, 0, false, false, true); addRecordToLW(res, "powerdns.com.", QType::NS, "ns1.powerdns.com.", DNSResourceRecord::AUTHORITY, 3600); addDS(DNSName("powerdns.com."), 300, res->d_records, keys); addRRSIG(keys, res->d_records, DNSName("com."), 300); addRecordToLW(res, "ns1.powerdns.com.", QType::A, "192.0.2.2", DNSResourceRecord::ADDITIONAL, 3600); } return 1; } else if (ip == ComboAddress("192.0.2.2:53")) { setLWResult(res, 0, true, false, true); if (type == QType::NS) { if (domain == DNSName("powerdns.com.")) { addRecordToLW(res, domain, QType::NS, "ns1.powerdns.com."); addRRSIG(keys, res->d_records, DNSName("powerdns.com"), 300); addRecordToLW(res, "ns1.powerdns.com.", QType::A, "192.0.2.2", DNSResourceRecord::ADDITIONAL, 3600); addRRSIG(keys, res->d_records, DNSName("powerdns.com"), 300); } else { addRecordToLW(res, domain, QType::SOA, "pdns-public-ns1.powerdns.com. pieter\\.lexis.powerdns.com. 2017032301 10800 3600 604800 3600", DNSResourceRecord::AUTHORITY, 3600); addRRSIG(keys, res->d_records, DNSName("powerdns.com"), 300); addNSECRecordToLW(DNSName("www.powerdns.com."), DNSName("wwz.powerdns.com."), { QType::A, QType::NSEC, QType::RRSIG }, 600, res->d_records); addRRSIG(keys, res->d_records, DNSName("powerdns.com"), 300); } } else { addRecordToLW(res, domain, QType::A, "192.0.2.42"); addRRSIG(keys, res->d_records, DNSName("powerdns.com"), 300, false, boost::none, DNSName("*.powerdns.com")); } return 1; } } return 0; }); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Bogus); BOOST_REQUIRE_EQUAL(ret.size(), 2); BOOST_CHECK_EQUAL(queriesCount, 9); /* again, to test the cache */ ret.clear(); res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Bogus); BOOST_REQUIRE_EQUAL(ret.size(), 2); BOOST_CHECK_EQUAL(queriesCount, 9); } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr, true); setDNSSECValidation(sr, DNSSECMode::ValidateAll); primeHints(); const DNSName target("www.powerdns.com."); testkeysset_t keys; auto luaconfsCopy = g_luaconfs.getCopy(); luaconfsCopy.dsAnchors.clear(); generateKeyMaterial(g_rootdnsname, DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys, luaconfsCopy.dsAnchors); generateKeyMaterial(DNSName("com."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); generateKeyMaterial(DNSName("powerdns.com."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); g_luaconfs.setState(luaconfsCopy); size_t queriesCount = 0; size_t dsQueriesCount = 0; sr->setAsyncCallback([target,&queriesCount,&dsQueriesCount,keys](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { queriesCount++; if (type == QType::DS) { DNSName auth(domain); auth.chopOff(); dsQueriesCount++; setLWResult(res, 0, true, false, true); addDS(domain, 300, res->d_records, keys, DNSResourceRecord::ANSWER); addRRSIG(keys, res->d_records, auth, 300); return 1; } else if (type == QType::DNSKEY) { setLWResult(res, 0, true, false, true); addDNSKEY(keys, domain, 300, res->d_records); addRRSIG(keys, res->d_records, domain, 300); return 1; } else { if (isRootServer(ip)) { setLWResult(res, 0, false, false, true); addRecordToLW(res, "com.", QType::NS, "a.gtld-servers.com.", DNSResourceRecord::AUTHORITY, 3600); addRecordToLW(res, "a.gtld-servers.com.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); /* No DS on referral, and no denial of the DS either */ return 1; } else if (ip == ComboAddress("192.0.2.1:53")) { if (domain == DNSName("com.")) { setLWResult(res, 0, true, false, true); addRecordToLW(res, domain, QType::NS, "a.gtld-servers.com."); addRRSIG(keys, res->d_records, domain, 300); addRecordToLW(res, "a.gtld-servers.com.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); addRRSIG(keys, res->d_records, domain, 300); } else { setLWResult(res, 0, false, false, true); addRecordToLW(res, "powerdns.com.", QType::NS, "ns1.powerdns.com.", DNSResourceRecord::AUTHORITY, 3600); addRecordToLW(res, "ns1.powerdns.com.", QType::A, "192.0.2.2", DNSResourceRecord::ADDITIONAL, 3600); /* No DS on referral, and no denial of the DS either */ } return 1; } else if (ip == ComboAddress("192.0.2.2:53")) { setLWResult(res, 0, true, false, true); if (type == QType::NS) { if (domain == DNSName("powerdns.com.")) { addRecordToLW(res, domain, QType::NS, "ns1.powerdns.com."); addRRSIG(keys, res->d_records, DNSName("powerdns.com"), 300); addRecordToLW(res, "ns1.powerdns.com.", QType::A, "192.0.2.2", DNSResourceRecord::ADDITIONAL, 3600); addRRSIG(keys, res->d_records, DNSName("powerdns.com"), 300); } else { addRecordToLW(res, domain, QType::SOA, "pdns-public-ns1.powerdns.com. pieter\\.lexis.powerdns.com. 2017032301 10800 3600 604800 3600", DNSResourceRecord::AUTHORITY, 3600); addRRSIG(keys, res->d_records, DNSName("powerdns.com"), 300); addNSECRecordToLW(DNSName("www.powerdns.com."), DNSName("wwz.powerdns.com."), { QType::A, QType::NSEC, QType::RRSIG }, 600, res->d_records); addRRSIG(keys, res->d_records, DNSName("powerdns.com"), 300); } } else { addRecordToLW(res, domain, QType::A, "192.0.2.42"); addRRSIG(keys, res->d_records, DNSName("powerdns.com"), 300); } return 1; } } return 0; }); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Secure); BOOST_REQUIRE_EQUAL(ret.size(), 2); BOOST_CHECK_EQUAL(queriesCount, 9); BOOST_CHECK_EQUAL(dsQueriesCount, 3); /* again, to test the cache */ ret.clear(); res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Secure); BOOST_REQUIRE_EQUAL(ret.size(), 2); BOOST_CHECK_EQUAL(queriesCount, 9); BOOST_CHECK_EQUAL(dsQueriesCount, 3); } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr, true); setDNSSECValidation(sr, DNSSECMode::ValidateAll); primeHints(); const DNSName target("www.powerdns.com."); testkeysset_t keys; auto luaconfsCopy = g_luaconfs.getCopy(); luaconfsCopy.dsAnchors.clear(); generateKeyMaterial(g_rootdnsname, DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys, luaconfsCopy.dsAnchors); generateKeyMaterial(DNSName("com."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); generateKeyMaterial(DNSName("powerdns.com."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); generateKeyMaterial(DNSName("www.powerdns.com."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); g_luaconfs.setState(luaconfsCopy); size_t queriesCount = 0; sr->setAsyncCallback([target,&queriesCount,keys](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { queriesCount++; if (type == QType::DS) { DNSName auth(domain); auth.chopOff(); setLWResult(res, 0, true, false, true); if (domain == target) { addRecordToLW(res, domain, QType::SOA, "ns1.powerdns.com. blah. 2017032800 1800 900 604800 86400", DNSResourceRecord::AUTHORITY, 86400); addRRSIG(keys, res->d_records, target, 300); } else { addDS(domain, 300, res->d_records, keys, DNSResourceRecord::ANSWER); addRRSIG(keys, res->d_records, auth, 300); } return 1; } else if (type == QType::DNSKEY) { setLWResult(res, 0, true, false, true); addDNSKEY(keys, domain, 300, res->d_records); addRRSIG(keys, res->d_records, domain, 300); return 1; } else { if (isRootServer(ip)) { setLWResult(res, 0, false, false, true); addRecordToLW(res, "com.", QType::NS, "a.gtld-servers.com.", DNSResourceRecord::AUTHORITY, 3600); addRecordToLW(res, "a.gtld-servers.com.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); addDS(DNSName("com."), 300, res->d_records, keys); addRRSIG(keys, res->d_records, DNSName("."), 300); return 1; } else if (ip == ComboAddress("192.0.2.1:53")) { if (domain == DNSName("com.")) { setLWResult(res, 0, true, false, true); addRecordToLW(res, domain, QType::NS, "a.gtld-servers.com."); addRRSIG(keys, res->d_records, domain, 300); addRecordToLW(res, "a.gtld-servers.com.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); addRRSIG(keys, res->d_records, domain, 300); } else { setLWResult(res, 0, false, false, true); addRecordToLW(res, "powerdns.com.", QType::NS, "ns1.powerdns.com.", DNSResourceRecord::AUTHORITY, 3600); /* no DS */ addNSECRecordToLW(domain, DNSName("z.powerdns.com."), { QType::NS }, 600, res->d_records); addRRSIG(keys, res->d_records, DNSName("com."), 300); addRecordToLW(res, "ns1.powerdns.com.", QType::A, "192.0.2.2", DNSResourceRecord::ADDITIONAL, 3600); } return 1; } else if (ip == ComboAddress("192.0.2.2:53")) { if (type == QType::NS) { if (domain == DNSName("powerdns.com.")) { setLWResult(res, RCode::Refused, false, false, true); } else { setLWResult(res, 0, true, false, true); addRecordToLW(res, domain, QType::NS, "ns1.powerdns.com."); addRRSIG(keys, res->d_records, domain, 300); addRecordToLW(res, "ns1.powerdns.com.", QType::A, "192.0.2.2", DNSResourceRecord::ADDITIONAL, 3600); addRRSIG(keys, res->d_records, domain, 300); } } else { setLWResult(res, 0, true, false, true); addRecordToLW(res, domain, QType::A, "192.0.2.42"); addRRSIG(keys, res->d_records, DNSName("www.powerdns.com"), 300); } return 1; } } return 0; }); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Bogus); BOOST_REQUIRE_EQUAL(ret.size(), 2); BOOST_CHECK_EQUAL(queriesCount, 9); /* again, to test the cache */ ret.clear(); res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Bogus); BOOST_REQUIRE_EQUAL(ret.size(), 2); BOOST_CHECK_EQUAL(queriesCount, 9); } <API key>(<API key>) { /* check that we don't accept a signer below us */ std::unique_ptr<SyncRes> sr; initSR(sr, true); setDNSSECValidation(sr, DNSSECMode::ValidateAll); primeHints(); const DNSName target("www.powerdns.com."); testkeysset_t keys; auto luaconfsCopy = g_luaconfs.getCopy(); luaconfsCopy.dsAnchors.clear(); generateKeyMaterial(g_rootdnsname, DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys, luaconfsCopy.dsAnchors); generateKeyMaterial(DNSName("com."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); generateKeyMaterial(DNSName("powerdns.com."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); generateKeyMaterial(DNSName("www.powerdns.com."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); generateKeyMaterial(DNSName("sub.www.powerdns.com."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); g_luaconfs.setState(luaconfsCopy); size_t queriesCount = 0; sr->setAsyncCallback([target,&queriesCount,keys](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { queriesCount++; if (type == QType::DS) { DNSName auth(domain); auth.chopOff(); setLWResult(res, 0, true, false, true); if (domain == target) { addRecordToLW(res, domain, QType::SOA, "ns1.powerdns.com. blah. 2017032800 1800 900 604800 86400", DNSResourceRecord::AUTHORITY, 86400); addRRSIG(keys, res->d_records, target, 300); } else { addDS(domain, 300, res->d_records, keys, DNSResourceRecord::ANSWER); addRRSIG(keys, res->d_records, auth, 300); } return 1; } else if (type == QType::DNSKEY) { setLWResult(res, 0, true, false, true); addDNSKEY(keys, domain, 300, res->d_records); if (domain == DNSName("www.powerdns.com.")) { addRRSIG(keys, res->d_records, DNSName("sub.www.powerdns.com."), 300); } else { addRRSIG(keys, res->d_records, domain, 300); } return 1; } else { if (isRootServer(ip)) { setLWResult(res, 0, false, false, true); addRecordToLW(res, "com.", QType::NS, "a.gtld-servers.com.", DNSResourceRecord::AUTHORITY, 3600); addRecordToLW(res, "a.gtld-servers.com.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); addDS(DNSName("com."), 300, res->d_records, keys); addRRSIG(keys, res->d_records, DNSName("."), 300); return 1; } else if (ip == ComboAddress("192.0.2.1:53")) { if (domain == DNSName("com.")) { setLWResult(res, 0, true, false, true); addRecordToLW(res, domain, QType::NS, "a.gtld-servers.com."); addRRSIG(keys, res->d_records, domain, 300); addRecordToLW(res, "a.gtld-servers.com.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); addRRSIG(keys, res->d_records, domain, 300); } else { setLWResult(res, 0, false, false, true); addRecordToLW(res, "powerdns.com.", QType::NS, "ns1.powerdns.com.", DNSResourceRecord::AUTHORITY, 3600); addDS(DNSName("powerdns.com."), 300, res->d_records, keys); addRRSIG(keys, res->d_records, DNSName("com."), 300); addRecordToLW(res, "ns1.powerdns.com.", QType::A, "192.0.2.2", DNSResourceRecord::ADDITIONAL, 3600); } return 1; } else if (ip == ComboAddress("192.0.2.2:53")) { if (type == QType::NS) { setLWResult(res, 0, true, false, true); addRecordToLW(res, domain, QType::NS, "ns1.powerdns.com."); addRRSIG(keys, res->d_records, domain, 300); addRecordToLW(res, "ns1.powerdns.com.", QType::A, "192.0.2.2", DNSResourceRecord::ADDITIONAL, 3600); addRRSIG(keys, res->d_records, domain, 300); } else { setLWResult(res, 0, true, false, true); addRecordToLW(res, domain, QType::A, "192.0.2.42"); addRRSIG(keys, res->d_records, domain, 300); } return 1; } } return 0; }); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Bogus); BOOST_REQUIRE_EQUAL(ret.size(), 2); BOOST_CHECK_EQUAL(queriesCount, 9); /* again, to test the cache */ ret.clear(); res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Bogus); BOOST_REQUIRE_EQUAL(ret.size(), 2); BOOST_CHECK_EQUAL(queriesCount, 9); } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr, true); setDNSSECValidation(sr, DNSSECMode::ValidateAll); primeHints(); const DNSName target("www.powerdns.com."); testkeysset_t keys; auto luaconfsCopy = g_luaconfs.getCopy(); luaconfsCopy.dsAnchors.clear(); generateKeyMaterial(g_rootdnsname, DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys, luaconfsCopy.dsAnchors); generateKeyMaterial(DNSName("com."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); g_luaconfs.setState(luaconfsCopy); size_t queriesCount = 0; size_t dsQueriesCount = 0; sr->setAsyncCallback([target,&queriesCount,&dsQueriesCount,keys](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { queriesCount++; if (type == QType::DS) { DNSName auth(domain); auth.chopOff(); dsQueriesCount++; setLWResult(res, 0, true, false, true); if (domain == DNSName("com.")) { addDS(domain, 300, res->d_records, keys, DNSResourceRecord::ANSWER); } else { addRecordToLW(res, "com.", QType::SOA, "a.gtld-servers.com. hostmastercom. 2017032301 10800 3600 604800 3600", DNSResourceRecord::AUTHORITY, 3600); addRRSIG(keys, res->d_records, DNSName("com."), 300); addNSECRecordToLW(domain, DNSName("powerdnt.com."), { QType::NS }, 600, res->d_records); } addRRSIG(keys, res->d_records, auth, 300); return 1; } else if (type == QType::DNSKEY) { setLWResult(res, 0, true, false, true); addDNSKEY(keys, domain, 300, res->d_records); addRRSIG(keys, res->d_records, domain, 300); return 1; } else { if (isRootServer(ip)) { setLWResult(res, 0, false, false, true); addRecordToLW(res, "com.", QType::NS, "a.gtld-servers.com.", DNSResourceRecord::AUTHORITY, 3600); addRecordToLW(res, "a.gtld-servers.com.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); /* No DS on referral, and no denial of the DS either */ return 1; } else if (ip == ComboAddress("192.0.2.1:53")) { if (domain == DNSName("com.")) { setLWResult(res, 0, true, false, true); addRecordToLW(res, domain, QType::NS, "a.gtld-servers.com."); addRRSIG(keys, res->d_records, domain, 300); addRecordToLW(res, "a.gtld-servers.com.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); addRRSIG(keys, res->d_records, domain, 300); } else { setLWResult(res, 0, false, false, true); addRecordToLW(res, "powerdns.com.", QType::NS, "ns1.powerdns.com.", DNSResourceRecord::AUTHORITY, 3600); addRecordToLW(res, "ns1.powerdns.com.", QType::A, "192.0.2.2", DNSResourceRecord::ADDITIONAL, 3600); /* No DS on referral, and no denial of the DS either */ } return 1; } else if (ip == ComboAddress("192.0.2.2:53")) { setLWResult(res, 0, true, false, true); if (type == QType::NS) { if (domain == DNSName("powerdns.com.")) { addRecordToLW(res, domain, QType::NS, "ns1.powerdns.com."); addRecordToLW(res, "ns1.powerdns.com.", QType::A, "192.0.2.2", DNSResourceRecord::ADDITIONAL, 3600); } else { addRecordToLW(res, domain, QType::SOA, "pdns-public-ns1.powerdns.com. pieter\\.lexis.powerdns.com. 2017032301 10800 3600 604800 3600", DNSResourceRecord::AUTHORITY, 3600); } } else { addRecordToLW(res, domain, QType::A, "192.0.2.42"); } return 1; } } return 0; }); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Insecure); BOOST_REQUIRE_EQUAL(ret.size(), 1); BOOST_CHECK_EQUAL(queriesCount, 7); BOOST_CHECK_EQUAL(dsQueriesCount, 2); /* again, to test the cache */ ret.clear(); res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Insecure); BOOST_REQUIRE_EQUAL(ret.size(), 1); BOOST_CHECK_EQUAL(queriesCount, 7); BOOST_CHECK_EQUAL(dsQueriesCount, 2); } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr, true); setDNSSECValidation(sr, DNSSECMode::ValidateAll); primeHints(); const DNSName target("powerdns.com."); testkeysset_t keys; auto luaconfsCopy = g_luaconfs.getCopy(); luaconfsCopy.dsAnchors.clear(); generateKeyMaterial(g_rootdnsname, DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys, luaconfsCopy.dsAnchors); generateKeyMaterial(DNSName("com."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); generateKeyMaterial(DNSName("powerdns.com."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); g_luaconfs.setState(luaconfsCopy); size_t queriesCount = 0; sr->setAsyncCallback([target,&queriesCount,keys](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { queriesCount++; if (type == QType::DS || type == QType::DNSKEY) { return <API key>(res, domain, domain, type, keys); } else { if (isRootServer(ip)) { setLWResult(res, 0, false, false, true); addRecordToLW(res, "com.", QType::NS, "a.gtld-servers.com.", DNSResourceRecord::AUTHORITY, 3600); addDS(DNSName("com."), 300, res->d_records, keys); addRRSIG(keys, res->d_records, DNSName("."), 300); addRecordToLW(res, "a.gtld-servers.com.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); return 1; } else if (ip == ComboAddress("192.0.2.1:53")) { if (domain == DNSName("com.")) { setLWResult(res, 0, true, false, true); addRecordToLW(res, DNSName("com."), QType::NS, "a.gtld-servers.com."); addRRSIG(keys, res->d_records, DNSName("com."), 300); addRecordToLW(res, "a.gtld-servers.com.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); } else { setLWResult(res, 0, false, false, true); addRecordToLW(res, domain, QType::NS, "ns1.powerdns.com.", DNSResourceRecord::AUTHORITY, 3600); addDS(domain, 300, res->d_records, keys); addRRSIG(keys, res->d_records, DNSName("com."), 300); addRecordToLW(res, "ns1.powerdns.com.", QType::A, "192.0.2.2", DNSResourceRecord::ADDITIONAL, 3600); } return 1; } else if (ip == ComboAddress("192.0.2.2:53")) { setLWResult(res, 0, true, false, true); if (type == QType::NS) { addRecordToLW(res, domain, QType::NS, "ns1.powerdns.com."); addRRSIG(keys, res->d_records, domain, 300); } else { addRecordToLW(res, domain, QType::SOA, "pdns-public-ns1.powerdns.com. pieter\\.lexis.powerdns.com. 2017032301 10800 3600 604800 3600", DNSResourceRecord::AUTHORITY, 3600); addRRSIG(keys, res->d_records, domain, 300); addNSECRecordToLW(domain, DNSName("z.powerdns.com."), { QType::NS, QType::DNSKEY }, 600, res->d_records); /* NO RRSIG for the NSEC record! */ } return 1; } } return 0; }); /* NSEC record without the corresponding RRSIG in a secure zone, should be Bogus! */ vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Bogus); BOOST_CHECK_EQUAL(ret.size(), 3); BOOST_CHECK_EQUAL(queriesCount, 8); /* again, to test the cache */ ret.clear(); res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Bogus); BOOST_REQUIRE_EQUAL(ret.size(), 3); BOOST_CHECK_EQUAL(queriesCount, 8); } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr, true); setDNSSECValidation(sr, DNSSECMode::ValidateAll); primeHints(); const DNSName target("powerdns.com."); testkeysset_t keys; auto luaconfsCopy = g_luaconfs.getCopy(); luaconfsCopy.dsAnchors.clear(); generateKeyMaterial(g_rootdnsname, DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys, luaconfsCopy.dsAnchors); generateKeyMaterial(DNSName("com."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); generateKeyMaterial(DNSName("powerdns.com."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); g_luaconfs.setState(luaconfsCopy); size_t queriesCount = 0; sr->setAsyncCallback([target,&queriesCount,keys](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { queriesCount++; if (type == QType::DS || type == QType::DNSKEY) { return <API key>(res, domain, domain, type, keys); } else { if (isRootServer(ip)) { setLWResult(res, 0, false, false, true); addRecordToLW(res, "com.", QType::NS, "a.gtld-servers.com.", DNSResourceRecord::AUTHORITY, 3600); addDS(DNSName("com."), 300, res->d_records, keys); addRRSIG(keys, res->d_records, DNSName("."), 300); addRecordToLW(res, "a.gtld-servers.com.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); return 1; } else if (ip == ComboAddress("192.0.2.1:53")) { if (domain == DNSName("com.")) { setLWResult(res, 0, true, false, true); addRecordToLW(res, DNSName("com."), QType::NS, "a.gtld-servers.com."); addRRSIG(keys, res->d_records, DNSName("com."), 300); addRecordToLW(res, "a.gtld-servers.com.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); } else { setLWResult(res, 0, false, false, true); addRecordToLW(res, domain, QType::NS, "ns1.powerdns.com.", DNSResourceRecord::AUTHORITY, 3600); addDS(domain, 300, res->d_records, keys); addRRSIG(keys, res->d_records, DNSName("com."), 300); addRecordToLW(res, "ns1.powerdns.com.", QType::A, "192.0.2.2", DNSResourceRecord::ADDITIONAL, 3600); } return 1; } else if (ip == ComboAddress("192.0.2.2:53")) { setLWResult(res, 0, true, false, true); if (type == QType::NS) { addRecordToLW(res, domain, QType::NS, "ns1.powerdns.com."); addRRSIG(keys, res->d_records, domain, 300); } else { addRecordToLW(res, domain, QType::SOA, "pdns-public-ns1.powerdns.com. pieter\\.lexis.powerdns.com. 2017032301 10800 3600 604800 3600", DNSResourceRecord::AUTHORITY, 3600); addRRSIG(keys, res->d_records, domain, 300); /* NO NSEC record! */ } return 1; } } return 0; }); /* no NSEC record in a secure zone, should be Bogus! */ vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Bogus); BOOST_CHECK_EQUAL(ret.size(), 2); BOOST_CHECK_EQUAL(queriesCount, 8); /* again, to test the cache */ ret.clear(); res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Bogus); BOOST_REQUIRE_EQUAL(ret.size(), 2); BOOST_CHECK_EQUAL(queriesCount, 8); } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr, true); setDNSSECValidation(sr, DNSSECMode::ValidateAll); primeHints(); const DNSName target("powerdns.com."); const ComboAddress targetAddr("192.0.2.42"); testkeysset_t keys; auto luaconfsCopy = g_luaconfs.getCopy(); luaconfsCopy.dsAnchors.clear(); generateKeyMaterial(g_rootdnsname, DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys, luaconfsCopy.dsAnchors); generateKeyMaterial(DNSName("com."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); g_luaconfs.setState(luaconfsCopy); size_t queriesCount = 0; sr->setAsyncCallback([target,targetAddr,&queriesCount,keys](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { queriesCount++; if (type == QType::DS) { if (domain == target) { setLWResult(res, 0, false, false, true); addRecordToLW(res, domain, QType::SOA, "pdns-public-ns1.powerdns.com. pieter\\.lexis.powerdns.com. 2017032301 10800 3600 604800 3600", DNSResourceRecord::AUTHORITY, 3600); addNSECRecordToLW(domain, DNSName("z.powerdns.com."), { QType::NS }, 600, res->d_records); addRRSIG(keys, res->d_records, DNSName("com."), 300); return 1; } else { return <API key>(res, domain, domain, type, keys); } } else if (type == QType::DNSKEY) { if (domain == g_rootdnsname || domain == DNSName("com.")) { setLWResult(res, 0, true, false, true); addDNSKEY(keys, domain, 300, res->d_records); addRRSIG(keys, res->d_records, domain, 300); return 1; } else { setLWResult(res, 0, false, false, true); addRecordToLW(res, domain, QType::SOA, "pdns-public-ns1.powerdns.com. pieter\\.lexis.powerdns.com. 2017032301 10800 3600 604800 3600", DNSResourceRecord::AUTHORITY, 3600); return 1; } } else { if (isRootServer(ip)) { setLWResult(res, 0, false, false, true); addRecordToLW(res, "com.", QType::NS, "a.gtld-servers.com.", DNSResourceRecord::AUTHORITY, 3600); addDS(DNSName("com."), 300, res->d_records, keys); addRRSIG(keys, res->d_records, DNSName("."), 300); addRecordToLW(res, "a.gtld-servers.com.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); return 1; } else if (ip == ComboAddress("192.0.2.1:53")) { if (domain == DNSName("com.")) { setLWResult(res, 0, true, false, true); addRecordToLW(res, DNSName("com."), QType::NS, "a.gtld-servers.com."); addRRSIG(keys, res->d_records, DNSName("com."), 300); addRecordToLW(res, "a.gtld-servers.com.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); } else { setLWResult(res, 0, false, false, true); addRecordToLW(res, domain, QType::NS, "ns1.powerdns.com.", DNSResourceRecord::AUTHORITY, 3600); /* no DS */ addNSECRecordToLW(domain, DNSName("z.powerdns.com."), { QType::NS }, 600, res->d_records); addRRSIG(keys, res->d_records, DNSName("com."), 300); addRecordToLW(res, "ns1.powerdns.com.", QType::A, "192.0.2.2", DNSResourceRecord::ADDITIONAL, 3600); } return 1; } else if (ip == ComboAddress("192.0.2.2:53")) { setLWResult(res, 0, true, false, true); if (type == QType::NS) { addRecordToLW(res, domain, QType::NS, "ns1.powerdns.com."); } else { addRecordToLW(res, domain, QType::A, targetAddr.toString()); } return 1; } } return 0; }); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Insecure); BOOST_REQUIRE_EQUAL(ret.size(), 1); BOOST_CHECK(ret[0].d_type == QType::A); /* 4 NS: com at ., com at com, powerdns.com at com, powerdns.com at powerdns.com 4 DNSKEY: ., com (not for powerdns.com because DS denial in referral) 1 query for A */ BOOST_CHECK_EQUAL(queriesCount, 7); /* again, to test the cache */ ret.clear(); res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Insecure); BOOST_REQUIRE_EQUAL(ret.size(), 1); BOOST_CHECK(ret[0].d_type == QType::A); BOOST_CHECK_EQUAL(queriesCount, 7); } <API key>(<API key>) { /* Direct DS query: - parent is secure, zone is secure: DS should be secure */ std::unique_ptr<SyncRes> sr; initSR(sr, true); setDNSSECValidation(sr, DNSSECMode::ValidateAll); primeHints(); const DNSName target("powerdns.com."); testkeysset_t keys; auto luaconfsCopy = g_luaconfs.getCopy(); luaconfsCopy.dsAnchors.clear(); generateKeyMaterial(g_rootdnsname, DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys, luaconfsCopy.dsAnchors); generateKeyMaterial(DNSName("com."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); generateKeyMaterial(DNSName("powerdns.com."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); g_luaconfs.setState(luaconfsCopy); size_t queriesCount = 0; sr->setAsyncCallback([target,&queriesCount,keys](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { queriesCount++; if (type == QType::DS || type == QType::DNSKEY) { return <API key>(res, domain, domain, type, keys); } else { if (isRootServer(ip)) { setLWResult(res, 0, false, false, true); addRecordToLW(res, "com.", QType::NS, "a.gtld-servers.com.", DNSResourceRecord::AUTHORITY, 3600); addDS(DNSName("com."), 300, res->d_records, keys); addRRSIG(keys, res->d_records, DNSName("."), 300); addRecordToLW(res, "a.gtld-servers.com.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); return 1; } } return 0; }); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::DS), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Secure); BOOST_REQUIRE_EQUAL(ret.size(), 2); for (const auto& record : ret) { BOOST_CHECK(record.d_type == QType::DS || record.d_type == QType::RRSIG); } BOOST_CHECK_EQUAL(queriesCount, 4); /* again, to test the cache */ ret.clear(); res = sr->beginResolve(target, QType(QType::DS), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Secure); BOOST_REQUIRE_EQUAL(ret.size(), 2); for (const auto& record : ret) { BOOST_CHECK(record.d_type == QType::DS || record.d_type == QType::RRSIG); } BOOST_CHECK_EQUAL(queriesCount, 4); } <API key>(<API key>) { /* Direct DS query: - parent is secure, zone is insecure: DS denial should be secure */ std::unique_ptr<SyncRes> sr; initSR(sr, true); setDNSSECValidation(sr, DNSSECMode::ValidateAll); primeHints(); const DNSName target("powerdns.com."); testkeysset_t keys; auto luaconfsCopy = g_luaconfs.getCopy(); luaconfsCopy.dsAnchors.clear(); generateKeyMaterial(g_rootdnsname, DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys, luaconfsCopy.dsAnchors); generateKeyMaterial(DNSName("com."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); g_luaconfs.setState(luaconfsCopy); size_t queriesCount = 0; sr->setAsyncCallback([target,&queriesCount,keys](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { queriesCount++; if (type == QType::DS || type == QType::DNSKEY) { return <API key>(res, domain, domain, type, keys); } else { if (isRootServer(ip)) { setLWResult(res, 0, false, false, true); addRecordToLW(res, "com.", QType::NS, "a.gtld-servers.com.", DNSResourceRecord::AUTHORITY, 3600); addDS(DNSName("com."), 300, res->d_records, keys); addRRSIG(keys, res->d_records, DNSName("."), 300); addRecordToLW(res, "a.gtld-servers.com.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); return 1; } } return 0; }); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::DS), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Secure); BOOST_REQUIRE_EQUAL(ret.size(), 4); for (const auto& record : ret) { BOOST_CHECK(record.d_type == QType::SOA || record.d_type == QType::NSEC || record.d_type == QType::RRSIG); } BOOST_CHECK_EQUAL(queriesCount, 4); /* again, to test the cache */ ret.clear(); res = sr->beginResolve(target, QType(QType::DS), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Secure); BOOST_REQUIRE_EQUAL(ret.size(), 4); for (const auto& record : ret) { BOOST_CHECK(record.d_type == QType::SOA || record.d_type == QType::NSEC || record.d_type == QType::RRSIG); } BOOST_CHECK_EQUAL(queriesCount, 4); } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr, true); setDNSSECValidation(sr, DNSSECMode::ValidateAll); primeHints(); const DNSName target("www.sub.powerdns.com."); const ComboAddress targetAddr("192.0.2.42"); testkeysset_t keys; auto luaconfsCopy = g_luaconfs.getCopy(); luaconfsCopy.dsAnchors.clear(); generateKeyMaterial(g_rootdnsname, DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys, luaconfsCopy.dsAnchors); generateKeyMaterial(DNSName("com."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); generateKeyMaterial(DNSName("powerdns.com."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); g_luaconfs.setState(luaconfsCopy); size_t queriesCount = 0; sr->setAsyncCallback([target,targetAddr,&queriesCount,keys](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { queriesCount++; if (type == QType::DS) { if (domain == DNSName("sub.powerdns.com.")) { setLWResult(res, 0, false, false, true); addRecordToLW(res, domain, QType::SOA, "pdns-public-ns1.powerdns.com. pieter\\.lexis.powerdns.com. 2017032301 10800 3600 604800 3600", DNSResourceRecord::AUTHORITY, 3600); addRRSIG(keys, res->d_records, DNSName("powerdns.com."), 300); addNSECRecordToLW(domain, DNSName("z.powerdns.com."), { QType::NS }, 600, res->d_records); addRRSIG(keys, res->d_records, DNSName("powerdns.com."), 300); return 1; } else if (domain == DNSName("www.sub.powerdns.com.")) { setLWResult(res, 0, false, false, true); addRecordToLW(res, DNSName("sub.powerdns.com."), QType::SOA, "pdns-public-ns1.powerdns.com. pieter\\.lexis.powerdns.com. 2017032301 10800 3600 604800 3600", DNSResourceRecord::AUTHORITY, 3600); return 1; } else { return <API key>(res, domain, domain, type, keys); } } else if (type == QType::DNSKEY) { if (domain == g_rootdnsname || domain == DNSName("com.") || domain == DNSName("powerdns.com.")) { setLWResult(res, 0, true, false, true); addDNSKEY(keys, domain, 300, res->d_records); addRRSIG(keys, res->d_records, domain, 300); return 1; } else { setLWResult(res, 0, false, false, true); addRecordToLW(res, domain, QType::SOA, "pdns-public-ns1.powerdns.com. pieter\\.lexis.powerdns.com. 2017032301 10800 3600 604800 3600", DNSResourceRecord::AUTHORITY, 3600); return 1; } } else { if (isRootServer(ip)) { setLWResult(res, 0, false, false, true); addRecordToLW(res, "com.", QType::NS, "a.gtld-servers.com.", DNSResourceRecord::AUTHORITY, 3600); addDS(DNSName("com."), 300, res->d_records, keys); addRRSIG(keys, res->d_records, DNSName("."), 300); addRecordToLW(res, "a.gtld-servers.com.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); return 1; } else if (ip == ComboAddress("192.0.2.1:53")) { if (domain == DNSName("com.")) { setLWResult(res, 0, true, false, true); addRecordToLW(res, DNSName("com."), QType::NS, "a.gtld-servers.com."); addRRSIG(keys, res->d_records, DNSName("com."), 300); addRecordToLW(res, "a.gtld-servers.com.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); } else { setLWResult(res, 0, false, false, true); addRecordToLW(res, DNSName("powerdns.com."), QType::NS, "ns1.powerdns.com.", DNSResourceRecord::AUTHORITY, 3600); addDS(DNSName("powerdns.com."), 300, res->d_records, keys); addRRSIG(keys, res->d_records, DNSName("com."), 300); addRecordToLW(res, "ns1.powerdns.com.", QType::A, "192.0.2.2", DNSResourceRecord::ADDITIONAL, 3600); } return 1; } else if (ip == ComboAddress("192.0.2.2:53")) { setLWResult(res, 0, true, false, true); if (type == QType::NS) { if (domain == DNSName("www.sub.powerdns.com.")) { addRecordToLW(res, DNSName("sub.powerdns.com"), QType::SOA, "pdns-public-ns1.powerdns.com. pieter\\.lexis.powerdns.com. 2017032301 10800 3600 604800 3600", DNSResourceRecord::AUTHORITY, 3600); } else if (domain == DNSName("sub.powerdns.com.")) { addRecordToLW(res, domain, QType::NS, "ns1.powerdns.com."); } else if (domain == DNSName("powerdns.com.")) { addRecordToLW(res, domain, QType::NS, "ns1.powerdns.com."); addRRSIG(keys, res->d_records, DNSName("powerdns.com."), 300); } } else { addRecordToLW(res, domain, QType::A, targetAddr.toString(), DNSResourceRecord::ANSWER, 3600); } return 1; } } return 0; }); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Insecure); BOOST_REQUIRE_EQUAL(ret.size(), 1); BOOST_CHECK(ret[0].d_type == QType::A); BOOST_CHECK_EQUAL(queriesCount, 9); /* again, to test the cache */ ret.clear(); res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Insecure); BOOST_REQUIRE_EQUAL(ret.size(), 1); BOOST_CHECK(ret[0].d_type == QType::A); BOOST_CHECK_EQUAL(queriesCount, 9); } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr, true); setDNSSECValidation(sr, DNSSECMode::ValidateAll); primeHints(); const DNSName target("www.sub.powerdns.com."); const ComboAddress targetAddr("192.0.2.42"); testkeysset_t keys; auto luaconfsCopy = g_luaconfs.getCopy(); luaconfsCopy.dsAnchors.clear(); generateKeyMaterial(g_rootdnsname, DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys, luaconfsCopy.dsAnchors); /* No key material for .com */ /* But TA for sub.powerdns.com. */ generateKeyMaterial(DNSName("sub.powerdns.com."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); luaconfsCopy.dsAnchors[DNSName("sub.powerdns.com.")].insert(keys[DNSName("sub.powerdns.com.")].second); g_luaconfs.setState(luaconfsCopy); size_t queriesCount = 0; sr->setAsyncCallback([target,targetAddr,&queriesCount,keys](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { queriesCount++; if (type == QType::DS) { if (domain == DNSName("www.sub.powerdns.com")) { setLWResult(res, 0, false, false, true); addRecordToLW(res, DNSName("sub.powerdns.com"), QType::SOA, "pdns-public-ns1.powerdns.com. pieter\\.lexis.powerdns.com. 2017032301 10800 3600 604800 3600", DNSResourceRecord::AUTHORITY, 3600); addRRSIG(keys, res->d_records, DNSName("sub.powerdns.com"), 300); addNSECRecordToLW(DNSName("www.sub.powerdns.com"), DNSName("vww.sub.powerdns.com."), { QType::A }, 600, res->d_records); addRRSIG(keys, res->d_records, DNSName("sub.powerdns.com"), 300); } else { setLWResult(res, 0, false, false, true); if (domain == DNSName("com.")) { addRecordToLW(res, domain, QType::SOA, "pdns-public-ns1.powerdns.com. pieter\\.lexis.powerdns.com. 2017032301 10800 3600 604800 3600", DNSResourceRecord::AUTHORITY, 3600); /* no DS */ addNSECRecordToLW(DNSName("com."), DNSName("dom."), { QType::NS }, 600, res->d_records); addRRSIG(keys, res->d_records, DNSName("."), 300); } else { setLWResult(res, 0, false, false, true); addRecordToLW(res, domain, QType::SOA, "pdns-public-ns1.powerdns.com. pieter\\.lexis.powerdns.com. 2017032301 10800 3600 604800 3600", DNSResourceRecord::AUTHORITY, 3600); } } return 1; } else if (type == QType::DNSKEY) { if (domain == g_rootdnsname || domain == DNSName("sub.powerdns.com.")) { setLWResult(res, 0, true, false, true); addDNSKEY(keys, domain, 300, res->d_records); addRRSIG(keys, res->d_records, domain, 300); return 1; } } else { if (isRootServer(ip)) { setLWResult(res, 0, false, false, true); addRecordToLW(res, "com.", QType::NS, "a.gtld-servers.com.", DNSResourceRecord::AUTHORITY, 3600); /* no DS */ addNSECRecordToLW(DNSName("com."), DNSName("dom."), { QType::NS }, 600, res->d_records); addRRSIG(keys, res->d_records, DNSName("."), 300); addRecordToLW(res, "a.gtld-servers.com.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); return 1; } else if (ip == ComboAddress("192.0.2.1:53")) { if (domain == DNSName("com.")) { setLWResult(res, 0, true, false, true); addRecordToLW(res, DNSName("com."), QType::NS, "a.gtld-servers.com."); addRecordToLW(res, "a.gtld-servers.com.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); } else if (domain.isPartOf(DNSName("powerdns.com."))) { setLWResult(res, 0, false, false, true); addRecordToLW(res, DNSName("powerdns.com."), QType::NS, "ns1.powerdns.com.", DNSResourceRecord::AUTHORITY, 3600); addRecordToLW(res, "ns1.powerdns.com.", QType::A, "192.0.2.2", DNSResourceRecord::ADDITIONAL, 3600); } return 1; } else if (ip == ComboAddress("192.0.2.2:53")) { setLWResult(res, 0, true, false, true); if (type == QType::NS) { if (domain == DNSName("www.sub.powerdns.com.")) { addRecordToLW(res, DNSName("sub.powerdns.com"), QType::SOA, "pdns-public-ns1.powerdns.com. pieter\\.lexis.powerdns.com. 2017032301 10800 3600 604800 3600", DNSResourceRecord::AUTHORITY, 3600); addRRSIG(keys, res->d_records, DNSName("sub.powerdns.com"), 300); addNSECRecordToLW(DNSName("www.sub.powerdns.com"), DNSName("vww.sub.powerdns.com."), { QType::A }, 600, res->d_records); addRRSIG(keys, res->d_records, DNSName("sub.powerdns.com"), 300); } else if (domain == DNSName("sub.powerdns.com.")) { addRecordToLW(res, domain, QType::NS, "ns1.powerdns.com."); addRRSIG(keys, res->d_records, DNSName("sub.powerdns.com."), 300); } else if (domain == DNSName("powerdns.com.")) { addRecordToLW(res, domain, QType::NS, "ns1.powerdns.com."); } } else if (domain == DNSName("www.sub.powerdns.com.")) { addRecordToLW(res, domain, QType::A, targetAddr.toString(), DNSResourceRecord::ANSWER, 3600); addRRSIG(keys, res->d_records, DNSName("sub.powerdns.com."), 300); } return 1; } } return 0; }); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Secure); BOOST_REQUIRE_EQUAL(ret.size(), 2); BOOST_CHECK(ret[0].d_type == QType::A); BOOST_CHECK_EQUAL(queriesCount, 7); /* again, to test the cache */ ret.clear(); res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Secure); BOOST_REQUIRE_EQUAL(ret.size(), 2); BOOST_CHECK(ret[0].d_type == QType::A); BOOST_CHECK_EQUAL(queriesCount, 7); } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr, true); setDNSSECValidation(sr, DNSSECMode::ValidateAll); primeHints(); const DNSName target("powerdns.com."); testkeysset_t keys; auto luaconfsCopy = g_luaconfs.getCopy(); luaconfsCopy.dsAnchors.clear(); generateKeyMaterial(g_rootdnsname, DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys, luaconfsCopy.dsAnchors); generateKeyMaterial(DNSName("com."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); g_luaconfs.setState(luaconfsCopy); size_t queriesCount = 0; sr->setAsyncCallback([target,&queriesCount,keys](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { queriesCount++; if (type == QType::DS) { if (domain == target) { setLWResult(res, 0, false, false, true); addRecordToLW(res, domain, QType::SOA, "pdns-public-ns1.powerdns.com. pieter\\.lexis.powerdns.com. 2017032301 10800 3600 604800 3600", DNSResourceRecord::AUTHORITY, 3600); addNSECRecordToLW(domain, DNSName("z.powerdns.com."), { QType::NS }, 600, res->d_records); addRRSIG(keys, res->d_records, DNSName("com."), 300); return 1; } else { return <API key>(res, domain, domain, type, keys); } } else if (type == QType::DNSKEY) { if (domain == g_rootdnsname || domain == DNSName("com.")) { setLWResult(res, 0, true, false, true); addDNSKEY(keys, domain, 300, res->d_records); addRRSIG(keys, res->d_records, domain, 300); return 1; } else { setLWResult(res, 0, false, false, true); addRecordToLW(res, domain, QType::SOA, "pdns-public-ns1.powerdns.com. pieter\\.lexis.powerdns.com. 2017032301 10800 3600 604800 3600", DNSResourceRecord::AUTHORITY, 3600); return 1; } } else { if (isRootServer(ip)) { setLWResult(res, 0, false, false, true); addRecordToLW(res, "com.", QType::NS, "a.gtld-servers.com.", DNSResourceRecord::AUTHORITY, 3600); addDS(DNSName("com."), 300, res->d_records, keys); addRRSIG(keys, res->d_records, DNSName("."), 300); addRecordToLW(res, "a.gtld-servers.com.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); return 1; } else if (ip == ComboAddress("192.0.2.1:53")) { if (domain == DNSName("com.")) { setLWResult(res, 0, true, false, true); addRecordToLW(res, domain, QType::NS, "a.gtld-servers.com."); addRRSIG(keys, res->d_records, DNSName("com."), 300); addRecordToLW(res, "a.gtld-servers.com.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); addRRSIG(keys, res->d_records, DNSName("com."), 300); } else { setLWResult(res, 0, false, false, true); addRecordToLW(res, domain, QType::NS, "ns1.powerdns.com.", DNSResourceRecord::AUTHORITY, 3600); /* no DS */ addNSECRecordToLW(domain, DNSName("z.powerdns.com."), { QType::NS }, 600, res->d_records); addRRSIG(keys, res->d_records, DNSName("com."), 300); addRecordToLW(res, "ns1.powerdns.com.", QType::A, "192.0.2.2", DNSResourceRecord::ADDITIONAL, 3600); } return 1; } else if (ip == ComboAddress("192.0.2.2:53")) { if (type == QType::NS) { addRecordToLW(res, domain, QType::NS, "ns1.powerdns.com."); addRecordToLW(res, "ns1.powerdns.com.", QType::A, "192.0.2.2", DNSResourceRecord::ADDITIONAL, 3600); } else { setLWResult(res, 0, true, false, true); addRecordToLW(res, domain, QType::SOA, "pdns-public-ns1.powerdns.com. pieter\\.lexis.powerdns.com. 2017032301 10800 3600 604800 3600", DNSResourceRecord::AUTHORITY, 3600); } return 1; } } return 0; }); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Insecure); BOOST_REQUIRE_EQUAL(ret.size(), 1); /* 4 NS (com from root, com from com, powerdns.com from com, powerdns.com from powerdns.com) 2 DNSKEY (. and com., none for powerdns.com because no DS) 1 query for A */ BOOST_CHECK_EQUAL(queriesCount, 7); /* again, to test the cache */ ret.clear(); res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Insecure); BOOST_REQUIRE_EQUAL(ret.size(), 1); BOOST_CHECK_EQUAL(queriesCount, 7); } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr, true); setDNSSECValidation(sr, DNSSECMode::ValidateAll); primeHints(); const DNSName target("powerdns.com."); const DNSName targetCName("power-dns.com."); const ComboAddress targetCNameAddr("192.0.2.42"); testkeysset_t keys; auto luaconfsCopy = g_luaconfs.getCopy(); luaconfsCopy.dsAnchors.clear(); generateKeyMaterial(g_rootdnsname, DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys, luaconfsCopy.dsAnchors); generateKeyMaterial(DNSName("com."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); generateKeyMaterial(DNSName("powerdns.com."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); g_luaconfs.setState(luaconfsCopy); size_t queriesCount = 0; sr->setAsyncCallback([target,targetCName,targetCNameAddr,&queriesCount,keys](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { queriesCount++; if (type == QType::DS) { if (domain == targetCName) { setLWResult(res, 0, false, false, true); addRecordToLW(res, domain, QType::SOA, "pdns-public-ns1.powerdns.com. pieter\\.lexis.powerdns.com. 2017032301 10800 3600 604800 3600", DNSResourceRecord::AUTHORITY, 3600); addNSECRecordToLW(domain, DNSName("z.power-dns.com."), { QType::NS }, 600, res->d_records); addRRSIG(keys, res->d_records, DNSName("com."), 300); return 1; } else { return <API key>(res, domain, domain, type, keys); } } else if (type == QType::DNSKEY) { if (domain == g_rootdnsname || domain == DNSName("com.") || domain == DNSName("powerdns.com.")) { setLWResult(res, 0, true, false, true); addDNSKEY(keys, domain, 300, res->d_records); addRRSIG(keys, res->d_records, domain, 300); return 1; } else { setLWResult(res, 0, false, false, true); addRecordToLW(res, domain, QType::SOA, "pdns-public-ns1.powerdns.com. pieter\\.lexis.powerdns.com. 2017032301 10800 3600 604800 3600", DNSResourceRecord::AUTHORITY, 3600); return 1; } } else { if (isRootServer(ip)) { setLWResult(res, 0, false, false, true); addRecordToLW(res, "com.", QType::NS, "a.gtld-servers.com.", DNSResourceRecord::AUTHORITY, 3600); addDS(DNSName("com."), 300, res->d_records, keys); addRRSIG(keys, res->d_records, DNSName("."), 300); addRecordToLW(res, "a.gtld-servers.com.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); return 1; } else if (ip == ComboAddress("192.0.2.1:53")) { setLWResult(res, 0, false, false, true); if (domain == DNSName("com.")) { setLWResult(res, 0, true, false, true); addRecordToLW(res, domain, QType::NS, "a.gtld-servers.com."); addRRSIG(keys, res->d_records, DNSName("com."), 300); addRecordToLW(res, "a.gtld-servers.com.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); addRRSIG(keys, res->d_records, DNSName("com."), 300); } else { addRecordToLW(res, domain, QType::NS, "ns1.powerdns.com.", DNSResourceRecord::AUTHORITY, 3600); if (domain == DNSName("powerdns.com.")) { addDS(DNSName("powerdns.com."), 300, res->d_records, keys); } else if (domain == targetCName) { addNSECRecordToLW(domain, DNSName("z.power-dns.com."), { QType::NS }, 600, res->d_records); } addRRSIG(keys, res->d_records, DNSName("com."), 300); addRecordToLW(res, "ns1.powerdns.com.", QType::A, "192.0.2.2", DNSResourceRecord::ADDITIONAL, 3600); } return 1; } else if (ip == ComboAddress("192.0.2.2:53")) { setLWResult(res, 0, true, false, true); if (type == QType::NS) { addRecordToLW(res, domain, QType::NS, "ns1.powerdns.com."); if (domain == DNSName("powerdns.com.")) { addRRSIG(keys, res->d_records, domain, 300); } addRecordToLW(res, "ns1.powerdns.com.", QType::A, "192.0.2.2", DNSResourceRecord::ADDITIONAL, 3600); if (domain == DNSName("powerdns.com.")) { addRRSIG(keys, res->d_records, domain, 300); } } else { if (domain == DNSName("powerdns.com.")) { addRecordToLW(res, domain, QType::CNAME, targetCName.toString()); addRRSIG(keys, res->d_records, domain, 300); } else if (domain == targetCName) { addRecordToLW(res, domain, QType::A, targetCNameAddr.toString()); } } return 1; } } return 0; }); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Insecure); BOOST_REQUIRE_EQUAL(ret.size(), 3); BOOST_CHECK_EQUAL(queriesCount, 11); /* again, to test the cache */ ret.clear(); res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Insecure); BOOST_REQUIRE_EQUAL(ret.size(), 3); BOOST_CHECK_EQUAL(queriesCount, 11); } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr, true); setDNSSECValidation(sr, DNSSECMode::ValidateAll); primeHints(); const DNSName target("powerdns.com."); const DNSName targetCName1("cname.sub.powerdns.com."); const DNSName targetCName2("cname2.sub.powerdns.com."); const ComboAddress targetCName2Addr("192.0.2.42"); testkeysset_t keys; auto luaconfsCopy = g_luaconfs.getCopy(); luaconfsCopy.dsAnchors.clear(); generateKeyMaterial(g_rootdnsname, DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys, luaconfsCopy.dsAnchors); generateKeyMaterial(DNSName("com."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); generateKeyMaterial(DNSName("powerdns.com."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); g_luaconfs.setState(luaconfsCopy); size_t queriesCount = 0; sr->setAsyncCallback([target,targetCName1,targetCName2,targetCName2Addr,&queriesCount,keys](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { queriesCount++; if (type == QType::DS || type == QType::DNSKEY) { if (domain == DNSName("sub.powerdns.com")) { setLWResult(res, 0, false, false, true); addRecordToLW(res, domain, QType::SOA, "pdns-public-ns1.powerdns.com. pieter\\.lexis.powerdns.com. 2017032301 10800 3600 604800 3600", DNSResourceRecord::AUTHORITY, 3600); addNSECRecordToLW(domain, DNSName("z.power-dns.com."), { QType::NS }, 600, res->d_records); addRRSIG(keys, res->d_records, DNSName("com."), 300); return 1; } else { return <API key>(res, domain, domain, type, keys); } } else { if (isRootServer(ip)) { setLWResult(res, 0, false, false, true); addRecordToLW(res, "com.", QType::NS, "a.gtld-servers.com.", DNSResourceRecord::AUTHORITY, 3600); addDS(DNSName("com."), 300, res->d_records, keys); addRRSIG(keys, res->d_records, DNSName("."), 300); addRecordToLW(res, "a.gtld-servers.com.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); return 1; } else if (ip == ComboAddress("192.0.2.1:53")) { setLWResult(res, 0, false, false, true); if (domain == DNSName("com.")) { setLWResult(res, 0, true, false, true); addRecordToLW(res, domain, QType::NS, "a.gtld-servers.com."); addRRSIG(keys, res->d_records, DNSName("com."), 300); addRecordToLW(res, "a.gtld-servers.com.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); addRRSIG(keys, res->d_records, DNSName("com."), 300); } else { addRecordToLW(res, domain, QType::NS, "ns1.powerdns.com.", DNSResourceRecord::AUTHORITY, 3600); if (domain == DNSName("powerdns.com.")) { addDS(DNSName("powerdns.com."), 300, res->d_records, keys); } else if (domain == DNSName("sub.powerdns.com")) { addNSECRecordToLW(domain, DNSName("z.power-dns.com."), { QType::NS }, 600, res->d_records); } addRRSIG(keys, res->d_records, DNSName("com."), 300); addRecordToLW(res, "ns1.powerdns.com.", QType::A, "192.0.2.2", DNSResourceRecord::ADDITIONAL, 3600); } return 1; } else if (ip == ComboAddress("192.0.2.2:53")) { setLWResult(res, 0, true, false, true); if (type == QType::NS) { addRecordToLW(res, domain, QType::NS, "ns1.powerdns.com."); if (domain == DNSName("powerdns.com.")) { addRRSIG(keys, res->d_records, domain, 300); } addRecordToLW(res, "ns1.powerdns.com.", QType::A, "192.0.2.2", DNSResourceRecord::ADDITIONAL, 3600); if (domain == DNSName("powerdns.com.")) { addRRSIG(keys, res->d_records, domain, 300); } } else { if (domain == DNSName("powerdns.com.")) { addRecordToLW(res, domain, QType::CNAME, targetCName1.toString()); addRRSIG(keys, res->d_records, domain, 300); /* add the CNAME target as a glue, with no RRSIG since the sub zone is insecure */ addRecordToLW(res, targetCName1, QType::CNAME, targetCName2.toString()); addRecordToLW(res, targetCName2, QType::A, targetCName2Addr.toString()); } else if (domain == targetCName1) { addRecordToLW(res, domain, QType::CNAME, targetCName2.toString()); } else if (domain == targetCName2) { addRecordToLW(res, domain, QType::A, targetCName2Addr.toString()); } } return 1; } } return 0; }); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Insecure); BOOST_REQUIRE_EQUAL(ret.size(), 4); BOOST_CHECK_EQUAL(queriesCount, 11); /* again, to test the cache */ ret.clear(); res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Insecure); BOOST_REQUIRE_EQUAL(ret.size(), 4); BOOST_CHECK_EQUAL(queriesCount, 11); } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr, true); setDNSSECValidation(sr, DNSSECMode::ValidateAll); primeHints(); const DNSName target("power-dns.com."); const DNSName targetCName("powerdns.com."); const ComboAddress targetCNameAddr("192.0.2.42"); testkeysset_t keys; auto luaconfsCopy = g_luaconfs.getCopy(); luaconfsCopy.dsAnchors.clear(); generateKeyMaterial(g_rootdnsname, DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys, luaconfsCopy.dsAnchors); generateKeyMaterial(DNSName("com."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); generateKeyMaterial(DNSName("powerdns.com."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); g_luaconfs.setState(luaconfsCopy); size_t queriesCount = 0; sr->setAsyncCallback([target,targetCName,targetCNameAddr,&queriesCount,keys](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { queriesCount++; if (type == QType::DS) { if (domain == DNSName("power-dns.com.")) { setLWResult(res, 0, false, false, true); addRecordToLW(res, domain, QType::SOA, "pdns-public-ns1.powerdns.com. pieter\\.lexis.powerdns.com. 2017032301 10800 3600 604800 3600", DNSResourceRecord::AUTHORITY, 3600); addNSECRecordToLW(domain, DNSName("z.power-dns.com."), { QType::NS }, 600, res->d_records); addRRSIG(keys, res->d_records, DNSName("com."), 300); return 1; } else { return <API key>(res, domain, domain, type, keys); } } else if (type == QType::DNSKEY) { if (domain == g_rootdnsname || domain == DNSName("com.") || domain == DNSName("powerdns.com.")) { setLWResult(res, 0, true, false, true); addDNSKEY(keys, domain, 300, res->d_records); addRRSIG(keys, res->d_records, domain, 300); return 1; } else { setLWResult(res, 0, false, false, true); addRecordToLW(res, domain, QType::SOA, "pdns-public-ns1.powerdns.com. pieter\\.lexis.powerdns.com. 2017032301 10800 3600 604800 3600", DNSResourceRecord::AUTHORITY, 3600); return 1; } } else { if (isRootServer(ip)) { setLWResult(res, 0, false, false, true); addRecordToLW(res, "com.", QType::NS, "a.gtld-servers.com.", DNSResourceRecord::AUTHORITY, 3600); addDS(DNSName("com."), 300, res->d_records, keys); addRRSIG(keys, res->d_records, DNSName("."), 300); addRecordToLW(res, "a.gtld-servers.com.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); return 1; } else if (ip == ComboAddress("192.0.2.1:53")) { if (domain == DNSName("com.")) { setLWResult(res, 0, true, false, true); addRecordToLW(res, domain, QType::NS, "a.gtld-servers.com."); addRRSIG(keys, res->d_records, DNSName("com."), 300); addRecordToLW(res, "a.gtld-servers.com.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); addRRSIG(keys, res->d_records, DNSName("com."), 300); } else if (domain == DNSName("powerdns.com.") || domain == DNSName("power-dns.com.")) { setLWResult(res, 0, false, false, true); addRecordToLW(res, domain, QType::NS, "ns1.powerdns.com.", DNSResourceRecord::AUTHORITY, 3600); if (domain == targetCName) { addDS(DNSName("powerdns.com."), 300, res->d_records, keys); } else if (domain == target) { addNSECRecordToLW(domain, DNSName("z.power-dns.com."), { QType::NS }, 600, res->d_records); } addRRSIG(keys, res->d_records, DNSName("com."), 300); addRecordToLW(res, "ns1.powerdns.com.", QType::A, "192.0.2.2", DNSResourceRecord::ADDITIONAL, 3600); } return 1; } else if (ip == ComboAddress("192.0.2.2:53")) { setLWResult(res, 0, true, false, true); if (type == QType::NS) { addRecordToLW(res, domain, QType::NS, "ns1.powerdns.com."); if (domain == DNSName("powerdns.com.")) { addRRSIG(keys, res->d_records, domain, 300); } addRecordToLW(res, "ns1.powerdns.com.", QType::A, "192.0.2.2", DNSResourceRecord::ADDITIONAL, 3600); if (domain == DNSName("powerdns.com.")) { addRRSIG(keys, res->d_records, domain, 300); } } else { if (domain == target) { addRecordToLW(res, domain, QType::CNAME, targetCName.toString()); } else if (domain == targetCName) { addRecordToLW(res, domain, QType::A, targetCNameAddr.toString()); addRRSIG(keys, res->d_records, domain, 300); } } return 1; } } return 0; }); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Insecure); BOOST_REQUIRE_EQUAL(ret.size(), 3); BOOST_CHECK_EQUAL(queriesCount, 11); /* again, to test the cache */ ret.clear(); res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Insecure); BOOST_REQUIRE_EQUAL(ret.size(), 3); BOOST_CHECK_EQUAL(queriesCount, 11); } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr, true); setDNSSECValidation(sr, DNSSECMode::ValidateAll); primeHints(); const DNSName target("power-dns.com."); const DNSName targetCName("powerdns.com."); const ComboAddress targetCNameAddr("192.0.2.42"); testkeysset_t keys; auto luaconfsCopy = g_luaconfs.getCopy(); luaconfsCopy.dsAnchors.clear(); generateKeyMaterial(g_rootdnsname, DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys, luaconfsCopy.dsAnchors); generateKeyMaterial(DNSName("com."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); generateKeyMaterial(DNSName("powerdns.com."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); generateKeyMaterial(DNSName("power-dns.com."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); g_luaconfs.setState(luaconfsCopy); size_t queriesCount = 0; sr->setAsyncCallback([target,targetCName,targetCNameAddr,&queriesCount,keys](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { queriesCount++; if (type == QType::DS || type == QType::DNSKEY) { return <API key>(res, domain, domain, type, keys); } else { if (isRootServer(ip)) { setLWResult(res, 0, false, false, true); addRecordToLW(res, "com.", QType::NS, "a.gtld-servers.com.", DNSResourceRecord::AUTHORITY, 3600); addDS(DNSName("com."), 300, res->d_records, keys); addRRSIG(keys, res->d_records, DNSName("."), 300); addRecordToLW(res, "a.gtld-servers.com.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); return 1; } else if (ip == ComboAddress("192.0.2.1:53")) { if (domain == DNSName("com.")) { setLWResult(res, 0, true, false, true); addRecordToLW(res, domain, QType::NS, "a.gtld-servers.com."); addRRSIG(keys, res->d_records, DNSName("com."), 300); addRecordToLW(res, "a.gtld-servers.com.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); addRRSIG(keys, res->d_records, DNSName("com."), 300); } else if (domain == DNSName("powerdns.com.") || domain == DNSName("power-dns.com.")) { setLWResult(res, 0, false, false, true); addRecordToLW(res, domain, QType::NS, "ns1.powerdns.com.", DNSResourceRecord::AUTHORITY, 3600); addDS(DNSName(domain), 300, res->d_records, keys); addRRSIG(keys, res->d_records, DNSName("com."), 300); addRecordToLW(res, "ns1.powerdns.com.", QType::A, "192.0.2.2", DNSResourceRecord::ADDITIONAL, 3600); } return 1; } else if (ip == ComboAddress("192.0.2.2:53")) { setLWResult(res, 0, true, false, true); if (type == QType::NS) { addRecordToLW(res, domain, QType::NS, "ns1.powerdns.com."); addRRSIG(keys, res->d_records, domain, 300); addRecordToLW(res, "ns1.powerdns.com.", QType::A, "192.0.2.2", DNSResourceRecord::ADDITIONAL, 3600); addRRSIG(keys, res->d_records, domain, 300); } else { if (domain == target) { addRecordToLW(res, domain, QType::CNAME, targetCName.toString()); /* No RRSIG, leading to bogus */ } else if (domain == targetCName) { addRecordToLW(res, domain, QType::A, targetCNameAddr.toString()); addRRSIG(keys, res->d_records, domain, 300); } } return 1; } } return 0; }); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Bogus); BOOST_REQUIRE_EQUAL(ret.size(), 3); BOOST_CHECK_EQUAL(queriesCount, 11); /* again, to test the cache */ ret.clear(); res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Bogus); BOOST_REQUIRE_EQUAL(ret.size(), 3); BOOST_CHECK_EQUAL(queriesCount, 11); } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr, true); setDNSSECValidation(sr, DNSSECMode::ValidateAll); primeHints(); const DNSName target("power-dns.com."); const DNSName targetCName("powerdns.com."); const ComboAddress targetCNameAddr("192.0.2.42"); testkeysset_t keys; auto luaconfsCopy = g_luaconfs.getCopy(); luaconfsCopy.dsAnchors.clear(); generateKeyMaterial(g_rootdnsname, DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys, luaconfsCopy.dsAnchors); generateKeyMaterial(DNSName("com."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); generateKeyMaterial(DNSName("powerdns.com."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); generateKeyMaterial(DNSName("power-dns.com."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); g_luaconfs.setState(luaconfsCopy); size_t queriesCount = 0; sr->setAsyncCallback([target,targetCName,targetCNameAddr,&queriesCount,keys](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { queriesCount++; if (type == QType::DS || type == QType::DNSKEY) { return <API key>(res, domain, domain, type, keys); } else { if (isRootServer(ip)) { setLWResult(res, 0, false, false, true); addRecordToLW(res, "com.", QType::NS, "a.gtld-servers.com.", DNSResourceRecord::AUTHORITY, 3600); addDS(DNSName("com."), 300, res->d_records, keys); addRRSIG(keys, res->d_records, DNSName("."), 300); addRecordToLW(res, "a.gtld-servers.com.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); return 1; } else if (ip == ComboAddress("192.0.2.1:53")) { if (domain == DNSName("com.")) { setLWResult(res, 0, true, false, true); addRecordToLW(res, domain, QType::NS, "a.gtld-servers.com."); addRRSIG(keys, res->d_records, DNSName("com."), 300); addRecordToLW(res, "a.gtld-servers.com.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); addRRSIG(keys, res->d_records, DNSName("com."), 300); } else if (domain == DNSName("powerdns.com.") || domain == DNSName("power-dns.com.")) { setLWResult(res, 0, false, false, true); addRecordToLW(res, domain, QType::NS, "ns1.powerdns.com.", DNSResourceRecord::AUTHORITY, 3600); addDS(DNSName(domain), 300, res->d_records, keys); addRRSIG(keys, res->d_records, DNSName("com."), 300); addRecordToLW(res, "ns1.powerdns.com.", QType::A, "192.0.2.2", DNSResourceRecord::ADDITIONAL, 3600); } return 1; } else if (ip == ComboAddress("192.0.2.2:53")) { setLWResult(res, 0, true, false, true); if (type == QType::NS) { addRecordToLW(res, domain, QType::NS, "ns1.powerdns.com."); addRRSIG(keys, res->d_records, domain, 300); addRecordToLW(res, "ns1.powerdns.com.", QType::A, "192.0.2.2", DNSResourceRecord::ADDITIONAL, 3600); addRRSIG(keys, res->d_records, domain, 300); } else { if (domain == target) { addRecordToLW(res, domain, QType::CNAME, targetCName.toString()); addRRSIG(keys, res->d_records, domain, 300); } else if (domain == targetCName) { addRecordToLW(res, domain, QType::A, targetCNameAddr.toString()); /* No RRSIG, leading to bogus */ } } return 1; } } return 0; }); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Bogus); BOOST_REQUIRE_EQUAL(ret.size(), 3); BOOST_CHECK_EQUAL(queriesCount, 11); /* again, to test the cache */ ret.clear(); res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Bogus); BOOST_REQUIRE_EQUAL(ret.size(), 3); BOOST_CHECK_EQUAL(queriesCount, 11); } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr, true); setDNSSECValidation(sr, DNSSECMode::ValidateAll); primeHints(); const DNSName target("power-dns.com."); const DNSName targetCName("powerdns.com."); const ComboAddress targetCNameAddr("192.0.2.42"); testkeysset_t keys; auto luaconfsCopy = g_luaconfs.getCopy(); luaconfsCopy.dsAnchors.clear(); generateKeyMaterial(g_rootdnsname, DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys, luaconfsCopy.dsAnchors); generateKeyMaterial(DNSName("com."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); generateKeyMaterial(DNSName("powerdns.com."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); generateKeyMaterial(DNSName("power-dns.com."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); g_luaconfs.setState(luaconfsCopy); size_t queriesCount = 0; sr->setAsyncCallback([target,targetCName,targetCNameAddr,&queriesCount,keys](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { queriesCount++; if (type == QType::DS || type == QType::DNSKEY) { return <API key>(res, domain, domain, type, keys); } else { if (isRootServer(ip)) { setLWResult(res, 0, false, false, true); addRecordToLW(res, "com.", QType::NS, "a.gtld-servers.com.", DNSResourceRecord::AUTHORITY, 3600); addDS(DNSName("com."), 300, res->d_records, keys); addRRSIG(keys, res->d_records, DNSName("."), 300); addRecordToLW(res, "a.gtld-servers.com.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); return 1; } else if (ip == ComboAddress("192.0.2.1:53")) { if (domain == DNSName("com.")) { setLWResult(res, 0, true, false, true); addRecordToLW(res, domain, QType::NS, "a.gtld-servers.com."); addRRSIG(keys, res->d_records, DNSName("com."), 300); addRecordToLW(res, "a.gtld-servers.com.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); addRRSIG(keys, res->d_records, DNSName("com."), 300); } else if (domain == DNSName("powerdns.com.") || domain == DNSName("power-dns.com.")) { setLWResult(res, 0, false, false, true); addRecordToLW(res, domain, QType::NS, "ns1.powerdns.com.", DNSResourceRecord::AUTHORITY, 3600); addDS(DNSName(domain), 300, res->d_records, keys); addRRSIG(keys, res->d_records, DNSName("com."), 300); addRecordToLW(res, "ns1.powerdns.com.", QType::A, "192.0.2.2", DNSResourceRecord::ADDITIONAL, 3600); } return 1; } else if (ip == ComboAddress("192.0.2.2:53")) { setLWResult(res, 0, true, false, true); if (type == QType::NS) { addRecordToLW(res, domain, QType::NS, "ns1.powerdns.com."); addRRSIG(keys, res->d_records, domain, 300); addRecordToLW(res, "ns1.powerdns.com.", QType::A, "192.0.2.2", DNSResourceRecord::ADDITIONAL, 3600); addRRSIG(keys, res->d_records, domain, 300); } else { if (domain == target) { addRecordToLW(res, domain, QType::CNAME, targetCName.toString()); addRRSIG(keys, res->d_records, domain, 300); } else if (domain == targetCName) { addRecordToLW(res, domain, QType::A, targetCNameAddr.toString()); addRRSIG(keys, res->d_records, domain, 300); } } return 1; } } return 0; }); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Secure); BOOST_REQUIRE_EQUAL(ret.size(), 4); BOOST_CHECK_EQUAL(queriesCount, 12); /* again, to test the cache */ ret.clear(); res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Secure); BOOST_REQUIRE_EQUAL(ret.size(), 4); BOOST_CHECK_EQUAL(queriesCount, 12); } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr, true); setDNSSECValidation(sr, DNSSECMode::ValidateAll); primeHints(); const DNSName target("powerdns.com."); const DNSName targetCName("power-dns.com."); const ComboAddress targetCNameAddr("192.0.2.42"); testkeysset_t keys; auto luaconfsCopy = g_luaconfs.getCopy(); luaconfsCopy.dsAnchors.clear(); generateKeyMaterial(g_rootdnsname, DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys, luaconfsCopy.dsAnchors); generateKeyMaterial(DNSName("com."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); generateKeyMaterial(DNSName("powerdns.com."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); generateKeyMaterial(DNSName("power-dns.com."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); g_luaconfs.setState(luaconfsCopy); size_t queriesCount = 0; sr->setAsyncCallback([target,targetCName,targetCNameAddr,&queriesCount,keys](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { queriesCount++; if (type == QType::DS) { if (domain == DNSName("power-dns.com.")) { setLWResult(res, 0, false, false, true); addRecordToLW(res, domain, QType::SOA, "pdns-public-ns1.powerdns.com. pieter\\.lexis.powerdns.com. 2017032301 10800 3600 604800 3600", DNSResourceRecord::AUTHORITY, 3600); addNSECRecordToLW(domain, DNSName("z.power-dns.com."), { QType::NS }, 600, res->d_records); addRRSIG(keys, res->d_records, DNSName("com."), 300); return 1; } else { return <API key>(res, domain, domain, type, keys); } } else if (type == QType::DNSKEY) { if (domain == g_rootdnsname || domain == DNSName("com.") || domain == DNSName("powerdns.com.")) { setLWResult(res, 0, true, false, true); addDNSKEY(keys, domain, 300, res->d_records); addRRSIG(keys, res->d_records, domain, 300); return 1; } else { setLWResult(res, 0, false, false, true); addRecordToLW(res, domain, QType::SOA, "pdns-public-ns1.powerdns.com. pieter\\.lexis.powerdns.com. 2017032301 10800 3600 604800 3600", DNSResourceRecord::AUTHORITY, 3600); return 1; } } else { if (isRootServer(ip)) { setLWResult(res, 0, false, false, true); addRecordToLW(res, "com.", QType::NS, "a.gtld-servers.com.", DNSResourceRecord::AUTHORITY, 3600); addDS(DNSName("com."), 300, res->d_records, keys); addRRSIG(keys, res->d_records, DNSName("."), 300); addRecordToLW(res, "a.gtld-servers.com.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); return 1; } else if (ip == ComboAddress("192.0.2.1:53")) { if (domain == DNSName("com.")) { setLWResult(res, 0, true, false, true); addRecordToLW(res, domain, QType::NS, "a.gtld-servers.com."); addRRSIG(keys, res->d_records, DNSName("com."), 300); addRecordToLW(res, "a.gtld-servers.com.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); addRRSIG(keys, res->d_records, DNSName("com."), 300); } else if (domain == DNSName("powerdns.com.") || domain == DNSName("power-dns.com.")) { setLWResult(res, 0, false, false, true); addRecordToLW(res, domain, QType::NS, "ns1.powerdns.com.", DNSResourceRecord::AUTHORITY, 3600); if (domain == DNSName("powerdns.com.")) { addDS(DNSName("powerdns.com."), 300, res->d_records, keys); } else if (domain == targetCName) { addNSECRecordToLW(domain, DNSName("z.power-dns.com."), { QType::NS }, 600, res->d_records); } addRRSIG(keys, res->d_records, DNSName("com."), 300); addRecordToLW(res, "ns1.powerdns.com.", QType::A, "192.0.2.2", DNSResourceRecord::ADDITIONAL, 3600); } return 1; } else if (ip == ComboAddress("192.0.2.2:53")) { setLWResult(res, 0, true, false, true); if (type == QType::NS) { addRecordToLW(res, domain, QType::NS, "ns1.powerdns.com."); addRecordToLW(res, "ns1.powerdns.com.", QType::A, "192.0.2.2", DNSResourceRecord::ADDITIONAL, 3600); } else { if (domain == DNSName("powerdns.com.")) { addRecordToLW(res, domain, QType::CNAME, targetCName.toString()); /* No RRSIG -> Bogus */ } else if (domain == targetCName) { addRecordToLW(res, domain, QType::A, targetCNameAddr.toString()); } } return 1; } } return 0; }); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Bogus); /* no RRSIG to show */ BOOST_CHECK_EQUAL(ret.size(), 2); BOOST_CHECK_EQUAL(queriesCount, 10); /* again, to test the cache */ ret.clear(); res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Bogus); BOOST_CHECK_EQUAL(ret.size(), 2); BOOST_CHECK_EQUAL(queriesCount, 10); } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr, true); setDNSSECValidation(sr, DNSSECMode::ValidateAll); primeHints(); const DNSName target("powerdns.com."); const ComboAddress targetAddr("192.0.2.42"); testkeysset_t keys; auto luaconfsCopy = g_luaconfs.getCopy(); luaconfsCopy.dsAnchors.clear(); generateKeyMaterial(g_rootdnsname, DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys, luaconfsCopy.dsAnchors); /* No key material for .com */ generateKeyMaterial(target, DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); luaconfsCopy.dsAnchors[target].insert(keys[target].second); g_luaconfs.setState(luaconfsCopy); size_t queriesCount = 0; sr->setAsyncCallback([target,targetAddr,&queriesCount,keys](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { queriesCount++; if (type == QType::DNSKEY) { if (domain == g_rootdnsname || domain == DNSName("powerdns.com.")) { setLWResult(res, 0, true, false, true); addDNSKEY(keys, domain, 300, res->d_records); addRRSIG(keys, res->d_records, domain, 300); return 1; } else if (domain == DNSName("com.")) { setLWResult(res, 0, false, false, true); addRecordToLW(res, domain, QType::SOA, ". yop. 2017032301 10800 3600 604800 3600", DNSResourceRecord::AUTHORITY, 3600); return 1; } } else { if (isRootServer(ip)) { setLWResult(res, 0, false, false, true); addRecordToLW(res, "com.", QType::NS, "a.gtld-servers.com.", DNSResourceRecord::AUTHORITY, 3600); addNSECRecordToLW(DNSName("com."), DNSName("com."), { QType::NS }, 600, res->d_records); addRRSIG(keys, res->d_records, DNSName("."), 300); addRecordToLW(res, "a.gtld-servers.com.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); return 1; } else if (ip == ComboAddress("192.0.2.1:53")) { if (target == domain) { setLWResult(res, 0, false, false, true); addRecordToLW(res, domain, QType::NS, "ns1.powerdns.com.", DNSResourceRecord::AUTHORITY, 3600); addRecordToLW(res, "ns1.powerdns.com.", QType::A, "192.0.2.2", DNSResourceRecord::ADDITIONAL, 3600); } else if (domain == DNSName("com.")) { setLWResult(res, 0, true, false, true); addRecordToLW(res, domain, QType::NS, "a.gtld-servers.com."); addRecordToLW(res, "a.gtld-servers.com.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); } return 1; } else if (ip == ComboAddress("192.0.2.2:53")) { setLWResult(res, 0, true, false, true); if (type == QType::NS) { addRecordToLW(res, domain, QType::NS, "ns1.powerdns.com."); } else { addRecordToLW(res, domain, QType::A, targetAddr.toString(), DNSResourceRecord::ANSWER, 3600); } addRRSIG(keys, res->d_records, domain, 300); return 1; } } return 0; }); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); /* should be insecure but we have a TA for powerdns.com. */ BOOST_CHECK_EQUAL(sr->getValidationState(), Secure); /* We got a RRSIG */ BOOST_REQUIRE_EQUAL(ret.size(), 2); BOOST_CHECK(ret[0].d_type == QType::A); BOOST_CHECK_EQUAL(queriesCount, 5); /* again, to test the cache */ ret.clear(); res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Secure); BOOST_REQUIRE_EQUAL(ret.size(), 2); BOOST_CHECK(ret[0].d_type == QType::A); BOOST_CHECK_EQUAL(queriesCount, 5); } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr, true); setDNSSECValidation(sr, DNSSECMode::ValidateAll); primeHints(); const DNSName target("powerdns.com."); const ComboAddress targetAddr("192.0.2.42"); testkeysset_t keys; auto luaconfsCopy = g_luaconfs.getCopy(); luaconfsCopy.dsAnchors.clear(); generateKeyMaterial(g_rootdnsname, DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys, luaconfsCopy.dsAnchors); /* No key material for .com */ generateKeyMaterial(target, DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); luaconfsCopy.dsAnchors[target].insert(keys[target].second); g_luaconfs.setState(luaconfsCopy); size_t queriesCount = 0; sr->setAsyncCallback([target,targetAddr,&queriesCount,keys](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { queriesCount++; if (type == QType::DNSKEY) { if (domain == g_rootdnsname || domain == DNSName("powerdns.com.")) { setLWResult(res, 0, true, false, true); addDNSKEY(keys, domain, 300, res->d_records); addRRSIG(keys, res->d_records, domain, 300); return 1; } else if (domain == DNSName("com.")) { setLWResult(res, 0, false, false, true); addRecordToLW(res, domain, QType::SOA, ". yop. 2017032301 10800 3600 604800 3600", DNSResourceRecord::AUTHORITY, 3600); return 1; } } else { if (target.isPartOf(domain) && isRootServer(ip)) { setLWResult(res, 0, false, false, true); addRecordToLW(res, "com.", QType::NS, "a.gtld-servers.com.", DNSResourceRecord::AUTHORITY, 3600); addNSECRecordToLW(DNSName("com."), DNSName("com."), { QType::NS }, 600, res->d_records); addRRSIG(keys, res->d_records, DNSName("."), 300); addRecordToLW(res, "a.gtld-servers.com.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); return 1; } else if (ip == ComboAddress("192.0.2.1:53")) { if (target == domain) { setLWResult(res, 0, false, false, true); addRecordToLW(res, domain, QType::NS, "ns1.powerdns.com.", DNSResourceRecord::AUTHORITY, 3600); addRecordToLW(res, "ns1.powerdns.com.", QType::A, "192.0.2.2", DNSResourceRecord::ADDITIONAL, 3600); } else if (domain == DNSName("com.")) { setLWResult(res, 0, true, false, true); addRecordToLW(res, domain, QType::NS, "a.gtld-servers.com."); addRecordToLW(res, "a.gtld-servers.com.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); } return 1; } else if (domain == target && ip == ComboAddress("192.0.2.2:53")) { setLWResult(res, 0, true, false, true); if (type == QType::NS) { addRecordToLW(res, domain, QType::NS, "ns1.powerdns.com."); } else { addRecordToLW(res, domain, QType::A, targetAddr.toString(), DNSResourceRecord::ANSWER, 3600); } /* No RRSIG in a now (thanks to TA) Secure zone -> Bogus*/ return 1; } } return 0; }); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); /* should be insecure but we have a TA for powerdns.com., but no RRSIG so Bogus */ BOOST_CHECK_EQUAL(sr->getValidationState(), Bogus); /* No RRSIG */ BOOST_REQUIRE_EQUAL(ret.size(), 1); BOOST_CHECK(ret[0].d_type == QType::A); BOOST_CHECK_EQUAL(queriesCount, 4); /* again, to test the cache */ ret.clear(); res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Bogus); BOOST_REQUIRE_EQUAL(ret.size(), 1); BOOST_CHECK(ret[0].d_type == QType::A); BOOST_CHECK_EQUAL(queriesCount, 4); } <API key>(test_dnssec_nta) { std::unique_ptr<SyncRes> sr; initSR(sr, true); setDNSSECValidation(sr, DNSSECMode::ValidateAll); primeHints(); const DNSName target("."); testkeysset_t keys; auto luaconfsCopy = g_luaconfs.getCopy(); luaconfsCopy.dsAnchors.clear(); generateKeyMaterial(g_rootdnsname, DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys, luaconfsCopy.dsAnchors); /* Add a NTA for "." */ luaconfsCopy.negAnchors[g_rootdnsname] = "NTA for Root"; g_luaconfs.setState(luaconfsCopy); size_t queriesCount = 0; sr->setAsyncCallback([target,&queriesCount,keys](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { queriesCount++; if (domain == target && type == QType::NS) { setLWResult(res, 0, true, false, true); char addr[] = "a.root-servers.net."; for (char idx = 'a'; idx <= 'm'; idx++) { addr[0] = idx; addRecordToLW(res, domain, QType::NS, std::string(addr), DNSResourceRecord::ANSWER, 3600); } addRRSIG(keys, res->d_records, domain, 300); addRecordToLW(res, "a.root-servers.net.", QType::A, "198.41.0.4", DNSResourceRecord::ADDITIONAL, 3600); addRecordToLW(res, "a.root-servers.net.", QType::AAAA, "2001:503:ba3e::2:30", DNSResourceRecord::ADDITIONAL, 3600); return 1; } else if (domain == target && type == QType::DNSKEY) { setLWResult(res, 0, true, false, true); /* No DNSKEY */ return 1; } return 0; }); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::NS), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Insecure); /* 13 NS + 1 RRSIG */ BOOST_REQUIRE_EQUAL(ret.size(), 14); BOOST_CHECK_EQUAL(queriesCount, 1); /* again, to test the cache */ ret.clear(); res = sr->beginResolve(target, QType(QType::NS), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Insecure); BOOST_REQUIRE_EQUAL(ret.size(), 14); BOOST_CHECK_EQUAL(queriesCount, 1); } <API key>(test_dnssec_no_ta) { std::unique_ptr<SyncRes> sr; initSR(sr, true); setDNSSECValidation(sr, DNSSECMode::ValidateAll); primeHints(); const DNSName target("."); testkeysset_t keys; /* Remove the root DS */ auto luaconfsCopy = g_luaconfs.getCopy(); luaconfsCopy.dsAnchors.clear(); g_luaconfs.setState(luaconfsCopy); size_t queriesCount = 0; sr->setAsyncCallback([target,&queriesCount,keys](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { queriesCount++; if (domain == target && type == QType::NS) { setLWResult(res, 0, true, false, true); char addr[] = "a.root-servers.net."; for (char idx = 'a'; idx <= 'm'; idx++) { addr[0] = idx; addRecordToLW(res, domain, QType::NS, std::string(addr), DNSResourceRecord::ANSWER, 3600); } addRecordToLW(res, "a.root-servers.net.", QType::A, "198.41.0.4", DNSResourceRecord::ADDITIONAL, 3600); addRecordToLW(res, "a.root-servers.net.", QType::AAAA, "2001:503:ba3e::2:30", DNSResourceRecord::ADDITIONAL, 3600); return 1; } return 0; }); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::NS), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Insecure); /* 13 NS + 0 RRSIG */ BOOST_REQUIRE_EQUAL(ret.size(), 13); BOOST_CHECK_EQUAL(queriesCount, 1); /* again, to test the cache */ ret.clear(); res = sr->beginResolve(target, QType(QType::NS), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Insecure); BOOST_REQUIRE_EQUAL(ret.size(), 13); BOOST_CHECK_EQUAL(queriesCount, 1); } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr, true); setDNSSECValidation(sr, DNSSECMode::ValidateAll); primeHints(); const DNSName target("powerdns.com."); testkeysset_t keys; auto luaconfsCopy = g_luaconfs.getCopy(); luaconfsCopy.dsAnchors.clear(); generateKeyMaterial(DNSName("."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys, luaconfsCopy.dsAnchors); generateKeyMaterial(DNSName("com."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys, luaconfsCopy.dsAnchors); generateKeyMaterial(DNSName("powerdns.com."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); g_luaconfs.setState(luaconfsCopy); size_t queriesCount = 0; sr->setAsyncCallback([target,&queriesCount,keys](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { queriesCount++; if (type == QType::DS || type == QType::DNSKEY) { return <API key>(res, domain, domain, type, keys); } else { setLWResult(res, 0, true, false, true); return 1; } return 0; }); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Bogus); BOOST_REQUIRE_EQUAL(ret.size(), 0); /* com|NS, powerdns.com|NS, powerdns.com|A */ BOOST_CHECK_EQUAL(queriesCount, 3); /* again, to test the cache */ ret.clear(); res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Bogus); BOOST_REQUIRE_EQUAL(ret.size(), 0); /* we don't store empty results */ BOOST_CHECK_EQUAL(queriesCount, 4); } <API key>(<API key>) { init(); testkeysset_t keys; generateKeyMaterial(DNSName("example.org."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); vector<DNSRecord> records; vector<shared_ptr<DNSRecordContent>> recordContents; vector<shared_ptr<RRSIGRecordContent>> signatureContents; /* No wrap test case: a.example.org. -> d.example.org. denies the existence of b.example.org. */ addNSECRecordToLW(DNSName("a.example.org."), DNSName("d.example.org"), { QType::A, QType::TXT, QType::RRSIG, QType::NSEC }, 600, records); recordContents.push_back(records.at(0).d_content); addRRSIG(keys, records, DNSName("example.org."), 300); signatureContents.push_back(getRR<RRSIGRecordContent>(records.at(1))); records.clear(); ContentSigPair pair; pair.records = recordContents; pair.signatures = signatureContents; cspmap_t denialMap; denialMap[std::make_pair(DNSName("a.example.org."), QType::NSEC)] = pair; /* add wildcard denial */ recordContents.clear(); signatureContents.clear(); addNSECRecordToLW(DNSName("example.org."), DNSName("+.example.org"), { QType::A, QType::TXT, QType::RRSIG, QType::NSEC }, 600, records); recordContents.push_back(records.at(0).d_content); addRRSIG(keys, records, DNSName("example.org."), 300); signatureContents.push_back(getRR<RRSIGRecordContent>(records.at(1))); records.clear(); pair.records = recordContents; pair.signatures = signatureContents; denialMap[std::make_pair(DNSName("example.org."), QType::NSEC)] = pair; dState denialState = getDenial(denialMap, DNSName("b.example.org."), QType::A, false, false); BOOST_CHECK_EQUAL(denialState, NXDOMAIN); denialState = getDenial(denialMap, DNSName("d.example.org."), QType::A, false, false); /* let's check that d.example.org. is not denied by this proof */ BOOST_CHECK_EQUAL(denialState, NODATA); } <API key>(<API key>) { init(); testkeysset_t keys; generateKeyMaterial(DNSName("example.org."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); vector<DNSRecord> records; vector<shared_ptr<DNSRecordContent>> recordContents; vector<shared_ptr<RRSIGRecordContent>> signatureContents; /* Wrap case 1 test case: z.example.org. -> b.example.org. denies the existence of a.example.org. */ addNSECRecordToLW(DNSName("z.example.org."), DNSName("b.example.org"), { QType::A, QType::TXT, QType::RRSIG, QType::NSEC }, 600, records); recordContents.push_back(records.at(0).d_content); addRRSIG(keys, records, DNSName("example.org."), 300); signatureContents.push_back(getRR<RRSIGRecordContent>(records.at(1))); records.clear(); ContentSigPair pair; pair.records = recordContents; pair.signatures = signatureContents; cspmap_t denialMap; denialMap[std::make_pair(DNSName("z.example.org."), QType::NSEC)] = pair; dState denialState = getDenial(denialMap, DNSName("a.example.org."), QType::A, false, false); BOOST_CHECK_EQUAL(denialState, NXDOMAIN); denialState = getDenial(denialMap, DNSName("d.example.org."), QType::A, false, false); /* let's check that d.example.org. is not denied by this proof */ BOOST_CHECK_EQUAL(denialState, NODATA); } <API key>(<API key>) { init(); testkeysset_t keys; generateKeyMaterial(DNSName("example.org."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); vector<DNSRecord> records; vector<shared_ptr<DNSRecordContent>> recordContents; vector<shared_ptr<RRSIGRecordContent>> signatureContents; /* Wrap case 2 test case: y.example.org. -> a.example.org. denies the existence of z.example.org. */ addNSECRecordToLW(DNSName("y.example.org."), DNSName("a.example.org"), { QType::A, QType::TXT, QType::RRSIG, QType::NSEC }, 600, records); recordContents.push_back(records.at(0).d_content); addRRSIG(keys, records, DNSName("example.org."), 300); signatureContents.push_back(getRR<RRSIGRecordContent>(records.at(1))); records.clear(); ContentSigPair pair; pair.records = recordContents; pair.signatures = signatureContents; cspmap_t denialMap; denialMap[std::make_pair(DNSName("y.example.org."), QType::NSEC)] = pair; dState denialState = getDenial(denialMap, DNSName("z.example.org."), QType::A, false, false); BOOST_CHECK_EQUAL(denialState, NXDOMAIN); denialState = getDenial(denialMap, DNSName("d.example.org."), QType::A, false, false); /* let's check that d.example.org. is not denied by this proof */ BOOST_CHECK_EQUAL(denialState, NODATA); } <API key>(<API key>) { init(); testkeysset_t keys; generateKeyMaterial(DNSName("example.org."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); vector<DNSRecord> records; vector<shared_ptr<DNSRecordContent>> recordContents; vector<shared_ptr<RRSIGRecordContent>> signatureContents; /* Only one NSEC in the whole zone test case: a.example.org. -> a.example.org. denies the existence of b.example.org. */ addNSECRecordToLW(DNSName("a.example.org."), DNSName("a.example.org"), { QType::A, QType::TXT, QType::RRSIG, QType::NSEC }, 600, records); recordContents.push_back(records.at(0).d_content); addRRSIG(keys, records, DNSName("example.org."), 300); signatureContents.push_back(getRR<RRSIGRecordContent>(records.at(1))); records.clear(); ContentSigPair pair; pair.records = recordContents; pair.signatures = signatureContents; cspmap_t denialMap; denialMap[std::make_pair(DNSName("a.example.org."), QType::NSEC)] = pair; dState denialState = getDenial(denialMap, DNSName("b.example.org."), QType::A, false, false); BOOST_CHECK_EQUAL(denialState, NXDOMAIN); denialState = getDenial(denialMap, DNSName("a.example.org."), QType::A, false, false); /* let's check that d.example.org. is not denied by this proof */ BOOST_CHECK_EQUAL(denialState, NODATA); } <API key>(<API key>) { init(); testkeysset_t keys; generateKeyMaterial(DNSName("."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); vector<DNSRecord> records; vector<shared_ptr<DNSRecordContent>> recordContents; vector<shared_ptr<RRSIGRecordContent>> signatureContents; /* The RRSIG from "." denies the existence of anything between a. and c., including b. */ addNSECRecordToLW(DNSName("a."), DNSName("c."), { QType::NS }, 600, records); recordContents.push_back(records.at(0).d_content); addRRSIG(keys, records, DNSName("."), 300); signatureContents.push_back(getRR<RRSIGRecordContent>(records.at(1))); records.clear(); ContentSigPair pair; pair.records = recordContents; pair.signatures = signatureContents; cspmap_t denialMap; denialMap[std::make_pair(DNSName("a."), QType::NSEC)] = pair; /* add wildcard denial */ recordContents.clear(); signatureContents.clear(); addNSECRecordToLW(DNSName("."), DNSName("+"), { QType::A, QType::TXT, QType::RRSIG, QType::NSEC }, 600, records); recordContents.push_back(records.at(0).d_content); addRRSIG(keys, records, DNSName("."), 300); signatureContents.push_back(getRR<RRSIGRecordContent>(records.at(1))); records.clear(); pair.records = recordContents; pair.signatures = signatureContents; denialMap[std::make_pair(DNSName("."), QType::NSEC)] = pair; dState denialState = getDenial(denialMap, DNSName("b."), QType::A, false, false); BOOST_CHECK_EQUAL(denialState, NXDOMAIN); } <API key>(<API key>) { init(); testkeysset_t keys; generateKeyMaterial(DNSName("."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); vector<DNSRecord> records; vector<shared_ptr<DNSRecordContent>> recordContents; vector<shared_ptr<RRSIGRecordContent>> signatureContents; /* The RRSIG from "." denies the existence of any type except NS at a. However since it's an ancestor delegation NSEC (NS bit set, SOA bit clear, signer field that is shorter than the owner name of the NSEC RR) it can't be used to deny anything except the whole name or a DS. */ addNSECRecordToLW(DNSName("a."), DNSName("b."), { QType::NS }, 600, records); recordContents.push_back(records.at(0).d_content); addRRSIG(keys, records, DNSName("."), 300); signatureContents.push_back(getRR<RRSIGRecordContent>(records.at(1))); records.clear(); ContentSigPair pair; pair.records = recordContents; pair.signatures = signatureContents; cspmap_t denialMap; denialMap[std::make_pair(DNSName("a."), QType::NSEC)] = pair; /* RFC 6840 section 4.1 "Clarifications on Nonexistence Proofs": Ancestor delegation NSEC or NSEC3 RRs MUST NOT be used to assume nonexistence of any RRs below that zone cut, which include all RRs at that (original) owner name other than DS RRs, and all RRs below that owner name regardless of type. */ dState denialState = getDenial(denialMap, DNSName("a."), QType::A, false, false); /* no data means the qname/qtype is not denied, because an ancestor delegation NSEC can only deny the DS */ BOOST_CHECK_EQUAL(denialState, NODATA); /* it can not be used to deny any RRs below that owner name either */ denialState = getDenial(denialMap, DNSName("sub.a."), QType::A, false, false); BOOST_CHECK_EQUAL(denialState, NODATA); denialState = getDenial(denialMap, DNSName("a."), QType::DS, true, true); BOOST_CHECK_EQUAL(denialState, NXQTYPE); } <API key>(<API key>) { init(); testkeysset_t keys; generateKeyMaterial(DNSName("."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); vector<DNSRecord> records; vector<shared_ptr<DNSRecordContent>> recordContents; vector<shared_ptr<RRSIGRecordContent>> signatureContents; /* * RFC 5155 section 8.9: * If there is an NSEC3 RR present in the response that matches the * delegation name, then the validator MUST ensure that the NS bit is * set and that the DS bit is not set in the Type Bit Maps field of the * NSEC3 RR. */ /* The RRSIG from "." denies the existence of any type at a. NS should be set if it was proving an insecure delegation, let's check that we correctly detect that it's not. */ addNSECRecordToLW(DNSName("a."), DNSName("b."), { }, 600, records); recordContents.push_back(records.at(0).d_content); addRRSIG(keys, records, DNSName("."), 300); signatureContents.push_back(getRR<RRSIGRecordContent>(records.at(1))); records.clear(); ContentSigPair pair; pair.records = recordContents; pair.signatures = signatureContents; cspmap_t denialMap; denialMap[std::make_pair(DNSName("a."), QType::NSEC)] = pair; /* Insecure because the NS is not set, so while it does denies the DS, it can't prove an insecure delegation */ dState denialState = getDenial(denialMap, DNSName("a."), QType::DS, true, true); BOOST_CHECK_EQUAL(denialState, NODATA); } <API key>(<API key>) { init(); testkeysset_t keys; generateKeyMaterial(DNSName("powerdns.com."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); vector<DNSRecord> records; vector<shared_ptr<DNSRecordContent>> recordContents; vector<shared_ptr<RRSIGRecordContent>> signatureContents; addNSECRecordToLW(DNSName("a.powerdns.com."), DNSName("a.c.powerdns.com."), { QType::CNAME }, 600, records); recordContents.push_back(records.at(0).d_content); addRRSIG(keys, records, DNSName("powerdns.com."), 300); signatureContents.push_back(getRR<RRSIGRecordContent>(records.at(1))); records.clear(); ContentSigPair pair; pair.records = recordContents; pair.signatures = signatureContents; cspmap_t denialMap; denialMap[std::make_pair(DNSName("a.powerdns.com."), QType::NSEC)] = pair; /* this NSEC is not valid to deny a.powerdns.com|A since it states that a CNAME exists */ dState denialState = getDenial(denialMap, DNSName("a.powerdns.com."), QType::A, true, true); BOOST_CHECK_EQUAL(denialState, NODATA); } <API key>(<API key>) { init(); testkeysset_t keys; generateKeyMaterial(DNSName("powerdns.com."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); vector<DNSRecord> records; vector<shared_ptr<DNSRecordContent>> recordContents; vector<shared_ptr<RRSIGRecordContent>> signatureContents; <API key>(DNSName("a.powerdns.com."), DNSName("powerdns.com."), "whatever", { QType::CNAME }, 600, records); recordContents.push_back(records.at(0).d_content); addRRSIG(keys, records, DNSName("powerdns.com."), 300); signatureContents.push_back(getRR<RRSIGRecordContent>(records.at(1))); ContentSigPair pair; pair.records = recordContents; pair.signatures = signatureContents; cspmap_t denialMap; denialMap[std::make_pair(records.at(0).d_name, records.at(0).d_type)] = pair; records.clear(); /* this NSEC3 is not valid to deny a.powerdns.com|A since it states that a CNAME exists */ dState denialState = getDenial(denialMap, DNSName("a.powerdns.com."), QType::A, false, true); BOOST_CHECK_EQUAL(denialState, NODATA); } <API key>(<API key>) { init(); testkeysset_t keys; generateKeyMaterial(DNSName("powerdns.com."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); vector<DNSRecord> records; vector<shared_ptr<DNSRecordContent>> recordContents; vector<shared_ptr<RRSIGRecordContent>> signatureContents; addNSECRecordToLW(DNSName("a.powerdns.com."), DNSName("d.powerdns.com"), { QType::A, QType::TXT, QType::RRSIG, QType::NSEC }, 600, records); recordContents.push_back(records.at(0).d_content); addRRSIG(keys, records, DNSName("powerdns.com."), 300); signatureContents.push_back(getRR<RRSIGRecordContent>(records.at(1))); records.clear(); ContentSigPair pair; pair.records = recordContents; pair.signatures = signatureContents; cspmap_t denialMap; denialMap[std::make_pair(DNSName("a.powerdns.com."), QType::NSEC)] = pair; dState denialState = getDenial(denialMap, DNSName("b.powerdns.com."), QType::A, false, false); BOOST_CHECK_EQUAL(denialState, NODATA); } <API key>(<API key>) { init(); testkeysset_t keys; generateKeyMaterial(DNSName("powerdns.com."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); vector<DNSRecord> records; vector<shared_ptr<DNSRecordContent>> recordContents; vector<shared_ptr<RRSIGRecordContent>> signatureContents; <API key>(DNSName("a.powerdns.com."), DNSName("powerdns.com."), { QType::A, QType::TXT, QType::RRSIG, QType::NSEC }, 600, records); recordContents.push_back(records.at(0).d_content); addRRSIG(keys, records, DNSName("powerdns.com."), 300); signatureContents.push_back(getRR<RRSIGRecordContent>(records.at(1))); ContentSigPair pair; pair.records = recordContents; pair.signatures = signatureContents; cspmap_t denialMap; denialMap[std::make_pair(records.at(0).d_name, records.at(0).d_type)] = pair; /* Add NSEC3 for the closest encloser */ recordContents.clear(); signatureContents.clear(); records.clear(); <API key>(DNSName("powerdns.com."), DNSName("powerdns.com."), "whatever", { QType::A, QType::TXT, QType::RRSIG, QType::NSEC }, 600, records); recordContents.push_back(records.at(0).d_content); addRRSIG(keys, records, DNSName("powerdns.com."), 300); signatureContents.push_back(getRR<RRSIGRecordContent>(records.at(1))); pair.records = recordContents; pair.signatures = signatureContents; denialMap[std::make_pair(records.at(0).d_name, records.at(0).d_type)] = pair; dState denialState = getDenial(denialMap, DNSName("b.powerdns.com."), QType::A, false, false); BOOST_CHECK_EQUAL(denialState, NODATA); } <API key>(<API key>) { init(); testkeysset_t keys; generateKeyMaterial(DNSName("powerdns.com."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); vector<DNSRecord> records; vector<shared_ptr<DNSRecordContent>> recordContents; vector<shared_ptr<RRSIGRecordContent>> signatureContents; addNSECRecordToLW(DNSName("a.powerdns.com."), DNSName("a.c.powerdns.com."), { QType::A }, 600, records); recordContents.push_back(records.at(0).d_content); addRRSIG(keys, records, DNSName("powerdns.com."), 300); signatureContents.push_back(getRR<RRSIGRecordContent>(records.at(1))); records.clear(); ContentSigPair pair; pair.records = recordContents; pair.signatures = signatureContents; cspmap_t denialMap; denialMap[std::make_pair(DNSName("a.powerdns.com."), QType::NSEC)] = pair; /* this NSEC is valid to prove a NXQTYPE at c.powerdns.com because it proves that it is an ENT */ dState denialState = getDenial(denialMap, DNSName("c.powerdns.com."), QType::AAAA, true, true); BOOST_CHECK_EQUAL(denialState, NXQTYPE); /* this NSEC is not valid to prove a NXQTYPE at b.powerdns.com, it could prove a NXDOMAIN if it had an additional wildcard denial */ denialState = getDenial(denialMap, DNSName("b.powerdns.com."), QType::AAAA, true, true); BOOST_CHECK_EQUAL(denialState, NODATA); /* this NSEC is not valid to prove a NXQTYPE for QType::A at a.c.powerdns.com either */ denialState = getDenial(denialMap, DNSName("a.c.powerdns.com."), QType::A, true, true); BOOST_CHECK_EQUAL(denialState, NODATA); /* if we add the wildcard denial proof, we should get a NXDOMAIN proof for b.powerdns.com */ recordContents.clear(); signatureContents.clear(); addNSECRecordToLW(DNSName(").powerdns.com."), DNSName("+.powerdns.com."), { }, 600, records); recordContents.push_back(records.at(0).d_content); addRRSIG(keys, records, DNSName("powerdns.com."), 300); signatureContents.push_back(getRR<RRSIGRecordContent>(records.at(1))); records.clear(); pair.records = recordContents; pair.signatures = signatureContents; denialMap[std::make_pair(DNSName(").powerdns.com."), QType::NSEC)] = pair; denialState = getDenial(denialMap, DNSName("b.powerdns.com."), QType::A, true, false); BOOST_CHECK_EQUAL(denialState, NXDOMAIN); } <API key>(<API key>) { init(); testkeysset_t keys; generateKeyMaterial(DNSName("."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); vector<DNSRecord> records; vector<shared_ptr<DNSRecordContent>> recordContents; vector<shared_ptr<RRSIGRecordContent>> signatureContents; /* The RRSIG from "." denies the existence of any type except NS at a. However since it's an ancestor delegation NSEC (NS bit set, SOA bit clear, signer field that is shorter than the owner name of the NSEC RR) it can't be used to deny anything except the whole name or a DS. */ <API key>(DNSName("a."), DNSName("."), "whatever", { QType::NS }, 600, records); recordContents.push_back(records.at(0).d_content); addRRSIG(keys, records, DNSName("."), 300); signatureContents.push_back(getRR<RRSIGRecordContent>(records.at(1))); ContentSigPair pair; pair.records = recordContents; pair.signatures = signatureContents; cspmap_t denialMap; denialMap[std::make_pair(records.at(0).d_name, records.at(0).d_type)] = pair; records.clear(); /* RFC 6840 section 4.1 "Clarifications on Nonexistence Proofs": Ancestor delegation NSEC or NSEC3 RRs MUST NOT be used to assume nonexistence of any RRs below that zone cut, which include all RRs at that (original) owner name other than DS RRs, and all RRs below that owner name regardless of type. */ dState denialState = getDenial(denialMap, DNSName("a."), QType::A, false, true); /* no data means the qname/qtype is not denied, because an ancestor delegation NSEC3 can only deny the DS */ BOOST_CHECK_EQUAL(denialState, NODATA); denialState = getDenial(denialMap, DNSName("a."), QType::DS, true, true); BOOST_CHECK_EQUAL(denialState, NXQTYPE); /* it can not be used to deny any RRs below that owner name either */ /* Add NSEC3 for the next closer */ recordContents.clear(); signatureContents.clear(); records.clear(); <API key>(DNSName("sub.a."), DNSName("."), { QType::A, QType::TXT, QType::RRSIG, QType::NSEC3 }, 600, records); recordContents.push_back(records.at(0).d_content); addRRSIG(keys, records, DNSName("."), 300); signatureContents.push_back(getRR<RRSIGRecordContent>(records.at(1))); pair.records = recordContents; pair.signatures = signatureContents; denialMap[std::make_pair(records.at(0).d_name, records.at(0).d_type)] = pair; /* add wildcard denial */ recordContents.clear(); signatureContents.clear(); records.clear(); <API key>(DNSName("*.a."), DNSName("."), { QType::A, QType::TXT, QType::RRSIG, QType::NSEC3 }, 600, records); recordContents.push_back(records.at(0).d_content); addRRSIG(keys, records, DNSName("."), 300); signatureContents.push_back(getRR<RRSIGRecordContent>(records.at(1))); pair.records = recordContents; pair.signatures = signatureContents; denialMap[std::make_pair(records.at(0).d_name, records.at(0).d_type)] = pair; denialState = getDenial(denialMap, DNSName("sub.a."), QType::A, false, true); BOOST_CHECK_EQUAL(denialState, NODATA); } <API key>(<API key>) { init(); testkeysset_t keys; generateKeyMaterial(DNSName("."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); vector<DNSRecord> records; vector<shared_ptr<DNSRecordContent>> recordContents; vector<shared_ptr<RRSIGRecordContent>> signatureContents; /* adding a NSEC3 with more iterations that we support */ <API key>(DNSName("a."), DNSName("."), "whatever", { QType::AAAA }, 600, records, <API key> + 100); recordContents.push_back(records.at(0).d_content); addRRSIG(keys, records, DNSName("."), 300); signatureContents.push_back(getRR<RRSIGRecordContent>(records.at(1))); ContentSigPair pair; pair.records = recordContents; pair.signatures = signatureContents; cspmap_t denialMap; denialMap[std::make_pair(records.at(0).d_name, records.at(0).d_type)] = pair; records.clear(); dState denialState = getDenial(denialMap, DNSName("a."), QType::A, false, true); /* since we refuse to compute more than <API key> iterations, it should be Insecure */ BOOST_CHECK_EQUAL(denialState, INSECURE); } <API key>(<API key>) { init(); testkeysset_t keys; generateKeyMaterial(DNSName("."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); vector<DNSRecord> records; vector<shared_ptr<DNSRecordContent>> recordContents; vector<shared_ptr<RRSIGRecordContent>> signatureContents; /* * RFC 5155 section 8.9: * If there is an NSEC3 RR present in the response that matches the * delegation name, then the validator MUST ensure that the NS bit is * set and that the DS bit is not set in the Type Bit Maps field of the * NSEC3 RR. */ /* The RRSIG from "." denies the existence of any type at a. NS should be set if it was proving an insecure delegation, let's check that we correctly detect that it's not. */ <API key>(DNSName("a."), DNSName("."), "whatever", { }, 600, records); recordContents.push_back(records.at(0).d_content); addRRSIG(keys, records, DNSName("."), 300); signatureContents.push_back(getRR<RRSIGRecordContent>(records.at(1))); ContentSigPair pair; pair.records = recordContents; pair.signatures = signatureContents; cspmap_t denialMap; denialMap[std::make_pair(records.at(0).d_name, records.at(0).d_type)] = pair; records.clear(); /* Insecure because the NS is not set, so while it does denies the DS, it can't prove an insecure delegation */ dState denialState = getDenial(denialMap, DNSName("a."), QType::DS, true, true); BOOST_CHECK_EQUAL(denialState, NODATA); } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr, true); setDNSSECValidation(sr, DNSSECMode::ValidateAll); primeHints(); const DNSName target("com."); testkeysset_t keys; auto luaconfsCopy = g_luaconfs.getCopy(); luaconfsCopy.dsAnchors.clear(); generateKeyMaterial(g_rootdnsname, DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys, luaconfsCopy.dsAnchors); generateKeyMaterial(DNSName("com."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); g_luaconfs.setState(luaconfsCopy); size_t queriesCount = 0; sr->setAsyncCallback([target,&queriesCount,keys](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { queriesCount++; DNSName auth = domain; auth.chopOff(); if (type == QType::DS || type == QType::DNSKEY) { return <API key>(res, domain, auth, type, keys); } else { setLWResult(res, RCode::NoError, true, false, true); addRecordToLW(res, domain, QType::SOA, "pdns-public-ns1.powerdns.com. pieter\\.lexis.powerdns.com. 2017032301 10800 3600 604800 3600", DNSResourceRecord::AUTHORITY, 3600); addRRSIG(keys, res->d_records, domain, 300); addNSECRecordToLW(domain, DNSName("z."), { QType::NSEC, QType::RRSIG }, 600, res->d_records); addRRSIG(keys, res->d_records, domain, 1); return 1; } return 0; }); const time_t now = sr->getNow().tv_sec; vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Secure); BOOST_REQUIRE_EQUAL(ret.size(), 4); BOOST_CHECK_EQUAL(queriesCount, 4); /* check that the entry has not been negatively cached for longer than the RRSIG validity */ NegCache::NegCacheEntry ne; BOOST_CHECK_EQUAL(SyncRes::t_sstorage.negcache.size(), 1); BOOST_REQUIRE_EQUAL(SyncRes::t_sstorage.negcache.get(target, QType(QType::A), sr->getNow(), ne), true); BOOST_CHECK_EQUAL(ne.d_ttd, now + 1); BOOST_CHECK_EQUAL(ne.d_validationState, Secure); BOOST_CHECK_EQUAL(ne.authoritySOA.records.size(), 1); BOOST_CHECK_EQUAL(ne.authoritySOA.signatures.size(), 1); BOOST_CHECK_EQUAL(ne.DNSSECRecords.records.size(), 1); BOOST_CHECK_EQUAL(ne.DNSSECRecords.signatures.size(), 1); /* again, to test the cache */ ret.clear(); res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Secure); BOOST_REQUIRE_EQUAL(ret.size(), 4); BOOST_CHECK_EQUAL(queriesCount, 4); } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr, true); setDNSSECValidation(sr, DNSSECMode::ValidateAll); primeHints(); const DNSName target("com."); const ComboAddress targetAddr("192.0.2.42"); testkeysset_t keys; auto luaconfsCopy = g_luaconfs.getCopy(); luaconfsCopy.dsAnchors.clear(); generateKeyMaterial(g_rootdnsname, DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys, luaconfsCopy.dsAnchors); generateKeyMaterial(DNSName("com."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); g_luaconfs.setState(luaconfsCopy); size_t queriesCount = 0; sr->setAsyncCallback([target,targetAddr,&queriesCount,keys](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { queriesCount++; DNSName auth = domain; auth.chopOff(); if (type == QType::DS || type == QType::DNSKEY) { return <API key>(res, domain, auth, type, keys); } else { setLWResult(res, RCode::NoError, true, false, true); addRecordToLW(res, domain, QType::A, targetAddr.toString(), DNSResourceRecord::ANSWER, 3600); addRRSIG(keys, res->d_records, domain, 1); return 1; } return 0; }); const time_t now = sr->getNow().tv_sec; vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Secure); BOOST_REQUIRE_EQUAL(ret.size(), 2); BOOST_CHECK_EQUAL(queriesCount, 4); /* check that the entry has not been cached for longer than the RRSIG validity */ const ComboAddress who; vector<DNSRecord> cached; vector<std::shared_ptr<RRSIGRecordContent>> signatures; BOOST_REQUIRE_EQUAL(t_RC->get(now, target, QType(QType::A), true, &cached, who, &signatures), 1); BOOST_REQUIRE_EQUAL(cached.size(), 1); BOOST_REQUIRE_EQUAL(signatures.size(), 1); BOOST_CHECK_EQUAL((cached[0].d_ttl - now), 1); /* again, to test the cache */ ret.clear(); res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Secure); BOOST_REQUIRE_EQUAL(ret.size(), 2); BOOST_CHECK_EQUAL(queriesCount, 4); } <API key>(<API key>) { /* Validation is optional, and the first query does not ask for it, so the answer is cached as Indeterminate. The second query asks for validation, answer should be marked as Secure. */ std::unique_ptr<SyncRes> sr; initSR(sr, true); setDNSSECValidation(sr, DNSSECMode::Process); primeHints(); const DNSName target("com."); testkeysset_t keys; auto luaconfsCopy = g_luaconfs.getCopy(); luaconfsCopy.dsAnchors.clear(); generateKeyMaterial(g_rootdnsname, DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys, luaconfsCopy.dsAnchors); g_luaconfs.setState(luaconfsCopy); size_t queriesCount = 0; sr->setAsyncCallback([target,&queriesCount,keys](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { queriesCount++; if (type == QType::DS || type == QType::DNSKEY) { return <API key>(res, domain, domain, type, keys, false); } else { if (domain == target && type == QType::A) { setLWResult(res, 0, true, false, true); addRecordToLW(res, target, QType::A, "192.0.2.1"); addRRSIG(keys, res->d_records, DNSName("."), 300); return 1; } } return 0; }); vector<DNSRecord> ret; /* first query does not require validation */ sr-><API key>(false); int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Indeterminate); BOOST_REQUIRE_EQUAL(ret.size(), 2); for (const auto& record : ret) { BOOST_CHECK(record.d_type == QType::A || record.d_type == QType::RRSIG); } BOOST_CHECK_EQUAL(queriesCount, 1); ret.clear(); /* second one _does_ require validation */ sr-><API key>(true); res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Secure); BOOST_REQUIRE_EQUAL(ret.size(), 2); for (const auto& record : ret) { BOOST_CHECK(record.d_type == QType::A || record.d_type == QType::RRSIG); } BOOST_CHECK_EQUAL(queriesCount, 3); } <API key>(<API key>) { /* Validation is optional, and the first query does not ask for it, so the answer is cached as Indeterminate. The second query asks for validation, answer should be marked as Insecure. */ std::unique_ptr<SyncRes> sr; initSR(sr, true); setDNSSECValidation(sr, DNSSECMode::Process); primeHints(); const DNSName target("com."); testkeysset_t keys; auto luaconfsCopy = g_luaconfs.getCopy(); luaconfsCopy.dsAnchors.clear(); g_luaconfs.setState(luaconfsCopy); size_t queriesCount = 0; sr->setAsyncCallback([target,&queriesCount,keys](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { queriesCount++; if (type == QType::DS || type == QType::DNSKEY) { return <API key>(res, domain, domain, type, keys, false); } else { if (domain == target && type == QType::A) { setLWResult(res, 0, true, false, true); addRecordToLW(res, target, QType::A, "192.0.2.1"); return 1; } } return 0; }); vector<DNSRecord> ret; /* first query does not require validation */ sr-><API key>(false); int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Indeterminate); BOOST_REQUIRE_EQUAL(ret.size(), 1); for (const auto& record : ret) { BOOST_CHECK(record.d_type == QType::A); } BOOST_CHECK_EQUAL(queriesCount, 1); ret.clear(); /* second one _does_ require validation */ sr-><API key>(true); res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Insecure); BOOST_REQUIRE_EQUAL(ret.size(), 1); for (const auto& record : ret) { BOOST_CHECK(record.d_type == QType::A); } BOOST_CHECK_EQUAL(queriesCount, 1); } <API key>(<API key>) { /* Validation is optional, and the first query does not ask for it, so the answer is cached as Indeterminate. The second query asks for validation, answer should be marked as Bogus. */ std::unique_ptr<SyncRes> sr; initSR(sr, true); setDNSSECValidation(sr, DNSSECMode::Process); primeHints(); const DNSName target("com."); testkeysset_t keys; auto luaconfsCopy = g_luaconfs.getCopy(); luaconfsCopy.dsAnchors.clear(); generateKeyMaterial(g_rootdnsname, DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys, luaconfsCopy.dsAnchors); g_luaconfs.setState(luaconfsCopy); size_t queriesCount = 0; sr->setAsyncCallback([target,&queriesCount,keys](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { queriesCount++; if (type == QType::DS || type == QType::DNSKEY) { return <API key>(res, domain, domain, type, keys, false); } else { if (domain == target && type == QType::A) { setLWResult(res, 0, true, false, true); addRecordToLW(res, target, QType::A, "192.0.2.1"); /* no RRSIG */ return 1; } } return 0; }); vector<DNSRecord> ret; /* first query does not require validation */ sr-><API key>(false); int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Indeterminate); BOOST_REQUIRE_EQUAL(ret.size(), 1); for (const auto& record : ret) { BOOST_CHECK(record.d_type == QType::A); } BOOST_CHECK_EQUAL(queriesCount, 1); ret.clear(); /* second one _does_ require validation */ sr-><API key>(true); res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Bogus); BOOST_REQUIRE_EQUAL(ret.size(), 1); for (const auto& record : ret) { BOOST_CHECK(record.d_type == QType::A); } BOOST_CHECK_EQUAL(queriesCount, 3); } <API key>(<API key>) { /* Validation is optional, and the first query does not ask for it, so the answer is cached as Indeterminate. The second query asks for validation, answer should be marked as Secure. */ std::unique_ptr<SyncRes> sr; initSR(sr, true); setDNSSECValidation(sr, DNSSECMode::Process); primeHints(); const DNSName target("com."); const DNSName cnameTarget("cname-com."); testkeysset_t keys; auto luaconfsCopy = g_luaconfs.getCopy(); luaconfsCopy.dsAnchors.clear(); generateKeyMaterial(g_rootdnsname, DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys, luaconfsCopy.dsAnchors); g_luaconfs.setState(luaconfsCopy); size_t queriesCount = 0; sr->setAsyncCallback([target,cnameTarget,&queriesCount,keys](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { queriesCount++; if (type == QType::DS || type == QType::DNSKEY) { return <API key>(res, domain, domain, type, keys, false); } else { if (domain == target && type == QType::A) { setLWResult(res, 0, true, false, true); addRecordToLW(res, target, QType::CNAME, cnameTarget.toString()); addRRSIG(keys, res->d_records, DNSName("."), 300); addRecordToLW(res, cnameTarget, QType::A, "192.0.2.1"); addRRSIG(keys, res->d_records, DNSName("."), 300); return 1; } else if (domain == cnameTarget && type == QType::A) { setLWResult(res, 0, true, false, true); addRecordToLW(res, cnameTarget, QType::A, "192.0.2.1"); addRRSIG(keys, res->d_records, DNSName("."), 300); return 1; } } return 0; }); vector<DNSRecord> ret; /* first query does not require validation */ sr-><API key>(false); int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Indeterminate); BOOST_REQUIRE_EQUAL(ret.size(), 4); for (const auto& record : ret) { BOOST_CHECK(record.d_type == QType::CNAME || record.d_type == QType::A || record.d_type == QType::RRSIG); } BOOST_CHECK_EQUAL(queriesCount, 2); ret.clear(); /* second one _does_ require validation */ sr-><API key>(true); res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Secure); BOOST_REQUIRE_EQUAL(ret.size(), 4); for (const auto& record : ret) { BOOST_CHECK(record.d_type == QType::CNAME || record.d_type == QType::A || record.d_type == QType::RRSIG); } BOOST_CHECK_EQUAL(queriesCount, 5); } <API key>(<API key>) { /* Validation is optional, and the first query does not ask for it, so the answer is cached as Indeterminate. The second query asks for validation, answer should be marked as Insecure. */ std::unique_ptr<SyncRes> sr; initSR(sr, true); setDNSSECValidation(sr, DNSSECMode::Process); primeHints(); const DNSName target("com."); const DNSName cnameTarget("cname-com."); testkeysset_t keys; auto luaconfsCopy = g_luaconfs.getCopy(); luaconfsCopy.dsAnchors.clear(); g_luaconfs.setState(luaconfsCopy); size_t queriesCount = 0; sr->setAsyncCallback([target,cnameTarget,&queriesCount,keys](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { queriesCount++; if (type == QType::DS || type == QType::DNSKEY) { return <API key>(res, domain, domain, type, keys, false); } else { if (domain == target && type == QType::A) { setLWResult(res, 0, true, false, true); addRecordToLW(res, target, QType::CNAME, cnameTarget.toString()); addRecordToLW(res, cnameTarget, QType::A, "192.0.2.1"); return 1; } else if (domain == cnameTarget && type == QType::A) { setLWResult(res, 0, true, false, true); addRecordToLW(res, cnameTarget, QType::A, "192.0.2.1"); return 1; } } return 0; }); vector<DNSRecord> ret; /* first query does not require validation */ sr-><API key>(false); int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Indeterminate); BOOST_REQUIRE_EQUAL(ret.size(), 2); for (const auto& record : ret) { BOOST_CHECK(record.d_type == QType::CNAME || record.d_type == QType::A); } BOOST_CHECK_EQUAL(queriesCount, 2); ret.clear(); /* second one _does_ require validation */ sr-><API key>(true); res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Insecure); BOOST_REQUIRE_EQUAL(ret.size(), 2); for (const auto& record : ret) { BOOST_CHECK(record.d_type == QType::CNAME || record.d_type == QType::A); } BOOST_CHECK_EQUAL(queriesCount, 2); } <API key>(<API key>) { /* Validation is optional, and the first query does not ask for it, so the answer is cached as Indeterminate. The second query asks for validation, answer should be marked as Bogus. */ std::unique_ptr<SyncRes> sr; initSR(sr, true); setDNSSECValidation(sr, DNSSECMode::Process); primeHints(); const DNSName target("com."); const DNSName cnameTarget("cname-com."); testkeysset_t keys; auto luaconfsCopy = g_luaconfs.getCopy(); luaconfsCopy.dsAnchors.clear(); generateKeyMaterial(g_rootdnsname, DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys, luaconfsCopy.dsAnchors); g_luaconfs.setState(luaconfsCopy); size_t queriesCount = 0; sr->setAsyncCallback([target,cnameTarget,&queriesCount,keys](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { queriesCount++; if (type == QType::DS || type == QType::DNSKEY) { return <API key>(res, domain, domain, type, keys, false); } else { if (domain == target && type == QType::A) { setLWResult(res, 0, true, false, true); addRecordToLW(res, target, QType::CNAME, cnameTarget.toString()); addRecordToLW(res, cnameTarget, QType::A, "192.0.2.1"); /* no RRSIG */ return 1; } else if (domain == cnameTarget && type == QType::A) { setLWResult(res, 0, true, false, true); addRecordToLW(res, cnameTarget, QType::A, "192.0.2.1"); /* no RRSIG */ return 1; } } return 0; }); vector<DNSRecord> ret; /* first query does not require validation */ sr-><API key>(false); int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Indeterminate); BOOST_REQUIRE_EQUAL(ret.size(), 2); for (const auto& record : ret) { BOOST_CHECK(record.d_type == QType::CNAME || record.d_type == QType::A); } BOOST_CHECK_EQUAL(queriesCount, 2); ret.clear(); /* second one _does_ require validation */ sr-><API key>(true); res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Bogus); BOOST_REQUIRE_EQUAL(ret.size(), 2); for (const auto& record : ret) { BOOST_CHECK(record.d_type == QType::CNAME || record.d_type == QType::A); } BOOST_CHECK_EQUAL(queriesCount, 5); } <API key>(<API key>) { /* We get a record from a secure zone in the additional section, without the corresponding RRSIG. The record should not be marked as authoritative and should be correctly validated. */ std::unique_ptr<SyncRes> sr; initSR(sr, true); setDNSSECValidation(sr, DNSSECMode::Process); primeHints(); const DNSName target("com."); const DNSName addTarget("nsX.com."); testkeysset_t keys; auto luaconfsCopy = g_luaconfs.getCopy(); luaconfsCopy.dsAnchors.clear(); generateKeyMaterial(g_rootdnsname, DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys, luaconfsCopy.dsAnchors); g_luaconfs.setState(luaconfsCopy); size_t queriesCount = 0; sr->setAsyncCallback([target,addTarget,&queriesCount,keys](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { queriesCount++; if (type == QType::DS || type == QType::DNSKEY) { if (domain == addTarget) { DNSName auth(domain); /* no DS for com, auth will be . */ auth.chopOff(); return <API key>(res, domain, auth, type, keys, false); } return <API key>(res, domain, domain, type, keys, false); } else { if (domain == target && type == QType::A) { setLWResult(res, 0, true, false, true); addRecordToLW(res, target, QType::A, "192.0.2.1"); addRRSIG(keys, res->d_records, DNSName("."), 300); addRecordToLW(res, addTarget, QType::A, "192.0.2.42", DNSResourceRecord::ADDITIONAL); /* no RRSIG for the additional record */ return 1; } else if (domain == addTarget && type == QType::A) { setLWResult(res, 0, true, false, true); addRecordToLW(res, addTarget, QType::A, "192.0.2.42"); addRRSIG(keys, res->d_records, DNSName("."), 300); return 1; } } return 0; }); vector<DNSRecord> ret; /* first query for target/A, will pick up the additional record as non-auth / unvalidated */ sr-><API key>(false); int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Indeterminate); BOOST_CHECK_EQUAL(ret.size(), 2); for (const auto& record : ret) { BOOST_CHECK(record.d_type == QType::RRSIG || record.d_type == QType::A); } BOOST_CHECK_EQUAL(queriesCount, 1); ret.clear(); /* ask for the additional record directly, we should not use the non-auth one and issue a new query, properly validated */ sr-><API key>(true); res = sr->beginResolve(addTarget, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Secure); BOOST_CHECK_EQUAL(ret.size(), 2); for (const auto& record : ret) { BOOST_CHECK(record.d_type == QType::RRSIG || record.d_type == QType::A); } BOOST_CHECK_EQUAL(queriesCount, 5); } <API key>(<API key>) { /* Validation is optional, and the first query does not ask for it, so the answer is negatively cached as Indeterminate. The second query asks for validation, answer should be marked as Secure. */ std::unique_ptr<SyncRes> sr; initSR(sr, true); setDNSSECValidation(sr, DNSSECMode::Process); primeHints(); const DNSName target("com."); testkeysset_t keys; auto luaconfsCopy = g_luaconfs.getCopy(); luaconfsCopy.dsAnchors.clear(); generateKeyMaterial(g_rootdnsname, DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys, luaconfsCopy.dsAnchors); generateKeyMaterial(DNSName("com."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); g_luaconfs.setState(luaconfsCopy); size_t queriesCount = 0; sr->setAsyncCallback([target,&queriesCount,keys](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { queriesCount++; DNSName auth = domain; auth.chopOff(); if (type == QType::DS || type == QType::DNSKEY) { return <API key>(res, domain, auth, type, keys); } else { setLWResult(res, RCode::NoError, true, false, true); addRecordToLW(res, domain, QType::SOA, "pdns-public-ns1.powerdns.com. pieter\\.lexis.powerdns.com. 2017032301 10800 3600 604800 3600", DNSResourceRecord::AUTHORITY, 3600); addRRSIG(keys, res->d_records, domain, 300); addNSECRecordToLW(domain, DNSName("z."), { QType::NSEC, QType::RRSIG }, 600, res->d_records); addRRSIG(keys, res->d_records, domain, 1); return 1; } return 0; }); vector<DNSRecord> ret; /* first query does not require validation */ sr-><API key>(false); int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Indeterminate); BOOST_REQUIRE_EQUAL(ret.size(), 4); BOOST_CHECK_EQUAL(queriesCount, 1); /* check that the entry has not been negatively cached */ NegCache::NegCacheEntry ne; BOOST_CHECK_EQUAL(SyncRes::t_sstorage.negcache.size(), 1); BOOST_REQUIRE_EQUAL(SyncRes::t_sstorage.negcache.get(target, QType(QType::A), sr->getNow(), ne), true); BOOST_CHECK_EQUAL(ne.d_validationState, Indeterminate); BOOST_CHECK_EQUAL(ne.authoritySOA.records.size(), 1); BOOST_CHECK_EQUAL(ne.authoritySOA.signatures.size(), 1); BOOST_CHECK_EQUAL(ne.DNSSECRecords.records.size(), 1); BOOST_CHECK_EQUAL(ne.DNSSECRecords.signatures.size(), 1); ret.clear(); /* second one _does_ require validation */ sr-><API key>(true); res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Secure); BOOST_REQUIRE_EQUAL(ret.size(), 4); BOOST_CHECK_EQUAL(queriesCount, 4); BOOST_CHECK_EQUAL(SyncRes::t_sstorage.negcache.size(), 1); BOOST_REQUIRE_EQUAL(SyncRes::t_sstorage.negcache.get(target, QType(QType::A), sr->getNow(), ne), true); BOOST_CHECK_EQUAL(ne.d_validationState, Secure); BOOST_CHECK_EQUAL(ne.authoritySOA.records.size(), 1); BOOST_CHECK_EQUAL(ne.authoritySOA.signatures.size(), 1); BOOST_CHECK_EQUAL(ne.DNSSECRecords.records.size(), 1); BOOST_CHECK_EQUAL(ne.DNSSECRecords.signatures.size(), 1); } <API key>(<API key>) { /* Validation is optional, and the first query does not ask for it, so the answer is negatively cached as Indeterminate. The second query asks for validation, answer should be marked as Secure. The difference with <API key> is that have one more level here, so we are going to look for the proof that the DS does not exist for the last level. Since there is no cut, we should accept the fact that the NSEC denies DS and NS both. */ std::unique_ptr<SyncRes> sr; initSR(sr, true); setDNSSECValidation(sr, DNSSECMode::Process); primeHints(); const DNSName target("www.com."); testkeysset_t keys; auto luaconfsCopy = g_luaconfs.getCopy(); luaconfsCopy.dsAnchors.clear(); generateKeyMaterial(g_rootdnsname, DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys, luaconfsCopy.dsAnchors); generateKeyMaterial(DNSName("com."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); g_luaconfs.setState(luaconfsCopy); size_t queriesCount = 0; sr->setAsyncCallback([target,&queriesCount,keys](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { queriesCount++; if (type == QType::DS || type == QType::DNSKEY) { if (domain == target) { /* there is no cut */ return <API key>(res, domain, domain, type, keys, false); } return <API key>(res, domain, domain, type, keys); } return 0; }); vector<DNSRecord> ret; /* first query does not require validation */ sr-><API key>(false); int res = sr->beginResolve(target, QType(QType::DS), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Indeterminate); BOOST_REQUIRE_EQUAL(ret.size(), 4); BOOST_CHECK_EQUAL(queriesCount, 1); ret.clear(); /* second one _does_ require validation */ sr-><API key>(true); res = sr->beginResolve(target, QType(QType::DS), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Secure); BOOST_REQUIRE_EQUAL(ret.size(), 4); BOOST_CHECK_EQUAL(queriesCount, 4); } <API key>(<API key>) { /* Validation is optional, and the first query does not ask for it, so the answer is negatively cached as Indeterminate. The second query asks for validation, answer should be marked as Insecure. */ std::unique_ptr<SyncRes> sr; initSR(sr, true); setDNSSECValidation(sr, DNSSECMode::Process); primeHints(); const DNSName target("com."); testkeysset_t keys; auto luaconfsCopy = g_luaconfs.getCopy(); luaconfsCopy.dsAnchors.clear(); g_luaconfs.setState(luaconfsCopy); size_t queriesCount = 0; sr->setAsyncCallback([target,&queriesCount,keys](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { queriesCount++; DNSName auth = domain; auth.chopOff(); if (type == QType::DS || type == QType::DNSKEY) { return <API key>(res, domain, auth, type, keys); } else { setLWResult(res, RCode::NoError, true, false, true); addRecordToLW(res, domain, QType::SOA, "pdns-public-ns1.powerdns.com. pieter\\.lexis.powerdns.com. 2017032301 10800 3600 604800 3600", DNSResourceRecord::AUTHORITY, 3600); return 1; } return 0; }); vector<DNSRecord> ret; /* first query does not require validation */ sr-><API key>(false); int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Indeterminate); BOOST_REQUIRE_EQUAL(ret.size(), 1); BOOST_CHECK_EQUAL(queriesCount, 1); /* check that the entry has not been negatively cached */ NegCache::NegCacheEntry ne; BOOST_CHECK_EQUAL(SyncRes::t_sstorage.negcache.size(), 1); BOOST_REQUIRE_EQUAL(SyncRes::t_sstorage.negcache.get(target, QType(QType::A), sr->getNow(), ne), true); BOOST_CHECK_EQUAL(ne.d_validationState, Indeterminate); BOOST_CHECK_EQUAL(ne.authoritySOA.records.size(), 1); BOOST_CHECK_EQUAL(ne.authoritySOA.signatures.size(), 0); BOOST_CHECK_EQUAL(ne.DNSSECRecords.records.size(), 0); BOOST_CHECK_EQUAL(ne.DNSSECRecords.signatures.size(), 0); ret.clear(); /* second one _does_ require validation */ sr-><API key>(true); res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Insecure); BOOST_REQUIRE_EQUAL(ret.size(), 1); BOOST_CHECK_EQUAL(queriesCount, 1); BOOST_REQUIRE_EQUAL(SyncRes::t_sstorage.negcache.get(target, QType(QType::A), sr->getNow(), ne), true); BOOST_CHECK_EQUAL(ne.d_validationState, Insecure); BOOST_CHECK_EQUAL(ne.authoritySOA.records.size(), 1); BOOST_CHECK_EQUAL(ne.authoritySOA.signatures.size(), 0); BOOST_CHECK_EQUAL(ne.DNSSECRecords.records.size(), 0); BOOST_CHECK_EQUAL(ne.DNSSECRecords.signatures.size(), 0); } <API key>(<API key>) { /* Validation is optional, and the first query does not ask for it, so the answer is negatively cached as Indeterminate. The second query asks for validation, answer should be marked as Bogus. */ std::unique_ptr<SyncRes> sr; initSR(sr, true); setDNSSECValidation(sr, DNSSECMode::Process); primeHints(); const DNSName target("com."); testkeysset_t keys; auto luaconfsCopy = g_luaconfs.getCopy(); luaconfsCopy.dsAnchors.clear(); generateKeyMaterial(g_rootdnsname, DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys, luaconfsCopy.dsAnchors); generateKeyMaterial(DNSName("com."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); g_luaconfs.setState(luaconfsCopy); size_t queriesCount = 0; sr->setAsyncCallback([target,&queriesCount,keys](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { queriesCount++; DNSName auth = domain; auth.chopOff(); if (type == QType::DS || type == QType::DNSKEY) { return <API key>(res, domain, auth, type, keys); } else { setLWResult(res, RCode::NoError, true, false, true); addRecordToLW(res, domain, QType::SOA, "pdns-public-ns1.powerdns.com. pieter\\.lexis.powerdns.com. 2017032301 10800 3600 604800 3600", DNSResourceRecord::AUTHORITY, 3600); addRRSIG(keys, res->d_records, domain, 300); /* no denial */ return 1; } return 0; }); vector<DNSRecord> ret; /* first query does not require validation */ sr-><API key>(false); int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Indeterminate); BOOST_REQUIRE_EQUAL(ret.size(), 2); BOOST_CHECK_EQUAL(queriesCount, 1); NegCache::NegCacheEntry ne; BOOST_CHECK_EQUAL(SyncRes::t_sstorage.negcache.size(), 1); BOOST_REQUIRE_EQUAL(SyncRes::t_sstorage.negcache.get(target, QType(QType::A), sr->getNow(), ne), true); BOOST_CHECK_EQUAL(ne.d_validationState, Indeterminate); BOOST_CHECK_EQUAL(ne.authoritySOA.records.size(), 1); BOOST_CHECK_EQUAL(ne.authoritySOA.signatures.size(), 1); BOOST_CHECK_EQUAL(ne.DNSSECRecords.records.size(), 0); BOOST_CHECK_EQUAL(ne.DNSSECRecords.signatures.size(), 0); ret.clear(); /* second one _does_ require validation */ sr-><API key>(true); res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_CHECK_EQUAL(sr->getValidationState(), Bogus); BOOST_REQUIRE_EQUAL(ret.size(), 2); BOOST_CHECK_EQUAL(queriesCount, 4); BOOST_REQUIRE_EQUAL(SyncRes::t_sstorage.negcache.get(target, QType(QType::A), sr->getNow(), ne), true); BOOST_CHECK_EQUAL(ne.d_validationState, Bogus); BOOST_CHECK_EQUAL(ne.authoritySOA.records.size(), 1); BOOST_CHECK_EQUAL(ne.authoritySOA.signatures.size(), 1); BOOST_CHECK_EQUAL(ne.DNSSECRecords.records.size(), 0); BOOST_CHECK_EQUAL(ne.DNSSECRecords.signatures.size(), 0); } <API key>(<API key>) { g_lowercaseOutgoing = true; std::unique_ptr<SyncRes> sr; initSR(sr); primeHints(); vector<DNSName> sentOutQnames; const DNSName target("WWW.POWERDNS.COM"); const DNSName cname("WWW.PowerDNS.org"); sr->setAsyncCallback([target, cname, &sentOutQnames](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { sentOutQnames.push_back(domain); if (isRootServer(ip)) { if (domain == target) { setLWResult(res, 0, false, false, true); addRecordToLW(res, "powerdns.com.", QType::NS, "pdns-public-ns1.powerdns.com.", DNSResourceRecord::AUTHORITY, 172800); addRecordToLW(res, "pdns-public-ns1.powerdns.com.", QType::A, "192.0.2.1", DNSResourceRecord::ADDITIONAL, 3600); return 1; } if (domain == cname) { setLWResult(res, 0, false, false, true); addRecordToLW(res, "powerdns.org.", QType::NS, "pdns-public-ns1.powerdns.org.", DNSResourceRecord::AUTHORITY, 172800); addRecordToLW(res, "pdns-public-ns1.powerdns.org.", QType::A, "192.0.2.2", DNSResourceRecord::ADDITIONAL, 3600); return 1; } } else if (ip == ComboAddress("192.0.2.1:53")) { if (domain == target) { setLWResult(res, 0, true, false, false); addRecordToLW(res, domain, QType::CNAME, cname.toString()); return 1; } } else if (ip == ComboAddress("192.0.2.2:53")) { if (domain == cname) { setLWResult(res, 0, true, false, false); addRecordToLW(res, domain, QType::A, "127.0.0.1"); return 1; } } return 0; }); vector<DNSRecord> ret; int res = sr->beginResolve(target, QType(QType::A), QClass::IN, ret); BOOST_CHECK_EQUAL(res, RCode::NoError); BOOST_REQUIRE_EQUAL(ret.size(), 2); BOOST_CHECK_EQUAL(ret[0].d_content-><API key>(), cname.toString()); BOOST_REQUIRE_EQUAL(sentOutQnames.size(), 4); BOOST_CHECK_EQUAL(sentOutQnames[0].toString(), target.makeLowerCase().toString()); BOOST_CHECK_EQUAL(sentOutQnames[1].toString(), target.makeLowerCase().toString()); BOOST_CHECK_EQUAL(sentOutQnames[2].toString(), cname.makeLowerCase().toString()); BOOST_CHECK_EQUAL(sentOutQnames[3].toString(), cname.makeLowerCase().toString()); g_lowercaseOutgoing = false; } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr, true); setDNSSECValidation(sr, DNSSECMode::ValidateAll); primeHints(); const DNSName target("com."); testkeysset_t keys, keys2; auto luaconfsCopy = g_luaconfs.getCopy(); luaconfsCopy.dsAnchors.clear(); generateKeyMaterial(g_rootdnsname, DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys, luaconfsCopy.dsAnchors); generateKeyMaterial(DNSName("com."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); g_luaconfs.setState(luaconfsCopy); // As testkeysset_t only contains one DSRecordContent, create another one with a different hash algo generateKeyMaterial(DNSName("com."), DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA1, keys2); // But add the existing root key otherwise no RRSIG can be created auto rootkey = keys.find(g_rootdnsname); keys2.insert(*rootkey); sr->setAsyncCallback([target, keys, keys2](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { DNSName auth = domain; auth.chopOff(); if (type == QType::DS || type == QType::DNSKEY) { if (domain == target) { if (<API key>(res, domain, auth, type, keys2) != 1) { return 0; } } return <API key>(res, domain, auth, type, keys); } return 0; }); dsmap_t ds; auto state = sr->getDSRecords(target, ds, false, 0, false); BOOST_CHECK_EQUAL(state, Secure); BOOST_REQUIRE_EQUAL(ds.size(), 1); for (const auto& i : ds) { BOOST_CHECK_EQUAL(i.d_digesttype, DNSSECKeeper::SHA256); } } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr, true); setDNSSECValidation(sr, DNSSECMode::ValidateAll); primeHints(); const DNSName target("com."); testkeysset_t keys, keys2, keys3; auto luaconfsCopy = g_luaconfs.getCopy(); luaconfsCopy.dsAnchors.clear(); generateKeyMaterial(g_rootdnsname, DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys, luaconfsCopy.dsAnchors); generateKeyMaterial(target, DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); g_luaconfs.setState(luaconfsCopy); // As testkeysset_t only contains one DSRecordContent, create another one with a different hash algo generateKeyMaterial(target, DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA1, keys2); // But add the existing root key otherwise no RRSIG can be created auto rootkey = keys.find(g_rootdnsname); keys2.insert(*rootkey); generateKeyMaterial(target, DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA384, keys3); // But add the existing root key otherwise no RRSIG can be created keys3.insert(*rootkey); sr->setAsyncCallback([target, keys, keys2, keys3](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { DNSName auth = domain; auth.chopOff(); if (type == QType::DS || type == QType::DNSKEY) { if (domain == target) { if (<API key>(res, domain, auth, type, keys2) != 1) { return 0; } if (<API key>(res, domain, auth, type, keys3) != 1) { return 0; } } return <API key>(res, domain, auth, type, keys); } return 0; }); dsmap_t ds; auto state = sr->getDSRecords(target, ds, false, 0, false); BOOST_CHECK_EQUAL(state, Secure); BOOST_REQUIRE_EQUAL(ds.size(), 1); for (const auto& i : ds) { BOOST_CHECK_EQUAL(i.d_digesttype, DNSSECKeeper::SHA384); } } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr, true); setDNSSECValidation(sr, DNSSECMode::ValidateAll); primeHints(); const DNSName target("com."); testkeysset_t keys, keys2, keys3; auto luaconfsCopy = g_luaconfs.getCopy(); luaconfsCopy.dsAnchors.clear(); generateKeyMaterial(g_rootdnsname, DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys, luaconfsCopy.dsAnchors); generateKeyMaterial(target, DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); g_luaconfs.setState(luaconfsCopy); // As testkeysset_t only contains one DSRecordContent, create another one with a different hash algo generateKeyMaterial(target, DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys2); // But add the existing root key otherwise no RRSIG can be created auto rootkey = keys.find(g_rootdnsname); keys2.insert(*rootkey); generateKeyMaterial(target, DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA1, keys3); // But add the existing root key otherwise no RRSIG can be created keys3.insert(*rootkey); sr->setAsyncCallback([target, keys, keys2, keys3](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { DNSName auth = domain; auth.chopOff(); if (type == QType::DS || type == QType::DNSKEY) { if (domain == target) { if (<API key>(res, domain, auth, type, keys2) != 1) { return 0; } if (<API key>(res, domain, auth, type, keys3) != 1) { return 0; } } return <API key>(res, domain, auth, type, keys); } return 0; }); dsmap_t ds; auto state = sr->getDSRecords(target, ds, false, 0, false); BOOST_CHECK_EQUAL(state, Secure); BOOST_REQUIRE_EQUAL(ds.size(), 2); for (const auto& i : ds) { BOOST_CHECK_EQUAL(i.d_digesttype, DNSSECKeeper::SHA256); } } #ifdef HAVE_BOTAN <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr, true); setDNSSECValidation(sr, DNSSECMode::ValidateAll); primeHints(); const DNSName target("com."); testkeysset_t keys, keys2; auto luaconfsCopy = g_luaconfs.getCopy(); luaconfsCopy.dsAnchors.clear(); generateKeyMaterial(g_rootdnsname, DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys, luaconfsCopy.dsAnchors); generateKeyMaterial(target, DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA384, keys); g_luaconfs.setState(luaconfsCopy); // As testkeysset_t only contains one DSRecordContent, create another one with a different hash algo generateKeyMaterial(target, DNSSECKeeper::ECDSA256, DNSSECKeeper::GOST, keys2); // But add the existing root key otherwise no RRSIG can be created auto rootkey = keys.find(g_rootdnsname); keys2.insert(*rootkey); sr->setAsyncCallback([target, keys, keys2](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { DNSName auth = domain; auth.chopOff(); if (type == QType::DS || type == QType::DNSKEY) { if (domain == target) { if (<API key>(res, domain, auth, type, keys2) != 1) { return 0; } } return <API key>(res, domain, auth, type, keys); } return 0; }); dsmap_t ds; auto state = sr->getDSRecords(target, ds, false, 0, false); BOOST_CHECK_EQUAL(state, Secure); BOOST_REQUIRE_EQUAL(ds.size(), 1); for (const auto& i : ds) { BOOST_CHECK_EQUAL(i.d_digesttype, DNSSECKeeper::SHA384); } } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr, true); setDNSSECValidation(sr, DNSSECMode::ValidateAll); primeHints(); const DNSName target("com."); testkeysset_t keys, keys2; auto luaconfsCopy = g_luaconfs.getCopy(); luaconfsCopy.dsAnchors.clear(); generateKeyMaterial(g_rootdnsname, DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys, luaconfsCopy.dsAnchors); generateKeyMaterial(target, DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys); g_luaconfs.setState(luaconfsCopy); // As testkeysset_t only contains one DSRecordContent, create another one with a different hash algo generateKeyMaterial(target, DNSSECKeeper::ECDSA256, DNSSECKeeper::GOST, keys2); // But add the existing root key otherwise no RRSIG can be created auto rootkey = keys.find(g_rootdnsname); keys2.insert(*rootkey); sr->setAsyncCallback([target, keys, keys2](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { DNSName auth = domain; auth.chopOff(); if (type == QType::DS || type == QType::DNSKEY) { if (domain == target) { if (<API key>(res, domain, auth, type, keys2) != 1) { return 0; } } return <API key>(res, domain, auth, type, keys); } return 0; }); dsmap_t ds; auto state = sr->getDSRecords(target, ds, false, 0, false); BOOST_CHECK_EQUAL(state, Secure); BOOST_REQUIRE_EQUAL(ds.size(), 1); for (const auto& i : ds) { BOOST_CHECK_EQUAL(i.d_digesttype, DNSSECKeeper::SHA256); } } <API key>(<API key>) { std::unique_ptr<SyncRes> sr; initSR(sr, true); setDNSSECValidation(sr, DNSSECMode::ValidateAll); primeHints(); const DNSName target("com."); testkeysset_t keys, keys2; auto luaconfsCopy = g_luaconfs.getCopy(); luaconfsCopy.dsAnchors.clear(); generateKeyMaterial(g_rootdnsname, DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA256, keys, luaconfsCopy.dsAnchors); generateKeyMaterial(target, DNSSECKeeper::ECDSA256, DNSSECKeeper::SHA1, keys); g_luaconfs.setState(luaconfsCopy); // As testkeysset_t only contains one DSRecordContent, create another one with a different hash algo generateKeyMaterial(target, DNSSECKeeper::ECDSA256, DNSSECKeeper::GOST, keys2); // But add the existing root key otherwise no RRSIG can be created auto rootkey = keys.find(g_rootdnsname); keys2.insert(*rootkey); sr->setAsyncCallback([target, keys, keys2](const ComboAddress& ip, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult* res) { DNSName auth = domain; auth.chopOff(); if (type == QType::DS || type == QType::DNSKEY) { if (domain == target) { if (<API key>(res, domain, auth, type, keys2) != 1) { return 0; } } return <API key>(res, domain, auth, type, keys); } return 0; }); dsmap_t ds; auto state = sr->getDSRecords(target, ds, false, 0, false); BOOST_CHECK_EQUAL(state, Secure); BOOST_REQUIRE_EQUAL(ds.size(), 1); for (const auto& i : ds) { BOOST_CHECK_EQUAL(i.d_digesttype, DNSSECKeeper::GOST); } } #endif // HAVE_BOTAN110 /* // cerr<<"asyncresolve called to ask "<<ip.toStringWithPort()<<" about "<<domain.toString()<<" / "<<QType(type).getName()<<" over "<<(doTCP ? "TCP" : "UDP")<<" (rd: "<<sendRDQuery<<", EDNS0 level: "<<EDNS0Level<<")"<<endl; - check out of band support - check preoutquery */ <API key>()
"""Provides a number of objects to help with managing certain elements in the CFME UI. Specifically there are two categories of objects, organizational and elemental. * **Organizational** * :py:class:`Region` * :py:mod:`cfme.web_ui.menu` * **Elemental** * :py:class:`<API key>` * :py:class:`AngularSelect` * :py:class:`ButtonGroup` * :py:class:`Calendar` * :py:class:`ColorGroup` * :py:class:`CheckboxTable` * :py:class:`CheckboxSelect` * :py:class:`DHTMLSelect` * :py:class:`DriftGrid` * :py:class:`DynamicTable` * :py:class:`EmailSelectForm` * :py:class:`Filter` * :py:class:`Form` * :py:class:`InfoBlock` * :py:class:`Input` * :py:class:`MultiFill` * :py:class:`Quadicon` * :py:class:`Radio` * :py:class:`ScriptBox` * :py:class:`Select` * :py:class:`ShowingInputs` * :py:class:`SplitCheckboxTable` * :py:class:`SplitTable` * :py:class:`StatusBox` * :py:class:`Table` * :py:class:`Tree` * :py:mod:`cfme.web_ui.accordion` * :py:mod:`cfme.web_ui.cfme_exception` * :py:mod:`cfme.web_ui.expression_editor` * :py:mod:`cfme.web_ui.flash` * :py:mod:`cfme.web_ui.form_buttons` * :py:mod:`cfme.web_ui.jstimelines` * :py:mod:`cfme.web_ui.listaccordion` * :py:mod:`cfme.web_ui.menu` * :py:mod:`cfme.web_ui.mixins` * :py:mod:`cfme.web_ui.paginator` * :py:mod:`cfme.web_ui.search` * :py:mod:`cfme.web_ui.tabstrip` * :py:mod:`cfme.web_ui.toolbar` """ import atexit import os import re import time import types from datetime import date from collections import Sequence, Mapping, Callable, Iterable from tempfile import NamedTemporaryFile from xml.sax.saxutils import quoteattr, unescape from cached_property import cached_property from selenium.common import exceptions as sel_exceptions from selenium.common.exceptions import <API key> from selenium.webdriver.remote.file_detector import LocalFileDetector from multimethods import multimethod, multidispatch, Anything from widgetastic.xpath import quote import cfme.fixtures.pytest_selenium as sel from cfme import exceptions, js from cfme.fixtures.pytest_selenium import browser # For backward compatibility with code that pulls in Select from web_ui instead of sel from cfme.fixtures.pytest_selenium import Select from utils import attributize_string, castmap, normalize_space, version from utils.log import logger from utils.pretty import Pretty from wait_for import TimedOutError, wait_for class Selector(object): """ Special Selector object allowing object resolution on attr access The Selector is a simple class which allows a 'super' widget to support multiple implementations. This is achieved by the use of a ``decide`` method which accesses attrs of the object set by the ``__init__`` of the child class. These attributes are then used to decide which type of object is on a page. In some cases, this can avoid a version pick if the information used to instantiate both old and new implementations can be identical. This is most noteably if using an "id" which remains constant from implementation to implementation. As an example, imagine the normal "checkbox" is replaced wit ha fancy new web 2.0 checkbox. Both have an "input" element, and give it the same "id". When the decide method is invoked, the "id" is inspected and used to determine if it is an old or a new style widget. We then set a hidden attribute of the super widget and proxy all further attr requests to that object. This means that in order for things to behave as expect ALL implementations must also expose the same "public" API. """ def __init__(self): self._obj = None def __getattr__(self, name): if not self._obj: self._obj = self.decide() return getattr(self._obj, name) def decide(self): raise Exception('This widget does not have a "decide" method which is mandatory') class Region(Pretty): """ Base class for all UI regions/pages Args: locators: A dict of locator objects for the given region title: A string containing the title of the page, or a versioned dict of page title strings identifying_loc: Single locator key from locators used by :py:meth:`Region.is_displayed` to check if the region is currently visible Usage: page = Region(locators={ '<API key>': (By.CSS_SELECTOR, "div.dhx_toolbar_btn[title='Configuration']"), 'discover_button': (By.CSS_SELECTOR, "tr[title='Discover Cloud Providers']>td.td_btn_txt>" "div.btn_sel_text") }, title='Cloud Providers', identifying_loc='discover_button' ) The elements can then accessed like so:: page.<API key> Locator attributes will return the locator tuple for that particular element, and can be passed on to other functions, such as :py:func:`element` and :py:func:`click`. Note: When specifying a region title, omit the "Cloudforms Management Engine: " or "ManageIQ: " prefix. They are included on every page, and different for the two versions of the appliance, and :py:meth:`is_displayed` strips them off before checking for equality. """ pretty_attrs = ['title'] def __getattr__(self, name): if hasattr(self, 'locators') and name in self.locators: locator = self.locators[name] if isinstance(locator, dict): return version.pick(locator) else: return locator else: raise AttributeError("Region has no attribute named " + name) def __init__(self, locators=None, title=None, identifying_loc=None, **kwargs): self.locators = locators self.identifying_loc = identifying_loc self._title = title self.infoblock = InfoBlock # Legacy support @property def title(self): # support title being a versioned dict if isinstance(self._title, dict): self._title = version.pick(self._title) return self._title def is_displayed(self): """ Checks to see if the region is currently displayed. Returns: A boolean describing if the region is currently displayed """ if not self.identifying_loc and not self.title: logger.warning("Region doesn't have an identifying locator or title, " "can't determine if current page.") return True # All page titles have a prefix; strip it off window_title = browser_title() if self.identifying_loc and sel.is_displayed( self.locators[self.identifying_loc], _no_deeper=True): ident_match = True else: if not self.title: logger.info('Identifying locator for region not found') else: logger.info('Identifying locator for region %s not found', self.title) ident_match = False if self.title is None: # If we don't have a title we can't match it, and some Regions are multi-page # so we can't have a title set. title_match = True elif self.title and window_title == self.title: title_match = True else: logger.info("Title %s doesn't match expected title %s", window_title, self.title) title_match = False return title_match and ident_match def <API key>(): """ Returns the current page name Returns: A string containing the current page name """ url = browser().current_url() stripped = url.lstrip('https: return stripped[stripped.find('/'):stripped.rfind('?')] class CachedTableHeaders(object): """the internal cache of headers This allows columns to be moved and the Table updated. The :py:attr:`headers` stores the header cache element and the list of headers are stored in _headers. The attribute header_indexes is then created, before finally creating the items attribute. """ def __init__(self, table): self.headers = sel.elements('td | th', root=table.header_row) self.indexes = { attributize_string(cell.text): index for index, cell in enumerate(self.headers)} class Table(Pretty): """ Helper class for Table/List objects Turns CFME custom Table/Lists into iterable objects using a generator. Args: table_locator: locator pointing to a table element with child thead and tbody elements representing that table's header and body row containers header_offset: In the case of a padding table row above the header, the row offset can be used to skip rows in ``<thead>`` to locate the correct header row. This offset is 1-indexed, not 0-indexed, so an offset of 1 is the first child row element body_offset: In the case of a padding table row above the body rows, the row offset can be used to skip rows in ``<ttbody>`` to locate the correct header row. This offset is 1-indexed, not 0-indexed, so an offset of 1 is the first child row element hidden_locator: If the table can disappear, you probably want ot set this param as it instructs the table that if it cannot find the table on the page but the element represented by ``hidden_locator`` is visible, it assumes no data and returns no rows. Attributes: header_indexes: A dict of header names related to their int index as a column. Usage: table = Table('//div[@id="prov_pxe_img_div"]//table') The HTML code for the table looks something like this:: <div id="prov_pxe_img_div"> <table> <thead> <tr> <th>Name</th> <th>Animal</th> <th>Size</th> </tr> </thead> <tbody> <tr> <td>John</td> <td>Monkey</td> <td>Small</td> </tr> <tr> <td>Mike</td> <td>Tiger</td> <td>Large</td> </tr> </tbody> </table> </div> We can now click on an element in the list like so, by providing the column name and the value that we are searching for:: table.click_cell('name', 'Mike') We can also perform the same, by using the index of the column, like so:: table.click_cell(1, 'Tiger') Additionally, the rows of a table can be iterated over, and that row's columns can be accessed by name or index (left to right, 0-index):: for row in table.rows() # Get the first cell in the row row[0] # Get the row's contents for the column with header 'Row Name' # All of these will work, though the first is preferred row.row_name, row['row_name'], row['Row Name'] When doing bulk opererations, such as selecting rows in a table based on their content, the ``*_by_cells`` methods are able to find matching row much more quickly than iterating, as the work can be done with fewer selenium calls. * :py:meth:`find_rows_by_cells` * :py:meth:`find_row_by_cells` * :py:meth:`click_rows_by_cells` * :py:meth:`click_row_by_cells` Note: A table is defined by the containers of the header and data areas, and offsets to them. This allows a table to include one or more padding rows above the header row. In the example above, there is no padding row, as our offset values are set to 0. """ pretty_attrs = ['_loc'] def __init__(self, table_locator, header_offset=0, body_offset=0, hidden_locator=None): self._headers = None self._header_indexes = None self._loc = table_locator self.header_offset = int(header_offset) self.body_offset = int(body_offset) self.hidden_locator = hidden_locator @property def header_row(self): """Property representing the ``<tr>`` element that contains header cells""" # thead/tr containing header data # xpath is 1-indexed, so we need to add 1 to the offset to get the correct row return sel.element('./thead/tr[{}]'.format(self.header_offset + 1), root=sel.element(self)) @property def body(self): """Property representing the ``<tbody>`` element that contains body rows""" # tbody containing body rows return sel.element('./tbody', root=sel.element(self)) @cached_property def _headers_cache(self): return CachedTableHeaders(self) def verify_headers(self): """Verifies whether the headers in the table correspond with the cached ones.""" current_headers = CachedTableHeaders(self) cached_headers = self._headers_cache if current_headers.indexes != cached_headers.indexes: raise exceptions.UsingSharedTables( ('{cn} suspects that you are using shared tables! ' 'That means you are using one {cn} instance to represent different UI tables. ' 'This is not possible due to the header caching, but also wrong from the ' 'design point of view. Please, create separate instances of {cn} for EACH table ' 'in the user interface.').format(cn=type(self).__name__)) def _update_cache(self): """refresh the cache in case we know its stale""" try: del self._headers_cache except AttributeError: pass # it's not cached, dont try to be eager else: self._headers_cache @property def headers(self): """List of ``<td>`` or ``<th>`` elements in :py:attr:`header_row` """ return self._headers_cache.headers @property def header_indexes(self): """Dictionary of header name: column index for this table's rows Derived from :py:attr:`headers` """ return self._headers_cache.indexes def locate(self): return sel.move_to_element(self._loc) @property def _root_loc(self): return self.locate() def rows(self): """A generator method holding the Row objects This generator yields Row objects starting at the first data row. Yields: :py:class:`Table.Row` object corresponding to the next row in the table. """ try: index = self.body_offset row_elements = sel.elements('./tr', root=self.body) for row_element in row_elements[index:]: yield self.<API key>(row_element) except (exceptions.<API key>, <API key>): if self.hidden_locator is None: # No hiding is documented here, so just explode raise elif not sel.is_displayed(self.hidden_locator): # Hiding is documented but the element that signalizes that it is all right is not # present so explode too. raise else: # The table is not present but there is something that signalizes it is all right # but no data. return def rows_as_list(self): """Returns rows as list""" return [i for i in self.rows()] def row_count(self): """Returns row count""" return len(self.rows_as_list()) def find_row(self, header, value): """ Finds a row in the Table by iterating through each visible item. Args: header: A string or int, describing which column to inspect. value: The value to be compared when trying to identify the correct row to return. Returns: :py:class:`Table.Row` containing the requested cell, else ``None``. """ return self.find_row_by_cells({header: value}) def find_cell(self, header, value): """ Finds an item in the Table by iterating through each visible item, this work used to be done by the :py:meth::`click_cell` method but has not been abstracted out to be called separately. Args: header: A string or int, describing which column to inspect. value: The value to be compared when trying to identify the correct cell to click. Returns: WebElement of the element if item was found, else ``None``. """ matching_cell_rows = self.find_rows_by_cells({header: value}) try: if isinstance(header, basestring): return getattr(matching_cell_rows[0], header) else: return matching_cell_rows[0][header] except IndexError: return None def find_rows_by_cells(self, cells, partial_check=False): """A fast row finder, based on cell content. If you pass a regexp as a value, then it will be used with its ``.match()`` method. Args: cells: A dict of ``header: value`` pairs or a sequence of nested ``(header, value)`` pairs. partial_check: If to use the ``in`` operator rather than ``==``. Returns: A list of containing :py:class:`Table.Row` objects whose contents match all of the header: value pairs in ``cells`` """ # accept dicts or supertuples cells = dict(cells) cell_text_loc = ( './/td/descendant-or-self::*[contains(normalize-space(text()), "{}")]/ancestor::tr[1]') matching_rows_list = list() for value in cells.values(): # Get all td elements that contain the value text matching_elements = sel.elements(cell_text_loc.format(value), root=sel.move_to_element(self._root_loc)) if matching_elements: matching_rows_list.append(set(matching_elements)) # Now, find the common row elements that matched all the input cells # (though not yet matching values to headers) if not matching_rows_list: # If none matched, short out return [] rows_elements = list(reduce(lambda set1, set2: set1 & set2, matching_rows_list)) # Convert them to rows # This is slow, which is why we do it after reducing the row element pile, # and not when building matching_rows_list, but it makes comparing header # names and expected values easy rows = [self.<API key>(element) for element in rows_elements] # Only include rows where the expected values are in the right columns matching_rows = list() def matching_row_filter(heading, value): text = normalize_space(row[heading].text) if isinstance(value, re._pattern_type): return value.match(text) is not None elif partial_check: return value in text else: return text == value for row in rows: if all(matching_row_filter(*cell) for cell in cells.items()): matching_rows.append(row) return matching_rows def find_row_by_cells(self, cells, partial_check=False): """Find the first row containing cells Args: cells: See :py:meth:`Table.find_rows_by_cells` Returns: The first matching row found, or None if no matching row was found """ try: rows = self.find_rows_by_cells(cells, partial_check=partial_check) return rows[0] except IndexError: return None def click_rows_by_cells(self, cells, click_column=None, partial_check=False): """Click the cell at ``click_column`` in the rows matched by ``cells`` Args: cells: See :py:meth:`Table.find_rows_by_cells` click_column: Which column in the row to click, defaults to None, which will attempt to click the row element Note: The value of click_column can be a string or an int, and will be passed directly to the item accessor (``__getitem__``) for :py:class:`Table.Row` """ rows = self.find_rows_by_cells(cells, partial_check=partial_check) if click_column is not None: rows = [row[click_column] for row in rows] for row in rows: if row is None: self.verify_headers() # Suspected shared table use sel.click(row) def click_row_by_cells(self, cells, click_column=None, partial_check=False): """Click the cell at ``click_column`` in the first row matched by ``cells`` Args: cells: See :py:meth:`Table.find_rows_by_cells` click_column: See :py:meth:`Table.click_rows_by_cells` """ row = self.find_row_by_cells(cells, partial_check=partial_check) if row is None: raise NameError('No row matching {} found'.format(repr(cells))) elif click_column is not None: row = row[click_column] if row is None: self.verify_headers() # Suspected shared table use sel.click(row) def <API key>(self, row_element): """Given a row element in this table, create a :py:class:`Table.Row` Args: row_element: A table row (``<tr>``) WebElement representing a row in this table. Returns: A :py:class:`Table.Row` for ``row_element`` """ return Table.Row(row_element, self) def click_cells(self, cell_map): """Submits multiple cells to be clicked on Args: cell_map: A mapping of header names and values, representing cells to click. As an example, ``{'name': ['wing', 'nut']}, {'age': ['12']}`` would click on the cells which had ``wing`` and ``nut`` in the name column and ``12`` in the age column. The yaml example for this would be as follows:: list_items: name: - wing - nut age: - 12 Raises: NotAllItemsClicked: If some cells were unable to be found. """ failed_clicks = [] for header, values in cell_map.items(): if isinstance(values, basestring): values = [values] for value in values: res = self.click_cell(header, value) if not res: failed_clicks.append("{}:{}".format(header, value)) if failed_clicks: raise exceptions.NotAllItemsClicked(failed_clicks) def click_cell(self, header, value): """Clicks on a cell defined in the row. Uses the header identifier and a value to determine which cell to click on. Args: header: A string or int, describing which column to inspect. value: The value to be compared when trying to identify the correct cell to click the cell in. Returns: ``True`` if item was found and clicked, else ``False``. """ cell = self.find_cell(header, value) if cell: sel.click(cell) return True else: # This *might* lead to the shared table. So be safe here. self.verify_headers() return False class Row(Pretty): """An object representing a row in a Table. The Row object returns a dymanically addressable attribute space so that the tables headers are automatically generated. Args: row_element: A table row ``WebElement`` parent_table: :py:class:`Table` containing ``row_element`` Notes: Attributes are dynamically generated. The index/key accessor is more flexible than the attr accessor, as it can operate on int indices and header names. """ pretty_attrs = ['row_element', 'table'] def __init__(self, row_element, parent_table): self.table = parent_table self.row_element = row_element @property def columns(self): """A list of WebElements corresponding to the ``<td>`` elements in this row""" return sel.elements('./td', root=self.row_element) def __getattr__(self, name): """ Returns Row element by header name """ try: return self.columns[self.table.header_indexes[attributize_string(name)]] except (KeyError, IndexError): # Suspected shared table use self.table.verify_headers() # If it did not fail at that time, reraise raise def __getitem__(self, index): """ Returns Row element by header index or name """ try: return self.columns[index] except TypeError: # Index isn't an int, assume it's a string return getattr(self, attributize_string(index)) except IndexError: # Suspected shared table use self.table.verify_headers() # If it did not fail at that time, reraise raise def __str__(self): return ", ".join(["'{}'".format(el.text) for el in self.columns]) def __eq__(self, other): if isinstance(other, type(self)): # Selenium elements support equality checks, so we can, too. return self.row_element == other.row_element else: return id(self) == id(other) def locate(self): # table.<API key>(row_instance) might actually work... return sel.move_to_element(self.row_element) class CAndUGroupTable(Table): """Type of tables used in C&U, not tested in others. Provides ``.groups()`` generator which yields group objects. A group objects consists of the rows that are located in the group plus the summary informations. THe main principle is that all the rows inside group are stored in group object's ``.rows`` and when the script encounters the end of the group, it will store the summary data after the data rows as attributes, so eg. ``Totals:`` will become ``group.totals``. All the rows are represented as dictionaries. """ class States: NORMAL_ROWS = 0 GROUP_SUMMARY = 1 class Group(object): def __init__(self, group_id, headers, rows, info_rows): self.id = group_id self.rows = [dict(zip(headers, row)) for row in rows] info_headers = headers[1:] for info_row in info_rows: name = info_row[0] rest = info_row[1:] data = dict(zip(info_headers, rest)) group_attr = attributize_string(name) setattr(self, group_attr, data) def __repr__(self): return '<CAndUGroupTable.Group {}'.format(repr(self.id)) def paginated_rows(self): from cfme.web_ui import paginator for page in paginator.pages(): for row in self.rows(): yield row def find_group(self, group_id): """Finds a group by its group ID (the string that is alone on the line)""" for group in self.groups(): if group.id == group_id: return group_id else: raise KeyError('Group {} not found'.format(group_id)) def groups(self): headers = map(sel.text, self.headers) headers_length = len(headers) rows = self.paginated_rows() current_group_rows = [] <API key> = [] current_group_id = None state = self.States.NORMAL_ROWS while True: try: row = rows.next() except StopIteration: if state == self.States.GROUP_SUMMARY: row = None else: break if state == self.States.NORMAL_ROWS: if len(row.columns) == headers_length: current_group_rows.append(tuple(map(sel.text, row.columns))) else: # Transition to the group summary current_group_id = sel.text(row.columns[0]).strip() state = self.States.GROUP_SUMMARY elif state == self.States.GROUP_SUMMARY: # row is None == we are at the end of the table so a slightly different behaviour if row is not None: fc_length = len(sel.text(row.columns[0]).strip()) if row is None or fc_length == 0: # Done with group yield self.Group( current_group_id, headers, current_group_rows, <API key>) current_group_rows = [] <API key> = [] current_group_id = None state = self.States.NORMAL_ROWS else: <API key>.append(tuple(map(sel.text, row.columns))) else: raise RuntimeError('This should never happen') if current_group_id is not None or current_group_rows or <API key>: raise ValueError( 'GroupTable could not be parsed properly: {} {} {}'.format( current_group_id, repr(current_group_rows), repr(<API key>))) class SplitTable(Table): """:py:class:`Table` that supports the header and body rows being in separate tables Args: header_data: A tuple, containing an element locator and an offset value. These point to the container of the header row. The offset is used in case there is a padding row above the header, or in the case that the header and the body are contained inside the same table element. body_data: A tuple, containing an element locator and an offset value. These point to the container of the body rows. The offset is used in case there is a padding row above the body rows, or in the case that the header and the body are contained inside the same table element. Usage: table = SplitTable(header_data=('//div[@id="header_table"]//table/tbody', 0), body_data=('//div[@id="body_table"]//table/tbody', 1)) The HTML code for a split table looks something like this:: <div id="prov_pxe_img_div"> <table id="header_table"> <tbody> <tr> <td>Name</td> <td>Animal</td> <td>Size</td> </tr> </tbody> </table> <table id="body_table"> <tbody> <tr> <td>Useless</td> <td>Padding</td> <td>Row</td> </tr> <tr> <td>John</td> <td>Monkey</td> <td>Small</td> </tr> <tr> <td>Mike</td> <td>Tiger</td> <td>Large</td> </tr> </tbody> </table> </div> Note the use of the offset to skip the "Useless Padding Row" in ``body_data``. Most split tables require an offset for both the heading and body rows. """ def __init__(self, header_data, body_data): self._header_loc, header_offset = header_data self._body_loc, body_offset = body_data self.header_offset = int(header_offset) self.body_offset = int(body_offset) @property def _root_loc(self): return self._body_loc @property def header_row(self): """Property representing the ``<tr>`` element that contains header cells""" # thead/tr containing header data # xpath is 1-indexed, so we need to add 1 to the offset to get the correct row return sel.element( 'tr[{}]'.format(self.header_offset + 1), root=sel.element(self._header_loc)) @property def body(self): """Property representing the element that contains body rows""" # tbody containing body rows return sel.element(self._body_loc) def locate(self): # Use the header locator as the overall table locator return sel.move_to_element(self._header_loc) class SortTable(Table): """This table is the same as :py:class:`Table`, but with added sorting functionality.""" SORT_CELL = './th[./div/i[contains(@class, "fa-sort")] or contains(@class, "sorting_")]' SORT_LINK = './th/a[normalize-space(.)={}]' @property def _sort_by_cell(self): try: return sel.element(self.SORT_CELL, root=self.header_row) except <API key>: return None @property def sorted_by(self): """Return column name what is used for sorting now. """ cell = self._sort_by_cell if cell is None: return None return sel.text("./a", root=cell).encode("utf-8") @property def sort_order(self): """Return order. Returns: 'ascending' or 'descending' """ cell = self._sort_by_cell if cell is None: return None try: # Newer type el = sel.element('./div/i[contains(@class, "fa-sort")]', root=cell) except <API key>: # Older type el = cell cls = sel.get_attribute(el, "class") if "fa-sort-asc" in cls or 'sorting_asc' in cls: return "ascending" elif "fa-sort-desc" in cls or 'sorting_desc' in cls: return "descending" else: return None def click_header_cell(self, text): """Clicks on the header to change sorting conditions. Args: text: Header cell text. """ sel.click(sel.element(self.SORT_LINK.format(quoteattr(text)), root=self.header_row)) def sort_by(self, header, order): """Sorts the table by given conditions Args: header: Text of the header cell to use for sorting. order: ascending or descending """ order = order.lower().strip() if header != self.sorted_by: # Change column to order by self.click_header_cell(header) if self.sorted_by != header: raise Exception( "Detected malfunction in table ordering (wanted {}, got {})".format( header, self.sorted_by)) if order != self.sort_order: # Change direction self.click_header_cell(header) if self.sort_order != order: raise Exception("Detected malfunction in table ordering (wanted {}, got {})".format( order, self.sort_order)) class CheckboxTable(Table): """:py:class:`Table` with support for checkboxes Args: table_locator: See :py:class:`cfme.web_ui.Table` <API key>: Locator of header checkbox (default `None`) Specify in case the header checkbox is not part of the header row <API key>: Locator for checkboxes in body rows header_offset: See :py:class:`cfme.web_ui.Table` body_offset: See :py:class:`cfme.web_ui.Table` """ _checkbox_loc = ".//input[@type='checkbox']" def __init__(self, table_locator, header_offset=0, body_offset=0, <API key>=None, <API key>=None): super(CheckboxTable, self).__init__(table_locator, header_offset, body_offset) if <API key>: self._checkbox_loc = <API key> self.<API key> = <API key> @property def header_checkbox(self): """Checkbox used to select/deselect all rows""" if self.<API key> is not None: return sel.element(self.<API key>) else: return sel.element(self._checkbox_loc, root=self.header_row) def select_all(self): """Select all rows using the header checkbox or one by one if not present""" if self.<API key> is None: for row in self.rows(): self._set_row_checkbox(row, True) else: sel.uncheck(self.header_checkbox) sel.check(self.header_checkbox) def deselect_all(self): """Deselect all rows using the header checkbox or one by one if not present""" if self.<API key> is None: for row in self.rows(): self._set_row_checkbox(row, False) else: sel.check(self.header_checkbox) sel.uncheck(self.header_checkbox) def _set_row_checkbox(self, row, set_to=False): row_checkbox = sel.element(self._checkbox_loc, root=row.locate()) sel.checkbox(row_checkbox, set_to) def _set_row(self, header, value, set_to=False): """ Internal method used to select/deselect a row by column header and cell value Args: header: See :py:meth:`Table.find_row` value: See :py:meth:`Table.find_row` set_to: Select if `True`, deselect if `False` """ row = self.find_row(header, value) if row: self._set_row_checkbox(row, set_to) return True else: return False def <API key>(self, *indexes): """Select rows specified by row indexes (starting with 0) """ for i, row in enumerate(self.rows()): if i in indexes: self._set_row_checkbox(row, True) def <API key>(self, *indexes): """Deselect rows specified by row indexes (starting with 0) """ for i, row in enumerate(self.rows()): if i in indexes: self._set_row_checkbox(row, False) def select_row(self, header, value): """Select a single row specified by column header and cell value Args: header: See :py:meth:`Table.find_row` value: See :py:meth:`Table.find_row` Returns: `True` if successful, `False` otherwise """ return self._set_row(header, value, True) def deselect_row(self, header, value): """Deselect a single row specified by column header and cell value Args: header: See :py:meth:`Table.find_row` value: See :py:meth:`Table.find_row` Returns: `True` if successful, `False` otherwise """ return self._set_row(header, value, False) def _set_rows(self, cell_map, set_to=False): """ Internal method used to select/deselect multiple rows Args: cell_map: See :py:meth:`Table.click_cells` set_to: Select if `True`, deselect if `False` """ failed_selects = [] for header, values in cell_map.items(): if isinstance(values, basestring): values = [values] for value in values: res = self._set_row(header, value, set_to) if not res: failed_selects.append("{}:{}".format(header, value)) if failed_selects: raise exceptions.<API key>(failed_selects) def select_rows(self, cell_map): """Select multiple rows Args: cell_map: See :py:meth:`Table.click_cells` Raises: <API key>: If some cells were unable to be found """ self._set_rows(cell_map, True) def deselect_rows(self, cell_map): """Deselect multiple rows Args: cell_map: See :py:meth:`Table.click_cells` Raises: <API key>: If some cells were unable to be found """ self._set_rows(cell_map, False) def _set_row_by_cells(self, cells, set_to=False, partial_check=False): row = self.find_row_by_cells(cells, partial_check=partial_check) if row: self._set_row_checkbox(row, set_to) else: raise sel_exceptions.<API key>() def select_row_by_cells(self, cells, partial_check=False): """Select the first row matched by ``cells`` Args: cells: See :py:meth:`Table.find_rows_by_cells` """ self._set_row_by_cells(cells, True, partial_check) def <API key>(self, cells, partial_check=False): """Deselect the first row matched by ``cells`` Args: cells: See :py:meth:`Table.find_rows_by_cells` """ self._set_row_by_cells(cells, False, partial_check) def _set_rows_by_cells(self, cells, set_to=False, partial_check=False): rows = self.find_rows_by_cells(cells) for row in rows: self._set_row_checkbox(row, set_to) def <API key>(self, cells, partial_check=False): """Select the rows matched by ``cells`` Args: cells: See :py:meth:`Table.find_rows_by_cells` """ self._set_rows_by_cells(cells, True, partial_check) def <API key>(self, cells, partial_check=False): """Deselect the rows matched by ``cells`` Args: cells: See :py:meth:`Table.find_rows_by_cells` """ self._set_rows_by_cells(cells, False, partial_check) class SplitCheckboxTable(SplitTable, CheckboxTable): """:py:class:`SplitTable` with support for checkboxes Args: header_data: See :py:class:`cfme.web_ui.SplitTable` body_data: See :py:class:`cfme.web_ui.SplitTable` <API key>: See :py:class:`cfme.web_ui.CheckboxTable` <API key>: See :py:class:`cfme.web_ui.CheckboxTable` header_offset: See :py:class:`cfme.web_ui.Table` body_offset: See :py:class:`cfme.web_ui.Table` """ _checkbox_loc = './/img[contains(@src, "item_chk")]' def __init__(self, header_data, body_data, <API key>=None, <API key>=None): # To limit multiple inheritance surprises, explicitly call out to SplitTable's __init__ SplitTable.__init__(self, header_data, body_data) # ...then set up CheckboxTable's locators here self.<API key> = <API key> if <API key>: self._checkbox_loc = <API key> class PagedTable(Table): """:py:class:`Table` with support for paginator Args: table_locator: See :py:class:`cfme.web_ui.Table` <API key>: Locator of header checkbox (default `None`) Specify in case the header checkbox is not part of the header row <API key>: Locator for checkboxes in body rows header_offset: See :py:class:`cfme.web_ui.Table` body_offset: See :py:class:`cfme.web_ui.Table` """ def <API key>(self, header, value): from cfme.web_ui import paginator for _ in paginator.pages(): sel.wait_for_element(self) row = self.find_row(header, value) if row is not None: return row def <API key>(self, cells): """Find the first row containing cells on all pages Args: cells: See :py:meth:`Table.find_rows_by_cells` Returns: The first matching row found on any page """ from cfme.web_ui import paginator for _ in paginator.pages(): sel.wait_for_element(self) row = self.find_row_by_cells(cells) if row is not None: return row class SplitPagedTable(SplitTable, PagedTable): """:py:class:`SplitTable` with support for paginator Args: header_data: See :py:class:`cfme.web_ui.SplitTable` body_data: See :py:class:`cfme.web_ui.SplitTable` header_offset: See :py:class:`cfme.web_ui.Table` body_offset: See :py:class:`cfme.web_ui.Table` """ def __init__(self, header_data, body_data): # To limit multiple inheritance surprises, explicitly call out to SplitTable's __init__ SplitTable.__init__(self, header_data, body_data) def table_in_object(table_title): """If you want to point to tables inside object view, this is what you want to use. Works both on down- and upstream. Args: table_title: Text in `p` element preceeding the table Returns: XPath locator for the desired table. """ return ("//table[(preceding-sibling::p[1] | preceding-sibling::h3[1])[normalize-space(.)={}]]" .format(quoteattr(table_title))) @multimethod(lambda loc, value: (sel.tag(loc), sel.get_attribute(loc, 'type'))) def fill_tag(loc, value): """ Return a tuple of function to do the filling, and a value to log.""" raise NotImplementedError("Don't know how to fill {} into this type: {}".format(value, loc)) @fill_tag.method(("select", Anything)) def fill_select_tag(select, value): return (sel.select, value) @fill_tag.method((Anything, 'text')) @fill_tag.method((Anything, 'textarea')) def fill_text(textbox, val): return (sel.set_text, val) @fill_tag.method((Anything, 'number')) def fill_number(bmbox, val): return (sel.set_text, val) @fill_tag.method((Anything, 'password')) def fill_password(pwbox, password): return (sel.set_text, "********") @fill_tag.method(('a', Anything)) @fill_tag.method(('img', Anything)) @fill_tag.method((Anything, 'image')) @fill_tag.method((Anything, 'submit')) def fill_click(el, val): """Click only when given a truthy value""" def click_if(e, v): if v: sel.click(e) return (click_if, val) @fill_tag.method((Anything, 'file')) def fill_file(fd, val): return (sel.send_keys, val) @fill_tag.method((Anything, 'checkbox')) def fill_checkbox(cb, val): return (sel.checkbox, bool(val)) @multidispatch def fill(loc, content, **kwargs): """ Fills in a UI component with the given content. Usage: fill(textbox, "text to fill") fill(myform, [ ... data to fill ...]) fill(radio, "choice to select") Returns: True if any UI action was taken, False otherwise """ action, logval = fill_tag(loc, content) if hasattr(loc, 'name'): ident = loc.name else: ident = loc logger.debug(' Filling in [%s], with value %s', ident, logval) prev_state = action(loc, content) sel.<API key>(loc) return prev_state @fill.method((Mapping, Anything)) def _version_pick(m, a, **kwargs): return fill(version.pick(m), a, **kwargs) @fill.method((Table, Mapping)) def _sd_fill_table(table, cells): """ How to fill a table with a value (by selecting the value as cells in the table) See Table.click_cells """ table._update_cache() logger.debug(' Clicking Table cell') table.click_cells(cells) return bool(cells) @fill.method((CheckboxTable, object)) def <API key>(table, cells): """ How to fill a checkboxtable with a value (by selecting the right rows) See CheckboxTable.select_by_cells """ table._update_cache() logger.debug(' Selecting CheckboxTable row') table.select_rows(cells) return bool(cells) @fill.method((Callable, object)) def fill_callable(f, val): """Fill in a Callable by just calling it with the value, allow for arbitrary actions""" return f(val) @fill.method((Select, types.NoneType)) @fill.method((Select, object)) def fill_select(slist, val): logger.debug(' Filling in {} with value {}'.format(str(slist), val)) prev_sel = sel.select(slist, val) slist.observer_wait() return prev_sel class Calendar(Pretty): """A CFME calendar form field Calendar fields are readonly, and managed by the dxhtmlCalendar widget. A Calendar field will accept any object that can be coerced into a string, but the value may not match the format expected by dhtmlxCalendar or CFME. For best results, either a ``datetime.date`` or ``datetime.datetime`` object should be used to create a valid date field. Args: name: "name" property of the readonly calendar field. Usage: calendar = web_ui.Calendar("miq_date_1") web_ui.fill(calendar, date(2000, 1, 1)) web_ui.fill(calendar, '1/1/2001') """ def __init__(self, name): self.name = name def locate(self): return sel.move_to_element(Input(self.name)) @fill.method((Calendar, object)) def _sd_fill_date(calendar, value): input = sel.element(calendar) if isinstance(value, date): date_str = '{}/{}/{}'.format(value.month, value.day, value.year) else: date_str = str(value) # need to write to a readonly field: resort to evil if sel.get_attribute(input, 'ng-model') is not None: sel.set_angularjs_value(input, date_str) else: sel.set_attribute(input, "value", date_str) # Now when we set the value, we need to simulate a change event. if sel.get_attribute(input, "data-date-autoclose"): # New one script = "$(\"#{}\").trigger('changeDate');" else: # Old one script = ( "if(typeof $j == 'undefined') {var jq = $;} else {var jq = $j;} " "jq(\"#{}\").change();") try: sel.execute_script(script.format(calendar.name)) except sel_exceptions.WebDriverException as e: logger.warning( "An exception was raised during handling of the Cal #{}'s change event:\n{}" .format(calendar.name, str(e))) sel.wait_for_ajax() return True @fill.method((object, types.NoneType)) @fill.method((types.NoneType, object)) def _sd_fill_none(*args, **kwargs): """ Ignore a NoneType """ pass class Form(Region): """ A class for interacting with Form elements on pages. The Form class takes a set of locators and binds them together to create a unified Form object. This Form object has a defined field order so that the user does not have to worry about which order the information is provided. This enables the data to be provided as a dict meaning it can be passed directly from yamls. It inherits the base Region class, meaning that locators can still be referenced in the same way a Region's locators can. You can also add one more field which will be a :py:class:`dict` of metadata, determining mostly field validity. See :py:meth:`field_valid` Args: fields: A list of field name/locator tuples. The argument not only defines the order of the elements but also which elements comprise part of the form. identifying_loc: A locator which should be present if the form is visible. Usage: provider_form = web_ui.Form( fields=[ ('type_select', "//*[@id='server_emstype']"), ('name_text', "//*[@id='name']"), ('hostname_text', "//*[@id='hostname']"), ('ipaddress_text', "//*[@id='ipaddress']"), ('<API key>', "//*[@id='hostname']"), ('api_port', "//*[@id='port']"), ]) Forms can then be filled in like so.:: provider_info = { 'type_select': "OpenStack", 'name_text': "RHOS-01", 'hostname_text': "RHOS-01", 'ipaddress_text': "10.0.0.0", 'api_port': "5000", } web_ui.fill(provider_form, provider_info) Note: Using supertuples in a list, although ordered due to the properties of a List, will not overide the field order defined in the Form. """ pretty_attrs = ['fields'] def __init__(self, fields=None, identifying_loc=None): self.metadata = {} self.locators = {} fields_seen = set() for field in fields: try: if field[0] in fields_seen: raise ValueError('You cannot have duplicate field names in a Form ({})'.format( field[0])) self.locators[field[0]] = field[1] if len(field) == 3: self.metadata[field[0]] = field[2] fields_seen.add(field[0]) except IndexError: raise ValueError("fields= can be 2- or 3-tuples only! (name, loc[, metadata])") self.fields = fields self.identifying_loc = identifying_loc def field_valid(self, field_name): """Add the validity constraints here.""" if field_name not in self.metadata: return True metadata = self.metadata[field_name] if "removed_since" in metadata: removed_since = metadata["removed_since"] return version.current_version() < removed_since if "appeared_in" in metadata: appeared_in = metadata["appeared_in"] return version.current_version() >= appeared_in return True def fill(self, fill_data): fill(self, fill_data) @fill.method((Form, Sequence)) def _fill_form_list(form, values, action=None, action_always=False): """Fills in field elements on forms Takes a set of values in dict or supertuple format and locates form elements, in the correct order, and fills them in. Note: Currently supports, text, textarea, select, checkbox, radio, password, a and Table objects/elements. Args: values: a dict or supertuple formatted set of data where each key is the name of the form locator from the page model. Some objects/elements, such as :py:class:`Table` objects, support providing multiple values to be clicked on in a single call. action: a locator which will be clicked when the form filling is complete action_always: if True, perform the action even if none of the values to be filled in required any UI interaction (eg, text boxes already had the text to be filled in, checkbox already checked, etc) """ logger.info('Beginning to fill in form...') sel.wait_for_ajax() values = list(val for key in form.fields for val in values if val[0] == key[0]) res = [] for field, value in values: if value is not None and form.field_valid(field): loc = form.locators[field] try: sel.wait_for_element(loc, timeout=10) except TypeError: # TypeError - when loc is not resolvable to an element, elements() will yell # vvv An alternate scenario when element is not resolvable, just wait a bit. time.sleep(1) except TimedOutError: logger.warning("This element [{}] couldn't be waited for".format(loc)) logger.trace(' Dispatching fill for %s', field) fill_prev = fill(loc, value) # re-dispatch to fill for each item res.append(fill_prev != value) # note whether anything changed elif value is None and isinstance(form.locators[field], Select): fill_prev = fill(form.locators[field], None) res.append(fill_prev != value) else: res.append(False) if action and (any(res) or action_always): # only perform action if something changed logger.debug(' Invoking end of form action') fill(action, True) # re-dispatch with truthy value logger.debug('Finished filling in form') return any(res) or action_always @fill.method((object, Mapping)) def _fill_form_dict(form, values, **kwargs): """Fill in a dict by converting it to a list""" return _fill_form_list(form, values.items(), **kwargs) class Input(Pretty): """Class designed to handle things about ``<input>`` tags that have name attr in one place. Also applies on ``textarea``, which is basically input with multiple lines (if it has name). Args: *names: Possible values (or) of the ``name`` attribute. Keywords: use_id: Whether to use ``id`` instead of ``name``. Useful if there is some input that does not have ``name`` attribute present. """ pretty_attrs = ['_names', '_use_id'] def __init__(self, *names, **kwargs): self._names = names self._use_id = kwargs.pop("use_id", False) @property def names(self): if len(self._names) == 1 and isinstance(self._names[0], dict): return (version.pick(self._names[0]),) else: return self._names def _generate_attr(self, name): return "@{}={}".format("id" if self._use_id else "name", quoteattr(name)) def locate(self): # If the end of the locator is changed, modify also the choice in Radio!!! """Returns the first visible angular helper text (like 'Required').""" """A file input handling widget. Accepts a string. If the string is a file, then it is put in the input. Otherwise a temporary file is generated and that one is fed to the file input. """ """ A class for Radio button groups Radio allows the usage of HTML radio elements without resorting to previous practice of iterating over elements to find the value. The name of the radio group is passed and then when choices are required, the locator is built. Args: name: The HTML elements ``name`` attribute that identifies a group of radio buttons. Usage: radio = Radio("<API key>") A specific radio element can then be returned by running the following:: el = radio.choice('immediately') click(el) The :py:class:`Radio` object can be reused over and over with repeated calls to the :py:func:`Radio.choice` method. """ """ Returns the locator for a choice Args: val: A string representing the ``value`` attribute of the specific radio element. Returns: A string containing the XPATH of the specific radio element. """ """How to fill a radio button group (by selecting the given value)""" """A class representing the Bootstrap treeview used in newer builds. Implements ``expand_path``, ``click_path``, ``read_contents``. All are implemented in manner very similar to the original :py:class:`Tree`. Args: tree_id: Id of the tree, the closest div to the root ``ul`` element. """ """Look up the image that is hidden in the style tag Returns: The name of the image without the hash, path and extension. """ """Expands a node given its nodeid. Must be visible Args: nodeid: ``nodeId`` of the node Returns: ``True`` if it was possible to expand the node, otherwise ``False``. """ """Collapses a node given its nodeid. Must be visible Args: nodeid: ``nodeId`` of the node Returns: ``True`` if it was possible to expand the node, otherwise ``False``. """ """Steps can be plain strings or tuples when matching images""" """Expands given path and returns the leaf node. The path items can be plain strings. In that case, exact string matching happens. Path items can also be compiled regexps, where the ``match`` method is used to determine if the node is the one we want. And finally, the path items can be 2-tuples, where the second item can be the string or regular expression and the first item is the image to be matched using :py:meth:`image_getter` method. Args: *path: The path (explained above) Returns: The leaf WebElement. Raises: :py:class:`exceptions.CandidateNotFound` when the node is not found in the tree. """ """Expands the path and clicks the leaf node. See :py:meth:`expand_path` for more informations about synopsis. """ """Expands the passed path and checks a checkbox that is located at the node.""" """Expands the passed path and unchecks a checkbox that is located at the node.""" """Check if a checkbox is checked on the node in that path.""" """ Method used to look up the exact path to an item we know only by its regexp or partial description. Expands whole tree during the execution. Args: target: Item searched for. Can be regexp made by :py:func:`re.compile <python:re.compile>`, otherwise it is taken as a string for `in` matching. exact: Useful in string matching. If set to True, it matches the exact string. Default is False. Returns: :py:class:`list` with path to that item. """ """ A class directed at CFME Tree elements The Tree class aims to deal with all kinds of CFME trees Args: locator: This is a locator object pointing to the ``<ul>`` element which contains the rest of the table. Returns: A :py:class:`Tree` object. A Tree object is set up by using a locator which contains the node elements. This element will usually be a ``<ul>`` in the case of a Dynatree. Usage: tree = web_ui.Tree((By.XPATH, '//table//tr[@title="Datastore"]/../..')) The path can then be navigated to return the last object in the path list, like so:: tree.click_path('Automation', 'VM Lifecycle Management (VMLifecycle)', 'VM Migrate (Migrate)') Each path element will be expanded along the way, but will not be clicked. When used in a :py:class:`Form`, a list of path tuples is expected in the form fill data. The paths will be passed individually to :py:meth:`Tree.check_node`:: form = Form(fields=[ ('tree_field', List(locator)), ]) form_fill_data = { 'tree_field': [ ('Tree Node', 'Value'), ('Tree Node', 'Branch Node', 'Value'), ] ] Note: Dynatrees, rely on a ``<ul><li>`` setup. We class a ``<li>`` as a node. """ """ Exposes a path. Args: *path: The path as multiple positional string arguments denoting the course to take. Keywords: by_id: Whether to match ids instead of text. Returns: The leaf web element. """ """ Exposes a path and then clicks it. Args: *path: The path as multiple positional string arguments denoting the course to take. Keywords: by_id: Whether to match ids instead of text. Returns: The leaf web element. """ """Browse through tree via path. If node not found, raises exception. If the browsing reached leaf(str), returns True if also the step was last, otherwise False. If the result of the path is a subtree, it is returned. Args: tree: List with tree. *path: Path to browse. """ """Extracts just node names from current tree (top). It makes: .. code-block:: python ["asd", "fgh", ("ijk", [...]), ("lmn", [...])] to .. code-block:: python ["asd", "fgh", "ijk", "lmn"] Useful for checking of contents of current tree level """ """ Method used to look up the exact path to an item we know only by its regexp or partial description. Expands whole tree during the execution. Args: target: Item searched for. Can be regexp made by :py:func:`re.compile <python:re.compile>`, otherwise it is taken as a string for `in` matching. exact: Useful in string matching. If set to True, it matches the exact string. Default is False. Returns: :py:class:`list` with path to that item. """ """Tree that has a checkbox on each node, adds methods to check/uncheck them""" """ Checks or unchecks a node. Args: *path: The path as multiple positional string arguments denoting the course to take. check: If ``True``, the node is checked, ``False`` the node is unchecked. """ """ Convenience function to check a node Args: *path: The path as multiple positional string arguments denoting the course to take. """ """ Convenience function to uncheck a node Args: *path: The path as multiple positional string arguments denoting the course to take. """ """values should be a list of tuple pairs, where the first item is the path to select, and the second is whether to check or uncheck. Usage: select(cbtree, [(['Foo', 'Bar'], False), (['Baz'], True)]) """ """In case you want to find the item by icon in the value field (like OS infra diff.)""" """A present for @smyers""" """ Represents a single quadruple icon in the CFME UI. A Quadicon contains multiple quadrants. These are accessed via attributes. The qtype is currently one of the following and determines which attribute names are present. They are mapped internally and can be reassigned easily if the UI changes. A Quadicon is used by defining the name of the icon and the type. After that, it can be used to obtain the locator of the Quadicon, or query its quadrants, via attributes. Args: name: The label of the icon. qtype: The type of the quad icon. By default it is ``None``, therefore plain quad without any retrievable data usable for selecting/clicking. Usage: qi = web_ui.Quadicon('hostname.local', 'host') qi.creds click(qi) .. rubric:: Known Quadicon Types and Attributes * **host** - *from the infra/host page* - has quads: * a. **no_vm** - Number of VMs * b. **state** - The current state of the host * c. **vendor** - The vendor of the host * d. **creds** - If the creds are valid * **infra_prov** - *from the infra/providers page* - has quads: * a. **no_host** - Number of hosts * b. *Blank* * c. **vendor** - The vendor of the provider * d. **creds** - If the creds are valid * **vm** - *from the infra/virtual_machines page* - has quads: * a. **os** - The OS of the vm * b. **state** - The current state of the vm * c. **vendor** - The vendor of the vm's host * d. **no_snapshot** - The number of snapshots * g. **policy** - The state of the policy * **cloud_prov** - *from the cloud/providers page* - has quads: * a. **no_instance** - Number of instances * b. **no_image** - Number of machine images * c. **vendor** - The vendor of the provider * d. **creds** - If the creds are valid * **instance** - *from the cloud/instances page* - has quads: * a. **os** - The OS of the instance * b. **state** - The current state of the instance * c. **vendor** - The vendor of the instance's host * d. **no_snapshot** - The number of snapshots * g. **policy** - The state of the policy * **datastore** - *from the infra/datastores page* - has quads: * a. **type** - File system type * b. **no_vm** - Number of VMs * c. **no_host** - Number of hosts * d. **avail_space** - Available space * **cluster** - *from the infra/cluster page* - has no quads * **resource_pool** - *from the infra/resource_pool page* - has no quads * **stack** - *from the clouds/stacks page* - has no quads Returns: A :py:class:`Quadicon` object. """ """ Returns: a locator for the internal checkbox for the quadicon""" """ Returns: a locator for the quadicon anchor""" """ Returns: a locator for the specific quadrant""" """ Queries the quadrants by name Args: name: The name of the quadrant identifier, as defined above. Returns: A string containing a representation of what is in the quadrant. """ """Allows iteration over Quadicons. Args: qtype: Quadicon type. Refer to the constructor for reference. this_page: Whether to look for Quadicons only on current page (do not list pages). Returns: :py:class:`list` of :py:class:`Quadicon` """ """ Returns name of the quadicon.""" """ Checks if the quad icon is a single quadrant icon.""" """ A special Select object for CFME's icon enhanced DHTMLx Select elements. Args: loc: A locator. Returns a :py:class:`cfme.web_ui.DHTMLSelect` object. """ """ Get's the name reference of the element from its hidden attribute. """ """ Returns all selected options. Note: Since the DHTML select can only have one option selected at a time, we simple return the first element (the only element). Returns: A Web element. """ """ Returns the first selected option in the DHTML select Note: In a DHTML select, there is only one option selectable at a time. Returns: A webelement. """ """ Returns a list of options of the select as webelements. Returns: A list of Webelements. """ """ Selects an option by index. Args: index: The select element's option by index. """ """ Selects an option by visible text. Args: text: The select element option's visible text. """ """ Selects an option by value. Args: value: The select element's option value. """ """ Filters requests pages This class inherits Form as its base and adds a few methods to assist in filtering request pages. Usage: f = Filter(fields=[ ('type', Select('//select[@id="type_choice"]')), ('approved', Input("<API key>")), ('denied', Input"<API key>")), ('pending_approval', Input("<API key>")), ('date', Select('//select[@id="time_period"]')), ('reason', Input("reason_text")), ]) f.apply_filter(type="VM Clone", approved=False, pending_approval=False, date="Last 24 Hours", reason="Just Because") """ """ Method to reset the filter back to defaults. """ """ Method to reset the changes to the filter since last applying. """ """ Method to apply a filter. First resets the filter to default and then applies the filter. Args: **kwargs: A dictionary of form elements to fill and their values. """ """Represents a UI widget where there are two select boxes, one with possible selections, and another with selected items. Has two arrow buttons to move items between the two""" """Multiselect with two arrows (up/down) next to it. Eg. in AE/Domain priority selection. Args: select_loc: Locator for the select box (without Select element wrapping) up_loc: Locator of the Move Up arrow. down_loc: Locator with Move Down arrow. """ """Represents a script box as is present on the customization templates pages. This box has to be activated before keys can be sent. Since this can't be done until the box element is visible, and some dropdowns change the element, it must be activated "inline". Args: """ """This function now clears and sets the ScriptBox. """ """Class used for filling those bunches of checkboxes I (@mfalesni) always hated to search for. Can fill by values, text or both. To search the text for the checkbox, you have 2 choices: * If the text can be got from parent's tag (like `<div><input type="checkbox">blablabla</div>` where blablabla is the checkbox's description looked up), you can leave the `text_access_func` unfilled. * If there is more complicated layout and you don't mind a bit slower operation, you can pass the text_access_func, which should be like `lambda checkbox_el: get_text_of(checkbox_el)`. The checkbox `WebElement` is passed to it and the description text is the expected output of the function. Args: search_root: Root element for checkbox search text_access_func: Function returning descriptive text about passed CB element. """ """All checkboxes.""" """Only selected checkboxes.""" """Only selected checkboxes' values.""" """Only unselected checkboxes.""" """Only unselected checkboxes' values.""" """Find checkbox's WebElement by id.""" """Selects all checkboxes.""" """Unselects all checkboxes.""" """Returns checkbox's WebElement by searched by its text.""" """Checking function. Args: values: Dictionary with key=CB name, value=bool with status. Look in the function to see. """ """This class abstracts out as a container of inputs, that appear after preceeding was filled. Args: *locators: In-order-of-display specification of locators. Keywords: min_values: How many values are required (Default: 0) """ """To delegate access to the separate locators""" """Class designed to fill the same value to multiple fields Args: *fields: The fields where the value will be mirrored """ """ Class representing the table (grid) specific to host drift analysis comparison page """ """ Finds cell element of the grid specified by column index and row text Args: row_text: Title text of the cell's row col_index: Column index of the cell, starting with 0 for 1st data-containing column Note: `col_index` of 0 is used for the 2nd actual column in the drift grid, because the 1st column does not contain headers, only row descriptions. Returns: Selenium element of the cell. """ """ Finds out if a cell, specified by column index and row text, indicates change Args: row_text: Title text of the cell's row col_index: Column index of the cell Note: `col_index` of 0 is used for the 2nd actual column in the drift grid, because the 1st column does not contain headers, only row descriptions. Returns: ``True`` if there is a change present, ``False`` otherwise """ """ Expands all sections to make the row elements found therein available """ """ A ButtonGroup is a set of buttons next to each other, as is used on the DefaultViews page. Args: key: The name of the key field text before the button group. """ """ Moves to the element """ """ Returns the alt tag text of the active button in thr group. """ """ Returns the status of the button identified by the Alt Text of the image. """ """ Sets the ButtonGroup to select the button identified by the alt text. """ """ A ColourGroup is a set of colour buttons next to each other, as is used on the DefaultViews page. Args: key: The name of the key field text before the button group. """ """ Moves to the element """ """ Returns the alt tag text of the active button in thr group. """ """ Returns the status of the color button identified by the Title Text of the image. """ """ Sets the ColorGroup to select the button identified by the title text. """ """A table that can add or remove the rows. """ """Combines class from the button and from select.""" """Class encapsulating the e-mail selector, eg. in Control/Alarms editing.""" """Returns list of e-mails that are selected""" """Returns list of e-mail that users inside CFME have so that they can be selected""" """Remove specified e-mail Args: email: E-mail to remove """ """Function for filling e-mails Args: emails: List of e-mails that should be filled. Any existing e-mails that are not in this variable will be deleted. """ """A Bootstrap On/Off switch Args: input_id: The HTML ID of the input element associated with the checkbox """ """Convenience function""" """Checks the bootstrap box""" """Unchecks the bootstrap box""" """Returns the first visible angular helper text (like 'Required').""" """An original HTML checkbox element Args: input_id: The HTML ID of the input element associated with the checkbox """ """ Checks or unchecks Args: value: The value the checkbox should represent as a bool (or None to do nothing) Returns: Previous state of the checkbox """ """Convenience function""" """Convenience function""" """Returns a list of breadcrumbs names if names==True else return as elements. Returns: :py:class:`list` of breadcrumbs if they are present, :py:class:`NoneType` otherwise. """ """Returns a title of the page. Returns: :py:class:`str` if present, :py:class:`NoneType` otherwise. """ """Returns a title of the page. Returns: :py:class:`str` if present, :py:class:`NoneType` otherwise. """ """Returns a title of the page. Returns: :py:class:`str` if present, :py:class:`NoneType` otherwise. """ """Does exact match of passed data Returns: :py:class:`bool` """ """ Status box as seen in containers overview page Status box modelling. Args: name: The name of the status box as it appears in CFME, e.g. 'Nodes' Returns: A StatusBox instance. """
// The LLVM Compiler Infrastructure // This file is distributed under the University of Illinois Open Source // This file defines the ModuleMap implementation, which describes the layout // of a module as it relates to headers. #include "clang/Lex/ModuleMap.h" #include "clang/Lex/Lexer.h" #include "clang/Lex/LiteralSupport.h" #include "clang/Lex/LexDiagnostic.h" #include "clang/Basic/Diagnostic.h" #include "clang/Basic/DiagnosticOptions.h" #include "clang/Basic/FileManager.h" #include "clang/Basic/TargetInfo.h" #include "clang/Basic/TargetOptions.h" #include "llvm/Support/Allocator.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Host.h" #include "llvm/Support/PathV2.h" #include "llvm/Support/raw_ostream.h" #include "llvm/ADT/StringRef.h" #include "llvm/ADT/StringSwitch.h" #include <stdlib.h> using namespace clang; Module::ExportDecl ModuleMap::resolveExport(Module *Mod, const Module::<API key> &Unresolved, bool Complain) { // We may have just a wildcard. if (Unresolved.Id.empty()) { assert(Unresolved.Wildcard && "Invalid unresolved export"); return Module::ExportDecl(0, true); } // Find the starting module. Module *Context = <API key>(Unresolved.Id[0].first, Mod); if (!Context) { if (Complain) Diags->Report(Unresolved.Id[0].second, diag::<API key>) << Unresolved.Id[0].first << Mod->getFullModuleName(); return Module::ExportDecl(); } // Dig into the module path. for (unsigned I = 1, N = Unresolved.Id.size(); I != N; ++I) { Module *Sub = <API key>(Unresolved.Id[I].first, Context); if (!Sub) { if (Complain) Diags->Report(Unresolved.Id[I].second, diag::<API key>) << Unresolved.Id[I].first << Context->getFullModuleName() << SourceRange(Unresolved.Id[0].second, Unresolved.Id[I-1].second); return Module::ExportDecl(); } Context = Sub; } return Module::ExportDecl(Context, Unresolved.Wildcard); } ModuleMap::ModuleMap(FileManager &FileMgr, const DiagnosticConsumer &DC, const LangOptions &LangOpts, const TargetInfo *Target) : LangOpts(LangOpts), Target(Target), BuiltinIncludeDir(0) { IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(new DiagnosticIDs); Diags = IntrusiveRefCntPtr<DiagnosticsEngine>( new DiagnosticsEngine(DiagIDs, new DiagnosticOptions)); Diags->setClient(DC.clone(*Diags), /*ShouldOwnClient=*/true); SourceMgr = new SourceManager(*Diags, FileMgr); } ModuleMap::~ModuleMap() { for (llvm::StringMap<Module *>::iterator I = Modules.begin(), IEnd = Modules.end(); I != IEnd; ++I) { delete I->getValue(); } delete SourceMgr; } void ModuleMap::setTarget(const TargetInfo &Target) { assert((!this->Target || this->Target == &Target) && "Improper target override"); this->Target = &Target; } \brief "Sanitize" a filename so that it can be used as an identifier. static StringRef <API key>(StringRef Name, SmallVectorImpl<char> &Buffer) { if (Name.empty()) return Name; // Check whether the filename is already an identifier; this is the common // case. bool isIdentifier = true; for (unsigned I = 0, N = Name.size(); I != N; ++I) { if (isalpha(Name[I]) || Name[I] == '_' || (isdigit(Name[I]) && I > 0)) continue; isIdentifier = false; break; } if (!isIdentifier) { // If we don't already have something with the form of an identifier, // create a buffer with the sanitized name. Buffer.clear(); if (isdigit(Name[0])) Buffer.push_back('_'); Buffer.reserve(Buffer.size() + Name.size()); for (unsigned I = 0, N = Name.size(); I != N; ++I) { if (isalnum(Name[I]) || isspace(Name[I])) Buffer.push_back(Name[I]); else Buffer.push_back('_'); } Name = StringRef(Buffer.data(), Buffer.size()); } while (llvm::StringSwitch<bool>(Name) #define KEYWORD(Keyword,Conditions) .Case(#Keyword, true) #define ALIAS(Keyword, AliasOf, Conditions) .Case(Keyword, true) #include "clang/Basic/TokenKinds.def" .Default(false)) { if (Name.data() != Buffer.data()) Buffer.append(Name.begin(), Name.end()); Buffer.push_back('_'); Name = StringRef(Buffer.data(), Buffer.size()); } return Name; } Module *ModuleMap::findModuleForHeader(const FileEntry *File) { HeadersMap::iterator Known = Headers.find(File); if (Known != Headers.end()) { // If a header is not available, don't report that it maps to anything. if (!Known->second.isAvailable()) return 0; return Known->second.getModule(); } const DirectoryEntry *Dir = File->getDir(); llvm::SmallVector<const DirectoryEntry *, 2> SkippedDirs; StringRef DirName = Dir->getName(); // Keep walking up the directory hierarchy, looking for a directory with // an umbrella header. do { llvm::DenseMap<const DirectoryEntry *, Module *>::iterator KnownDir = UmbrellaDirs.find(Dir); if (KnownDir != UmbrellaDirs.end()) { Module *Result = KnownDir->second; // Search up the module stack until we find a module with an umbrella // directory. Module *UmbrellaModule = Result; while (!UmbrellaModule->getUmbrellaDir() && UmbrellaModule->Parent) UmbrellaModule = UmbrellaModule->Parent; if (UmbrellaModule->InferSubmodules) { // Infer submodules for each of the directories we found between // the directory of the umbrella header and the directory where // the actual header is located. bool Explicit = UmbrellaModule-><API key>; for (unsigned I = SkippedDirs.size(); I != 0; --I) { // Find or create the module that corresponds to this directory name. SmallString<32> NameBuf; StringRef Name = <API key>( llvm::sys::path::stem(SkippedDirs[I-1]->getName()), NameBuf); Result = findOrCreateModule(Name, Result, /*IsFramework=*/false, Explicit).first; // Associate the module and the directory. UmbrellaDirs[SkippedDirs[I-1]] = Result; // If inferred submodules export everything they import, add a // wildcard to the set of exports. if (UmbrellaModule->InferExportWildcard && Result->Exports.empty()) Result->Exports.push_back(Module::ExportDecl(0, true)); } // Infer a submodule with the same name as this header file. SmallString<32> NameBuf; StringRef Name = <API key>( llvm::sys::path::stem(File->getName()), NameBuf); Result = findOrCreateModule(Name, Result, /*IsFramework=*/false, Explicit).first; Result->TopHeaders.insert(File); // If inferred submodules export everything they import, add a // wildcard to the set of exports. if (UmbrellaModule->InferExportWildcard && Result->Exports.empty()) Result->Exports.push_back(Module::ExportDecl(0, true)); } else { // Record each of the directories we stepped through as being part of // the module we found, since the umbrella header covers them all. for (unsigned I = 0, N = SkippedDirs.size(); I != N; ++I) UmbrellaDirs[SkippedDirs[I]] = Result; } Headers[File] = KnownHeader(Result, /*Excluded=*/false); // If a header corresponds to an unavailable module, don't report // that it maps to anything. if (!Result->isAvailable()) return 0; return Result; } SkippedDirs.push_back(Dir); // Retrieve our parent path. DirName = llvm::sys::path::parent_path(DirName); if (DirName.empty()) break; // Resolve the parent path to a directory entry. Dir = SourceMgr->getFileManager().getDirectory(DirName); } while (Dir); return 0; } bool ModuleMap::<API key>(const FileEntry *Header) { HeadersMap::iterator Known = Headers.find(Header); if (Known != Headers.end()) return !Known->second.isAvailable(); const DirectoryEntry *Dir = Header->getDir(); llvm::SmallVector<const DirectoryEntry *, 2> SkippedDirs; StringRef DirName = Dir->getName(); // Keep walking up the directory hierarchy, looking for a directory with // an umbrella header. do { llvm::DenseMap<const DirectoryEntry *, Module *>::iterator KnownDir = UmbrellaDirs.find(Dir); if (KnownDir != UmbrellaDirs.end()) { Module *Found = KnownDir->second; if (!Found->isAvailable()) return true; // Search up the module stack until we find a module with an umbrella // directory. Module *UmbrellaModule = Found; while (!UmbrellaModule->getUmbrellaDir() && UmbrellaModule->Parent) UmbrellaModule = UmbrellaModule->Parent; if (UmbrellaModule->InferSubmodules) { for (unsigned I = SkippedDirs.size(); I != 0; --I) { // Find or create the module that corresponds to this directory name. SmallString<32> NameBuf; StringRef Name = <API key>( llvm::sys::path::stem(SkippedDirs[I-1]->getName()), NameBuf); Found = <API key>(Name, Found); if (!Found) return false; if (!Found->isAvailable()) return true; } // Infer a submodule with the same name as this header file. SmallString<32> NameBuf; StringRef Name = <API key>( llvm::sys::path::stem(Header->getName()), NameBuf); Found = <API key>(Name, Found); if (!Found) return false; } return !Found->isAvailable(); } SkippedDirs.push_back(Dir); // Retrieve our parent path. DirName = llvm::sys::path::parent_path(DirName); if (DirName.empty()) break; // Resolve the parent path to a directory entry. Dir = SourceMgr->getFileManager().getDirectory(DirName); } while (Dir); return false; } Module *ModuleMap::findModule(StringRef Name) { llvm::StringMap<Module *>::iterator Known = Modules.find(Name); if (Known != Modules.end()) return Known->getValue(); return 0; } Module *ModuleMap::<API key>(StringRef Name, Module *Context) { for(; Context; Context = Context->Parent) { if (Module *Sub = <API key>(Name, Context)) return Sub; } return findModule(Name); } Module *ModuleMap::<API key>(StringRef Name, Module *Context) { if (!Context) return findModule(Name); return Context->findSubmodule(Name); } std::pair<Module *, bool> ModuleMap::findOrCreateModule(StringRef Name, Module *Parent, bool IsFramework, bool IsExplicit) { // Try to find an existing module with this name. if (Module *Sub = <API key>(Name, Parent)) return std::make_pair(Sub, false); // Create a new module with this name. Module *Result = new Module(Name, SourceLocation(), Parent, IsFramework, IsExplicit); if (!Parent) Modules[Name] = Result; return std::make_pair(Result, true); } bool ModuleMap::<API key>(const DirectoryEntry *ParentDir, StringRef Name, bool &IsSystem) { // Check whether we have already looked into the parent directory // for a module map. llvm::DenseMap<const DirectoryEntry *, InferredDirectory>::iterator inferred = InferredDirectories.find(ParentDir); if (inferred == InferredDirectories.end()) return false; if (!inferred->second.InferModules) return false; // We're allowed to infer for this directory, but make sure it's okay // to infer this particular module. bool canInfer = std::find(inferred->second.ExcludedModules.begin(), inferred->second.ExcludedModules.end(), Name) == inferred->second.ExcludedModules.end(); if (canInfer && inferred->second.InferSystemModules) IsSystem = true; return canInfer; } Module * ModuleMap::<API key>(StringRef ModuleName, const DirectoryEntry *FrameworkDir, bool IsSystem, Module *Parent) { // Check whether we've already found this module. if (Module *Mod = <API key>(ModuleName, Parent)) return Mod; FileManager &FileMgr = SourceMgr->getFileManager(); // If the framework has a parent path from which we're allowed to infer // a framework module, do so. if (!Parent) { bool canInfer = false; if (llvm::sys::path::has_parent_path(FrameworkDir->getName())) { // Figure out the parent path. StringRef Parent = llvm::sys::path::parent_path(FrameworkDir->getName()); if (const DirectoryEntry *ParentDir = FileMgr.getDirectory(Parent)) { // Check whether we have already looked into the parent directory // for a module map. llvm::DenseMap<const DirectoryEntry *, InferredDirectory>::iterator inferred = InferredDirectories.find(ParentDir); if (inferred == InferredDirectories.end()) { // We haven't looked here before. Load a module map, if there is // one. SmallString<128> ModMapPath = Parent; llvm::sys::path::append(ModMapPath, "module.map"); if (const FileEntry *ModMapFile = FileMgr.getFile(ModMapPath)) { parseModuleMapFile(ModMapFile); inferred = InferredDirectories.find(ParentDir); } if (inferred == InferredDirectories.end()) inferred = InferredDirectories.insert( std::make_pair(ParentDir, InferredDirectory())).first; } if (inferred->second.InferModules) { // We're allowed to infer for this directory, but make sure it's okay // to infer this particular module. StringRef Name = llvm::sys::path::filename(FrameworkDir->getName()); canInfer = std::find(inferred->second.ExcludedModules.begin(), inferred->second.ExcludedModules.end(), Name) == inferred->second.ExcludedModules.end(); if (inferred->second.InferSystemModules) IsSystem = true; } } } // If we're not allowed to infer a framework module, don't. if (!canInfer) return 0; } // Look for an umbrella header. SmallString<128> UmbrellaName = StringRef(FrameworkDir->getName()); llvm::sys::path::append(UmbrellaName, "Headers"); llvm::sys::path::append(UmbrellaName, ModuleName + ".h"); const FileEntry *UmbrellaHeader = FileMgr.getFile(UmbrellaName); // FIXME: If there's no umbrella header, we could probably scan the // framework to load *everything*. But, it's not clear that this is a good // idea. if (!UmbrellaHeader) return 0; Module *Result = new Module(ModuleName, SourceLocation(), Parent, /*IsFramework=*/true, /*IsExplicit=*/false); if (IsSystem) Result->IsSystem = IsSystem; if (!Parent) Modules[ModuleName] = Result; // umbrella header "<API key>" Result->Umbrella = UmbrellaHeader; Headers[UmbrellaHeader] = KnownHeader(Result, /*Excluded=*/false); UmbrellaDirs[UmbrellaHeader->getDir()] = Result; // export * Result->Exports.push_back(Module::ExportDecl(0, true)); // module * { export * } Result->InferSubmodules = true; Result->InferExportWildcard = true; // Look for subframeworks. llvm::error_code EC; SmallString<128> <API key> = StringRef(FrameworkDir->getName()); llvm::sys::path::append(<API key>, "Frameworks"); SmallString<128> <API key>; llvm::sys::path::native(<API key>.str(), <API key>); for (llvm::sys::fs::directory_iterator Dir(<API key>.str(), EC), DirEnd; Dir != DirEnd && !EC; Dir.increment(EC)) { if (!StringRef(Dir->path()).endswith(".framework")) continue; if (const DirectoryEntry *SubframeworkDir = FileMgr.getDirectory(Dir->path())) { // Note: as an egregious but useful hack, we use the real path here and // check whether it is actually a subdirectory of the parent directory. // This will not be the case if the 'subframework' is actually a symlink // out to a top-level framework. #ifdef LLVM_ON_UNIX char <API key>[PATH_MAX]; if (realpath(Dir->path().c_str(), <API key>)) { StringRef SubframeworkDirName = <API key>; bool FoundParent = false; do { // Get the parent directory name. SubframeworkDirName = llvm::sys::path::parent_path(SubframeworkDirName); if (SubframeworkDirName.empty()) break; if (FileMgr.getDirectory(SubframeworkDirName) == FrameworkDir) { FoundParent = true; break; } } while (true); if (!FoundParent) continue; } #endif // FIXME: Do we want to warn about subframeworks without umbrella headers? SmallString<32> NameBuf; <API key>(<API key>( llvm::sys::path::stem(Dir->path()), NameBuf), SubframeworkDir, IsSystem, Result); } } return Result; } void ModuleMap::setUmbrellaHeader(Module *Mod, const FileEntry *UmbrellaHeader){ Headers[UmbrellaHeader] = KnownHeader(Mod, /*Excluded=*/false); Mod->Umbrella = UmbrellaHeader; UmbrellaDirs[UmbrellaHeader->getDir()] = Mod; } void ModuleMap::setUmbrellaDir(Module *Mod, const DirectoryEntry *UmbrellaDir) { Mod->Umbrella = UmbrellaDir; UmbrellaDirs[UmbrellaDir] = Mod; } void ModuleMap::addHeader(Module *Mod, const FileEntry *Header, bool Excluded) { if (Excluded) Mod->ExcludedHeaders.push_back(Header); else Mod->Headers.push_back(Header); Headers[Header] = KnownHeader(Mod, Excluded); } const FileEntry * ModuleMap::<API key>(Module *Module) { if (Module->DefinitionLoc.isInvalid() || !SourceMgr) return 0; return SourceMgr->getFileEntryForID( SourceMgr->getFileID(Module->DefinitionLoc)); } void ModuleMap::dump() { llvm::errs() << "Modules:"; for (llvm::StringMap<Module *>::iterator M = Modules.begin(), MEnd = Modules.end(); M != MEnd; ++M) M->getValue()->print(llvm::errs(), 2); llvm::errs() << "Headers:"; for (HeadersMap::iterator H = Headers.begin(), HEnd = Headers.end(); H != HEnd; ++H) { llvm::errs() << " \"" << H->first->getName() << "\" -> " << H->second.getModule()->getFullModuleName() << "\n"; } } bool ModuleMap::resolveExports(Module *Mod, bool Complain) { bool HadError = false; for (unsigned I = 0, N = Mod->UnresolvedExports.size(); I != N; ++I) { Module::ExportDecl Export = resolveExport(Mod, Mod->UnresolvedExports[I], Complain); if (Export.getPointer() || Export.getInt()) Mod->Exports.push_back(Export); else HadError = true; } Mod->UnresolvedExports.clear(); return HadError; } Module *ModuleMap::<API key>(FullSourceLoc Loc) { if (Loc.isInvalid()) return 0; // Use the expansion location to determine which module we're in. FullSourceLoc ExpansionLoc = Loc.getExpansionLoc(); if (!ExpansionLoc.isFileID()) return 0; const SourceManager &SrcMgr = Loc.getManager(); FileID ExpansionFileID = ExpansionLoc.getFileID(); while (const FileEntry *ExpansionFile = SrcMgr.getFileEntryForID(ExpansionFileID)) { // Find the module that owns this header (if any). if (Module *Mod = findModuleForHeader(ExpansionFile)) return Mod; // No module owns this header, so look up the inclusion chain to see if // any included header has an associated module. SourceLocation IncludeLoc = SrcMgr.getIncludeLoc(ExpansionFileID); if (IncludeLoc.isInvalid()) return 0; ExpansionFileID = SrcMgr.getFileID(IncludeLoc); } return 0; } // Module map file parser namespace clang { \brief A token in a module map file. struct MMToken { enum TokenKind { Comma, EndOfFile, HeaderKeyword, Identifier, ExcludeKeyword, ExplicitKeyword, ExportKeyword, FrameworkKeyword, ModuleKeyword, Period, UmbrellaKeyword, RequiresKeyword, Star, StringLiteral, LBrace, RBrace, LSquare, RSquare } Kind; unsigned Location; unsigned StringLength; const char *StringData; void clear() { Kind = EndOfFile; Location = 0; StringLength = 0; StringData = 0; } bool is(TokenKind K) const { return Kind == K; } SourceLocation getLocation() const { return SourceLocation::getFromRawEncoding(Location); } StringRef getString() const { return StringRef(StringData, StringLength); } }; \brief The set of attributes that can be attached to a module. struct Attributes { Attributes() : IsSystem() { } \brief Whether this is a system module. unsigned IsSystem : 1; }; class ModuleMapParser { Lexer &L; SourceManager &SourceMgr; \brief Default target information, used only for string literal parsing. const TargetInfo *Target; DiagnosticsEngine &Diags; ModuleMap &Map; \brief The directory that this module map resides in. const DirectoryEntry *Directory; \brief The directory containing Clang-supplied headers. const DirectoryEntry *BuiltinIncludeDir; \brief Whether an error occurred. bool HadError; \brief Stores string data for the various string literals referenced during parsing. llvm::BumpPtrAllocator StringData; \brief The current token. MMToken Tok; \brief The active module. Module *ActiveModule; \brief Consume the current token and return its location. SourceLocation consumeToken(); \brief Skip tokens until we reach the a token with the given kind (or the end of the file). void skipUntil(MMToken::TokenKind K); typedef llvm::SmallVector<std::pair<std::string, SourceLocation>, 2> ModuleId; bool parseModuleId(ModuleId &Id); void parseModuleDecl(); void parseRequiresDecl(); void parseHeaderDecl(SourceLocation UmbrellaLoc, SourceLocation ExcludeLoc); void <API key>(SourceLocation UmbrellaLoc); void parseExportDecl(); void <API key>(bool Framework, bool Explicit); bool <API key>(Attributes &Attrs); const DirectoryEntry *<API key>(); public: explicit ModuleMapParser(Lexer &L, SourceManager &SourceMgr, const TargetInfo *Target, DiagnosticsEngine &Diags, ModuleMap &Map, const DirectoryEntry *Directory, const DirectoryEntry *BuiltinIncludeDir) : L(L), SourceMgr(SourceMgr), Target(Target), Diags(Diags), Map(Map), Directory(Directory), BuiltinIncludeDir(BuiltinIncludeDir), HadError(false), ActiveModule(0) { Tok.clear(); consumeToken(); } bool parseModuleMapFile(); }; } SourceLocation ModuleMapParser::consumeToken() { retry: SourceLocation Result = Tok.getLocation(); Tok.clear(); Token LToken; L.LexFromRawLexer(LToken); Tok.Location = LToken.getLocation().getRawEncoding(); switch (LToken.getKind()) { case tok::raw_identifier: Tok.StringData = LToken.<API key>(); Tok.StringLength = LToken.getLength(); Tok.Kind = llvm::StringSwitch<MMToken::TokenKind>(Tok.getString()) .Case("header", MMToken::HeaderKeyword) .Case("exclude", MMToken::ExcludeKeyword) .Case("explicit", MMToken::ExplicitKeyword) .Case("export", MMToken::ExportKeyword) .Case("framework", MM<API key>) .Case("module", MMToken::ModuleKeyword) .Case("requires", MMToken::RequiresKeyword) .Case("umbrella", MMToken::UmbrellaKeyword) .Default(MMToken::Identifier); break; case tok::comma: Tok.Kind = MMToken::Comma; break; case tok::eof: Tok.Kind = MMToken::EndOfFile; break; case tok::l_brace: Tok.Kind = MMToken::LBrace; break; case tok::l_square: Tok.Kind = MMToken::LSquare; break; case tok::period: Tok.Kind = MMToken::Period; break; case tok::r_brace: Tok.Kind = MMToken::RBrace; break; case tok::r_square: Tok.Kind = MMToken::RSquare; break; case tok::star: Tok.Kind = MMToken::Star; break; case tok::string_literal: { if (LToken.hasUDSuffix()) { Diags.Report(LToken.getLocation(), diag::<API key>); HadError = true; goto retry; } // Parse the string literal. LangOptions LangOpts; StringLiteralParser StringLiteral(&LToken, 1, SourceMgr, LangOpts, *Target); if (StringLiteral.hadError) goto retry; // Copy the string literal into our string data allocator. unsigned Length = StringLiteral.GetStringLength(); char *Saved = StringData.Allocate<char>(Length + 1); memcpy(Saved, StringLiteral.GetString().data(), Length); Saved[Length] = 0; // Form the token. Tok.Kind = MMToken::StringLiteral; Tok.StringData = Saved; Tok.StringLength = Length; break; } case tok::comment: goto retry; default: Diags.Report(LToken.getLocation(), diag::<API key>); HadError = true; goto retry; } return Result; } void ModuleMapParser::skipUntil(MMToken::TokenKind K) { unsigned braceDepth = 0; unsigned squareDepth = 0; do { switch (Tok.Kind) { case MMToken::EndOfFile: return; case MMToken::LBrace: if (Tok.is(K) && braceDepth == 0 && squareDepth == 0) return; ++braceDepth; break; case MMToken::LSquare: if (Tok.is(K) && braceDepth == 0 && squareDepth == 0) return; ++squareDepth; break; case MMToken::RBrace: if (braceDepth > 0) --braceDepth; else if (Tok.is(K)) return; break; case MMToken::RSquare: if (squareDepth > 0) --squareDepth; else if (Tok.is(K)) return; break; default: if (braceDepth == 0 && squareDepth == 0 && Tok.is(K)) return; break; } consumeToken(); } while (true); } \brief Parse a module-id. module-id: identifier identifier '.' module-id \returns true if an error occurred, false otherwise. bool ModuleMapParser::parseModuleId(ModuleId &Id) { Id.clear(); do { if (Tok.is(MMToken::Identifier)) { Id.push_back(std::make_pair(Tok.getString(), Tok.getLocation())); consumeToken(); } else { Diags.Report(Tok.getLocation(), diag::<API key>); return true; } if (!Tok.is(MMToken::Period)) break; consumeToken(); } while (true); return false; } namespace { \brief Enumerates the known attributes. enum AttributeKind { \brief An unknown attribute. AT_unknown, \brief The 'system' attribute. AT_system }; } \brief Parse a module declaration. module-declaration: 'explicit'[opt] 'framework'[opt] 'module' module-id attributes[opt] { module-member* } module-member: <API key> header-declaration <API key> export-declaration <API key>: module-declaration <API key> void ModuleMapParser::parseModuleDecl() { assert(Tok.is(MMToken::ExplicitKeyword) || Tok.is(MMToken::ModuleKeyword) || Tok.is(MM<API key>)); // Parse 'explicit' or 'framework' keyword, if present. SourceLocation ExplicitLoc; bool Explicit = false; bool Framework = false; // Parse 'explicit' keyword, if present. if (Tok.is(MMToken::ExplicitKeyword)) { ExplicitLoc = consumeToken(); Explicit = true; } // Parse 'framework' keyword, if present. if (Tok.is(MM<API key>)) { consumeToken(); Framework = true; } // Parse 'module' keyword. if (!Tok.is(MMToken::ModuleKeyword)) { Diags.Report(Tok.getLocation(), diag::<API key>); consumeToken(); HadError = true; return; } consumeToken(); // 'module' keyword // If we have a wildcard for the module name, this is an inferred submodule. // Parse it. if (Tok.is(MMToken::Star)) return <API key>(Framework, Explicit); // Parse the module name. ModuleId Id; if (parseModuleId(Id)) { HadError = true; return; } if (ActiveModule) { if (Id.size() > 1) { Diags.Report(Id.front().second, diag::<API key>) << SourceRange(Id.front().second, Id.back().second); HadError = true; return; } } else if (Id.size() == 1 && Explicit) { // Top-level modules can't be explicit. Diags.Report(ExplicitLoc, diag::<API key>); Explicit = false; ExplicitLoc = SourceLocation(); HadError = true; } Module *<API key> = ActiveModule; if (Id.size() > 1) { // This module map defines a submodule. Go find the module of which it // is a submodule. ActiveModule = 0; for (unsigned I = 0, N = Id.size() - 1; I != N; ++I) { if (Module *Next = Map.<API key>(Id[I].first, ActiveModule)) { ActiveModule = Next; continue; } if (ActiveModule) { Diags.Report(Id[I].second, diag::<API key>) << Id[I].first << ActiveModule->getTopLevelModule(); } else { Diags.Report(Id[I].second, diag::<API key>); } HadError = true; return; } } StringRef ModuleName = Id.back().first; SourceLocation ModuleNameLoc = Id.back().second; // Parse the optional attribute list. Attributes Attrs; <API key>(Attrs); // Parse the opening brace. if (!Tok.is(MMToken::LBrace)) { Diags.Report(Tok.getLocation(), diag::<API key>) << ModuleName; HadError = true; return; } SourceLocation LBraceLoc = consumeToken(); // Determine whether this (sub)module has already been defined. if (Module *Existing = Map.<API key>(ModuleName, ActiveModule)) { if (Existing->DefinitionLoc.isInvalid() && !ActiveModule) { // Skip the module definition. skipUntil(MMToken::RBrace); if (Tok.is(MMToken::RBrace)) consumeToken(); else { Diags.Report(Tok.getLocation(), diag::<API key>); Diags.Report(LBraceLoc, diag::<API key>); HadError = true; } return; } Diags.Report(ModuleNameLoc, diag::<API key>) << ModuleName; Diags.Report(Existing->DefinitionLoc, diag::<API key>); // Skip the module definition. skipUntil(MMToken::RBrace); if (Tok.is(MMToken::RBrace)) consumeToken(); HadError = true; return; } // Start defining this module. ActiveModule = Map.findOrCreateModule(ModuleName, ActiveModule, Framework, Explicit).first; ActiveModule->DefinitionLoc = ModuleNameLoc; if (Attrs.IsSystem) ActiveModule->IsSystem = true; bool Done = false; do { switch (Tok.Kind) { case MMToken::EndOfFile: case MMToken::RBrace: Done = true; break; case MMToken::ExplicitKeyword: case MM<API key>: case MMToken::ModuleKeyword: parseModuleDecl(); break; case MMToken::ExportKeyword: parseExportDecl(); break; case MMToken::RequiresKeyword: parseRequiresDecl(); break; case MMToken::UmbrellaKeyword: { SourceLocation UmbrellaLoc = consumeToken(); if (Tok.is(MMToken::HeaderKeyword)) parseHeaderDecl(UmbrellaLoc, SourceLocation()); else <API key>(UmbrellaLoc); break; } case MMToken::ExcludeKeyword: { SourceLocation ExcludeLoc = consumeToken(); if (Tok.is(MMToken::HeaderKeyword)) { parseHeaderDecl(SourceLocation(), ExcludeLoc); } else { Diags.Report(Tok.getLocation(), diag::<API key>) << "exclude"; } break; } case MMToken::HeaderKeyword: parseHeaderDecl(SourceLocation(), SourceLocation()); break; default: Diags.Report(Tok.getLocation(), diag::<API key>); consumeToken(); break; } } while (!Done); if (Tok.is(MMToken::RBrace)) consumeToken(); else { Diags.Report(Tok.getLocation(), diag::<API key>); Diags.Report(LBraceLoc, diag::<API key>); HadError = true; } // We're done parsing this module. Pop back to the previous module. ActiveModule = <API key>; } \brief Parse a requires declaration. <API key>: 'requires' feature-list feature-list: identifier ',' feature-list identifier void ModuleMapParser::parseRequiresDecl() { assert(Tok.is(MMToken::RequiresKeyword)); // Parse 'requires' keyword. consumeToken(); // Parse the feature-list. do { if (!Tok.is(MMToken::Identifier)) { Diags.Report(Tok.getLocation(), diag::<API key>); HadError = true; return; } // Consume the feature name. std::string Feature = Tok.getString(); consumeToken(); // Add this feature. ActiveModule->addRequirement(Feature, Map.LangOpts, *Map.Target); if (!Tok.is(MMToken::Comma)) break; // Consume the comma. consumeToken(); } while (true); } \brief Append to \p Paths the set of paths needed to get to the subframework in which the given module lives. static void <API key>(Module *Mod, llvm::SmallVectorImpl<char> &Path) { // Collect the framework names from the given module to the top-level module. llvm::SmallVector<StringRef, 2> Paths; for (; Mod; Mod = Mod->Parent) { if (Mod->IsFramework) Paths.push_back(Mod->Name); } if (Paths.empty()) return; // Add Frameworks/Name.framework for each subframework. for (unsigned I = Paths.size() - 1; I != 0; --I) { llvm::sys::path::append(Path, "Frameworks"); llvm::sys::path::append(Path, Paths[I-1] + ".framework"); } } \brief Determine whether the given file name is the name of a builtin header, supplied by Clang to replace, override, or augment existing system headers. static bool isBuiltinHeader(StringRef FileName) { return llvm::StringSwitch<bool>(FileName) .Case("float.h", true) .Case("iso646.h", true) .Case("limits.h", true) .Case("stdalign.h", true) .Case("stdarg.h", true) .Case("stdbool.h", true) .Case("stddef.h", true) .Case("stdint.h", true) .Case("tgmath.h", true) .Case("unwind.h", true) .Default(false); } \brief Parse a header declaration. header-declaration: 'umbrella'[opt] 'header' string-literal 'exclude'[opt] 'header' string-literal void ModuleMapParser::parseHeaderDecl(SourceLocation UmbrellaLoc, SourceLocation ExcludeLoc) { assert(Tok.is(MMToken::HeaderKeyword)); consumeToken(); bool Umbrella = UmbrellaLoc.isValid(); bool Exclude = ExcludeLoc.isValid(); assert(!(Umbrella && Exclude) && "Cannot have both 'umbrella' and 'exclude'"); // Parse the header name. if (!Tok.is(MMToken::StringLiteral)) { Diags.Report(Tok.getLocation(), diag::<API key>) << "header"; HadError = true; return; } std::string FileName = Tok.getString(); SourceLocation FileNameLoc = consumeToken(); // Check whether we already have an umbrella. if (Umbrella && ActiveModule->Umbrella) { Diags.Report(FileNameLoc, diag::<API key>) << ActiveModule->getFullModuleName(); HadError = true; return; } // Look for this file. const FileEntry *File = 0; const FileEntry *BuiltinFile = 0; SmallString<128> PathName; if (llvm::sys::path::is_absolute(FileName)) { PathName = FileName; File = SourceMgr.getFileManager().getFile(PathName); } else if (const DirectoryEntry *Dir = <API key>()) { PathName = Dir->getName(); llvm::sys::path::append(PathName, FileName); File = SourceMgr.getFileManager().getFile(PathName); } else { // Search for the header file within the search directory. PathName = Directory->getName(); unsigned PathLength = PathName.size(); if (ActiveModule->isPartOfFramework()) { <API key>(ActiveModule, PathName); // Check whether this file is in the public headers. llvm::sys::path::append(PathName, "Headers"); llvm::sys::path::append(PathName, FileName); File = SourceMgr.getFileManager().getFile(PathName); if (!File) { // Check whether this file is in the private headers. PathName.resize(PathLength); llvm::sys::path::append(PathName, "PrivateHeaders"); llvm::sys::path::append(PathName, FileName); File = SourceMgr.getFileManager().getFile(PathName); } } else { // Lookup for normal headers. llvm::sys::path::append(PathName, FileName); File = SourceMgr.getFileManager().getFile(PathName); // If this is a system module with a top-level header, this header // may have a counterpart (or replacement) in the set of headers // supplied by Clang. Find that builtin header. if (ActiveModule->IsSystem && !Umbrella && BuiltinIncludeDir && BuiltinIncludeDir != Directory && isBuiltinHeader(FileName)) { SmallString<128> BuiltinPathName(BuiltinIncludeDir->getName()); llvm::sys::path::append(BuiltinPathName, FileName); BuiltinFile = SourceMgr.getFileManager().getFile(BuiltinPathName); // If Clang supplies this header but the underlying system does not, // just silently swap in our builtin version. Otherwise, we'll end // up adding both (later). if (!File && BuiltinFile) { File = BuiltinFile; BuiltinFile = 0; } } } } // FIXME: We shouldn't be eagerly stat'ing every file named in a module map. // Come up with a lazy way to do this. if (File) { if (ModuleMap::KnownHeader OwningModule = Map.Headers[File]) { Diags.Report(FileNameLoc, diag::<API key>) << FileName << OwningModule.getModule()->getFullModuleName(); HadError = true; } else if (Umbrella) { const DirectoryEntry *UmbrellaDir = File->getDir(); if (Module *UmbrellaModule = Map.UmbrellaDirs[UmbrellaDir]) { Diags.Report(UmbrellaLoc, diag::<API key>) << UmbrellaModule->getFullModuleName(); HadError = true; } else { // Record this umbrella header. Map.setUmbrellaHeader(ActiveModule, File); } } else { // Record this header. Map.addHeader(ActiveModule, File, Exclude); // If there is a builtin counterpart to this file, add it now. if (BuiltinFile) Map.addHeader(ActiveModule, BuiltinFile, Exclude); } } else { Diags.Report(FileNameLoc, diag::<API key>) << Umbrella << FileName; HadError = true; } } \brief Parse an umbrella directory declaration. <API key>: umbrella string-literal void ModuleMapParser::<API key>(SourceLocation UmbrellaLoc) { // Parse the directory name. if (!Tok.is(MMToken::StringLiteral)) { Diags.Report(Tok.getLocation(), diag::<API key>) << "umbrella"; HadError = true; return; } std::string DirName = Tok.getString(); SourceLocation DirNameLoc = consumeToken(); // Check whether we already have an umbrella. if (ActiveModule->Umbrella) { Diags.Report(DirNameLoc, diag::<API key>) << ActiveModule->getFullModuleName(); HadError = true; return; } // Look for this file. const DirectoryEntry *Dir = 0; if (llvm::sys::path::is_absolute(DirName)) Dir = SourceMgr.getFileManager().getDirectory(DirName); else { SmallString<128> PathName; PathName = Directory->getName(); llvm::sys::path::append(PathName, DirName); Dir = SourceMgr.getFileManager().getDirectory(PathName); } if (!Dir) { Diags.Report(DirNameLoc, diag::<API key>) << DirName; HadError = true; return; } if (Module *OwningModule = Map.UmbrellaDirs[Dir]) { Diags.Report(UmbrellaLoc, diag::<API key>) << OwningModule->getFullModuleName(); HadError = true; return; } // Record this umbrella directory. Map.setUmbrellaDir(ActiveModule, Dir); } \brief Parse a module export declaration. export-declaration: 'export' wildcard-module-id wildcard-module-id: identifier '*' identifier '.' wildcard-module-id void ModuleMapParser::parseExportDecl() { assert(Tok.is(MMToken::ExportKeyword)); SourceLocation ExportLoc = consumeToken(); // Parse the module-id with an optional wildcard at the end. ModuleId ParsedModuleId; bool Wildcard = false; do { if (Tok.is(MMToken::Identifier)) { ParsedModuleId.push_back(std::make_pair(Tok.getString(), Tok.getLocation())); consumeToken(); if (Tok.is(MMToken::Period)) { consumeToken(); continue; } break; } if(Tok.is(MMToken::Star)) { Wildcard = true; consumeToken(); break; } Diags.Report(Tok.getLocation(), diag::<API key>); HadError = true; return; } while (true); Module::<API key> Unresolved = { ExportLoc, ParsedModuleId, Wildcard }; ActiveModule->UnresolvedExports.push_back(Unresolved); } \brief Parse an inferried module declaration (wildcard modules). module-declaration: 'explicit'[opt] 'framework'[opt] 'module' * attributes[opt] { <API key>* } <API key>: 'export' '*' 'exclude' identifier void ModuleMapParser::<API key>(bool Framework, bool Explicit) { assert(Tok.is(MMToken::Star)); SourceLocation StarLoc = consumeToken(); bool Failed = false; // Inferred modules must be submodules. if (!ActiveModule && !Framework) { Diags.Report(StarLoc, diag::<API key>); Failed = true; } if (ActiveModule) { // Inferred modules must have umbrella directories. if (!Failed && !ActiveModule->getUmbrellaDir()) { Diags.Report(StarLoc, diag::<API key>); Failed = true; } // Check for redefinition of an inferred module. if (!Failed && ActiveModule->InferSubmodules) { Diags.Report(StarLoc, diag::<API key>); if (ActiveModule-><API key>.isValid()) Diags.Report(ActiveModule-><API key>, diag::<API key>); Failed = true; } // Check for the 'framework' keyword, which is not permitted here. if (Framework) { Diags.Report(StarLoc, diag::<API key>); Framework = false; } } else if (Explicit) { Diags.Report(StarLoc, diag::<API key>); Explicit = false; } // If there were any problems with this inferred submodule, skip its body. if (Failed) { if (Tok.is(MMToken::LBrace)) { consumeToken(); skipUntil(MMToken::RBrace); if (Tok.is(MMToken::RBrace)) consumeToken(); } HadError = true; return; } // Parse optional attributes. Attributes Attrs; <API key>(Attrs); if (ActiveModule) { // Note that we have an inferred submodule. ActiveModule->InferSubmodules = true; ActiveModule-><API key> = StarLoc; ActiveModule-><API key> = Explicit; } else { // We'll be inferring framework modules for this directory. Map.InferredDirectories[Directory].InferModules = true; Map.InferredDirectories[Directory].InferSystemModules = Attrs.IsSystem; } // Parse the opening brace. if (!Tok.is(MMToken::LBrace)) { Diags.Report(Tok.getLocation(), diag::<API key>); HadError = true; return; } SourceLocation LBraceLoc = consumeToken(); // Parse the body of the inferred submodule. bool Done = false; do { switch (Tok.Kind) { case MMToken::EndOfFile: case MMToken::RBrace: Done = true; break; case MMToken::ExcludeKeyword: { if (ActiveModule) { Diags.Report(Tok.getLocation(), diag::<API key>) << (ActiveModule != 0); consumeToken(); break; } consumeToken(); if (!Tok.is(MMToken::Identifier)) { Diags.Report(Tok.getLocation(), diag::<API key>); break; } Map.InferredDirectories[Directory].ExcludedModules .push_back(Tok.getString()); consumeToken(); break; } case MMToken::ExportKeyword: if (!ActiveModule) { Diags.Report(Tok.getLocation(), diag::<API key>) << (ActiveModule != 0); consumeToken(); break; } consumeToken(); if (Tok.is(MMToken::Star)) ActiveModule->InferExportWildcard = true; else Diags.Report(Tok.getLocation(), diag::<API key>); consumeToken(); break; case MMToken::ExplicitKeyword: case MMToken::ModuleKeyword: case MMToken::HeaderKeyword: case MMToken::UmbrellaKeyword: default: Diags.Report(Tok.getLocation(), diag::<API key>) << (ActiveModule != 0); consumeToken(); break; } } while (!Done); if (Tok.is(MMToken::RBrace)) consumeToken(); else { Diags.Report(Tok.getLocation(), diag::<API key>); Diags.Report(LBraceLoc, diag::<API key>); HadError = true; } } \brief Parse optional attributes. attributes: attribute attributes attribute attribute: [ identifier ] \param Attrs Will be filled in with the parsed attributes. \returns true if an error occurred, false otherwise. bool ModuleMapParser::<API key>(Attributes &Attrs) { bool HadError = false; while (Tok.is(MMToken::LSquare)) { // Consume the '['. SourceLocation LSquareLoc = consumeToken(); // Check whether we have an attribute name here. if (!Tok.is(MMToken::Identifier)) { Diags.Report(Tok.getLocation(), diag::<API key>); skipUntil(MMToken::RSquare); if (Tok.is(MMToken::RSquare)) consumeToken(); HadError = true; } // Decode the attribute name. AttributeKind Attribute = llvm::StringSwitch<AttributeKind>(Tok.getString()) .Case("system", AT_system) .Default(AT_unknown); switch (Attribute) { case AT_unknown: Diags.Report(Tok.getLocation(), diag::<API key>) << Tok.getString(); break; case AT_system: Attrs.IsSystem = true; break; } consumeToken(); // Consume the ']'. if (!Tok.is(MMToken::RSquare)) { Diags.Report(Tok.getLocation(), diag::<API key>); Diags.Report(LSquareLoc, diag::<API key>); skipUntil(MMToken::RSquare); HadError = true; } if (Tok.is(MMToken::RSquare)) consumeToken(); } return HadError; } \brief If there is a specific header search directory due the presence of an umbrella directory, retrieve that directory. Otherwise, returns null. const DirectoryEntry *ModuleMapParser::<API key>() { for (Module *Mod = ActiveModule; Mod; Mod = Mod->Parent) { // If we have an umbrella directory, use that. if (Mod->hasUmbrellaDir()) return Mod->getUmbrellaDir(); // If we have a framework directory, stop looking. if (Mod->IsFramework) return 0; } return 0; } \brief Parse a module map file. module-map-file: module-declaration* bool ModuleMapParser::parseModuleMapFile() { do { switch (Tok.Kind) { case MMToken::EndOfFile: return HadError; case MMToken::ExplicitKeyword: case MMToken::ModuleKeyword: case MM<API key>: parseModuleDecl(); break; case MMToken::Comma: case MMToken::ExcludeKeyword: case MMToken::ExportKeyword: case MMToken::HeaderKeyword: case MMToken::Identifier: case MMToken::LBrace: case MMToken::LSquare: case MMToken::Period: case MMToken::RBrace: case MMToken::RSquare: case MMToken::RequiresKeyword: case MMToken::Star: case MMToken::StringLiteral: case MMToken::UmbrellaKeyword: Diags.Report(Tok.getLocation(), diag::<API key>); HadError = true; consumeToken(); break; } } while (true); } bool ModuleMap::parseModuleMapFile(const FileEntry *File) { assert(Target != 0 && "Missing target information"); FileID ID = SourceMgr->createFileID(File, SourceLocation(), SrcMgr::C_User); const llvm::MemoryBuffer *Buffer = SourceMgr->getBuffer(ID); if (!Buffer) return true; // Parse this module map file. Lexer L(ID, SourceMgr->getBuffer(ID), *SourceMgr, MMapLangOpts); Diags->getClient()->BeginSourceFile(MMapLangOpts); ModuleMapParser Parser(L, *SourceMgr, Target, *Diags, *this, File->getDir(), BuiltinIncludeDir); bool Result = Parser.parseModuleMapFile(); Diags->getClient()->EndSourceFile(); return Result; }
package org.tigris.subversion.javahl; import java.util.Date; /** * Class to describe a lock. It is returned by the lock operation. * @since 1.2 */ public class Lock implements java.io.Serializable { // Update the serialVersionUID when there is a incompatible change // made to this class. See any of the following, depending upon // the Java release. // http://java.sun.com/j2se/1.5.0/docs/guide/serialization/spec/version.html#6678 // http://java.sun.com/javase/6/docs/platform/serialization/spec/version.html#6678 private static final long serialVersionUID = 1L; /** * the owner of the lock */ private String owner; /** * the path of the locked item */ private String path; /** * the token provided during the lock operation */ private String token; /** * the comment provided during the lock operation */ private String comment; /** * the date when the lock was created */ private long creationDate; /** * the date when the lock will expire */ private long expirationDate; /** * this constructor should only called from JNI code * @param owner the owner of the lock * @param path the path of the locked item * @param token the lock token * @param comment the lock comment * @param creationDate the date when the lock was created * @param expirationDate the date when the lock will expire */ Lock(String owner, String path, String token, String comment, long creationDate, long expirationDate) { this.owner = owner; this.path = path; this.token = token; this.comment = comment; this.creationDate = creationDate; this.expirationDate = expirationDate; } /** * @return the owner of the lock */ public String getOwner() { return owner; } /** * @return the path of the locked item */ public String getPath() { return path; } /** * @return the token provided during the lock operation */ public String getToken() { return token; } /** * @return the comment provided during the lock operation */ public String getComment() { return comment; } /** * @return the date the lock was created */ public Date getCreationDate() { if (creationDate == 0) return null; else return new Date(creationDate/1000); } /** * @return the date when the lock will expire */ public Date getExpirationDate() { if (expirationDate == 0) return null; else return new Date(expirationDate/1000); } }
// THE LUNCHER // HOW TO COMPILE: // make launch // OPTIONS // -d program will run in debug mode // RUN THIS PROGRAM: // without debug: ./launch // with debug: ./launch -d // make launch && ./launch #include <stdio.h> #include <unistd.h> #include "example.h" #include "log.h" unsigned int m_is_debug = 0; int main(int argc, char *argv[]) { int option; // this will allow our program to get -d option in // the command line to check for debug while ((option = getopt(argc, argv, "d")) != EOF) { switch(option) { case 'd': m_is_debug = 1; break; default: break; } // these steps we use to make sure // we skip the options we read argc -= optind; argv += optind; } display_welcome(); // Clears the log and instantiate // a new instance of it clear_log_file(); if (open_log_file() && m_is_debug) fprintf(stderr,"Could not use the Log service\n"); if (m_is_debug) { log_info("[Main] Debug enabled"); fprintf(stderr,"Debug enabled\n"); } else { log_info("[Main] Debug disabled"); } log_warning("Deu um warning aqui bro"); log_erro("Deu um erro aqui bro"); log_info("Deu um info aqui bro"); return 0; }
<?php if (!defined('BASEPATH')) exit('No direct script access allowed'); class Report_types extends CI_Model { protected $_hooks = array(); function __construct() { parent::__construct(); // Fill up hooks array $pluginsConfig = Zend_Registry::getInstance()->get('pluginsConfig'); if (isset($pluginsConfig->common->report_types)) { foreach($pluginsConfig->common->report_types as $hookClass) { $hookObj = new $hookClass(); if ($hookObj instanceof <API key>) { $this->_hooks[] = $hookObj; } } } } //end Report_types public function get_list($params) { $this->db->select('id_report_type, title') ->join('report_types', 'roles.id_role=report_types.id_role') ->where('name', $params['role']); if (isset($params['group'])) { $this->db->where('report_group', $params['group']); } $res = $this->db->order_by('report_group ASC, report_order ASC') ->get('roles'); $list = array(); if (isset($params['all'])) { $list[0] = __('all'); } foreach ($res->result() as $row) { // Modify plugin's report type foreach($this->_hooks as $hookObj) { $row = $hookObj->modifyReportType(array($row, $params["role"])); } $list[$row->id_report_type] = __($row->title); } return $list; } //end get_list public function get_visible_columns($role, $id_entity, $group = 0) { $res = $this->db->select('report_types.id_report_type AS id_report_type, visible_columns*1 AS visible_columns', FALSE) ->join('report_types', 'roles.id_role=report_types.id_role') ->join('<API key>', 'report_types.id_report_type=<API key>.id_report_type') ->where(array('name' => $role, 'id_entity' => $id_entity, 'report_group' => $group)) ->get('roles'); $visible = array(); foreach ($res->result() as $row) { $visible[$row->id_report_type] = $row->visible_columns; } $this->db->select('report_types.id_report_type AS id_report_type, report_type_fields.title AS title, report_type_fields.name AS name, column_order, report_type_fields.is_unchanged'); $this->db->from('roles'); $this->db->join('report_types', 'roles.id_role=report_types.id_role'); $this->db->join('report_type_fields', 'report_types.id_report_type=report_type_fields.id_report_type'); $this->db->where(array('roles.name' => $role, 'report_group' => $group)); $this->db->order_by('id_report_type, column_order'); $res = $this->db->get(); $columns = array(); foreach ($res->result() as $row) { $columns[$row->id_report_type][$row->name]['title'] = __($row->title); $columns[$row->id_report_type][$row->name]['is_unchanged'] = 'true' == $row->is_unchanged ? true : false; if (isset($visible[$row->id_report_type])) { $columns[$row->id_report_type][$row->name]['visible'] = $columns[$row->id_report_type][$row->name]['is_unchanged'] || (($visible[$row->id_report_type] & (1 << $row->column_order)) > 0); } else { $columns[$row->id_report_type][$row->name]['visible'] = TRUE; } } return $columns; } //end get_visible_columns public function <API key>($id_entity, $id_report_type, $columns) { $this->db->where(array('id_entity' => $id_entity, 'id_report_type' => $id_report_type)) ->from('<API key>'); $records = $this->db->count_all_results(); if ($records) { $this->db->where(array('id_entity' => $id_entity, 'id_report_type' => $id_report_type)) ->update('<API key>', array('visible_columns' => $columns)); } else { $this->db->insert('<API key>', array( 'id_entity' => $id_entity, 'id_report_type' => $id_report_type, 'visible_columns' => $columns)); } } //end <API key> public function add_new_report($id_entity, $id_report_type, $visible_columns, $from, $to, $title, $extra = '') { $this->db->insert('requested_reports', array( 'id_entity' => $id_entity, 'custom_title' => $title, 'id_report_type' => $id_report_type, 'visible_columns' => $visible_columns, 'period_start' => type_to_str($from, 'databasedate'), 'period_end' => type_to_str($to, 'databasedate'), 'request_date' => type_to_str(time(), 'databasedatetime'), 'extra_params' => $extra ) ); return $this->db->insert_id(); } //end add_new_report public function get_reports($id_entity, $page, $per_page, $sort_field, $sort_direction, $range, $role, $type = 0, $group = NULL) { $this->db->select('id_requested_report, custom_title, title, unix_timestamp(request_date) as date'); $this->db->from('requested_reports'); $this->db->join('report_types', 'requested_reports.id_report_type = report_types.id_report_type'); $this->db->join('roles', 'report_types.id_role = roles.id_role'); $this->db->where('roles.name', $role); if (!is_null($group)) { $this->db->where('report_group', $group); } if ($type != 0) { $this->db->where('requested_reports.id_report_type', $type); } $this->db->where('requested_reports.id_entity', $id_entity); $this->db->where('DATE(request_date) >=', type_to_str($range['from'], 'databasedate')); $this->db->where('DATE(request_date) <=', type_to_str($range['to'], 'databasedate')); $this->db->order_by($sort_field, $sort_direction); $this->db->limit($per_page, ($page-1)*$per_page); $res = $this->db->get(); $reports = array(); foreach ($res->result() as $row) { foreach($this->_hooks as $hookObj) { $row = $hookObj->modifyReportType(array($row, $role)); } $reports[$row->id_requested_report]['title'] = $row->custom_title; $reports[$row->id_requested_report]['type'] = __($row->title); $reports[$row->id_requested_report]['date'] = type_to_str($row->date, 'date'); } return $reports; } //end get_reports public function report($id_entity, $id_report) { $this->db->select('custom_title, visible_columns*1 AS cols, UNIX_TIMESTAMP(period_start) AS date_from, UNIX_TIMESTAMP(period_end) AS date_to, extra_params, id_report_type, id_entity', FALSE); $this->db->from('requested_reports'); $this->db->where(array(/*'id_entity' => $id_entity, */'id_requested_report' => $id_report)); $res = $this->db->get(); foreach ($res->result() as $row) { return array( 'title' => $row->custom_title, 'type' => $row->id_report_type, 'vis' => $row->cols, 'from' => type_to_str($row->date_from, 'date'), 'to' => type_to_str($row->date_to, 'date'), 'extra' => $row->extra_params, 'id_entity' => $row->id_entity ); } return FALSE; } //end report public function action($action, $id_entity, $id_requested_report) { $this->db->where( array( 'id_entity' => $id_entity, 'id_requested_report' => $id_requested_report)); switch ($action) { case 'delete': $this->db->delete('requested_reports'); break; } } //end action public function total($id_entity, $range, $role, $type = 0, $group = NULL) { $this->db->where('id_entity', $id_entity); if (!is_null($group)) { $this->db->where('report_group', $group); } $this->db->where('request_date >=', type_to_str($range['from'], 'databasedatetime')); $this->db->where('request_date <=', type_to_str($range['to'], 'databasedatetime')); if ($type != 0) { $this->db->where('requested_reports.id_report_type', $type); } $this->db->join('report_types', 'requested_reports.id_report_type = report_types.id_report_type'); $this->db->join('roles', 'report_types.id_role = roles.id_role'); $this->db->where('roles.name', $role); $this->db->from('requested_reports'); return $this->db->count_all_results(); } //end total public function columns_info($id_report_type, $visible) { $this->db->select('report_type_fields.name AS name, report_type_fields.title AS title,'. ' field_types.name AS type, sort_column=column_order AS sorted, sort_direction, direction,'. ' report_type_fields.is_total, report_type_fields.is_unchanged, roles.name AS role'); $this->db->from('report_type_fields'); $this->db->join('field_types', 'report_type_fields.id_field_type = field_types.id_field_type'); $this->db->join('report_types', 'report_type_fields.id_report_type = report_types.id_report_type'); $this->db->join('roles', 'report_types.id_role = roles.id_role'); $this->db->where('report_type_fields.id_report_type', $id_report_type); $this->db->order_by('column_order'); $res = $this->db->get(); $bit = 1; $columns = array(); $sort = FALSE; $first = NULL; $first_dir = NULL; foreach ($res->result() as $row) { if (-1 == $visible || $row->is_unchanged == 'true' || $visible & $bit) { if (is_null($first)) { $first = $row->name; $first_dir = $row->direction; } $columns['columns'][$row->name]['title'] = $row->title; $columns['columns'][$row->name]['type'] = $row->type; $columns['columns'][$row->name]['direction'] = $row->direction; $columns['columns'][$row->name]['role'] = $row->role; $columns['columns'][$row->name]['is_total'] = 'true' == $row->is_total ? true : false; $columns['columns'][$row->name]['is_unchanged'] = 'true' == $row->is_unchanged ? true : false; if ($row->sorted) { $sort = TRUE; $columns['sort']['name'] = $row->name; $columns['sort']['direction'] = $row->sort_direction; } } $bit = $bit<<1; } if (!$sort) { $columns['sort']['name']= $first; $columns['sort']['direction'] = $first_dir; } return $columns; } //end columns_info } //end Report_types class ?>
/** \file Thread.cpp ** \date 2004-10-30 ** \author grymse@alhem.net **/ #include <stdio.h> #ifdef _WIN32 #include <process.h> #include "socket_include.h" #else #include <unistd.h> #endif #include <cstdlib> #include <iostream> #include "Thread.h" #include "Lock.h" #include "Mutex.h" #ifdef SOCKETS_NAMESPACE namespace SOCKETS_NAMESPACE { #endif // Mutex Thread::s_threadListMutex; // Thread::ThreadMap Thread::s_waiting_threads; // Mutex Thread::s_mutex; Thread::Thread(bool release) :m_thread(0) ,m_running(true) ,m_release(release) ,m_b_delete_on_exit(false) ,m_b_destructor(false) { } void Thread::Start() { // Lock runLock(m_runMutex); #ifdef _WIN32 // m_thread = ::CreateThread(NULL, 0, StartThread, this, 0, &m_dwThreadId); m_thread = (HANDLE)_beginthreadex(NULL, 0, &StartThread, this, 0, &m_dwThreadId); #else pthread_attr_t attr; pthread_attr_init(&attr); <API key>(&attr,<API key>); // if (pthread_create(&m_thread,&attr, StartThread,this) == -1) if (pthread_create(&m_thread, &attr, StartThread, this) == -1) { perror("Thread: create failed"); SetRunning(false); } // <API key>(&attr); #endif // m_release = release; // Lock runLock(m_runMutex); // Lock listLock(s_threadListMutex); // s_waiting_threads.insert(ThreadMap::value_type(this, &this->m_runMutex)); // std::cout << "constructor waiting: " << s_waiting_threads.size() << std::endl; } Thread::~Thread() { m_b_destructor = true; if (m_running) { SetRelease(true); SetRunning(false); #ifdef _WIN32 Sleep(1000); #else sleep(1); #endif } #ifdef _WIN32 if (m_thread) ::CloseHandle(m_thread); #endif } // Mutex Thread::s_mutex; threadfunc_t STDPREFIX Thread::StartThread(threadparam_t zz) { // std::cout << "worker waiting: " << s_waiting_threads.size() << std::endl; // Lock listLock(s_threadListMutex); // std::cout << "got lock waiting: " << s_waiting_threads.size() << std::endl; // Lock lock(s_mutex); // ThreadInfo *i = (ThreadInfo*) zz; // Lock runLock(*i->m); Thread *p = (Thread *)zz; while (p -> m_running && !p -> m_release) { #ifdef _WIN32 Sleep(1000); #else std::cout << "this shouldn't happen" <<std::endl; exit(-1); sleep(1); #endif } if (p -> m_running) { p -> Run(); } p -> SetRunning(false); // if return if (p -> DeleteOnExit() && !p -> IsDestructor()) { delete p; } #ifdef _WIN32 _endthreadex(0); #endif return (threadfunc_t)NULL; // delete i; // Lock runLock(p -> m_runMutex); p->Run(); p -> SetRunning(false); // if return if (p -> DeleteOnExit() && !p -> IsDestructor()) { delete p; } #ifdef _WIN32 _endthreadex(0); #endif return (threadfunc_t)NULL; // bool <API key> = false; // while(!<API key>) { // long unsigned int size = 0; // Lock listLock(s_threadListMutex); // size = s_waiting_threads.size(); // if (size == 0) { // // sleep(1); // continue; // Lock listLock(s_threadListMutex); // ThreadMap::iterator itr = s_waiting_threads.begin(); // Lock runLock(*(itr->second)); // p = itr->first; // s_waiting_threads.erase(itr); // <API key> = true; // /* bool bInList = false; // { // Lock listLock(s_threadListMutex); // ThreadMap::iterator itr = s_waiting_threads.find(p); // bInList = (itr != s_waiting_threads.end()); // } // if (!bInList ) { // std::cout << "not inlist" << std::endl; // sleep(1); // continue; // }*/ // /* Lock listLock(s_threadListMutex); // ThreadMap::iterator itr = s_waiting_threads.find(p); // if (itr == s_waiting_threads.end()) { // continue; // }*/ // // std::cout << "got listlock, waiting " << s_waiting_threads.size() << std::endl; // // for(ThreadMap::iterator itr=s_waiting_threads.begin(); itr != s_waiting_threads.end(); ++itr) { // // std::cout << "p = " << p << " itr=" << itr->first <<std::endl; // // ThreadMap::iterator itr = s_waiting_threads.find(p); // // std::cout << "found p in list " << p << std::endl; // // Lock runLock(*(itr->second)); // // <API key> = true; // // s_waiting_threads.erase(p); // Lock constructorLock(p->getMutex()); // Mutex threadMutex; // s_waiting_threads.insert(std::pair<p, threadMutex>); while (p -> m_running && !p -> m_release) { #ifdef _WIN32 Sleep(1000); #else std::cout << "this shouldn't happen" <<std::endl; exit(-1); sleep(1); #endif } if (p -> m_running) { p -> Run(); } p -> SetRunning(false); // if return if (p -> DeleteOnExit() && !p -> IsDestructor()) { delete p; } #ifdef _WIN32 _endthreadex(0); #endif return (threadfunc_t)NULL; } bool Thread::IsRunning() { return m_running; } void Thread::SetRunning(bool x) { m_running = x; } bool Thread::IsReleased() { return m_release; } void Thread::SetRelease(bool x) { m_release = x; } bool Thread::DeleteOnExit() { return m_b_delete_on_exit; } void Thread::SetDeleteOnExit(bool x) { m_b_delete_on_exit = x; } bool Thread::IsDestructor() { return m_b_destructor; } #ifdef SOCKETS_NAMESPACE } #endif