jcifs-1.2.9

16:37:19.125 INFO  jd.cli.Main - Decompiling jcifs-1.2.9.jar
package jcifs;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Properties;
import java.util.StringTokenizer;
import jcifs.util.LogStream;

public class Config
{
  private static Properties prp = new Properties();
  private static LogStream log;
  
  static
  {
    FileInputStream in = null;
    
    log = LogStream.getInstance();
    try
    {
      String filename = System.getProperty("jcifs.properties");
      if ((filename != null) && (filename.length() > 1)) {
        in = new FileInputStream(filename);
      }
      load(in);
    }
    catch (IOException ioe)
    {
      if (LogStream.level > 0) {
        ioe.printStackTrace(log);
      }
    }
    int level;
    if ((level = getInt("jcifs.util.loglevel", -1)) != -1) {
      LogStream.setLevel(level);
    }
    if (LogStream.level > 2) {
      try
      {
        prp.store(log, "JCIFS PROPERTIES");
      }
      catch (IOException ioe) {}
    }
  }
  
  public static void registerSmbURLHandler()
  {
    String ver = System.getProperty("java.version");
    if ((ver.startsWith("1.1.")) || (ver.startsWith("1.2."))) {
      throw new RuntimeException("jcifs-0.7.0b4+ requires Java 1.3 or above. You are running " + ver);
    }
    String pkgs = System.getProperty("java.protocol.handler.pkgs");
    if (pkgs == null)
    {
      System.setProperty("java.protocol.handler.pkgs", "jcifs");
    }
    else if (pkgs.indexOf("jcifs") == -1)
    {
      pkgs = pkgs + "|jcifs";
      System.setProperty("java.protocol.handler.pkgs", pkgs);
    }
  }
  
  public static void setProperties(Properties prp)
  {
    prp = new Properties(prp);
    try
    {
      prp.putAll(System.getProperties());
    }
    catch (SecurityException se)
    {
      if (LogStream.level > 1) {
        log.println("SecurityException: jcifs will ignore System properties");
      }
    }
  }
  
  public static void load(InputStream in)
    throws IOException
  {
    if (in != null) {
      prp.load(in);
    }
    try
    {
      prp.putAll(System.getProperties());
    }
    catch (SecurityException se)
    {
      if (LogStream.level > 1) {
        log.println("SecurityException: jcifs will ignore System properties");
      }
    }
  }
  
  public static void store(OutputStream out, String header)
    throws IOException
  {
    prp.store(out, header);
  }
  
  public static void list(PrintStream out)
    throws IOException
  {
    prp.list(out);
  }
  
  public static Object setProperty(String key, String value)
  {
    return prp.setProperty(key, value);
  }
  
  public static Object get(String key)
  {
    return prp.get(key);
  }
  
  public static String getProperty(String key, String def)
  {
    return prp.getProperty(key, def);
  }
  
  public static String getProperty(String key)
  {
    return prp.getProperty(key);
  }
  
  public static int getInt(String key, int def)
  {
    String s = prp.getProperty(key);
    if (s != null) {
      try
      {
        def = Integer.parseInt(s);
      }
      catch (NumberFormatException nfe)
      {
        if (LogStream.level > 0) {
          nfe.printStackTrace(log);
        }
      }
    }
    return def;
  }
  
  public static int getInt(String key)
  {
    String s = prp.getProperty(key);
    int result = -1;
    if (s != null) {
      try
      {
        result = Integer.parseInt(s);
      }
      catch (NumberFormatException nfe)
      {
        if (LogStream.level > 0) {
          nfe.printStackTrace(log);
        }
      }
    }
    return result;
  }
  
  public static long getLong(String key, long def)
  {
    String s = prp.getProperty(key);
    if (s != null) {
      try
      {
        def = Long.parseLong(s);
      }
      catch (NumberFormatException nfe)
      {
        if (LogStream.level > 0) {
          nfe.printStackTrace(log);
        }
      }
    }
    return def;
  }
  
  public static InetAddress getInetAddress(String key, InetAddress def)
  {
    String addr = prp.getProperty(key);
    if (addr != null) {
      try
      {
        def = InetAddress.getByName(addr);
      }
      catch (UnknownHostException uhe)
      {
        if (LogStream.level > 0)
        {
          log.println(addr);
          uhe.printStackTrace(log);
        }
      }
    }
    return def;
  }
  
  public static InetAddress getLocalHost()
  {
    String addr = prp.getProperty("jcifs.smb.client.laddr");
    if (addr != null) {
      try
      {
        return InetAddress.getByName(addr);
      }
      catch (UnknownHostException uhe)
      {
        if (LogStream.level > 0)
        {
          log.println("Ignoring jcifs.smb.client.laddr address: " + addr);
          uhe.printStackTrace(log);
        }
      }
    }
    return null;
  }
  
  public static boolean getBoolean(String key, boolean def)
  {
    String b = getProperty(key);
    if (b != null) {
      def = b.toLowerCase().equals("true");
    }
    return def;
  }
  
