This discussion is archived
5 Replies Latest reply: Mar 30, 2013 4:48 PM by EJP RSS

LDAP connection timeout exception - some times

999371 Newbie
Currently Being Moderated
Hi Team,


I'm using Ldap authentication for my web applications. Everything is working fine most of the times.

But ones in every 15 days or 10 days, I'm getting the connection timeout. But if I restart the tomcat then everything working fine. I couldn't find any

issues with my code. Can anyone please help me on this. below is my java code. I'm keeping all the ldap entries in tomcat's server.xml and getting them in my java code to avoid the hard

code configurations in my java code.

I'm closing the context and naming enumerations like below, but still getting javax.naming.CommunicationException: error.

Can anyone please help me out on this.
public boolean authenticateFromLdap(String username, String password)throws AuthenticationException,Exception {
    LdapContext ctx = null;
    Context newctx = new InitialContext();
    Context envCtx = (Context) newctx.lookup("java:comp/env");
    DirContext ctxDir = (DirContext)envCtx.lookup("ldap/myapp");
    NamingEnumeration<?> namingEnum = null;
    String userDN=null;
    boolean isauthenticated = false;

    try {
        Hashtable env = null;
        Control[] connCtls = null;
        env = ctxDir.getEnvironment();
        env.put(Context.REFERRAL, "follow");
        this.filter = (String)env.get("ldap.filter");
        this.base = (String)env.get("ldap.base");

        try {
            ctx = new InitialLdapContext(env, connCtls);
            ctx.setRequestControls(null);
        } catch (javax.naming.AuthenticationException ex) {
            throw new Exception("ldap.server.exception");
        } catch (Exception ex) {
            throw new Exception("ldap.server.exception");
        }

        try {
            SearchControls searchControls = new SearchControls();
            searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
            searchControls.setTimeLimit(30000);
            String filter="("+this.filter+"="+username+")";
            ctx.setRequestControls(null);
            namingEnum = ctx.search(this.base, filter, searchControls);
            SearchResult result = (SearchResult) namingEnum.next();
            Attributes attrs = result.getAttributes();
            Attribute str1=attrs.get("userprincipalname");
            userDN=str1.get().toString();
            if(userDN==null){
                userDN=username;
            }
            ctx.addToEnvironment(Context.SECURITY_PRINCIPAL,userDN);
            ctx.addToEnvironment(Context.SECURITY_CREDENTIALS,password);
            ctx.reconnect(connCtls);
            isauthenticated = true;
        }catch (AuthenticationException ex) {
            throw new AuthenticationException();
        }catch (NamingException ex) {
            throw new Exception("ldap.server.exception");
        }
        return isauthenticated;
    } finally {
        if (null != namingEnum) {
            try {
                namingEnum.close();
            } catch (Exception e) {
                throw new Exception("close.ldap.failure");
            }
        }
        if (null != ctx) {
            try {
                ctx.close();
            } catch (Exception e) {
                throw new Exception("close.ldap.failure");
            }
        }
    }
}
Tomcat (v6.0.14) server.xml:
                <Resource name="ldap/myapp"
                                                auth="Container"
                                                type="com.sun.jndi.ldap.LdapCtx"
                                                factory="com.myapp.MyLdapFactory"
                                                java.naming.factory.initial="com.sun.jndi.ldap.LdapCtxFactory"
                                                com.sun.jndi.ldap.connect.pool="false"
                                                java.naming.provider.url="ldap://ldap.com.test.net:389"
                                                java.naming.security.authentication="simple"
                                                java.naming.security.principal="MyAdmin"
                                                java.naming.security.credentials="xxxxxxx"
                                                ldap.base="DC=com,DC=test,DC=net"
                                                ldap.filter="sAMAccountName"
                />
Below is the error log trace:
2013-Mar-26 12:01:34,714 AppUserDetailsService - javax.naming.CommunicationException: ldap.com.test.net:389 [Root exception is java.net.ConnectException: Connection timed out: connect]
Note: Once we restart the tomcat, everything is working as usual and after 2 weeks again same problem occuring.

Ganesh

