Subdomain Posts
HTML | 72 days ago
Java | 147 days ago
None | 148 days ago
Recent Posts
None | 12 sec ago
None | 18 sec ago
None | 21 sec ago
HTML | 42 sec ago
T-SQL | 58 sec ago
None | 1 min ago
None | 1 min ago
None | 1 min ago
None | 1 min ago
C | 1 min ago
Sitereport
Find cool info about any domain on the internet?
visit sitereport
Free Subdomains
Want a pastebin.com sub-domain for your community?
learn more...
What is pastebin?
Pastebin is a website that hosts all your text & code on dedicated servers for easy sharing.
learn more...
Learn a little bit about the new Pastebin.com on our help page. hide message
By Mykola Makhin on the 23rd of Oct 2009 05:45:59 AM Download | Raw | Embed | Report
  1. package makhin.mykola.minor.utils.routerreset;
  2.  
  3. import java.awt.BorderLayout;
  4. import java.awt.GridLayout;
  5. import java.awt.event.ActionEvent;
  6. import java.awt.event.ActionListener;
  7. import java.io.IOException;
  8. import java.net.InetAddress;
  9. import java.net.Socket;
  10. import java.net.UnknownHostException;
  11. import java.security.SecureRandom;
  12. import java.text.SimpleDateFormat;
  13. import java.util.Date;
  14. import javax.net.ssl.SSLContext;
  15. import javax.net.ssl.SSLSocketFactory;
  16. import javax.net.ssl.TrustManager;
  17. import javax.swing.JButton;
  18. import javax.swing.JComboBox;
  19. import javax.swing.JComponent;
  20. import javax.swing.JFrame;
  21. import javax.swing.JLabel;
  22. import javax.swing.JOptionPane;
  23. import javax.swing.JPanel;
  24. import javax.swing.JPasswordField;
  25. import javax.swing.JScrollPane;
  26. import javax.swing.JTextArea;
  27. import javax.swing.JTextField;
  28. import javax.swing.SwingUtilities;
  29. import javax.swing.border.EmptyBorder;
  30. import org.apache.commons.httpclient.ConnectTimeoutException;
  31. import org.apache.commons.httpclient.Credentials;
  32. import org.apache.commons.httpclient.HttpClient;
  33. import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
  34. import org.apache.commons.httpclient.URI;
  35. import org.apache.commons.httpclient.UsernamePasswordCredentials;
  36. import org.apache.commons.httpclient.auth.AuthScope;
  37. import org.apache.commons.httpclient.methods.GetMethod;
  38. import org.apache.commons.httpclient.methods.PostMethod;
  39. import org.apache.commons.httpclient.params.HttpConnectionParams;
  40. import org.apache.commons.httpclient.protocol.Protocol;
  41. import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;
  42.  
  43. /**
  44.  * @author Mykola Makhin
  45.  * @version 0.2
  46.  */
  47. public class RouterResetUtil extends JComponent {
  48.  
  49.         private static final long serialVersionUID = -6196217426008036402L;
  50.        
  51.         public static final int WAIT_TIME = 30000;
  52.  
  53.         public static void main(String[] args) {
  54.                 JFrame frame = new JFrame("Router resetter");
  55.                 frame.getContentPane().setLayout(new BorderLayout());
  56.                 frame.getContentPane().add(new RouterResetUtil(), BorderLayout.CENTER);
  57.                 frame.pack();
  58.                 frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
  59.                 frame.setVisible(true);        
  60.         }
  61.        
  62.         public RouterResetUtil() {
  63.                 initGui();
  64.                 initNet();
  65.         }
  66.        
  67.         protected void error(final Throwable t) {
  68.                 t.printStackTrace();
  69.                 SwingUtilities.invokeLater(new Runnable() {
  70.                         public void run() {
  71.                                 JOptionPane.showMessageDialog(RouterResetUtil.this, "Error "+t.getClass().getName()+" occured: "+t.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);                          
  72.                         }
  73.                 });
  74.         }
  75.        
  76.         protected SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss S");
  77.         protected void log(String message) {
  78.                 System.out.println("["+dateFormat.format(new Date())+"]: "+message);
  79.         }
  80.        
  81.         // ## GUI start
  82.         // TODO: move to separate GUI class
  83.         protected JPanel pnlRouterParams = new JPanel();
  84.         protected JTextField tfRouterHost = new JTextField("192.168.1.1");
  85.         protected JTextField tfRouterLogin = new JTextField("admin");
  86.         protected JPasswordField tfRouterPass = new JPasswordField("admin");
  87.         protected JComboBox cbProtocol = new JComboBox();
  88.         protected JPanel pnlStatusLog = new JPanel();
  89.         protected JTextField tfStatus = new JTextField();
  90.         protected JTextArea taLog = new JTextArea();
  91.         protected JButton btnSave = new JButton("Save");
  92.         protected JButton btnTest = new JButton("Test");
  93.        
  94.         protected ButtonsHandler buttonsHandler = new ButtonsHandler();
  95.         protected static final String ACT_SAVE = "ACT_SAVE";
  96.         protected static final String ACT_TEST = "ACT_TEST";
  97.        
  98.         public void initGui() {
  99.                
  100.                 // Init components
  101.                 cbProtocol.addItem("HTTP");
  102.                 cbProtocol.addItem("HTTPS");
  103.                 btnSave.addActionListener(buttonsHandler);
  104.                 btnSave.setActionCommand(ACT_SAVE);
  105.                 btnTest.addActionListener(buttonsHandler);
  106.                 btnTest.setActionCommand(ACT_TEST);
  107.                
  108.                 tfStatus.setEditable(false);
  109.                 taLog.setEditable(false);
  110.  
  111.                 // Init config panel
  112.                 pnlRouterParams.setLayout(new GridLayout(5,2));
  113.                 pnlRouterParams.add(new JLabel("Router host")); pnlRouterParams.add(tfRouterHost);
  114.                 pnlRouterParams.add(new JLabel("Protocol")); pnlRouterParams.add(cbProtocol);
  115.                 pnlRouterParams.add(new JLabel("Login")); pnlRouterParams.add(tfRouterLogin);
  116.                 pnlRouterParams.add(new JLabel("Password")); pnlRouterParams.add(tfRouterPass);
  117.                 pnlRouterParams.add(btnTest); pnlRouterParams.add(btnSave);
  118.                
  119.                 // Init status/log panel
  120.                 pnlStatusLog.setLayout(new BorderLayout());
  121.                 pnlStatusLog.add(tfStatus, BorderLayout.NORTH);
  122.                 pnlStatusLog.add(new JScrollPane(taLog), BorderLayout.CENTER);
  123.                
  124.                 this.setLayout(new BorderLayout());
  125.                 this.add(pnlRouterParams, BorderLayout.CENTER);
  126.                 this.setBorder(new EmptyBorder(10,10,10,10));
  127.         }
  128.  
  129.         // ## Handler start
  130.         protected class ButtonsHandler implements ActionListener {
  131.                 public void actionPerformed(ActionEvent actEvent) {
  132.                         String actionCommand = actEvent.getActionCommand();
  133.                        
  134.                         String routerHost = tfRouterHost.getText();
  135.                         boolean useHttps = cbProtocol.getSelectedItem().toString().toLowerCase().equals("https");
  136.                         String routerLogin = tfRouterLogin.getText();
  137.                         String routerPass = new String(tfRouterPass.getPassword());
  138.                        
  139.                         if(ACT_SAVE.equals(actionCommand)) {
  140.                                 RouterResetUtil.this.configureNet(routerHost, useHttps, routerLogin, routerPass);
  141.                                 if(RouterResetUtil.this.testRouterLogin()) RouterResetUtil.this.doSaveParams();
  142.                                 else JOptionPane.showMessageDialog(RouterResetUtil.this, "Connection error", "Error", JOptionPane.ERROR_MESSAGE);
  143.                         } else if(ACT_TEST.equals(actionCommand)) {
  144.                                 RouterResetUtil.this.configureNet(routerHost, useHttps, routerLogin, routerPass);
  145.                                 if(RouterResetUtil.this.testRouterLogin()) JOptionPane.showMessageDialog(RouterResetUtil.this, "Router connection OK", "Message", JOptionPane.INFORMATION_MESSAGE);
  146.                                 else JOptionPane.showMessageDialog(RouterResetUtil.this, "Connection error", "Error", JOptionPane.ERROR_MESSAGE);
  147.                         }
  148.                 }
  149.         }
  150.        
  151.         Thread monitorThread = null;
  152.         protected void doSaveParams() {
  153.                 this.removeAll();
  154.                 this.add(pnlStatusLog, BorderLayout.CENTER);
  155.                 this.invalidate();
  156.                 this.revalidate();
  157.                 if(monitorThread!=null) {
  158.                         try {
  159.                                 monitorThread.interrupt();
  160.                                 doStartMonitor();
  161.                         } catch (Throwable t) {
  162.                                 error(t);
  163.                         }
  164.                 } else {
  165.                         doStartMonitor();
  166.                 }
  167.                  
  168.         }
  169.        
  170.         protected void doStartMonitor() {
  171.                 monitorThread = new Thread(new MonitorResetter());
  172.                 monitorThread.setDaemon(true);
  173.                 monitorThread.start();                 
  174.                 this.setStatus("Monitoring started");
  175.                 this.logInfoMsg("Monitoring started");                         
  176.         }
  177.         // ## Handler end
  178.        
  179.         protected void setStatus(final String status) {
  180.                 SwingUtilities.invokeLater(new Runnable() {
  181.                         public void run() {
  182.                                 tfStatus.setText("["+dateFormat.format(new Date())+"]: "+status);
  183.                         }
  184.                 });
  185.         }
  186.        
  187.         protected void logInfoMsg(final String message) {
  188.                 SwingUtilities.invokeLater(new Runnable() {
  189.                         public void run() {
  190.                                 taLog.append("["+dateFormat.format(new Date())+"]: "+message+"\n");
  191.                         }
  192.                 });
  193.         }      
  194.         // ## GUI end
  195.  
  196.         // ## Netz start
  197.         protected void initSsl() {
  198.                 try {
  199.                        
  200.                         SSLContext context = SSLContext.getInstance("TLS");
  201.                         context.init(null, new TrustManager[] {new AllowAllTrustManager()}, new SecureRandom());
  202.                         /*
  203.                         javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
  204.                         context = SSLContext.getInstance("SSL");
  205.                         context.init(null, new TrustManager[] {new AllowAllTrustManager()}, new SecureRandom());
  206.                         javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
  207.                         */
  208.                         Protocol myhttps = new Protocol("https", new ProtocolSocketFactory() {
  209.                                 SSLSocketFactory socketFactory;
  210.                                
  211.                                 public ProtocolSocketFactory setSocketFactory(SSLSocketFactory socketFactory) {
  212.                                         this.socketFactory = socketFactory;
  213.                                         return this;
  214.                                 }
  215.  
  216.                                 public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
  217.                                         return socketFactory.createSocket(host, port);
  218.                                 }
  219.  
  220.                                 public Socket createSocket(String host, int port, InetAddress localAddress, int localPort) throws IOException, UnknownHostException {
  221.                                         return socketFactory.createSocket(host, port, localAddress, localPort);
  222.                                 }
  223.                                 public Socket createSocket(String host, int port, InetAddress localAddress, int localPort, HttpConnectionParams params) throws IOException, UnknownHostException,
  224.                                                 ConnectTimeoutException {
  225.                                         return socketFactory.createSocket(host, port, localAddress, localPort);
  226.                                 }
  227.                         }.setSocketFactory(context.getSocketFactory()), 443);
  228.                         Protocol.registerProtocol("https", myhttps);
  229.                 }catch(Throwable t) {
  230.                         t.printStackTrace();
  231.                 }              
  232.         }
  233.        
  234.         protected HttpClient httpClient;
  235.         protected GetMethod getGoogle = new GetMethod("http://www.google.com");
  236.         protected GetMethod getRouterStartPage = new GetMethod();
  237.         protected PostMethod postRouterDHCPRenew = new PostMethod();
  238.        
  239.         protected void initHttpClient() {
  240.                 MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
  241.                 httpClient = new HttpClient(connectionManager);
  242.                 httpClient.getParams().setConnectionManagerTimeout(12000L);
  243.                 httpClient.getParams().setSoTimeout(12000);
  244.                                
  245.                 postRouterDHCPRenew.addParameter("submit_type", "renew");
  246.                 postRouterDHCPRenew.addParameter("submit_button", "Status_Router");
  247.                 postRouterDHCPRenew.addParameter("change_action", "gozila_cgi");
  248.                 postRouterDHCPRenew.addParameter("dhcp_renew", "DHCP Renew");          
  249.         }
  250.        
  251.         protected void initNet() {
  252.                 initSsl();
  253.                 initHttpClient();
  254.         }
  255.        
  256.         protected void configureNet(String routerHost, boolean useHttps, String login, String pass) {
  257.                 Credentials credentials = new UsernamePasswordCredentials(login, pass);
  258.                 httpClient.getState().clearCredentials();
  259.                 httpClient.getState().setCredentials(new AuthScope(routerHost, AuthScope.ANY_PORT), credentials);
  260.                 //httpClient.getState().setCredentials(AuthScope.ANY, credentials);
  261.                 try {
  262.                         getRouterStartPage.setURI(new URI((useHttps? "https://" : "http://") + routerHost+"/index.asp", true));
  263.                         postRouterDHCPRenew.setURI(new URI((useHttps? "https://" : "http://") + routerHost+"/apply.cgi", true));
  264.                 } catch (Exception e) {
  265.                         error(e);
  266.                 }
  267.         }
  268.        
  269.         protected boolean testRouterLogin() {
  270.                 boolean result = false;
  271.                 try {
  272.                         log("Trying Router login");
  273.                         int rspCode = httpClient.executeMethod(getRouterStartPage);
  274.                         System.out.println(getRouterStartPage.getURI());
  275.                         if(rspCode>=200 && rspCode<300) {
  276.                                 result = true;
  277.                                 log("Router login seems successfull. Code: "+rspCode);
  278.                         } else {
  279.                                 log("Router login seems not OK. Code: "+rspCode+".\nResponse:\n"+getRouterStartPage.getResponseBodyAsString());
  280.                         }
  281.                 } catch (Throwable t) {
  282.                         error(t);
  283.                         log("!! Error loggin in to Router - "+t.getClass().getName()+": "+t.getMessage());
  284.                 } finally {
  285.                         getRouterStartPage.releaseConnection();
  286.         }
  287.                 return result;
  288.         }
  289.        
  290.         protected boolean testInetConnection() {
  291.                 boolean connected = false;                     
  292.                 try {
  293.                         log("Testing Inet connection");
  294.                         int responseCode = httpClient.executeMethod(getGoogle);
  295.                         byte[] responseBytes = getGoogle.getResponseBody();
  296.                         String responseText = new String(responseBytes, getGoogle.getResponseCharSet());
  297.  
  298.                         if(responseCode<200 || responseCode>=300 || responseText.indexOf("<title>Google</title>")<0) {
  299.                                 if(responseCode<200 || responseCode>=300) {
  300.                                         log("Wrong response code from google.com");
  301.                                 } else {
  302.                                         log("Suspicious response text from google.com");
  303.                                 }
  304.                                 log("Response code: "+responseCode+"\nResponse text:"+responseText);
  305.                         }
  306.                         connected = true;
  307.                         log("Inet connection OK");
  308.                 } catch(UnknownHostException unknownHostException) {
  309.                         connected = false; // Superficial. Well, whatever...
  310.                         unknownHostException.printStackTrace();
  311.                         log("Unknown host exception for www.google.com - obvious DNS failure");
  312.                         log(unknownHostException.getClass().getName()+": "+unknownHostException.getMessage());
  313.                 } catch(Throwable err) {
  314.                         err.printStackTrace();
  315.                         log("Error on testing Inet connection: "+err.getMessage());
  316.                         log(err.getClass().getName()+": "+err.getMessage());
  317.                 }  finally {
  318.                         getGoogle.releaseConnection();
  319.         }
  320.                 return connected;              
  321.         }
  322.        
  323.         private boolean resetInternetConnection() {
  324.                 boolean done = false;
  325.                 try {
  326.                         log("Resetting Inet connection");
  327.                        
  328.                         if(!testRouterLogin()) log("Warning - router login error!");
  329.                        
  330.                         int responseCode = httpClient.executeMethod(postRouterDHCPRenew);
  331.                         byte[] responseBytes = postRouterDHCPRenew.getResponseBody();
  332.                         String responseText = new String(responseBytes, postRouterDHCPRenew.getResponseCharSet());
  333.                         if(responseCode<200 || responseCode>=300 || responseText.indexOf(">0.0.0.0<")>=0) {
  334.                                 if(responseCode<200 || responseCode>=300) {
  335.                                         log("Wrong response code from Router");
  336.                                 } else {
  337.                                         log("Zero IPs in response text from Router");
  338.                                 }
  339.                                 log("Router response code: "+responseCode+"\nRouter response text:"+responseText);
  340.                                 log("Resetting Inet connection unsuccessfull");
  341.                         } else {
  342.                                 done = true;   
  343.                                 log("Resetting Inet connection seems successfull");
  344.                         }
  345.                 } catch (Throwable err) {
  346.                         err.printStackTrace();
  347.                         log("Error on resetting Inet connection: "+err.getMessage());
  348.                         log(err.getClass().getName()+": "+err.getMessage());                   
  349.                 } finally {
  350.                         postRouterDHCPRenew.releaseConnection();
  351.                 }
  352.                 return done;
  353.         }      
  354.         // ## Netz end 
  355.        
  356.         protected enum TheCode { GREEN, YELLOW, RED};
  357.         protected class MonitorResetter implements Runnable {
  358.  
  359.                 protected TheCode code = TheCode.GREEN;
  360.                
  361.                 public void run() {
  362.                         while(true) {
  363.                                 if(!RouterResetUtil.this.testInetConnection()) {
  364.                                         log("!! Internet connection failure suspected");
  365.                                         setStatus("YELLOW: Connection failure suspected");
  366.                                         if(code.equals(TheCode.GREEN)) {
  367.                                                 code = TheCode.YELLOW;
  368.                                                 log("!! Code YELLOW");
  369.                                         } else if(code.equals(TheCode.YELLOW)) {
  370.                                                 code = TheCode.RED;
  371.                                                 log("!! Code RED");
  372.                                                 log("!! Internet connection failure detected");
  373.                                                 setStatus("RED: Connection failure detected!");
  374.                                                 logInfoMsg("Connection failure detected");
  375.                                         }
  376.                                        
  377.                                         if(code.equals(TheCode.RED)) {
  378.                                                 log("!! Resetting Inet connection");
  379.                                                 if(resetInternetConnection()) {
  380.                                                         code = TheCode.YELLOW;
  381.                                                         log("!! Connection reset\nCode YELLOW");
  382.                                                         setStatus("YELLOW: Connection reset");
  383.                                                         logInfoMsg("Connection reset attempt");
  384.                                                 } else {
  385.                                                         log("!! Failed to reset connection\nCode RED");
  386.                                                         setStatus("RED: Failed to reset connection!!!");
  387.                                                         logInfoMsg("Failed to reset connection!");
  388.                                                 }
  389.                                         }
  390.                                 } else {
  391.                                         if(!code.equals(TheCode.GREEN)) {
  392.                                                 if(code.equals(TheCode.RED)) {
  393.                                                         code = TheCode.YELLOW;
  394.                                                         log("!! Internet connection seems OK now by itself\nCode YELLOW");
  395.                                                         setStatus("YELLOW: Connection seems OK by itself");
  396.                                                 } else {
  397.                                                         code = TheCode.GREEN;
  398.                                                         log("!! Internet connection is OK\nCode GREEN");
  399.                                                         setStatus("GREEN: Connection is now OK");
  400.                                                         logInfoMsg("Connection is now OK");
  401.                                                 }
  402.                                         } else {
  403.                                                 log("Connection Ok");
  404.                                                 setStatus("GREEN: Connection is OK");
  405.                                         }
  406.                                 }
  407.  
  408.                                 try {
  409.                                         if(code.equals(TheCode.GREEN))
  410.                                                 Thread.sleep(WAIT_TIME);
  411.                                         else
  412.                                                 Thread.sleep(WAIT_TIME/4);
  413.                                 } catch (InterruptedException e) {
  414.                                         log("!! We've been interrupted");
  415.                                         log("InterruptedException");
  416.                                         break;
  417.                                 } catch (Exception e) {
  418.                                         log("!! Thread insomnia");
  419.                                         log(e.getClass().getName()+": "+e.getMessage());
  420.                                         break;                                         
  421.                                 }
  422.                         }
  423.                 }
  424.                
  425.         }
  426.        
  427.         public static class AllowAllTrustManager implements javax.net.ssl.TrustManager, javax.net.ssl.X509TrustManager {
  428.                 public java.security.cert.X509Certificate[] getAcceptedIssuers() {
  429.                         return null;
  430.                 }
  431.  
  432.                 public boolean isServerTrusted(java.security.cert.X509Certificate[] certs) {
  433.                         return true;
  434.                 }
  435.  
  436.                 public boolean isClientTrusted(java.security.cert.X509Certificate[] certs) {
  437.                         return true;
  438.                 }
  439.  
  440.                 public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) throws java.security.cert.CertificateException {
  441.                         return;
  442.                 }
  443.  
  444.                 public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) throws java.security.cert.CertificateException {
  445.                         return;
  446.                 }
  447.         }      
  448.        
  449. }
Submit a correction or amendment below. [ previous version ] | [ difference ] | Make A New Post
To highlight particular lines, prefix each line with @h@
Syntax highlighting:
Post expiration:
Post exposure:
Name / Title:
Email: