4.12.2.1 Some Useful Functions

To illustrate the concept of user-defined functions, this subsection shows definitions of some of the library functions shipped with mailfromd. These functions are contained in modules installed along with the mailfromd binary. To use any of them in your code, require the appropriate module as described in Require and Import, e.g. to use the revip function, do require 'revip'.

Functions and their definitions:

  1. revip

    The function revip (see revip) is implemented as follows:

     
    func revip(string ip) returns string
    do
      return inet_ntoa(ntohl(inet_aton(%ip)))
    done    
    

    Previously it was implemented using regular expressions. Below we include this variant as well, as an illustration for the use of regular expressions:

     
    #pragma regex push +extended
    func revip(string ip) returns string
    do
      if %ip matches '([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+)'
        return "\4.\3.\2.\1"
      fi
      return %ip
    done
    #pragma regex pop
    
  2. strip_domain_part

    This function returns at most n last components of the domain name domain (see strip_domain_part).

     
    #pragma regex push +extended
    
    func strip_domain_part(string domain, number n) returns string
    do
      if %n = 0
        return domainpart %domain
      elif domainpart(%domain) matches '.*((\.[^.]+){' $2 '})'
        return substring(\1, 1, -1)
      else
        return %domain
      fi
    done
    #pragma regex pop
    
  3. valid_domain

    See valid_domain, for a description of this function. Its definition follows:

     
    require dns
    
    func valid_domain(string domain) returns number
    do
      return not (resolve(%domain) = "0" and not hasmx(%domain))
    done
    
  4. match_dnsbl

    The function match_dnsbl (see match_dnsbl) is defined as follows:

     
    require dns
    require match_cidr
    #pragma regex push +extended
    
    func match_dnsbl(string address, string zone, string range)
        returns number
    do
      string rbl_ip
      if %range = 'ANY'
        set rbl_ip '127.0.0.0/8'
      else
        set rbl_ip %range
        if not %range matches '^([0-9]{1,3}\.){3}[0-9]{1,3}$'
          return 0
        fi
      fi
    
      if not (%address matches '^([0-9]{1,3}\.){3}[0-9]{1,3}$'
              and %address != %range)
        return 0
      fi
    
      if %address matches
            '^([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$'
        if match_cidr (resolve ("\4.\3.\2.\1", %zone), %rbl_ip)
          return 1
        else
          return 0
        fi
      fi
      # never reached
    done