Edited by: EJP on 27/03/2013 14:26: added {noformat}
{noformat} tags. Please use them. Your code is unreadable without them.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            
  • 1. Re: LDAP connection timeout exception - some times
    EJP Guru
    Currently Being Moderated
    1. 'filter' and 'base' need to be local variables, not instance variables, otherwise the method isn't thread-safe.

    2. It isn't clear that you are closing the search results or contexts if you get an exception, in all that spaghetti, especially the part where you just catch and rethrow exceptions, which is pointless. You need to rewrite that lot like this:
    public boolean authenticateFromLdap(String username, String password) throws AuthenticationException, NamingException
    {
         Context newctx = new InitialContext();
         try
         {
              Context envCtx = (Context)newctx.lookup("java:comp/env");
              try
              {
                   DirContext ctxDir = (DirContext)envCtx.lookup("ldap/myapp");
                   try
                   {
                        String userDN = null;
                        boolean isauthenticated = false;
                        Control[] connCtls = null;
                        Hashtable env = ctxDir.getEnvironment();
                        env.put(Context.REFERRAL, "follow");
                        String     filter = (String)env.get("ldap.filter");
                        String     base = (String)env.get("ldap.base");
                        LdapContext ctx = new InitialLdapContext(env, connCtls);
                        try
                        {
                             ctx.setRequestControls(null);
                             SearchControls searchControls = new SearchControls();
                             searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
                             searchControls.setTimeLimit(30000);
                             filter = "(" + filter + "=" + username + ")";
                             ctx.setRequestControls(null);
                             NamingEnumeration<SearchResult> namingEnum = ctx.search(base, filter, searchControls);
                             try
                             {
                                  SearchResult result = namingEnum.next();
                                  Attributes attrs = result.getAttributes();
                                  Attribute str1 = attrs.get("userprincipalname");
                                  userDN = str1.get().toString();
                                  if (userDN == null)
                                  {
                                       userDN = username;
                                  }
                                  ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, userDN);
                                  ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, password);
                                  ctx.reconnect(connCtls);
                                  isauthenticated = true;
                                  return isauthenticated;
                             }
                             finally
                             {
                                  namingEnum.close();
                             }
                        }
                        finally
                        {
                             ctx.close();
                        }
                   }
                   finally
                   {
                        ctxDir.close();
                   }
              }
              finally
              {
                   envCtx.close();
              }
         }
         finally
         {
              newctx.close();
         }
    }
    Also, you are suppressing exceptions when you rethrow. Never do that. Always log the actual exception. But there aren't any exceptions here that need to be caught and rethrown.
  • 2. Re: LDAP connection timeout exception - some times
    999371 Newbie
    Currently Being Moderated
    Thanks EJP. I tried refactoring the code but couldn't find the fix. and also

    1. 'filter' and 'base' need to be local variables, not instance variables, otherwise the method isn't thread-safe

    I didn't see the use of making these variables as local. Because these are just kind of constants and we are just reading (by map's get method) them. We have another method in same clause to create the user in DB if he is authorised in ldap. So in this method also we need these two variables, hence declared them as instance variables. Does it make any sense in making them as local, please advise me.

    2. After refactoring the code, had the same problem.

    Thanks a lot for your quick turnaround my query EJP. Please correct me if my understanding/configurations are wrong.


    Regards,
    Ganesh
  • 3. Re: LDAP connection timeout exception - some times
    jtahlborn Expert
    Currently Being Moderated
    what makes you think it is a code problem and not a network problem?
  • 4. Re: LDAP connection timeout exception - some times
    999371 Newbie
    Currently Being Moderated
    Hi JT,

    That is the problem. I'm not able to find the problem with Network or my code. Because if there is any problem with code, everything is working, but after 15 days again getting connection timeout exception. if the problem with network, how it is working for 20 days and why it is again working after restarting the tomcat? This is really a strange behaviour of my application. Is there any way to identify the problem? what could be the problem? Please share your inputs to resolve the problem.

    Thanks for your time.

    Regards,
    Ganesh
  • 5. Re: LDAP connection timeout exception - some times
    EJP Guru
    Currently Being Moderated
    what makes you think it is a code problem and not a network problem?
    It is most likely a connection leak. Connection timeout can be caused by many things but most of them would cause it every time. Very likely the LDAP server has a maximum number of connections it will handle simultaneously, and beyond that it won't call accept(), so new incoming connections remain in the backlog queue, which fills up, which can cause further incoming connections to time out.

    @OP Can you run netstat -anp at the server when this happens, to check the hypothesis above? Can you also set a connection-idle timeout at the LDAP server? That would fix connection leaks but in a brute-force way that may break other things.

Legend

  • Correct Answers - 10 points
  • Helpful Answers - 5 points