import socket
import tempfile

import synapse.lib.socket as s_socket

from synapse.common import *
from synapse.links.common import *

class LocalRelay(LinkRelay):
    '''
    Implements the PF_UNIX/PF_LOCAL protocol for synapse.
    ( and named pipes on windows platforms )

    local://<name>/

    '''
    proto = 'local'

    def _reqValidLink(self):
        # we use the "host" part as the local name
        host = self.link[1].get('host')
        if not host:
            raise BadUrl('local://<name>/<path>')

    def _getTempPath(self):
        host = self.link[1].get('host')
        # use the host part to generate a local path
        tdir = tempfile.gettempdir()
        return os.path.join(tdir,host)

    def _listen(self):

        s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        s.bind( self._getTempPath() )
        s.listen(120)

        return s_socket.Socket(s, listen=True)

    def _connect(self):
        path = self._getTempPath()
        s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        s.connect(path)
        return s_socket.Socket(s)


@@ -795,24 +795,25 @@
 STREAM)%0A
+%0A
         
 s.bind( 
@@ -808,15 +808,14 @@
     
-s.bind(
+path =
  sel
@@ -830,17 +830,98 @@
 mpPath()
- 
+%0A        if os.path.exists(path):%0A            os.unlink(path)%0A%0A        s.bind(path
 )%0A      

remove previous AF_UNIX socket if present