  public static InetAddress[] getInetAddressArray(String key, String delim, InetAddress[] def)
  {
    String p = getProperty(key);
    if (p != null)
    {
      StringTokenizer tok = new StringTokenizer(p, delim);
      int len = tok.countTokens();
      InetAddress[] arr = new InetAddress[len];
      for (int i = 0; i < len; i++)
      {
        String addr = tok.nextToken();
        try
        {
          arr[i] = InetAddress.getByName(addr);
        }
        catch (UnknownHostException uhe)
        {
          if (LogStream.level > 0)
          {
            log.println(addr);
            uhe.printStackTrace(log);
          }
          return def;
        }
      }
      return arr;
    }
    return def;
  }
}

/* Location:
 * Qualified Name:     jcifs.Config
 * Java Class Version: 1.2 (46.0)
 * JD-Core Version:    0.7.1
 */
package jcifs;

import java.net.InetAddress;
import java.net.UnknownHostException;
import jcifs.netbios.NbtAddress;

class UniAddress$QueryThread
  extends Thread
{
  UniAddress.Sem sem;
  String host;
  String scope;
  int type;
  NbtAddress ans = null;
  InetAddress svr;
  UnknownHostException uhe;
  
  UniAddress$QueryThread(UniAddress.Sem sem, String host, int type, String scope, InetAddress svr)
  {
    super("JCIFS-QueryThread: " + host);
    this.sem = sem;
    this.host = host;
    this.type = type;
    this.scope = scope;
    this.svr = svr;
  }
  
  public void run()
  {
    try
    {
      ans = NbtAddress.getByName(host, type, scope, svr);
    }
    catch (UnknownHostException uhe)
    {
      this.uhe = uhe;
    }
    catch (Exception ex)
    {
      this.uhe = new UnknownHostException(ex.getMessage());
    }
    finally
    {
      synchronized (sem)
      {
        sem.count -= 1;
        sem.notify();
      }
    }
  }
}

/* Location:
 * Qualified Name:     jcifs.UniAddress.QueryThread
 * Java Class Version: 1.2 (46.0)
 * JD-Core Version:    0.7.1
 */
package jcifs;

class UniAddress$Sem
{
  int count;
  
  UniAddress$Sem(int count)
  {
    this.count = count;
  }
}

/* Location:
 * Qualified Name:     jcifs.UniAddress.Sem
 * Java Class Version: 1.2 (46.0)
 * JD-Core Version:    0.7.1
 */
package jcifs;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.StringTokenizer;
import jcifs.netbios.Lmhosts;
import jcifs.netbios.NbtAddress;
import jcifs.util.LogStream;

public class UniAddress
{
  private static final int RESOLVER_WINS = 0;
  private static final int RESOLVER_BCAST = 1;
  private static final int RESOLVER_DNS = 2;
  private static final int RESOLVER_LMHOSTS = 3;
  private static int[] resolveOrder;
  private static InetAddress baddr;
  private static LogStream log = ;
  Object addr;
  String calledName;
  
  static
  {
    String ro = Config.getProperty("jcifs.resolveOrder");
    InetAddress nbns = NbtAddress.getWINSAddress();
    try
    {
      baddr = Config.getInetAddress("jcifs.netbios.baddr", InetAddress.getByName("255.255.255.255"));
    }
    catch (UnknownHostException uhe) {}
    if ((ro == null) || (ro.length() == 0))
    {
      if (nbns == null)
      {
        resolveOrder = new int[3];
        resolveOrder[0] = 3;
        resolveOrder[1] = 1;
        resolveOrder[2] = 2;
      }
      else
      {
        resolveOrder = new int[4];
        resolveOrder[0] = 3;
        resolveOrder[1] = 0;
        resolveOrder[2] = 1;
        resolveOrder[3] = 2;
      }
    }
    else
    {
      int[] tmp = new int[4];
      StringTokenizer st = new StringTokenizer(ro, ",");
      int i = 0;
      while (st.hasMoreTokens())
      {
        String s = st.nextToken().trim();
        if (s.equalsIgnoreCase("LMHOSTS")) {
          tmp[(i++)] = 3;
        } else if (s.equalsIgnoreCase("WINS"))
        {
          if (nbns == null)
          {
            if (LogStream.level > 1) {
              log.println("UniAddress resolveOrder specifies WINS however the jcifs.netbios.wins property has not been set");
            }
          }
          else {
            tmp[(i++)] = 0;
          }
        }
        else if (s.equalsIgnoreCase("BCAST")) {
          tmp[(i++)] = 1;
        } else if (s.equalsIgnoreCase("DNS")) {
          tmp[(i++)] = 2;
        } else if (LogStream.level > 1) {
          log.println("unknown resolver method: " + s);
        }
      }
      resolveOrder = new int[i];
      System.arraycopy(tmp, 0, resolveOrder, 0, i);
    }
  }
  
  static class Sem
  {
    int count;
    
    Sem(int count)
    {
      this.count = count;
    }
  }
  
