repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
mkroman/bl602-604
components/bl602/bl602_std/bl602_std/LHalDriver/Src/lhal_uart.c
#include "bl602_uart.h" #include "bl602_glb.h" #include "lhal_uart.h" static void LHAL_UART_TX_Int_CallBack0(void); static void LHAL_UART_TX_Int_CallBack1(void); static void LHAL_UART_RX_Int_CallBack0(void); static void LHAL_UART_RX_Int_CallBack1(void); static LHAL_UART_Handle_Type* uartHandlerList[UART_ID_MAX] = {NULL}; static intCallback_Type* uartTxIntCallBackList[UART_ID_MAX] = {&LHAL_UART_TX_Int_CallBack0,&LHAL_UART_TX_Int_CallBack1}; static intCallback_Type* uartRxIntCallBackList[UART_ID_MAX] = {&LHAL_UART_RX_Int_CallBack0,&LHAL_UART_RX_Int_CallBack1}; LHAL_Err_Type LHal_UART_Init(LHAL_UART_Handle_Type *uartHandler) { LHal_Glue_UART_Init(uartHandler); if(NULL!=uartHandler->txBuf){ Ring_Buffer_Init(&uartHandler->txRb,uartHandler->txBuf,uartHandler->txBufLen,uartHandler->txRbLock,uartHandler->txRbUnlock); } if(NULL!=uartHandler->rxBuf){ Ring_Buffer_Init(&uartHandler->rxRb,uartHandler->rxBuf,uartHandler->rxBufLen,uartHandler->rxRbLock,uartHandler->rxRbUnlock); } return LHAL_SUCCESS; } LHAL_Err_Type LHal_UART_DeInit(uint8_t uartId) { UART_DeInit((UART_ID_Type)uartId); return LHAL_SUCCESS; } LHAL_Err_Type LHal_UART_Send_Polling(LHAL_UART_Handle_Type *uartHandler,uint8_t *data,uint32_t len,uint32_t timout) { return LHal_Glue_UART_SendData(uartHandler,data,len); } int32_t LHal_UART_Recv_Polling(LHAL_UART_Handle_Type *uartHandler,uint8_t *data,uint32_t maxLen,uint32_t timout) { int32_t recvLen=0; //uint64_t curMs=0; //curMs=LHAL_Get_Time_MS(); do{ //if(LHAL_Get_Time_MS()>curMs+timout){ // return 0; //} recvLen+=LHal_Glue_UART_RecvData(uartHandler,data,maxLen); }while(recvLen==0); return recvLen; } LHAL_Err_Type LHal_UART_Send_IT(LHAL_UART_Handle_Type *uartHandler,uint8_t *data,uint32_t len,uint32_t timout) { uint32_t sentLen=0; uint32_t curLen=0; //uint64_t curMs=0; LHAL_Err_Type ret=LHAL_SUCCESS; if(NULL!=uartHandler->txBuf){ //curMs=LHAL_Get_Time_MS(); do{ /* do send data */ curLen=Ring_Buffer_Get_Empty_Length(&uartHandler->txRb); if(curLen>len-sentLen){ curLen=len-sentLen; } if(curLen==0){ LHal_Glue_UART_Enable_TX_Int(uartHandler); }else{ Ring_Buffer_Write(&uartHandler->txRb,data+sentLen,curLen); sentLen+=curLen; } if(timout==0&&sentLen<len){ ret=LHAL_ERROR; break; }else{ //if(LHAL_Get_Time_MS()>curMs+timout&&sentLen<len){ // return LHAL_TIMEOUT; //} } }while(sentLen<len); /* Enable TX interrupt anyway*/ LHal_Glue_UART_Enable_TX_Int(uartHandler); } return ret; } int32_t LHal_UART_Recv_IT(LHAL_UART_Handle_Type *uartHandler,uint8_t *data,uint32_t maxLen,uint32_t timout) { //uint64_t curMs=0; uint32_t recvLen=0; if(NULL!=uartHandler->rxBuf){ //curMs=LHAL_Get_Time_MS(); do{ recvLen=Ring_Buffer_Get_Length(&uartHandler->rxRb); if(recvLen>maxLen){ recvLen=maxLen; } if(timout==0&&recvLen==0){ LHal_Glue_UART_Enable_RX_Int(uartHandler); return 0; }else{ LHal_Glue_UART_Enable_RX_Int(uartHandler); //if(LHAL_Get_Time_MS()>curMs+timout&&recvLen==0){ // return LHAL_TIMEOUT; //} } }while(recvLen==0); maxLen=Ring_Buffer_Read(&uartHandler->rxRb,data,recvLen); LHal_Glue_UART_Enable_RX_Int(uartHandler); return maxLen; } return 0; } static void LHAL_UART_TX_RB_CallBack(void *parameter,uint8_t *data,uint16_t len) { LHAL_UART_Handle_Type *uartHandler=parameter; LHal_Glue_UART_SendData(uartHandler,data,len); } static void LHAL_UART_TX_Int_CallBack(uint8_t uartId) { uint32_t curLen=0; uint32_t emptyLen=0; LHAL_UART_Handle_Type *uartHandler=uartHandlerList[uartId]; if(NULL!=uartHandler->txBuf){ curLen=Ring_Buffer_Get_Length(&uartHandler->txRb); emptyLen=UART_GetTxFifoCount(uartHandler->cfg.id); if(curLen>emptyLen){ curLen=emptyLen; } if(curLen!=0){ /*Ring buffer has data, just send it out and return */ Ring_Buffer_Read_Callback(&uartHandler->txRb,curLen,LHAL_UART_TX_RB_CallBack,uartHandler); if(uartHandler->txDoneCallBack){ uartHandler->txDoneCallBack(uartHandler); } return; } } if(uartHandler->txFullCallBack){ uartHandler->txFullCallBack(uartHandler); } /* Mask interrupt and wait for data */ LHal_Glue_UART_Disable_TX_Int(uartHandler); } static void LHAL_UART_TX_Int_CallBack0(void) { LHAL_UART_TX_Int_CallBack(0); } static void LHAL_UART_TX_Int_CallBack1(void) { LHAL_UART_TX_Int_CallBack(1); } static void LHAL_UART_RX_RB_CallBack(void *parameter,uint8_t *data,uint16_t len) { LHAL_UART_Handle_Type *uartHandler=parameter; LHal_Glue_UART_RecvData(uartHandler,data,len); } static void LHAL_UART_RX_Int_CallBack(uint8_t uartId) { LHAL_UART_Handle_Type *uartHandler=uartHandlerList[uartId]; uint32_t rxLen=0; uint32_t emptyLen=0; if(NULL!=uartHandler->rxBuf){ emptyLen=Ring_Buffer_Get_Empty_Length(&uartHandler->rxRb); rxLen=UART_GetRxFifoCount(uartHandler->cfg.id); if(rxLen>emptyLen){ rxLen=emptyLen; } if(rxLen!=0){ Ring_Buffer_Write_Callback(&uartHandler->rxRb,rxLen,LHAL_UART_RX_RB_CallBack,uartHandler); if(uartHandler->rxDoneCallBack){ uartHandler->rxDoneCallBack(uartHandler); } return; }else{ LHal_Glue_UART_Disable_RX_Int(uartHandler); /*Ring buffer is full, what to do*/ if(uartHandler->rxFullCallBack){ uartHandler->rxFullCallBack(uartHandler); } } } } static void LHAL_UART_RX_Int_CallBack0(void) { LHAL_UART_RX_Int_CallBack(0); } static void LHAL_UART_RX_Int_CallBack1(void) { LHAL_UART_RX_Int_CallBack(1); } BL_Err_Type LHal_UART_Notify_Register(LHAL_UART_Handle_Type *uartHandler) { Ring_Buffer_Init(&uartHandler->txRb,uartHandler->txBuf,sizeof(uartHandler->txBuf),NULL,NULL); Ring_Buffer_Init(&uartHandler->rxRb,uartHandler->rxBuf,sizeof(uartHandler->rxBuf),NULL,NULL); return LHAL_SUCCESS; } LHAL_Err_Type LHal_Glue_UART_Init(LHAL_UART_Handle_Type *uartHandler) { UART_CFG_Type uartCfg = { 96*1000*1000, /* UART clock */ 115200, /* UART Baudrate */ UART_DATABITS_8, /* UART data bits length */ UART_STOPBITS_1, /* UART data stop bits length */ UART_PARITY_NONE, /* UART no parity */ DISABLE, /* Disable auto flow control */ DISABLE, /* Disable rx input de-glitch function */ DISABLE, /* Disable RTS output SW control mode */ UART_LSB_FIRST /* UART each data byte is send out LSB-first */ }; UART_FifoCfg_Type fifoCfg = { 16, /* TX FIFO threshold */ 16, /* RX FIFO threshold */ DISABLE, /* Disable tx dma req/ack interface */ DISABLE /* Disable rx dma req/ack interface */ }; uartHandlerList[uartHandler->cfg.id]=uartHandler; /* Apply config */ uartCfg.baudRate=uartHandler->cfg.baudRate; uartCfg.dataBits=uartHandler->cfg.dataBits-5+UART_DATABITS_5; uartCfg.stopBits=uartHandler->cfg.stopBits-1+UART_STOPBITS_1; uartCfg.parity=uartHandler->cfg.parity; if(uartHandler->cfg.enableRts){ uartCfg.rtsSoftwareControl=DISABLE; }else{ uartCfg.rtsSoftwareControl=ENABLE; } if(uartHandler->cfg.enableCts){ uartCfg.ctsFlowControl=ENABLE; }else{ uartCfg.ctsFlowControl=DISABLE; } /* Disable all interrupt */ UART_IntMask(uartHandler->cfg.id,UART_INT_ALL,MASK); /* Disable UART before config */ UART_Disable(uartHandler->cfg.id,UART_TXRX); /* UART init */ UART_Init(uartHandler->cfg.id,&uartCfg); /* UART fifo configuration */ UART_FifoConfig(uartHandler->cfg.id,&fifoCfg); /* Enable tx free run mode */ UART_TxFreeRun(uartHandler->cfg.id,ENABLE); /* Set rx time-out value */ UART_SetRxTimeoutValue(uartHandler->cfg.id,UART_DEFAULT_RECV_TIMEOUT); /* UART interrupt configuration */ if(NULL!=uartHandler->txBuf){ /* Install the interrupt callback function */ UART_Int_Callback_Install(uartHandler->cfg.id,UART_INT_TX_FIFO_REQ,uartTxIntCallBackList[uartHandler->cfg.id]); UART_IntMask(uartHandler->cfg.id,UART_INT_TX_FIFO_REQ,UNMASK); } if(NULL!=uartHandler->rxBuf){ UART_Int_Callback_Install(uartHandler->cfg.id,UART_INT_RX_FIFO_REQ,uartRxIntCallBackList[uartHandler->cfg.id]); UART_Int_Callback_Install(uartHandler->cfg.id,UART_INT_RTO,uartRxIntCallBackList[uartHandler->cfg.id]); UART_IntMask(uartHandler->cfg.id,UART_INT_RX_FIFO_REQ,UNMASK); UART_IntMask(uartHandler->cfg.id,UART_INT_RTO,UNMASK); } /* Enable UART interrupt*/ NVIC_EnableIRQ(uartHandler->cfg.id+UART0_IRQn); System_NVIC_SetPriority(uartHandler->cfg.id+UART0_IRQn,4,1); /* Enable UART */ if(uartHandler->cfg.enableTx&&uartHandler->cfg.enableRx){ UART_Enable(uartHandler->cfg.id,UART_TXRX); }else if(uartHandler->cfg.enableTx){ UART_Enable(uartHandler->cfg.id,UART_TX); }else if(uartHandler->cfg.enableRx){ UART_Enable(uartHandler->cfg.id,UART_RX); } return LHAL_SUCCESS; } LHAL_Err_Type LHal_Glue_UART_Enable_TX_Int(LHAL_UART_Handle_Type *uartHandler) { /* Mask interupt and wait for data */ UART_IntMask(uartHandler->cfg.id,UART_INT_TX_FIFO_REQ,UNMASK); return LHAL_SUCCESS; } LHAL_Err_Type LHal_Glue_UART_Enable_RX_Int(LHAL_UART_Handle_Type *uartHandler) { UART_IntMask(uartHandler->cfg.id,UART_INT_RX_FIFO_REQ,UNMASK); UART_IntMask(uartHandler->cfg.id,UART_INT_RTO,UNMASK); return LHAL_SUCCESS; } LHAL_Err_Type LHal_Glue_UART_Disable_TX_Int(LHAL_UART_Handle_Type *uartHandler) { /* Mask interupt and wait for data */ UART_IntMask(uartHandler->cfg.id,UART_INT_TX_FIFO_REQ,MASK); return LHAL_SUCCESS; } LHAL_Err_Type LHal_Glue_UART_Disable_RX_Int(LHAL_UART_Handle_Type *uartHandler) { UART_IntMask(uartHandler->cfg.id,UART_INT_RX_FIFO_REQ,MASK); UART_IntMask(uartHandler->cfg.id,UART_INT_RTO,MASK); return LHAL_SUCCESS; } LHAL_Err_Type LHal_Glue_UART_SendData(LHAL_UART_Handle_Type *uartHandler,uint8_t* data,uint32_t len) { BL_Err_Type ret=UART_SendData(uartHandler->cfg.id,data,len); if(ret==SUCCESS){ return LHAL_SUCCESS; }else if(ret==TIMEOUT){ return LHAL_TIMEOUT; } return LHAL_SUCCESS; } int32_t LHal_Glue_UART_RecvData(LHAL_UART_Handle_Type *uartHandler,uint8_t* data,uint32_t maxLen) { return UART_ReceiveData(uartHandler->cfg.id,data,maxLen); }
mkroman/bl602-604
components/hal_drv/bl602_hal/bl_gpio_cli.c
<gh_stars>0 /* * Copyright (c) 2020 Bouffalolab. * * This file is part of * *** Bouffalolab Software Dev Kit *** * (see www.bouffalolab.com). * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of Bouffalo Lab nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <stdlib.h> #include <stdio.h> #include <cli.h> #include "bl_gpio.h" static void cmd_gpio_func(char *buf, int len, int argc, char **argv) { int ionum = -1, inputmode = -1, pullup = -1, pulldown = -1; if (5 != argc) { printf("Usage: %s 24 1 1 0\r\n set GPIO24 to input with pullup\r\n", argv[0] ); return; } ionum = atoi(argv[1]); inputmode = atoi(argv[2]); pullup = atoi(argv[3]); pulldown = atoi(argv[4]); if (ionum < 0 || inputmode < 0 || pullup < 0 || pulldown < 0) { puts("Illegal arg\r\n"); return; } printf("GPIO%d is set %s with %s pullup %s pulldown\r\n", ionum, inputmode ? "input" : "output", pullup ? "Active" : "null", pulldown ? "Active" : "null" ); if (inputmode) { bl_gpio_enable_input(ionum, pullup ? 1 : 0, pulldown ? 1 : 0); } else { bl_gpio_enable_output(ionum, pullup ? 1 : 0, pulldown ? 1 : 0); } } static void cmd_gpio_set(char *buf, int len, int argc, char **argv) { int ionum = -1, val = -1; if (3 != argc) { printf("Usage: %s 24 1\r\n set GPIO24 output to high\r\n", argv[0] ); return; } ionum = atoi(argv[1]); val = atoi(argv[2]); if (ionum < 0 || val < 0) { puts("Illegal arg\r\n"); return; } printf("GPIO%d is set to %s\r\n", ionum, val ? "high" : "lo" ); bl_gpio_output_set(ionum, val ? 1 : 0); } static void cmd_gpio_get(char *buf, int len, int argc, char **argv) { int ionum = -1, ret; uint8_t val; if (2 != argc) { printf("Usage: %s 24\r\n get GPIO24 value\r\n", argv[0] ); return; } ionum = atoi(argv[1]); if (ionum < 0) { puts("Illegal arg\r\n"); return; } ret = bl_gpio_input_get(ionum, &val); printf("GPIO%d val is %s\r\n", ionum, 0 == ret ? (val ? "high" : "low") : "Err" ); } // STATIC_CLI_CMD_ATTRIBUTE makes this(these) command(s) static const static struct cli_command cmds_user[] STATIC_CLI_CMD_ATTRIBUTE = { {"gpio-func", "gpio-func pinnum 0/1[0:output, 1:input] 0/1[pullup] 0/1[pulldown]", cmd_gpio_func}, {"gpio-set", "gpio-set pinnum 0/1", cmd_gpio_set}, {"gpio-get", "gpio-get pinnum", cmd_gpio_get}, }; int bl_gpio_cli_init(void) { // static command(s) do NOT need to call aos_cli_register_command(s) to register. // However, calling aos_cli_register_command(s) here is OK but is of no effect as cmds_user are included in cmds list. // XXX NOTE: Calling this *empty* function is necessary to make cmds_user in this file to be kept in the final link. //return aos_cli_register_commands(cmds_user, sizeof(cmds_user)/sizeof(cmds_user[0])); return 0; }
mkroman/bl602-604
components/network/ble/blestack/src/include/bluetooth/buf.h
<gh_stars>0 /* * Copyright (c) 2020 Bouffalolab. * * This file is part of * *** Bouffalolab Software Dev Kit *** * (see www.bouffalolab.com). * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of Bouffalo Lab nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** @file * @brief Bluetooth data buffer API */ /* * Copyright (c) 2016 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ #ifndef ZEPHYR_INCLUDE_BLUETOOTH_BUF_H_ #define ZEPHYR_INCLUDE_BLUETOOTH_BUF_H_ /** * @brief Data buffers * @defgroup bt_buf Data buffers * @ingroup bluetooth * @{ */ #include <zephyr/types.h> #include <net/buf.h> #include <hci_host.h> /** Possible types of buffers passed around the Bluetooth stack */ enum bt_buf_type { /** HCI command */ BT_BUF_CMD, /** HCI event */ BT_BUF_EVT, /** Outgoing ACL data */ BT_BUF_ACL_OUT, /** Incoming ACL data */ BT_BUF_ACL_IN, }; /** Minimum amount of user data size for buffers passed to the stack. */ #define BT_BUF_USER_DATA_MIN 4 #if defined(CONFIG_BT_HCI_RAW) #define BT_BUF_RESERVE MAX(CONFIG_BT_HCI_RESERVE, CONFIG_BT_HCI_RAW_RESERVE) #else #define BT_BUF_RESERVE CONFIG_BT_HCI_RESERVE #endif /** Data size neeed for HCI RX buffers */ #define BT_BUF_RX_SIZE (BT_BUF_RESERVE + CONFIG_BT_RX_BUF_LEN) /** Allocate a buffer for incoming data * * This will set the buffer type so bt_buf_set_type() does not need to * be explicitly called before bt_recv_prio(). * * @param type Type of buffer. Only BT_BUF_EVT and BT_BUF_ACL_IN are * allowed. * @param timeout Timeout in milliseconds, or one of the special values * K_NO_WAIT and K_FOREVER. * @return A new buffer. */ struct net_buf *bt_buf_get_rx(enum bt_buf_type type, s32_t timeout); /** Allocate a buffer for an HCI Command Complete/Status Event * * This will set the buffer type so bt_buf_set_type() does not need to * be explicitly called before bt_recv_prio(). * * @param timeout Timeout in milliseconds, or one of the special values * K_NO_WAIT and K_FOREVER. * @return A new buffer. */ struct net_buf *bt_buf_get_cmd_complete(s32_t timeout); /** Allocate a buffer for an HCI Event * * This will set the buffer type so bt_buf_set_type() does not need to * be explicitly called before bt_recv_prio() or bt_recv(). * * @param evt HCI event code * @param discardable Whether the driver considers the event discardable. * @param timeout Timeout in milliseconds, or one of the special values * K_NO_WAIT and K_FOREVER. * @return A new buffer. */ struct net_buf *bt_buf_get_evt(u8_t evt, bool discardable, s32_t timeout); /** Set the buffer type * * @param buf Bluetooth buffer * @param type The BT_* type to set the buffer to */ static inline void bt_buf_set_type(struct net_buf *buf, enum bt_buf_type type) { *(u8_t *)net_buf_user_data(buf) = type; } /** Get the buffer type * * @param buf Bluetooth buffer * * @return The BT_* type to of the buffer */ static inline enum bt_buf_type bt_buf_get_type(struct net_buf *buf) { /* De-referencing the pointer from net_buf_user_data(buf) as a * pointer to an enum causes issues on qemu_x86 because the true * size is 8-bit, but the enum is 32-bit on qemu_x86. So we put in * a temporary cast to 8-bit to ensure only 8 bits are read from * the pointer. */ return (enum bt_buf_type)(*(u8_t *)net_buf_user_data(buf)); } /** * @} */ #endif /* ZEPHYR_INCLUDE_BLUETOOTH_BUF_H_ */
mkroman/bl602-604
components/hal_drv/bl602_hal/bl_adc.c
<gh_stars>0 /* * Copyright (c) 2020 Bouffalolab. * * This file is part of * *** Bouffalolab Software Dev Kit *** * (see www.bouffalolab.com). * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of Bouffalo Lab nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <stdio.h> #include <stdint.h> #include <string.h> #if 0 #include <device/vfs_uart.h> #include <vfs_err.h> #include <vfs_register.h> #include <hal/soc/uart.h> #include <aos/kernel.h> #endif #include "bl602_aon.h" #include "bl602_common.h" #include "bl602_glb.h" #include "bl602_hbn.h" #include "bl602_dma.h" #include "bl602_adc.h" #include <utils_log.h> //#define TEMP_OFFSET_X 22791 #define TEMP_OFFSET_X 2318 ADC_CFG_Type adcCfg = { .v18Sel=ADC_V18_SEL_1P82V, /*!< ADC 1.8V select */ .v11Sel=ADC_V11_SEL_1P1V, /*!< ADC 1.1V select */ .clkDiv=ADC_CLK_DIV_16, /*!< Clock divider */ .gain1=ADC_PGA_GAIN_NONE, /*!< PGA gain 1 */ .gain2=ADC_PGA_GAIN_NONE, /*!< PGA gain 2 */ .chopMode=ADC_CHOP_MOD_AZ_PGA_ON, /*!< ADC chop mode select */ .biasSel=ADC_BIAS_SEL_MAIN_BANDGAP, /*!< ADC current form main bandgap or aon bandgap */ .vcm=ADC_PGA_VCM_1V, /*!< ADC VCM value */ .vref=ADC_VREF_2V, /*!< ADC voltage reference */ .inputMode=ADC_INPUT_SINGLE_END, /*!< ADC input signal type */ .resWidth=ADC_DATA_WIDTH_16_WITH_256_AVERAGE, /*!< ADC resolution and oversample rate */ .offsetCalibEn=0, /*!< Offset calibration enable */ .offsetCalibVal=0, /*!< Offset calibration value */ }; ADC_FIFO_Cfg_Type adcFifoCfg = { .fifoThreshold = ADC_FIFO_THRESHOLD_1, .dmaEn = DISABLE, }; void ADC_Clock_Init(uint8_t div) { GLB_Set_ADC_CLK(ENABLE,GLB_ADC_CLK_96M,div); log_info("GLB_Set_ADC_CLK_Div(%d) == clock 96M/(%d+1)\r\n",div,div); } void TSEN_Calibration(void) { ADC_SET_TSVBE_LOW(); ADC_Start(); ARCH_Delay_MS(100); while(ADC_Get_FIFO_Count() == 0); ADC_Read_FIFO(); ADC_SET_TSVBE_HIGH(); ADC_Start(); ARCH_Delay_MS(100); while(ADC_Get_FIFO_Count() == 0); ADC_Read_FIFO(); ADC_SET_TSVBE_LOW(); } static void ADC_tsen_case(void) { ADC_Result_Type result; uint32_t regVal=0; uint8_t i=0; uint32_t v0=0,v1=0; float v_error=0; ADC_Reset(); ADC_Disable(); ADC_Enable(); ADC_Init(&adcCfg); ADC_Channel_Config(ADC_CHAN_TSEN_P,ADC_CHAN_GND,0); ADC_Tsen_Init(ADC_TSEN_MOD_INTERNAL_DIODE); ADC_FIFO_Cfg(&adcFifoCfg); TSEN_Calibration(); printf("\ntsen test case\n"); for(i=0;i<40;i++){ ADC_Start(); while(ADC_Get_FIFO_Count() == 0); do{ regVal = ADC_Read_FIFO(); ADC_Parse_Result(&regVal,1,&result); if(i%2 ==0){ v0 = result.value; }else{ v1 = result.value; } }while(ADC_Get_FIFO_Count() != 0); if(i%2 !=0){ v_error = (float)v0 - (float)v1; v_error = v_error - TEMP_OFFSET_X; v_error = v_error /7.753; printf(" v0=%ld v1 = %ld \n",v0,v1); //MSG(" ((v0-v1)-X)/7.753= %d \n",(uint32_t)(v_error * 1000)); printf(" chip Tempture = %ld degree centigrade\n",(uint32_t)(v_error)); } if( i%2 ==0 ) ADC_SET_TSVBE_HIGH(); else ADC_SET_TSVBE_LOW(); ARCH_Delay_MS(500); } } int test_adc_init(void) { ADC_Clock_Init(2); ADC_Reset(); ADC_Disable(); ADC_Enable(); ADC_Init(&adcCfg); ADC_Channel_Config(ADC_CHAN_TSEN_P, ADC_CHAN_GND, 0); ADC_Tsen_Init(ADC_TSEN_MOD_INTERNAL_DIODE); ADC_FIFO_Cfg(&adcFifoCfg); TSEN_Calibration(); return 0; } int test_adc_get(int16_t *tmp) { ADC_Result_Type result; uint32_t regVal=0; uint8_t i=0; uint32_t v0=0,v1=0; float v_error=0; for (i = 0; i < 2; i++) { ADC_Start(); while(ADC_Get_FIFO_Count() == 0) { extern void aos_msleep(int ms); aos_msleep(1); } do{ regVal = ADC_Read_FIFO(); ADC_Parse_Result(&regVal,1,&result); if(i%2 == 0) { v0 = result.value; } else { v1 = result.value; } } while(ADC_Get_FIFO_Count() != 0); if (i%2 != 0) { v_error = (float)v0 - (float)v1; //log_info("v_error = %d\r\n", v_error); v_error = v_error - TEMP_OFFSET_X; v_error = v_error / 7.753; //log_info("v0 = %ld, v1 = %ld\r\n", v0, v1); //log_info(" chip Tempture = %ld degree centigrade\r\n", (uint32_t)(v_error)); *tmp = (int16_t)v_error; } if (i%2 == 0) { ADC_SET_TSVBE_HIGH(); } else { ADC_SET_TSVBE_LOW(); } } return 0; } int test_adc_test(void) { ADC_tsen_case(); return 0; }
mkroman/bl602-604
components/bl602/bl602_std/bl602_std/StdDriver/Src/bl602_sf_cfg_ext.c
/** ****************************************************************************** * @file bl602_sf_cfg_ext.c * @version V1.0 * @date * @brief This file is the standard driver c file ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT(c) 2020 Bouffalo Lab</center></h2> * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of Bouffalo Lab nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************** */ #include "bl602_glb.h" #include "bl602_sf_cfg.h" #include "bl602_sf_cfg_ext.h" #include "bl602_xip_sflash.h" #include "bl602_romdriver.h" /** @addtogroup BL602_Peripheral_Driver * @{ */ /** @addtogroup SF_CFG_EXT * @{ */ /** @defgroup SF_CFG_EXT_Private_Macros * @{ */ #define BFLB_FLASH_CFG_MAGIC "FCFG" /*@} end of group SF_CFG_EXT_Private_Macros */ /** @defgroup SF_CFG_EXT_Private_Types * @{ */ /*@} end of group SF_CFG_EXT_Private_Types */ /** @defgroup SF_CFG_EXT_Private_Variables * @{ */ /*@} end of group SF_CFG_EXT_Private_Variables */ /** @defgroup SF_CFG_EXT_Global_Variables * @{ */ /*@} end of group SF_CFG_EXT_Global_Variables */ /** @defgroup SF_CFG_EXT_Private_Fun_Declaration * @{ */ /*@} end of group SF_CFG_EXT_Private_Fun_Declaration */ /** @defgroup SF_CFG_EXT_Private_Functions * @{ */ /****************************************************************************//** * @brief Init internal flash GPIO according to flash GPIO config * * @param None * * @return None * *******************************************************************************/ void ATTR_TCM_SECTION SF_Cfg_Init_Internal_Flash_Gpio(void) { GLB_GPIO_Cfg_Type gpioCfg = { .gpioPin = GLB_GPIO_PIN_0, .gpioFun = GPIO_FUN_SWGPIO, .gpioMode = GPIO_MODE_INPUT, .pullType = GPIO_PULL_NONE, .drive = 0, .smtCtrl = 1, }; /* Turn on Flash pad, GPIO23 - GPIO28 */ for(uint32_t pin=23;pin<29;pin++){ gpioCfg.gpioPin = pin; if(pin==24){ gpioCfg.pullType = GPIO_PULL_DOWN; }else{ gpioCfg.pullType = GPIO_PULL_NONE; } GLB_GPIO_Init(&gpioCfg); } } /****************************************************************************//** * @brief Get flash config according to flash ID * * @param flashID: Flash ID * @param pFlashCfg: Flash config pointer * * @return SUCCESS or ERROR * *******************************************************************************/ BL_Err_Type ATTR_TCM_SECTION SF_Cfg_Get_Flash_Cfg_Need_Lock(uint32_t flashID,SPI_Flash_Cfg_Type * pFlashCfg) { uint8_t buf[sizeof(SPI_Flash_Cfg_Type)+8]; uint32_t crc,*pCrc; if(flashID==0){ XIP_SFlash_Read_Via_Cache_Need_Lock(8+BL602_FLASH_XIP_BASE,buf,sizeof(SPI_Flash_Cfg_Type)+8); if(BL602_MemCmp(buf,BFLB_FLASH_CFG_MAGIC,4)==0){ crc=BFLB_Soft_CRC32((uint8_t *)buf+4,sizeof(SPI_Flash_Cfg_Type)); pCrc=(uint32_t *)(buf+4+sizeof(SPI_Flash_Cfg_Type)); if(*pCrc==crc){ BL602_MemCpy_Fast(pFlashCfg,(uint8_t *)buf+4,sizeof(SPI_Flash_Cfg_Type)); return SUCCESS ; } } }else{ return RomDriver_SF_Cfg_Get_Flash_Cfg_Need_Lock(flashID, pFlashCfg); } return ERROR; } /*@} end of group SF_CFG_EXT_Private_Functions */ /*@} end of group SF_CFG_EXT */ /*@} end of group BL602_Peripheral_Driver */
mkroman/bl602-604
components/network/ble/blestack/src/common/include/misc/stack.h
/* * Copyright (c) 2020 Bouffalolab. * * This file is part of * *** Bouffalolab Software Dev Kit *** * (see www.bouffalolab.com). * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of Bouffalo Lab nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @file stack.h * Stack usage analysis helpers */ /* * Copyright (c) 2015 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ #ifndef _MISC_STACK_H_ #define _MISC_STACK_H_ #include <misc/printk.h> #if defined(CONFIG_INIT_STACKS) static inline size_t stack_unused_space_get(const char *stack, size_t size) { size_t unused = 0; int i; #ifdef CONFIG_STACK_SENTINEL /* First 4 bytes of the stack buffer reserved for the sentinel * value, it won't be 0xAAAAAAAA for thread stacks. */ stack += 4; #endif /* TODO Currently all supported platforms have stack growth down and * there is no Kconfig option to configure it so this always build * "else" branch. When support for platform with stack direction up * (or configurable direction) is added this check should be confirmed * that correct Kconfig option is used. */ #if defined(STACK_GROWS_UP) for (i = size - 1; i >= 0; i--) { if ((unsigned char)stack[i] == 0xaa) { unused++; } else { break; } } #else for (i = 0; i < size; i++) { if ((unsigned char)stack[i] == 0xaa) { unused++; } else { break; } } #endif return unused; } #else static inline size_t stack_unused_space_get(const char *stack, size_t size) { return 0; } #endif #if defined(CONFIG_INIT_STACKS) && defined(CONFIG_PRINTK) static inline void stack_analyze(const char *name, const char *stack, unsigned int size) { unsigned int pcnt, unused = 0; unused = stack_unused_space_get(stack, size); /* Calculate the real size reserved for the stack */ pcnt = ((size - unused) * 100) / size; printk("%s (real size %u):\tunused %u\tusage %u / %u (%u %%)\n", name, size, unused, size - unused, size, pcnt); } #else static inline void stack_analyze(const char *name, const char *stack, unsigned int size) { } #endif #define STACK_ANALYZE(name, sym) \ stack_analyze(name, K_THREAD_STACK_BUFFER(sym), \ K_THREAD_STACK_SIZEOF(sym)) #endif /* _MISC_STACK_H_ */
mkroman/bl602-604
components/hal_drv/bl602_hal/bl_wifi.c
/* * Copyright (c) 2020 Bouffalolab. * * This file is part of * *** Bouffalolab Software Dev Kit *** * (see www.bouffalolab.com). * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of Bouffalo Lab nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <stdint.h> #include <string.h> #include <stdio.h> #include <bl602.h> #include "bl_efuse.h" #include "bl_wifi.h" #include "bl_irq.h" typedef struct _bl_wifi_env { uint8_t sta_mac_addr_board[6]; uint8_t sta_mac_addr_usr[6]; uint8_t ap_mac_addr_board[6]; uint8_t ap_mac_addr_usr[6]; uint8_t country_code; bl_wifi_ap_info_t ap_info; uint8_t ap_info_en; } bl_wifi_env_t; bl_wifi_env_t wifi_env; int bl_wifi_clock_enable(void) { static int called = 0; if (0 == called) { called = 1; //GLB_Set_System_CLK(PLL_XTAL_38P4M, GLB_PLL_CLK_160M); //GLB_Set_WiFi_Core_CLK(1);//0: 80MHZ, 1: 40MHZ } return 0; } void mac_irq(void); void bl_irq_handler(void); int bl_wifi_enable_irq(void) { bl_irq_register(WIFI_IRQn, mac_irq); bl_irq_register(WIFI_IPC_PUBLIC_IRQn, bl_irq_handler); bl_irq_enable(WIFI_IRQn); bl_irq_enable(WIFI_IPC_PUBLIC_IRQn); //NVIC_SetPriority((IRQn_Type)5, 0); //NVIC_EnableIRQ((IRQn_Type)5); puts("Enable BMX IRQ\r\n"); //NVIC_EnableIRQ((IRQn_Type)0); //NVIC_EnableIRQ((IRQn_Type)1); //NVIC_EnableIRQ((IRQn_Type)2); //NVIC_EnableIRQ((IRQn_Type)3); //NVIC_EnableIRQ((IRQn_Type)4); //*(uint32_t*)0x40000050 = ((0xF << 28) | (1 << 24)); return 0; } int bl_wifi_sta_mac_addr_set(uint8_t mac[6]) { memcpy(wifi_env.sta_mac_addr_board, mac, 6); return 0; } int bl_wifi_ap_mac_addr_set(uint8_t mac[6]) { memcpy(wifi_env.ap_mac_addr_board, mac, 6); return 0; } int bl_wifi_mac_addr_set(uint8_t mac[6]) { memcpy(wifi_env.sta_mac_addr_usr, mac, 6); return 0; } int bl_wifi_mac_addr_get(uint8_t mac[6]) { memcpy(mac, wifi_env.sta_mac_addr_board, 6); return 0; } int bl_wifi_country_code_set(uint8_t country_code) { wifi_env.country_code = country_code; return 0; } #if 0 int bl_wifi_power_table_set(bl_tx_pwr_tbl_t* tx_pwr_tbl) { bl60x_fw_rf_tx_power_table_set(tx_pwr_tbl); return 0; } #endif int bl_wifi_ap_info_set(uint8_t* ssid, uint8_t ssid_len, uint8_t* psk, uint8_t psk_len, uint8_t chan) { memset(&wifi_env.ap_info, 0, sizeof(bl_wifi_ap_info_t)); memcpy(wifi_env.ap_info.ssid, ssid, ssid_len); memcpy(wifi_env.ap_info.psk, psk, psk_len); wifi_env.ap_info.chan = chan; wifi_env.ap_info_en = 1; return 0; } int bl_wifi_ap_info_get(bl_wifi_ap_info_t* ap_info) { if (wifi_env.ap_info_en != 1) { return -1; } memcpy(ap_info, &wifi_env.ap_info, sizeof(bl_wifi_ap_info_t)); return 0; } #if 0 int bl_wifi_netif_init(void) { struct netif *netif = &wifi_netif; ip4_addr_t ipaddr; ip4_addr_t netmask; ip4_addr_t gw; ipaddr.addr = 0; netmask.addr = 0; gw.addr = 0; netif->hwaddr[0] = 0x18; netif->hwaddr[1] = 0xB9; netif->hwaddr[2] = 0x05; netif->hwaddr[3] = 0x88; netif->hwaddr[4] = 0x88; netif->hwaddr[5] = 0x88; /* - netif_add(struct netif *netif, struct ip_addr *ipaddr, * struct ip_addr *netmask, struct ip_addr *gw, * void *state, err_t (* init)(struct netif *netif), * err_t (* input)(struct pbuf *p, struct netif *netif)) * * Adds your network interface to the netif_list. Allocate a struct * netif and pass a pointer to this structure as the first argument. * Give pointers to cleared ip_addr structures when using DHCP, * or fill them with sane numbers otherwise. The state pointer may be NULL. * * The init function pointer must point to a initialization function for * your ethernet netif interface. The following code illustrates it's use.*/ netif_add(netif, &ipaddr, &netmask, &gw, NULL, &bl606a0_wifi_netif_init, &tcpip_input); netif->name[0] = 's'; netif->name[1] = 't'; netif->flags |= NETIF_FLAG_LINK_UP; netif_set_default(netif); netif_set_up(netif); netifapi_dhcp_start(netif); return 0; } #endif
mkroman/bl602-604
components/network/ble/blestack/src/host_cmdproc/oadc_cmdproc.c
/* * Copyright (c) 2020 Bouffalolab. * * This file is part of * *** Bouffalolab Software Dev Kit *** * (see www.bouffalolab.com). * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of Bouffalo Lab nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "oadc_cmdproc.h" #include "oad.h" struct oad_cmdproc_block_req_t { struct oad_file_info file_info; uint32_t file_offset; uint8_t data_len; }__packed; struct oad_cmdproc_upgrd_end_t { uint8_t status; struct oad_file_info file_info; }__packed; struct oad_cmdproc_req_t { uint8_t cmd_id; union{ struct oad_file_info file_info; struct oad_cmdproc_block_req_t block_req; struct oad_cmdproc_upgrd_end_t upgrd_end; }q; }__packed; void oad_cmdproc_start(void) { uint8_t req[1]; req[0] = OAD_CMDPROC_START; cmdproc_data_send(CMDPROC_TYPE_OAD, req, sizeof(req)); } void oad_cmdproc_image_identity(struct oad_file_info* file_info) { struct oad_cmdproc_req_t req; req.cmd_id = OAD_CMDPROC_IMAGE_IDENTITY; memcpy(&req.q.file_info, file_info, sizeof(*file_info)); cmdproc_data_send(CMDPROC_TYPE_OAD, (uint8_t *)&req, sizeof(req)); } void oad_cmdproc_block_req(struct oad_file_info* file_info, uint32_t file_offset, uint8_t data_len) { struct oad_cmdproc_req_t req; req.cmd_id = OAD_CMDPROC_BLOCK_REQ; memcpy(&req.q.block_req.file_info, file_info, sizeof(*file_info)); req.q.block_req.file_offset = file_offset; req.q.block_req.data_len = data_len; cmdproc_data_send(CMDPROC_TYPE_OAD, (uint8_t *)&req, sizeof(req)); } void oad_cmdproc_upgrd_end(uint8_t status, struct oad_file_info* file_info) { struct oad_cmdproc_req_t req; req.cmd_id = OAD_CMDPROC_UPGRD_END; req.q.upgrd_end.status = status; memcpy(&req.q.upgrd_end.file_info, file_info, sizeof(*file_info)); cmdproc_data_send(CMDPROC_TYPE_OAD, (uint8_t *)&req, sizeof(req)); } void oad_cmdproc_enable(cmdproc_recv_cb cb) { cmdproc_callback_set(CMDPROC_TYPE_OAD, cb); cmdproc_init(); }
mkroman/bl602-604
components/bl602/bl602_std/bl602_std/StdDriver/Src/bl602_sflash_ext.c
<reponame>mkroman/bl602-604 /** ****************************************************************************** * @file bl602_sflash_ext.c * @version V1.0 * @date * @brief This file is the standard driver c file ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT(c) 2020 Bouffalo Lab</center></h2> * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of Bouffalo Lab nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************** */ #include "bl602_l1c.h" #include "bl602_sflash_ext.h" #include "bl602_sf_ctrl.h" #include "l1c_reg.h" /** @addtogroup BL602_Peripheral_Driver * @{ */ /** @addtogroup SFLASH_EXT * @{ */ /** @defgroup SFLASH_EXT_Private_Macros * @{ */ /*@} end of group SFLASH_EXT_Private_Macros */ /** @defgroup SFLASH_EXT_Private_Types * @{ */ /*@} end of group SFLASH_EXT_Private_Types */ /** @defgroup SFLASH_EXT_Private_Variables * @{ */ /*@} end of group SFLASH_EXT_Private_Variables */ /** @defgroup SFLASH_EXT_Global_Variables * @{ */ /*@} end of group SFLASH_EXT_Global_Variables */ /** @defgroup SFLASH_EXT_Private_Fun_Declaration * @{ */ /*@} end of group SFLASH_EXT_Private_Fun_Declaration */ /** @defgroup SFLASH_EXT_Private_Functions * @{ */ /*@} end of group SFLASH_EXT_Private_Functions */ /** @defgroup SFLASH_EXT_Public_Functions * @{ */ /****************************************************************************//** * @brief Read flash register with read command * * @param flashCfg: Serial flash parameter configuration pointer * @param readRegCmd: read command * @param regValue: register value pointer to store data * @param regLen: register value length * * @return SUCCESS or ERROR * *******************************************************************************/ BL_Err_Type ATTR_TCM_SECTION SFlash_Read_Reg_With_Cmd(SPI_Flash_Cfg_Type *flashCfg,uint8_t readRegCmd,uint8_t *regValue,uint8_t regLen) { uint8_t * const flashCtrlBuf=(uint8_t *)SF_CTRL_BUF_BASE; SF_Ctrl_Cmd_Cfg_Type flashCmd; uint32_t cnt=0; if(((uint32_t)&flashCmd)%4==0){ BL602_MemSet4((uint32_t *)&flashCmd,0,sizeof(flashCmd)/4); }else{ BL602_MemSet(&flashCmd,0,sizeof(flashCmd)); } flashCmd.cmdBuf[0]=readRegCmd<<24; flashCmd.rwFlag=SF_CTRL_READ; flashCmd.nbData=regLen; SF_Ctrl_SendCmd(&flashCmd); while(SET==SF_Ctrl_GetBusyState()){ BL602_Delay_US(1); cnt++; if(cnt>1000){ return ERROR; } } BL602_MemCpy(regValue,flashCtrlBuf,regLen); return SUCCESS; } /****************************************************************************//** * @brief Write flash register with write command * * @param flashCfg: Serial flash parameter configuration pointer * @param writeRegCmd: write command * @param regValue: register value pointer storing data * @param regLen: register value length * * @return SUCCESS or ERROR * *******************************************************************************/ BL_Err_Type ATTR_TCM_SECTION SFlash_Write_Reg_With_Cmd(SPI_Flash_Cfg_Type *flashCfg,uint8_t writeRegCmd,uint8_t *regValue,uint8_t regLen) { uint8_t * const flashCtrlBuf=(uint8_t *)SF_CTRL_BUF_BASE; uint32_t cnt=0; SF_Ctrl_Cmd_Cfg_Type flashCmd; if(((uint32_t)&flashCmd)%4==0){ BL602_MemSet4((uint32_t *)&flashCmd,0,sizeof(flashCmd)/4); }else{ BL602_MemSet(&flashCmd,0,sizeof(flashCmd)); } BL602_MemCpy(flashCtrlBuf,regValue,regLen); flashCmd.cmdBuf[0]=writeRegCmd<<24; flashCmd.rwFlag=SF_CTRL_WRITE; flashCmd.nbData=regLen; SF_Ctrl_SendCmd(&flashCmd); /* take 40ms for tw(write status register) as default */ while(SET==SFlash_Busy(flashCfg)){ BL602_Delay_US(100); cnt++; if(cnt>400){ return ERROR; } } return SUCCESS; } /****************************************************************************//** * @brief Enable cache * * @param wayDisable: cache way disable config * * @return SUCCESS or ERROR * *******************************************************************************/ BL_Err_Type ATTR_TCM_SECTION SFlash_Cache_Enable_Set(uint8_t wayDisable) { uint32_t tmpVal; uint32_t cnt=0; /* Set cacheable to 0 */ tmpVal=BL_RD_REG(L1C_BASE,L1C_CONFIG); tmpVal=BL_CLR_REG_BIT(tmpVal,L1C_CACHEABLE); tmpVal=BL_SET_REG_BIT(tmpVal,L1C_BYPASS); tmpVal=BL_CLR_REG_BIT(tmpVal,L1C_WAY_DIS); tmpVal=BL_CLR_REG_BIT(tmpVal,L1C_CNT_EN); BL_WR_REG(L1C_BASE,L1C_CONFIG,tmpVal); tmpVal=BL_RD_REG(L1C_BASE,L1C_CONFIG); /*Set Tag RAM to zero */ tmpVal=BL_CLR_REG_BIT(tmpVal,L1C_INVALID_EN); BL_WR_REG(L1C_BASE,L1C_CONFIG,tmpVal); /* Left space for hardware change status*/ __NOP(); __NOP(); __NOP(); __NOP(); tmpVal=BL_SET_REG_BIT(tmpVal,L1C_INVALID_EN); BL_WR_REG(L1C_BASE,L1C_CONFIG,tmpVal); /* Left space for hardware change status*/ __NOP(); __NOP(); __NOP(); __NOP(); /* Polling for invalid done:100US*/ do{ cnt++; tmpVal=BL_RD_REG(L1C_BASE,L1C_CONFIG); }while(!BL_IS_REG_BIT_SET(tmpVal,L1C_INVALID_DONE)&&cnt<100*32); tmpVal=BL_SET_REG_BIT(tmpVal,L1C_BYPASS); BL_WR_REG(L1C_BASE,L1C_CONFIG,tmpVal); tmpVal=BL_CLR_REG_BIT(tmpVal,L1C_BYPASS); tmpVal=BL_CLR_REG_BIT(tmpVal,L1C_WAY_DIS); tmpVal=BL_SET_REG_BIT(tmpVal,L1C_CNT_EN); BL_WR_REG(L1C_BASE,L1C_CONFIG,tmpVal); tmpVal|=(wayDisable<<L1C_WAY_DIS_POS); /* If way disable is 0x0f, cacheable can't be set */ if(wayDisable!=0x0f){ tmpVal=BL_SET_REG_BIT(tmpVal,L1C_CACHEABLE); }else{ tmpVal=BL_CLR_REG_BIT(tmpVal,L1C_CACHEABLE); } BL_WR_REG(L1C_BASE,L1C_CONFIG,tmpVal); return SUCCESS; } /****************************************************************************//** * @brief Flush cache * * @param None * * @return SUCCESS or ERROR * *******************************************************************************/ BL_Err_Type ATTR_TCM_SECTION SFlash_Cache_Flush(void) { uint32_t tmpVal; /* Disable early respone */ tmpVal=BL_RD_REG(L1C_BASE,L1C_CONFIG); SFlash_Cache_Enable_Set((tmpVal>>L1C_WAY_DIS_POS)&0xf); __NOP(); __NOP(); __NOP(); __NOP(); __NOP(); return SUCCESS; } /****************************************************************************//** * @brief Enable cache read from flash with cache * * @param flashCfg: Serial flash parameter configuration pointer * @param ioMode: flash controller interface mode * @param contRead: Wether enable cont read mode * @param wayDisable: cache way disable config * * @return SUCCESS or ERROR * *******************************************************************************/ BL_Err_Type ATTR_TCM_SECTION SFlash_Cache_Read_Enable(SPI_Flash_Cfg_Type *flashCfg, SF_Ctrl_IO_Type ioMode,uint8_t contRead,uint8_t wayDisable) { BL_Err_Type stat; /* Cache now only support 32 bytes read */ stat=SFlash_Set_IDbus_Cfg(flashCfg,ioMode,contRead,0,32); if(SUCCESS!=stat){ return stat; } return SFlash_Cache_Enable_Set(wayDisable); } /****************************************************************************//** * @brief Sflash restore from power down * * @param pFlashCfg: Flash configuration pointer * @param flashContRead: Whether enable continuous read * * @return SUCCESS or ERROR * *******************************************************************************/ BL_Err_Type ATTR_TCM_SECTION SFlash_Restore_From_Powerdown(SPI_Flash_Cfg_Type *pFlashCfg,uint8_t flashContRead) { BL_Err_Type stat=SUCCESS; uint32_t jdecId=0; uint8_t tmp[8]; uint8_t ioMode=pFlashCfg->ioMode&0xf; /* Wake flash up from power down */ SFlash_Releae_Powerdown(pFlashCfg); BL602_Delay_US(120); SFlash_GetJedecId(pFlashCfg,(uint8_t *)&jdecId); if(SF_CTRL_QO_MODE==ioMode||SF_CTRL_QIO_MODE==ioMode){ SFlash_Qspi_Enable(pFlashCfg); } if(((pFlashCfg->ioMode>>4)&0x01)==1){ /* unwrap */ L1C_Set_Wrap(DISABLE); }else{ /* burst wrap */ L1C_Set_Wrap(ENABLE); /* For command that is setting register instead of send command, we need write enable */ SFlash_Write_Enable(pFlashCfg); SFlash_SetBurstWrap(pFlashCfg); } if(flashContRead){ stat=SFlash_Read(pFlashCfg,ioMode,1,0x00000000,(uint8_t *)tmp, sizeof(tmp)); SF_Ctrl_Set_Owner(SF_CTRL_OWNER_IAHB); }else{ stat=SFlash_Set_IDbus_Cfg(pFlashCfg,ioMode,0,0,32); } return stat; } /*@} end of group SFLASH_EXT_Public_Functions */ /*@} end of group SFLASH_EXT */ /*@} end of group BL602_Peripheral_Driver */
Mleekko/CarND-PID-Control-Project
src/PID.h
#ifndef PID_H #define PID_H #include <vector> enum TwiddlePhase { ADD, REMOVE, ADJUST }; class PID { public: /** * Constructor */ PID(); /** * Destructor. */ virtual ~PID(); /** * Initialize PID. * @param (Kp_, Ki_, Kd_) The initial PID coefficients */ void Init(double Kp_, double Ki_, double Kd_); /** * Update the PID error variables given cross track error. * @param cte The current cross track error */ void UpdateError(double cte); /** * Calculate the total PID error. * @output The total PID error */ double TotalError(); /** * Returns the target value of the control for PID */ double getControlValue(); /** * Adjusts param during twiddle */ void adjustParam(int index, double amount); private: /** * PID Errors */ double errorP; double errorI; double errorD; double prev_cte; // holds cte val from the previous step /** * PID Coefficients */ double Kp; double Ki; double Kd; /** * twiddling parameters */ std::vector<double> dp; int twiddleSteps; double tolerance; double multiplier; int step; int dpIdx; double sumErrors, minError; bool twiddleEnabled; bool initializedError; TwiddlePhase phase; void rotateParam(); void checkTolerance() const; }; #endif // PID_H
Mleekko/CarND-PID-Control-Project
src/SteeringWheel.h
<gh_stars>0 // // Created by Mleekko on 2020-03-16. // #ifndef PID_STEERINGWHEEL_H #define PID_STEERINGWHEEL_H class SteeringWheel { private: double angle = 0.; public: double turnTo(double desiredAngle); void reset(); }; #endif //PID_STEERINGWHEEL_H
BladeTail/OOListBox
OOListBox/Classes/NNTestFile.h
<gh_stars>0 // // NNTestFile.h // OOListBox // // Created by <NAME> on 2018-02-23. // #import <Foundation/Foundation.h> @interface NNTestFile : NSObject @end
BladeTail/OOListBox
OOListBox/Classes/OOListBox.h
// // OOListBox.h // // Created by <NAME> on 5/13/16. // Copyright © 2016 Oldone. All rights reserved. // #import <UIKit/UIKit.h> // Tell the compiler to assume that no method should have a NULL value NS_ASSUME_NONNULL_BEGIN /** Tasteful Checkbox for iOS. */ IB_DESIGNABLE @interface OOListBox : UIView #pragma mark - The list box's background color. /** * The color could be change when you set it. */ @property (nonatomic,assign) IBInspectable UIColor *color; /** * The strings array to holdplace those selection items. */ @property (nonatomic,strong) NSMutableArray *selectStrings; /** * The default selected items,if it's nil,then the list box will set the first element of * the selectStrings. */ @property (nonatomic,copy) IBInspectable NSString *defaultFirstSelection; -(NSInteger)selectedItemIndex; -(NSString *)selectedItemString; @end NS_ASSUME_NONNULL_END
BladeTail/OOListBox
Example/Pods/Target Support Files/OOListBox/OOListBox-umbrella.h
<reponame>BladeTail/OOListBox #ifdef __OBJC__ #import <UIKit/UIKit.h> #else #ifndef FOUNDATION_EXPORT #if defined(__cplusplus) #define FOUNDATION_EXPORT extern "C" #else #define FOUNDATION_EXPORT extern #endif #endif #endif #import "ATest.h" #import "NNTestFile.h" #import "OOListBox.h" #import "OOListBoxBundle.h" #import "OOVC.h" FOUNDATION_EXPORT double OOListBoxVersionNumber; FOUNDATION_EXPORT const unsigned char OOListBoxVersionString[];
BladeTail/OOListBox
OOListBox/Classes/OOVC.h
// // OOVC.h // OOListBox // // Created by <NAME> on 2018-02-09. // #import <UIKit/UIKit.h> @interface OOVC : UIViewController +(OOVC *)loadFromNib; @end
BladeTail/OOListBox
OOListBox/Classes/OOListBoxBundle.h
// // OOListBoxBundle.h // OOListBox // // Created by <NAME> on 2018-02-09. // #import <Foundation/Foundation.h> @interface OOListBoxBundle : NSObject +(NSBundle *)frameworkBundle; @end
BladeTail/OOListBox
OOListBox/Classes/ATest.h
<filename>OOListBox/Classes/ATest.h // // ATest.h // OOListBox // // Created by <NAME> on 04/02/2018. // #import <Foundation/Foundation.h> @interface ATest : NSObject @property (nonatomic,copy) NSString *test; @end
openwengo/qmail-ldap
slurpclose.h
#ifndef SLURPCLOSE_H #define SLURPCLOSE_H #include "stralloc.h" extern int slurpclose(int, stralloc *, unsigned int); #endif
openwengo/qmail-ldap
auto_userl.h
<gh_stars>10-100 #ifndef AUTO_USERL_H #define AUTO_USERL_H extern char auto_userl[]; #endif
openwengo/qmail-ldap
idedit.c
<reponame>openwengo/qmail-ldap #include <sys/types.h> #include <pwd.h> #include <grp.h> #include <unistd.h> #include "readwrite.h" #include "exit.h" #include "scan.h" #include "fmt.h" #include "strerr.h" #include "open.h" #include "seek.h" #include "fork.h" #include "wait.h" #define FATAL "idedit: fatal: " #define WARNING "idedit: warning: " int fd; void byte(pos,value) char *pos; unsigned int value; { unsigned long u; unsigned char ch; if (pos[scan_ulong(pos,&u)]) return; if (seek_set(fd,(seek_pos) u) == -1) strerr_die2sys(111,FATAL,"unable to seek: "); ch = value; if (write(fd,&ch,1) != 1) strerr_die2sys(111,FATAL,"unable to write: "); } char *args[10]; void run() { int pid; int wstat; pid = fork(); if (pid == -1) strerr_die2sys(111,FATAL,"unable to fork: "); if (pid == 0) { execv(*args,args); strerr_die4sys(111,WARNING,"unable to run ",*args,": "); } if (wait_pid(&wstat,pid) != pid) strerr_die2sys(111,FATAL,"waitpid surprise"); } void u(account,group,home,pos0,pos1,pos2,pos3) char *account; char *group; char *home; char *pos0; char *pos1; char *pos2; char *pos3; { struct passwd *pw; unsigned int value; pw = getpwnam(account); if (!pw && group) { args[0] = (char *)"add-account"; args[1] = account; args[2] = group; args[3] = home; args[4] = 0; run(); pw = getpwnam(account); } if (!pw) strerr_die3x(111,FATAL,"unable to find uid for ",account); value = pw->pw_uid; byte(pos0,value); value >>= 8; byte(pos1,value); value >>= 8; byte(pos2,value); value >>= 8; byte(pos3,value); value >>= 8; if (value) strerr_die3x(111,FATAL,"excessively large uid for ",account); } void g(group,pos0,pos1,pos2,pos3) char *group; char *pos0; char *pos1; char *pos2; char *pos3; { struct group *gr; unsigned int value; gr = getgrnam(group); if (!gr) { args[0] = (char *)"add-group"; args[1] = group; args[2] = 0; run(); gr = getgrnam(group); } if (!gr) strerr_die3x(111,FATAL,"unable to find gid for ",group); value = gr->gr_gid; byte(pos0,value); value >>= 8; byte(pos1,value); value >>= 8; byte(pos2,value); value >>= 8; byte(pos3,value); value >>= 8; if (value) strerr_die3x(111,FATAL,"excessively large gid for ",group); } int main(argc,argv) int argc; char **argv; { if (argc < 42) _exit(100); fd = open_write(argv[1]); if (fd == -1) strerr_die4sys(111,FATAL,"unable to open ",argv[1],": "); g("qmail",argv[34],argv[35],argv[36],argv[37]); g("nofiles",argv[38],argv[39],argv[40],argv[41]); u("root",(char *) 0,"/",argv[14],argv[15],argv[16],argv[17]); u("qmaild","nofiles","/var/qmail",argv[6],argv[7],argv[8],argv[9]); u("qmaill","nofiles","/var/qmail",argv[10],argv[11],argv[12],argv[13]); u("qmailp","nofiles","/var/qmail",argv[18],argv[19],argv[20],argv[21]); u("alias","nofiles","/var/qmail/alias",argv[2],argv[3],argv[4],argv[5]); u("qmailq","qmail","/var/qmail",argv[22],argv[23],argv[24],argv[25]); u("qmailr","qmail","/var/qmail",argv[26],argv[27],argv[28],argv[29]); u("qmails","qmail","/var/qmail",argv[30],argv[31],argv[32],argv[33]); return 0; }
openwengo/qmail-ldap
sig.h
#ifndef SIG_H #define SIG_H extern void sig_catch(int, void (*)()); extern void sig_block(int); extern void sig_unblock(int); extern void sig_blocknone(void); extern void sig_pause(void); extern void sig_dfl(); extern void sig_miscignore(void); extern void sig_bugcatch(void (*)()); extern void sig_pipeignore(void); extern void sig_pipedefault(void); /* XXX not available in qmail-1.03 extern void sig_contblock(); extern void sig_contunblock(); extern void sig_contcatch(); extern void sig_contdefault(); */ extern void sig_termblock(void); extern void sig_termunblock(void); extern void sig_termcatch(void (*)()); extern void sig_termdefault(void); extern void sig_alarmblock(void); extern void sig_alarmunblock(void); extern void sig_alarmcatch(void (*)()); extern void sig_alarmdefault(void); extern void sig_childblock(void); extern void sig_childunblock(void); extern void sig_childcatch(void (*)()); extern void sig_childdefault(void); extern void sig_hangupblock(void); extern void sig_hangupunblock(void); extern void sig_hangupcatch(void (*)()); extern void sig_hangupdefault(void); #endif
openwengo/qmail-ldap
auto_patrn.h
#ifndef AUTO_PATRN_H #define AUTO_PATRN_H extern unsigned int auto_patrn; #endif
openwengo/qmail-ldap
qbiff.c
#include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <utmp.h> #ifndef UTMP_FILE #ifdef _PATH_UTMP #define UTMP_FILE _PATH_UTMP #else #define UTMP_FILE "/etc/utmp" #endif #endif #include "readwrite.h" #include "stralloc.h" #include "substdio.h" #include "subfd.h" #include "open.h" #include "byte.h" #include "str.h" #include "headerbody.h" #include "hfield.h" #include "env.h" #include "exit.h" substdio ssutmp; char bufutmp[sizeof(struct utmp) * 16]; int fdutmp; substdio sstty; char buftty[1024]; int fdtty; struct utmp ut; char line[sizeof(ut.ut_line) + 1]; stralloc woof = {0}; stralloc tofrom = {0}; stralloc text = {0}; void doit(s,n) char *s; unsigned int n; { if (!stralloc_catb(&text,s,n)) _exit(0); if (text.len > 78) text.len = 78; } void dobody(h) stralloc *h; { doit(h->s,h->len); } void doheader(h) stralloc *h; { unsigned int i; if (hfield_known(h->s,h->len) == H_SUBJECT) { i = hfield_skipname(h->s,h->len); doit(h->s + i,h->len - i); } } void finishheader() { ; } int main() { char *user; char *sender; char *userext; struct stat st; unsigned int i; if (chdir("/dev") == -1) _exit(0); if (!(user = env_get("USER"))) _exit(0); if (!(sender = env_get("SENDER"))) _exit(0); if (!(userext = env_get("LOCAL"))) _exit(0); if (str_len(user) > sizeof(ut.ut_name)) _exit(0); if (!stralloc_copys(&tofrom,"*** TO <")) _exit(0); if (!stralloc_cats(&tofrom,userext)) _exit(0); if (!stralloc_cats(&tofrom,"> FROM <")) _exit(0); if (!stralloc_cats(&tofrom,sender)) _exit(0); if (!stralloc_cats(&tofrom,">")) _exit(0); for (i = 0;i < tofrom.len;++i) if ((tofrom.s[i] < 32) || (tofrom.s[i] > 126)) tofrom.s[i] = '_'; if (!stralloc_copys(&text," ")) _exit(0); if (headerbody(subfdin,doheader,finishheader,dobody) == -1) _exit(0); for (i = 0;i < text.len;++i) if ((text.s[i] < 32) || (text.s[i] > 126)) text.s[i] = '/'; if (!stralloc_copys(&woof,"\015\n\007")) _exit(0); if (!stralloc_cat(&woof,&tofrom)) _exit(0); if (!stralloc_cats(&woof,"\015\n")) _exit(0); if (!stralloc_cat(&woof,&text)) _exit(0); if (!stralloc_cats(&woof,"\015\n")) _exit(0); fdutmp = open_read(UTMP_FILE); if (fdutmp == -1) _exit(0); substdio_fdbuf(&ssutmp,subread,fdutmp,bufutmp,sizeof(bufutmp)); while (substdio_get(&ssutmp,(char *)&ut,sizeof(ut)) == sizeof(ut)) if (!str_diffn(ut.ut_name,user,sizeof(ut.ut_name))) { byte_copy(line,sizeof(ut.ut_line),ut.ut_line); line[sizeof(ut.ut_line)] = 0; if (line[0] == '/') continue; if (!line[0]) continue; if (line[str_chr(line,'.')]) continue; fdtty = open_append(line); if (fdtty == -1) continue; if (fstat(fdtty,&st) == -1) { close(fdtty); continue; } if (!(st.st_mode & 0100)) { close(fdtty); continue; } if (st.st_uid != getuid()) { close(fdtty); continue; } substdio_fdbuf(&sstty,subwrite,fdtty,buftty,sizeof(buftty)); substdio_putflush(&sstty,woof.s,woof.len); close(fdtty); } return 0; }
openwengo/qmail-ldap
fmtqfn.h
#ifndef FMTQFN_H #define FMTQFN_H extern unsigned int fmtqfn(char *, const char *, unsigned long, int); #define FMTQFN 40 /* maximum space needed, if len(dirslash) <= 10 */ #endif
openwengo/qmail-ldap
subfd.h
#ifndef SUBFD_H #define SUBFD_H #include "substdio.h" extern substdio *subfdin; extern substdio *subfdinsmall; extern substdio *subfdout; extern substdio *subfdoutsmall; extern substdio *subfderr; extern int subfd_read(int, void *, int); extern int subfd_readsmall(int, void *, int); #endif
openwengo/qmail-ldap
getln.c
<gh_stars>10-100 #include "substdio.h" #include "byte.h" #include "stralloc.h" #include "getln.h" int getln(ss,sa,match,sep) register substdio *ss; register stralloc *sa; int *match; int sep; { char *cont; unsigned int clen; if (getln2(ss,sa,&cont,&clen,sep) == -1) return -1; if (!clen) { *match = 0; return 0; } if (!stralloc_catb(sa,cont,clen)) return -1; *match = 1; return 0; }
openwengo/qmail-ldap
maildir.h
#ifndef MAILDIR_H #define MAILDIR_H #include "prioq.h" #include "stralloc.h" #include "strerr.h" extern struct strerr maildir_chdir_err; extern struct strerr maildir_scan_err; extern int maildir_chdir(void); extern void maildir_clean(stralloc *); extern int maildir_scan(prioq *, stralloc *, int, int); #endif
openwengo/qmail-ldap
env.h
#ifndef ENV_H #define ENV_H extern int env_isinit; extern int env_init(void); extern int env_put(const char *); extern int env_put2(const char *, const char *); extern int env_unset(const char *); extern /*@null@*/char *env_get(const char *); extern char *env_pick(void); extern void env_clear(void); extern const char *env_findeq(const char *); extern char **environ; #endif
openwengo/qmail-ldap
ipmeprint.c
#include "subfd.h" #include "substdio.h" #include "ip.h" #include "ipme.h" #include "exit.h" char temp[IPFMT]; int main(int argc, char **argv) { unsigned int j; switch(ipme_init()) { case 0: substdio_putsflush(subfderr,"out of memory\n"); _exit(111); case -1: substdio_putsflush(subfderr,"hard error\n"); _exit(100); } for (j = 0;j < ipme.len;++j) { substdio_put(subfdout,temp,ip_fmt(temp,&ipme.ix[j].ip)); substdio_puts(subfdout,"\n"); } substdio_flush(subfdout); return 0; }
openwengo/qmail-ldap
ipme.c
#include <sys/types.h> #include <sys/param.h> #include <sys/time.h> #include <sys/ioctl.h> #include <sys/socket.h> #include <net/if.h> #include <netinet/in.h> #ifndef SIOCGIFCONF /* whatever works */ #include <sys/sockio.h> #endif #include <unistd.h> #include "hassalen.h" #include "byte.h" #include "ip.h" #include "ipalloc.h" #include "stralloc.h" #include "ipme.h" static int ipmeok = 0; ipalloc ipme = {0}; int ipme_is(ip) struct ip_address *ip; { unsigned int i; if (ipme_init() != 1) return -1; for (i = 0;i < ipme.len;++i) if (byte_equal(&ipme.ix[i].ip,4,ip)) return 1; return 0; } static stralloc buf = {0}; int ipme_init() { struct ifconf ifc; char *x; struct ifreq *ifr; struct sockaddr_in *s_in; unsigned int len; int s; struct ip_mx ix; if (ipmeok) return 1; if (!ipalloc_readyplus(&ipme,0)) return 0; ipme.len = 0; ix.pref = 0; /* 0.0.0.0 is a special address which always refers to * "this host, this network", according to RFC 1122, Sec. 3.2.1.3a. */ byte_copy(&ix.ip,4,"\0\0\0\0"); if (!ipalloc_append(&ipme,&ix)) { return 0; } if ((s = socket(AF_INET,SOCK_STREAM,0)) == -1) return -1; len = 256; for (;;) { if (!stralloc_ready(&buf,len)) { close(s); return 0; } buf.len = 0; ifc.ifc_buf = buf.s; ifc.ifc_len = len; if (ioctl(s,SIOCGIFCONF,&ifc) >= 0) /* > is for System V */ if (ifc.ifc_len + sizeof(*ifr) + 64 < len) { /* what a stupid interface */ buf.len = ifc.ifc_len; break; } if (len > 200000) { close(s); return -1; } len += 100 + (len >> 2); } x = buf.s; while (x < buf.s + buf.len) { ifr = (struct ifreq *) x; #ifdef HASSALEN len = sizeof(ifr->ifr_name) + ifr->ifr_addr.sa_len; if (len < sizeof(*ifr)) len = sizeof(*ifr); if (ifr->ifr_addr.sa_family == AF_INET) { s_in = (struct sockaddr_in *) &ifr->ifr_addr; byte_copy(&ix.ip,4,&s_in->sin_addr); if (ioctl(s,SIOCGIFFLAGS,x) == 0) if (ifr->ifr_flags & IFF_UP) if (!ipalloc_append(&ipme,&ix)) { close(s); return 0; } } #else len = sizeof(*ifr); if (ioctl(s,SIOCGIFFLAGS,x) == 0) if (ifr->ifr_flags & IFF_UP) if (ioctl(s,SIOCGIFADDR,x) == 0) if (ifr->ifr_addr.sa_family == AF_INET) { s_in = (struct sockaddr_in *) &ifr->ifr_addr; byte_copy(&ix.ip,4,&s_in->sin_addr); if (!ipalloc_append(&ipme,&ix)) { close(s); return 0; } } #endif x += len; } close(s); ipmeok = 1; return 1; }
openwengo/qmail-ldap
dns.h
#ifndef DNS_H #define DNS_H #include "ip.h" #include "ipalloc.h" #include "stralloc.h" #define DNS_SOFT -1 #define DNS_HARD -2 #define DNS_MEM -3 void dns_init(int); int dns_cname(stralloc *); int dns_mxip(ipalloc *, stralloc *, unsigned long); int dns_ip(ipalloc *, stralloc *); int dns_ptr(stralloc *, struct ip_address *); #endif
openwengo/qmail-ldap
tryflock.c
#include <sys/types.h> #include <sys/file.h> #include <fcntl.h> void main() { flock(0,LOCK_EX | LOCK_UN | LOCK_NB); }
openwengo/qmail-ldap
timeoutwrite.h
<gh_stars>10-100 #ifndef TIMEOUTWRITE_H #define TIMEOUTWRITE_H extern int timeoutwrite(int, int, const void *, int); #endif
openwengo/qmail-ldap
substdi.c
#include "substdio.h" #include "byte.h" #include "error.h" static int oneread(op,fd,buf,len) register int (*op)(); register int fd; register char *buf; register unsigned int len; { register int r; for (;;) { r = op(fd,buf,len); if (r == -1) if (errno == error_intr) continue; return r; } } static int getthis(s,buf,len) register substdio *s; register char *buf; register unsigned int len; { register unsigned int r; register int q; r = s->p; q = r - len; if (q > 0) { r = len; s->p = q; } else s->p = 0; byte_copy(buf,r,s->x + s->n); s->n += r; return r; } int substdio_feed(s) register substdio *s; { register int r; register int q; if (s->p) return s->p; q = s->n; r = oneread(s->op,s->fd,s->x,q); if (r <= 0) return r; s->p = r; q -= r; s->n = q; if (q > 0) /* damn, gotta shift */ byte_copyr(s->x + q,r,s->x); return r; } int substdio_bget(s,buf,len) register substdio *s; register char *buf; register unsigned int len; { unsigned int u; int r; if (s->p > 0) return getthis(s,buf,len); u = s->n; if (u <= len) return oneread(s->op,s->fd,buf,u); r = substdio_feed(s); if (r <= 0) return r; return getthis(s,buf,len); } int substdio_get(s,buf,len) register substdio *s; register char *buf; register unsigned int len; { register int r; if (s->p > 0) return getthis(s,buf,len); if (s->n <= len) return oneread(s->op,s->fd,buf,len); r = substdio_feed(s); if (r <= 0) return r; return getthis(s,buf,len); } char *substdio_peek(s) register substdio *s; { return s->x + s->n; } void substdio_seek(s,len) register substdio *s; register unsigned int len; { s->n += len; s->p -= len; }
openwengo/qmail-ldap
tcpto_clean.c
<reponame>openwengo/qmail-ldap #include <unistd.h> #include "tcpto.h" #include "open.h" #include "substdio.h" #include "readwrite.h" char tcpto_cleanbuf[1024]; void tcpto_clean(void) /* running from queue/mess */ { int fd; unsigned int i; substdio ss; fd = open_write("../lock/tcpto"); if (fd == -1) return; substdio_fdbuf(&ss,subwrite,fd,tcpto_cleanbuf,sizeof(tcpto_cleanbuf)); for (i = 0;i < sizeof(tcpto_cleanbuf);++i) substdio_put(&ss,"",1); substdio_flush(&ss); /* if it fails, bummer */ close(fd); }
openwengo/qmail-ldap
headerbody.c
<reponame>openwengo/qmail-ldap #include "stralloc.h" #include "substdio.h" #include "getln.h" #include "hfield.h" #include "headerbody.h" static int getsa(ss,sa,match) substdio *ss; stralloc *sa; int *match; { if (!*match) return 0; if (getln(ss,sa,match,'\n') == -1) return -1; if (*match) return 1; if (!sa->len) return 0; if (!stralloc_append(sa,"\n")) return -1; return 1; } static stralloc line = {0}; static stralloc nextline = {0}; int headerbody(ss,dohf,hdone,dobl) substdio *ss; void (*dohf)(); void (*hdone)(); void (*dobl)(); { int match; int flaglineok; match = 1; flaglineok = 0; for (;;) { switch(getsa(ss,&nextline,&match)) { case -1: return -1; case 0: if (flaglineok) dohf(&line); hdone(); /* no message body; could insert blank line here */ return 0; } if (flaglineok) { if ((nextline.s[0] == ' ') || (nextline.s[0] == '\t')) { if (!stralloc_cat(&line,&nextline)) return -1; continue; } dohf(&line); } if (nextline.len == 1) { hdone(); dobl(&nextline); break; } if (stralloc_starts(&nextline,"From ")) { if (!stralloc_copys(&line,"MBOX-Line: ")) return -1; if (!stralloc_cat(&line,&nextline)) return -1; } else if (hfield_valid(nextline.s,nextline.len)) { if (!stralloc_copy(&line,&nextline)) return -1; } else { hdone(); if (!stralloc_copys(&line,"\n")) return -1; dobl(&line); dobl(&nextline); break; } flaglineok = 1; } for (;;) switch(getsa(ss,&nextline,&match)) { case -1: return -1; case 0: return 0; case 1: dobl(&nextline); } }
openwengo/qmail-ldap
auto-int.c
#include "substdio.h" #include "readwrite.h" #include "exit.h" #include "scan.h" #include "fmt.h" char buf1[256]; substdio ss1 = SUBSTDIO_FDBUF(subwrite,1,buf1,sizeof(buf1)); void putstr(s) char *s; { if (substdio_puts(&ss1,s) == -1) _exit(111); } int main(argc,argv) int argc; char **argv; { char *name; char *value; unsigned long num; char strnum[FMT_ULONG]; name = argv[1]; if (!name) _exit(100); value = argv[2]; if (!value) _exit(100); scan_ulong(value,&num); strnum[fmt_ulong(strnum,num)] = 0; putstr("unsigned int "); putstr(name); putstr(" = "); putstr(strnum); putstr(";\n"); if (substdio_flush(&ss1) == -1) _exit(111); return 0; }
openwengo/qmail-ldap
now.h
<reponame>openwengo/qmail-ldap<filename>now.h<gh_stars>10-100 #ifndef NOW_H #define NOW_H #include "datetime.h" extern datetime_sec now(void); #endif
openwengo/qmail-ldap
fifo.h
<reponame>openwengo/qmail-ldap<gh_stars>10-100 #ifndef FIFO_H #define FIFO_H extern int fifo_make(const char *, int); #endif
openwengo/qmail-ldap
stralloc.h
<gh_stars>10-100 #ifndef STRALLOC_H #define STRALLOC_H #include "gen_alloc.h" GEN_ALLOC_typedef(stralloc,char,s,len,a) extern int stralloc_ready(stralloc *, unsigned int); extern int stralloc_readyplus(stralloc *, unsigned int); extern int stralloc_copy(stralloc *, stralloc *); extern int stralloc_cat(stralloc *, stralloc *); extern int stralloc_copys(stralloc *, const char *); extern int stralloc_cats(stralloc *, const char *); extern int stralloc_copyb(stralloc *, const char *, unsigned int); extern int stralloc_catb(stralloc *, const char *, unsigned int); extern int stralloc_append(stralloc *, const char *); /* beware: this takes a pointer to 1 char */ extern int stralloc_starts(stralloc *, const char *); #define stralloc_0(sa) stralloc_append(sa,"") #endif
openwengo/qmail-ldap
prot.h
#ifndef PROT_H #define PROT_H extern int prot_gid(unsigned int); extern int prot_uid(unsigned int); #endif
openwengo/qmail-ldap
endian.c
<filename>endian.c /* endian.c * ---------------------------------------------------------------------------- * "THE BEER-WARE LICENSE" (Revision 42): * <<EMAIL>> wrote this file. As long as you retain this notice you * can do whatever you want with this stuff. If we meet some day, and you think * this stuff is worth it, you can buy me a beer in return. <NAME> * ---------------------------------------------------------------------------- * * This is a lowest-common-denominator (endian) program which should compile * under the default cc on any system, no matter how primitite ... * (even the SunOS one ;-) ) */ #include <stdio.h> union endian_t { unsigned char c[8]; long l; } endian; int main() { endian.c[0]=0x80; endian.c[1]=0; endian.c[2]=0; endian.c[3]=0; endian.c[4]=0; endian.c[5]=0; endian.c[6]=0; endian.c[7]=0; if( endian.l < 0 ) printf( "-D__BIG_ENDIAN__" ); else printf( "-D__LITTLE_ENDIAN__" ); return(0); }
openwengo/qmail-ldap
substdo.c
<reponame>openwengo/qmail-ldap #include "substdio.h" #include "str.h" #include "byte.h" #include "error.h" static int allwrite(op,fd,buf,len) register int (*op)(); register int fd; register const char *buf; register unsigned int len; { register int w; while (len) { w = op(fd,buf,len); if (w == -1) { if (errno == error_intr) continue; return -1; /* note that some data may have been written */ } if (w == 0) ; /* luser's fault */ buf += w; len -= w; } return 0; } int substdio_flush(s) register substdio *s; { register unsigned int p; p = s->p; if (!p) return 0; s->p = 0; return allwrite(s->op,s->fd,s->x,p); } int substdio_bput(s,buf,len) register substdio *s; register const char *buf; register unsigned int len; { register unsigned int n; while (len > (n = s->n - s->p)) { byte_copy(s->x + s->p,n,buf); s->p += n; buf += n; len -= n; if (substdio_flush(s) == -1) return -1; } /* now len <= s->n - s->p */ byte_copy(s->x + s->p,len,buf); s->p += len; return 0; } int substdio_put(s,buf,len) register substdio *s; register const char *buf; register unsigned int len; { register unsigned int n; n = s->n; if (len > n - s->p) { if (substdio_flush(s) == -1) return -1; /* now s->p == 0 */ if (n < SUBSTDIO_OUTSIZE) n = SUBSTDIO_OUTSIZE; while (len > s->n) { if (n > len) n = len; if (allwrite(s->op,s->fd,buf,n) == -1) return -1; buf += n; len -= n; } } /* now len <= s->n - s->p */ byte_copy(s->x + s->p,len,buf); s->p += len; return 0; } int substdio_putflush(s,buf,len) register substdio *s; register const char *buf; register unsigned int len; { if (substdio_flush(s) == -1) return -1; return allwrite(s->op,s->fd,buf,len); } int substdio_bputs(s,buf) register substdio *s; register const char *buf; { return substdio_bput(s,buf,str_len(buf)); } int substdio_puts(s,buf) register substdio *s; register const char *buf; { return substdio_put(s,buf,str_len(buf)); } int substdio_putsflush(s,buf) register substdio *s; register const char *buf; { return substdio_putflush(s,buf,str_len(buf)); }
openwengo/qmail-ldap
ip.c
#include "fmt.h" #include "scan.h" #include "ip.h" unsigned int ip_fmt(s,ip) char *s; struct ip_address *ip; { unsigned int len; unsigned int i; len = 0; i = fmt_ulong(s,(unsigned long) ip->d[0]); len += i; if (s) s += i; i = fmt_str(s,"."); len += i; if (s) s += i; i = fmt_ulong(s,(unsigned long) ip->d[1]); len += i; if (s) s += i; i = fmt_str(s,"."); len += i; if (s) s += i; i = fmt_ulong(s,(unsigned long) ip->d[2]); len += i; if (s) s += i; i = fmt_str(s,"."); len += i; if (s) s += i; i = fmt_ulong(s,(unsigned long) ip->d[3]); len += i; if (s) s += i; return len; } unsigned int ip_scan(s,ip) const char *s; struct ip_address *ip; { unsigned int i; unsigned int len; unsigned long u; /* * Don't play games. everything over 255 is invalid and we need a full * IP address. No magic expands like 127.1 or similar bullshit. */ len = 0; i = scan_ulong(s,&u); if (!i || u > 255) return 0; ip->d[0] = u; s += i; len += i; if (*s != '.') return 0; ++s; ++len; i = scan_ulong(s,&u); if (!i || u > 255) return 0; ip->d[1] = u; s += i; len += i; if (*s != '.') return 0; ++s; ++len; i = scan_ulong(s,&u); if (!i || u > 255) return 0; ip->d[2] = u; s += i; len += i; if (*s != '.') return 0; ++s; ++len; i = scan_ulong(s,&u); if (!i || u > 255) return 0; ip->d[3] = u; s += i; len += i; return len; } unsigned int ip_scanbracket(s,ip) const char *s; struct ip_address *ip; { unsigned int len; if (*s != '[') return 0; len = ip_scan(s + 1,ip); if (!len) return 0; if (s[len + 1] != ']') return 0; return len + 2; }
openwengo/qmail-ldap
qmail-start.c
<filename>qmail-start.c #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include "fd.h" #include "prot.h" #include "exit.h" #include "fork.h" #include "auto_uids.h" const char *(qsargs[]) = { "qmail-send", 0 }; const char *(qcargs[]) = { "qmail-clean", 0 }; const char *(qlargs[]) = { "qmail-lspawn", "./Mailbox", 0 }; const char *(qrargs[]) = { "qmail-rspawn", 0 }; #ifdef EXTERNAL_TODO const char *(qtargs[]) = { "qmail-todo", 0}; #endif void die() { _exit(111); } int pi0[2]; int pi1[2]; int pi2[2]; int pi3[2]; int pi4[2]; int pi5[2]; int pi6[2]; #ifdef EXTERNAL_TODO int pi7[2]; int pi8[2]; int pi9[2]; int pi10[2]; #endif void close23456() { close(2); close(3); close(4); close(5); close(6); #ifdef EXTERNAL_TODO close(7); close(8); #endif } void closepipes() { close(pi1[0]); close(pi1[1]); close(pi2[0]); close(pi2[1]); close(pi3[0]); close(pi3[1]); close(pi4[0]); close(pi4[1]); close(pi5[0]); close(pi5[1]); close(pi6[0]); close(pi6[1]); #ifdef EXTERNAL_TODO close(pi7[0]); close(pi7[1]); close(pi8[0]); close(pi8[1]); close(pi9[0]); close(pi9[1]); close(pi10[0]); close(pi10[1]); #endif } int main(argc,argv) int argc; char **argv; { if (chdir("/") == -1) die(); umask(077); if (prot_gid(auto_gidq) == -1) die(); if (fd_copy(2,0) == -1) die(); if (fd_copy(3,0) == -1) die(); if (fd_copy(4,0) == -1) die(); if (fd_copy(5,0) == -1) die(); if (fd_copy(6,0) == -1) die(); #ifdef EXTERNAL_TODO if (fd_copy(7,0) == -1) die(); if (fd_copy(8,0) == -1) die(); #endif if (argv[1]) { qlargs[1] = argv[1]; ++argv; } if (argv[1]) { if (pipe(pi0) == -1) die(); switch(fork()) { case -1: die(); case 0: if (prot_gid(auto_gidn) == -1) die(); if (prot_uid(auto_uidl) == -1) die(); close(pi0[1]); if (fd_move(0,pi0[0]) == -1) die(); close23456(); execvp(argv[1],argv + 1); die(); } close(pi0[0]); if (fd_move(1,pi0[1]) == -1) die(); } if (pipe(pi1) == -1) die(); if (pipe(pi2) == -1) die(); if (pipe(pi3) == -1) die(); if (pipe(pi4) == -1) die(); if (pipe(pi5) == -1) die(); if (pipe(pi6) == -1) die(); #ifdef EXTERNAL_TODO if (pipe(pi7) == -1) die(); if (pipe(pi8) == -1) die(); if (pipe(pi9) == -1) die(); if (pipe(pi10) == -1) die(); #endif switch(fork()) { case -1: die(); case 0: if (fd_copy(0,pi1[0]) == -1) die(); if (fd_copy(1,pi2[1]) == -1) die(); close23456(); closepipes(); execvp(*qlargs,(char **)qlargs); die(); } switch(fork()) { case -1: die(); case 0: if (prot_uid(auto_uidr) == -1) die(); if (fd_copy(0,pi3[0]) == -1) die(); if (fd_copy(1,pi4[1]) == -1) die(); close23456(); closepipes(); execvp(*qrargs,(char **)qrargs); die(); } switch(fork()) { case -1: die(); case 0: if (prot_uid(auto_uidq) == -1) die(); if (fd_copy(0,pi5[0]) == -1) die(); if (fd_copy(1,pi6[1]) == -1) die(); close23456(); closepipes(); execvp(*qcargs,(char **)qcargs); die(); } #ifdef EXTERNAL_TODO switch(fork()) { case -1: die(); case 0: if (prot_uid(auto_uids) == -1) die(); if (fd_copy(0,pi7[0]) == -1) die(); if (fd_copy(1,pi8[1]) == -1) die(); close23456(); if (fd_copy(2,pi9[1]) == -1) die(); if (fd_copy(3,pi10[0]) == -1) die(); closepipes(); execvp(*qtargs,(char **)qtargs); die(); } switch(fork()) { case -1: die(); case 0: if (prot_uid(auto_uidq) == -1) die(); if (fd_copy(0,pi9[0]) == -1) die(); if (fd_copy(1,pi10[1]) == -1) die(); close23456(); closepipes(); execvp(*qcargs,(char **)qcargs); die(); } #endif if (prot_uid(auto_uids) == -1) die(); if (fd_copy(0,1) == -1) die(); if (fd_copy(1,pi1[1]) == -1) die(); if (fd_copy(2,pi2[0]) == -1) die(); if (fd_copy(3,pi3[1]) == -1) die(); if (fd_copy(4,pi4[0]) == -1) die(); if (fd_copy(5,pi5[1]) == -1) die(); if (fd_copy(6,pi6[0]) == -1) die(); #ifdef EXTERNAL_TODO if (fd_copy(7,pi7[1]) == -1) die(); if (fd_copy(8,pi8[0]) == -1) die(); #endif closepipes(); execvp(*qsargs,(char **)qsargs); return 111; }
openwengo/qmail-ldap
qmail-smtpd.c
#include <unistd.h> #include "sig.h" #include "readwrite.h" #include "stralloc.h" #include "substdio.h" #include "subfd.h" #include "alloc.h" #include "auto_qmail.h" #include "auto_break.h" #include "control.h" #include "received.h" #include "constmap.h" #include "error.h" #include "ipme.h" #include "ip.h" #include "qmail.h" #include "str.h" #include "fmt.h" #include "scan.h" #include "byte.h" #include "case.h" #include "env.h" #include "now.h" #include "exit.h" #include "rcpthosts.h" #include "rbl.h" #include "timeoutread.h" #include "timeoutwrite.h" #include "commands.h" #include "dns.h" #include "smtpcall.h" #include "qmail-ldap.h" #include "limit.h" #ifdef SMTPEXECCHECK #include "execcheck.h" #endif #ifdef TLS_SMTPD #include <openssl/ssl.h> SSL *ssl = NULL; #endif #ifdef DATA_COMPRESS /* zlib needs to be after openssl includes or build will fail */ #include <zlib.h> #endif #define MAXHOPS 100 #define MAXLINELEN 10000 unsigned long databytes = 0; int timeout = 1200; #ifdef TLS_SMTPD int flagtimedout = 0; void sigalrm() { flagtimedout = 1; } int ssl_timeoutread(int tout, int fd, void *buf, int n) { int r; int saveerrno; if (flagtimedout) { errno = error_timeout; return -1; } alarm(tout); r = SSL_read(ssl,buf,n); saveerrno = errno; alarm(0); if (flagtimedout) { errno = error_timeout; return -1; } errno = saveerrno; return r; } int ssl_timeoutwrite(int tout, int fd, const void *buf, int n) { int r; int saveerrno; if (flagtimedout) { errno = error_timeout; return -1; } alarm(tout); r = SSL_write(ssl,buf,n); saveerrno = errno; alarm(0); if (flagtimedout) { errno = error_timeout; return -1; } errno = saveerrno; return r; } #endif void die_write(void); int safewrite(int fd, void *buf, int len) { int r; #ifdef TLS_SMTPD if (ssl) r = ssl_timeoutwrite(timeout,fd,buf,len); else #endif r = timeoutwrite(timeout,fd,buf,len); if (r <= 0) die_write(); return r; } char ssoutbuf[512]; substdio ssout = SUBSTDIO_FDBUF(safewrite,1,ssoutbuf,sizeof ssoutbuf); void flush(void) { substdio_flush(&ssout); } void out(const char *s) { substdio_puts(&ssout,s); } /* level 0 = no logging 1 = fatal errors 2 = connection setup and warnings 3 = verbose */ int loglevel = 0; void logpid(int level) { char pidstring[FMT_ULONG]; if (level > loglevel) return; substdio_puts(subfderr,"qmail-smtpd "); pidstring[fmt_uint(pidstring, getpid())] = 0; substdio_puts(subfderr,pidstring); substdio_puts(subfderr,": "); } void logline(int level, const char *string) { if (level > loglevel) return; logpid(level); substdio_puts(subfderr,string); substdio_puts(subfderr,"\n"); substdio_flush(subfderr); } void logline2(int level, const char *s1, const char *s2) { if (level > loglevel) return; logpid(level); substdio_puts(subfderr,s1); substdio_puts(subfderr,s2); substdio_puts(subfderr,"\n"); substdio_flush(subfderr); } void logstring(int level, const char *string) { if (level > loglevel) return; substdio_puts(subfderr,string); } void logflush(int level) { if (level > loglevel) return; substdio_puts(subfderr,"\n"); substdio_flush(subfderr); } void cleanup(void); const char *remoteip; void die_read(void) { logline(1,"read error or connection closed"); cleanup(); _exit(1); } void die_write(void) { logline(1,"write error, connection closed"); cleanup(); _exit(1); } void die_alarm(void) { out("451 timeout (#4.4.2)\r\n"); logline(1,"connection timed out, closing connection"); flush(); cleanup(); _exit(1); } void die_nomem(void) { out("421 out of memory (#4.3.0)\r\n"); logline(1,"out of memory, closing connection"); flush(); cleanup(); _exit(1); } void die_control(void) { out("421 unable to read controls (#4.3.0)\r\n"); logline(1,"unable to read controls, closing connection"); flush(); _exit(1); } void die_ipme(void) { out("421 unable to figure out my IP addresses (#4.3.0)\r\n"); logline(1,"unable to figure out my IP address, closing connection"); flush(); _exit(1); } void straynewline(void) { out("451 See http://pobox.com/~djb/docs/smtplf.html.\r\n"); logline(1,"stray new line detected, closing connection"); flush(); _exit(1); } void oversizedline(void) { out("500 Text line too long."); logline(1,"Oversized line in data part, closing connection"); flush(); _exit(1); } void err_qqt(void) { out("451 qqt failure (#4.3.0)\r\n"); } void err_dns(void) { out("421 DNS temporary failure at return MX check, try again later (#4.3.0)\r\n"); } void err_soft(char *s) { out("451 "); out(s); out("\r\n"); logline2(1,"temporary verify error: ", s); } void err_bmf(void) { out("553 sorry, your mail was administratively denied. (#5.7.1)\r\n"); } void err_bmfunknown(void) { out("553 sorry, your mail from a host ["); out(remoteip); out("] without valid reverse DNS was administratively denied (#5.7.1)\r\n"); } void err_maxrcpt(void) { out("553 sorry, too many recipients (#5.7.1)\r\n"); } void err_nogateway(void) { out("553 sorry, relaying denied from your location ["); out(remoteip); out("] (#5.7.1)\r\n"); } void err_badbounce(void) { out("550 sorry, I don't accept bounce messages with more than one recipient. Go read RFC2821. (#5.7.1)\r\n"); } void err_unimpl(const char *arg) { out("502 unimplemented (#5.5.1)\r\n"); logline2(3,"unrecognized command: ",arg); } void err_size(void) { out("552 sorry, that message size exceeds my databytes limit (#5.3.4)\r\n"); logline(3,"message denied because: 'SMTP SIZE' too big"); } void err_syntax(void) { out("555 syntax error (#5.5.4)\r\n"); } void err_relay(void) { out("553 sorry, we don't relay for ["); out(remoteip); out("] (#5.7.1)\r\n"); } void err_wantmail(void) { out("503 MAIL first (#5.5.1)\r\n"); logline(4,"'mail from' first"); } void err_wantrcpt(void) { out("503 RCPT first (#5.5.1)\r\n"); logline(4,"'rcpt to' first"); } void err_noop(char *arg) { out("250 ok\r\n"); logline(4,"'noop'"); } void err_vrfy(char *arg) { out("252 send some mail, i'll try my best\r\n"); logline2(4,"vrfy for: ",arg); } void err_rbl(char *arg) { out("553 sorry, your mailserver ["); out(remoteip); out("] is rejected by "); out(arg); out("\r\n"); } void err_deny(void) { out("553 sorry, mail from your location ["); out(remoteip); out("] is administratively denied (#5.7.1)\r\n"); } void err_badrcptto(void) { out("553 sorry, mail to that recipient is not accepted (#5.7.1)\r\n"); } void err_554msg(const char *arg) { out("554 "); out(arg); out("\r\n"); logline2(3,"message denied: ",arg); } stralloc me = {0}; stralloc greeting = {0}; stralloc cookie = {0}; void stutter(const char *); void smtp_greet(const char *code) { stutter(code); stutter(me.s); stutter(" ESMTP "); substdio_put(&ssout,greeting.s,greeting.len); if (cookie.len > 0) { substdio_puts(&ssout," "); substdio_put(&ssout,cookie.s,cookie.len); } out("\r\n"); } void smtp_line(const char *code) { substdio_puts(&ssout,code); substdio_puts(&ssout,me.s); substdio_puts(&ssout," "); substdio_put(&ssout,greeting.s,greeting.len); out("\r\n"); } void smtp_help(char *arg) { out("214-qmail home page: http://pobox.com/~djb/qmail.html\r\n"); out("214 qmail-ldap patch home page: http://www.nrg4u.com\r\n"); logline(4,"help requested"); } void smtp_quit(char *arg) { if (!stralloc_copys(&greeting,"Goodbye.")) die_nomem(); smtp_line("221 "); logline(4,"quit, closing connection"); flush(); cleanup(); _exit(0); } void err_quit(void) { logline(4,"force closing connection"); flush(); cleanup(); _exit(0); } const char *remotehost; const char *remoteinfo; const char *local; const char *relayclient; const char *relayok; const char *greeting550; const char *greeting421; int spamflag = 0; stralloc helohost = {0}; char *fakehelo; /* pointer into helohost, or 0 */ void dohelo(const char *arg) { if (!stralloc_copys(&helohost,arg)) die_nomem(); if (!stralloc_0(&helohost)) die_nomem(); fakehelo = case_diffs(remotehost,helohost.s) ? helohost.s : 0; } int liphostok = 0; stralloc liphost = {0}; int gmfok = 0; stralloc gmf = {0}; struct constmap mapgmf; int bmfok = 0; stralloc bmf = {0}; struct constmap mapbmf; int bmfunknownok = 0; stralloc bmfunknown = {0}; struct constmap mapbmfunknown; int rmfok = 0; stralloc rmf = {0}; struct constmap maprmf; int brtok = 0; stralloc brt = {0}; struct constmap mapbadrcptto; int gmaok = 0; stralloc gma = {0}; struct constmap mapgma; int rblok = 0; int rbloh = 0; int errdisconnect = 0; int nobounce = 0; int sanitycheck = 0; int returnmxcheck = 0; int blockrelayprobe = 0; unsigned int tarpitcount = 0; unsigned int tarpitdelay = 5; unsigned int maxrcptcount = 0; unsigned int badrcptdelay = 0; int sendercheck = 0; int rcptcheck = 0; int ldapsoftok = 0; int flagauth = 0; int needauth = 0; int needssl = 0; int flagauthok = 0; int flagextauth = 0; int flagnolocal = 0; const char *authprepend; #ifdef TLS_SMTPD stralloc sslcert = {0}; #endif char smtpsize[FMT_ULONG]; unsigned int stutterdelay = 0; int droprushgreet = 0; void setup(void) { #ifdef TLS_SMTPD char *sslpath; #endif char *x, *l; char ulbuf[FMT_ULONG]; unsigned long u; l = env_get("LOGLEVEL"); if (l) { scan_ulong(l,&u); loglevel = u > 4 ? 4 : u; } if (control_init() == -1) die_control(); if (control_readline(&me,"control/me") != 1) die_control(); if (!stralloc_0(&me)) die_nomem(); if (control_rldef(&greeting,"control/smtpgreeting", 0, "") == -1) die_control(); if (control_rldef(&cookie,"control/smtpclustercookie", 0, "") == -1) die_control(); if (cookie.len > 32) cookie.len = 32; liphostok = control_rldef(&liphost,"control/localiphost",1,(char *) 0); if (liphostok == -1) die_control(); if (control_readint(&timeout,"control/timeoutsmtpd") == -1) die_control(); if (timeout <= 0) timeout = 1; #ifdef TLS_SMTPD sslpath = env_get("SSLCERT"); if (!sslpath) { sslpath = (char *)"control/smtpcert"; if (control_readline(&sslcert, sslpath) == -1) die_control(); } else if (!stralloc_copys(&sslcert, sslpath)) die_nomem(); if (!stralloc_0(&sslcert)) die_nomem(); #endif x = env_get("TARPITCOUNT"); if (x) { scan_ulong(x,&u); tarpitcount = u >= UINT_MAX ? UINT_MAX - 1 : u; } x = env_get("TARPITDELAY"); if (x) { scan_ulong(x,&u); tarpitdelay = u > INT_MAX ? INT_MAX : u; } x = env_get("MAXRCPTCOUNT"); if (x) { scan_ulong(x,&u); maxrcptcount = u >= UINT_MAX ? UINT_MAX - 1 : u; }; x = env_get("BADRCPTDELAY"); if (x) { scan_ulong(x,&u); badrcptdelay = u > INT_MAX ? INT_MAX : u; } x = env_get("GREETDELAY"); if (x) { scan_ulong(x,&u); stutterdelay = u > INT_MAX ? INT_MAX : u; } if (env_get("DROPRUSHGREET")) droprushgreet = 1; if (rcpthosts_init() == -1) die_control(); gmfok = control_readfile(&gmf,"control/goodmailfrom",0); if (gmfok == -1) die_control(); if (gmfok) if (!constmap_init(&mapgmf,gmf.s,gmf.len,0)) die_nomem(); bmfok = control_readfile(&bmf,"control/badmailfrom",0); if (bmfok == -1) die_control(); if (bmfok) if (!constmap_init(&mapbmf,bmf.s,bmf.len,0)) die_nomem(); bmfunknownok = control_readfile(&bmfunknown,"control/badmailfrom-unknown",0); if (bmfunknownok == -1) die_control(); if (bmfunknownok) if (!constmap_init(&mapbmfunknown,bmfunknown.s,bmfunknown.len,0)) die_nomem(); rmfok = control_readfile(&rmf,"control/relaymailfrom",0); if (rmfok == -1) die_control(); if (rmfok) if (!constmap_init(&maprmf,rmf.s,rmf.len,0)) die_nomem(); brtok = control_readfile(&brt,"control/badrcptto",0); if (brtok == -1) die_control(); if (brtok) if (!constmap_init(&mapbadrcptto,brt.s,brt.len,0)) die_nomem(); gmaok = control_readfile(&gma,"control/goodmailaddr",0); if (gmaok == -1) die_control(); if (gmaok) if (!constmap_init(&mapgma,gma.s,gma.len,0)) die_nomem(); if (env_get("RBL")) { rblok = rblinit(); if (rblok == -1) die_control(); if (env_get("RBLONLYHEADER")) rbloh = 1; } if (env_get("SMTP550DISCONNECT")) errdisconnect = 1; if (env_get("NOBOUNCE")) nobounce = 1; if (env_get("SANITYCHECK")) sanitycheck = 1; if (env_get("RETURNMXCHECK")) returnmxcheck = 1; if (env_get("BLOCKRELAYPROBE")) blockrelayprobe = 1; if (env_get("SENDERCHECK")) { sendercheck = 1; if (!case_diffs("LOOSE",env_get("SENDERCHECK"))) sendercheck = 2; if (!case_diffs("STRICT",env_get("SENDERCHECK"))) sendercheck = 3; } if (env_get("RCPTCHECK")) rcptcheck = 1; if (env_get("LDAPSOFTOK")) ldapsoftok = 1; greeting550 = env_get("550GREETING"); greeting421 = env_get("421GREETING"); relayok = relayclient = env_get("RELAYCLIENT"); if (env_get("SMTPAUTH")) { flagauth = 1; if (!case_diffs("TLSREQUIRED", env_get("SMTPAUTH"))) needssl = 1; } if (env_get("AUTHREQUIRED")) needauth = 1; if (env_get("AUTHORIZED")) flagextauth = 1; authprepend = env_get("AUTHPREPEND"); if (env_get("NOLOCAL")) flagnolocal = 1; #ifdef SMTPEXECCHECK execcheck_setup(); #endif if (control_readulong(&databytes,"control/databytes") == -1) die_control(); x = env_get("DATABYTES"); if (x) scan_ulong(x,&databytes); if (!(databytes + 1)) --databytes; /* poor man overflow detection */ remoteip = env_get("TCPREMOTEIP"); if (!remoteip) remoteip = "unknown"; remotehost = env_get("TCPREMOTEHOST"); if (!remotehost) remotehost = "unknown"; remoteinfo = env_get("TCPREMOTEINFO"); local = env_get("TCPLOCALHOST"); if (!local) local = env_get("TCPLOCALIP"); if (!local) local = "unknown"; logpid(2); logstring(2,"connection from "); logstring(2,remoteip); logstring(2," ("); logstring(2,remotehost); if (remoteinfo) { logstring(2,", "); logstring(2,remoteinfo); } logstring(2,") to "); logstring(2,local); logflush(2); logpid(3); logstring(3, "enabled options: "); if (databytes != 0) { smtpsize[fmt_ulong(smtpsize, databytes)] = 0; logstring(3,"max msg size: "); logstring(3,smtpsize); logstring(3," "); } if (greeting550) logstring(3,"greeting550 "); if (greeting421) logstring(3,"greeting421 "); if (stutterdelay != 0) { ulbuf[fmt_ulong(ulbuf, stutterdelay)] = 0; logstring(3, "GREETDELAY "); logstring(3,ulbuf); logstring(3," "); } if (droprushgreet) logstring(3,"droprushgreet "); #ifdef TLS_SMTPD if (sslcert.s && *sslcert.s) logstring(3, "starttls "); #endif if (flagnolocal) logstring(3, "nolocal "); if (relayclient) logstring(3,"relayclient "); if (sanitycheck) logstring(3,"sanitycheck "); if (returnmxcheck) logstring(3,"returnmxcheck "); if (blockrelayprobe) logstring(3,"blockrelayprobe "); if (nobounce) logstring(3,"nobounce "); if (rblok) logstring(3,"rblcheck "); if (rbloh) logstring(3,"rblonlyheader "); if (sendercheck) logstring(3,"sendercheck"); if (sendercheck == 1) logstring(3," "); if (sendercheck == 2) logstring(3,"-loose "); if (sendercheck == 3) logstring(3,"-strict "); if (rcptcheck) logstring(3,"rcptcheck "); if (badrcptdelay) { ulbuf[fmt_ulong(ulbuf, badrcptdelay)] = 0; logstring(3, "badrcptdelay "); logstring(3,ulbuf); logstring(3," "); } if (ldapsoftok) logstring(3,"ldapsoftok "); if (flagauth) logstring(3, "smtp-auth"); if (needssl) logstring(3, "-tls-required "); else logstring(3, " "); if (needauth) logstring(3, "authrequired "); if (flagextauth) logstring(3, "authorized "); if (authprepend) { logstring(3, "authprepend: "); logstring(3,authprepend); logstring(3," "); } #ifdef SMTPEXECCHECK if (execcheck_on()) logstring(3, "rejectexecutables "); #endif if (errdisconnect) logstring(3,"smtp550disconnect "); #ifdef ALTQUEUE if (env_get("QMAILQUEUE")) { logstring(3,"qmailqueue "); logstring(3,env_get("QMAILQUEUE")); } #endif logflush(3); dohelo(remotehost); } stralloc addr = {0}; /* will be 0-terminated, if addrparse returns 1 */ int addrparse(char *arg) { unsigned int i; char ch; char terminator; struct ip_address ip; int flagesc; int flagquoted; terminator = '>'; i = str_chr(arg,'<'); if (arg[i]) arg += i + 1; else { /* partner should go read rfc 821 */ terminator = ' '; arg += str_chr(arg,':'); if (*arg == ':') ++arg; if (*arg == '\0') return 0; while (*arg == ' ') ++arg; } /* strip source route */ if (*arg == '@') while (*arg) if (*arg++ == ':') break; if (!stralloc_copys(&addr,"")) die_nomem(); flagesc = 0; flagquoted = 0; for (i = 0;(ch = arg[i]);++i) { /* copy arg to addr, stripping quotes */ if (flagesc) { if (!stralloc_append(&addr,&ch)) die_nomem(); flagesc = 0; } else { if (!flagquoted && (ch == terminator)) break; switch(ch) { case '\\': flagesc = 1; break; case '"': flagquoted = !flagquoted; break; default: if (!stralloc_append(&addr,&ch)) die_nomem(); } } } /* could check for termination failure here, but why bother? */ if (!stralloc_append(&addr,"")) die_nomem(); if (liphostok) { i = byte_rchr(addr.s,addr.len,'@'); if (i < addr.len) /* if not, partner should go read rfc 821 */ if (addr.s[i + 1] == '[') if (!addr.s[i + 1 + ip_scanbracket(addr.s + i + 1,&ip)]) if (ipme_is(&ip)) { addr.len = i + 1; if (!stralloc_cat(&addr,&liphost)) die_nomem(); if (!stralloc_0(&addr)) die_nomem(); } } if (addr.len > 900) return 0; return 1; } stralloc checkhost = {0}; ipalloc checkip = {0}; int badmxcheck(char *dom) { int ret = 0; unsigned long r; if (!*dom) return (DNS_HARD); if (!stralloc_copys(&checkhost,dom)) return (DNS_SOFT); r = now() + (getpid() << 16); switch (dns_mxip(&checkip,&checkhost,r)) { case DNS_MEM: case DNS_SOFT: ret = DNS_SOFT; break; case DNS_HARD: ret = DNS_HARD; break; case 1: if (checkip.len <= 0) ret = DNS_SOFT; break; default: if (checkip.len <= 0) ret = DNS_HARD; break; } return (ret); } stralloc parameter = {0}; char *getparameter(char *arg, const char *name) { unsigned int i; char ch; char terminator; int flagesc; int flagquoted; terminator = '>'; i = str_chr(arg,'<'); if (arg[i]) arg += i + 1; else { /* partner should go read rfc 821 */ terminator = ' '; arg += str_chr(arg,':'); if (*arg == ':') ++arg; while (*arg == ' ') ++arg; } flagesc = 0; flagquoted = 0; for (i = 0;(ch = arg[i]);++i) { /* skipping addr, respecting quotes */ if (flagesc) { flagesc = 0; } else { if (!flagquoted && (ch == terminator)) break; switch(ch) { case '\\': flagesc = 1; break; case '"': flagquoted = !flagquoted; break; default: break; } } } if (!arg[i++]) return (char *)0; /* no parameters */ arg += i; do { while (*arg == ' ') if (!*arg++) return (char *)0; if (case_diffb(arg, str_len(name), name) == 0) { arg += str_len(name); if (*arg++ == '=') { i = str_chr(arg, ' '); if (!stralloc_copyb(&parameter, arg, i)) die_nomem(); if (!stralloc_0(&parameter)) die_nomem(); return parameter.s; } } while (*arg != ' ') if (!*arg++) return (char *)0; } while (1); } int sizelimit(char *arg) { char *size; unsigned long sizebytes = 0; size = getparameter(arg, "SIZE"); if (!size) return 1; scan_ulong(size, &sizebytes); return databytes >= sizebytes; } int gmfcheck(void) { unsigned int j; if (!gmfok) return 0; if (constmap(&mapgmf,addr.s,addr.len - 1)) return 1; j = byte_rchr(addr.s,addr.len,'@'); if (j < addr.len) { if (constmap(&mapgmf,addr.s + j,addr.len - j - 1)) return 1; if (constmap(&mapgmf,addr.s, j + 1)) return 1; } return 0; } int bmfcheck(void) { unsigned int j; if (!bmfok) return 0; if (constmap(&mapbmf,addr.s,addr.len - 1)) return 1; j = byte_rchr(addr.s,addr.len,'@'); if (j < addr.len) { if (constmap(&mapbmf,addr.s + j,addr.len - j - 1)) return 1; if (constmap(&mapbmf,addr.s, j + 1)) return 1; } return 0; } int bmfunknowncheck(void) { unsigned int j; if (!bmfunknownok) return 0; if (case_diffs(remotehost,"unknown")) return 0; if (constmap(&mapbmfunknown,addr.s,addr.len - 1)) return 1; j = byte_rchr(addr.s,addr.len,'@'); if (j < addr.len) { if (constmap(&mapbmfunknown,addr.s + j, addr.len - j - 1)) return 1; if (constmap(&mapbmfunknown,addr.s, j + 1)) return 1; } return 0; } int seenmail = 0; stralloc mailfrom = {0}; stralloc rcptto = {0}; unsigned int rcptcount; int rmfcheck(void) { unsigned int j; if (!rmfok) return 0; if (constmap(&maprmf,addr.s,addr.len - 1)) return 1; j = byte_rchr(addr.s,addr.len,'@'); if (j < addr.len) if (constmap(&maprmf,addr.s + j,addr.len - j - 1)) return 1; return 0; } int addrallowed(void) { int r; r = rcpthosts(addr.s,addr.len - 1, flagnolocal); if (r == -1) die_control(); return r; } int addrlocals(void) { int r; r = localhosts(addr.s, addr.len - 1); if (r == -1) die_control(); return r; } int rcptdenied(void) { unsigned int j; if (!brtok) return 0; if (constmap(&mapbadrcptto, addr.s, addr.len - 1)) return 1; j = byte_rchr(addr.s,addr.len,'@'); if (j < addr.len) { if (constmap(&mapbadrcptto, addr.s + j, addr.len - j - 1)) return 1; if (constmap(&mapbadrcptto, addr.s, j + 1)) return 1; } return 0; } stralloc gmaddr; int goodmailaddr(void) { unsigned int at; #ifdef DASH_EXT unsigned int ext; int extcnt; #endif if (!gmaok) return 0; if (constmap(&mapgma, addr.s, addr.len - 1)) return 1; at = byte_rchr(addr.s,addr.len,'@'); if (at < addr.len) { if (constmap(&mapgma, addr.s + at, addr.len - at - 1)) return 1; if (constmap(&mapgma, addr.s, at + 1)) return 1; #ifdef DASH_EXT /* <EMAIL> */ for (ext = 0, extcnt = 1; ext < at && extcnt <= DASH_EXT_LEVELS; ext++) if (addr.s[ext] == *auto_break) extcnt++; for (;;) { if (addr.s[ext] == *auto_break) { if (!stralloc_copyb(&gmaddr, addr.s, ext + 1)) die_nomem(); if (!stralloc_cats(&gmaddr, LDAP_CATCH_ALL)) die_nomem(); if (!stralloc_catb(&gmaddr, addr.s + at, addr.len - at - 1)) die_nomem(); if (constmap(&mapgma, gmaddr.s, gmaddr.len)) return 1; } if (ext == 0) break; ext--; } #endif /* <EMAIL> */ if (!stralloc_copys(&gmaddr, LDAP_CATCH_ALL)) die_nomem(); if (!stralloc_catb(&gmaddr, addr.s + at, addr.len - at - 1)) die_nomem(); if (constmap(&mapgma, gmaddr.s, gmaddr.len)) return 1; } return 0; } struct call ccverify; stralloc verifyresponse; int flagverify = 0; void ldaplookupdone(void) { if (flagverify != 1) return; call_close(&ccverify); flagverify = 0; return; } int ldaplookup(char *address, char **s) { char ch; if (flagverify == -1) return -1; if (flagverify == 0) { if (call_open(&ccverify, "bin/qmail-verify", 30, 0) == -1) { flagverify = -1; return -1; } flagverify = 1; } call_puts(&ccverify, address); call_putflush(&ccverify, "", 1); if (call_getc(&ccverify, &ch) != 1) goto fail; switch (ch) { case 'K': return 1; case 'D': /* get response */ if (!stralloc_copys(&verifyresponse, "")) die_nomem(); while (call_getc(&ccverify, &ch) == 1) { if (!stralloc_append(&verifyresponse, &ch)) die_nomem(); if (ch == 0) { *s = verifyresponse.s; return 0; } } break; case 'Z': /* soft error */ if (!stralloc_copys(&verifyresponse, "")) die_nomem(); while (call_getc(&ccverify, &ch) == 1) { if (!stralloc_append(&verifyresponse, &ch)) die_nomem(); if (ch == 0) { *s = verifyresponse.s; return -1; } } break; default: break; } fail: flagverify = -1; call_close(&ccverify); return -1; } int relayprobe(void) /* relay probes trying stupid old sendwhale bugs */ { unsigned int j; for (j = byte_rchr(addr.s, addr.len, '@'); j-- > 0; ) { if (addr.s[j] == '@') return 1; /* double @ */ if (addr.s[j] == '%') return 1; /* percent relaying */ if (addr.s[j] == '!') return 1; /* UUCP bang path */ } return 0; } void smtp_helo(char *arg) { smtp_line("250 "); seenmail = 0; dohelo(arg); logline2(4, "remote helo: ", arg); } void smtp_ehlo(char *arg) { smtp_line("250-"); out("250-PIPELINING\r\n"); if (databytes != 0) { smtpsize[fmt_ulong(smtpsize, databytes)] = 0; out("250-SIZE "); out(smtpsize); out("\r\n"); } #ifdef DATA_COMPRESS out("250-DATAZ\r\n"); #endif #ifdef TLS_SMTPD if (!ssl && sslcert.s && *sslcert.s) out("250-STARTTLS\r\n"); #endif #ifdef TLS_SMTPD if (!needssl || ssl) #endif if (flagauth) out("250-AUTH LOGIN PLAIN\r\n"); out("250 8BITMIME\r\n"); seenmail = 0; dohelo(arg); logline2(4,"remote ehlo: ",arg); } void smtp_rset(char *arg) { seenmail = 0; if (relayclient != NULL && relayok == NULL) env_unset("RELAYCLIENT"); relayclient = relayok; /* restore original relayclient setting */ out("250 flushed\r\n"); logline(4,"remote rset"); } struct qmail qqt; void smtp_mail(char *arg) { unsigned int i; char *rblname; int bounceflag = 0; int isgmf = 0; /* address syntax check */ if (!addrparse(arg)) { err_syntax(); logline2(3,"RFC2821 syntax error in mail from: ",arg); if (errdisconnect) err_quit(); return; } logline2(4,"mail from: ",addr.s); if (needauth && !(flagauthok || flagextauth)) { out("530 authentication needed\r\n"); logline(3, "auth needed"); if (errdisconnect) err_quit(); return; } /* check if we are authenticated, if yes enable relaying */ if (flagauthok && relayclient == 0) { relayclient = ""; if (!env_put("RELAYCLIENT=")) die_nomem(); } /* smtp size check */ if (databytes && !sizelimit(arg)) { err_size(); /* logging is done in error routine */ if (errdisconnect) err_quit(); return; } /* good mailfrom check */ if (gmfcheck()) isgmf = 1; /* bad mailfrom check */ if (!isgmf && bmfcheck()) { err_bmf(); logline2(3,"bad mailfrom: ",addr.s); if (errdisconnect) err_quit(); return; } /* bad mailfrom unknown check */ if (!isgmf && bmfunknowncheck()) { err_bmfunknown(); logline2(3,"bad mailfrom unknown: ",addr.s); if (errdisconnect) err_quit(); return; } /* NOBOUNCE check */ if (!addr.s[0] || !str_diff("#@[]", addr.s)) { bounceflag = 1; if (nobounce) { err_554msg("RFC2821 bounces are administratively denied"); if (errdisconnect) err_quit(); return; } } /* Sanity checks */ if (!isgmf && sanitycheck && !bounceflag) { /* Invalid Mailfrom */ if ((i=byte_rchr(addr.s,addr.len,'@')) >= addr.len) { err_554msg("mailfrom without @ is administratively denied"); if (errdisconnect) err_quit(); return; } if (i == 0 || addr.s[i+1] == '\0') { err_554msg("mailfrom without user or domain part is " "administratively denied"); if (errdisconnect) err_quit(); return; } /* No '.' in domain.TLD */ if (byte_rchr(addr.s+i, addr.len-i, '.') >= addr.len-i) { err_554msg("mailfrom without . in domain part is " "administratively denied"); if (errdisconnect) err_quit(); return; } } /* relay mail from check (allow relaying based on evelope sender address) */ if (!relayclient) { if (rmfcheck()) { relayclient = ""; if (!env_put("RELAYCLIENT=")) die_nomem(); logline(4,"relaying allowed via relaymailfrom"); } } /* Check RBL only if relayclient is not set */ if (!isgmf && rblok && !relayclient) { switch(rblcheck(remoteip, &rblname, rbloh)) { case 2: /* soft error lookup */ /* * continue if RBL DNS has a problem. if a RBL is unreachable * we dont want to fail. accept message anyway. a false negative * is better in this case than rejecting every message just * because one RBL failed. play safe, might be an important mail. */ break; case 1: /* host is listed in RBL */ err_rbl(rblname); if (errdisconnect) err_quit(); return; default: /* ok, go ahead */ logline(4,"RBL checking completed"); break; } } /* return MX check */ if (!isgmf && returnmxcheck && !bounceflag) { if ((i=byte_rchr(addr.s,addr.len,'@')) < addr.len) switch (badmxcheck(&addr.s[i+1])) { case 0: break; /* valid */ case DNS_SOFT: err_dns(); logline(3,"refused mailfrom because return MX lookup " "failed temporarly"); if (errdisconnect) err_quit(); return; case DNS_HARD: default: err_554msg("refused mailfrom because return MX does not exist"); if (errdisconnect) err_quit(); return; } } /* check if sender exists in ldap */ if (!isgmf && sendercheck && !bounceflag) { if (!goodmailaddr()) { /* good mail addrs go through anyway */ logline(4,"sender verify, sender not in goodmailaddr"); if (addrlocals()) { char *s; logline(4,"sender verify, sender is local"); switch (ldaplookup(addr.s, &s)) { case 1: /* valid */ logline(4,"sender verify OK"); break; case 0: /* invalid */ logline2(2, "bad sender: ", addr.s); err_554msg(s); if (errdisconnect) err_quit(); return; case -1: default: /* other error, treat as soft 4xx */ if (ldapsoftok) break; err_soft(s); if (errdisconnect) err_quit(); return; } } else { /* not in addrlocals, ldap lookup is useless */ /* normal mode: let through, it's just an external mail coming in */ /* loose mode (2): see if sender is in rcpthosts, if no reject here */ /* strict mode (3): validated sender required so reject in any case */ if ((sendercheck == 2 && !addrallowed()) || sendercheck == 3) { err_554msg("refused mailfrom because valid " "local sender address required"); if (errdisconnect) err_quit(); return; } } } } seenmail = 1; if (!stralloc_copys(&rcptto,"")) die_nomem(); if (!stralloc_copys(&mailfrom,addr.s)) die_nomem(); if (!stralloc_0(&mailfrom)) die_nomem(); rcptcount = 0; if (loglevel < 4) logline2(2,"mail from: ",mailfrom.s); out("250 ok\r\n"); } void smtp_rcpt(char *arg) { if (!seenmail) { err_wantmail(); if (errdisconnect) err_quit(); return; } /* syntax check */ if (!addrparse(arg)) { err_syntax(); logline2(3,"syntax error in 'rcpt to': ",arg); if (errdisconnect) err_quit(); return; } logline2(4,"rcpt to: ",addr.s); /* block stupid and bogus sendwhale bug relay probing */ /* don't enable this if you use percenthack */ if (blockrelayprobe && relayprobe()) { err_relay(); logline(3,"'rcpt to' denied, looks like bogus sendwhale bug relay probe"); if (errdisconnect) err_quit(); return; } /* do we block this recipient */ if (rcptdenied()) { err_badrcptto(); logline2(3,"'rcpt to' denied via badrcptto: ",addr.s); if (errdisconnect) err_quit(); return; } /* is sender ip allowed to relay */ if (relayclient) { --addr.len; if (!stralloc_cats(&addr,relayclient)) die_nomem(); if (!stralloc_0(&addr)) die_nomem(); } else { if (!addrallowed()) { err_nogateway(); logline2(3,"no mail relay for 'rcpt to': ",addr.s); if (errdisconnect) err_quit(); return; } } ++rcptcount; /* maximum recipient limit reached */ if (maxrcptcount && rcptcount > maxrcptcount) { err_maxrcpt(); logline(3,"message denied because of more 'RCPT TO' than " "allowed by MAXRCPTCOUNT"); if (errdisconnect) err_quit(); return; } /* only one recipient for bounce messages */ if (rcptcount > 1 && (!mailfrom.s[0] || !str_diff("#@[]", mailfrom.s))) { err_badbounce(); logline(3,"bounce message denied because it has more than one recipient"); if (errdisconnect) err_quit(); return; } /* check if recipient exists in ldap */ if (rcptcheck) { if (!goodmailaddr()) { logline(4,"recipient verify, recipient not in goodmailaddr"); if (addrlocals()||addrallowed()) { char *s; logline(4,"recipient verify, recipient is local"); switch (ldaplookup(addr.s, &s)) { case 1: /* valid */ logline(4,"recipient verify OK"); break; case 0: /* invalid */ logline2(2, "bad recipient: ", addr.s); if (badrcptdelay) sleep(badrcptdelay); err_554msg(s); if (errdisconnect) err_quit(); return; case -1: default: /* other error, treat as soft 4xx */ if (ldapsoftok) break; err_soft(s); if (errdisconnect) err_quit(); return; } } /* else this is relaying, don't do anything */ } } if (loglevel < 4) logline2(2,"rcpt to: ",addr.s); if (!stralloc_cats(&rcptto,"T")) die_nomem(); if (!stralloc_cats(&rcptto,addr.s)) die_nomem(); if (!stralloc_0(&rcptto)) die_nomem(); if (tarpitcount && tarpitdelay && rcptcount >= tarpitcount) { logline(3,"tarpitting"); sleep(tarpitdelay); } out("250 ok\r\n"); } #ifdef DATA_COMPRESS z_stream stream; char zbuf[4096]; int wantcomp = 0; int compdata = 0; int compression_init(void) { compdata = 1; stream.zalloc = Z_NULL; stream.zfree = Z_NULL; stream.opaque = Z_NULL; stream.avail_in = 0; stream.next_in = zbuf; if (inflateInit(&stream) != Z_OK) { out("451 Initalizing data compression failed: "); out(stream.msg); out(" #(4.3.0)\r\n"); flush(); return -1; } return 0; } int compression_done(void) { char num[FMT_ULONG + 1]; int r; compdata = 0; if (stream.avail_out != sizeof(zbuf)) { /* there is some left data, ignore */ } if (inflateEnd(&stream) != Z_OK) { out("451 Finishing data compression failed: "); out(stream.msg); out(" #(4.3.0)\r\n"); flush(); return -1; } r = 100 - (int)(100.0*stream.total_in/stream.total_out); if (r < 0) { num[0] = '-'; r *= -1; } else num[0] = ' '; num[fmt_uint(num+1,r)+1] = 0; logpid(3); logstring(3,"DDC saved "); logstring(3,num); logstring(3," percent"); logflush(3); return 0; } #endif int saferead(int fd,void *buf,int len) { int r; flush(); #ifdef DATA_COMPRESS if (compdata) { stream.avail_out = len; stream.next_out = buf; do { if (stream.avail_in == 0) { #ifdef TLS_SMTPD if (ssl) r = ssl_timeoutread(timeout,fd,zbuf,sizeof(zbuf)); else #endif r = timeoutread(timeout,fd,zbuf,sizeof(zbuf)); if (r == -1) if (errno == error_timeout) die_alarm(); if (r <= 0) die_read(); stream.avail_in = r; stream.next_in = zbuf; } r = inflate(&stream, 0); switch (r) { case Z_OK: if (stream.avail_out == 0) return len; break; case Z_STREAM_END: compdata = 0; return len - stream.avail_out; default: out("451 Receiving compressed data failed: "); out(stream.msg); out(" #(4.3.0)\r\n"); logline2(1, "compressed data read failed: ", stream.msg); flush(); die_read(); } if (stream.avail_out == (unsigned int)len) continue; return len - stream.avail_out; } while (1); } #endif #ifdef TLS_SMTPD if (ssl) r = ssl_timeoutread(timeout,fd,buf,len); else #endif r = timeoutread(timeout,fd,buf,len); if (r == -1) if (errno == error_timeout) die_alarm(); if (r <= 0) die_read(); return r; } char ssinbuf[1024]; substdio ssin = SUBSTDIO_FDBUF(saferead,0,ssinbuf,sizeof ssinbuf); unsigned long bytestooverflow = 0; unsigned long bytesreceived = 0; void put(const char *ch) { #ifdef SMTPEXECCHECK execcheck_put(&qqt, ch); #endif if (bytestooverflow) if (!--bytestooverflow) qmail_fail(&qqt); qmail_put(&qqt,ch,1); ++bytesreceived; } void stutter(const char *str) { int x; if (stutterdelay) { for (; *str && stutterdelay > 0; stutterdelay--) { substdio_bput(&ssout, str++, 1); flush(); if (droprushgreet) { x = timeoutread(1,0,ssinbuf,sizeof ssinbuf); if (x > 0) { err_554msg("SMTP protocol violation"); flush(); cleanup(); _exit(1); } else if (x == 0 || (x == -1 && errno != error_timeout)) die_read(); } else sleep(1); } } substdio_puts(&ssout,str); } void blast(unsigned int *hops) { char ch; int state; int flaginheader; unsigned int pos; /* number of bytes since most recent \n, if fih */ int flagmaybex; /* 1 if this line might match RECEIVED, if fih */ int flagmaybey; /* 1 if this line might match \r\n, if fih */ int flagmaybez; /* 1 if this line might match DELIVERED, if fih */ state = 1; *hops = 0; flaginheader = 1; pos = 0; flagmaybex = flagmaybey = flagmaybez = 1; for (;;) { substdio_get(&ssin,&ch,1); if (flaginheader) { if (pos < 9) { if (ch != "delivered"[pos]) if (ch != "DELIVERED"[pos]) flagmaybez = 0; if (flagmaybez) if (pos == 8) ++*hops; if (pos < 8) if (ch != "received"[pos]) if (ch != "RECEIVED"[pos]) flagmaybex = 0; if (flagmaybex) if (pos == 7) ++*hops; if (pos < 2) if (ch != "\r\n"[pos]) flagmaybey = 0; if (flagmaybey) if (pos == 1) flaginheader = 0; } ++pos; if (pos > MAXLINELEN) oversizedline(); if (ch == '\n') { pos = 0; flagmaybex = flagmaybey = flagmaybez = 1; } } switch(state) { case 0: if (ch == '\n') straynewline(); if (ch == '\r') { state = 4; continue; } break; case 1: /* \r\n */ if (ch == '\n') straynewline(); if (ch == '.') { state = 2; continue; } if (ch == '\r') { state = 4; continue; } state = 0; break; case 2: /* \r\n + . */ if (ch == '\n') straynewline(); if (ch == '\r') { state = 3; continue; } state = 0; break; case 3: /* \r\n + .\r */ if (ch == '\n') return; put("."); put("\r"); if (ch == '\r') { state = 4; continue; } state = 0; break; case 4: /* + \r */ if (ch == '\n') { state = 1; break; } if (ch != '\r') { put("\r"); state = 0; } } put(&ch); } } void acceptmessage(unsigned long qp) { static char buf[FMT_ULONG]; datetime_sec when; when = now(); out("250 ok "); buf[fmt_ulong(buf,(unsigned long) when)] = 0; out(buf); logpid(2); logstring(2,"message queued: "); logstring(2,buf); out(" qp "); buf[fmt_ulong(buf,qp)] = 0; out(buf); out(" by "); out(me.s); out("\r\n"); logstring(2," qp "); logstring(2,buf); buf[fmt_ulong(buf, bytesreceived)] = 0; logstring(2, " size "); logstring(2, buf); logstring(2, " bytes"); logflush(2); } #ifdef TLS_SMTPD stralloc protocolinfo = {0}; #endif void smtp_data(char *arg) { unsigned int hops; unsigned long qp; const char *qqx; ldaplookupdone(); if (!seenmail) { err_wantmail(); if (errdisconnect) err_quit(); return; } if (!rcptto.len) { err_wantrcpt(); if (errdisconnect) err_quit(); return; } seenmail = 0; if (databytes) bytestooverflow = databytes + 1; #ifdef SMTPEXECCHECK execcheck_start(); #endif if (qmail_open(&qqt) == -1) { err_qqt(); logline(1,"failed to start qmail-queue"); return; } qp = qmail_qp(&qqt); out("354 go ahead punk, make my day\r\n"); logline(4,"go ahead"); rblheader(&qqt); #ifdef TLS_SMTPD if(ssl){ if (!stralloc_copys(&protocolinfo, SSL_CIPHER_get_name(SSL_get_current_cipher(ssl)))) die_nomem(); #ifdef DATA_COMPRESS if (wantcomp) { if (!stralloc_cats(&protocolinfo, " encrypted compressed SMTP")) die_nomem(); } else #endif if (!stralloc_cats(&protocolinfo, " encrypted SMTP")) die_nomem(); } else { #ifdef DATA_COMPRESS if (wantcomp) { if (!stralloc_copys(&protocolinfo,"compressed SMTP")) die_nomem(); } else #endif if (!stralloc_copys(&protocolinfo,"SMTP")) die_nomem(); } if (!stralloc_0(&protocolinfo)) die_nomem(); received(&qqt,protocolinfo.s,local,remoteip,remotehost,remoteinfo,fakehelo,mailfrom.s,&rcptto.s[1]); #else #ifdef DATA_COMPRESS if (wantcomp) received(&qqt,"compressed SMTP",local,remoteip,remotehost,remoteinfo,fakehelo,mailfrom.s,&rcptto.s[1]); else #endif received(&qqt,"SMTP",local,remoteip,remotehost,remoteinfo,fakehelo,mailfrom.s,&rcptto.s[1]); #endif #ifdef DATA_COMPRESS if (wantcomp) { if (compression_init() != 0) return; } #endif blast(&hops); #ifdef DATA_COMPRESS if (wantcomp) { if (compression_done() != 0) return; } #endif hops = (hops >= MAXHOPS); if (hops) qmail_fail(&qqt); qmail_from(&qqt,mailfrom.s); qmail_put(&qqt,rcptto.s,rcptto.len); qqx = qmail_close(&qqt); if (!*qqx) { acceptmessage(qp); return; } if (hops) { out("554 too many hops, this message is looping (#5.4.6)\r\n"); logline(3,"too many hops, message is looping"); if (errdisconnect) err_quit(); return; } if (databytes) if (!bytestooverflow) { out("552 sorry, that message size exceeds my databytes limit (#5.3.4)\r\n"); logline(3,"datasize limit exceeded"); if (errdisconnect) err_quit(); return; } #ifdef SMTPEXECCHECK if (execcheck_flag()) { out("552 we don't accept email with this MIME content (#5.3.4)\r\n"); logline(3,"bad MIME attachement detected"); if (errdisconnect) err_quit(); return; } #endif logpid(1); if (*qqx == 'D') { out("554 "); logstring(1,"message permanently not accepted because: "); } else { out("451 "); logstring(1,"message temporarly not accepted because: "); } out(qqx + 1); logstring(1,qqx + 1); logflush(1); out("\r\n"); } #ifdef DATA_COMPRESS void smtp_dataz(char *arg) { wantcomp = 1; smtp_data((char *)0); } #endif stralloc line = {0}; void smtp_auth(char *arg) { struct call cct; char *type; const char *status; if (!flagauth) { err_unimpl("AUTH"); return; } if (flagauthok) { out("503 you are already authenticated\r\n"); logline(3,"reauthentication attempt rejected"); if (errdisconnect) err_quit(); return; } #ifdef TLS_SMTPD if (needssl && !ssl) { out("538 Encryption required for requested authentication mechanism"); logline(3,"TLS encryption required for authentication"); if (errdisconnect) err_quit(); return; } #endif type = arg; while (*arg != '\0' && *arg != ' ') ++arg; if (*arg) { *arg++ = '\0'; while (*arg == ' ') ++arg; } if (case_diffs(type, "login") == 0) { logline(4,"auth login"); if (call_open(&cct, "bin/auth_smtp", 30, 1) == -1) goto fail; call_puts(&cct, "login"); call_put(&cct, "", 1); if (*arg) { call_puts(&cct, arg); call_put(&cct, "", 1); } else { out("334 VXNlcm5hbWU6\r\n"); flush(); /* base64 for 'Username:' */ if (call_getln(&ssin, &line) == -1) die_read(); call_puts(&cct, line.s); call_put(&cct, "", 1); } out("334 UGFzc3dvcmQ6\r\n"); flush(); /* base64 for 'Password:' */ if (call_getln(&ssin, &line) == -1) die_read(); call_puts(&cct, line.s); call_putflush(&cct, "", 1); } else if (case_diffs(type, "plain") == 0) { logline(4,"auth plain"); if (call_open(&cct, "bin/auth_smtp", 30, 1) == -1) goto fail; call_puts(&cct, "plain"); call_put(&cct, "", 1); if (*arg) { call_puts(&cct, arg); call_putflush(&cct, "", 1); } else { out("334 \r\n"); flush(); if (call_getln(&ssin, &line) == -1) die_read(); call_puts(&cct, line.s); call_putflush(&cct, "", 1); } } else { out("504 authentication type not supported\r\n"); logstring(3,"authentication type "); logstring(3,type); logstring(3,": not supported"); logflush(3); if (errdisconnect) err_quit(); return; } fail: status = auth_close(&cct, &line, authprepend); switch (*status) { case '2': flagauthok = 1; remoteinfo = line.s; out(status); logline2(2,"authentication success, user ", remoteinfo); if (!env_put2("SMTPAUTHUSER", remoteinfo)) die_nomem(); break; case '4': case '5': sleep(1); out(status); flush(); logline2(3, "authentication failed: ", status + 4); sleep(4); if (errdisconnect) err_quit(); break; } } #ifdef TLS_SMTPD RSA *tmp_rsa_cb(SSL *s,int export,int keylength) { RSA* rsa; BIO* in; if (!export || keylength == 512) if ((in=BIO_new(BIO_s_file_internal()))) if (BIO_read_filename(in,"control/rsa512.pem") > 0) if ((rsa=PEM_read_bio_RSAPrivateKey(in,NULL,NULL,NULL))) return rsa; return (RSA_generate_key(export?keylength:512,RSA_F4,NULL,NULL)); } void smtp_tls(char *arg) { SSL_CTX *ctx; if (sslcert.s == 0 || *sslcert.s == '\0') { err_unimpl("STARTTLS"); return; } if (*arg) { out("501 Syntax error (no parameters allowed) (#5.5.4)\r\n"); logline(3,"aborting TLS negotiations, no parameters to starttls allowed"); return; } SSLeay_add_ssl_algorithms(); if(!(ctx=SSL_CTX_new(SSLv23_server_method()))) { out("454 TLS not available: unable to initialize ctx (#4.3.0)\r\n"); logline(3,"aborting TLS negotiations, " "unable to initialize local SSL context"); return; } if(!SSL_CTX_use_RSAPrivateKey_file(ctx, sslcert.s, SSL_FILETYPE_PEM)) { out("454 TLS not available: missing RSA private key (#4.3.0)\r\n"); logline2(3,"aborting TLS negotiations, " "RSA private key invalid or unable to read ", sslcert.s); return; } if(!SSL_CTX_use_certificate_chain_file(ctx, sslcert.s)) { out("454 TLS not available: missing certificate (#4.3.0)\r\n"); logline2(3,"aborting TLS negotiations, " "local cert invalid or unable to read ", sslcert.s); return; } SSL_CTX_set_tmp_rsa_callback(ctx, tmp_rsa_cb); out("220 ready for tls\r\n"); flush(); if(!(ssl=SSL_new(ctx))) { logline(3,"aborting TLS connection, unable to set up SSL session"); die_read(); } SSL_set_rfd(ssl,substdio_fileno(&ssin)); SSL_set_wfd(ssl,substdio_fileno(&ssout)); if(SSL_accept(ssl)<=0) { logline(3,"aborting TLS connection, unable to finish SSL accept"); die_read(); } //substdio_fdbuf(&ssout,SSL_write,ssl,ssoutbuf,sizeof(ssoutbuf)); remotehost = env_get("TCPREMOTEHOST"); if (!remotehost) remotehost = "unknown"; dohelo(remotehost); } #endif void cleanup(void) { ldaplookupdone(); } void err_503or421(char *arg) { if (greeting421) out("421 Service temporarily not available (#4.3.2)\r\n"); else out("503 bad sequence of commands (#5.5.1)\r\n"); if (errdisconnect) err_quit(); } void err_badcommand(char *arg) { out("503 bad sequence of commands (#5.5.1)\r\n"); } struct commands smtpcommands[] = { { "rcpt", smtp_rcpt, 0 } , { "mail", smtp_mail, 0 } , { "data", smtp_data, flush } , { "quit", smtp_quit, flush } , { "helo", smtp_helo, flush } , { "ehlo", smtp_ehlo, flush } , { "rset", smtp_rset, 0 } , { "help", smtp_help, flush } #ifdef TLS_SMTPD , { "starttls", smtp_tls, flush } #endif #ifdef DATA_COMPRESS , { "dataz", smtp_dataz, flush } #endif , { "auth", smtp_auth, flush } , { "noop", err_noop, flush } , { "vrfy", err_vrfy, flush } , { 0, err_unimpl, flush } } ; struct commands smtprestricted[] = { { "quit", smtp_quit, flush } , { "helo", err_503or421, flush } , { "ehlo", err_503or421, flush } , { 0, err_badcommand, flush } }; int main(int argc, char **argv) { #ifdef TLS_SMTPD sig_alarmcatch(sigalrm); #endif sig_pipeignore(); if (chdir(auto_qmail) == -1) die_control(); setup(); if (ipme_init() != 1) die_ipme(); if (greeting550 || greeting421) { if (!stralloc_copys(&greeting,greeting550 ? greeting550 : greeting421)) die_nomem(); timeout = 20; /* reduce timeout so the abuser is kicked out faster */ if (greeting.len == 0 && greeting550) stralloc_copys(&greeting, "Sorry, your mail was administratively denied. (#5.7.1)"); else if (greeting.len == 0 && greeting421) stralloc_copys(&greeting, "Service temporarily not available (#4.3.2)"); smtp_line(greeting550 ? "554 " : "421 "); if (errdisconnect) err_quit(); if (commands(&ssin,smtprestricted) == 0) die_read(); die_nomem(); } smtp_greet("220 "); if (commands(&ssin,smtpcommands) == 0) die_read(); die_nomem(); /* NOTREACHED */ return 1; }
openwengo/qmail-ldap
dnsdoe.c
#include "substdio.h" #include "subfd.h" #include "exit.h" #include "dns.h" #include "dnsdoe.h" void dnsdoe(r) int r; { switch (r) { case DNS_HARD: substdio_putsflush(subfderr,"hard error\n"); _exit(100); case DNS_SOFT: substdio_putsflush(subfderr,"soft error\n"); _exit(111); case DNS_MEM: substdio_putsflush(subfderr,"out of memory\n"); _exit(111); } }
openwengo/qmail-ldap
rcpthosts.c
#include "cdb.h" #include "byte.h" #include "case.h" #include "open.h" #include "error.h" #include "control.h" #include "constmap.h" #include "stralloc.h" #include "rcpthosts.h" static int flagrh = -1; static stralloc rh = {0}; static struct constmap maprh; static int fdlo; static int fdrh; static int fdmrh; static struct cdb cdblo; static struct cdb cdbrh; static struct cdb cdbmrh; static stralloc locals = {0}; static struct constmap maplocals; int rcpthosts_init(void) { fdlo = open_read("control/locals.cdb"); if (fdlo == -1) { if (errno != error_noent) return -1; if (control_readfile(&locals,"control/locals",1) != 1) return -1; if (!constmap_init(&maplocals,locals.s,locals.len,0)) return -1; } else cdb_init(&cdblo, fdlo); fdrh = open_read("control/rcpthosts.cdb"); if (fdrh == -1) { if (errno != error_noent) return -1; if (control_readfile(&rh,"control/rcpthosts",0) == -1) return -1; if (!constmap_init(&maprh,rh.s,rh.len,0)) return -1; fdmrh = open_read("control/morercpthosts.cdb"); if (fdmrh == -1) { if (errno != error_noent) return -1; } else cdb_init(&cdbmrh, fdmrh); } else cdb_init(&cdbrh, fdrh); flagrh = 1; return 0; } static stralloc host = {0}; int localhosts(char *buf, unsigned int len) { unsigned int j; uint32 dlen; if (flagrh < 0) return 0; j = byte_rchr(buf,len,'@'); if (j >= len) return 0; /* envnoathost is not acceptable */ ++j; buf += j; len -= j; if (!stralloc_copyb(&host,buf,len)) return -1; buf = host.s; case_lowerb(buf,len); /* if local.cdb available use this as source */ if (fdlo != -1) return cdb_seek(&cdblo, buf, len, &dlen); else if (constmap(&maplocals, buf, len)) return 1; return 0; } int rcpthosts(char *buf, unsigned int len, int nolocal) { unsigned int j; int r; uint32 dlen; if (flagrh < 0) return 0; /* uh-oh init failed so fail too, * never be a open relay! */ j = byte_rchr(buf,len,'@'); if (j >= len) return 1; /* presumably envnoathost is acceptable */ ++j; buf += j; len -= j; if (!stralloc_copyb(&host,buf,len)) return -1; buf = host.s; case_lowerb(buf,len); /* first locals if enabled */ if (!nolocal) { /* if local.cdb available use this as source */ if (fdlo != -1) { r = cdb_seek(&cdblo, buf, len, &dlen); if (r) return r; } else if (constmap(&maplocals,buf,len)) return 1; } /* then rcpthosts */ for (j = 0;j < len;++j) if (!j || (buf[j] == '.')) { /* if rcpthosts.cdb available use this as source */ if (fdrh != -1) { r = cdb_seek(&cdbrh, buf + j, len - j, &dlen); if (r) return r; } else if (constmap(&maprh,buf + j,len - j)) return 1; } /* finaly morercpthosts.cdb but only if not rcpthosts.cdb avail */ if (fdmrh != -1 && fdrh == -1) { for (j = 0;j < len;++j) if (!j || (buf[j] == '.')) { r = cdb_seek(&cdbmrh,buf + j,len - j,&dlen); if (r) return r; } } return 0; }
openwengo/qmail-ldap
qmail-newmrh.c
#include <sys/types.h> #include <sys/stat.h> #include <stdio.h> #include <unistd.h> #include "strerr.h" #include "stralloc.h" #include "substdio.h" #include "getln.h" #include "exit.h" #include "readwrite.h" #include "open.h" #include "auto_qmail.h" #include "cdb_make.h" #include "case.h" #define FATAL "qmail-newmrh: fatal: " void die_read() { strerr_die2sys(111,FATAL,"unable to read control/morercpthosts: "); } void die_write() { strerr_die2sys(111,FATAL,"unable to write to control/morercpthosts.tmp: "); } char inbuf[1024]; substdio ssin; int fd; int fdtemp; struct cdb_make cdbm; stralloc line = {0}; int match; int main() { umask(033); if (chdir(auto_qmail) == -1) strerr_die4sys(111,FATAL,"unable to chdir to ",auto_qmail,": "); fd = open_read("control/morercpthosts"); if (fd == -1) die_read(); substdio_fdbuf(&ssin,subread,fd,inbuf,sizeof inbuf); fdtemp = open_trunc("control/morercpthosts.tmp"); if (fdtemp == -1) die_write(); if (cdb_make_start(&cdbm,fdtemp) == -1) die_write(); for (;;) { if (getln(&ssin,&line,&match,'\n') != 0) die_read(); case_lowerb(line.s,line.len); while (line.len) { if (line.s[line.len - 1] == ' ') { --line.len; continue; } if (line.s[line.len - 1] == '\n') { --line.len; continue; } if (line.s[line.len - 1] == '\t') { --line.len; continue; } if (line.s[0] != '#') if (cdb_make_add(&cdbm,line.s,line.len,"",0) == -1) die_write(); break; } if (!match) break; } if (cdb_make_finish(&cdbm) == -1) die_write(); if (fsync(fdtemp) == -1) die_write(); if (close(fdtemp) == -1) die_write(); /* NFS stupidity */ if (rename("control/morercpthosts.tmp","control/morercpthosts.cdb") == -1) strerr_die2sys(111,FATAL,"unable to move control/morercpthosts.tmp to control/morercpthosts.cdb"); return 0; }
openwengo/qmail-ldap
hostname.c
<gh_stars>10-100 #include <unistd.h> #include "substdio.h" #include "subfd.h" #include "readwrite.h" #include "exit.h" char host[256]; int main() { host[0] = 0; /* sigh */ gethostname(host,sizeof(host)); host[sizeof(host) - 1] = 0; substdio_puts(subfdoutsmall,host); substdio_puts(subfdoutsmall,"\n"); substdio_flush(subfdoutsmall); return 0; }
openwengo/qmail-ldap
maildir.c
<gh_stars>1-10 #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include "prioq.h" #include "env.h" #include "stralloc.h" #include "direntry.h" #include "datetime.h" #include "now.h" #include "scan.h" #include "str.h" #include "maildir.h" struct strerr maildir_chdir_err; struct strerr maildir_scan_err; int maildir_chdir(void) { char *maildir; maildir = env_get("MAILDIR"); if (!maildir) STRERR(-1,maildir_chdir_err,"MAILDIR not set") if (chdir(maildir) == -1) STRERR_SYS3(-1,maildir_chdir_err,"unable to chdir to ",maildir,": ") return 0; } void maildir_clean(tmpname) stralloc *tmpname; { DIR *dir; direntry *d; datetime_sec tnow; struct stat st; tnow = now(); dir = opendir("tmp"); if (!dir) return; while ((d = readdir(dir))) { if (d->d_name[0] == '.') continue; if (!stralloc_copys(tmpname,"tmp/")) break; if (!stralloc_cats(tmpname,d->d_name)) break; if (!stralloc_0(tmpname)) break; if (stat(tmpname->s,&st) == 0) if (tnow > st.st_atime + 129600) unlink(tmpname->s); } closedir(dir); } static int gettime(char *name, datetime_sec *mtime) { char *s; unsigned long u; struct stat st; s = name + str_rchr(name, '/'); if (*s++ != '/') return -1; s += scan_ulong(s, &u); if (u != 0 && *s == '.') { *mtime = u; return 0; } if (stat(name, &st) == -1) return -1; *mtime = st.st_mtime; return (0); } static int append(pq,filenames,subdir,tnow) prioq *pq; stralloc *filenames; char *subdir; datetime_sec tnow; { DIR *dir; direntry *d; struct prioq_elt pe; unsigned int pos; datetime_sec mtime; dir = opendir(subdir); if (!dir) STRERR_SYS3(-1,maildir_scan_err,"unable to scan $MAILDIR/",subdir,": ") while ((d = readdir(dir))) { if (d->d_name[0] == '.') continue; pos = filenames->len; if (!stralloc_cats(filenames,subdir)) break; if (!stralloc_cats(filenames,"/")) break; if (!stralloc_cats(filenames,d->d_name)) break; if (!stralloc_0(filenames)) break; if (gettime(filenames->s + pos,&mtime) == 0) if (mtime < tnow) /* don't want to mix up the order */ { pe.dt = mtime; pe.id = pos; if (!prioq_insert(pq,&pe)) break; } } closedir(dir); if (d) STRERR_SYS3(-1,maildir_scan_err,"unable to read $MAILDIR/",subdir,": ") return 0; } int maildir_scan(pq,filenames,flagnew,flagcur) prioq *pq; stralloc *filenames; int flagnew; int flagcur; { struct prioq_elt pe; datetime_sec tnow; if (!stralloc_copys(filenames,"")) return 0; while (prioq_min(pq,&pe)) prioq_delmin(pq); tnow = now(); if (flagnew) if (append(pq,filenames,"new",tnow) == -1) return -1; if (flagcur) if (append(pq,filenames,"cur",tnow) == -1) return -1; return 0; }
openwengo/qmail-ldap
auto_break.h
<gh_stars>10-100 #ifndef AUTO_BREAK_H #define AUTO_BREAK_H extern char auto_break[]; #endif
openwengo/qmail-ldap
coe.h
<reponame>openwengo/qmail-ldap #ifndef COE_H #define COE_H extern int coe(int); #endif
openwengo/qmail-ldap
chkspawn.c
#include "substdio.h" #include "subfd.h" #include "fmt.h" #include "select.h" #include "exit.h" #include "auto_spawn.h" char num[FMT_ULONG]; fd_set fds; int main(int argc, char **argv) { unsigned long hiddenlimit; unsigned long maxnumd; hiddenlimit = sizeof(fds) * 8; maxnumd = (hiddenlimit - 5) / 2; if (auto_spawn < 1) { substdio_puts(subfderr,"Oops. You have set conf-spawn lower than 1.\n"); substdio_flush(subfderr); _exit(1); } if (auto_spawn > 65000) { substdio_puts(subfderr,"Oops. You have set conf-spawn higher than 65000.\n"); substdio_flush(subfderr); _exit(1); } if (auto_spawn > maxnumd) { substdio_puts(subfderr,"Oops. Your system's FD_SET() has a hidden limit of "); substdio_put(subfderr,num,fmt_ulong(num,hiddenlimit)); substdio_puts(subfderr," descriptors.\n\ This means that the qmail daemons could crash if you set the run-time\n\ concurrency higher than "); substdio_put(subfderr,num,fmt_ulong(num,maxnumd)); substdio_puts(subfderr,". So I'm going to insist that the concurrency\n\ limit in conf-spawn be at most "); substdio_put(subfderr,num,fmt_ulong(num,maxnumd)); substdio_puts(subfderr,". Right now it's "); substdio_put(subfderr,num,fmt_ulong(num,(unsigned long) auto_spawn)); substdio_puts(subfderr,".\n"); substdio_flush(subfderr); _exit(1); } return 0; }
openwengo/qmail-ldap
timeoutwrite.c
<reponame>openwengo/qmail-ldap<filename>timeoutwrite.c #include "timeoutwrite.h" #include "select.h" #include "error.h" #include "readwrite.h" int timeoutwrite(t,fd,buf,len) int t; int fd; const void *buf; int len; { fd_set wfds; struct timeval tv; tv.tv_sec = t; tv.tv_usec = 0; FD_ZERO(&wfds); FD_SET(fd,&wfds); if (select(fd + 1,(fd_set *) 0,&wfds,(fd_set *) 0,&tv) == -1) return -1; if (FD_ISSET(fd,&wfds)) return subwrite(fd,(void *)buf,len); errno = error_timeout; return -1; }
openwengo/qmail-ldap
auto_qmail_inst.h
#ifndef AUTO_QMAIL_INST_H #define AUTO_QMAIL_INST_H extern char auto_qmail_inst[]; #endif
openwengo/qmail-ldap
newfield.h
#ifndef NEWFIELD_H #define NEWFIELD_H #include "datetime.h" #include "stralloc.h" extern stralloc newfield_date; extern int newfield_datemake(datetime_sec); extern stralloc newfield_msgid; extern int newfield_msgidmake(const char *, int, datetime_sec); #endif
openwengo/qmail-ldap
stralloc_copy.c
#include "byte.h" #include "stralloc.h" int stralloc_copy(sato,safrom) stralloc *sato; stralloc *safrom; { return stralloc_copyb(sato,safrom->s,safrom->len); }
openwengo/qmail-ldap
byte.h
<filename>byte.h #ifndef BYTE_H #define BYTE_H extern unsigned int byte_chr(const char *, unsigned int, int); extern unsigned int byte_rchr(const char *, unsigned int, int); extern void byte_copy(void *, unsigned int, const void *); extern void byte_copyr(void *, unsigned int, const void *); extern int byte_diff(const void *, unsigned int, const void *); extern void byte_zero(void *, unsigned int); extern unsigned int byte_repl(char *, unsigned int, int, int); #define byte_equal(s,n,t) (!byte_diff((s),(n),(t))) #endif
openwengo/qmail-ldap
maildirmake.c
<reponame>openwengo/qmail-ldap #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include "strerr.h" #include "exit.h" #define FATAL "maildirmake: fatal: " int main(argc,argv) int argc; char **argv; { umask(077); if (!argv[1]) strerr_die1x(100,"maildirmake: usage: maildirmake name"); if (mkdir(argv[1],0700) == -1) strerr_die4sys(111,FATAL,"unable to mkdir ",argv[1],": "); if (chdir(argv[1]) == -1) strerr_die4sys(111,FATAL,"unable to chdir to ",argv[1],": "); if (mkdir("tmp",0700) == -1) strerr_die4sys(111,FATAL,"unable to mkdir ",argv[1],"/tmp: "); if (mkdir("new",0700) == -1) strerr_die4sys(111,FATAL,"unable to mkdir ",argv[1],"/new: "); if (mkdir("cur",0700) == -1) strerr_die4sys(111,FATAL,"unable to mkdir ",argv[1],"/cur: "); return 0; }
openwengo/qmail-ldap
stralloc_eady.c
<filename>stralloc_eady.c #include "alloc.h" #include "stralloc.h" #include "gen_allocdefs.h" GEN_ALLOC_ready(stralloc,char,s,len,a,i,n,x,30,stralloc_ready) GEN_ALLOC_readyplus(stralloc,char,s,len,a,i,n,x,30,stralloc_readyplus)
openwengo/qmail-ldap
substdio_copy.c
#include "substdio.h" int substdio_copy(ssout,ssin) register substdio *ssout; register substdio *ssin; { register int n; register char *x; for (;;) { n = substdio_feed(ssin); if (n < 0) return -2; if (!n) return 0; x = substdio_PEEK(ssin); if (substdio_put(ssout,x,n) == -1) return -3; substdio_SEEK(ssin,n); } }
openwengo/qmail-ldap
digest_sha1.h
/* digest_sha1.h for QLDAP modified to use djb stuff */ /* */ /* SHA1 */ /* */ /* * SHA-1 in C * By <NAME> <<EMAIL>> * 100% Public Domain */ #ifndef _SHA1_H #define _SHA1_H #include "uint32.h" typedef struct { uint32 state[5]; uint32 count[2]; unsigned char buffer[64]; } SHA1_CTX; #define SHA1_LEN 20 void SHA1Init(SHA1_CTX *); void SHA1Update(SHA1_CTX *, const unsigned char *, size_t); void SHA1Final(unsigned char [SHA1_LEN], SHA1_CTX *); #endif /* _SHA1_H */
openwengo/qmail-ldap
fmtqfn.c
#include "fmtqfn.h" #include "fmt.h" #include "auto_split.h" unsigned int fmtqfn(s,dirslash,id,flagsplit) char *s; const char *dirslash; unsigned long id; int flagsplit; { unsigned int len; unsigned int i; len = 0; i = fmt_str(s,dirslash); len += i; if (s) s += i; if (flagsplit) { i = fmt_ulong(s,id % auto_split); len += i; if (s) s += i; i = fmt_str(s,"/"); len += i; if (s) s += i; } i = fmt_ulong(s,id); len += i; if (s) s += i; if (s) *s++ = 0; ++len; return len; }
openwengo/qmail-ldap
tcp-env.c
<reponame>openwengo/qmail-ldap #include <sys/types.h> #include <sys/socket.h> #include <sys/param.h> #include <netinet/in.h> #include <unistd.h> #include "sig.h" #include "stralloc.h" #include "str.h" #include "env.h" #include "fmt.h" #include "scan.h" #include "subgetopt.h" #include "ip.h" #include "dns.h" #include "byte.h" #include "remoteinfo.h" #include "exit.h" #include "case.h" void die() { _exit(111); } struct sockaddr_in salocal; unsigned long localport; struct ip_address iplocal; stralloc localname = {0}; struct sockaddr_in saremote; unsigned long remoteport; struct ip_address ipremote; stralloc remotename = {0}; char temp[IPFMT + FMT_ULONG]; int main(argc,argv) int argc; char *argv[]; { int dummy; char *proto; int opt; int flagremoteinfo; unsigned long timeout; sig_pipeignore(); flagremoteinfo = 1; timeout = 30; while ((opt = sgopt(argc,argv,"rRt:")) != sgoptdone) switch(opt) { case 'r': flagremoteinfo = 1; break; case 'R': flagremoteinfo = 0; break; case 't': scan_ulong(sgoptarg,&timeout); break; } argv += sgoptind; argc -= sgoptind; if (argc < 1) die(); if (!env_init()) die(); proto = env_get("PROTO"); if (!proto || str_diff(proto,"TCP")) { if (!env_put("PROTO=TCP")) die(); dummy = sizeof(salocal); if (getsockname(0,(struct sockaddr *) &salocal,&dummy) == -1) die(); localport = ntohs(salocal.sin_port); temp[fmt_ulong(temp,localport)] = 0; if (!env_put2("TCPLOCALPORT",temp)) die(); byte_copy(&iplocal,4,&salocal.sin_addr); temp[ip_fmt(temp,&iplocal)] = 0; if (!env_put2("TCPLOCALIP",temp)) die(); switch(dns_ptr(&localname,&iplocal)) { case DNS_MEM: die(); case DNS_SOFT: if (!stralloc_copys(&localname,"softdnserror")) die(); case 0: if (!stralloc_0(&localname)) die(); case_lowers(localname.s); if (!env_put2("TCPLOCALHOST",localname.s)) die(); break; default: if (!env_unset("TCPLOCALHOST")) die(); } dummy = sizeof(saremote); if (getpeername(0,(struct sockaddr *) &saremote,&dummy) == -1) die(); remoteport = ntohs(saremote.sin_port); temp[fmt_ulong(temp,remoteport)] = 0; if (!env_put2("TCPREMOTEPORT",temp)) die(); byte_copy(&ipremote,4,&saremote.sin_addr); temp[ip_fmt(temp,&ipremote)] = 0; if (!env_put2("TCPREMOTEIP",temp)) die(); switch(dns_ptr(&remotename,&ipremote)) { case DNS_MEM: die(); case DNS_SOFT: if (!stralloc_copys(&remotename,"softdnserror")) die(); case 0: if (!stralloc_0(&remotename)) die(); case_lowers(remotename.s); if (!env_put2("TCPREMOTEHOST",remotename.s)) die(); break; default: if (!env_unset("TCPREMOTEHOST")) die(); } if (!env_unset("TCPREMOTEINFO")) die(); if (flagremoteinfo) { char *rinfo; rinfo = remoteinfo_get(&ipremote,remoteport,&iplocal,localport,(int) timeout); if (rinfo) if (!env_put2("TCPREMOTEINFO",rinfo)) die(); } } sig_pipedefault(); execvp(*argv,argv); return 111; }
openwengo/qmail-ldap
remoteinfo.c
<reponame>openwengo/qmail-ldap<filename>remoteinfo.c #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <fcntl.h> #include <unistd.h> #include "byte.h" #include "substdio.h" #include "ip.h" #include "fmt.h" #include "timeoutconn.h" #include "timeoutread.h" #include "timeoutwrite.h" #include "remoteinfo.h" static char line[999]; static int t; static int mywrite(fd,buf,len) int fd; char *buf; int len; { return timeoutwrite(t,fd,buf,len); } static int myread(fd,buf,len) int fd; char *buf; int len; { return timeoutread(t,fd,buf,len); } char *remoteinfo_get(ipr,rp,ipl,lp,timeout) struct ip_address *ipr; unsigned long rp; struct ip_address *ipl; unsigned long lp; int timeout; { char *x; int s; substdio ss; char buf[32]; unsigned int len; int numcolons; char ch; t = timeout; s = socket(AF_INET,SOCK_STREAM,0); if (s == -1) return 0; if (timeoutconn(s,ipr,ipl,113,timeout) == -1) { close(s); return 0; } fcntl(s,F_SETFL,fcntl(s,F_GETFL,0) & ~O_NDELAY); len = 0; len += fmt_ulong(line + len,rp); len += fmt_str(line + len," , "); len += fmt_ulong(line + len,lp); len += fmt_str(line + len,"\r\n"); substdio_fdbuf(&ss,mywrite,s,buf,sizeof buf); if (substdio_putflush(&ss,line,len) == -1) { close(s); return 0; } substdio_fdbuf(&ss,myread,s,buf,sizeof buf); x = line; numcolons = 0; for (;;) { if (substdio_get(&ss,&ch,1) != 1) { close(s); return 0; } if ((ch == ' ') || (ch == '\t') || (ch == '\r')) continue; if (ch == '\n') break; if (numcolons < 3) { if (ch == ':') ++numcolons; } else { *x++ = ch; if (x == line + sizeof(line) - 1) break; } } *x = 0; close(s); return line; }
openwengo/qmail-ldap
qsutil.h
<filename>qsutil.h #ifndef QSUTIL_H #define QSUTIL_H extern void log1(const char *); extern void log2(const char *, const char *); extern void log3(const char *, const char *, const char *); extern void logsa(stralloc *); extern void nomem(void); extern void pausedir(const char *); extern void logsafe(const char *); #endif
openwengo/qmail-ldap
qmail-send.c
<reponame>openwengo/qmail-ldap<filename>qmail-send.c #include <sys/types.h> #include <sys/stat.h> #include <stdlib.h> #include <unistd.h> #include "readwrite.h" #include "sig.h" #include "direntry.h" #include "control.h" #include "select.h" #include "open.h" #include "seek.h" #include "exit.h" #include "lock.h" #include "ndelay.h" #include "now.h" #include "getln.h" #include "substdio.h" #include "alloc.h" #include "error.h" #include "stralloc.h" #include "str.h" #include "byte.h" #include "fmt.h" #include "scan.h" #include "case.h" #include "auto_qmail.h" #include "trigger.h" #include "newfield.h" #include "quote.h" #include "qmail.h" #include "qsutil.h" #include "prioq.h" #include "constmap.h" #include "fmtqfn.h" #include "readsubdir.h" #include "cdb.h" /* critical timing feature #1: if not triggered, do not busy-loop */ /* critical timing feature #2: if triggered, respond within fixed time */ /* important timing feature: when triggered, respond instantly */ #define SLEEP_TODO 1500 /* check todo/ every 25 minutes in any case */ #define SLEEP_FUZZ 1 /* slop a bit on sleeps to avoid zeno effect */ #define SLEEP_FOREVER 86400 /* absolute maximum time spent in select() */ #define SLEEP_CLEANUP 76431 /* time between cleanups */ #define SLEEP_SYSFAIL 123 #define OSSIFIED 129600 /* 36 hours; _must_ exceed q-q's DEATH (24 hours) */ int lifetime = 604800; stralloc percenthack = {0}; struct constmap mappercenthack; stralloc locals = {0}; struct constmap maplocals; stralloc vdoms = {0}; struct constmap mapvdoms; stralloc envnoathost = {0}; stralloc bouncefrom = {0}; stralloc bouncehost = {0}; stralloc doublebounceto = {0}; stralloc doublebouncehost = {0}; stralloc custombouncetext = {0}; char strnum2[FMT_ULONG]; char strnum3[FMT_ULONG]; #define CHANNELS 2 const char *chanaddr[CHANNELS] = { "local/", "remote/" }; const char *chanstatusmsg[CHANNELS] = { " local ", " remote " }; const char *tochan[CHANNELS] = { " to local ", " to remote " }; int chanfdout[CHANNELS] = { 1, 3 }; int chanfdin[CHANNELS] = { 2, 4 }; int chanskip[CHANNELS] = { 10, 20 }; int flagexitasap = 0; void sigterm() { flagexitasap = 1; } int flagrunasap = 0; void sigalrm() { flagrunasap = 1; } int flagreadasap = 0; void sighup() { flagreadasap = 1; } void cleandied() { log1("alert: oh no! lost qmail-clean connection! dying...\n"); flagexitasap = 1; } int flagspawnalive[CHANNELS]; void spawndied(c) int c; { log1("alert: oh no! lost spawn connection! dying...\n"); flagspawnalive[c] = 0; flagexitasap = 1; } #define REPORTMAX 10000 datetime_sec recent; /* this file is too long ----------------------------------------- FILENAMES */ stralloc fn = {0}; stralloc fn2 = {0}; char fnmake_strnum[FMT_ULONG]; void fnmake_init() { while (!stralloc_ready(&fn,FMTQFN)) nomem(); while (!stralloc_ready(&fn2,FMTQFN)) nomem(); } void fnmake_info(id) unsigned long id; { fn.len = fmtqfn(fn.s,"info/",id,1); } #ifndef BIGTODO void fnmake_todo(id) unsigned long id; { fn.len = fmtqfn(fn.s,"todo/",id,0); } #else void fnmake_todo(id) unsigned long id; { fn.len = fmtqfn(fn.s,"todo/",id,1); } #endif void fnmake_mess(id) unsigned long id; { fn.len = fmtqfn(fn.s,"mess/",id,1); } void fnmake_foop(id) unsigned long id; { fn.len = fmtqfn(fn.s,"foop/",id,0); } void fnmake_split(id) unsigned long id; { fn.len = fmtqfn(fn.s,"",id,1); } void fnmake2_bounce(id) unsigned long id; { fn2.len = fmtqfn(fn2.s,"bounce/",id,0); } void fnmake_chanaddr(id,c) unsigned long id; int c; { fn.len = fmtqfn(fn.s,chanaddr[c],id,1); } /* this file is too long ----------------------------------------- REWRITING */ stralloc localscdb = {0}; stralloc rwline = {0}; struct cdb cdb; /* 1 if by land, 2 if by sea, 0 if out of memory. not allowed to barf. */ /* may trash recip. must set up rwline, between a T and a \0. */ int rewrite(recip) char *recip; { unsigned int i; unsigned int j; const char *x; static stralloc addr = {0}; unsigned int at; if (!stralloc_copys(&rwline,"T")) return 0; if (!stralloc_copys(&addr,recip)) return 0; i = byte_rchr(addr.s,addr.len,'@'); if (i == addr.len) { if (!stralloc_cats(&addr,"@")) return 0; if (!stralloc_cat(&addr,&envnoathost)) return 0; } while (constmap(&mappercenthack,addr.s + i + 1,addr.len - i - 1)) { j = byte_rchr(addr.s,i,'%'); if (j == i) break; addr.len = i; i = j; addr.s[i] = '@'; } at = byte_rchr(addr.s,addr.len,'@'); if (localscdb.s && localscdb.len > 1) { static stralloc lowaddr = {0}; int fd, r; uint32 dlen; if (!stralloc_copyb(&lowaddr,addr.s + at + 1,addr.len - at - 1)) return 0; case_lowerb(lowaddr.s, lowaddr.len); fd = open_read(localscdb.s); if (fd == -1) return 0; cdb_init(&cdb, fd); r = cdb_seek(&cdb, lowaddr.s,lowaddr.len, &dlen); cdb_free(&cdb); close(fd); if (r == -1) return 0; if (r == 1) { if (!stralloc_cat(&rwline,&addr)) return 0; if (!stralloc_0(&rwline)) return 0; return 1; } } else if (constmap(&maplocals,addr.s + at + 1,addr.len - at - 1)) { if (!stralloc_cat(&rwline,&addr)) return 0; if (!stralloc_0(&rwline)) return 0; return 1; } for (i = 0;i <= addr.len;++i) if (!i || (i == at + 1) || (i == addr.len) || ((i > at) && (addr.s[i] == '.'))) if ((x = constmap(&mapvdoms,addr.s + i,addr.len - i))) { if (!*x) break; if (!stralloc_cats(&rwline,x)) return 0; if (!stralloc_cats(&rwline,"-")) return 0; if (!stralloc_cat(&rwline,&addr)) return 0; if (!stralloc_0(&rwline)) return 0; return 1; } if (!stralloc_cat(&rwline,&addr)) return 0; if (!stralloc_0(&rwline)) return 0; return 2; } void senderadd(sa,sender,recip) stralloc *sa; char *sender; char *recip; { unsigned int i; unsigned int j; unsigned int k; i = str_len(sender); if (i >= 4) if (str_equal(sender + i - 4,"-@[]")) { j = byte_rchr(sender,i - 4,'@'); k = str_rchr(recip,'@'); if (recip[k] && (j + 5 <= i)) { /* owner-@host-@[] -> owner-recipbox=reciphost@host */ while (!stralloc_catb(sa,sender,j)) nomem(); while (!stralloc_catb(sa,recip,k)) nomem(); while (!stralloc_cats(sa,"=")) nomem(); while (!stralloc_cats(sa,recip + k + 1)) nomem(); while (!stralloc_cats(sa,"@")) nomem(); while (!stralloc_catb(sa,sender + j + 1,i - 5 - j)) nomem(); return; } } while (!stralloc_cats(sa,sender)) nomem(); } /* this file is too long ---------------------------------------------- INFO */ int getinfo(sa,dt,id) stralloc *sa; datetime_sec *dt; unsigned long id; { int fdinfo; struct stat st; static stralloc line = {0}; int match; substdio ss; char buf[128]; fnmake_info(id); fdinfo = open_read(fn.s); if (fdinfo == -1) return 0; if (fstat(fdinfo,&st) == -1) { close(fdinfo); return 0; } substdio_fdbuf(&ss,subread,fdinfo,buf,sizeof(buf)); if (getln(&ss,&line,&match,'\0') == -1) { close(fdinfo); return 0; } close(fdinfo); if (!match) return 0; if (line.s[0] != 'F') return 0; *dt = st.st_mtime; while (!stralloc_copys(sa,line.s + 1)) nomem(); while (!stralloc_0(sa)) nomem(); return 1; } /* this file is too long ------------------------------------- COMMUNICATION */ substdio sstoqc; char sstoqcbuf[1024]; substdio ssfromqc; char ssfromqcbuf[1024]; stralloc comm_buf[CHANNELS] = { {0}, {0} }; int comm_pos[CHANNELS]; int comm_needshup[CHANNELS]; void comm_init() { int c; substdio_fdbuf(&sstoqc,subwrite,5,sstoqcbuf,sizeof(sstoqcbuf)); substdio_fdbuf(&ssfromqc,subread,6,ssfromqcbuf,sizeof(ssfromqcbuf)); for (c = 0;c < CHANNELS;++c) if (ndelay_on(chanfdout[c]) == -1) /* this is so stupid: NDELAY semantics should be default on write */ spawndied(c); /* drastic, but better than risking deadlock */ } int comm_canwrite(c) int c; { /* XXX: could allow a bigger buffer; say 10 recipients */ if (comm_buf[c].s && comm_buf[c].len) return 0; return 1; } void comm_hup(c) int c; { unsigned int delnum = 0xbeef; unsigned char ch; /* * send a empty message with delivery number 0xbeef (48879) to the * spawn process. This may cause trouble if you have a concurrency * bigger than this. Acctually it should be save but who has such * a high concurrency anyway. */ if (comm_buf[c].s && comm_buf[c].len) { comm_needshup[c] = 1; return; } while (!stralloc_copys(&comm_buf[c],"")) nomem(); ch = delnum; while (!stralloc_append(&comm_buf[c],&ch)) nomem(); ch = delnum >> 8; while (!stralloc_append(&comm_buf[c],&ch)) nomem(); while (!stralloc_0(&comm_buf[c])) nomem(); while (!stralloc_0(&comm_buf[c])) nomem(); while (!stralloc_0(&comm_buf[c])) nomem(); comm_pos[c] = 0; comm_needshup[c] = 0; } void comm_write(c,delnum,id,sender,recip) int c; unsigned int delnum; unsigned long id; char *sender; char *recip; { char ch; if (comm_buf[c].s && comm_buf[c].len) return; while (!stralloc_copys(&comm_buf[c],"")) nomem(); ch = delnum; while (!stralloc_append(&comm_buf[c],&ch)) nomem(); ch = delnum >> 8; while (!stralloc_append(&comm_buf[c],&ch)) nomem(); fnmake_split(id); while (!stralloc_cats(&comm_buf[c],fn.s)) nomem(); while (!stralloc_0(&comm_buf[c])) nomem(); senderadd(&comm_buf[c],sender,recip); while (!stralloc_0(&comm_buf[c])) nomem(); while (!stralloc_cats(&comm_buf[c],recip)) nomem(); while (!stralloc_0(&comm_buf[c])) nomem(); comm_pos[c] = 0; } void comm_selprep(nfds,wfds) int *nfds; fd_set *wfds; { int c; for (c = 0;c < CHANNELS;++c) if (flagspawnalive[c]) if (comm_buf[c].s && comm_buf[c].len) { FD_SET(chanfdout[c],wfds); if (*nfds <= chanfdout[c]) *nfds = chanfdout[c] + 1; } } void comm_do(wfds) fd_set *wfds; { int c; for (c = 0;c < CHANNELS;++c) if (flagspawnalive[c]) if (comm_buf[c].s && comm_buf[c].len) if (FD_ISSET(chanfdout[c],wfds)) { int w; int len; len = comm_buf[c].len; w = write(chanfdout[c],comm_buf[c].s + comm_pos[c],len - comm_pos[c]); if (w <= 0) { if ((w == -1) && (errno == error_pipe)) spawndied(c); else continue; /* kernel select() bug; can't avoid busy-looping */ } else { comm_pos[c] += w; if (comm_pos[c] == len) { comm_buf[c].len = 0; if (comm_needshup[c]) comm_hup(c); } } } } /* this file is too long ------------------------------------------ CLEANUPS */ int flagcleanup; /* if 1, cleanupdir is initialized and ready */ readsubdir cleanupdir; datetime_sec cleanuptime; void cleanup_init() { flagcleanup = 0; cleanuptime = now(); } void cleanup_selprep(wakeup) datetime_sec *wakeup; { if (flagcleanup) *wakeup = 0; if (*wakeup > cleanuptime) *wakeup = cleanuptime; } void cleanup_do() { char ch; struct stat st; unsigned long id; if (!flagcleanup) { if (recent < cleanuptime) return; readsubdir_init(&cleanupdir,"mess",pausedir); flagcleanup = 1; } switch(readsubdir_next(&cleanupdir,&id)) { case 1: break; case 0: flagcleanup = 0; cleanuptime = recent + SLEEP_CLEANUP; default: return; } fnmake_mess(id); if (stat(fn.s,&st) == -1) return; /* probably qmail-queue deleted it */ if (recent <= st.st_atime + OSSIFIED) return; fnmake_info(id); if (stat(fn.s,&st) == 0) return; if (errno != error_noent) return; fnmake_todo(id); if (stat(fn.s,&st) == 0) return; if (errno != error_noent) return; fnmake_foop(id); if (substdio_putflush(&sstoqc,fn.s,fn.len) == -1) { cleandied(); return; } if (substdio_get(&ssfromqc,&ch,1) != 1) { cleandied(); return; } if (ch != '+') log3("warning: qmail-clean unable to clean up ",fn.s,"\n"); } /* this file is too long ----------------------------------- PRIORITY QUEUES */ prioq pqdone = {0}; /* -todo +info; HOPEFULLY -local -remote */ prioq pqchan[CHANNELS] = { {0}, {0} }; /* pqchan 0: -todo +info +local ?remote */ /* pqchan 1: -todo +info ?local +remote */ prioq pqfail = {0}; /* stat() failure; has to be pqadded again */ void pqadd(id) unsigned long id; { struct prioq_elt pe; struct prioq_elt pechan[CHANNELS]; int flagchan[CHANNELS]; struct stat st; int c; #define CHECKSTAT if (errno != error_noent) goto fail; fnmake_info(id); if (stat(fn.s,&st) == -1) { CHECKSTAT return; /* someone yanking our chain */ } fnmake_todo(id); if (stat(fn.s,&st) != -1) return; /* look, ma, dad crashed writing info! */ CHECKSTAT for (c = 0;c < CHANNELS;++c) { fnmake_chanaddr(id,c); if (stat(fn.s,&st) == -1) { flagchan[c] = 0; CHECKSTAT } else { flagchan[c] = 1; pechan[c].id = id; pechan[c].dt = st.st_mtime; } } for (c = 0;c < CHANNELS;++c) if (flagchan[c]) while (!prioq_insert(&pqchan[c],&pechan[c])) nomem(); for (c = 0;c < CHANNELS;++c) if (flagchan[c]) break; if (c == CHANNELS) { pe.id = id; pe.dt = now(); while (!prioq_insert(&pqdone,&pe)) nomem(); } return; fail: log3("warning: unable to stat ",fn.s,"; will try again later\n"); pe.id = id; pe.dt = now() + SLEEP_SYSFAIL; while (!prioq_insert(&pqfail,&pe)) nomem(); } void pqstart() { readsubdir rs; int x; unsigned long id; readsubdir_init(&rs,"info",pausedir); while ((x = readsubdir_next(&rs,&id))) if (x > 0) pqadd(id); } void pqfinish() { int c; struct prioq_elt pe; struct timeval tvv[2]; for (c = 0;c < CHANNELS;++c) while (prioq_min(&pqchan[c],&pe)) { prioq_delmin(&pqchan[c]); fnmake_chanaddr(pe.id,c); tvv[0].tv_sec = tvv[1].tv_sec = pe.dt; tvv[0].tv_usec = tvv[1].tv_usec = 0; if (utimes(fn.s,tvv) == -1) log3("warning: unable to utime ",fn.s,"; message will be retried too soon\n"); } } void pqrun() { int c; unsigned int i; for (c = 0;c < CHANNELS;++c) if (pqchan[c].p) if (pqchan[c].len) for (i = 0;i < pqchan[c].len;++i) pqchan[c].p[i].dt = recent; } /* this file is too long ---------------------------------------------- JOBS */ struct job { int refs; /* if 0, this struct is unused */ unsigned long id; int channel; datetime_sec retry; stralloc sender; int numtodo; int flaghiteof; int flagdying; } ; unsigned int numjobs; struct job *jo; void job_init() { unsigned int j; while (!(jo = (struct job *) alloc(numjobs * sizeof(struct job)))) nomem(); for (j = 0;j < numjobs;++j) { jo[j].refs = 0; jo[j].sender.s = 0; } } int job_avail() { unsigned int j; for (j = 0;j < numjobs;++j) if (!jo[j].refs) return 1; return 0; } int job_open(id,channel) unsigned long id; int channel; { unsigned int j; for (j = 0;j < numjobs;++j) if (!jo[j].refs) break; if (j == numjobs) return -1; jo[j].refs = 1; jo[j].id = id; jo[j].channel = channel; jo[j].numtodo = 0; jo[j].flaghiteof = 0; return j; } void job_close(j) int j; { struct prioq_elt pe; struct stat st; if (0 < --jo[j].refs) return; pe.id = jo[j].id; pe.dt = jo[j].retry; if (jo[j].flaghiteof && !jo[j].numtodo) { fnmake_chanaddr(jo[j].id,jo[j].channel); if (unlink(fn.s) == -1) { log3("warning: unable to unlink ",fn.s,"; will try again later\n"); pe.dt = now() + SLEEP_SYSFAIL; } else { int c; for (c = 0;c < CHANNELS;++c) if (c != jo[j].channel) { fnmake_chanaddr(jo[j].id,c); if (stat(fn.s,&st) == 0) return; /* more channels going */ if (errno != error_noent) { log3("warning: unable to stat ",fn.s,"\n"); break; /* this is the only reason for HOPEFULLY */ } } pe.dt = now(); while (!prioq_insert(&pqdone,&pe)) nomem(); return; } } while (!prioq_insert(&pqchan[jo[j].channel],&pe)) nomem(); } /* this file is too long ------------------------------------------- BOUNCES */ char *stripvdomprepend(recip) char *recip; { unsigned int i; char *domain; unsigned int domainlen; const char *prepend; i = str_rchr(recip,'@'); if (!recip[i]) return recip; domain = recip + i + 1; domainlen = str_len(domain); for (i = 0;i <= domainlen;++i) if ((i == 0) || (i == domainlen) || (domain[i] == '.')) if ((prepend = constmap(&mapvdoms,domain + i,domainlen - i))) { if (!*prepend) break; i = str_len(prepend); if (str_diffn(recip,prepend,i)) break; if (recip[i] != '-') break; return recip + i + 1; } return recip; } stralloc bouncetext = {0}; unsigned int bouncemaxbytes = 0; void addbounce(id,recip,report) unsigned long id; char *recip; char *report; { int fd; unsigned int pos; int w; while (!stralloc_copys(&bouncetext,"<")) nomem(); while (!stralloc_cats(&bouncetext,stripvdomprepend(recip))) nomem(); for (pos = 0;pos < bouncetext.len;++pos) if (bouncetext.s[pos] == '\n') bouncetext.s[pos] = '_'; while (!stralloc_cats(&bouncetext,">:\n")) nomem(); while (!stralloc_cats(&bouncetext,report)) nomem(); if (report[0]) if (report[str_len(report) - 1] != '\n') while (!stralloc_cats(&bouncetext,"\n")) nomem(); for (pos = bouncetext.len - 2;pos > 0;--pos) if (bouncetext.s[pos] == '\n') if (bouncetext.s[pos - 1] == '\n') bouncetext.s[pos] = '/'; while (!stralloc_cats(&bouncetext,"\n")) nomem(); fnmake2_bounce(id); for (;;) { fd = open_append(fn2.s); if (fd != -1) break; log1("alert: unable to append to bounce message; HELP! sleeping...\n"); sleep(10); } pos = 0; while (pos < bouncetext.len) { w = write(fd,bouncetext.s + pos,bouncetext.len - pos); if (w <= 0) { log1("alert: unable to append to bounce message; HELP! sleeping...\n"); sleep(10); } else pos += w; } close(fd); } int injectbounce(id) unsigned long id; { struct qmail qqt; struct stat st; const char *bouncesender; char *bouncerecip; int r; int fd; substdio ssread; char buf[128]; char inbuf[128]; static stralloc sender = {0}; static stralloc quoted = {0}; datetime_sec birth; unsigned long qp; if (!getinfo(&sender,&birth,id)) return 0; /* XXX: print warning */ /* owner-@host-@[] -> owner-@host */ if (sender.len >= 5) if (str_equal(sender.s + sender.len - 5,"-@[]")) { sender.len -= 4; sender.s[sender.len - 1] = 0; } fnmake2_bounce(id); fnmake_mess(id); if (stat(fn2.s,&st) == -1) { if (errno == error_noent) return 1; log3("warning: unable to stat ",fn2.s,"\n"); return 0; } if (str_equal(sender.s,"#@[]")) log3("triple bounce: discarding ",fn2.s,"\n"); else { if (qmail_open(&qqt) == -1) { log1("warning: unable to start qmail-queue, will try later\n"); return 0; } qp = qmail_qp(&qqt); if (*sender.s) { bouncesender = ""; bouncerecip = sender.s; } else { bouncesender = "#@[]"; bouncerecip = doublebounceto.s; } while (!newfield_datemake(now())) nomem(); qmail_put(&qqt,newfield_date.s,newfield_date.len); qmail_puts(&qqt,"From: "); while (!quote(&quoted,&bouncefrom)) nomem(); qmail_put(&qqt,quoted.s,quoted.len); qmail_puts(&qqt,"@"); qmail_put(&qqt,bouncehost.s,bouncehost.len); qmail_puts(&qqt,"\nTo: "); while (!quote2(&quoted,bouncerecip)) nomem(); qmail_put(&qqt,quoted.s,quoted.len); qmail_puts(&qqt,"\n\ Subject: failure notice\n\ \n\ Hi. This is the qmail-send program at "); qmail_put(&qqt,bouncehost.s,bouncehost.len); qmail_puts(&qqt,*sender.s ? ".\n\ I'm afraid I wasn't able to deliver your message to the following addresses.\n\ This is a permanent error; I've given up. Sorry it didn't work out.\n\ " : ".\n\ I tried to deliver a bounce message to this address, but the bounce bounced!\n\ "); if (custombouncetext.len > 1) { qmail_puts(&qqt,custombouncetext.s); if (custombouncetext.s[custombouncetext.len-2] != '\n') qmail_puts(&qqt,"\n"); /* I don't think we get here but anyway */ } qmail_puts(&qqt,"\n"); fd = open_read(fn2.s); if (fd == -1) qmail_fail(&qqt); else { substdio_fdbuf(&ssread,subread,fd,inbuf,sizeof(inbuf)); while ((r = substdio_get(&ssread,buf,sizeof(buf))) > 0) qmail_put(&qqt,buf,r); close(fd); if (r == -1) qmail_fail(&qqt); } qmail_puts(&qqt,*sender.s ? "--- Below this line is a copy of the message.\n\n" : "--- Below this line is the original bounce.\n\n"); qmail_puts(&qqt,"Return-Path: <"); while (!quote2(&quoted,sender.s)) nomem(); qmail_put(&qqt,quoted.s,quoted.len); qmail_puts(&qqt,">\n"); fd = open_read(fn.s); if (fd == -1) qmail_fail(&qqt); else { unsigned int bytestogo; unsigned int bytestoget; bytestogo = bouncemaxbytes; bytestoget = (bytestogo < sizeof(buf) && bouncemaxbytes != 0) ? bytestogo : sizeof(buf); substdio_fdbuf(&ssread,subread,fd,inbuf,sizeof(inbuf)); while ((r = substdio_get(&ssread,buf,bytestoget)) > 0) { qmail_put(&qqt,buf,r); bytestogo -= r; if (bouncemaxbytes != 0 && bytestogo <= 0) { qmail_puts(&qqt,"\n\n--- End of message stripped.\n"); break; } bytestoget = (bytestogo < sizeof(buf) && bouncemaxbytes != 0) ? bytestogo : sizeof(buf); } close(fd); if (r == -1) qmail_fail(&qqt); } qmail_from(&qqt,bouncesender); qmail_to(&qqt,bouncerecip); if (*qmail_close(&qqt)) { log1("warning: trouble injecting bounce message, will try later\n"); return 0; } strnum2[fmt_ulong(strnum2,id)] = 0; log2("bounce msg ",strnum2); strnum2[fmt_ulong(strnum2,qp)] = 0; log3(" qp ",strnum2,"\n"); } if (unlink(fn2.s) == -1) { log3("warning: unable to unlink ",fn2.s,"\n"); return 0; } return 1; } /* this file is too long ---------------------------------------- DELIVERIES */ struct del { int used; int j; unsigned long delid; seek_pos mpos; stralloc recip; } ; unsigned long masterdelid = 1; unsigned int concurrency[CHANNELS] = { 10, 20 }; unsigned int concurrencyused[CHANNELS] = { 0, 0 }; struct del *d[CHANNELS]; stralloc dline[CHANNELS]; char delbuf[2048]; void del_status() { int c; log1("status:"); for (c = 0;c < CHANNELS;++c) { strnum2[fmt_ulong(strnum2,(unsigned long) concurrencyused[c])] = 0; strnum3[fmt_ulong(strnum3,(unsigned long) concurrency[c])] = 0; log2(chanstatusmsg[c],strnum2); log2("/",strnum3); } if (flagexitasap) log1(" exitasap"); log1("\n"); } void del_init() { int c; unsigned int i; for (c = 0;c < CHANNELS;++c) { flagspawnalive[c] = 1; while (!(d[c] = (struct del *) alloc(concurrency[c] * sizeof(struct del)))) nomem(); for (i = 0;i < concurrency[c];++i) { d[c][i].used = 0; d[c][i].recip.s = 0; } dline[c].s = 0; while (!stralloc_copys(&dline[c],"")) nomem(); } del_status(); } int del_canexit() { int c; for (c = 0;c < CHANNELS;++c) if (flagspawnalive[c]) /* if dead, nothing we can do about its jobs */ if (concurrencyused[c]) return 0; return 1; } int del_avail(c) int c; { return flagspawnalive[c] && comm_canwrite(c) && (concurrencyused[c] < concurrency[c]); } void del_start(j,mpos,recip) unsigned int j; seek_pos mpos; char *recip; { unsigned int i; int c; c = jo[j].channel; if (!flagspawnalive[c]) return; if (!comm_canwrite(c)) return; for (i = 0;i < concurrency[c];++i) if (!d[c][i].used) break; if (i == concurrency[c]) return; if (!stralloc_copys(&d[c][i].recip,recip)) { nomem(); return; } if (!stralloc_0(&d[c][i].recip)) { nomem(); return; } d[c][i].j = j; ++jo[j].refs; d[c][i].delid = masterdelid++; d[c][i].mpos = mpos; d[c][i].used = 1; ++concurrencyused[c]; comm_write(c,i,jo[j].id,jo[j].sender.s,recip); strnum2[fmt_ulong(strnum2,d[c][i].delid)] = 0; strnum3[fmt_ulong(strnum3,jo[j].id)] = 0; log2("starting delivery ",strnum2); log3(": msg ",strnum3,tochan[c]); logsafe(recip); log1("\n"); del_status(); } void markdone(c,id,pos) int c; unsigned long id; seek_pos pos; { struct stat st; int fd; fnmake_chanaddr(id,c); for (;;) { fd = open_write(fn.s); if (fd == -1) break; if (fstat(fd,&st) == -1) { close(fd); break; } if (seek_set(fd,pos) == -1) { close(fd); break; } if (write(fd,"D",1) != 1) { close(fd); break; } /* further errors -> double delivery without us knowing about it, oh well */ close(fd); return; } log3("warning: trouble marking ",fn.s,"; message will be delivered twice!\n"); } void del_dochan(c) int c; { int r; char ch; int i; unsigned int delnum; r = read(chanfdin[c],delbuf,sizeof(delbuf)); if (r == -1) return; if (r == 0) { spawndied(c); return; } for (i = 0;i < r;++i) { ch = delbuf[i]; while (!stralloc_append(&dline[c],&ch)) nomem(); if (dline[c].len > REPORTMAX) dline[c].len = REPORTMAX; /* qmail-lspawn and qmail-rspawn are responsible for keeping it short */ /* but from a security point of view, we don't trust rspawn */ if (!ch && (dline[c].len > 2)) { delnum = (unsigned int)(unsigned char)dline[c].s[0]; delnum += (unsigned int)(unsigned char)dline[c].s[1] << 8; #if 0 /* A hup is sent as delivery num 0xBEEF = 48879 */ if (delnum == 0xBEEF) { log1("sighup response: "); logsafe(dline[c].s + 3); log1("\n"); } else #endif if ((delnum < 0) || (delnum >= concurrency[c]) || !d[c][delnum].used) log1("warning: internal error: delivery report out of range\n"); else { strnum3[fmt_ulong(strnum3,d[c][delnum].delid)] = 0; if (dline[c].s[2] == 'Z') if (jo[d[c][delnum].j].flagdying) { dline[c].s[2] = 'D'; --dline[c].len; while (!stralloc_cats(&dline[c],"I'm not going to try again; this message has been in the queue too long.\n")) nomem(); while (!stralloc_0(&dline[c])) nomem(); } switch(dline[c].s[2]) { case 'K': log3("delivery ",strnum3,": success: "); logsafe(dline[c].s + 3); log1("\n"); markdone(c,jo[d[c][delnum].j].id,d[c][delnum].mpos); --jo[d[c][delnum].j].numtodo; break; case 'Z': log3("delivery ",strnum3,": deferral: "); logsafe(dline[c].s + 3); log1("\n"); break; case 'D': log3("delivery ",strnum3,": failure: "); logsafe(dline[c].s + 3); log1("\n"); addbounce(jo[d[c][delnum].j].id,d[c][delnum].recip.s,dline[c].s + 3); markdone(c,jo[d[c][delnum].j].id,d[c][delnum].mpos); --jo[d[c][delnum].j].numtodo; break; case 'L': log3("delivery ",strnum3,": log: "); logsafe(dline[c].s + 3); log1("\n"); dline[c].len = 0; break; default: log3("delivery ",strnum3,": report mangled, will defer\n"); } if (dline[c].s[2] != 'L') { job_close(d[c][delnum].j); d[c][delnum].used = 0; --concurrencyused[c]; del_status(); } } dline[c].len = 0; } } } void del_selprep(nfds,rfds) int *nfds; fd_set *rfds; { int c; for (c = 0;c < CHANNELS;++c) if (flagspawnalive[c]) { FD_SET(chanfdin[c],rfds); if (*nfds <= chanfdin[c]) *nfds = chanfdin[c] + 1; } } void del_do(rfds) fd_set *rfds; { int c; for (c = 0;c < CHANNELS;++c) if (flagspawnalive[c]) if (FD_ISSET(chanfdin[c],rfds)) del_dochan(c); } /* this file is too long -------------------------------------------- PASSES */ struct { unsigned long id; /* if 0, need a new pass */ int j; /* defined if id; job number */ int fd; /* defined if id; reading from {local,remote} */ seek_pos mpos; /* defined if id; mark position */ substdio ss; char buf[128]; } pass[CHANNELS]; void pass_init() { int c; for (c = 0;c < CHANNELS;++c) pass[c].id = 0; } void pass_selprep(wakeup) datetime_sec *wakeup; { int c; struct prioq_elt pe; if (flagexitasap) return; for (c = 0;c < CHANNELS;++c) if (pass[c].id) if (del_avail(c)) { *wakeup = 0; return; } if (job_avail()) for (c = 0;c < CHANNELS;++c) if (!pass[c].id) if (prioq_min(&pqchan[c],&pe)) if (*wakeup > pe.dt) *wakeup = pe.dt; if (prioq_min(&pqfail,&pe)) if (*wakeup > pe.dt) *wakeup = pe.dt; if (prioq_min(&pqdone,&pe)) if (*wakeup > pe.dt) *wakeup = pe.dt; } static datetime_sec squareroot(x) /* result^2 <= x < (result + 1)^2 */ datetime_sec x; /* assuming: >= 0 */ { datetime_sec y; datetime_sec yy; datetime_sec y21; int j; y = 0; yy = 0; for (j = 15;j >= 0;--j) { y21 = (y << (j + 1)) + (1 << (j + j)); if (y21 <= x - yy) { y += (1 << j); yy += y21; } } return y; } datetime_sec nextretry(birth,c) datetime_sec birth; int c; { unsigned int n; if (birth > recent) n = 0; else { #ifdef notyet /* * add some fuzz to recent so that storms to a single host are * dampened over the time. */ recent += (int)random() % (((recent - birth) >> 2) + 1); #endif n = squareroot(recent - birth); } n += chanskip[c]; return birth + n * n; } void pass_dochan(c) int c; { datetime_sec birth; struct prioq_elt pe; static stralloc line = {0}; int match; if (flagexitasap) return; if (!pass[c].id) { if (!job_avail()) return; if (!prioq_min(&pqchan[c],&pe)) return; if (pe.dt > recent) return; fnmake_chanaddr(pe.id,c); prioq_delmin(&pqchan[c]); pass[c].mpos = 0; pass[c].fd = open_read(fn.s); if (pass[c].fd == -1) goto trouble; if (!getinfo(&line,&birth,pe.id)) { close(pass[c].fd); goto trouble; } pass[c].id = pe.id; substdio_fdbuf(&pass[c].ss,subread,pass[c].fd,pass[c].buf,sizeof(pass[c].buf)); pass[c].j = job_open(pe.id,c); jo[pass[c].j].retry = nextretry(birth,c); /* XXX add fast timeouts for bounce double bounce here */ jo[pass[c].j].flagdying = (recent > birth + lifetime); while (!stralloc_copy(&jo[pass[c].j].sender,&line)) nomem(); } if (!del_avail(c)) return; if (getln(&pass[c].ss,&line,&match,'\0') == -1) { fnmake_chanaddr(pass[c].id,c); log3("warning: trouble reading ",fn.s,"; will try again later\n"); close(pass[c].fd); job_close(pass[c].j); pass[c].id = 0; return; } if (!match) { close(pass[c].fd); jo[pass[c].j].flaghiteof = 1; job_close(pass[c].j); pass[c].id = 0; return; } switch(line.s[0]) { case 'T': ++jo[pass[c].j].numtodo; del_start(pass[c].j,pass[c].mpos,line.s + 1); break; case 'D': break; default: fnmake_chanaddr(pass[c].id,c); log3("warning: unknown record type in ",fn.s,"!\n"); close(pass[c].fd); job_close(pass[c].j); pass[c].id = 0; return; } pass[c].mpos += line.len; return; trouble: log3("warning: trouble opening ",fn.s,"; will try again later\n"); pe.dt = recent + SLEEP_SYSFAIL; while (!prioq_insert(&pqchan[c],&pe)) nomem(); } void messdone(id) unsigned long id; { char ch; int c; struct prioq_elt pe; struct stat st; for (c = 0;c < CHANNELS;++c) { fnmake_chanaddr(id,c); if (stat(fn.s,&st) == 0) return; /* false alarm; consequence of HOPEFULLY */ if (errno != error_noent) { log3("warning: unable to stat ",fn.s,"; will try again later\n"); goto fail; } } fnmake_todo(id); if (stat(fn.s,&st) == 0) return; if (errno != error_noent) { log3("warning: unable to stat ",fn.s,"; will try again later\n"); goto fail; } fnmake_info(id); if (stat(fn.s,&st) == -1) { if (errno == error_noent) return; log3("warning: unable to stat ",fn.s,"; will try again later\n"); goto fail; } /* -todo +info -local -remote ?bounce */ if (!injectbounce(id)) goto fail; /* injectbounce() produced error message */ strnum3[fmt_ulong(strnum3,id)] = 0; log3("end msg ",strnum3,"\n"); /* -todo +info -local -remote -bounce */ fnmake_info(id); if (unlink(fn.s) == -1) { log3("warning: unable to unlink ",fn.s,"; will try again later\n"); goto fail; } /* -todo -info -local -remote -bounce; we can relax */ fnmake_foop(id); if (substdio_putflush(&sstoqc,fn.s,fn.len) == -1) { cleandied(); return; } if (substdio_get(&ssfromqc,&ch,1) != 1) { cleandied(); return; } if (ch != '+') log3("warning: qmail-clean unable to clean up ",fn.s,"\n"); return; fail: pe.id = id; pe.dt = now() + SLEEP_SYSFAIL; while (!prioq_insert(&pqdone,&pe)) nomem(); } void pass_do() { int c; struct prioq_elt pe; for (c = 0;c < CHANNELS;++c) pass_dochan(c); if (prioq_min(&pqfail,&pe)) if (pe.dt <= recent) { prioq_delmin(&pqfail); pqadd(pe.id); } if (prioq_min(&pqdone,&pe)) if (pe.dt <= recent) { prioq_delmin(&pqdone); messdone(pe.id); } } /* this file is too long ---------------------------------------------- TODO */ #ifndef EXTERNAL_TODO datetime_sec nexttodorun; #ifndef BIGTODO DIR *tododir; /* if 0, have to opendir again */ #else int flagtododir = 0; /* if 0, have to readsubdir_init again */ readsubdir todosubdir; #endif stralloc todoline = {0}; char todobuf[SUBSTDIO_INSIZE]; char todobufinfo[512]; char todobufchan[CHANNELS][1024]; void todo_init() { #ifndef BIGTODO tododir = 0; #else flagtododir = 0; #endif nexttodorun = now(); trigger_set(); } void todo_selprep(nfds,rfds,wakeup) int *nfds; fd_set *rfds; datetime_sec *wakeup; { if (flagexitasap) return; trigger_selprep(nfds,rfds); #ifndef BIGTODO if (tododir) *wakeup = 0; #else if (flagtododir) *wakeup = 0; #endif if (*wakeup > nexttodorun) *wakeup = nexttodorun; } void todo_do(rfds) fd_set *rfds; { struct stat st; substdio ss; int fd; substdio ssinfo; int fdinfo; substdio sschan[CHANNELS]; int fdchan[CHANNELS]; int flagchan[CHANNELS]; struct prioq_elt pe; char ch; int match; unsigned long id; #ifndef BIGTODO unsigned int len; direntry *d; #endif int c; unsigned long uid; unsigned long pid; fd = -1; fdinfo = -1; for (c = 0;c < CHANNELS;++c) fdchan[c] = -1; if (flagexitasap) return; #ifndef BIGTODO if (!tododir) #else if (!flagtododir) #endif { if (!trigger_pulled(rfds)) if (recent < nexttodorun) return; trigger_set(); #ifndef BIGTODO tododir = opendir("todo"); if (!tododir) { pausedir("todo"); return; } #else readsubdir_init(&todosubdir, "todo", pausedir); flagtododir = 1; #endif nexttodorun = recent + SLEEP_TODO; } #ifndef BIGTODO d = readdir(tododir); if (!d) { closedir(tododir); tododir = 0; return; } if (str_equal(d->d_name,".")) return; if (str_equal(d->d_name,"..")) return; len = scan_ulong(d->d_name,&id); if (!len || d->d_name[len]) return; #else switch(readsubdir_next(&todosubdir, &id)) { case 1: break; case 0: flagtododir = 0; default: return; } #endif fnmake_todo(id); fd = open_read(fn.s); if (fd == -1) { log3("warning: unable to open ",fn.s,"\n"); return; } fnmake_mess(id); /* just for the statistics */ if (stat(fn.s,&st) == -1) { log3("warning: unable to stat ",fn.s,"\n"); goto fail; } for (c = 0;c < CHANNELS;++c) { fnmake_chanaddr(id,c); if (unlink(fn.s) == -1) if (errno != error_noent) { log3("warning: unable to unlink ",fn.s,"\n"); goto fail; } } fnmake_info(id); if (unlink(fn.s) == -1) if (errno != error_noent) { log3("warning: unable to unlink ",fn.s,"\n"); goto fail; } fdinfo = open_excl(fn.s); if (fdinfo == -1) { log3("warning: unable to create ",fn.s,"\n"); goto fail; } strnum3[fmt_ulong(strnum3,id)] = 0; log3("new msg ",strnum3,"\n"); for (c = 0;c < CHANNELS;++c) flagchan[c] = 0; substdio_fdbuf(&ss,subread,fd,todobuf,sizeof(todobuf)); substdio_fdbuf(&ssinfo,subwrite,fdinfo,todobufinfo,sizeof(todobufinfo)); uid = 0; pid = 0; for (;;) { if (getln(&ss,&todoline,&match,'\0') == -1) { /* perhaps we're out of memory, perhaps an I/O error */ fnmake_todo(id); log3("warning: trouble reading ",fn.s,"\n"); goto fail; } if (!match) break; switch(todoline.s[0]) { case 'u': scan_ulong(todoline.s + 1,&uid); break; case 'p': scan_ulong(todoline.s + 1,&pid); break; case 'F': if (substdio_putflush(&ssinfo,todoline.s,todoline.len) == -1) { fnmake_info(id); log3("warning: trouble writing to ",fn.s,"\n"); goto fail; } log2("info msg ",strnum3); strnum2[fmt_ulong(strnum2,(unsigned long) st.st_size)] = 0; log2(": bytes ",strnum2); log1(" from <"); logsafe(todoline.s + 1); strnum2[fmt_ulong(strnum2,pid)] = 0; log2("> qp ",strnum2); strnum2[fmt_ulong(strnum2,uid)] = 0; log2(" uid ",strnum2); log1("\n"); break; case 'T': switch(rewrite(todoline.s + 1)) { case 0: nomem(); goto fail; case 2: c = 1; break; default: c = 0; break; } if (fdchan[c] == -1) { fnmake_chanaddr(id,c); fdchan[c] = open_excl(fn.s); if (fdchan[c] == -1) { log3("warning: unable to create ",fn.s,"\n"); goto fail; } substdio_fdbuf(&sschan[c] ,subwrite,fdchan[c],todobufchan[c],sizeof(todobufchan[c])); flagchan[c] = 1; } if (substdio_bput(&sschan[c],rwline.s,rwline.len) == -1) { fnmake_chanaddr(id,c); log3("warning: trouble writing to ",fn.s,"\n"); goto fail; } break; default: fnmake_todo(id); log3("warning: unknown record type in ",fn.s,"\n"); goto fail; } } close(fd); fd = -1; fnmake_info(id); if (substdio_flush(&ssinfo) == -1) { log3("warning: trouble writing to ",fn.s,"\n"); goto fail; } if (fsync(fdinfo) == -1) { log3("warning: trouble fsyncing ",fn.s,"\n"); goto fail; } close(fdinfo); fdinfo = -1; for (c = 0;c < CHANNELS;++c) if (fdchan[c] != -1) { fnmake_chanaddr(id,c); if (substdio_flush(&sschan[c]) == -1) { log3("warning: trouble writing to ",fn.s,"\n"); goto fail; } if (fsync(fdchan[c]) == -1) { log3("warning: trouble fsyncing ",fn.s,"\n"); goto fail; } close(fdchan[c]); fdchan[c] = -1; } fnmake_todo(id); if (substdio_putflush(&sstoqc,fn.s,fn.len) == -1) { cleandied(); return; } if (substdio_get(&ssfromqc,&ch,1) != 1) { cleandied(); return; } if (ch != '+') { log3("warning: qmail-clean unable to clean up ",fn.s,"\n"); return; } pe.id = id; pe.dt = now(); for (c = 0;c < CHANNELS;++c) if (flagchan[c]) while (!prioq_insert(&pqchan[c],&pe)) nomem(); for (c = 0;c < CHANNELS;++c) if (flagchan[c]) break; if (c == CHANNELS) while (!prioq_insert(&pqdone,&pe)) nomem(); return; fail: if (fd != -1) close(fd); if (fdinfo != -1) close(fdinfo); for (c = 0;c < CHANNELS;++c) if (fdchan[c] != -1) close(fdchan[c]); } #endif /* this file is too long ------------------------------------- EXTERNAL TODO */ #ifdef EXTERNAL_TODO stralloc todoline = {0}; char todobuf[2048]; int todofdin; int todofdout; int flagtodoalive; void tododied() { log1("alert: oh no! lost qmail-todo connection! dying...\n"); flagexitasap = 1; flagtodoalive = 0; } void todo_init() { todofdout = 7; todofdin = 8; flagtodoalive = 1; /* sync with external todo */ if (write(todofdout, "S", 1) != 1) tododied(); return; } void todo_selprep(nfds,rfds,wakeup) int *nfds; fd_set *rfds; datetime_sec *wakeup; { if (flagexitasap) { if (flagtodoalive) { write(todofdout, "X", 1); } } if (flagtodoalive) { FD_SET(todofdin,rfds); if (*nfds <= todofdin) *nfds = todofdin + 1; } } void todo_del(char* s) { int flagchan[CHANNELS]; struct prioq_elt pe; unsigned long id; unsigned int len; int c; for (c = 0;c < CHANNELS;++c) flagchan[c] = 0; switch(*s++) { case 'L': flagchan[0] = 1; break; case 'R': flagchan[1] = 1; break; case 'B': flagchan[0] = 1; flagchan[1] = 1; break; case 'X': /* * this is not an error but it is neither correct, * sending messages with no recipients is plain stupid. */ log1("warning: qmail-todo neither by land nor by sea...\n"); break; default: log1("warning: qmail-todo has a unknown feature or dialect.\n"); return; } len = scan_ulong(s,&id); if (!len || s[len]) { log1("warning: qmail-todo please don't muble.\n"); return; } pe.id = id; pe.dt = now(); for (c = 0;c < CHANNELS;++c) if (flagchan[c]) while (!prioq_insert(&pqchan[c],&pe)) nomem(); for (c = 0;c < CHANNELS;++c) if (flagchan[c]) break; if (c == CHANNELS) while (!prioq_insert(&pqdone,&pe)) nomem(); return; } void todo_do(rfds) fd_set *rfds; { int r; char ch; int i; if (!flagtodoalive) return; if (!FD_ISSET(todofdin,rfds)) return; r = read(todofdin,todobuf,sizeof(todobuf)); if (r == -1) return; if (r == 0) { if (flagexitasap) flagtodoalive = 0; else tododied(); return; } for (i = 0;i < r;++i) { ch = todobuf[i]; while (!stralloc_append(&todoline,&ch)) nomem(); if (todoline.len > REPORTMAX) todoline.len = REPORTMAX; /* qmail-todo is responsible for keeping it short */ if (!ch && (todoline.len > 1)) { switch (todoline.s[0]) { case 'D': if (flagexitasap) break; todo_del(todoline.s + 1); break; case 'L': log1(todoline.s + 1); break; case 'X': if (flagexitasap) flagtodoalive = 0; else tododied(); break; default: log1("warning: qmail-send unable to understand qmail-todo: report mangled\n"); break; } todoline.len = 0; } } } #endif /* this file is too long ---------------------------------------------- MAIN */ int getcontrols() { struct stat st; if (control_init() == -1) return 0; if (control_readint(&lifetime,"control/queuelifetime") == -1) return 0; if (control_readint(&concurrency[0],"control/concurrencylocal") == -1) return 0; if (control_readint(&concurrency[1],"control/concurrencyremote") == -1) return 0; if (control_rldef(&envnoathost,"control/envnoathost",1,"envnoathost") != 1) return 0; if (control_rldef(&bouncefrom,"control/bouncefrom",0,"MAILER-DAEMON") != 1) return 0; if (control_rldef(&bouncehost,"control/bouncehost",1,"bouncehost") != 1) return 0; if (control_rldef(&doublebouncehost,"control/doublebouncehost",1,"doublebouncehost") != 1) return 0; if (control_rldef(&doublebounceto,"control/doublebounceto",0,"postmaster") != 1) return 0; if (!stralloc_cats(&doublebounceto,"@")) return 0; if (!stralloc_cat(&doublebounceto,&doublebouncehost)) return 0; if (!stralloc_0(&doublebounceto)) return 0; if (control_readint(&bouncemaxbytes,"control/bouncemaxbytes") == -1) return 0; if (control_readrawfile(&custombouncetext,"control/custombouncetext") == -1) return 0; if (!stralloc_0(&custombouncetext) ) return 0; if (stat("control/locals.cdb", &st) == 0) { if (!stralloc_copys(&localscdb, auto_qmail)) return 0; if (!stralloc_cats(&localscdb, "/control/locals.cdb")) return 0; if (!stralloc_0(&localscdb)) return 0; if (!constmap_init(&maplocals,"",0,1)) return 0; } else { if (control_readfile(&locals,"control/locals",1) != 1) return 0; if (!constmap_init(&maplocals,locals.s,locals.len,0)) return 0; } switch(control_readfile(&percenthack,"control/percenthack",0)) { case -1: return 0; case 0: if (!constmap_init(&mappercenthack,"",0,0)) return 0; break; case 1: if (!constmap_init(&mappercenthack,percenthack.s,percenthack.len,0)) return 0; break; } switch(control_readfile(&vdoms,"control/virtualdomains",0)) { case -1: return 0; case 0: if (!constmap_init(&mapvdoms,"",0,1)) return 0; break; case 1: if (!constmap_init(&mapvdoms,vdoms.s,vdoms.len,1)) return 0; break; } return 1; } stralloc newlocals = {0}; stralloc newvdoms = {0}; stralloc newcbtext = {0}; void regetcontrols() { struct stat st; int r; if (control_readint(&bouncemaxbytes,"control/bouncemaxbytes") == -1) { log1("alert: unable to reread control/bouncemaxbytes\n"); return; } if (control_readrawfile(&newcbtext,"control/custombouncetext") == -1) { log1("alert: unable to reread control/custombouncetext\n"); return; } while (!stralloc_0(&newcbtext)) nomem(); while (!stralloc_copy(&custombouncetext,&newcbtext)) nomem(); if (stat("control/locals.cdb", &st) == 0) { while (!stralloc_copys(&localscdb, auto_qmail)) nomem(); while (!stralloc_cats(&localscdb, "/control/locals.cdb")) nomem(); while (!stralloc_0(&localscdb)) nomem(); constmap_free(&maplocals); while (!constmap_init(&maplocals,"",0,1)) nomem(); } else { if (control_readfile(&newlocals,"control/locals",1) != 1) { log1("alert: unable to reread control/locals\n"); return; } while (!stralloc_copys(&localscdb, "")) nomem(); constmap_free(&maplocals); while (!stralloc_copy(&locals,&newlocals)) nomem(); while (!constmap_init(&maplocals,locals.s,locals.len,0)) nomem(); } r = control_readfile(&newvdoms,"control/virtualdomains",0); if (r == -1) { log1("alert: unable to reread control/virtualdomains\n"); return; } constmap_free(&mapvdoms); if (r) { while (!stralloc_copy(&vdoms,&newvdoms)) nomem(); while (!constmap_init(&mapvdoms,vdoms.s,vdoms.len,1)) nomem(); } else while (!constmap_init(&mapvdoms,"",0,1)) nomem(); } void reread() { if (chdir(auto_qmail) == -1) { log1("alert: unable to reread controls: unable to switch to home directory\n"); return; } #ifdef EXTERNAL_TODO write(todofdout, "H", 1); #endif comm_hup(0); /* send hup to qmail-lspawn */ regetcontrols(); while (chdir("queue") == -1) { log1("alert: unable to switch back to queue directory; HELP! sleeping...\n"); sleep(10); } #ifdef notyet srandom(now()); #endif } int main() { int fd; datetime_sec wakeup; fd_set rfds; fd_set wfds; int nfds; struct timeval tv; int c; if (chdir(auto_qmail) == -1) { log1("alert: cannot start: unable to switch to home directory\n"); _exit(111); } if (!getcontrols()) { log1("alert: cannot start: unable to read controls\n"); _exit(111); } if (chdir("queue") == -1) { log1("alert: cannot start: unable to switch to queue directory\n"); _exit(111); } #ifdef notyet srandom(now() + (getpid() << 16)); #endif sig_pipeignore(); sig_termcatch(sigterm); sig_alarmcatch(sigalrm); sig_hangupcatch(sighup); sig_childdefault(); umask(077); fd = open_write("lock/sendmutex"); if (fd == -1) { log1("alert: cannot start: unable to open mutex\n"); _exit(111); } if (lock_exnb(fd) == -1) { log1("alert: cannot start: qmail-send is already running\n"); _exit(111); } numjobs = 0; for (c = 0;c < CHANNELS;++c) { char ch, ch1; unsigned int u; int r; do r = read(chanfdin[c],&ch,1); while ((r == -1) && (errno == error_intr)); if (r < 1) { log1("alert: cannot start qmail-lspawn or it had an error! " "Check if ~control/ldapserver exists.\n"); _exit(111); } do r = read(chanfdin[c],&ch1,1); while ((r == -1) && (errno == error_intr)); if (r < 1) { log1("alert: cannot start: hath the daemon spawn no fire?\n"); _exit(111); } u = (unsigned int) (unsigned char) ch; u += (unsigned int) ((unsigned char) ch1) << 8; if (concurrency[c] > u) concurrency[c] = u; numjobs += concurrency[c]; } fnmake_init(); comm_init(); pqstart(); job_init(); del_init(); pass_init(); todo_init(); cleanup_init(); #ifdef EXTERNAL_TODO while (!flagexitasap || !del_canexit() || flagtodoalive) #else while (!flagexitasap || !del_canexit()) #endif { recent = now(); if (flagrunasap) { flagrunasap = 0; pqrun(); } if (flagreadasap) { flagreadasap = 0; reread(); } wakeup = recent + SLEEP_FOREVER; FD_ZERO(&rfds); FD_ZERO(&wfds); nfds = 1; comm_selprep(&nfds,&wfds); del_selprep(&nfds,&rfds); pass_selprep(&wakeup); todo_selprep(&nfds,&rfds,&wakeup); cleanup_selprep(&wakeup); if (wakeup <= recent) tv.tv_sec = 0; else tv.tv_sec = wakeup - recent + SLEEP_FUZZ; tv.tv_usec = 0; if (select(nfds,&rfds,&wfds,(fd_set *) 0,&tv) == -1) if (errno == error_intr) ; else log1("warning: trouble in select\n"); else { recent = now(); comm_do(&wfds); del_do(&rfds); todo_do(&rfds); pass_do(); cleanup_do(); } } pqfinish(); log1("status: exiting\n"); return 0; }
openwengo/qmail-ldap
env.c
/* env.c, envread.c, env.h: environ library <NAME>, <EMAIL>. Depends on str.h, alloc.h. Requires environ. 19960113: rewrite. warning: interface is different. No known patent problems. */ #include "str.h" #include "alloc.h" #include "env.h" int env_isinit = 0; /* if env_isinit: */ static unsigned int ea; /* environ is a pointer to ea+1 char*'s. */ static unsigned int en; /* the first en of those are ALLOCATED. environ[en] is 0. */ static void env_goodbye(i) int i; { alloc_free(environ[i]); environ[i] = environ[--en]; environ[en] = 0; } static char *null = 0; void env_clear(void) { if (env_isinit) while (en) env_goodbye(0); else environ = &null; } static void env_unsetlen(s,len) const char *s; unsigned int len; { unsigned int i; i = en; do { --i; if (!str_diffn(s,environ[i],len)) if (environ[i][len] == '=') env_goodbye(i); } while (i > 0); } int env_unset(s) const char *s; { if (!env_isinit) if (!env_init()) return 0; env_unsetlen(s,str_len(s)); return 1; } static int env_add(s) char *s; { const char *t; t = env_findeq(s); if (t) env_unsetlen(s,t - s); if (en == ea) { ea += 30; if (!alloc_re((char **)&environ,(en + 1) * sizeof(char *),(ea + 1) * sizeof(char *))) { ea = en; return 0; } } environ[en++] = s; environ[en] = 0; return 1; } int env_put(s) const char *s; { char *u; if (!env_isinit) if (!env_init()) return 0; u = alloc(str_len(s) + 1); if (!u) return 0; str_copy(u,s); if (!env_add(u)) { alloc_free(u); return 0; } return 1; } int env_put2(s,t) const char *s; const char *t; { char *u; unsigned int slen; if (!env_isinit) if (!env_init()) return 0; slen = str_len(s); u = alloc(slen + str_len(t) + 2); if (!u) return 0; str_copy(u,s); u[slen] = '='; str_copy(u + slen + 1,t); if (!env_add(u)) { alloc_free(u); return 0; } return 1; } int env_init(void) { char **newenviron; unsigned int i; for (en = 0;environ[en];++en) ; ea = en + 10; newenviron = (char **) alloc((ea + 1) * sizeof(char *)); if (!newenviron) return 0; for (en = 0;environ[en];++en) { newenviron[en] = alloc(str_len(environ[en]) + 1); if (!newenviron[en]) { for (i = 0;i < en;++i) alloc_free(newenviron[i]); alloc_free(newenviron); return 0; } str_copy(newenviron[en],environ[en]); } newenviron[en] = 0; environ = newenviron; env_isinit = 1; return 1; }
openwengo/qmail-ldap
trigger.h
#ifndef TRIGGER_H #define TRIGGER_H #include "select.h" extern void trigger_set(void); extern void trigger_selprep(int *, fd_set *); extern int trigger_pulled(fd_set *); #endif
openwengo/qmail-ldap
qmail-qmqpc.c
#include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #include "substdio.h" #include "getln.h" #include "readwrite.h" #include "exit.h" #include "stralloc.h" #include "slurpclose.h" #include "error.h" #include "sig.h" #include "ip.h" #include "timeoutconn.h" #include "timeoutread.h" #include "timeoutwrite.h" #include "auto_qmail.h" #include "control.h" #include "fmt.h" #ifdef QMQP_COMPRESS #include <zlib.h> #endif #ifndef PORT_QMQP /* this is for testing purposes */ #define PORT_QMQP 628 #endif void die_success(void) { _exit(0); } void die_perm(void) { _exit(31); } void nomem(void) { _exit(51); } void die_read(void) { if (errno == error_nomem) nomem(); _exit(54); } void die_control(void) { _exit(55); } void die_socket(void) { _exit(56); } void die_home(void) { _exit(61); } void die_temp(void) { _exit(71); } void die_conn(void) { _exit(74); } void die_format(void) { _exit(91); } int timeoutconnect = 60; int lasterror = 55; int qmqpfd; #ifdef QMQP_COMPRESS z_stream stream; char zbuf[4096]; void compression_init(void) { stream.zalloc = Z_NULL; stream.zfree = Z_NULL; stream.opaque = Z_NULL; stream.avail_out = sizeof(zbuf); stream.next_out = zbuf; if (deflateInit(&stream,Z_DEFAULT_COMPRESSION) != Z_OK) die_format(); } void compression_done(void) { int r; do { r = deflate(&stream,Z_FINISH); switch (r) { case Z_OK: if (stream.avail_out == 0) { r = timeoutwrite(60,qmqpfd,zbuf,sizeof(zbuf)); if (r <= 0) die_conn(); stream.avail_out = sizeof(zbuf); stream.next_out = zbuf; r = Z_OK; } break; case Z_STREAM_END: break; default: die_format(); } } while (r!=Z_STREAM_END); if (stream.avail_out != sizeof(zbuf)) { /* write left data */ r = timeoutwrite(60,qmqpfd,zbuf,sizeof(zbuf)-stream.avail_out); if (r <= 0) die_conn(); } if (deflateEnd(&stream) != Z_OK) die_format(); } #endif int saferead(int fd, void *buf, int len) { int r; r = timeoutread(60,qmqpfd,buf,len); if (r <= 0) die_conn(); return r; } int safewrite(int fd, void *buf, int len) { int r; #ifdef QMQP_COMPRESS stream.avail_in = len; stream.next_in = buf; do { r = deflate(&stream, 0); switch (r) { case Z_OK: if (stream.avail_out == 0) { r = timeoutwrite(60,qmqpfd,zbuf,sizeof(zbuf)); if (r <= 0) die_conn(); stream.avail_out = sizeof(zbuf); stream.next_out = zbuf; } break; default: die_format(); } } while (stream.avail_in != 0); return len; #endif r = timeoutwrite(60,qmqpfd,buf,len); if (r <= 0) die_conn(); return r; } char buf[1024]; substdio to = SUBSTDIO_FDBUF(safewrite,-1,buf,sizeof buf); substdio from = SUBSTDIO_FDBUF(saferead,-1,buf,sizeof buf); substdio envelope = SUBSTDIO_FDBUF(subread,1,buf,sizeof buf); /* WARNING: can use only one of these at a time! */ stralloc beforemessage = {0}; stralloc message = {0}; stralloc aftermessage = {0}; char strnum[FMT_ULONG]; stralloc line = {0}; void getmess() { int match; if (slurpclose(0,&message,1024) == -1) die_read(); strnum[fmt_uint(strnum,message.len)] = 0; if (!stralloc_copys(&beforemessage,strnum)) nomem(); if (!stralloc_cats(&beforemessage,":")) nomem(); if (!stralloc_copys(&aftermessage,",")) nomem(); if (getln(&envelope,&line,&match,'\0') == -1) die_read(); if (!match) die_format(); if (line.len < 2) die_format(); if (line.s[0] != 'F') die_format(); strnum[fmt_uint(strnum,line.len - 2)] = 0; if (!stralloc_cats(&aftermessage,strnum)) nomem(); if (!stralloc_cats(&aftermessage,":")) nomem(); if (!stralloc_catb(&aftermessage,line.s + 1,line.len - 2)) nomem(); if (!stralloc_cats(&aftermessage,",")) nomem(); for (;;) { if (getln(&envelope,&line,&match,'\0') == -1) die_read(); if (!match) die_format(); if (line.len < 2) break; if (line.s[0] != 'T') die_format(); strnum[fmt_uint(strnum,line.len - 2)] = 0; if (!stralloc_cats(&aftermessage,strnum)) nomem(); if (!stralloc_cats(&aftermessage,":")) nomem(); if (!stralloc_catb(&aftermessage,line.s + 1,line.len - 2)) nomem(); if (!stralloc_cats(&aftermessage,",")) nomem(); } } struct ip_address outip; void doit(server) char *server; { struct ip_address ip; char ch; if (!ip_scan(server,&ip)) return; qmqpfd = socket(AF_INET,SOCK_STREAM,0); if (qmqpfd == -1) die_socket(); if (timeoutconn(qmqpfd,&ip,&outip,PORT_QMQP,timeoutconnect) != 0) { lasterror = 73; if (errno == error_timeout) lasterror = 72; close(qmqpfd); return; } #ifdef QMQP_COMPRESS compression_init(); #endif strnum[fmt_uint(strnum, (beforemessage.len + message.len + aftermessage.len))] = 0; substdio_puts(&to,strnum); substdio_puts(&to,":"); substdio_put(&to,beforemessage.s,beforemessage.len); substdio_put(&to,message.s,message.len); substdio_put(&to,aftermessage.s,aftermessage.len); substdio_puts(&to,","); substdio_flush(&to); #ifdef QMQP_COMPRESS compression_done(); #endif for (;;) { substdio_get(&from,&ch,1); if (ch == 'K') die_success(); if (ch == 'Z') die_temp(); if (ch == 'D') die_perm(); } } stralloc servers = {0}; stralloc outgoingip = {0}; #include "dns.h" #include "ipalloc.h" ipalloc ia = {0}; int main(argc,argv) int argc; char **argv; { unsigned int i; unsigned int j; sig_pipeignore(); if (chdir(auto_qmail) == -1) die_home(); if (control_init() == -1) die_control(); if ( argv[1] ) { char temp[IPFMT]; if (!stralloc_copys(&servers,argv[1])) nomem(); dns_init(0); switch (dns_ip(&ia,&servers)) { case DNS_HARD: die_perm(); case DNS_SOFT: die_temp(); case DNS_MEM: nomem(); } temp[ip_fmt(temp,&ia.ix[0].ip)]=0; if (!stralloc_copys(&servers, temp)) nomem(); if (!stralloc_0(&servers)) nomem(); } else if (control_readfile(&servers,"control/qmqpservers",0) != 1) die_control(); if (control_readint(&timeoutconnect,"control/timeoutconnect") == -1) die_control(); if (control_rldef(&outgoingip, "control/qmqpcip", 0, "0.0.0.0") == -1) die_control(); if (!stralloc_0(&outgoingip)) nomem(); if (!ip_scan(outgoingip.s,&outip)) die_control(); getmess(); i = 0; for (j = 0;j < servers.len;++j) if (!servers.s[j]) { doit(servers.s + i); i = j + 1; } return lasterror; }
openwengo/qmail-ldap
tcpto.h
<filename>tcpto.h #ifndef TCPTO_H #define TCPTO_H struct ip_address; extern int tcpto(struct ip_address *); extern void tcpto_err(struct ip_address *, int); extern void tcpto_clean(void); #endif
openwengo/qmail-ldap
stralloc_catb.c
<filename>stralloc_catb.c #include "stralloc.h" #include "byte.h" int stralloc_catb(sa,s,n) stralloc *sa; const char *s; unsigned int n; { if (!sa->s) return stralloc_copyb(sa,s,n); if (!stralloc_readyplus(sa,n + 1)) return 0; byte_copy(sa->s + sa->len,n,s); sa->len += n; sa->s[sa->len] = 'Z'; /* ``offensive programming'' */ return 1; }
openwengo/qmail-ldap
scan_8long.c
<gh_stars>10-100 #include "scan.h" unsigned int scan_8long(s,u) register const char *s; register unsigned long *u; { register unsigned int pos; register unsigned long result; register unsigned long c; pos = 0; result = 0; while ((c = (unsigned long) (unsigned char) (s[pos] - '0')) < 8) { result = result * 8 + c; ++pos; } *u = result; return pos; }
openwengo/qmail-ldap
seek.h
#ifndef SEEK_H #define SEEK_H typedef unsigned long seek_pos; extern seek_pos seek_cur(int fd); extern int seek_set(int fd, seek_pos); extern int seek_end(int fd); extern int seek_trunc(int fd, seek_pos); #define seek_begin(fd) (seek_set((fd),(seek_pos) 0)) #endif
openwengo/qmail-ldap
getln.h
#ifndef GETLN_H #define GETLN_H #include "stralloc.h" #include "substdio.h" extern int getln(substdio *, stralloc *, int *, int); extern int getln2(substdio *, stralloc *, char **, unsigned int *, int); #endif
openwengo/qmail-ldap
readwrite.h
#ifndef READWRITE_H #define READWRITE_H int subread(int, void *, int); int subwrite(int, void *, int); #endif
openwengo/qmail-ldap
hfield.c
<filename>hfield.c #include "hfield.h" static const char *(hname[]) = { "unknown-header" , "sender" , "from" , "reply-to" , "to" , "cc" , "bcc" , "date" , "message-id" , "subject" , "resent-sender" , "resent-from" , "resent-reply-to" , "resent-to" , "resent-cc" , "resent-bcc" , "resent-date" , "resent-message-id" , "return-receipt-to" , "errors-to" , "apparently-to" , "received" , "return-path" , "delivered-to" , "content-length" , "content-type" , "content-transfer-encoding" , "notice-requested-upon-delivery-to" , "mail-followup-to" , 0 }; static int hmatch(s,len,t) char *s; unsigned int len; const char *t; { unsigned int i; char ch; for (i = 0;(ch = t[i]);++i) { if (i >= len) return 0; if (ch != s[i]) { if (ch == '-') return 0; if (ch - 32 != s[i]) return 0; } } for (;;) { if (i >= len) return 0; ch = s[i]; if (ch == ':') return 1; if ((ch != ' ') && (ch != '\t')) return 0; ++i; } } int hfield_known(s,len) char *s; unsigned int len; { unsigned int i; const char *t; for (i = 1;(t = hname[i]);++i) if (hmatch(s,len,t)) return i; return 0; } int hfield_valid(s,len) char *s; unsigned int len; { unsigned int i; unsigned int j; char ch; for (j = 0;j < len;++j) if (s[j] == ':') break; if (j >= len) return 0; while (j) { ch = s[j - 1]; if ((ch != ' ') && (ch != '\t')) break; --j; } if (!j) return 0; for (i = 0;i < j;++i) { ch = s[i]; if (ch <= 32) return 0; if (ch >= 127) return 0; } return 1; } unsigned int hfield_skipname(s,len) char *s; unsigned int len; { unsigned int i; char ch; for (i = 0;i < len;++i) if (s[i] == ':') break; if (i < len) ++i; while (i < len) { ch = s[i]; if ((ch != '\t') && (ch != '\n') && (ch != '\r') && (ch != ' ')) break; ++i; } return i; }
openwengo/qmail-ldap
fd.h
<gh_stars>10-100 #ifndef FD_H #define FD_H extern int fd_copy(int, int); extern int fd_move(int, int); #endif
openwengo/qmail-ldap
prot.c
#include <unistd.h> #include "hasshsgr.h" #include "prot.h" /* XXX: there are more portability problems here waiting to leap out at me */ int prot_gid(gid) unsigned int gid; { #ifdef HASSHORTSETGROUPS short x[2]; x[0] = gid; x[1] = 73; /* catch errors */ if (setgroups(1,x) == -1) return -1; #else if (setgroups(1,&gid) == -1) return -1; #endif return setgid(gid); /* _should_ be redundant, but on some systems it isn't */ } int prot_uid(uid) unsigned int uid; { return setuid(uid); }
openwengo/qmail-ldap
trysalen.c
<gh_stars>10-100 #include <sys/types.h> #include <sys/param.h> #include <sys/time.h> #include <sys/ioctl.h> #include <sys/socket.h> void foo() { struct sockaddr sa; sa.sa_len = 0; }
openwengo/qmail-ldap
preline.c
<filename>preline.c<gh_stars>10-100 #include <unistd.h> #include "fd.h" #include "sgetopt.h" #include "readwrite.h" #include "strerr.h" #include "substdio.h" #include "exit.h" #include "fork.h" #include "wait.h" #include "env.h" #include "sig.h" #include "error.h" #define FATAL "preline: fatal: " void die_usage() { strerr_die1x(100,"preline: usage: preline cmd [ arg ... ]"); } int flagufline = 1; char *ufline; int flagrpline = 1; char *rpline; int flagdtline = 1; char *dtline; char outbuf[SUBSTDIO_OUTSIZE]; char inbuf[SUBSTDIO_INSIZE]; substdio ssout = SUBSTDIO_FDBUF(subwrite,1,outbuf,sizeof outbuf); substdio ssin = SUBSTDIO_FDBUF(subread,0,inbuf,sizeof inbuf); int main(argc,argv) int argc; char **argv; { int opt; int pi[2]; int pid; int wstat; sig_pipeignore(); if (!(ufline = env_get("UFLINE"))) die_usage(); if (!(rpline = env_get("RPLINE"))) die_usage(); if (!(dtline = env_get("DTLINE"))) die_usage(); while ((opt = getopt(argc,argv,"frdFRD")) != opteof) switch(opt) { case 'f': flagufline = 0; break; case 'r': flagrpline = 0; break; case 'd': flagdtline = 0; break; case 'F': flagufline = 1; break; case 'R': flagrpline = 1; break; case 'D': flagdtline = 1; break; default: die_usage(); } argc -= optind; argv += optind; if (!*argv) die_usage(); if (pipe(pi) == -1) strerr_die2sys(111,FATAL,"unable to create pipe: "); pid = fork(); if (pid == -1) strerr_die2sys(111,FATAL,"unable to fork: "); if (pid == 0) { close(pi[1]); if (fd_move(0,pi[0]) == -1) strerr_die2sys(111,FATAL,"unable to set up fds: "); sig_pipedefault(); execvp(*argv,argv); strerr_die4sys(error_temp(errno) ? 111 : 100,FATAL,"unable to run ",*argv,": "); } close(pi[0]); if (fd_move(1,pi[1]) == -1) strerr_die2sys(111,FATAL,"unable to set up fds: "); if (flagufline) substdio_bputs(&ssout,ufline); if (flagrpline) substdio_bputs(&ssout,rpline); if (flagdtline) substdio_bputs(&ssout,dtline); if (substdio_copy(&ssout,&ssin) != 0) strerr_die2sys(111,FATAL,"unable to copy input: "); substdio_flush(&ssout); close(1); if (wait_pid(&wstat,pid) == -1) strerr_die2sys(111,FATAL,"wait failed: "); if (wait_crashed(wstat)) strerr_die2x(111,FATAL,"child crashed"); return wait_exitcode(wstat); }
openwengo/qmail-ldap
auto_uids.h
#ifndef AUTO_UIDS_H #define AUTO_UIDS_H extern unsigned int auto_uida; extern unsigned int auto_uidd; extern unsigned int auto_uidl; extern unsigned int auto_uido; extern unsigned int auto_uidp; extern unsigned int auto_uidq; extern unsigned int auto_uidr; extern unsigned int auto_uids; extern unsigned int auto_gidn; extern unsigned int auto_gidq; #endif
openwengo/qmail-ldap
date822fmt.c
<filename>date822fmt.c #include "datetime.h" #include "fmt.h" #include "date822fmt.h" static const char *montab[12] = { "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec" }; unsigned int date822fmt(s,dt) char *s; struct datetime *dt; { unsigned int i; unsigned int len; len = 0; i = fmt_uint(s,dt->mday); len += i; if (s) s += i; i = fmt_str(s," "); len += i; if (s) s += i; i = fmt_str(s,montab[dt->mon]); len += i; if (s) s += i; i = fmt_str(s," "); len += i; if (s) s += i; i = fmt_uint(s,dt->year + 1900); len += i; if (s) s += i; i = fmt_str(s," "); len += i; if (s) s += i; i = fmt_uint0(s,dt->hour,2); len += i; if (s) s += i; i = fmt_str(s,":"); len += i; if (s) s += i; i = fmt_uint0(s,dt->min,2); len += i; if (s) s += i; i = fmt_str(s,":"); len += i; if (s) s += i; i = fmt_uint0(s,dt->sec,2); len += i; if (s) s += i; i = fmt_str(s," -0000\n"); len += i; if (s) s += i; return len; }
openwengo/qmail-ldap
newfield.c
#include <sys/types.h> #include <unistd.h> #include "fmt.h" #include "datetime.h" #include "stralloc.h" #include "date822fmt.h" #include "newfield.h" /* "Date: 26 Sep 1995 04:46:53 -0000\n" */ stralloc newfield_date = {0}; /* "Message-ID: <19950926044653.<EMAIL>>\n" */ stralloc newfield_msgid = {0}; static unsigned int datefmt(s,when) char *s; datetime_sec when; { unsigned int i; unsigned int len; struct datetime dt; datetime_tai(&dt,when); len = 0; i = fmt_str(s,"Date: "); len += i; if (s) s += i; i = date822fmt(s,&dt); len += i; if (s) s += i; return len; } static unsigned int msgidfmt(s,idhost,idhostlen,when) char *s; const char *idhost; int idhostlen; datetime_sec when; { unsigned int i; unsigned int len; struct datetime dt; datetime_tai(&dt,when); len = 0; i = fmt_str(s,"Message-ID: <"); len += i; if (s) s += i; i = fmt_uint(s,dt.year + 1900); len += i; if (s) s += i; i = fmt_uint0(s,dt.mon + 1,2); len += i; if (s) s += i; i = fmt_uint0(s,dt.mday,2); len += i; if (s) s += i; i = fmt_uint0(s,dt.hour,2); len += i; if (s) s += i; i = fmt_uint0(s,dt.min,2); len += i; if (s) s += i; i = fmt_uint0(s,dt.sec,2); len += i; if (s) s += i; i = fmt_str(s,"."); len += i; if (s) s += i; i = fmt_uint(s,getpid()); len += i; if (s) s += i; i = fmt_str(s,".qmail@"); len += i; if (s) s += i; i = fmt_strn(s,idhost,idhostlen); len += i; if (s) s += i; i = fmt_str(s,">\n"); len += i; if (s) s += i; return len; } int newfield_datemake(when) datetime_sec when; { if (!stralloc_ready(&newfield_date,datefmt(FMT_LEN,when))) return 0; newfield_date.len = datefmt(newfield_date.s,when); return 1; } int newfield_msgidmake(idhost,idhostlen,when) const char *idhost; int idhostlen; datetime_sec when; { if (!stralloc_ready(&newfield_msgid,msgidfmt(FMT_LEN,idhost,idhostlen,when))) return 0; newfield_msgid.len = msgidfmt(newfield_msgid.s,idhost,idhostlen,when); return 1; }
openwengo/qmail-ldap
dnsdoe.h
<reponame>openwengo/qmail-ldap<filename>dnsdoe.h<gh_stars>10-100 #ifndef DNSDOE_H #define DNSDOE_H extern void dnsdoe(int); #endif
openwengo/qmail-ldap
case_lowers.c
<reponame>openwengo/qmail-ldap #include "case.h" void case_lowers(s) char *s; { unsigned char x; while ((x = *s)) { x -= 'A'; if (x <= 'Z' - 'A') *s = x + 'a'; ++s; } }
openwengo/qmail-ldap
ndelay.c
<reponame>openwengo/qmail-ldap #include <sys/types.h> #include <fcntl.h> #include "ndelay.h" #ifndef O_NONBLOCK #define O_NONBLOCK O_NDELAY #endif int ndelay_on(fd) int fd; { return fcntl(fd,F_SETFL,fcntl(fd,F_GETFL,0) | O_NONBLOCK); }
openwengo/qmail-ldap
fmt_uint.c
#include "fmt.h" unsigned int fmt_uint(s,u) register char *s; register unsigned int u; { register unsigned long l; l = u; return fmt_ulong(s,l); }
openwengo/qmail-ldap
seek_end.c
<reponame>openwengo/qmail-ldap #include <sys/types.h> #include <unistd.h> #include "seek.h" #define END 2 /* sigh */ int seek_end(fd) int fd; { if (lseek(fd,(off_t) 0,END) == -1) return -1; return 0; }
openwengo/qmail-ldap
qlx.h
#ifndef QLX_H #define QLX_H /* 0, 111, 100 are qmail-local success, soft, hard */ #define QLX_USAGE 112 #define QLX_BUG 101 #define QLX_ROOT 113 #define QLX_NFS 115 #define QLX_NOALIAS 116 #define QLX_CDB 117 #define QLX_SYS 118 #define QLX_NOMEM 119 #define QLX_EXECSOFT 120 #define QLX_EXECPW 121 #define QLX_EXECHARD 126 /* qmail-ldap specific exit codes */ /* ldap specific errors */ #define QLX_MAXSIZE 150 #define QLX_LDAPFAIL 152 /* generic fail of ldap functions */ #define QLX_LDAPAUTH 153 /* LDAP_BIND_AUTH */ #define QLX_SEARCHTIMEOUT 154 /* TIMEOUT */ #define QLX_BINDTIMEOUT 155 /* LDAP_BIND_UNREACH */ #define QLX_TOOMANY 156 #define QLX_NEEDED 157 #define QLX_ILLVAL 158 #define QLX_DISABLED 159 #define QLX_DELETED 160 /* cluster errors */ #define QLX_CLUSTERSOFT 162 #define QLX_CLUSTERHARD 163 #define QLX_CLUSTERCRASHED 164 #define QLX_CLUSTERLOOP 165 /* dirmaker errors */ #define QLX_DIRMAKESOFT 167 #define QLX_DIRMAKEHARD 168 #define QLX_DIRMAKECRASH 169 #endif
openwengo/qmail-ldap
datetime.c
<filename>datetime.c /* 19950925 */ #include "datetime.h" void datetime_tai(dt,t) struct datetime *dt; datetime_sec t; { int day; int tod; int year; int yday; int wday; int mon; tod = t % 86400; day = t / 86400; if (tod < 0) { tod += 86400; --day; } dt->hour = tod / 3600; tod %= 3600; dt->min = tod / 60; dt->sec = tod % 60; wday = (day + 4) % 7; if (wday < 0) wday += 7; dt->wday = wday; day -= 11017; /* day 0 is march 1, 2000 */ year = 5 + day / 146097; day = day % 146097; if (day < 0) { day += 146097; --year; } /* from now on, day is nonnegative */ year *= 4; if (day == 146096) { year += 3; day = 36524; } else { year += day / 36524; day %= 36524; } year *= 25; year += day / 1461; day %= 1461; year *= 4; yday = (day < 306); if (day == 1460) { year += 3; day = 365; } else { year += day / 365; day %= 365; } yday += day; day *= 10; mon = (day + 5) / 306; day = day + 5 - 306 * mon; day /= 10; if (mon >= 10) { yday -= 306; ++year; mon -= 10; } else { yday += 59; mon += 2; } dt->yday = yday; dt->year = year - 1900; dt->mon = mon; dt->mday = day + 1; }
openwengo/qmail-ldap
limit.h
#ifndef __LIMIT_H__ #define __LIMIT_H__ #include <limits.h> /* * we only need the max value for 32bit integers so make sure that we have * those available. * So we assume ILP32 or I32LP64 based systems which should be the default * for unix systems. AFAIK only Cray is ILP64... */ #ifndef UINT_MAX #define UINT_MAX 0xffffffffU /* max value for an unsigned int */ #endif #ifndef INT_MAX #define INT_MAX 0x7fffffff /* max value for an int */ #endif #ifndef INT_MIN #define INT_MIN (-0x7fffffff-1) /* min value for an int */ #endif #endif
openwengo/qmail-ldap
now.c
<gh_stars>10-100 #include <time.h> #include "datetime.h" #include "now.h" datetime_sec now(void) { return time((void *)0); }
openwengo/qmail-ldap
gfrom.c
#include "str.h" #include "gfrom.h" int gfrom(s,len) char *s; int len; { while ((len > 0) && (*s == '>')) { ++s; --len; } return (len >= 5) && !str_diffn(s,"From ",5); }
openwengo/qmail-ldap
trysgact.c
<reponame>openwengo/qmail-ldap #include <signal.h> void main() { struct sigaction sa; sa.sa_handler = 0; sa.sa_flags = 0; sigemptyset(&sa.sa_mask); sigaction(0,&sa,(struct sigaction *) 0); }
openwengo/qmail-ldap
subfderr.c
#include "readwrite.h" #include "substdio.h" #include "subfd.h" char subfd_errbuf[256]; static substdio it = SUBSTDIO_FDBUF(subwrite,2,subfd_errbuf,256); substdio *subfderr = &it;
openwengo/qmail-ldap
install.c
#include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include "substdio.h" #include "strerr.h" #include "error.h" #include "open.h" #include "readwrite.h" #include "exit.h" #include "fifo.h" extern void hier(); #define FATAL "install: fatal: " #ifdef FAKE_CHOWN #include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <pwd.h> #include <grp.h> int fake_chown(dir,uid,gid) const char *dir; int uid; int gid; { struct passwd *result ; result = getpwuid(uid); struct group *result2 ; result2 = getgrgid(gid); if (dir[0] == '/') { printf("chown %s.%s %s\n",result->pw_name,result2->gr_name,dir) ; } else { printf("chown %s.%s %s/%s\n",result->pw_name,result2->gr_name,get_current_dir_name(),dir) ; } return 0; } #define chown(dir,uid,gid) fake_chown(dir,uid,gid) #endif int fdsourcedir = -1; void h(home,uid,gid,mode) const char *home; int uid; int gid; int mode; { if (mkdir(home,0700) == -1) if (errno != error_exist) strerr_die4sys(111,FATAL,"unable to mkdir ",home,": "); if (chown(home,uid,gid) == -1) strerr_die4sys(111,FATAL,"unable to chown ",home,": "); if (chmod(home,mode) == -1) strerr_die4sys(111,FATAL,"unable to chmod ",home,": "); } void d(home,subdir,uid,gid,mode) const char *home; const char *subdir; int uid; int gid; int mode; { if (chdir(home) == -1) strerr_die4sys(111,FATAL,"unable to switch to ",home,": "); if (mkdir(subdir,0700) == -1) if (errno != error_exist) strerr_die6sys(111,FATAL,"unable to mkdir ",home,"/",subdir,": "); if (chown(subdir,uid,gid) == -1) strerr_die6sys(111,FATAL,"unable to chown ",home,"/",subdir,": "); if (chmod(subdir,mode) == -1) strerr_die6sys(111,FATAL,"unable to chmod ",home,"/",subdir,": "); } void p(home,fifo,uid,gid,mode) const char *home; const char *fifo; int uid; int gid; int mode; { if (chdir(home) == -1) strerr_die4sys(111,FATAL,"unable to switch to ",home,": "); if (fifo_make(fifo,0700) == -1) if (errno != error_exist) strerr_die6sys(111,FATAL,"unable to mkfifo ",home,"/",fifo,": "); if (chown(fifo,uid,gid) == -1) strerr_die6sys(111,FATAL,"unable to chown ",home,"/",fifo,": "); if (chmod(fifo,mode) == -1) strerr_die6sys(111,FATAL,"unable to chmod ",home,"/",fifo,": "); } char inbuf[SUBSTDIO_INSIZE]; char outbuf[SUBSTDIO_OUTSIZE]; substdio ssin; substdio ssout; void c(home,subdir,file,uid,gid,mode) const char *home; const char *subdir; const char *file; int uid; int gid; int mode; { int fdin; int fdout; if (fchdir(fdsourcedir) == -1) strerr_die2sys(111,FATAL,"unable to switch back to source directory: "); fdin = open_read(file); if (fdin == -1) strerr_die4sys(111,FATAL,"unable to read ",file,": "); substdio_fdbuf(&ssin,subread,fdin,inbuf,sizeof inbuf); if (chdir(home) == -1) strerr_die4sys(111,FATAL,"unable to switch to ",home,": "); if (chdir(subdir) == -1) strerr_die6sys(111,FATAL,"unable to switch to ",home,"/",subdir,": "); fdout = open_trunc(file); if (fdout == -1) strerr_die6sys(111,FATAL,"unable to write .../",subdir,"/",file,": "); substdio_fdbuf(&ssout,subwrite,fdout,outbuf,sizeof outbuf); switch(substdio_copy(&ssout,&ssin)) { case -2: strerr_die4sys(111,FATAL,"unable to read ",file,": "); case -3: strerr_die6sys(111,FATAL,"unable to write .../",subdir,"/",file,": "); } close(fdin); if (substdio_flush(&ssout) == -1) strerr_die6sys(111,FATAL,"unable to write .../",subdir,"/",file,": "); if (fsync(fdout) == -1) strerr_die6sys(111,FATAL,"unable to write .../",subdir,"/",file,": "); if (close(fdout) == -1) /* NFS silliness */ strerr_die6sys(111,FATAL,"unable to write .../",subdir,"/",file,": "); if (chown(file,uid,gid) == -1) strerr_die6sys(111,FATAL,"unable to chown .../",subdir,"/",file,": "); if (chmod(file,mode) == -1) strerr_die6sys(111,FATAL,"unable to chmod .../",subdir,"/",file,": "); } void C(home,subdir,file,source,uid,gid,mode) const char *home; const char *subdir; const char *file; const char *source; int uid; int gid; int mode; { struct stat st; int fdin; int fdout; if (fchdir(fdsourcedir) == -1) strerr_die2sys(111,FATAL,"unable to switch back to source directory: "); fdin = open_read(source); if (fdin == -1) strerr_die4sys(111,FATAL,"unable to read ",source,": "); substdio_fdbuf(&ssin,subread,fdin,inbuf,sizeof inbuf); if (chdir(home) == -1) strerr_die4sys(111,FATAL,"unable to switch to ",home,": "); if (chdir(subdir) == -1) strerr_die6sys(111,FATAL,"unable to switch to ",home,"/",subdir,": "); /* if file seems to exist don't overwrite */ if (stat(file, &st) == 0) { close(fdin); return; } fdout = open_trunc(file); if (fdout == -1) strerr_die6sys(111,FATAL,"unable to write .../",subdir,"/",file,": "); substdio_fdbuf(&ssout,subwrite,fdout,outbuf,sizeof outbuf); switch(substdio_copy(&ssout,&ssin)) { case -2: strerr_die4sys(111,FATAL,"unable to read ",source,": "); case -3: strerr_die6sys(111,FATAL,"unable to write .../",subdir,"/",file,": "); } close(fdin); if (substdio_flush(&ssout) == -1) strerr_die6sys(111,FATAL,"unable to write .../",subdir,"/",file,": "); if (fsync(fdout) == -1) strerr_die6sys(111,FATAL,"unable to write .../",subdir,"/",file,": "); if (close(fdout) == -1) /* NFS silliness */ strerr_die6sys(111,FATAL,"unable to write .../",subdir,"/",file,": "); if (chown(file,uid,gid) == -1) strerr_die6sys(111,FATAL,"unable to chown .../",subdir,"/",file,": "); if (chmod(file,mode) == -1) strerr_die6sys(111,FATAL,"unable to chmod .../",subdir,"/",file,": "); } void l(home,subdir,logdir,loguser,uid,gid,mode) const char *home; const char *subdir; const char *logdir; const char *loguser; int uid; int gid; int mode; { int fdout; struct stat st; if (chdir(home) == -1) strerr_die4sys(111,FATAL,"unable to switch to ",home,": "); if (chdir(subdir) == -1) strerr_die6sys(111,FATAL,"unable to switch to ",home,"/",subdir,": "); /* if file seems to exist don't overwrite */ if (stat("run", &st) == 0) return; fdout = open_trunc("run"); if (fdout == -1) strerr_die4sys(111,FATAL,"unable to write .../",subdir,"/run: "); substdio_fdbuf(&ssout,subwrite,fdout,outbuf,sizeof outbuf); /* write log script */ if (substdio_puts(&ssout, "#!/bin/sh\n\nexec setuidgid ") == -1) strerr_die4sys(111,FATAL,"unable to write .../",subdir,"/run: "); if (substdio_puts(&ssout, loguser) == -1) strerr_die4sys(111,FATAL,"unable to write .../",subdir,"/run: "); if (substdio_puts(&ssout, " multilog t ") == -1) strerr_die4sys(111,FATAL,"unable to write .../",subdir,"/run: "); if (substdio_puts(&ssout, home) == -1) strerr_die4sys(111,FATAL,"unable to write .../",subdir,"/run: "); if (substdio_puts(&ssout, "/") == -1) strerr_die4sys(111,FATAL,"unable to write .../",subdir,"/run: "); if (substdio_puts(&ssout, logdir) == -1) strerr_die4sys(111,FATAL,"unable to write .../",subdir,"/run: "); if (substdio_puts(&ssout, "\n\n") == -1) strerr_die4sys(111,FATAL,"unable to write .../",subdir,"/run: "); if (substdio_flush(&ssout) == -1) strerr_die4sys(111,FATAL,"unable to write .../",subdir,"/run: "); if (fsync(fdout) == -1) strerr_die4sys(111,FATAL,"unable to write .../",subdir,"/run: "); if (close(fdout) == -1) /* NFS silliness */ strerr_die4sys(111,FATAL,"unable to write .../",subdir,"/run: "); if (chown("run",uid,gid) == -1) strerr_die4sys(111,FATAL,"unable to chown .../",subdir,"/run: "); if (chmod("run",mode) == -1) strerr_die4sys(111,FATAL,"unable to chmod .../",subdir,"/run: "); } void z(home,file,len,uid,gid,mode) const char *home; const char *file; int len; int uid; int gid; int mode; { int fdout; if (chdir(home) == -1) strerr_die4sys(111,FATAL,"unable to switch to ",home,": "); fdout = open_trunc(file); if (fdout == -1) strerr_die6sys(111,FATAL,"unable to write ",home,"/",file,": "); substdio_fdbuf(&ssout,subwrite,fdout,outbuf,sizeof outbuf); while (len-- > 0) if (substdio_put(&ssout,"",1) == -1) strerr_die6sys(111,FATAL,"unable to write ",home,"/",file,": "); if (substdio_flush(&ssout) == -1) strerr_die6sys(111,FATAL,"unable to write ",home,"/",file,": "); if (fsync(fdout) == -1) strerr_die6sys(111,FATAL,"unable to write ",home,"/",file,": "); if (close(fdout) == -1) /* NFS silliness */ strerr_die6sys(111,FATAL,"unable to write ",home,"/",file,": "); if (chown(file,uid,gid) == -1) strerr_die6sys(111,FATAL,"unable to chown ",home,"/",file,": "); if (chmod(file,mode) == -1) strerr_die6sys(111,FATAL,"unable to chmod ",home,"/",file,": "); } int main() { fdsourcedir = open_read("."); if (fdsourcedir == -1) strerr_die2sys(111,FATAL,"unable to open current directory: "); umask(077); hier(); return 0; }
openwengo/qmail-ldap
extra.h
#ifndef EXTRA_H #define EXTRA_H #define QUEUE_EXTRA "" #define QUEUE_EXTRALEN 0 #endif
openwengo/qmail-ldap
quote.h
#ifndef QUOTE_H #define QUOTE_H #include "stralloc.h" extern int quote_need(const char *, unsigned int); extern int quote(stralloc *, stralloc *); extern int quote2(stralloc *, const char *); #endif