Grepular

Accessing Memcached from Exim

Written 16 years ago by Mike Cardwell

You can get Exim to set and get arbitrary values in memcached by using the ${readsocket} string expansion.

I initially installed version 1.2.2 of memcached as that is the one that currently comes as a Debian package with Lenny. I found a bug in that version however so had to upgrade to the latest version (currently 1.2.8).

First of all define some macros at the top of the Exim config:

MEMCACHED_HOST = localhost
MEMCACHED_PORT = 11211

You may want to change those if your memcache daemon is listening elsewhere. The below two macros do all the magic and need adding beneath the above two macros, and shouldn’t need changing if you just want to do basic get/set:

MEMCACHED_SET = ${sg{${readsocket{inet:MEMCACHED_HOST:MEMCACHED_PORT}{set $acl_c_memcache_key 0 $acl_c_memcache_timeout ${strlen:$acl_c_memcache_value}\r\n$acl_c_memcache_value\r\nquit\r\n}}}{\N\r\n$\N}{}} MEMCACHED_GET = ${sg{${readsocket{inet:MEMCACHED_HOST:MEMCACHED_PORT}{get $acl_c_memcache_key\r\n}{5s}{\n}}}{\N^(?:VALUE \S+ \d+ \d+\r\n(.*?)\r\n)?END\r\n$\N}{\$1}}

Now, if you want to store some data in memcached, you set three acl variables and call the MEMCACHED_SET macro. In the following example, I store a key which is the connecting ip address and a value which is the envelope sender, and I set the value to expire after 60 seconds.

warn set acl_c_memcache_key     = $sender_host_address
     set acl_c_memcache_value   = $sender_address
     set acl_c_memcache_timeout = 60
     condition                  = ${if eq{MEMCACHED_SET}{STORED}}
     logwrite                   = Stored data in memcached

To do a lookup on the data you set acl_c_memcache_key and then call MEMCACHED_GET. Eg:

warn set acl_c_memcache_key = $sender_host_address
     logwrite               = MemCached stored value = MEMCACHED_GET

If you want no timeout then set it to 0. If you want a timeout which is longer than 30 days, it gets a little more complicated as you need to use seconds from the epoch. Check out the Expiration section in the memcached protocol documentation.

Want to leave a tip?BitcoinMoneroZcashPaypalYou can follow this Blog using RSS. To read more, visit my blog index.