  static class QueryThread
    extends Thread
  {
    UniAddress.Sem sem;
    String host;
    String scope;
    int type;
    NbtAddress ans = null;
    InetAddress svr;
    UnknownHostException uhe;
    
    QueryThread(UniAddress.Sem sem, String host, int type, String scope, InetAddress svr)
    {
      super();
      this.sem = sem;
      this.host = host;
      this.type = type;
      this.scope = scope;
      this.svr = svr;
    }
    
    public void run()
    {
      try
      {
        ans = NbtAddress.getByName(host, type, scope, svr);
      }
      catch (UnknownHostException uhe)
      {
        this.uhe = uhe;
      }
      catch (Exception ex)
      {
        this.uhe = new UnknownHostException(ex.getMessage());
      }
      finally
      {
        synchronized (sem)
        {
          sem.count -= 1;
          sem.notify();
        }
      }
    }
  }
  
  static NbtAddress lookupServerOrWorkgroup(String name, InetAddress svr)
    throws UnknownHostException
  {
    Sem sem = new Sem(2);
    int type = NbtAddress.isWINS(svr) ? 27 : 29;
    
    QueryThread q1x = new QueryThread(sem, name, type, null, svr);
    QueryThread q20 = new QueryThread(sem, name, 32, null, svr);
    q1x.setDaemon(true);
    q20.setDaemon(true);
    try
    {
      synchronized (sem)
      {
        q1x.start();
        q20.start();
        while ((count > 0) && (ans == null) && (ans == null)) {
          sem.wait();
        }
      }
    }
    catch (InterruptedException ie)
    {
      throw new UnknownHostException(name);
    }
    if (ans != null) {
      return ans;
    }
    if (ans != null) {
      return ans;
    }
    throw uhe;
  }
  
  public static UniAddress getByName(String hostname)
    throws UnknownHostException
  {
    return getByName(hostname, false);
  }
  
  static boolean isDotQuadIP(String hostname)
  {
    if (Character.isDigit(hostname.charAt(0)))
    {
      int dots;
      int i = dots = 0;
      int len = hostname.length();
      char[] data = hostname.toCharArray();
      while ((i < len) && (Character.isDigit(data[(i++)])))
      {
        if ((i == len) && (dots == 3)) {
          return true;
        }
        if ((i < len) && (data[i] == '.'))
        {
          dots++;
          i++;
        }
      }
    }
    return false;
  }
  
  static boolean isAllDigits(String hostname)
  {
    for (int i = 0; i < hostname.length(); i++) {
      if (!Character.isDigit(hostname.charAt(i))) {
        return false;
      }
    }
    return true;
  }
  
  public static UniAddress getByName(String hostname, boolean possibleNTDomainOrWorkgroup)
    throws UnknownHostException
  {
    if ((hostname == null) || (hostname.length() == 0)) {
      throw new UnknownHostException();
    }
    if (isDotQuadIP(hostname)) {
      return new UniAddress(NbtAddress.getByName(hostname));
    }
    for (int i = 0; i < resolveOrder.length; i++) {
      try
      {
        Object addr;
        Object addr;
        Object addr;
        switch (resolveOrder[i])
        {
        case 3: 
          Object addr;
          if ((addr = Lmhosts.getByName(hostname)) != null) {
            break;
          }
          break;
        case 0: 
          if ((hostname != "\001\002__MSBROWSE__\002") && (hostname.length() > 15)) {
            continue;
          }
          Object addr;
          if (possibleNTDomainOrWorkgroup) {
            addr = lookupServerOrWorkgroup(hostname, NbtAddress.getWINSAddress());
          } else {
            addr = NbtAddress.getByName(hostname, 32, null, NbtAddress.getWINSAddress());
          }
          break;
        case 1: 
          if (hostname.length() > 15) {
            continue;
          }
          Object addr;
          if (possibleNTDomainOrWorkgroup) {
            addr = lookupServerOrWorkgroup(hostname, baddr);
          } else {
            addr = NbtAddress.getByName(hostname, 32, null, baddr);
          }
          break;
        case 2: 
          if (isAllDigits(hostname)) {
            throw new UnknownHostException(hostname);
          }
          addr = InetAddress.getByName(hostname);
          break;
        default: 
          throw new UnknownHostException(hostname);
        }
        return new UniAddress(addr);
      }
      catch (IOException ioe) {}
    }
    throw new UnknownHostException(hostname);
  }
  
  public UniAddress(Object addr)
  {
    if (addr == null) {
      throw new IllegalArgumentException();
    }
    this.addr = addr;
  }
  
  public int hashCode()
  {
    return addr.hashCode();
  }
  
  public boolean equals(Object obj)
  {
    return ((obj instanceof UniAddress)) && (addr.hashCode() == obj.hashCode());
  }
  
  public String firstCalledName()
  {
    if ((addr instanceof NbtAddress)) {
      return ((NbtAddress)addr).firstCalledName();
    }
    calledName = ((InetAddress)addr).getHostName();
    if (isDotQuadIP(calledName))
    {
      calledName = "*SMBSERVER     ";
    }
    else
    {
      int i = calledName.indexOf('.');
      if ((i > 1) && (i < 15)) {
        calledName = calledName.substring(0, i).toUpperCase();
      } else if (calledName.length() > 15) {
        calledName = "*SMBSERVER     ";
      } else {
        calledName = calledName.toUpperCase();
      }
    }
    return calledName;
  }
  
  public String nextCalledName()
  {
    if ((addr instanceof NbtAddress)) {
      return ((NbtAddress)addr).nextCalledName();
    }
    if (calledName != "*SMBSERVER     ")
    {
      calledName = "*SMBSERVER     ";
      return calledName;
    }
    return null;
  }
  
  public Object getAddress()
  {
    return addr;
  }
  
  public String getHostName()
  {
    if ((addr instanceof NbtAddress)) {
      return ((NbtAddress)addr).getHostName();
    }
    return ((InetAddress)addr).getHostName();
  }
  
  public String getHostAddress()
  {
    if ((addr instanceof NbtAddress)) {
      return ((NbtAddress)addr).getHostAddress();
    }
    return ((InetAddress)addr).getHostAddress();
  }
  
  public String toString()
  {
    return addr.toString();
  }
}

/* Location:
 * Qualified Name:     jcifs.UniAddress
 * Java Class Version: 1.2 (46.0)
 * JD-Core Version:    0.7.1
 */
package jcifs.http;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;
import java.net.URLStreamHandlerFactory;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;

public class Handler
  extends URLStreamHandler
{
  public static final int DEFAULT_HTTP_PORT = 80;
  private static final Map PROTOCOL_HANDLERS = new HashMap();
  private static final String HANDLER_PKGS_PROPERTY = "java.protocol.handler.pkgs";
  private static final String[] JVM_VENDOR_DEFAULT_PKGS = { "sun.net.www.protocol" };
  private static URLStreamHandlerFactory factory;
  
  public static void setURLStreamHandlerFactory(URLStreamHandlerFactory factory)
  {
    synchronized (PROTOCOL_HANDLERS)
    {
      if (factory != null) {
        throw new IllegalStateException("URLStreamHandlerFactory already set.");
      }
      PROTOCOL_HANDLERS.clear();
      factory = factory;
    }
  }
  
  protected int getDefaultPort()
  {
    return 80;
  }
  
  protected URLConnection openConnection(URL url)
    throws IOException
  {
    url = new URL(url, url.toExternalForm(), getDefaultStreamHandler(url.getProtocol()));
    
    return new NtlmHttpURLConnection((HttpURLConnection)url.openConnection());
  }
  
  private static URLStreamHandler getDefaultStreamHandler(String protocol)
    throws IOException
  {
    synchronized (PROTOCOL_HANDLERS)
    {
      URLStreamHandler handler = (URLStreamHandler)PROTOCOL_HANDLERS.get(protocol);
      if (handler != null) {
        return handler;
      }
      if (factory != null) {
        handler = factory.createURLStreamHandler(protocol);
      }
      if (handler == null)
      {
        String path = System.getProperty("java.protocol.handler.pkgs");
        StringTokenizer tokenizer = new StringTokenizer(path, "|");
        while (tokenizer.hasMoreTokens())
        {
          String provider = tokenizer.nextToken().trim();
          if (!provider.equals("jcifs"))
          {
            String className = provider + "." + protocol + ".Handler";
            try
            {
              Class handlerClass = null;
              try
              {
                handlerClass = Class.forName(className);
              }
              catch (Exception ex) {}
              if (handlerClass == null) {
                handlerClass = ClassLoader.getSystemClassLoader().loadClass(className);
              }
              handler = (URLStreamHandler)handlerClass.newInstance();
            }
            catch (Exception ex) {}
          }
        }
      }
      if (handler == null) {
        for (int i = 0; i < JVM_VENDOR_DEFAULT_PKGS.length; i++)
        {
          String className = JVM_VENDOR_DEFAULT_PKGS[i] + "." + protocol + ".Handler";
          try
          {
            Class handlerClass = null;
            try
            {
              handlerClass = Class.forName(className);
            }
            catch (Exception ex) {}
            if (handlerClass == null) {
              handlerClass = ClassLoader.getSystemClassLoader().loadClass(className);
            }
            handler = (URLStreamHandler)handlerClass.newInstance();
          }
          catch (Exception ex) {}
          if (handler != null) {
            break;
          }
        }
      }
      if (handler == null) {
        throw new IOException("Unable to find default handler for protocol: " + protocol);
      }
      PROTOCOL_HANDLERS.put(protocol, handler);
      return handler;
    }
  }
}

/* Location:
 * Qualified Name:     jcifs.http.Handler
 * Java Class Version: 1.2 (46.0)
 * JD-Core Version:    0.7.1
 */
package jcifs.http;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.GregorianCalendar;
import java.util.LinkedList;
import java.util.ListIterator;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import jcifs.Config;
import jcifs.UniAddress;
import jcifs.netbios.NbtAddress;
import jcifs.smb.DfsReferral;
import jcifs.smb.NtlmPasswordAuthentication;
import jcifs.smb.SmbAuthException;
import jcifs.smb.SmbException;
import jcifs.smb.SmbFile;
import jcifs.smb.SmbFileInputStream;
import jcifs.smb.SmbSession;
import jcifs.util.Base64;
import jcifs.util.LogStream;
import jcifs.util.MimeMap;

public class NetworkExplorer
  extends HttpServlet
{
  private static LogStream log = ;
  private MimeMap mimeMap;
  private String style;
  private NtlmSsp ntlmSsp;
  private boolean credentialsSupplied;
  private boolean enableBasic;
  private boolean insecureBasic;
  private String realm;
  private String defaultDomain;
  
  public void init()
    throws ServletException
  {
    StringBuffer sb = new StringBuffer();
    byte[] buf = new byte['?'];
    
    Config.setProperty("jcifs.smb.client.soTimeout", "600000");
    Config.setProperty("jcifs.smb.client.attrExpirationPeriod", "300000");
    
    Enumeration e = getInitParameterNames();
    while (e.hasMoreElements())
    {
      String name = (String)e.nextElement();
      if (name.startsWith("jcifs.")) {
        Config.setProperty(name, getInitParameter(name));
      }
    }
    if (Config.getProperty("jcifs.smb.client.username") == null) {
      ntlmSsp = new NtlmSsp();
    } else {
      credentialsSupplied = true;
    }
    try
    {
      mimeMap = new MimeMap();
      InputStream is = getClass().getClassLoader().getResourceAsStream("jcifs/http/ne.css");
      int n;
      while ((n = is.read(buf)) != -1) {
        sb.append(new String(buf, 0, n, "ISO8859_1"));
      }
      style = sb.toString();
    }
    catch (IOException ioe)
    {
      throw new ServletException(ioe.getMessage());
    }
    int n;
    InputStream is;
    enableBasic = Config.getBoolean("jcifs.http.enableBasic", false);
    insecureBasic = Config.getBoolean("jcifs.http.insecureBasic", false);
    realm = Config.getProperty("jcifs.http.basicRealm");
    if (realm == null) {
      realm = "jCIFS";
    }
    defaultDomain = Config.getProperty("jcifs.smb.client.domain");
    int level;
    if ((level = Config.getInt("jcifs.util.loglevel", -1)) != -1) {
      LogStream.setLevel(level);
    }
    if (LogStream.level > 2) {
      try
      {
        Config.store(log, "JCIFS PROPERTIES");
      }
      catch (IOException ioe) {}
    }
  }
  
  protected void doFile(HttpServletRequest req, HttpServletResponse resp, SmbFile file)
    throws IOException
  {
    byte[] buf = new byte['?'];
    
    SmbFileInputStream in = new SmbFileInputStream(file);
    ServletOutputStream out = resp.getOutputStream();
    String url = file.getPath();
    
    resp.setContentType("text/plain");
    int n;
    String type;
    if (((n = url.lastIndexOf('.')) > 0) && ((type = url.substring(n + 1)) != null) && (type.length() > 1) && (type.length() < 6)) {
      resp.setContentType(mimeMap.getMimeType(type));
    }
    resp.setHeader("Content-Length", file.length() + "");
    resp.setHeader("Accept-Ranges", "Bytes");
    while ((n = in.read(buf)) != -1) {
      out.write(buf, 0, n);
    }
  }
  
  protected int compareNames(SmbFile f1, String f1name, SmbFile f2)
    throws IOException
  {
    if (f1.isDirectory() != f2.isDirectory()) {
      return f1.isDirectory() ? -1 : 1;
    }
    return f1name.compareToIgnoreCase(f2.getName());
  }
  
  protected int compareSizes(SmbFile f1, String f1name, SmbFile f2)
    throws IOException
  {
    if (f1.isDirectory() != f2.isDirectory()) {
      return f1.isDirectory() ? -1 : 1;
    }
    if (f1.isDirectory()) {
      return f1name.compareToIgnoreCase(f2.getName());
    }
    long diff = f1.length() - f2.length();
    if (diff == 0L) {
      return f1name.compareToIgnoreCase(f2.getName());
    }
    return diff > 0L ? -1 : 1;
  }
  
  protected int compareTypes(SmbFile f1, String f1name, SmbFile f2)
    throws IOException
  {
    if (f1.isDirectory() != f2.isDirectory()) {
      return f1.isDirectory() ? -1 : 1;
    }
    String f2name = f2.getName();
    if (f1.isDirectory()) {
      return f1name.compareToIgnoreCase(f2name);
    }
    int i = f1name.lastIndexOf('.');
    String t1 = i == -1 ? "" : f1name.substring(i + 1);
    i = f2name.lastIndexOf('.');
    String t2 = i == -1 ? "" : f2name.substring(i + 1);
    
    i = t1.compareToIgnoreCase(t2);
    if (i == 0) {
      return f1name.compareToIgnoreCase(f2name);
    }
    return i;
  }
  
  protected int compareDates(SmbFile f1, String f1name, SmbFile f2)
    throws IOException
  {
    if (f1.isDirectory() != f2.isDirectory()) {
      return f1.isDirectory() ? -1 : 1;
    }
    if (f1.isDirectory()) {
      return f1name.compareToIgnoreCase(f2.getName());
    }
    return f1.lastModified() > f2.lastModified() ? -1 : 1;
  }
  
  protected void doDirectory(HttpServletRequest req, HttpServletResponse resp, SmbFile dir)
    throws IOException
  {
    SimpleDateFormat sdf = new SimpleDateFormat("MM/d/yy h:mm a");
    GregorianCalendar cal = new GregorianCalendar();
    
    sdf.setCalendar(cal);
    
    SmbFile[] dirents = dir.listFiles();
    if (LogStream.level > 2) {
      log.println(dirents.length + " items listed");
    }
    LinkedList sorted = new LinkedList();
    String fmt;
    if ((fmt = req.getParameter("fmt")) == null) {
      fmt = "col";
    }
    int sort = 0;
    String str;
    if (((str = req.getParameter("sort")) == null) || (str.equals("name"))) {
      sort = 0;
    } else if (str.equals("size")) {
      sort = 1;
    } else if (str.equals("type")) {
      sort = 2;
    } else if (str.equals("date")) {
      sort = 3;
    }
    int fileCount;
    int dirCount = fileCount = 0;
    int maxLen = 28;
    for (int i = 0; i < dirents.length; i++)
    {
      try
      {
        if (dirents[i].getType() == 16) {
          continue;
        }
      }
      catch (SmbAuthException sae)
      {
        if (LogStream.level > 2) {
          sae.printStackTrace(log);
        }
      }
      catch (SmbException se)
      {
        if (LogStream.level > 2) {
          se.printStackTrace(log);
        }
        if (se.getNtStatus() != -1073741823) {
          throw se;
        }
      }
      if (dirents[i].isDirectory()) {
        dirCount++;
      } else {
        fileCount++;
      }
      String name = dirents[i].getName();
      if (LogStream.level > 3) {
        log.println(i + ": " + name);
      }
      int len = name.length();
      if (len > maxLen) {
        maxLen = len;
      }
      ListIterator iter = sorted.listIterator();
      for (int j = 0; iter.hasNext(); j++) {
        if (sort == 0 ? 
          compareNames(dirents[i], name, (SmbFile)iter.next()) >= 0 : 
          
          sort == 1 ? 
          compareSizes(dirents[i], name, (SmbFile)iter.next()) >= 0 : 
          
          sort == 2 ? 
          compareTypes(dirents[i], name, (SmbFile)iter.next()) >= 0 : 
          
          (sort == 3) && 
          (compareDates(dirents[i], name, (SmbFile)iter.next()) < 0)) {
          break;
        }
      }
      sorted.add(j, dirents[i]);
    }
    if (maxLen > 50) {
      maxLen = 50;
    }
    maxLen *= 9;
    
    PrintWriter out = resp.getWriter();
    
    resp.setContentType("text/html");
    
    out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
    out.println("<html><head><title>Network Explorer</title>");
    out.println("<meta HTTP-EQUIV=\"Pragma\" CONTENT=\"no-cache\">");
    out.println("<style TYPE=\"text/css\">");
    
    out.println(style);
    if (dirents.length < 200)
    {
      out.println("    a:hover {");
      out.println("        background: #a2ff01;");
      out.println("    }");
    }
    out.println("</STYLE>");
    out.println("</head><body>");
    
    out.print("<a class=\"sort\" style=\"width: " + maxLen + ";\" href=\"?fmt=detail&sort=name\">Name</a>");
    out.println("<a class=\"sort\" href=\"?fmt=detail&sort=size\">Size</a>");
    out.println("<a class=\"sort\" href=\"?fmt=detail&sort=type\">Type</a>");
    out.println("<a class=\"sort\" style=\"width: 180\" href=\"?fmt=detail&sort=date\">Modified</a><br clear='all'><p>");
    
    String path = dir.getCanonicalPath();
    if (path.length() < 7)
    {
      out.println("<b><big>smb://</big></b><br>");
      path = ".";
    }
    else
    {
      out.println("<b><big>" + path + "</big></b><br>");
      path = "../";
    }
    out.println(dirCount + fileCount + " objects (" + dirCount + " directories, " + fileCount + " files)<br>");
    out.println("<b><a class=\"plain\" href=\".\">normal</a> | <a class=\"plain\" href=\"?fmt=detail\">detailed</a></b>");
    out.println("<p><table border='0' cellspacing='0' cellpadding='0'><tr><td>");
    
    out.print("<A style=\"width: " + maxLen);
    out.print("; height: 18;\" HREF=\"");
    out.print(path);
    out.println("\"><b>&uarr;</b></a>");
    if (fmt.equals("detail")) {
      out.println("<br clear='all'>");
    }
    if ((path.length() == 1) || (dir.getType() != 2)) {
      path = "";
    }
    ListIterator iter = sorted.listIterator();
    while (iter.hasNext())
    {
      SmbFile f = (SmbFile)iter.next();
      String name = f.getName();
      if (fmt.equals("detail"))
      {
        out.print("<A style=\"width: " + maxLen);
        out.print("; height: 18;\" HREF=\"");
        out.print(path);
        out.print(name);
        if (f.isDirectory())
        {
          out.print("?fmt=detail\"><b>");
          out.print(name);
          out.print("</b></a>");
        }
        else
        {
          out.print("\"><b>");
          out.print(name);
          out.print("</b></a><div align='right'>");
          out.print(f.length() / 1024L + " KB </div><div>");
          i = name.lastIndexOf('.') + 1;
          if ((i > 1) && (name.length() - i < 6)) {
            out.print(name.substring(i).toUpperCase() + "</div class='ext'>");
          } else {
            out.print("&nbsp;</div>");
          }
          out.print("<div style='width: 180'>");
          out.print(sdf.format(new Date(f.lastModified())));
          out.print("</div>");
        }
        out.println("<br clear='all'>");
      }
      else
      {
        out.print("<A style=\"width: " + maxLen);
        if (f.isDirectory())
        {
          out.print("; height: 18;\" HREF=\"");
          out.print(path);
          out.print(name);
          out.print("\"><b>");
          out.print(name);
          out.print("</b></a>");
        }
        else
        {
          out.print(";\" HREF=\"");
          out.print(path);
          out.print(name);
          out.print("\"><b>");
          out.print(name);
          out.print("</b><br><small>");
          out.print(f.length() / 1024L + "KB <br>");
          out.print(sdf.format(new Date(f.lastModified())));
          out.print("</small>");
          out.println("</a>");
        }
      }
    }
    out.println("</td></tr></table>");
    out.println("</BODY></HTML>");
    out.close();
  }
  
  private String parseServerAndShare(String pathInfo)
  {
    char[] out = new char['?'];
    if (pathInfo == null) {
      return null;
    }
    int len = pathInfo.length();
    int i;
    int p = i = 0;
    while ((p < len) && (pathInfo.charAt(p) == '/')) {
      p++;
    }
    if (p == len) {
      return null;
    }
    char ch;
    while ((p < len) && ((ch = pathInfo.charAt(p)) != '/'))
    {
      out[(i++)] = ch;
      p++;
    }
    while ((p < len) && (pathInfo.charAt(p) == '/')) {
      p++;
    }
    if (p < len)
    {
      out[(i++)] = '/';
      char ch;
      do
      {
        out[(i++)] = (ch = pathInfo.charAt(p++));
      } while ((p < len) && (ch != '/'));
    }
    return new String(out, 0, i);
  }
  
  public void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws IOException, ServletException
  {
    String server = null;
    boolean possibleWorkgroup = true;
    NtlmPasswordAuthentication ntlm = null;
    HttpSession ssn = req.getSession(false);
    String pathInfo;
    if ((pathInfo = req.getPathInfo()) != null)
    {
      server = parseServerAndShare(pathInfo);
      int i;
      if ((server != null) && ((i = server.indexOf('/')) > 0))
      {
        server = server.substring(0, i).toLowerCase();
        possibleWorkgroup = false;
      }
    }
    String msg = req.getHeader("Authorization");
    boolean offerBasic = (enableBasic) && ((insecureBasic) || (req.isSecure()));
    if ((msg != null) && ((msg.startsWith("NTLM ")) || ((offerBasic) && (msg.startsWith("Basic ")))))
    {
      if (msg.startsWith("NTLM "))
      {
        UniAddress dc;
        UniAddress dc;
        if ((pathInfo == null) || (server == null))
        {
          String mb = NbtAddress.getByName("\001\002__MSBROWSE__\002", 1, null).getHostAddress();
          dc = UniAddress.getByName(mb);
        }
        else
        {
          dc = UniAddress.getByName(server, possibleWorkgroup);
        }
        req.getSession();
        byte[] challenge = SmbSession.getChallenge(dc);
        if ((ntlm = NtlmSsp.authenticate(req, resp, challenge)) == null) {
          return;
        }
      }
      else
      {
        String auth = new String(Base64.decode(msg.substring(6)), "US-ASCII");
        int index = auth.indexOf(':');
        String user = index != -1 ? auth.substring(0, index) : auth;
        String password = index != -1 ? auth.substring(index + 1) : "";
        index = user.indexOf('\\');
        if (index == -1) {
          index = user.indexOf('/');
        }
        String domain = index != -1 ? user.substring(0, index) : defaultDomain;
        user = index != -1 ? user.substring(index + 1) : user;
        ntlm = new NtlmPasswordAuthentication(domain, user, password);
      }
      req.getSession().setAttribute("npa-" + server, ntlm);
    }
    else if (!credentialsSupplied)
    {
      if (ssn != null) {
        ntlm = (NtlmPasswordAuthentication)ssn.getAttribute("npa-" + server);
      }
      if (ntlm == null)
      {
        resp.setHeader("WWW-Authenticate", "NTLM");
        if (offerBasic) {
          resp.addHeader("WWW-Authenticate", "Basic realm=\"" + realm + "\"");
        }
        resp.setHeader("Connection", "close");
        resp.setStatus(401);
        resp.flushBuffer();
        return;
      }
    }
    try
    {
      SmbFile file;
      SmbFile file;
      if (ntlm != null)
      {
        file = new SmbFile("smb:/" + pathInfo, ntlm);
      }
      else
      {
        SmbFile file;
        if (server == null) {
          file = new SmbFile("smb://");
        } else {
          file = new SmbFile("smb:/" + pathInfo);
        }
      }
      if (file.isDirectory()) {
        doDirectory(req, resp, file);
      } else {
        doFile(req, resp, file);
      }
    }
    catch (SmbAuthException sae)
    {
      if (ssn != null) {
        ssn.removeAttribute("npa-" + server);
      }
      if (sae.getNtStatus() == -1073741819)
      {
        resp.sendRedirect(req.getRequestURL().toString());
        return;
      }
      resp.setHeader("WWW-Authenticate", "NTLM");
      if (offerBasic) {
        resp.addHeader("WWW-Authenticate", "Basic realm=\"" + realm + "\"");
      }
      resp.setHeader("Connection", "close");
      resp.setStatus(401);
      resp.flushBuffer();
      return;
    }
    catch (DfsReferral dr)
    {
      StringBuffer redir = req.getRequestURL();
      String qs = req.getQueryString();
      redir = new StringBuffer(redir.substring(0, redir.length() - req.getPathInfo().length()));
      redir.append(node.replace('\\', '/'));
      redir.append('/');
      if (qs != null) {
        redir.append(req.getQueryString());
      }
      resp.sendRedirect(redir.toString());
      resp.flushBuffer();
      return;
    }
  }
}

/* Location:
 * Qualified Name:     jcifs.http.NetworkExplorer
 * Java Class Version: 1.2 (46.0)
 * JD-Core Version:    0.7.1
 */
package jcifs.http;

import java.io.IOException;
import java.util.Enumeration;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import jcifs.Config;
import jcifs.UniAddress;
import jcifs.smb.NtlmChallenge;
import jcifs.smb.NtlmPasswordAuthentication;
import jcifs.smb.SmbAuthException;
import jcifs.smb.SmbSession;
import jcifs.util.Base64;
import jcifs.util.Hexdump;
import jcifs.util.LogStream;

public class NtlmHttpFilter
  implements Filter
{
  private static LogStream log = ;
  private String defaultDomain;
  private String domainController;
  private boolean loadBalance;
  private boolean enableBasic;
  private boolean insecureBasic;
  private String realm;
  
  public void init(FilterConfig filterConfig)
    throws ServletException
  {
    Config.setProperty("jcifs.smb.client.soTimeout", "300000");
    Config.setProperty("jcifs.netbios.cachePolicy", "1200");
    
    Enumeration e = filterConfig.getInitParameterNames();
    while (e.hasMoreElements())
    {
      String name = (String)e.nextElement();
      if (name.startsWith("jcifs.")) {
        Config.setProperty(name, filterConfig.getInitParameter(name));
      }
    }
    defaultDomain = Config.getProperty("jcifs.smb.client.domain");
    domainController = Config.getProperty("jcifs.http.domainController");
    if (domainController == null)
    {
      domainController = defaultDomain;
      loadBalance = Config.getBoolean("jcifs.http.loadBalance", true);
    }
    enableBasic = Boolean.valueOf(Config.getProperty("jcifs.http.enableBasic")).booleanValue();
    
    insecureBasic = Boolean.valueOf(Config.getProperty("jcifs.http.insecureBasic")).booleanValue();
    
    realm = Config.getProperty("jcifs.http.basicRealm");
    if (realm == null) {
      realm = "jCIFS";
    }
    int level;
    if ((level = Config.getInt("jcifs.util.loglevel", -1)) != -1) {
      LogStream.setLevel(level);
    }
    if (LogStream.level > 2) {
      try
      {
        Config.store(log, "JCIFS PROPERTIES");
      }
      catch (IOException ioe) {}
    }
  }
  
  public void destroy() {}
  
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
    throws IOException, ServletException
  {
    HttpServletRequest req = (HttpServletRequest)request;
    HttpServletResponse resp = (HttpServletResponse)response;
    NtlmPasswordAuthentication ntlm;
    if ((ntlm = negotiate(req, resp, false)) == null) {
      return;
    }
    chain.doFilter(new NtlmHttpServletRequest(req, ntlm), response);
  }
  
  protected NtlmPasswordAuthentication negotiate(HttpServletRequest req, HttpServletResponse resp, boolean skipAuthentication)
    throws IOException, ServletException
  {
    NtlmPasswordAuthentication ntlm = null;
    String msg = req.getHeader("Authorization");
    boolean offerBasic = (enableBasic) && ((insecureBasic) || (req.isSecure()));
    if ((msg != null) && ((msg.startsWith("NTLM ")) || ((offerBasic) && (msg.startsWith("Basic ")))))
    {
      UniAddress dc;
      if (msg.startsWith("NTLM "))
      {
        HttpSession ssn = req.getSession();
        byte[] challenge;
        byte[] challenge;
        if (loadBalance)
        {
          NtlmChallenge chal = (NtlmChallenge)ssn.getAttribute("NtlmHttpChal");
          if (chal == null)
          {
            chal = SmbSession.getChallengeForDomain();
            ssn.setAttribute("NtlmHttpChal", chal);
          }
          UniAddress dc = dc;
          challenge = challenge;
        }
        else
        {
          UniAddress dc = UniAddress.getByName(domainController, true);
          challenge = SmbSession.getChallenge(dc);
        }
        if ((ntlm = NtlmSsp.authenticate(req, resp, challenge)) == null) {
          return null;
        }
        ssn.removeAttribute("NtlmHttpChal");
  
1 2 3 4 5 6 7 8 9 10 11 12 13

Further reading...

For more information on Java 1.5 Tiger, you may find Java 1.5 Tiger, A developer's Notebook by D. Flanagan and B. McLaughlin from O'Reilly of interest.

New!JAR listings


Copyright 2006-2017. Infinite Loop Ltd