code stringlengths 3 1.18M | language stringclasses 1
value |
|---|---|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package _bai02_phantichphankhaibao;
/**
* Các thông tin về lỗi của phần khai báo
* @author Administrator
*/
public enum jEnum_Loi {
CacBienTrungTen ("Tồn tại tham số hoặc giá trị trả về trùng tên nhau!"),
ChuoiKhaiBaoSaiDinhDang ("Chuổi khai báo sai định dạng! Vui lòng xem lại!"),
KieuDuLieuKhongDuocHoTro ("Hiện chỉ hộ trở các kiểu N, N1, R, B, Char và kiểu mảng!"),
KhongCoLoi ("");
private final String value;
jEnum_Loi(String value) {
this.value = value;
}
String value(){
return this.value;
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package _bai02_phantichphankhaibao;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
*
* @author Administrator
*/
public class jClass_GiaTri {
public static Boolean jKiemTraChuoiHopDinhDang(String str_ChuoiCanKienTra) {
Pattern pat=Pattern.compile(jEnum_ChuoiDinhDang.GiaTri.value());
Matcher matcher =pat.matcher(str_ChuoiCanKienTra);
return matcher.matches();
}
}
| Java |
/*
* _Bai02_PhanTichPhanKhaiBaoAboutBox.java
*/
package _bai02_phantichphankhaibao;
import org.jdesktop.application.Action;
public class _Bai02_PhanTichPhanKhaiBaoAboutBox extends javax.swing.JDialog {
public _Bai02_PhanTichPhanKhaiBaoAboutBox(java.awt.Frame parent) {
super(parent);
initComponents();
getRootPane().setDefaultButton(closeButton);
}
@Action public void closeAboutBox() {
dispose();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
closeButton = new javax.swing.JButton();
javax.swing.JLabel appTitleLabel = new javax.swing.JLabel();
javax.swing.JLabel versionLabel = new javax.swing.JLabel();
javax.swing.JLabel appVersionLabel = new javax.swing.JLabel();
javax.swing.JLabel vendorLabel = new javax.swing.JLabel();
javax.swing.JLabel appVendorLabel = new javax.swing.JLabel();
javax.swing.JLabel homepageLabel = new javax.swing.JLabel();
javax.swing.JLabel appHomepageLabel = new javax.swing.JLabel();
javax.swing.JLabel appDescLabel = new javax.swing.JLabel();
javax.swing.JLabel imageLabel = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(_bai02_phantichphankhaibao._Bai02_PhanTichPhanKhaiBaoApp.class).getContext().getResourceMap(_Bai02_PhanTichPhanKhaiBaoAboutBox.class);
setTitle(resourceMap.getString("title")); // NOI18N
setModal(true);
setName("aboutBox"); // NOI18N
setResizable(false);
javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(_bai02_phantichphankhaibao._Bai02_PhanTichPhanKhaiBaoApp.class).getContext().getActionMap(_Bai02_PhanTichPhanKhaiBaoAboutBox.class, this);
closeButton.setAction(actionMap.get("closeAboutBox")); // NOI18N
closeButton.setName("closeButton"); // NOI18N
appTitleLabel.setFont(appTitleLabel.getFont().deriveFont(appTitleLabel.getFont().getStyle() | java.awt.Font.BOLD, appTitleLabel.getFont().getSize()+4));
appTitleLabel.setText(resourceMap.getString("Application.title")); // NOI18N
appTitleLabel.setName("appTitleLabel"); // NOI18N
versionLabel.setFont(versionLabel.getFont().deriveFont(versionLabel.getFont().getStyle() | java.awt.Font.BOLD));
versionLabel.setText(resourceMap.getString("versionLabel.text")); // NOI18N
versionLabel.setName("versionLabel"); // NOI18N
appVersionLabel.setText(resourceMap.getString("Application.version")); // NOI18N
appVersionLabel.setName("appVersionLabel"); // NOI18N
vendorLabel.setFont(vendorLabel.getFont().deriveFont(vendorLabel.getFont().getStyle() | java.awt.Font.BOLD));
vendorLabel.setText(resourceMap.getString("vendorLabel.text")); // NOI18N
vendorLabel.setName("vendorLabel"); // NOI18N
appVendorLabel.setText(resourceMap.getString("Application.vendor")); // NOI18N
appVendorLabel.setName("appVendorLabel"); // NOI18N
homepageLabel.setFont(homepageLabel.getFont().deriveFont(homepageLabel.getFont().getStyle() | java.awt.Font.BOLD));
homepageLabel.setText(resourceMap.getString("homepageLabel.text")); // NOI18N
homepageLabel.setName("homepageLabel"); // NOI18N
appHomepageLabel.setText(resourceMap.getString("Application.homepage")); // NOI18N
appHomepageLabel.setName("appHomepageLabel"); // NOI18N
appDescLabel.setText(resourceMap.getString("appDescLabel.text")); // NOI18N
appDescLabel.setName("appDescLabel"); // NOI18N
imageLabel.setIcon(resourceMap.getIcon("imageLabel.icon")); // NOI18N
imageLabel.setName("imageLabel"); // NOI18N
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(imageLabel)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(versionLabel)
.addComponent(vendorLabel)
.addComponent(homepageLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(appVersionLabel)
.addComponent(appVendorLabel)
.addComponent(appHomepageLabel)))
.addComponent(appTitleLabel, javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(appDescLabel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 266, Short.MAX_VALUE)
.addComponent(closeButton))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(imageLabel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(appTitleLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(appDescLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(versionLabel)
.addComponent(appVersionLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(vendorLabel)
.addComponent(appVendorLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(homepageLabel)
.addComponent(appHomepageLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 19, Short.MAX_VALUE)
.addComponent(closeButton)
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton closeButton;
// End of variables declaration//GEN-END:variables
}
| Java |
/*
* _Bai02_PhanTichPhanKhaiBaoApp.java
*/
package _bai02_phantichphankhaibao;
import org.jdesktop.application.Application;
import org.jdesktop.application.SingleFrameApplication;
/**
* The main class of the application.
*/
public class _Bai02_PhanTichPhanKhaiBaoApp extends SingleFrameApplication {
/**
* At startup create and show the main frame of the application.
*/
@Override protected void startup() {
show(new _Bai02_PhanTichPhanKhaiBaoView(this));
}
/**
* This method is to initialize the specified window by injecting resources.
* Windows shown in our application come fully initialized from the GUI
* builder, so this additional configuration is not needed.
*/
@Override protected void configureWindow(java.awt.Window root) {
}
/**
* A convenient static getter for the application instance.
* @return the instance of _Bai02_PhanTichPhanKhaiBaoApp
*/
public static _Bai02_PhanTichPhanKhaiBaoApp getApplication() {
return Application.getInstance(_Bai02_PhanTichPhanKhaiBaoApp.class);
}
/**
* Main method launching the application.
*/
public static void main(String[] args) {
launch(_Bai02_PhanTichPhanKhaiBaoApp.class, args);
}
}
| Java |
/*
* _Bai02_PhanTichPhanKhaiBaoView.java
*/
package _bai02_phantichphankhaibao;
import java.awt.Color;
import java.io.FileNotFoundException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jdesktop.application.Action;
import org.jdesktop.application.ResourceMap;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.FrameView;
import org.jdesktop.application.TaskMonitor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import javax.swing.Timer;
import javax.swing.Icon;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.text.MutableAttributeSet;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
/**
* The application's main frame.
*/
public class _Bai02_PhanTichPhanKhaiBaoView extends FrameView {
private jClass_CacStyleChuoi cacStyleChuoi = new jClass_CacStyleChuoi();
public _Bai02_PhanTichPhanKhaiBaoView(SingleFrameApplication app) {
super(app);
initComponents();
toMau_HighlightSyntax();
// status bar initialization - message timeout, idle icon and busy animation, etc
ResourceMap resourceMap = getResourceMap();
int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
messageTimer = new Timer(messageTimeout, new ActionListener() {
public void actionPerformed(ActionEvent e) {
statusMessageLabel.setText("");
}
});
messageTimer.setRepeats(false);
int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
for (int i = 0; i < busyIcons.length; i++) {
busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
}
busyIconTimer = new Timer(busyAnimationRate, new ActionListener() {
public void actionPerformed(ActionEvent e) {
busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
}
});
idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
statusAnimationLabel.setIcon(idleIcon);
progressBar.setVisible(false);
// connecting action tasks to status bar via TaskMonitor
TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
public void propertyChange(java.beans.PropertyChangeEvent evt) {
String propertyName = evt.getPropertyName();
if ("started".equals(propertyName)) {
if (!busyIconTimer.isRunning()) {
statusAnimationLabel.setIcon(busyIcons[0]);
busyIconIndex = 0;
busyIconTimer.start();
}
progressBar.setVisible(true);
progressBar.setIndeterminate(true);
} else if ("done".equals(propertyName)) {
busyIconTimer.stop();
statusAnimationLabel.setIcon(idleIcon);
progressBar.setVisible(false);
progressBar.setValue(0);
} else if ("message".equals(propertyName)) {
String text = (String)(evt.getNewValue());
statusMessageLabel.setText((text == null) ? "" : text);
messageTimer.restart();
} else if ("progress".equals(propertyName)) {
int value = (Integer)(evt.getNewValue());
progressBar.setVisible(true);
progressBar.setIndeterminate(false);
progressBar.setValue(value);
}
}
});
}
@Action
public void showAboutBox() {
if (aboutBox == null) {
JFrame mainFrame = _Bai02_PhanTichPhanKhaiBaoApp.getApplication().getMainFrame();
aboutBox = new _Bai02_PhanTichPhanKhaiBaoAboutBox(mainFrame);
aboutBox.setLocationRelativeTo(mainFrame);
}
_Bai02_PhanTichPhanKhaiBaoApp.getApplication().show(aboutBox);
}
private boolean caretCapNhat() throws NumberFormatException {
// TODO add your handling code here:
jClass_PhanKhaiBao jPKB_PhanKhaiBao = new jClass_PhanKhaiBao();
//Boolean b_HopDinhDang = jPKB_PhanKhaiBao.jKiemTraChuoiHopDinhDang(jTextPane_PhanNhapKhaiBao.getText());
jClass_Loi jCL_Loi = jPKB_PhanKhaiBao.jKiemTraLoiCuaBieuThucDuocNhap(jTextPane_PhanNhapKhaiBao.getText().trim().split("\n")[0]);
if (jCL_Loi.getMoTa() == jEnum_Loi.KhongCoLoi) {
//jPKB_PhanKhaiBao.jCapNhatTuChuoi(jTextPane_PhanNhapKhaiBao.getText());
//jButton_PhanTich.setEnabled(true);
jLabel_ThongBaoLoi.setVisible(false);
} else {
//Nếu có lỗi
//jButton_PhanTich.setEnabled(false);
jLabel_ThongBaoLoi.setVisible(true);
jLabel_ThongBaoLoi.setText(jCL_Loi.getMoTa().value());
if (jCL_Loi.getMoTa() == jEnum_Loi.ChuoiKhaiBaoSaiDinhDang) {
return true;
}
jClass_Bien jB_BienCoLoi = jPKB_PhanKhaiBao.getGiaTriTraVe();
//Lấy stt biến có lỗi từ thông tin bổ sung của lỗi
int i_STTBienCoLoi = Integer.valueOf(jCL_Loi.getThongTinBoSung());
if (i_STTBienCoLoi != -1) {
//Biến bị trùng tên không phải giá trị trả về
jB_BienCoLoi = jPKB_PhanKhaiBao.getCacThamSo().get(i_STTBienCoLoi);
}
if (jCL_Loi.getMoTa() == jEnum_Loi.CacBienTrungTen) {
//Tô màu tên biến có lỗi
toMau_LoiTrungTenBien(jB_BienCoLoi.getTen());
}
if (jCL_Loi.getMoTa() == jEnum_Loi.KieuDuLieuKhongDuocHoTro) {
//Tô màu kiểu dữ liệu có lỗi
toMau_LoiKieuDuLieu(jB_BienCoLoi);
}
}
return false;
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
mainPanel = new javax.swing.JPanel();
jPanel1 = new javax.swing.JPanel();
jScrollPane5 = new javax.swing.JScrollPane();
jScrollPane1 = new javax.swing.JScrollPane();
jTextPane_PhanNhapKhaiBao = new javax.swing.JTextPane();
jLabel1 = new javax.swing.JLabel();
jPanel2 = new javax.swing.JPanel();
jScrollPane2 = new javax.swing.JScrollPane();
jTextPane_PhanKetQuaPhanTich = new javax.swing.JTextPane();
jPanel3 = new javax.swing.JPanel();
jButton_PhanTich = new javax.swing.JButton();
jButton_MoFile = new javax.swing.JButton();
jButton_Luu = new javax.swing.JButton();
jComboBox_ViDuMau = new javax.swing.JComboBox();
jButton_PhanTich1 = new javax.swing.JButton();
jLabel_ThongBaoLoi = new javax.swing.JLabel();
jButton_Thoat = new javax.swing.JButton();
jPanel_Code = new javax.swing.JPanel();
jScrollPane4 = new javax.swing.JScrollPane();
jScrollPane3 = new javax.swing.JScrollPane();
jTextPane_PhanCodeDuocTao = new javax.swing.JTextPane();
jCheckBox_TaoHamMain = new javax.swing.JCheckBox();
menuBar = new javax.swing.JMenuBar();
javax.swing.JMenu fileMenu = new javax.swing.JMenu();
javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem();
javax.swing.JMenu helpMenu = new javax.swing.JMenu();
javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem();
statusPanel = new javax.swing.JPanel();
javax.swing.JSeparator statusPanelSeparator = new javax.swing.JSeparator();
statusMessageLabel = new javax.swing.JLabel();
statusAnimationLabel = new javax.swing.JLabel();
progressBar = new javax.swing.JProgressBar();
mainPanel.setName("mainPanel"); // NOI18N
org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(_bai02_phantichphankhaibao._Bai02_PhanTichPhanKhaiBaoApp.class).getContext().getResourceMap(_Bai02_PhanTichPhanKhaiBaoView.class);
jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("jPanel1.border.title"))); // NOI18N
jPanel1.setName("jPanel1"); // NOI18N
jScrollPane5.setBorder(null);
jScrollPane5.setAutoscrolls(true);
jScrollPane5.setName("jScrollPane5"); // NOI18N
jScrollPane5.setPreferredSize(new java.awt.Dimension(500, 50));
jScrollPane1.setAutoscrolls(true);
jScrollPane1.setName("jScrollPane1"); // NOI18N
jScrollPane1.setPreferredSize(new java.awt.Dimension(500, 22));
jTextPane_PhanNhapKhaiBao.setText(resourceMap.getString("jTextPane_PhanNhapKhaiBao.text")); // NOI18N
jTextPane_PhanNhapKhaiBao.setName("jTextPane_PhanNhapKhaiBao"); // NOI18N
jTextPane_PhanNhapKhaiBao.setPreferredSize(new java.awt.Dimension(500, 20));
jTextPane_PhanNhapKhaiBao.addCaretListener(new javax.swing.event.CaretListener() {
public void caretUpdate(javax.swing.event.CaretEvent evt) {
jTextPane_PhanNhapKhaiBaoCaretUpdate(evt);
}
});
jTextPane_PhanNhapKhaiBao.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
public void propertyChange(java.beans.PropertyChangeEvent evt) {
jTextPane_PhanNhapKhaiBaoPropertyChange(evt);
}
});
jTextPane_PhanNhapKhaiBao.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
jTextPane_PhanNhapKhaiBaoKeyReleased(evt);
}
});
jScrollPane1.setViewportView(jTextPane_PhanNhapKhaiBao);
jScrollPane5.setViewportView(jScrollPane1);
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jScrollPane5, javax.swing.GroupLayout.PREFERRED_SIZE, 338, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(53, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane5, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 243, Short.MAX_VALUE)
);
jLabel1.setFont(resourceMap.getFont("jLabel1.font")); // NOI18N
jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
jLabel1.setName("jLabel1"); // NOI18N
jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("jPanel2.border.title"))); // NOI18N
jPanel2.setName("jPanel2"); // NOI18N
jScrollPane2.setName("jScrollPane2"); // NOI18N
jTextPane_PhanKetQuaPhanTich.setEditable(false);
jTextPane_PhanKetQuaPhanTich.setName("jTextPane_PhanKetQuaPhanTich"); // NOI18N
jScrollPane2.setViewportView(jTextPane_PhanKetQuaPhanTich);
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 370, Short.MAX_VALUE)
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 95, Short.MAX_VALUE)
);
jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("jPanel3.border.title"))); // NOI18N
jPanel3.setName("jPanel3"); // NOI18N
jButton_PhanTich.setText(resourceMap.getString("jButton_PhanTich.text")); // NOI18N
jButton_PhanTich.setName("jButton_PhanTich"); // NOI18N
jButton_PhanTich.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_PhanTichActionPerformed(evt);
}
});
jButton_MoFile.setText(resourceMap.getString("jButton_MoFile.text")); // NOI18N
jButton_MoFile.setName("jButton_MoFile"); // NOI18N
jButton_MoFile.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_MoFileActionPerformed(evt);
}
});
jButton_Luu.setText(resourceMap.getString("jButton_Luu.text")); // NOI18N
jButton_Luu.setName("jButton_Luu"); // NOI18N
jButton_Luu.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_LuuActionPerformed(evt);
}
});
jComboBox_ViDuMau.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Bài 1", "Bài 2", " " }));
jComboBox_ViDuMau.setName("jComboBox_ViDuMau"); // NOI18N
jComboBox_ViDuMau.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox_ViDuMauActionPerformed(evt);
}
});
jButton_PhanTich1.setText(resourceMap.getString("jButton_PhanTich1.text")); // NOI18N
jButton_PhanTich1.setName("jButton_PhanTich1"); // NOI18N
jButton_PhanTich1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_PhanTich1ActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jButton_MoFile)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton_Luu)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jComboBox_ViDuMau, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(149, 149, 149)
.addComponent(jButton_PhanTich1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton_PhanTich)))
.addContainerGap(21, Short.MAX_VALUE))
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton_MoFile, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton_Luu, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jComboBox_ViDuMau, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(58, 58, 58)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton_PhanTich1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton_PhanTich, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
);
jLabel_ThongBaoLoi.setForeground(resourceMap.getColor("jLabel_ThongBaoLoi.foreground")); // NOI18N
jLabel_ThongBaoLoi.setText(resourceMap.getString("jLabel_ThongBaoLoi.text")); // NOI18N
jLabel_ThongBaoLoi.setName("jLabel_ThongBaoLoi"); // NOI18N
javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(_bai02_phantichphankhaibao._Bai02_PhanTichPhanKhaiBaoApp.class).getContext().getActionMap(_Bai02_PhanTichPhanKhaiBaoView.class, this);
jButton_Thoat.setAction(actionMap.get("quit")); // NOI18N
jButton_Thoat.setText(resourceMap.getString("jButton_Thoat.text")); // NOI18N
jButton_Thoat.setName("jButton_Thoat"); // NOI18N
jPanel_Code.setBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("jPanel_Code.border.title"))); // NOI18N
jPanel_Code.setAutoscrolls(true);
jPanel_Code.setName("jPanel_Code"); // NOI18N
jPanel_Code.setPreferredSize(new java.awt.Dimension(4, 5));
jScrollPane4.setName("jScrollPane4"); // NOI18N
jScrollPane3.setName("jScrollPane3"); // NOI18N
jScrollPane3.setPreferredSize(new java.awt.Dimension(5000, 10000));
jTextPane_PhanCodeDuocTao.setEditable(false);
jTextPane_PhanCodeDuocTao.setMinimumSize(new java.awt.Dimension(2000, 2000));
jTextPane_PhanCodeDuocTao.setName("jTextPane_PhanCodeDuocTao"); // NOI18N
jTextPane_PhanCodeDuocTao.setPreferredSize(new java.awt.Dimension(2000, 2000));
jScrollPane3.setViewportView(jTextPane_PhanCodeDuocTao);
jScrollPane4.setViewportView(jScrollPane3);
javax.swing.GroupLayout jPanel_CodeLayout = new javax.swing.GroupLayout(jPanel_Code);
jPanel_Code.setLayout(jPanel_CodeLayout);
jPanel_CodeLayout.setHorizontalGroup(
jPanel_CodeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane4, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 431, Short.MAX_VALUE)
);
jPanel_CodeLayout.setVerticalGroup(
jPanel_CodeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 504, Short.MAX_VALUE)
);
jCheckBox_TaoHamMain.setSelected(true);
jCheckBox_TaoHamMain.setText(resourceMap.getString("jCheckBox_TaoHamMain.text")); // NOI18N
jCheckBox_TaoHamMain.setToolTipText(resourceMap.getString("jCheckBox_TaoHamMain.toolTipText")); // NOI18N
jCheckBox_TaoHamMain.setName("jCheckBox_TaoHamMain"); // NOI18N
javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
mainPanel.setLayout(mainPanelLayout);
mainPanelLayout.setHorizontalGroup(
mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(mainPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 866, Short.MAX_VALUE)
.addGroup(mainPanelLayout.createSequentialGroup()
.addComponent(jLabel_ThongBaoLoi)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jPanel2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel3, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(mainPanelLayout.createSequentialGroup()
.addComponent(jCheckBox_TaoHamMain, javax.swing.GroupLayout.DEFAULT_SIZE, 352, Short.MAX_VALUE)
.addGap(15, 15, 15)
.addComponent(jButton_Thoat, javax.swing.GroupLayout.DEFAULT_SIZE, 86, Short.MAX_VALUE))
.addGroup(mainPanelLayout.createSequentialGroup()
.addGap(6, 6, 6)
.addComponent(jPanel_Code, javax.swing.GroupLayout.DEFAULT_SIZE, 447, Short.MAX_VALUE)))))
.addContainerGap())
);
mainPanelLayout.setVerticalGroup(
mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, mainPanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, mainPanelLayout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(mainPanelLayout.createSequentialGroup()
.addGap(11, 11, 11)
.addComponent(jLabel_ThongBaoLoi, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(mainPanelLayout.createSequentialGroup()
.addGap(25, 25, 25)
.addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, mainPanelLayout.createSequentialGroup()
.addComponent(jPanel_Code, javax.swing.GroupLayout.DEFAULT_SIZE, 534, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jCheckBox_TaoHamMain, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton_Thoat, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
.addGap(18, 18, 18))
);
jLabel_ThongBaoLoi.getAccessibleContext().setAccessibleName(resourceMap.getString("jLabel2.AccessibleContext.accessibleName")); // NOI18N
menuBar.setName("menuBar"); // NOI18N
fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N
fileMenu.setName("fileMenu"); // NOI18N
exitMenuItem.setAction(actionMap.get("quit")); // NOI18N
exitMenuItem.setName("exitMenuItem"); // NOI18N
fileMenu.add(exitMenuItem);
menuBar.add(fileMenu);
helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N
helpMenu.setName("helpMenu"); // NOI18N
aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N
aboutMenuItem.setName("aboutMenuItem"); // NOI18N
helpMenu.add(aboutMenuItem);
menuBar.add(helpMenu);
statusPanel.setName("statusPanel"); // NOI18N
statusPanelSeparator.setName("statusPanelSeparator"); // NOI18N
statusMessageLabel.setName("statusMessageLabel"); // NOI18N
statusAnimationLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
statusAnimationLabel.setName("statusAnimationLabel"); // NOI18N
progressBar.setName("progressBar"); // NOI18N
javax.swing.GroupLayout statusPanelLayout = new javax.swing.GroupLayout(statusPanel);
statusPanel.setLayout(statusPanelLayout);
statusPanelLayout.setHorizontalGroup(
statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(statusPanelSeparator, javax.swing.GroupLayout.DEFAULT_SIZE, 886, Short.MAX_VALUE)
.addGroup(statusPanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(statusMessageLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 716, Short.MAX_VALUE)
.addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(statusAnimationLabel)
.addContainerGap())
);
statusPanelLayout.setVerticalGroup(
statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(statusPanelLayout.createSequentialGroup()
.addComponent(statusPanelSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(statusMessageLabel)
.addComponent(statusAnimationLabel)
.addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(3, 3, 3))
);
setComponent(mainPanel);
setMenuBar(menuBar);
setStatusBar(statusPanel);
}// </editor-fold>//GEN-END:initComponents
private void jButton_PhanTichActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_PhanTichActionPerformed
//Lay Chuoi duoc nhap
String Str_KhaiBao = jTextPane_PhanNhapKhaiBao.getText();
/* jClass_PhanKhaiBao jPKB_KhaiBao = new jClass_PhanKhaiBao();
if (jPKB_KhaiBao.jKiemTraLoiCuaBieuThucDuocNhap(Str_KhaiBao).getMoTa() != jEnum_Loi.KhongCoLoi){
JOptionPane.showMessageDialog(null, "Có lỗi trong phần dữ liệu đầu vào. Xin kiểm tra lại!");
return;
}
//Lay Chuoi Ket Qua de xuat ra man hinh
String Str_KetQua = jPKB_KhaiBao.toString();
jTextPane_PhanKetQuaPhanTich.setText(Str_KetQua);
jClass_PhanDacTa jPDT_DacTa = new jClass_PhanDacTa();
jPDT_DacTa.setPhanKhaiBao(jPKB_KhaiBao);
String str_Code = jClass_BoTaoCode.jTaoCode(jPDT_DacTa);
// if (jCheckBox_TaoHamMain.isSelected())
*/
String str_Code = phatSinhCode(Str_KhaiBao);
jTextPane_PhanCodeDuocTao.setText(str_Code);
}//GEN-LAST:event_jButton_PhanTichActionPerformed
private String phatSinhCode (String dacTa){
String Kq = "";
jClass_PhanDacTa phanDacTa = new jClass_PhanDacTa();
phanDacTa.jCapNhatTuChuoi(dacTa);
Kq = phanDacTa.jToCCode(0);
return Kq;
}
private String phatSinhCodeCS(String dacTa){
String Kq = "";
jClass_PhanDacTa phanDacTa = new jClass_PhanDacTa();
phanDacTa.jCapNhatTuChuoi(dacTa);
Kq = phanDacTa.jCSharpCode(0);
return Kq;
}
private File moDialogChonFile()
{
File Kq = null;
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
fileChooser.setCurrentDirectory(new File(".").getAbsoluteFile().getParentFile());
int ketQuaShowOpenDialog = fileChooser.showOpenDialog(null);
if (ketQuaShowOpenDialog == JFileChooser.APPROVE_OPTION){
Kq = fileChooser.getSelectedFile();
}
return Kq;
}
static public String getContents(File aFile) {
//...checks on aFile are elided
StringBuilder contents = new StringBuilder();
try {
//use buffering, reading one line at a time
//FileReader always assumes default encoding is OK!
BufferedReader input = new BufferedReader(new FileReader(aFile));
try {
String line = null; //not declared within while loop
/*
* readLine is a bit quirky :
* it returns the content of a line MINUS the newline.
* it returns null only for the END of the stream.
* it returns an empty String if two newlines appear in a row.
*/
while (( line = input.readLine()) != null){
contents.append(line);
contents.append(System.getProperty("line.separator"));
}
}
finally {
input.close();
}
}
catch (IOException ex){
ex.printStackTrace();
}
return contents.toString();
}
private void jButton_MoFileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_MoFileActionPerformed
// TODO add your handling code here:
File file = moDialogChonFile();
if (file != null){
String content = getContents(file);
jTextPane_PhanNhapKhaiBao.setText(content);
toMau_HighlightSyntax();
caretCapNhat();
}
}//GEN-LAST:event_jButton_MoFileActionPerformed
private void jTextPane_PhanNhapKhaiBaoPropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_jTextPane_PhanNhapKhaiBaoPropertyChange
// TODO add your handling code here:
}//GEN-LAST:event_jTextPane_PhanNhapKhaiBaoPropertyChange
private void jTextPane_PhanNhapKhaiBaoKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextPane_PhanNhapKhaiBaoKeyReleased
// TODO add your handling code here:
toMau_TraTatCaVeDangChuThuong();
toMau_HighlightSyntax();
jTextPane_PhanNhapKhaiBaoCaretUpdate(null);
}//GEN-LAST:event_jTextPane_PhanNhapKhaiBaoKeyReleased
private void jTextPane_PhanNhapKhaiBaoCaretUpdate(javax.swing.event.CaretEvent evt) {//GEN-FIRST:event_jTextPane_PhanNhapKhaiBaoCaretUpdate
//jPKB_PhanKhaiBao.jCapNhatTuChuoi(jTextPane_PhanNhapKhaiBao.getText());
if (caretCapNhat())return;
}//GEN-LAST:event_jTextPane_PhanNhapKhaiBaoCaretUpdate
static public void setContents(File aFile, String string) {
//...checks on aFile are elided
StringBuilder contents = new StringBuilder();
try {
//use buffering, reading one line at a time
//FileReader always assumes default encoding is OK!
BufferedWriter output = new BufferedWriter(new FileWriter(aFile));
try {
output.write(string, 0, string.length());
}
finally {
output.close();
}
}
catch (IOException ex){
ex.printStackTrace();
}
}
private void jButton_LuuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_LuuActionPerformed
// TODO add your handling code here:
File Kq = null;
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
fileChooser.setCurrentDirectory(new File(".").getAbsoluteFile().getParentFile());
int ketQuaShowOpenDialog = fileChooser.showSaveDialog(null);
if (ketQuaShowOpenDialog == JFileChooser.APPROVE_OPTION){
Kq = fileChooser.getSelectedFile();
setContents(Kq, jTextPane_PhanCodeDuocTao.getText());
}
}//GEN-LAST:event_jButton_LuuActionPerformed
private void jComboBox_ViDuMauActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox_ViDuMauActionPerformed
// TODO add your handling code here:
if (jComboBox_ViDuMau.getSelectedItem().toString().equalsIgnoreCase("bài 1")){
jTextPane_PhanNhapKhaiBao.setText("KiemTraNamNhuan (n: N) Kq:B\npre \tn > 0\npost \t((Kq = true) /\\ (n % 4 = 0) /\\ (n % 100 <> 0) )\\/ ((Kq = true) /\\ (n % 400 = 0)) \\/((Kq = false) /\\ (n % 100 = 0) /\\ (n%400 <>0))\\/((Kq = false) /\\ (n % 100 <> 0) /\\ (n%4 <> 0))\n");
toMau_HighlightSyntax();
caretCapNhat();
}
if (jComboBox_ViDuMau.getSelectedItem().toString().equalsIgnoreCase("bài 2")){
jTextPane_PhanNhapKhaiBao.setText("KTMangGiaTriChan (a:N*, n:N)kq:B\npre\npost kq = (VM i TH {0..n-1}. a[i] % 2 = 0)");
toMau_HighlightSyntax();
caretCapNhat();
}
}//GEN-LAST:event_jComboBox_ViDuMauActionPerformed
private void jButton_PhanTich1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_PhanTich1ActionPerformed
// TODO add your handling code here:
String Str_KhaiBao = jTextPane_PhanNhapKhaiBao.getText();
/* jClass_PhanKhaiBao jPKB_KhaiBao = new jClass_PhanKhaiBao();
if (jPKB_KhaiBao.jKiemTraLoiCuaBieuThucDuocNhap(Str_KhaiBao).getMoTa() != jEnum_Loi.KhongCoLoi){
JOptionPane.showMessageDialog(null, "Có lỗi trong phần dữ liệu đầu vào. Xin kiểm tra lại!");
return;
}
//Lay Chuoi Ket Qua de xuat ra man hinh
String Str_KetQua = jPKB_KhaiBao.toString();
jTextPane_PhanKetQuaPhanTich.setText(Str_KetQua);
jClass_PhanDacTa jPDT_DacTa = new jClass_PhanDacTa();
jPDT_DacTa.setPhanKhaiBao(jPKB_KhaiBao);
String str_Code = jClass_BoTaoCode.jTaoCode(jPDT_DacTa);
// if (jCheckBox_TaoHamMain.isSelected())
*/
String str_Code = phatSinhCodeCS(Str_KhaiBao);
jTextPane_PhanCodeDuocTao.setText(str_Code);
}//GEN-LAST:event_jButton_PhanTich1ActionPerformed
/**
* Tô màu biến có lỗi
* @param jCB_Bien Tên biến cần tô màu
*/
private void toMau_LoiTrungTenBien (String str_TenBien){
String str_ChuoiKhaiBao = jTextPane_PhanNhapKhaiBao.getText();
//Tìm vị trí cuối cùng có dạng " jCB_Bien"
int i_STTTruongHopCoKhoangTrang = str_ChuoiKhaiBao.lastIndexOf(str_TenBien + " ");
//Tìm vị trí cuối cùng có dạng ":jCB_Bien"
int i_STTTruongHopKhongCoKhoangTrang = str_ChuoiKhaiBao.lastIndexOf(str_TenBien + ":");
//Vị trí nào đứng sau sẽ là vị trí cần tô màu
int i_STTViTriCanTo = 0;
if (i_STTTruongHopCoKhoangTrang > i_STTTruongHopKhongCoKhoangTrang)
i_STTViTriCanTo = i_STTTruongHopCoKhoangTrang;
else
i_STTViTriCanTo = i_STTTruongHopKhongCoKhoangTrang;
//Tạo AttributeSet chữ in nghiêng màu đỏ.
MutableAttributeSet mA_Loi = new SimpleAttributeSet();
StyleConstants.setForeground(mA_Loi, Color.RED);
StyleConstants.setItalic(mA_Loi, true);
StyledDocument doc = jTextPane_PhanNhapKhaiBao.getStyledDocument();
doc.setCharacterAttributes(i_STTViTriCanTo, str_TenBien.length(), mA_Loi, false);
jTextPane_PhanNhapKhaiBao.setDocument(doc);
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton_Luu;
private javax.swing.JButton jButton_MoFile;
private javax.swing.JButton jButton_PhanTich;
private javax.swing.JButton jButton_PhanTich1;
private javax.swing.JButton jButton_Thoat;
private javax.swing.JCheckBox jCheckBox_TaoHamMain;
private javax.swing.JComboBox jComboBox_ViDuMau;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel_ThongBaoLoi;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel_Code;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JScrollPane jScrollPane3;
private javax.swing.JScrollPane jScrollPane4;
private javax.swing.JScrollPane jScrollPane5;
private javax.swing.JTextPane jTextPane_PhanCodeDuocTao;
private javax.swing.JTextPane jTextPane_PhanKetQuaPhanTich;
private javax.swing.JTextPane jTextPane_PhanNhapKhaiBao;
private javax.swing.JPanel mainPanel;
private javax.swing.JMenuBar menuBar;
private javax.swing.JProgressBar progressBar;
private javax.swing.JLabel statusAnimationLabel;
private javax.swing.JLabel statusMessageLabel;
private javax.swing.JPanel statusPanel;
// End of variables declaration//GEN-END:variables
private final Timer messageTimer;
private final Timer busyIconTimer;
private final Icon idleIcon;
private final Icon[] busyIcons = new Icon[15];
private int busyIconIndex = 0;
private JDialog aboutBox;
private void toMau_TraTatCaVeDangChuThuong() {
//Nếu không có lổi thì tô màu lại, bật (true) button Phân tích và ẩn (false) thông báo lỗi
//Tạo AttributeSet chữ bình thường
/*MutableAttributeSet mA_Loi = new SimpleAttributeSet();
StyleConstants.setForeground(mA_Loi, Color.BLACK);
StyleConstants.setItalic(mA_Loi, false);
StyleConstants.setBold(mA_Loi, false);*/
MutableAttributeSet mA_ChuThuong = cacStyleChuoi.mChuThuong;
StyledDocument doc = jTextPane_PhanNhapKhaiBao.getStyledDocument();
doc.setCharacterAttributes(0, jTextPane_PhanNhapKhaiBao.getText().length(), mA_ChuThuong, false);
}
private void toMau_HighlightSyntax(){
String str_KhaiBao = jTextPane_PhanNhapKhaiBao.getText();
/*--------------------------------------------------------------------------------------------
Tạo các AttributeSet*/
/*//Tạo AttributeSet chữ bình thường
MutableAttributeSet mA_ChuThuong = new SimpleAttributeSet();
StyleConstants.setForeground(mA_ChuThuong, Color.BLACK);
StyleConstants.setItalic(mA_ChuThuong, false);
StyleConstants.setBold(mA_ChuThuong, false);
//Tạo AttributeSet tên hàm
MutableAttributeSet mA_TenHam = new SimpleAttributeSet();
StyleConstants.setForeground(mA_TenHam, Color.BLACK);
StyleConstants.setBold(mA_TenHam, true);
//Tạo AttributeSet tên biến
MutableAttributeSet mA_TenBien = new SimpleAttributeSet();
StyleConstants.setForeground(mA_TenBien, Color.MAGENTA);
//Tạo AttributeSet kiểu dữ liệu
MutableAttributeSet mA_KieuDuLieu = new SimpleAttributeSet();
StyleConstants.setForeground(mA_KieuDuLieu, Color.BLUE);*/
//MutableAttributeSet mA_ChuThuong = new SimpleAttributeSet();
MutableAttributeSet mA_TenHam = cacStyleChuoi.mTenHam;
MutableAttributeSet mA_TenBien = cacStyleChuoi.mTenBien;
MutableAttributeSet mA_KieuDuLieu = cacStyleChuoi.mKieuDuLieu;
StyledDocument sD_Doc = jTextPane_PhanNhapKhaiBao.getStyledDocument();
/*--------------------------------------------------------------------------------------------*/
//Tô màu phần tên hàm
int i_STTViTriDau = 0;
int i_DoDaiCanTo = 0;
//Tách tên hàm ra khỏi các phần còn lại
String Str_KyTuTachChuoi = jEnum_DauPhanCach.TenHam_PhanConLai.value();//jEnum_DauPhanCach.TenHam_PhanConLai.value();
//kiểm tra xem người dùng đã đánh xong tên hàm chưa dựa vào dấu "("
if (!str_KhaiBao.contains(Str_KyTuTachChuoi.substring(1)))
return;
String[] StrArr_TachTenHam = str_KhaiBao.split(Str_KyTuTachChuoi);
i_DoDaiCanTo = StrArr_TachTenHam[0].length();
sD_Doc.setCharacterAttributes(i_STTViTriDau, i_DoDaiCanTo, mA_TenHam, false);
//Cập nhật lại vị trí đầu và chuổi khai báo
i_STTViTriDau = str_KhaiBao.indexOf(jEnum_DauPhanCach.TenHam_PhanConLai.value().substring(1));
str_KhaiBao = str_KhaiBao.split(jEnum_DauPhanCach.TenHam_PhanConLai.value())[1];
i_STTViTriDau ++;
//Phần còn lại là các tham số và giá trị trả về
//Tách các tham số ra
String[] strArr_CacThamSo = str_KhaiBao.split(jEnum_DauPhanCach.CacThamSoVoiNhau.value());
int i_SoLuongBien = strArr_CacThamSo.length;
int i = 0;
for (; i < i_SoLuongBien - 1; i++){
String str_ThongTinBien = strArr_CacThamSo[i];
if (!str_ThongTinBien.contains(jEnum_DauPhanCach.TenBien_KieuDuLieu.value().substring(1)))
return;
//Cập nhật vị trí cuối tô màu tên tham số và cập nhật lại vị trí đầu
i_DoDaiCanTo = str_ThongTinBien.split(jEnum_DauPhanCach.TenBien_KieuDuLieu.value())[0].length();
sD_Doc.setCharacterAttributes(i_STTViTriDau, i_DoDaiCanTo, mA_TenBien, false);
i_STTViTriDau += i_DoDaiCanTo + 1;
//Cập nhật vị trí cuối tô màu kiểu dữ liệu và cập nhật lại vị trí đầu
i_DoDaiCanTo = str_ThongTinBien.split(jEnum_DauPhanCach.TenBien_KieuDuLieu.value())[1].length();
sD_Doc.setCharacterAttributes(i_STTViTriDau, i_DoDaiCanTo, mA_KieuDuLieu, false);
i_STTViTriDau += i_DoDaiCanTo + 1;
}
//Phần còn lại là tham số cuối và giá trị trả về
//Tách giá tham số cuối ra
String str_ThamSoCuoi = strArr_CacThamSo[i].split(jEnum_DauPhanCach.GiaTriTraVe_CacThamSo.value())[0];
//Tô màu tham số cuối
if (!str_ThamSoCuoi.contains(jEnum_DauPhanCach.TenBien_KieuDuLieu.value().substring(1)))
return;
//Cập nhật vị trí cuối tô màu tên tham số và cập nhật lại vị trí đầu
i_DoDaiCanTo = str_ThamSoCuoi.split(jEnum_DauPhanCach.TenBien_KieuDuLieu.value())[0].length();
sD_Doc.setCharacterAttributes(i_STTViTriDau, i_DoDaiCanTo, mA_TenBien, false);
i_STTViTriDau += i_DoDaiCanTo + 1;
//Cập nhật vị trí cuối tô màu kiểu dữ liệu và cập nhật lại vị trí đầu
i_DoDaiCanTo = str_ThamSoCuoi.split(jEnum_DauPhanCach.TenBien_KieuDuLieu.value())[1].length();
sD_Doc.setCharacterAttributes(i_STTViTriDau, i_DoDaiCanTo, mA_KieuDuLieu, false);
i_STTViTriDau += i_DoDaiCanTo + 1;
//Kiểm tra xem có giá trị trả về không nếu không thì kết thúc
if (!str_KhaiBao.contains(jEnum_DauPhanCach.GiaTriTraVe_CacThamSo.value().substring(1)) || //Chưa có dấu ")"
str_KhaiBao.endsWith(jEnum_DauPhanCach.GiaTriTraVe_CacThamSo.value().substring(1))) //Kết thúc = dấu ")"
return;
//Tô màu tham số cuối
String str_GiaTriTraVe = strArr_CacThamSo[i].split(jEnum_DauPhanCach.GiaTriTraVe_CacThamSo.value())[1];
if (!str_ThamSoCuoi.contains(jEnum_DauPhanCach.TenBien_KieuDuLieu.value().substring(1)))
return;
//Cập nhật vị trí cuối tô màu tên tham số và cập nhật lại vị trí đầu
i_DoDaiCanTo = str_GiaTriTraVe.split(jEnum_DauPhanCach.TenBien_KieuDuLieu.value())[0].length();
sD_Doc.setCharacterAttributes(i_STTViTriDau, i_DoDaiCanTo, mA_TenBien, false);
i_STTViTriDau += i_DoDaiCanTo + 1;
//Cập nhật vị trí cuối tô màu kiểu dữ liệu và cập nhật lại vị trí đầu
i_DoDaiCanTo = str_GiaTriTraVe.split(jEnum_DauPhanCach.TenBien_KieuDuLieu.value())[1].trim().length();
sD_Doc.setCharacterAttributes(i_STTViTriDau, i_DoDaiCanTo, mA_KieuDuLieu, false);
i_STTViTriDau += i_DoDaiCanTo + 1;
/*
//Tô màu các tham số
//Lấy các chuổi chứa các thông tin về các tham số
String[] StrArr_CacThamSo = StrArr_TachGiaTriTraVe[0].split(jEnum_DauPhanCach.CacThamSoVoiNhau.value());
for (String str_ThongTinThamSo : StrArr_CacThamSo){
//Lấy các chuổi chứa các thông tin về các tham số thành các chuổi tên biến và kiểu dữ liệu
String[] strArr_TachTenBien = str_ThongTinThamSo.split(jEnum_DauPhanCach.TenBien_KieuDuLieu.value());
if (strArr_TachTenBien.length == 2) {//Nếu đã đánh xong tên biến
//Tô màu tên biến
i_STTViTriCuoi = i_STTViTriDau + strArr_TachTenBien[0].length();
sD_Doc.setCharacterAttributes(i_STTViTriDau, i_STTViTriCuoi, mA_TenBien, false);
i_STTViTriDau = i_STTViTriCuoi + 1;
sD_Doc.setCharacterAttributes(i_STTViTriCuoi, jTextPane_PhanNhapKhaiBao.getText().length(), mA_ChuThuong, false);
//Tô màu kiểu dữ liêu
i_STTViTriCuoi = i_STTViTriDau + strArr_TachTenBien[1].length();
sD_Doc.setCharacterAttributes(i_STTViTriDau, i_STTViTriCuoi, mA_KieuDuLieu, false);
i_STTViTriDau = i_STTViTriCuoi + 1;
sD_Doc.setCharacterAttributes(i_STTViTriCuoi, jTextPane_PhanNhapKhaiBao.getText().length(), mA_ChuThuong, false);
}
}
//Tô màu phần tên giá trị trả về
String[] strArr_TachTenBien = StrArr_TachGiaTriTraVe[1].split(jEnum_DauPhanCach.TenBien_KieuDuLieu.value());
if (strArr_TachTenBien.length == 2) {//Nếu đã đánh xong tên biến
//Tô màu tên biến
i_STTViTriCuoi = i_STTViTriDau + strArr_TachTenBien[0].length();
sD_Doc.setCharacterAttributes(i_STTViTriDau, i_STTViTriCuoi, mA_TenBien, false);
i_STTViTriDau = i_STTViTriCuoi + 1;
sD_Doc.setCharacterAttributes(i_STTViTriCuoi, jTextPane_PhanNhapKhaiBao.getText().length(), mA_ChuThuong, false);
//Tô màu kiểu dữ liêu
i_STTViTriCuoi = i_STTViTriDau + strArr_TachTenBien[1].length();
sD_Doc.setCharacterAttributes(i_STTViTriDau, i_STTViTriCuoi, mA_KieuDuLieu, false);
i_STTViTriDau = i_STTViTriCuoi + 1;
sD_Doc.setCharacterAttributes(i_STTViTriCuoi, jTextPane_PhanNhapKhaiBao.getText().length(), mA_ChuThuong, false);
}*/
}
private void toMau_LoiKieuDuLieu (jClass_Bien jCB_Bien){
String str_ChuoiKhaiBao = jTextPane_PhanNhapKhaiBao.getText();
//Tìm vị trí cuối cùng có dạng "jCB_Bien :"
int i_STTViTriCuaBien = str_ChuoiKhaiBao.lastIndexOf(jCB_Bien.getTen() + ":");
//Xác định vị trí của kiểu dữ liệu
int i_STTViTriCanTo = i_STTViTriCuaBien + jCB_Bien.getTen().length() + ":".length(); //
//Tạo AttributeSet chữ in nghiêng màu đỏ.
MutableAttributeSet mA_Loi = new SimpleAttributeSet();
StyleConstants.setForeground(mA_Loi, Color.RED);
StyleConstants.setItalic(mA_Loi, true);
StyledDocument doc = jTextPane_PhanNhapKhaiBao.getStyledDocument();
doc.setCharacterAttributes(i_STTViTriCanTo, jCB_Bien.getKieuDuLieu().length(), mA_Loi, false);
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package _bai02_phantichphankhaibao;
/**
* Các chuổi định dạng (RegEx) cho tên biến, kiểu dữ liệu...
* @author Administrator
*/
public enum jEnum_ChuoiDinhDang {
TenBien ("[A-Za-z0-9_]+"),
TenHam ("[A-Za-z0-9_]+"),
KieuDuLieu ("[A-Za-z0-9_]+\\*?"),
GiaTri ("(([A-Za-z0-9_]+(\\[[A-Za-z0-9_]+(\\s*(\\+|-|\\*|/|%)\\s*[A-Za-z0-9_])*\\])?)|(\".*+\")|('.'))(\\s*(\\+|-|\\*|/|%)\\s*((([A-Za-z0-9_]+(\\[[A-Za-z0-9]+(\\s*(\\+|-|\\*|/|%)\\s*[A-Za-z0-9_])\\])?)|(\".*+\")|('.'))))*"),
//GiaTri ("((\"?[A-Za-z0-9_]+\"?)|('.'))"),//co the la ten bien, chuoi, ky tu...
//GiaTri ("\\[[A-Za-z0-9]+\\]"),//co the la ten bien, chuoi, ky tu...
CacToanTuLogic ("((<>)|>=?|<=?|=)"),
CacKieuDuLieuDuocHoTro("(B|Char|N|R|N1?)\\*?");
private final String value;
jEnum_ChuoiDinhDang(String value) {
this.value = value;
}
String value(){
return this.value;
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package _bai02_phantichphankhaibao;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* VM i TH {1 .. n-1}
* @author Administrator
*/
public class jClass_PhanKhaiBaoBieuThucLuongTu implements Interface_CacThanhPhanDacTa {
private jEnum_BieuThucLuongTu _LoaiBieuThuc;
private String _TenBienDiem;
private String _ViTriDemDau;
private String _ViTriDemCuoi;
//private String _BuocNhay;
//private jClass_TruongHopDacTa _DieuKien;
private static String _BieuThucDinhDang;
/**
* @return the _BieuThucDinhDang
*/
public static String getBieuThucDinhDang() {
return _BieuThucDinhDang;
}
/**
* @param aBieuThucDinhDang the _BieuThucDinhDang to set
*/
public static void setBieuThucDinhDang(String aBieuThucDinhDang) {
_BieuThucDinhDang = aBieuThucDinhDang;
}
/**
* @return the _LoaiBieuThuc
*/
public jEnum_BieuThucLuongTu getLoaiBieuThuc() {
return _LoaiBieuThuc;
}
/**
* @param loaiBieuThuc the _LoaiBieuThuc to set
*/
public void setLoaiBieuThuc(jEnum_BieuThucLuongTu loaiBieuThuc) {
this._LoaiBieuThuc = loaiBieuThuc;
}
/**
* @return the _TenBienDiem
*/
public String getBienDiem() {
return getTenBienDiem();
}
/**
* @param BienDiem the _TenBienDiem to set
*/
public void setBienDiem(String BienDiem) {
this.setTenBienDiem(BienDiem);
}
/**
* @return the _ViTriDemDau
*/
public String getViTriDiemDau() {
return _ViTriDemDau;
}
/**
* @param ViTriDiemDau the _ViTriDemDau to set
*/
public void setViTriDiemDau(String ViTriDiemDau) {
this._ViTriDemDau = ViTriDiemDau;
}
/**
* @return the _ViTriDemCuoi
*/
public String getViTriDemCuoi() {
return _ViTriDemCuoi;
}
/**
* @param ViTriDemCuoi the _ViTriDemCuoi to set
*/
public void setViTriDemCuoi(String ViTriDemCuoi) {
this._ViTriDemCuoi = ViTriDemCuoi;
}
public jClass_PhanKhaiBaoBieuThucLuongTu(){
_LoaiBieuThuc = jEnum_BieuThucLuongTu.TonTai;
_TenBienDiem = "i";
//_DieuKien = new jClass_TruongHopDacTa();
//_BuocNhay = "1";
_ViTriDemCuoi = "0";
_ViTriDemDau = "n - 1";
_BieuThucDinhDang = "(";
for (jEnum_BieuThucLuongTu bieuThucLuongTu : jEnum_BieuThucLuongTu.values())
_BieuThucDinhDang += bieuThucLuongTu.value() + "|";
_BieuThucDinhDang = _BieuThucDinhDang.substring(0, _BieuThucDinhDang.lastIndexOf("|")) + ")";
//(VM|TT)
_BieuThucDinhDang += ".+" + jEnum_CacKyTuDacBietCoTheChoNguoiDungDinhNghia.Thuoc.value();
//(VM|TT) i TH
_BieuThucDinhDang += "\\s*\\{.+\\.\\..+\\}";
//VM i TH {1 .. n-1}
}
public void jCapNhatTuChuoi(String Str_KhaiBao) {
//throw new UnsupportedOperationException("Not supported yet.");
Str_KhaiBao = Str_KhaiBao.trim();
String tachCacPhan[] = Str_KhaiBao.split(" ", 3);
for (jEnum_BieuThucLuongTu bieuThucLuongTu : jEnum_BieuThucLuongTu.values())
if (bieuThucLuongTu.value().equals(tachCacPhan[0]))
_LoaiBieuThuc = bieuThucLuongTu;
if (!jClass_TenBien.jKiemTraChuoiHopDinhDang(tachCacPhan[1])){
//Doan thu 2 khong phai la mot ten bien
//Bao loi va exc
}
_TenBienDiem = tachCacPhan[1].trim();
String TH = jEnum_CacKyTuDacBietCoTheChoNguoiDungDinhNghia.Thuoc.value();
if (!tachCacPhan[2].startsWith(TH)){
//Doan thu 3 khong bat dau = TH
//Bao loi va exc
}
String haiDauDuyet[] = tachCacPhan[2].substring(TH.length()).trim().split("\\.\\.", 2);
_ViTriDemDau = haiDauDuyet[0].substring(1, haiDauDuyet[0].length()).trim();
if (!jClass_GiaTri.jKiemTraChuoiHopDinhDang(_ViTriDemDau)){
}
_ViTriDemCuoi = haiDauDuyet[1].substring(0, haiDauDuyet[1].length() - 1).trim();
if (!jClass_GiaTri.jKiemTraChuoiHopDinhDang(_ViTriDemDau)){
}
}
public Boolean jKiemTraChuoiHopDinhDang(String str_ChuoiCanKienTra) {
Pattern pat=Pattern.compile(getBieuThucDinhDang());
Matcher matcher =pat.matcher(str_ChuoiCanKienTra);
return matcher.matches();
}
public String jToCCode(int DoLui) {
//throw new UnsupportedOperationException("Not supported yet.");
String Kq = "for (int " + _TenBienDiem + " = " + _ViTriDemDau + "; ";
Kq += _TenBienDiem + " <= " + _ViTriDemCuoi + " && ";
Kq +="; " + _TenBienDiem + "++";
Kq += ")";
return Kq;
}
public String jCSharpCode(int DoLui) {
//throw new UnsupportedOperationException("Not supported yet.");
String Kq = "for (int " + _TenBienDiem + " = " + _ViTriDemDau + "; ";
Kq += _TenBienDiem + " <= " + _ViTriDemCuoi + " && ";
Kq +="; " + _TenBienDiem + "++";
Kq += ")";
return Kq;
}
public String jVBNetCode(int DoLui) {
throw new UnsupportedOperationException("Not supported yet.");
}
/**
* @return the _TenBienDiem
*/
public String getTenBienDiem() {
return _TenBienDiem;
}
/**
* @param TenBienDiem the _TenBienDiem to set
*/
public void setTenBienDiem(String TenBienDiem) {
this._TenBienDiem = TenBienDiem;
}
public String jToCCode(int DoLui, String bienKq) {
//throw new UnsupportedOperationException("Not supported yet.");
String Kq = "for (int " + _TenBienDiem + " = " + _ViTriDemDau + "; ";
Kq += _TenBienDiem + " <= " + _ViTriDemCuoi + " && ";
if (_LoaiBieuThuc == jEnum_BieuThucLuongTu.TonTai)
Kq+="!";
Kq+= bienKq;
Kq +="; " + _TenBienDiem + "++";
Kq += ")";
return Kq;
}
public String jToCSharpCode(int DoLui, String bienKq) {
//throw new UnsupportedOperationException("Not supported yet.");
String Kq = "for (int " + _TenBienDiem + " = " + _ViTriDemDau + "; ";
Kq += _TenBienDiem + " <= " + _ViTriDemCuoi + " && ";
if (_LoaiBieuThuc == jEnum_BieuThucLuongTu.TonTai)
Kq+="!";
Kq+= bienKq;
Kq +="; " + _TenBienDiem + "++";
Kq += ")";
return Kq;
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package _bai02_phantichphankhaibao;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JOptionPane;
/**
* //(VM i TH {1 .. n-1}. TT j TH{1 .. n-2}. (x[i] > x[j]))
* @author Administrator
*/
public class jClass_BieuThucLuongTu implements Interface_CacThanhPhanDacTa{
private jClass_Bien _BienTraVe = new jClass_Bien();
private ArrayList<jClass_PhanKhaiBaoBieuThucLuongTu> _cacPhanKhaiBao = new ArrayList<jClass_PhanKhaiBaoBieuThucLuongTu>();
private jClass_TruongHopDacTa _CacDieuKien = new jClass_TruongHopDacTa();
private String _BieuThucDinhDang = "\\((.+\\.)+.+\\)";
public jClass_BieuThucLuongTu(jClass_Bien bien){
_BienTraVe = bien;
_BieuThucDinhDang = bien.getTen() + "\\s=\\s" + _CacDieuKien;
}
public void jCapNhatTuChuoi(String Str_KhaiBao) {
//throw new UnsupportedOperationException("Not supported yet.");
Str_KhaiBao = Str_KhaiBao.trim().substring(1, Str_KhaiBao.length() - 1);
while(Str_KhaiBao.contains("..")){
Str_KhaiBao.trim();
int doDaiPhanKhaiBaoBieuThucLuongTu = Str_KhaiBao.indexOf(".", Str_KhaiBao.indexOf("..") + "..".length());
String chuoiKhaiBaoBieuThucLuongTu = Str_KhaiBao.substring(0, doDaiPhanKhaiBaoBieuThucLuongTu);
//JOptionPane.showMessageDialog(null, chuoiKhaiBaoBieuThucLuongTu);
Str_KhaiBao = Str_KhaiBao.substring(doDaiPhanKhaiBaoBieuThucLuongTu + 1);
jClass_PhanKhaiBaoBieuThucLuongTu phanKhaiBaoBieuThucLuongTu = new jClass_PhanKhaiBaoBieuThucLuongTu();
phanKhaiBaoBieuThucLuongTu.jCapNhatTuChuoi(chuoiKhaiBaoBieuThucLuongTu);
getCacPhanKhaiBao().add(phanKhaiBaoBieuThucLuongTu);
}
setCacDieuKien(new jClass_TruongHopDacTa());
if (!Str_KhaiBao.startsWith("("))
Str_KhaiBao = "(" + Str_KhaiBao + ")";
getCacDieuKien().jCapNhatTuChuoi(Str_KhaiBao.trim());
}
public Boolean jKiemTraChuoiHopDinhDang(String str_ChuoiCanKienTra) {
Pattern pat=Pattern.compile(getBieuThucDinhDang());
Matcher matcher =pat.matcher(str_ChuoiCanKienTra);
return matcher.matches();
}
public String jTaoBienKetQua (String tenGoc, int soTT){
String Kq = tenGoc;
if (soTT > 0)
Kq += soTT;
return Kq;
}
public String jToCCode(int DoLui) {
//throw new UnsupportedOperationException("Not supported yet.");
String Kq = "";
jClass_PhanKhaiBaoBieuThucLuongTu phanKhaiBao = new jClass_PhanKhaiBaoBieuThucLuongTu();
int i = 0;
for (;i<getCacPhanKhaiBao().size(); i++){
phanKhaiBao = getCacPhanKhaiBao().get(i);
Kq += jClass_BoTaoCode.jTaoKhaiBaoBien(DoLui, getBienTraVe(), false, "");
if(i != 0)
Kq += i;
//Kq
switch (phanKhaiBao.getLoaiBieuThuc()){
case TonTai:{
Kq += " = 0;\n";
break;
}
case VoiMoi:{
Kq += " = 1;\n";
break;
}
}
Kq += jClass_BoTaoCode.jTaoCapDo(DoLui);
Kq += phanKhaiBao.jToCCode(DoLui, jTaoBienKetQua(_BienTraVe.getTen(), i)) + "\n";
Kq += jClass_BoTaoCode.jTaoCapDo(DoLui++) + "{\n";
/**
* Kq = 0;
* for (int i = 0; i < n - 1; i++)
* {
*/
}
Kq += jClass_BoTaoCode.jTaoCapDo(DoLui);
//Kq += "if(!" + getCacDieuKien().jToCCode(DoLui++) + ")\n";
Kq += "if (";
switch (phanKhaiBao.getLoaiBieuThuc()){
case TonTai:{
break;
}
case VoiMoi:{
Kq += "!";
break;
}
}
for (jClass_BieuThucLogic bieuThucLogic : _CacDieuKien.getCacDieuKien()){
Kq+=bieuThucLogic.jToCCode(DoLui) + " && ";
}
Kq = Kq.substring(0, Kq.lastIndexOf(" && ")) + ")\n";
//if (!(x[i] > x[j] && x[k] > x[l]))
Kq += jClass_BoTaoCode.jTaoCapDo(DoLui + 1);
String bien = jTaoBienKetQua(_BienTraVe.getTen(), --i);
Kq += bien;
/*
Kq += _BienTraVe.getTen();
if (--i > 0)
Kq += i;
* */
Kq += " = !";
bien = jTaoBienKetQua(_BienTraVe.getTen(), i);
Kq += bien;/*
Kq += _BienTraVe.getTen();
if (i > 0)
Kq += i;*/
Kq += ";\n";
//Kq2 = !Kq2;
for(;i >0; i--){
phanKhaiBao = getCacPhanKhaiBao().get(i);
Kq += jClass_BoTaoCode.jTaoCapDo(--DoLui) + "}\n";
Kq += jClass_BoTaoCode.jTaoCapDo(DoLui) + "if(";
switch (phanKhaiBao.getLoaiBieuThuc()){
case TonTai:{
Kq += "!";
break;
}
case VoiMoi:{
break;
}
}
bien = jTaoBienKetQua(_BienTraVe.getTen(), i);
Kq += bien;/*
Kq += _BienTraVe.getTen();
if (i > 0)
Kq += i;*/
Kq += ")\n";
Kq += jClass_BoTaoCode.jTaoCapDo(DoLui + 1);
bien = jTaoBienKetQua(_BienTraVe.getTen(), --i);
Kq += bien;/*
Kq += _BienTraVe.getTen();
if (--i > 0)
Kq += i;*/
Kq += " = !";
bien = jTaoBienKetQua(_BienTraVe.getTen(), i);
Kq += bien;/*
Kq += _BienTraVe.getTen();
if (i > 0)
Kq += i;*/
Kq += ";\n";
Kq += jClass_BoTaoCode.jTaoCapDo(--DoLui) + "}\n";
}
Kq += jClass_BoTaoCode.jTaoCapDo(--DoLui) + "}\n";
if (_cacPhanKhaiBao.size() % 2 == 0)
Kq = Kq.substring(0, Kq.lastIndexOf("}")) + "\n";
//Kq += jClass_BoTaoCode.jTaoCapDo(DoLui) + "return " + _BienTraVe.getTen() + ";\n";
return Kq;
}
public String jCSharpCode(int DoLui) {
//throw new UnsupportedOperationException("Not supported yet.");
String Kq = "";
jClass_PhanKhaiBaoBieuThucLuongTu phanKhaiBao = new jClass_PhanKhaiBaoBieuThucLuongTu();
int i = 0;
for (;i<getCacPhanKhaiBao().size(); i++){
phanKhaiBao = getCacPhanKhaiBao().get(i);
Kq += jClass_BoTaoCode.jTaoKhaiBaoBien(DoLui, getBienTraVe(), false, "");
if(i != 0)
Kq += i;
//Kq
switch (phanKhaiBao.getLoaiBieuThuc()){
case TonTai:{
Kq += " = 0;\n";
break;
}
case VoiMoi:{
Kq += " = 1;\n";
break;
}
}
Kq += jClass_BoTaoCode.jTaoCapDo(DoLui);
Kq += phanKhaiBao.jToCSharpCode(DoLui, jTaoBienKetQua(_BienTraVe.getTen(), i)) + "\n";
Kq += jClass_BoTaoCode.jTaoCapDo(DoLui++) + "{\n";
/**
* Kq = 0;
* for (int i = 0; i < n - 1; i++)
* {
*/
}
Kq += jClass_BoTaoCode.jTaoCapDo(DoLui);
//Kq += "if(!" + getCacDieuKien().jToCCode(DoLui++) + ")\n";
Kq += "if (";
switch (phanKhaiBao.getLoaiBieuThuc()){
case TonTai:{
break;
}
case VoiMoi:{
Kq += "!";
break;
}
}
for (jClass_BieuThucLogic bieuThucLogic : _CacDieuKien.getCacDieuKien()){
Kq+=bieuThucLogic.jToCCode(DoLui) + " && ";
}
Kq = Kq.substring(0, Kq.lastIndexOf(" && ")) + ")\n";
//if (!(x[i] > x[j] && x[k] > x[l]))
Kq += jClass_BoTaoCode.jTaoCapDo(DoLui + 1);
String bien = jTaoBienKetQua(_BienTraVe.getTen(), --i);
Kq += bien;
/*
Kq += _BienTraVe.getTen();
if (--i > 0)
Kq += i;
* */
Kq += " = !";
bien = jTaoBienKetQua(_BienTraVe.getTen(), i);
Kq += bien;/*
Kq += _BienTraVe.getTen();
if (i > 0)
Kq += i;*/
Kq += ";\n";
//Kq2 = !Kq2;
for(;i >0; i--){
phanKhaiBao = getCacPhanKhaiBao().get(i);
Kq += jClass_BoTaoCode.jTaoCapDo(--DoLui) + "}\n";
Kq += jClass_BoTaoCode.jTaoCapDo(DoLui) + "if(";
switch (phanKhaiBao.getLoaiBieuThuc()){
case TonTai:{
Kq += "!";
break;
}
case VoiMoi:{
break;
}
}
bien = jTaoBienKetQua(_BienTraVe.getTen(), i);
Kq += bien;/*
Kq += _BienTraVe.getTen();
if (i > 0)
Kq += i;*/
Kq += ")\n";
Kq += jClass_BoTaoCode.jTaoCapDo(DoLui + 1);
bien = jTaoBienKetQua(_BienTraVe.getTen(), --i);
Kq += bien;/*
Kq += _BienTraVe.getTen();
if (--i > 0)
Kq += i;*/
Kq += " = !";
bien = jTaoBienKetQua(_BienTraVe.getTen(), i);
Kq += bien;/*
Kq += _BienTraVe.getTen();
if (i > 0)
Kq += i;*/
Kq += ";\n";
Kq += jClass_BoTaoCode.jTaoCapDo(--DoLui) + "}\n";
}
Kq += jClass_BoTaoCode.jTaoCapDo(--DoLui) + "}\n";
if (_cacPhanKhaiBao.size() % 2 == 0)
Kq = Kq.substring(0, Kq.lastIndexOf("}")) + "\n";
//Kq += jClass_BoTaoCode.jTaoCapDo(DoLui) + "return " + _BienTraVe.getTen() + ";\n";
return Kq;
}
public String jVBNetCode(int DoLui) {
throw new UnsupportedOperationException("Not supported yet.");
}
/**
* @return the _BienTraVe
*/
public jClass_Bien getBienTraVe() {
return _BienTraVe;
}
/**
* @param BienTraVe the _BienTraVe to set
*/
public void setBienTraVe(jClass_Bien BienTraVe) {
this._BienTraVe = BienTraVe;
}
/**
* @return the _cacPhanKhaiBao
*/
public ArrayList<jClass_PhanKhaiBaoBieuThucLuongTu> getCacPhanKhaiBao() {
return _cacPhanKhaiBao;
}
/**
* @param cacPhanKhaiBao the _cacPhanKhaiBao to set
*/
public void setCacPhanKhaiBao(ArrayList<jClass_PhanKhaiBaoBieuThucLuongTu> cacPhanKhaiBao) {
this._cacPhanKhaiBao = cacPhanKhaiBao;
}
/**
* @return the _CacDieuKien
*/
public jClass_TruongHopDacTa getCacDieuKien() {
return _CacDieuKien;
}
/**
* @param CacDieuKien the _CacDieuKien to set
*/
public void setCacDieuKien(jClass_TruongHopDacTa CacDieuKien) {
this._CacDieuKien = CacDieuKien;
}
/**
* @return the _BieuThucDinhDang
*/
public String getBieuThucDinhDang() {
return _BieuThucDinhDang;
}
/**
* @param BieuThucDinhDang the _BieuThucDinhDang to set
*/
public void setBieuThucDinhDang(String BieuThucDinhDang) {
this._BieuThucDinhDang = BieuThucDinhDang;
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package _bai02_phantichphankhaibao;
/**
*
* @author Administrator
*/
public enum jEnum_BieuThucLuongTu {
VoiMoi ("VM"),
TonTai ("TT");
private String value;
jEnum_BieuThucLuongTu(String value) {
this.value = value;
}
String value(){
return this.getValue();
}
/**
* @return the value
*/
public String getValue() {
return value;
}
/**
* @param value the value to set
*/
public void setValue(String value) {
this.value = value;
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package _bai02_phantichphankhaibao;
/**
*
* @author Administrator
*/
public interface Interface_CacThanhPhanDacTa {
/**
*
* Tách chuổi và đưa và các thuộc tính của lớp jClass_PhaKhaiBao
* @param Str_KhaiBao chuoi khai bao hop le vi du: Max2Numbers (v1: R, v2: R) result: R
*/
void jCapNhatTuChuoi(String Str_KhaiBao);
/**
* Kiểm tra xem một chuổi có thỏa biểu thức định dạng không.
* Nhớ thêm dấu ',' vào vị trí thích hợp (xem phần hàm khởi tạo để biết thêm chi tiết)
* @param str_ChuoiCanKienTra
* @return
*/
Boolean jKiemTraChuoiHopDinhDang(String str_ChuoiCanKienTra);
String jToCCode (int DoLui);
String jCSharpCode (int DoLui);
String jVBNetCode (int DoLui);
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package _bai02_phantichphankhaibao;
import java.util.ArrayList;
/**
*
* @author Administrator
*/
public class jClass_BoTaoCode {
/**
* Chuyển kiểu dữ liệu từ ngôn ngữ đặc tả sang ngôn ngữ lập trình
* @param str_KieuDuLieuDacTa Kiểu dữ liệu ở dạng ngôn ngữ đặc tả (R, N, B, Char...)
* @return Kiểu dữ liệu ở dạng ngôn ngữ lập trình (int, long, char...)
*/
static jClass_PhanDacTa _phanDacTa = new jClass_PhanDacTa();
public static String jChuyenKieuDuLieu (String str_KieuDuLieuDacTa){
Boolean isArr = false;
if (str_KieuDuLieuDacTa.contains("*")){
str_KieuDuLieuDacTa = str_KieuDuLieuDacTa.replace("*", "");
isArr = true;
}
String str_KetQua = "";
str_KieuDuLieuDacTa = str_KieuDuLieuDacTa.trim();
if (str_KieuDuLieuDacTa.equals("R"))
str_KetQua += "float";
else if (str_KieuDuLieuDacTa.equals("N"))
str_KetQua += "int";
else if (str_KieuDuLieuDacTa.equals("Char"))
str_KetQua += "char";
else if (str_KieuDuLieuDacTa.equals("B"))
str_KetQua += "bool";
else str_KetQua += "void";
if (isArr)
str_KetQua += "*";
return str_KetQua;
}public static String jChuyenKieuDuLieuCS (String str_KieuDuLieuDacTa){
Boolean isArr = false;
if (str_KieuDuLieuDacTa.contains("*")){
str_KieuDuLieuDacTa = str_KieuDuLieuDacTa.replace("*", "");
isArr = true;
}
String str_KetQua = "";
str_KieuDuLieuDacTa = str_KieuDuLieuDacTa.trim();
if (str_KieuDuLieuDacTa.equals("R"))
str_KetQua += "Double";
else if (str_KieuDuLieuDacTa.equals("N"))
str_KetQua += "Int16";
else if (str_KieuDuLieuDacTa.equals("Char"))
str_KetQua += "Char";
else if (str_KieuDuLieuDacTa.equals("B"))
str_KetQua += "Boolean";
else str_KetQua += "void";
if (isArr)
str_KetQua = "ArrayList";
return str_KetQua;
}
/**
* Tạo các chuổi thay thế biến dùng trong lệnh printf
* @param str_KieuDuLieuDacTa Kiểu dữ liệu ở dạng ngôn ngữ đặc tả
* @return chuổi thay thế cho kiểu dữ liệu (%d, %c, %f...)
*/
public static String jTaoChuoiThayTheBienTrongLenhPrintf (String str_KieuDuLieuDacTa){
String str_KetQua = "";
str_KieuDuLieuDacTa = str_KieuDuLieuDacTa.trim();
if (str_KieuDuLieuDacTa.equals("R"))
str_KetQua += "%f";
else if (str_KieuDuLieuDacTa.contains("N") || str_KieuDuLieuDacTa.contains("B"))
str_KetQua += "%d";
else if (str_KieuDuLieuDacTa.equals("Char"))
str_KetQua += "%c";
else if (str_KieuDuLieuDacTa.equals("String"))
str_KetQua += "%s";
return str_KetQua;
}
/**
* Tạo các khoảng lui thích hợp cho các cấp độ cha con
* @param i_CapDo Cấp độ (số khoảng lui) cần tạo
* @return Chuổi gồm các khoảng lui
*/
public static String jTaoCapDo (int i_CapDo){
String str_KetQua = "";
for (int i = 0; i < i_CapDo; i++)
str_KetQua += jEnum_ThongTinBoSung.KhoangCachLuiGiuaChaCon.value();
return str_KetQua;
}
/**
* Tạo giá trị mặc định cho kiểu dữ liệu ví dụ: int có gtmd là 0...
* @param str_KieuDuLieu Kiểu dữ liệu cần tạo giá trị mặc định ở dạng ngôn ngữ đặc tả
* @return Giá trị mặc định của kiểu dữ liệu
*/
public static String jTaoGiaTriMacDinhChoKieuDuLieu (String str_KieuDuLieu){
str_KieuDuLieu = str_KieuDuLieu.trim();
if (str_KieuDuLieu.equals("R")||str_KieuDuLieu.equals("N")||str_KieuDuLieu.equals("Char"))
return "0";
else if (str_KieuDuLieu.equals("B"))
return "true";
else if (str_KieuDuLieu.equals("N1"))
return "1";
return "NULL";
}
/**
* Tạo chuổi code khai báo cho biến
* @param jB_Bien Biến cần tạo code khai báo
* @param b_TaoGiaTriMacDinh Có tạo giá trị mặc định cho biến vừa được tạo không
* @param str_DauPhanCachPhiaSau Dấu phân cách phía sau biến ví dụ: "," hay ";"
* @return Chuổi code được tạo
*/
public static String jTaoKhaiBaoBien (int DoLui,jClass_Bien jB_Bien, boolean b_TaoGiaTriMacDinh, String str_DauPhanCachPhiaSau){
String str_KetQua = jClass_BoTaoCode.jTaoCapDo(DoLui);;
//Thêm kiểu dữ liệu và dấu phân cách
str_KetQua += jChuyenKieuDuLieu(jB_Bien.getKieuDuLieu().trim()) + " ";
//Thêm tên biến
str_KetQua += jB_Bien.getTen().trim();
if (b_TaoGiaTriMacDinh)
//Nếu tạo giá trị mặc định
str_KetQua += " = " + jTaoGiaTriMacDinhChoKieuDuLieu(jB_Bien.getKieuDuLieu());
str_KetQua += str_DauPhanCachPhiaSau;
return str_KetQua;
}
public static String jTaoKhaiBaoBienCS (int DoLui,jClass_Bien jB_Bien, boolean b_TaoGiaTriMacDinh, String str_DauPhanCachPhiaSau){
String str_KetQua = jClass_BoTaoCode.jTaoCapDo(DoLui);;
//Thêm kiểu dữ liệu và dấu phân cách
str_KetQua += jChuyenKieuDuLieuCS(jB_Bien.getKieuDuLieu().trim()) + " ";
//Thêm tên biến
str_KetQua += jB_Bien.getTen().trim();
if (b_TaoGiaTriMacDinh)
//Nếu tạo giá trị mặc định
str_KetQua += " = " + jTaoGiaTriMacDinhChoKieuDuLieu(jB_Bien.getKieuDuLieu());
str_KetQua += str_DauPhanCachPhiaSau;
return str_KetQua;
}
/**
* Tạo chuổi code khai báo có giá trị mặc định cho biến và với dấu phân cách phía sau là ";"
* @param jB_Bien Biến cần tạo code khai báo
* @return Chuổi code được tạo
*/
public static String jTaoKhaiBaoBien (int DoLui,jClass_Bien jB_Bien){
/*String str_KetQua = "";
//Thêm kiểu dữ liệu và dấu phân cách
str_KetQua += jChuyenKieuDuLieu(jB_Bien.getKieuDuLieu()) + " ";
//Thêm tên biến và dấu ","
str_KetQua += jB_Bien.getTen();
str_KetQua += " = " + jTaoGiaTriMacDinhChoKieuDuLieu(jB_Bien.getKieuDuLieu());
str_KetQua += ";";
return str_KetQua;*/
//jTaoK
return jTaoKhaiBaoBien(DoLui,jB_Bien, true, ";");
}
/**
* Tạo khai báo biến kiểu mảng
* @param jB_Bien Biến cần tạo khai báo
* @return Kết quả chuổi khai báo biến
*/
public static String jTaoKhaiBaoBienKieuMang (jClass_Bien jB_Bien, int i_SoLuongPhanTuTrongMang){
String str_KetQua = "";
//Thêm kiểu dữ liệu, dấu "*" và dấu phân cách
//Kết quả: "int* "
str_KetQua += jChuyenKieuDuLieu(jB_Bien.getKieuDuLieu()) + "*" + " ";
//Thêm tên biến và chuổi " = new "
//Kết quả: "int* i"
str_KetQua += jB_Bien.getTen() + " = new ";
//Thêm kiểu dữ liệu và số lượng phần tử và dấu chấm phẩy
//Kết quả "int* i = new int[4]
str_KetQua += jB_Bien.getKieuDuLieu() + " [" + i_SoLuongPhanTuTrongMang + "];";
return str_KetQua;
}
/**
* Tạo code cho phần khai báo bao gồm giá trị trả về mặc định nếu có
* @param jPKB_KhaiBao Phần khai báo cần tạo code
* @return Đoạn code được tạo ra
*/
public static String jTaoCodeC (jClass_PhanDacTa jPKB_DacTa){
_phanDacTa = jPKB_DacTa;
jClass_PhanKhaiBao jPKB_KhaiBao = _phanDacTa.getPhanKhaiBao();
String str_KetQua = "";
//Tạo biến lưu lại cấp độ của dòng hiện tại (dùng cho việc lui vào khi tạo code)
//Trước mỗi dòng code phải in ra cấp độ thích hợp của dòng đó
int i_CapDo = 0;
//Tạo hàm nhập giá trị các tham số
str_KetQua += jTaoHamNhapCacThamSoC(jPKB_KhaiBao.getCacThamSo(), i_CapDo);
str_KetQua += jEnum_ThongTinBoSung.KhoangCachGiuaCacPhan.value();
//Tạo hàm xuất giá trị các tham số
str_KetQua += jTaoHamXuatCacThamSoC(jPKB_KhaiBao.getCacThamSo(), i_CapDo);
str_KetQua += jEnum_ThongTinBoSung.KhoangCachGiuaCacPhan.value();
//Tạo hàm xuất ketqua
str_KetQua += jTaoHamXuatKetQuaC(jPKB_KhaiBao.getGiaTriTraVe(), i_CapDo);
str_KetQua += jEnum_ThongTinBoSung.KhoangCachGiuaCacPhan.value();
//Ham main
str_KetQua += jTaoHamMainC(jPKB_KhaiBao, i_CapDo);
str_KetQua += jEnum_ThongTinBoSung.KhoangCachGiuaCacPhan.value();
return str_KetQua;
/*
//Tạo biến lưu lại cấp độ của dòng hiện tại (dùng cho việc lui vào khi tạo code)
//Trước mỗi dòng code phải in ra cấp độ thích hợp của dòng đó
int i_CapDo = 0;
//Tìm kiểu dữ liệu trả về
String str_KetQua = jTaoCapDo(i_CapDo) + jChuyenKieuDuLieu(jPKB_KhaiBao.getGiaTriTraVe().getKieuDuLieu());
//Ghép tên hàm và mở ngoặc nhọn vào
str_KetQua += " " + jPKB_KhaiBao.getTenHam().trim();
str_KetQua += " ";
//Thêm dấu "("
str_KetQua += "(";
//Thêm các tham số
for (jClass_Bien jB_Bien : jPKB_KhaiBao.getCacThamSo())
str_KetQua += jTaoKhaiBaoBien(jB_Bien, false, ",")+ " ";
if (str_KetQua.contains(","))
//Loại bỏ dấu "," cuối nếu có
str_KetQua = str_KetQua.substring(0, str_KetQua.lastIndexOf(","));
//Thêm dấu ")" + xuống hàng
str_KetQua += ")" + "";
//Thêm dấu "{" + xuống hàng
str_KetQua += jTaoCapDo(i_CapDo) + "\n{\n";
//Đoạn code
//Tăng cấp độ lên
i_CapDo ++;
//Tự khởi tạo giá trị trả về nếu có
if (jPKB_KhaiBao.getGiaTriTraVe().getTen().length() != 0)
str_KetQua += jTaoCapDo(i_CapDo) + jTaoKhaiBaoBien(jPKB_KhaiBao.getGiaTriTraVe()) + "\n";
str_KetQua += jTaoCapDo(i_CapDo) + "printf (\"Nhap vao tham so:\");\n";
//Trả về
str_KetQua += jTaoCapDo(i_CapDo) + "return";
if (jPKB_KhaiBao.getGiaTriTraVe().getTen().length() != 0)
str_KetQua += " " + jPKB_KhaiBao.getGiaTriTraVe().getTen();
str_KetQua += ";\n";
//Giảm cấp độ xuống
i_CapDo --;
//Thêm dấu xuống hàng và "}"
str_KetQua += jTaoCapDo(i_CapDo) + "}";
return str_KetQua;
*/
}
/**
* Tạo một hàm main với các chức năng đơn giản như nhập, xuất tham số, nhận và xuất giá trị trả về nếu có
* @param jPKB_KhaiBao Phần khai báo cần tạo hàm main
* @return Đoạn code của hàm main vừa được tạo
*/
public static String jTaoHamMainC (jClass_PhanKhaiBao jPKB_KhaiBao, int i_CapDo){
//Tạo biến lưu lại cấp độ của dòng hiện tại (dùng cho việc lui vào khi tạo code)
//Trước mỗi dòng code phải in ra cấp độ thích hợp của dòng đó
String str_KetQua = jTaoCapDo(i_CapDo) + "int _tmain (int argc, _TCHAR* argv[])\n";
//Thêm dấu xuống dòng và dấu "{"
str_KetQua += jTaoCapDo(i_CapDo) + "{\n";
//Đoạn code
//Tăng cấp độ
i_CapDo ++;
//Khởi tạo các biến
for (jClass_Bien jB_Bien : jPKB_KhaiBao.getCacThamSo())
str_KetQua += jTaoKhaiBaoBien(i_CapDo,jB_Bien) + "\n";
str_KetQua += jTaoKhaiBaoBien(i_CapDo, jPKB_KhaiBao.getGiaTriTraVe()) ;
//Gọi hàm nhập thông tin các tham số
str_KetQua += "\n";
ArrayList<jClass_Bien> jB_CacThamSo =jPKB_KhaiBao.getCacThamSo();
if (jB_CacThamSo.get(0).getKieuDuLieu().contains("*")){
jClass_Bien jB_Bien = jB_CacThamSo.get(1);
str_KetQua += jTaoCapDo(i_CapDo) + jTaoChuoiThongBaoNhapC(jB_Bien);
str_KetQua += jTaoCapDo(i_CapDo) + "scanf (\"" + jTaoChuoiThayTheBienTrongLenhPrintf(jB_Bien.getKieuDuLieu())
+ "\",&" + jB_Bien.getTen().trim() + ");\n";
}
str_KetQua += jTaoCapDo(i_CapDo) + "nhapCacThamSo_"+ jPKB_KhaiBao.getTenHam() +"(";
//Dua cac tham so vao loi goi ham
for (int i = 0; i < jPKB_KhaiBao.getCacThamSo().size(); i++){
jClass_Bien jB_Bien = jPKB_KhaiBao.getCacThamSo().get(i);
str_KetQua += jB_Bien.getTen();
if (i != jPKB_KhaiBao.getCacThamSo().size() - 1)
str_KetQua += ", ";
}
//Tạo dấu ");" và xuống dòng;
str_KetQua += ");\n";
str_KetQua += jTaoCapDo(i_CapDo)+ "if (KiemTraDuLieuNhap_"+ jPKB_KhaiBao.getTenHam()+"(";
for (jClass_Bien bien : jPKB_KhaiBao.getCacThamSo()){
//Thêm kiểu dữ liệu và ' '
// str_KetQua += jClass_BoTaoCode.jChuyenKieuDuLieu(bien.getKieuDuLieu()) + " ";
//Thêm tên biến và ", "
str_KetQua += bien.getTen() + ","+
" ";
//ví dụ đoạn code hiện tại "int (int a, "
}
if (str_KetQua.contains("," + " ")){
str_KetQua = str_KetQua.substring(0, str_KetQua.lastIndexOf("," +
" "));
}
//Thêm ') '
str_KetQua += ")";
//}
str_KetQua += " == 1)\n";
//ví dụ đoạn code hiện tại "int (int a, "
str_KetQua += jTaoCapDo(i_CapDo + 1) + jPKB_KhaiBao.getGiaTriTraVe().getTen() + " = " + jPKB_KhaiBao.getTenHam() ;
str_KetQua += "(";
for (jClass_Bien bien : jPKB_KhaiBao.getCacThamSo()){
//Thêm kiểu dữ liệu và ' '
// str_KetQua += jClass_BoTaoCode.jChuyenKieuDuLieu(bien.getKieuDuLieu()) + " ";
//Thêm tên biến và ", "
str_KetQua += bien.getTen() + ","+
" ";
//ví dụ đoạn code hiện tại "int (int a, "
}
if (str_KetQua.contains("," + " ")){
str_KetQua = str_KetQua.substring(0, str_KetQua.lastIndexOf("," +
" "));
}
str_KetQua += ");\n";
//Gọi hàm xuất giá trị các tham số
str_KetQua += jTaoCapDo(i_CapDo)+"else \n "+jTaoCapDo(i_CapDo + 1)+"printf(\"Du lieu nhap khong hop le!\");\n";
str_KetQua += jTaoCapDo(i_CapDo) + "xuatKetQua_"+jPKB_KhaiBao.getTenHam()+ "(";
//Dua cac tham so vao loi goi ham
str_KetQua += _phanDacTa.getPhanKhaiBao().getGiaTriTraVe().getTen();
//Tạo dấu ");" và xuống dòng;
str_KetQua += ");\n";
str_KetQua += jTaoCapDo(i_CapDo) + "return 0;\n";
//Giảm cấp độ
i_CapDo --;
//Thêm dấu "}"
str_KetQua += jTaoCapDo(i_CapDo) + "}";
return str_KetQua;
/*
//Tạo biến lưu lại cấp độ của dòng hiện tại (dùng cho việc lui vào khi tạo code)
//Trước mỗi dòng code phải in ra cấp độ thích hợp của dòng đó
int i_CapDo = 0;
String str_KetQua = jTaoCapDo(i_CapDo) + "int _tmain (int argc, _TCHAR* argv[])\n";
//Thêm dấu xuống dòng và dấu "{"
str_KetQua += "{\n";
//Đoạn code
//Tăng cấp độ
i_CapDo ++;
for (jClass_Bien jB_Bien : jPKB_KhaiBao.getCacThamSo()){
str_KetQua += jTaoCapDo(i_CapDo) + jTaoKhaiBaoBien(jB_Bien) + "\n";
//Tạo hàm printf thông báo nhập
str_KetQua += jTaoCapDo(i_CapDo) + jTaoChuoiThongBaoNhap(jB_Bien);//"printf (\"Nhap vao tham so " + jB_Bien.getTen().trim() + ": \");\n";
//Tạo hàm scanf nhận dữ liệu đưa vào biến
str_KetQua += jTaoCapDo(i_CapDo) + "scanf (\"" + jTaoChuoiThayTheBienTrongLenhPrintf(jB_Bien.getKieuDuLieu())
+ "\",&" + jB_Bien.getTen().trim() + ");\n";
//Tạo hàm printf xuất thông tin biến
str_KetQua += jTaoCapDo(i_CapDo) + jTaoChuoiThongBaoGiaTriBien(jB_Bien) + jB_Bien.getTen().trim() + ");\n";
}
//return
str_KetQua += jTaoCapDo(i_CapDo) + "return;\n";
//Giảm cấp độ
i_CapDo --;
//Thêm dấu "}"
str_KetQua += jTaoCapDo(i_CapDo) + "}";
return str_KetQua;
*/
}
/**
* Tạo chuổi thông báo cho người dùng nhập vào giá trị của một biến ví dụ:
* @param jB_Bien Biến cần được nhập vào
* @return Chuổi được tạo
* Ví dụ: printf("Nhap vao tham so X: "); \n
*/
//CSharp
public static String jTaoChuoiThongBaoNhapC (jClass_Bien jB_Bien){
return "printf (\"Nhap vao tham so " + jB_Bien.getTen().trim() + ": \");\n";
}
/**
* Tạo chuổi xuất thông báo giá trị của một biến lưu ý là sao khi dùng hàm này cần phải bổ sung
* giá trị của biến và ");\n";
* @param jB_Bien Biến cần thông báo giá trị
* @return Chuổi được tạo
* Ví dụ: printf ("Ban vua nhap cho X gia tri: %d \n",
*/
public static String jTaoChuoiThongBaoGiaTriBienC (jClass_Bien jB_Bien){
return "printf (\"Ban vua nhap cho " + jB_Bien.getTen().trim() + " gia tri: "
+ jTaoChuoiThayTheBienTrongLenhPrintf(jB_Bien.getKieuDuLieu()) + "\\n\", ";
}
/**
* Tạo chuổi hàm xuất giá trị các tham số
* @param jB_CacThamSo danh sách các tham số
* @param i_CapDo cấp độ (độ lùi hiện tại chỉ phục vụ cho việc định dạng code cho dể nhìn :)) của hàm xuất
* @return chuổi được tạo
*/
public static String jTaoHamXuatCacThamSoC(ArrayList<jClass_Bien> jB_CacThamSo, int i_CapDo){
String str_KetQua = jTaoCapDo(i_CapDo)+" void xuatCacThamSo_"+ _phanDacTa.getPhanKhaiBao().getTenHam()+" (";
//Dua cac bien can nhap vao voi tu cach la tham bien cua ham nhap;
for (jClass_Bien jB_Bien : jB_CacThamSo){
str_KetQua += jChuyenKieuDuLieu(jB_Bien.getKieuDuLieu().trim()) + " &" + jB_Bien.getTen().trim() + ", ";
}
if (str_KetQua.contains(","))
str_KetQua = str_KetQua.substring(0, str_KetQua.lastIndexOf(","));
//Đóng ngoặc "(" vàxuống dòng.
str_KetQua += ")\n";
//Tạo dấu "{" và tăng cấp độ
str_KetQua += jTaoCapDo(i_CapDo++) + "{\n";
//Tạo các chuổi xuất thông báo và nhập biến
for (jClass_Bien jB_Bien : jB_CacThamSo){
//Tạo hàm printf xuất thông tin biến
str_KetQua += jTaoCapDo(i_CapDo) + jTaoChuoiThongBaoGiaTriBienC(jB_Bien) /*"printf (\"Ban vua nhap cho " + jB_Bien.getTen().trim() + " gia tri: "
+ jTaoChuoiThayTheBienTrongLenhPrintf(jB_Bien.getKieuDuLieu()) + "\\n\","*/ + jB_Bien.getTen().trim() + ");\n";
}
//Giảm cấp độ và tạo dấu "}"
str_KetQua += jTaoCapDo(--i_CapDo) + "}";
return str_KetQua;
}
public static String jTaoHamXuatKetQuaC(jClass_Bien KetQua, int i_CapDo){
String str_KetQua = jTaoCapDo(i_CapDo)+" void xuatKetQua_"+ _phanDacTa.getPhanKhaiBao().getTenHam()+" (";
//Dua cac bien can nhap vao voi tu cach la tham bien cua ham nhap;
str_KetQua += jChuyenKieuDuLieu(KetQua.getKieuDuLieu().trim())+ " " + KetQua.getTen().trim() + ", ";
if (str_KetQua.contains(","))
str_KetQua = str_KetQua.substring(0, str_KetQua.lastIndexOf(","));
//Đóng ngoặc "(" vàxuống dòng.
str_KetQua += ")\n";
//Tạo dấu "{" và tăng cấp độ
str_KetQua += jTaoCapDo(i_CapDo++) + "{\n";
//Tạo các chuổi xuất thông báo và nhập biến
//Tạo hàm printf xuất thông tin biến
str_KetQua += jTaoCapDo(i_CapDo) + "printf (\"Ket qua " + KetQua.getTen().trim() + " gia tri: "
+ jTaoChuoiThayTheBienTrongLenhPrintf(KetQua.getKieuDuLieu()) + "\\n\", " /*"printf (\"Ban vua nhap cho " + jB_Bien.getTen().trim() + " gia tri: "
+ jTaoChuoiThayTheBienTrongLenhPrintf(jB_Bien.getKieuDuLieu()) + "\\n\","*/ + KetQua.getTen().trim() + ");\n";
//Giảm cấp độ và tạo dấu "}"
str_KetQua += jTaoCapDo(--i_CapDo) + "}";
return str_KetQua;
}
public static String jTaoHamNhapMangC(jClass_Bien bienMang, jClass_Bien bienDem, int CapDo){
String Kq = jTaoCapDo(CapDo) + bienMang.getTen() + " = new " +
jChuyenKieuDuLieu(bienMang.getKieuDuLieu().replace("*", "")) + "[" + bienDem.getTen() + " + 1];\n";
String jBienDem = bienDem.getTen() == "i" ? "n" : "i";
Kq += jTaoCapDo(CapDo) + "for (int " + jBienDem + " = 0; " + jBienDem + " < " + bienDem.getTen() + "; " + jBienDem + "++)\n";
Kq += jTaoCapDo(CapDo++) + "{\n";
jClass_Bien bien = new jClass_Bien(bienMang.getTen() + "[i]", bienMang.getKieuDuLieu().replace("*", ""));
Kq += jTaoCapDo(CapDo) + jTaoChuoiThongBaoNhapC(bien);//"printf (\"Nhap vao tham so " + jB_Bien.getTen().trim() + ": \");\n";
//Tạo hàm scanf nhận dữ liệu đưa vào biến
Kq += jTaoCapDo(CapDo) + "scanf (\"" + jTaoChuoiThayTheBienTrongLenhPrintf(bien.getKieuDuLieu())
+ "\",&" + bien.getTen().trim() + ");\n";
Kq += jTaoCapDo(--CapDo) + "}\n";
Kq += jTaoCapDo(CapDo) + bienMang.getTen() + "[" + bienDem.getTen() + "] = 0;\n";
return Kq;
}
public static String jTaoHamNhapCacThamSoC(ArrayList<jClass_Bien> jB_CacThamSo, int i_CapDo){
String str_KetQua = jTaoCapDo(i_CapDo)+"void nhapCacThamSo_" + _phanDacTa.getPhanKhaiBao().getTenHam() + "(";
//Dua cac bien can nhap vao voi tu cach la tham bien cua ham nhap;
for (jClass_Bien jB_Bien : jB_CacThamSo){
str_KetQua += jChuyenKieuDuLieu(jB_Bien.getKieuDuLieu().trim()) + " &" + jB_Bien.getTen().trim() + ", ";
}
if (str_KetQua.contains(","))
str_KetQua = str_KetQua.substring(0, str_KetQua.lastIndexOf(","));
//Đóng ngoặc "(" vàxuống dòng.
str_KetQua += ")\n";
//Tạo dấu "{" và tăng cấp độ
str_KetQua += jTaoCapDo(i_CapDo++) + "{\n";
if (jB_CacThamSo.get(0).getKieuDuLieu().contains("*"))
{
//"printf (\"Nhap vao tham so " + jB_Bien.getTen().trim() + ": \");\n";
//Tạo hàm scanf nhận dữ liệu đưa vào biến
str_KetQua += jTaoHamNhapMangC(jB_CacThamSo.get(0), jB_CacThamSo.get(1), i_CapDo);
}
else
//Tạo các chuổi nhap giá trị các tham số
for (jClass_Bien jB_Bien : jB_CacThamSo){
//Tạo hàm printf thông báo nhập
str_KetQua += jTaoCapDo(i_CapDo) + jTaoChuoiThongBaoNhapC(jB_Bien);//"printf (\"Nhap vao tham so " + jB_Bien.getTen().trim() + ": \");\n";
//Tạo hàm scanf nhận dữ liệu đưa vào biến
str_KetQua += jTaoCapDo(i_CapDo) + "scanf (\"" + jTaoChuoiThayTheBienTrongLenhPrintf(jB_Bien.getKieuDuLieu())
+ "\",&" + jB_Bien.getTen().trim() + ");\n";
}
//Giảm cấp độ và tạo dấu "}"
str_KetQua += jTaoCapDo(--i_CapDo) + "}";
return str_KetQua;
}
/**
* Tạo chuổi hàm nhập giá trị cho các tham số
* @param jB_CacThamSo danh sách các tham số
* @param i_CapDo cấp độ (độ lùi hiện tại chỉ phục vụ cho việc định dạng code cho dể nhìn :)) của hàm nhập
* @return chuổi được tạo
*/
/**
* Tạo chuổi hàm nhập giá trị cho các tham số
* @param jB_CacThamSo danh sách các tham số
* @param i_CapDo cấp độ (độ lùi hiện tại chỉ phục vụ cho việc định dạng code cho dể nhìn :)) của hàm nhập
* @return chuổi được tạo
*/
/**
* Phát sinh code cho phần đặc tả
* @param phanDacTa phần đặc tả cần phát sinh code
* @param i_CapDo cấp độ (độ lùi hiện tại chỉ phục vụ cho việc định dạng code cho dể nhìn :)) của hàm
* @return
*/
public static String jTaoHamTuNgonNguDacTa (jClass_PhanDacTa phanDacTa, int i_CapDo){
jClass_PhanKhaiBao jPKB_KhaiBao = phanDacTa.getPhanKhaiBao();
//Lùi code và một đoạn hợp lý (dựa vào cấp độ) và thêm kiểu dữ liệu trả về và " ("
String str_KetQua = jTaoCapDo(i_CapDo) +
jChuyenKieuDuLieu(jPKB_KhaiBao.getGiaTriTraVe().getKieuDuLieu()) +
" " + "(";
//ví dụ đoạn code hiện tại: int (
//Thêm danh sách tham số
for (jClass_Bien bien : jPKB_KhaiBao.getCacThamSo()){
//Thêm kiểu dữ liệu và ' '
str_KetQua += jChuyenKieuDuLieu(bien.getKieuDuLieu()) + " ";
//Thêm tên biến và ", "
str_KetQua += bien.getTen() + ","+
" ";
//ví dụ đoạn code hiện tại "int (int a, "
}
//ví dụ đoạn code hiện tại "int (int a, int b, "
//Loại bỏ ", " dư (nếu có)
if (str_KetQua.contains("," + " "))
str_KetQua = str_KetQua.substring(0, str_KetQua.lastIndexOf("," +
" "));
//Thêm ') '
str_KetQua += ")";
//ví dụ đoạn code hiện tại "int (int a, int b)"
//Thêm dấu xuống dòng, "{" và dấu xuống dòng
str_KetQua += jTaoCapDo(i_CapDo) + "\n{\n";
/*ví dụ đoạn code hiện tại "int (int a, int b)
* {
* "
* Kể từ đây vì chỉ minh họa từng dòng code
*/
//-------------------Đoạn code thực hiện chương trình-------------------
//Tăng cấp độ
i_CapDo++;
//Khai báo biến trả về (nếu có) ví dụ: "int result = 0;\n"
if (jPKB_KhaiBao.getGiaTriTraVe().getTen().length() != 0)
str_KetQua += jTaoCapDo(i_CapDo) + jTaoKhaiBaoBien(i_CapDo,jPKB_KhaiBao.getGiaTriTraVe()) + "\n";
//Tạo phần trả về ví dụ: "return result;\"
str_KetQua += jTaoCapDo(i_CapDo) + "return " + jPKB_KhaiBao.getGiaTriTraVe().getTen() + ";\n";
//-----------------Kết thục đoạn code thực hiện chương trình------------
//Giảm cấp độ và tạo dấu "}"
str_KetQua += jTaoCapDo(--i_CapDo) + "}";
return str_KetQua;
}
public static String jTaoChuoiThongBaoNhapCSharp (jClass_Bien jB_Bien){
return "Console.Write(\"Nhap vao tham so " + jB_Bien.getTen().trim() + ": \");\n";
}
public static String jTaoChuoiThongBaoGiaTriBienCSharp (jClass_Bien jB_Bien){
String kq = "Console.Write (\"Ban vua nhap cho " + jB_Bien.getTen().trim() + " gia tri: "
+ "\\n\");\n " ;
kq +=jTaoCapDo(1)+ "Console.Write(" + jB_Bien.getTen()+");\n";
return kq;
}
public static String jTaoHamNhapMangCSharp(jClass_Bien bienMang, jClass_Bien bienDem, int CapDo){
String Kq = jTaoCapDo(CapDo) + bienMang.getTen() + " = new " +
jChuyenKieuDuLieu(bienMang.getKieuDuLieu().replace("*", "")) + "[" + bienDem.getTen() + " + 1];\n";
String jBienDem = bienDem.getTen() == "i" ? "n" : "i";
Kq += jTaoCapDo(CapDo) + "for (int " + jBienDem + " = 0; " + jBienDem + " < " + bienDem.getTen() + "; " + jBienDem + "++)\n";
Kq += jTaoCapDo(CapDo++) + "{\n";
jClass_Bien bien = new jClass_Bien(bienMang.getTen() + "[i]", bienMang.getKieuDuLieu().replace("*", ""));
Kq += jTaoCapDo(CapDo) + jTaoChuoiThongBaoNhapCSharp(bien);//"printf (\"Nhap vao tham so " + jB_Bien.getTen().trim() + ": \");\n";
//Tạo hàm scanf nhận dữ liệu đưa vào biến
Kq += jTaoCapDo(CapDo) + bien.getTen().trim() +"=Console.ReadLine ();\n";
Kq += jTaoCapDo(--CapDo) + "}\n";
Kq += jTaoCapDo(CapDo) + bienMang.getTen() + "[" + bienDem.getTen() + "] = 0;\n";
return Kq;
}
public static String jTaoHamNhapCacThamSoCSharp(ArrayList<jClass_Bien> jB_CacThamSo, int i_CapDo){
String str_KetQua = jTaoCapDo(i_CapDo)+"public static void nhapCacThamSo_"+ _phanDacTa.getPhanKhaiBao().getTenHam()+"(";
//Dua cac bien can nhap vao voi tu cach la tham bien cua ham nhap;
for (jClass_Bien jB_Bien : jB_CacThamSo){
str_KetQua += "ref " + jChuyenKieuDuLieuCS(jB_Bien.getKieuDuLieu().trim()) + " " + jB_Bien.getTen().trim() + ", ";
}
if (str_KetQua.contains(","))
str_KetQua = str_KetQua.substring(0, str_KetQua.lastIndexOf(","));
//Đóng ngoặc "(" vàxuống dòng.
str_KetQua += ")\n";
//Tạo dấu "{" và tăng cấp độ
str_KetQua += jTaoCapDo(i_CapDo++) + "{\n";
//Tạo các chuổi xuất giá trị các tham số
for (jClass_Bien jB_Bien : jB_CacThamSo){
//Tạo hàm printf thông báo nhập
str_KetQua += jTaoCapDo(i_CapDo) + jTaoChuoiThongBaoNhapCSharp(jB_Bien);
//"printf (\"Nhap vao tham so " + jB_Bien.getTen().trim() + ": \");\n";
//Tạo hàm scanf nhận dữ liệu đưa vào biến
str_KetQua += jTaoCapDo(i_CapDo) +
jB_Bien.getTen().trim() + " ="+ jChuyenKieuDuLieuCS(jB_Bien.getKieuDuLieu())+".Parse("+ "Console.ReadLine());\n";
}
//Giảm cấp độ và tạo dấu "}"
str_KetQua += jTaoCapDo(--i_CapDo) + "}";
return str_KetQua;
}
// CSharp
public static String jTaoHamXuatCacThamSoCSharp(ArrayList<jClass_Bien> jB_CacThamSo, int i_CapDo){
String str_KetQua = jTaoCapDo(i_CapDo)+"public static void xuatCacThamSo_"+ _phanDacTa.getPhanKhaiBao().getTenHam()+" (";
//Dua cac bien can nhap vao voi tu cach la tham bien cua ham nhap;
for (jClass_Bien jB_Bien : jB_CacThamSo){
str_KetQua += jChuyenKieuDuLieuCS(jB_Bien.getKieuDuLieu().trim()) + " " + jB_Bien.getTen().trim() + ", ";
}
if (str_KetQua.contains(","))
str_KetQua = str_KetQua.substring(0, str_KetQua.lastIndexOf(","));
//Đóng ngoặc "(" vàxuống dòng.
str_KetQua += ")\n";
//Tạo dấu "{" và tăng cấp độ
str_KetQua += jTaoCapDo(i_CapDo++) + "{\n";
//Tạo các chuổi xuất thông báo và nhập biến
for (jClass_Bien jB_Bien : jB_CacThamSo){
//Tạo hàm printf xuất thông tin biến
str_KetQua += jTaoCapDo(i_CapDo) + jTaoChuoiThongBaoGiaTriBienCSharp(jB_Bien) ;/*"printf (\"Ban vua nhap cho " + jB_Bien.getTen().trim() + " gia tri: "
+ jTaoChuoiThayTheBienTrongLenhPrintf(jB_Bien.getKieuDuLieu()) + "\\n\","*/
}
//Giảm cấp độ và tạo dấu "}"
str_KetQua += jTaoCapDo(--i_CapDo) + "}";
return str_KetQua;
}
public static String jTaoHamXuatKetQuaCSharp(jClass_Bien KetQua, int i_CapDo){
String str_KetQua = jTaoCapDo(i_CapDo)+"public static void xuatKetQua_"+ _phanDacTa.getPhanKhaiBao().getTenHam()+" (";
//Dua cac bien can nhap vao voi tu cach la tham bien cua ham nhap;
str_KetQua += jChuyenKieuDuLieuCS(KetQua.getKieuDuLieu().trim())+ " " + KetQua.getTen().trim() + ", ";
if (str_KetQua.contains(","))
str_KetQua = str_KetQua.substring(0, str_KetQua.lastIndexOf(","));
//Đóng ngoặc "(" vàxuống dòng.
str_KetQua += ")\n";
//Tạo dấu "{" và tăng cấp độ
str_KetQua += jTaoCapDo(i_CapDo++) + "{\n";
//Tạo các chuổi xuất thông báo và nhập biến
//Tạo hàm printf xuất thông tin biến
str_KetQua += jTaoCapDo(i_CapDo) + "Console.Write (\"Ket qua " + KetQua.getTen().trim() + " gia tri:\");\n ";
/*"printf (\"Ban vua nhap cho " + jB_Bien.getTen().trim() + " gia tri: "
+ jTaoChuoiThayTheBienTrongLenhPrintf(jB_Bien.getKieuDuLieu()) + "\\n\","*/
str_KetQua += jTaoCapDo(i_CapDo)+"Console.Write("+KetQua.getTen().trim() + ");\n";
//Giảm cấp độ và tạo dấu "}"
str_KetQua += jTaoCapDo(--i_CapDo) + "}";
return str_KetQua;
}
public static String jTaoHamMainCSharp (jClass_PhanKhaiBao jPKB_KhaiBao, int i_CapDo){
//Tạo biến lưu lại cấp độ của dòng hiện tại (dùng cho việc lui vào khi tạo code)
//Trước mỗi dòng code phải in ra cấp độ thích hợp của dòng đó
String str_KetQua = jTaoCapDo(i_CapDo) + "static void Main (string[] args)\n";
//Thêm dấu xuống dòng và dấu "{"
str_KetQua += jTaoCapDo(i_CapDo) + "{\n";
//Đoạn code
//Tăng cấp độ
i_CapDo ++;
//Khởi tạo các biến
for (jClass_Bien jB_Bien : jPKB_KhaiBao.getCacThamSo())
str_KetQua += jTaoKhaiBaoBienCS(i_CapDo,jB_Bien, true, ";") + "\n";
str_KetQua += jTaoKhaiBaoBienCS(i_CapDo, jPKB_KhaiBao.getGiaTriTraVe(), true, ";") ;
//Gọi hàm nhập thông tin các tham số
str_KetQua += "\n";
ArrayList<jClass_Bien> jB_CacThamSo =jPKB_KhaiBao.getCacThamSo();
if (jB_CacThamSo.get(0).getKieuDuLieu().contains("*")){
jClass_Bien jB_Bien = jB_CacThamSo.get(1);
str_KetQua += jTaoCapDo(i_CapDo) + jTaoChuoiThongBaoNhapCSharp(jB_Bien);
str_KetQua += jTaoCapDo(i_CapDo) + jB_Bien.getTen().trim()+" = Console.ReadLine();\n";
}
str_KetQua += jTaoCapDo(i_CapDo) + "nhapCacThamSo_"+ jPKB_KhaiBao.getTenHam() +"(";
//Dua cac tham so vao loi goi ham
for (int i = 0; i < jPKB_KhaiBao.getCacThamSo().size(); i++){
jClass_Bien jB_Bien = jPKB_KhaiBao.getCacThamSo().get(i);
str_KetQua += "ref ";
str_KetQua += jB_Bien.getTen();
if (i != jPKB_KhaiBao.getCacThamSo().size() - 1)
str_KetQua += ", ";
}
//Tạo dấu ");" và xuống dòng;
str_KetQua += ");\n";
str_KetQua += jTaoCapDo(i_CapDo)+ "if (KiemTraDuLieuNhap_"+ jPKB_KhaiBao.getTenHam()+"(";
for (jClass_Bien bien : jPKB_KhaiBao.getCacThamSo()){
//Thêm kiểu dữ liệu và ' '
// str_KetQua += jClass_BoTaoCode.jChuyenKieuDuLieu(bien.getKieuDuLieu()) + " ";
//Thêm tên biến và ", "
str_KetQua += bien.getTen() + ","+
" ";
//ví dụ đoạn code hiện tại "int (int a, "
}
if (str_KetQua.contains("," + " ")){
str_KetQua = str_KetQua.substring(0, str_KetQua.lastIndexOf("," +
" "));
}
//Thêm ') '
str_KetQua += ")";
//}
str_KetQua += " == true)\n";
//ví dụ đoạn code hiện tại "int (int a, "
str_KetQua += jTaoCapDo(i_CapDo + 1) + jPKB_KhaiBao.getGiaTriTraVe().getTen() + " = " + jPKB_KhaiBao.getTenHam() ;
str_KetQua += "(";
for (jClass_Bien bien : jPKB_KhaiBao.getCacThamSo()){
//Thêm kiểu dữ liệu và ' '
// str_KetQua += jClass_BoTaoCode.jChuyenKieuDuLieu(bien.getKieuDuLieu()) + " ";
//Thêm tên biến và ", "
str_KetQua += bien.getTen() + ","+
" ";
//ví dụ đoạn code hiện tại "int (int a, "
}
if (str_KetQua.contains("," + " ")){
str_KetQua = str_KetQua.substring(0, str_KetQua.lastIndexOf("," +
" "));
}
str_KetQua += ");\n";
str_KetQua += jTaoCapDo(i_CapDo)+"else \n "+jTaoCapDo(i_CapDo + 1)+"Console.Write(\"Du lieu nhap khong hop le!\");\n";
//Gọi hàm xuất giá trị các tham số
str_KetQua += jTaoCapDo(i_CapDo) + "xuatKetQua_"+jPKB_KhaiBao.getTenHam()+ "(";
//Dua cac tham so vao loi goi ham
str_KetQua += _phanDacTa.getPhanKhaiBao().getGiaTriTraVe().getTen();
//Tạo dấu ");" và xuống dòng;
str_KetQua += ");\n";
str_KetQua += jTaoCapDo(i_CapDo) + "return;\n";
//Giảm cấp độ
i_CapDo --;
//Thêm dấu "}"
str_KetQua += jTaoCapDo(i_CapDo) + "}";
return str_KetQua;
}
public static String jTaoCodeCSharp (jClass_PhanDacTa jPKB_DacTa){
_phanDacTa = jPKB_DacTa;
jClass_PhanKhaiBao jPKB_KhaiBao = _phanDacTa.getPhanKhaiBao();
String str_KetQua = "";
//Tạo biến lưu lại cấp độ của dòng hiện tại (dùng cho việc lui vào khi tạo code)
//Trước mỗi dòng code phải in ra cấp độ thích hợp của dòng đó
int i_CapDo = 0;
//Tạo hàm nhập giá trị các tham số
str_KetQua += jTaoHamNhapCacThamSoCSharp(jPKB_KhaiBao.getCacThamSo(), i_CapDo);
str_KetQua += jEnum_ThongTinBoSung.KhoangCachGiuaCacPhan.value();
//Tạo hàm xuất giá trị các tham số
str_KetQua += jTaoHamXuatCacThamSoCSharp(jPKB_KhaiBao.getCacThamSo(), i_CapDo);
str_KetQua += jEnum_ThongTinBoSung.KhoangCachGiuaCacPhan.value();
//Tạo hàm xuất ketqua
str_KetQua += jTaoHamXuatKetQuaCSharp(jPKB_KhaiBao.getGiaTriTraVe(), i_CapDo);
str_KetQua += jEnum_ThongTinBoSung.KhoangCachGiuaCacPhan.value();
//Ham main
str_KetQua += jTaoHamMainCSharp(jPKB_KhaiBao, i_CapDo);
str_KetQua += jEnum_ThongTinBoSung.KhoangCachGiuaCacPhan.value();
return str_KetQua;
}
} | Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package _bai02_phantichphankhaibao;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
*
* @author Administrator
*/
public class jClass_TenBien {
public static Boolean jKiemTraChuoiHopDinhDang(String str_ChuoiCanKienTra) {
Pattern pat=Pattern.compile(jEnum_ChuoiDinhDang.TenBien.value());
Matcher matcher =pat.matcher(str_ChuoiCanKienTra);
return matcher.matches();
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package _bai02_phantichphankhaibao;
/**
*
* @author Administrator
*/
enum jEnum_DauPhanCach{
//Doi voi cac ky tu dac biet phai dung them dau '\\'
TenHam_PhanConLai("\\("),
GiaTriTraVe_CacThamSo("\\)"),
CacThamSoVoiNhau(","),
TenBien_KieuDuLieu("\\:");
private final String value;
jEnum_DauPhanCach(String value) {
this.value = value;
}
public String value(){
return value;
}
};
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package _bai02_phantichphankhaibao;
/**
*
* @author Administrator
*/
public enum jEnum_CacKyTuDacBietCoTheChoNguoiDungDinhNghia {
Thuoc ("TH");
private String value;
jEnum_CacKyTuDacBietCoTheChoNguoiDungDinhNghia(String value) {
this.value = value;
}
String value(){
return this.getValue();
}
/**
* @return the value
*/
public String getValue() {
return value;
}
/**
* @param value the value to set
*/
public void setValue(String value) {
this.value = value;
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package _bai02_phantichphankhaibao;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JOptionPane;
/**
*
* @author Administrator
*/
public class jClass_BieuThucLogic implements Interface_CacThanhPhanDacTa{
private String _DoiTuong1 = "";
private String _PhepToan = "";
private String _DoiTuong2 = "";
private static String _BieuThucDinhDang = "(\\(\\s*"+jEnum_ChuoiDinhDang.GiaTri.value()
+ "\\s*" + jEnum_ChuoiDinhDang.CacToanTuLogic.value()
+ "\\s*" + jEnum_ChuoiDinhDang.GiaTri.value() + "\\s*\\))|(\\s*"+jEnum_ChuoiDinhDang.GiaTri.value()
+ "\\s*" + jEnum_ChuoiDinhDang.CacToanTuLogic.value()
+ "\\s*" + jEnum_ChuoiDinhDang.GiaTri.value() + "\\s*)";
//private static String _BieuThucDinhDang = "\\(.*\\)?.*";
// <editor-fold defaultstate="collapsed" desc="getter and setter">
public jClass_BieuThucLogic(){
}
/**
* @return the _DoiTuong1
*/
public String getDoiTuong1() {
return _DoiTuong1;
}
/**
* @param DoiTuong1 the _DoiTuong1 to set
*/
public void setDoiTuong1(String DoiTuong1) {
this._DoiTuong1 = DoiTuong1;
}
/**
* @return the _PhepToan
*/
public String getPhepToan() {
return _PhepToan;
}
/**
* @param PhepToan the _PhepToan to set
*/
public void setPhepToan(String PhepToan) {
this._PhepToan = PhepToan;
}
/**
* @return the _DoiTuong2
*/
public String getDoiTuong2() {
return _DoiTuong2;
}
/**
* @param DoiTuong2 the _DoiTuong2 to set
*/
public void setDoiTuong2(String DoiTuong2) {
this._DoiTuong2 = DoiTuong2;
}
/**
* @return the _BieuThucDinhDang
*/
public static String getBieuThucDinhDang() {
return _BieuThucDinhDang;
}
// </editor-fold>
public Boolean jKiemTraChuoiHopDinhDang (String str_ChuoiCanKienTra) {
//String str_ChuoiDaBoSungDauPhanCach = str_ChuoiCanKienTra;
//str_ChuoiDaBoSungDauPhanCach = str_ChuoiCanKienTra.replaceAll("\\)", ",\\)");
Pattern pat=Pattern.compile(_BieuThucDinhDang);
Matcher matcher =pat.matcher(str_ChuoiCanKienTra);
return matcher.matches();
}
public void jCapNhatTuChuoi(String Str_BieuThucLogic) {
Str_BieuThucLogic = Str_BieuThucLogic.trim();
//if (Str_BieuThucLogic.)
if (!jKiemTraChuoiHopDinhDang(Str_BieuThucLogic)){
String mess = "Chuoi:\n" + Str_BieuThucLogic + "\n khong hop dinh dang cua mot Bieu Thuc Logic!!!";
JOptionPane.showMessageDialog(null, mess);
throw new ExceptionInInitializerError(Str_BieuThucLogic);
}
Str_BieuThucLogic = Str_BieuThucLogic.trim();
if (Str_BieuThucLogic.contains("<"))
_PhepToan += "<";
if (Str_BieuThucLogic.contains(">"))
_PhepToan += ">";
if (Str_BieuThucLogic.contains("="))
_PhepToan += "=";
String CacDoiTuong[] = Str_BieuThucLogic.substring(1, Str_BieuThucLogic.length() - 1).split(_PhepToan);
_DoiTuong1 = CacDoiTuong[0].trim();
_DoiTuong2 = CacDoiTuong[1].trim();
}
public String jToCCode(int DoLui) {
//String str_KetQua = jClass_BoTaoCode.jTaoCapDo(DoLui);
String str_KetQua ="(" + _DoiTuong1 + " ";
if (_PhepToan.equals("="))
str_KetQua += "==";
else if (_PhepToan.equals("<>"))
str_KetQua += "!=";
else
str_KetQua += _PhepToan;
str_KetQua += " " + _DoiTuong2 + ")";
return str_KetQua;
}
public String jCSharpCode(int DoLui) {
String str_KetQua ="(" + _DoiTuong1 + " ";
if (_PhepToan.equals("="))
str_KetQua += "==";
else if (_PhepToan.equals("<>"))
str_KetQua += "!=";
else
str_KetQua += _PhepToan;
str_KetQua += " " + _DoiTuong2 + ")";
return str_KetQua;
}
public String jVBNetCode(int DoLui) {
String str_KetQua ="(" + _DoiTuong1 + " ";
if (_PhepToan.equals("="))
str_KetQua += "=";
else if (_PhepToan.equals("<>"))
str_KetQua += "<>";
else
str_KetQua += _PhepToan;
str_KetQua += " " + _DoiTuong2 + ")";
return str_KetQua;
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package _bai02_phantichphankhaibao;
/**
* Lưu thông tin của một lỗi
* @author Administrator
*/
public class jClass_Loi {
private jEnum_Loi _MoTa;
private int _ViTri;
private String _ThongTinBoSung;
/**
* @return the _Ten
*/
public jEnum_Loi getMoTa() {
return _MoTa;
}
/**
* @param Ten the _Ten to set
*/
public void setMoTa(jEnum_Loi Ten) {
this._MoTa = Ten;
}
/**
* @return the _ViTri
*/
public int getViTri() {
return _ViTri;
}
/**
* @param ViTri the _ViTri to set
*/
public void setViTri(int ViTri) {
this._ViTri = ViTri;
}
/**
* @return the _ThongTinBoSung
*/
public String getThongTinBoSung() {
return _ThongTinBoSung;
}
/**
* @param ThongTinBoSung the _ThongTinBoSung to set
*/
public void setThongTinBoSung(String ThongTinBoSung) {
this._ThongTinBoSung = ThongTinBoSung;
}
/**
* Mặc định là không có lổi
*/
public jClass_Loi(){
_MoTa = jEnum_Loi.KhongCoLoi;
_ViTri = -1;
_ThongTinBoSung = "";
}
/**
*
* @param jEL_Loi Mô tả lổi
* @param i_ViTri Vị trí lổi
* @param str_ThongTinBoSung Thông tin bổ sung
*/
public jClass_Loi(jEnum_Loi jEL_Loi, int i_ViTri, String str_ThongTinBoSung){
_MoTa = jEL_Loi;
_ViTri = i_ViTri;
_ThongTinBoSung = str_ThongTinBoSung;
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package _bai02_phantichphankhaibao;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* mot truong hop dac ta cho ra mot ket qua cu the
* vi du: (K1 = a) /\ (a >= b)
* @author Administrator
*/
public class jClass_TruongHopDacTa implements Interface_CacThanhPhanDacTa{
private jClass_BieuThucLogic[] _CacDieuKien = new jClass_BieuThucLogic[0];;
// private static String _BieuThucDinhDang = "\\(\\s*" + jEnum_ChuoiDinhDang.TenBien.value()
// + "\\s*"+ jClass_BieuThucLogic.getBieuThucDinhDang() + "\\s*" + jEnum_ChuoiDinhDang.GiaTri.value()
// + "\\s*\\)" + "(\\s*/\\\\\\s*" + jClass_BieuThucLogic.getBieuThucDinhDang() + ")*";
private static String _BieuThucDinhDang = "\\(.+\\)"+ "(\\s*/\\\\\\s*\\(.+\\))*";
// <editor-fold defaultstate="collapsed" desc="getter and setter">
public jClass_TruongHopDacTa()
{
//_CacDieuKien
}
/**
* @return the _CacDieuKien
*/
public jClass_BieuThucLogic[] getCacDieuKien() {
return _CacDieuKien;
}
/**
* @param CacDieuKien the _CacDieuKien to set
*/
public void setCacDieuKien(jClass_BieuThucLogic[] CacDieuKien) {
this.setCacDieuKien(CacDieuKien);
}
// </editor-fold>
public Boolean jKiemTraChuoiHopDinhDang (String str_ChuoiCanKienTra) {
//String str_ChuoiDaBoSungDauPhanCach = str_ChuoiCanKienTra;
//str_ChuoiDaBoSungDauPhanCach = str_ChuoiCanKienTra.replaceAll("\\)", ",\\)");
Pattern pat=Pattern.compile(getBieuThucDinhDang());
Matcher matcher =pat.matcher(str_ChuoiCanKienTra);
return matcher.matches();
}
/**
* @return the _BieuThucDinhDang
*/
public static String getBieuThucDinhDang() {
return _BieuThucDinhDang;
}
public void jCapNhatTuChuoi(String Str_BieuThucLogic) {
Str_BieuThucLogic = Str_BieuThucLogic.trim();
String CacBieuThuc[] = Str_BieuThucLogic.split("/\\\\");
_CacDieuKien = new jClass_BieuThucLogic[CacBieuThuc.length];
for (int i = 0; i < CacBieuThuc.length; i++){
_CacDieuKien[i] = new jClass_BieuThucLogic();
_CacDieuKien[i].jCapNhatTuChuoi(CacBieuThuc[i]);
}
}
public String jToCCode(int DoLui) {
String str_KetQua = jClass_BoTaoCode.jTaoCapDo(DoLui) + "if (";
int i = 1;
for (; i < _CacDieuKien.length; i++)
str_KetQua += _CacDieuKien[i].jToCCode(DoLui) + " && ";
if (str_KetQua.contains(" && "))
str_KetQua = str_KetQua.substring(0, str_KetQua.lastIndexOf(" && "));
else
str_KetQua += 1;
str_KetQua += ")\n" + jClass_BoTaoCode.jTaoCapDo(DoLui) + "{\n";
DoLui++;
str_KetQua += jClass_BoTaoCode.jTaoCapDo(DoLui) + _CacDieuKien[0].getDoiTuong1() + " = " + _CacDieuKien[0].getDoiTuong2();
str_KetQua += ";\n" + jClass_BoTaoCode.jTaoCapDo(DoLui - 1) + "}";
return str_KetQua;
}
public String jCSharpCode(int DoLui) {
String str_KetQua = jClass_BoTaoCode.jTaoCapDo(DoLui) + "if (";
int i = 1;
for (; i < _CacDieuKien.length; i++)
str_KetQua += _CacDieuKien[i].jToCCode(DoLui) + " && ";
if (str_KetQua.contains(" && "))
str_KetQua = str_KetQua.substring(0, str_KetQua.lastIndexOf(" && "));
else
str_KetQua += 1;
str_KetQua += ")\n" + jClass_BoTaoCode.jTaoCapDo(DoLui) + "{\n";
DoLui++;
str_KetQua += jClass_BoTaoCode.jTaoCapDo(DoLui) + _CacDieuKien[0].getDoiTuong1() + " = " + _CacDieuKien[0].getDoiTuong2();
str_KetQua += ";\n" + jClass_BoTaoCode.jTaoCapDo(DoLui - 1) + "}";
return str_KetQua;
}
public String jVBNetCode(int DoLui) {
String str_KetQua = jClass_BoTaoCode.jTaoCapDo(DoLui) + "if (";
int i = 1;
for (; i < _CacDieuKien.length; i++)
str_KetQua += _CacDieuKien[i].jVBNetCode(DoLui) + " AND ";
if (str_KetQua.contains(" AND "))
str_KetQua = str_KetQua.substring(0, str_KetQua.lastIndexOf(" AND "));
else
str_KetQua += 1;
str_KetQua += ")\n" + jClass_BoTaoCode.jTaoCapDo(DoLui) + "{\n";
DoLui++;
str_KetQua += jClass_BoTaoCode.jTaoCapDo(DoLui) + _CacDieuKien[0].getDoiTuong1() + " = " + _CacDieuKien[0].getDoiTuong2();
str_KetQua += ";\n" + jClass_BoTaoCode.jTaoCapDo(DoLui - 1) + "}";
return str_KetQua;
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package _bai02_phantichphankhaibao;
import java.util.ArrayList;
import java.util.regex.*;
import javax.swing.JOptionPane;
/**
*
* @author Administrator
*/
public class jClass_PhanKhaiBao implements Interface_CacThanhPhanDacTa {
private String _TenHam;
private ArrayList<jClass_Bien> _CacThamSo;
private jClass_Bien _GiaTriTraVe;
private static String _BieuThucDinhDang;
/*/**
* @return the _TenHam
*/
public String getTenHam() {
return _TenHam;
}
/**
* @param TenHam the _TenHam to set
*/
public void setTenHam(String TenHam) {
this._TenHam = TenHam;
}
/**
* @return the _CacThamSo
*/
public ArrayList<jClass_Bien> getCacThamSo() {
return _CacThamSo;
}
/**
* @param CacThamSo the _CacThamSo to set
*/
public void setCacThamSo(ArrayList<jClass_Bien> CacThamSo) {
this._CacThamSo = CacThamSo;
}
/**
* @return the _GiaTriTraVe
*/
public jClass_Bien getGiaTriTraVe() {
return _GiaTriTraVe;
}
/**
* @param GiaTriTraVe the _GiaTriTraVe to set
*/
public void setGiaTriTraVe(jClass_Bien GiaTriTraVe) {
this._GiaTriTraVe = GiaTriTraVe;
}
public jClass_PhanKhaiBao() {
_CacThamSo = new ArrayList<jClass_Bien>();
_GiaTriTraVe = new jClass_Bien();
_TenHam = "";
//_BieuThucDinhDang = "([a-zA-Z0-9._-]+)\\1+";
//_BieuThucDinhDang = "^[a-zA-Z0-9_]+\\(([a-zA-Z0-9_]:[NnRrBbQqCc])+\\)([a-zA-Z0-9_]:[NnRrBbQqCc])?";
/* Với Regex này thì khi khai báo các biến cần phải khai báo thêm dấu ','
ở phía sau biến sau cùng (phía trước dấu ')'). Cần nhớ điều này khi kiểm tra
(Thêm dấu ',' ở vị trí thích hợp vào chuổi cần kiểm tra)
*/
//Biểu thức hoàn chỉnh: "^[a-zA-Z0-9_]+\\s*\\(\\s*(([a-zA-Z0-9_]+\\s*:\\s*[a-zA-Z0-9_]\\s*,\\s*)|,*)+\\s*\\)\\s*[a-zA-Z0-9_]+\\s*:\\s*[a-zA-Z0-9_]?\\s*$";
/* Phần kiểm tra neo đầu, tên hàm với dấu phân cách tên hàm và phần còn lại
là đoạn "^[a-zA-Z0-9_]+\\s*\\(" trong đoạn hoàn chỉnh phía trên
tương đương "Max2Numbers("
*/
_BieuThucDinhDang = "^"+ jEnum_ChuoiDinhDang.TenHam.value() +
"\\s*" + jEnum_DauPhanCach.TenHam_PhanConLai.value();
/* Phần kiểm tra tên các biến, dấu phân cách tên biến_kiểu dữ liệu và dấu phân cách các biến với nhau
là đoạn "\\s*([a-zA-Z0-9_]+\\s*:\\s*[NnRrBbQqCc]\\s*,\\s*)+" trong đoạn hoàn chỉnh phía trên
tương đương "v1 : x, v2 : y," nên nhớ là dư một dấu ','
*/
_BieuThucDinhDang += "\\s*(("+ jEnum_ChuoiDinhDang.TenBien.value() + "\\s*";
_BieuThucDinhDang += jEnum_DauPhanCach.TenBien_KieuDuLieu.value() +
"\\s*" + jEnum_ChuoiDinhDang.KieuDuLieu.value() + "\\s*";
_BieuThucDinhDang += jEnum_DauPhanCach.CacThamSoVoiNhau.value() + "\\s*)*|,)";
/* Phần kiểm tra tên dấu phân cách phần trả về với các tham số, phần trả về và neo cuối
là đoạn "\\s*\\)\\s*[a-zA-Z0-9_]+\\s*:\\s*[NnRrBbQqCc]$" trong đoạn hoàn chỉnh phía trên
tương đương ")return:R"
*/
_BieuThucDinhDang += "\\s*" + jEnum_DauPhanCach.GiaTriTraVe_CacThamSo.value();
_BieuThucDinhDang += "\\s*(" + jEnum_ChuoiDinhDang.TenBien.value() + "\\s*" +
jEnum_DauPhanCach.TenBien_KieuDuLieu.value() + "\\s*" + jEnum_ChuoiDinhDang.KieuDuLieu.value() + ")?\\s*$";
}
/**
*
* @return chuổi kết quả để xuất ra màn hình. Có dạng:
* Tên hàm: Max2Numbers
* Các biến: số lượng: 2
* 1. Tên: x Kiểu dữ liệu: N
* 2. Tên: y Kiểu dữ liệu: R
* Trả về:
* Tên: result Kiểu dữ liệu: R
*
*/
@Override
public String toString() {
//Tạo chuổi: "Tên hàm: "
String Str_KetQua = jEnum_ThongTinBoSung.TenHam.value();
Str_KetQua += jEnum_ThongTinBoSung.KhoangCachTrongMotPhan.value();
//Bổ sung tên hàm:
Str_KetQua += _TenHam.trim();
Str_KetQua += jEnum_ThongTinBoSung.KhoangCachGiuaCacPhan.value();
//Tạo chuổi: "Số lượng tham số: "
Str_KetQua += jEnum_ThongTinBoSung.SoLuongThamSo.value();
Str_KetQua += jEnum_ThongTinBoSung.KhoangCachTrongMotPhan.value();
//Bổ sung số lượng tham số
int i_SoLuongThamSo = _CacThamSo.size();
Str_KetQua += String.valueOf(i_SoLuongThamSo);
Str_KetQua += jEnum_ThongTinBoSung.KhoangCachGiuaChaCon.value();
//Tạo chuổi: "Chi tiết các tham số:"
Str_KetQua += jEnum_ThongTinBoSung.CacThamSo.value();
//Tạo các chuổi thông tin chi tiết các tham số
for (jClass_Bien jB_Tam : _CacThamSo) {
Str_KetQua += jEnum_ThongTinBoSung.KhoangCachGiuaChaCon.value();
Str_KetQua += jEnum_ThongTinBoSung.KhoangCachLuiGiuaChaCon.value();
Str_KetQua += _CacThamSo.indexOf(jB_Tam) + 1 + ")" + jEnum_ThongTinBoSung.KhoangCachNho.value();
Str_KetQua += jB_Tam.toString();
}
Str_KetQua += jEnum_ThongTinBoSung.KhoangCachGiuaCacPhan.value();
//Tạo chuổi: "Trả về: "
Str_KetQua += jEnum_ThongTinBoSung.GiaTriTraVe.value();
Str_KetQua += jEnum_ThongTinBoSung.KhoangCachGiuaChaCon.value();
Str_KetQua += jEnum_ThongTinBoSung.KhoangCachTrongMotPhan.value();
//Bổ sung giá trị trả về:
Str_KetQua += _GiaTriTraVe.toString();
Str_KetQua += jEnum_ThongTinBoSung.KhoangCachGiuaCacPhan.value();
return Str_KetQua;
}
/**
*
* Tách chuổi và đưa và các thuộc tính của lớp jClass_PhaKhaiBao
* @param Str_KhaiBao chuoi khai bao hop le vi du: Max2Numbers (v1: R, v2: R) result: R
*/
public void jCapNhatTuChuoi(String Str_KhaiBao) {
//Tách tên hàm ra khỏi các phần còn lại
if (!jKiemTraChuoiHopDinhDang(Str_KhaiBao)){
String mess = "Chuoi:\n" + Str_KhaiBao + "\n khong hop dinh dang cua mot phan Khai Bao!!!";
JOptionPane.showMessageDialog(null, mess);
throw new ExceptionInInitializerError(Str_KhaiBao);
}
String Str_KyTuTachChuoi = jEnum_DauPhanCach.TenHam_PhanConLai.value();
String[] StrArr_TachTenHam = Str_KhaiBao.split(Str_KyTuTachChuoi);
//Xác định tên hàm
setTenHam(StrArr_TachTenHam[0]);
//Tách giá trị trả về ra khỏi các tham số
String[] StrArr_TachGiaTriTraVe = StrArr_TachTenHam[1].split(jEnum_DauPhanCach.GiaTriTraVe_CacThamSo.value());
//Xác định biến trả về
jClass_Bien jB_GiaTriTraVe = new jClass_Bien();
if (StrArr_TachGiaTriTraVe.length > 1) //Nếu có giá trị trả về thì cập nhật
{
jB_GiaTriTraVe.jCapNhatTuChuoi(StrArr_TachGiaTriTraVe[1]);
}
//Nếu không sẽ trả về biến có tên là "" và khi xuất ra chuổi sẽ được "void"
setGiaTriTraVe(jB_GiaTriTraVe);
//Xác định các tham số
//String Str_ChuoiCacThamSo = StrArr_TachGiaTriTraVe[0];
//Lấy các chuổi chứa các thông tin về các tham số
if (StrArr_TachGiaTriTraVe[0].trim().length() == 0){
setCacThamSo(new ArrayList<jClass_Bien>(0));
//if (StrArr_TachGiaTriTraVe[0].length() > 0){
return;
}
String[] StrArr_CacThamSo = StrArr_TachGiaTriTraVe[0].split(jEnum_DauPhanCach.CacThamSoVoiNhau.value());
//Đếm số lượng tham số
int i_SoLuongThamSo = StrArr_CacThamSo.length;
ArrayList<jClass_Bien> jB_CacThamSo = new ArrayList(i_SoLuongThamSo);
for (int i = 0; i < i_SoLuongThamSo; i++) {
jClass_Bien jB_Tam = new jClass_Bien();
jB_Tam.jCapNhatTuChuoi(StrArr_CacThamSo[i]);
jB_CacThamSo.add(jB_Tam);
}
setCacThamSo(jB_CacThamSo);
}
/**
* @return the _BieuThucDinhDang
*/
public static String getBieuThucDinhDang() {
return _BieuThucDinhDang;
}
/**
* @param BieuThucDinhDang the _BieuThucDinhDang to set
*/
public static void setBieuThucDinhDang(String BieuThucDinhDang) {
_BieuThucDinhDang = BieuThucDinhDang;
}
/**
* Kiểm tra xem một chuổi có thỏa biểu thức định dạng không.
* Nhớ thêm dấu ',' vào vị trí thích hợp (xem phần hàm khởi tạo để biết thêm chi tiết)
* @param str_ChuoiCanKienTra
* @return
*/
public Boolean jKiemTraChuoiHopDinhDang (String str_ChuoiCanKienTra) {
String str_ChuoiDaBoSungDauPhanCach = str_ChuoiCanKienTra;
str_ChuoiDaBoSungDauPhanCach = str_ChuoiCanKienTra.replaceAll("\\)", ",\\)");
Pattern pat=Pattern.compile(_BieuThucDinhDang);
Matcher matcher =pat.matcher(str_ChuoiDaBoSungDauPhanCach);
return matcher.matches();
}
/**
*
* @return số thứ tự của biến đầu tiên trùng tên với biến trước đó,
* hoặc -1 nếu là kết quả trả về, -2 nếu không có biến trùng.
* Kiểm tra bằng cách loại bỏ các trường hợp trùng tên.
*/
public int jKiemTraCacBienKhongTrungTen () {
ArrayList<jClass_Bien> jBArr_CacThamSo= getCacThamSo();
if (jBArr_CacThamSo.size() == 0)
return -2; //Không có tham số thì làm gì có tam số trùng :)
//Từ tham số đầu tiên đến tham số kế cuối (đã loại bỏ trường hợp tham số cuối cùng ở phía dưới)
for (int i = 0; i < jBArr_CacThamSo.size() - 1; i++){
for (int j = i + 1; j < jBArr_CacThamSo.size(); j++)
//Kiểm tra từng cặp tham số thứ i với các tham số thứ >i
if (jBArr_CacThamSo.get(i).getTen().compareTo(jBArr_CacThamSo.get(j).getTen()) == 0)
return j;
//Kiểm tra tham số thứ i có trùng tên với giá trị trả về không
if (jBArr_CacThamSo.get(i).getTen().compareTo(_GiaTriTraVe.getTen()) == 0)
return -1;
}
//Nếu tham số cuối cùng có trùng tên với giá trị trả về không. Nếu có trả về false
if (jBArr_CacThamSo.get(jBArr_CacThamSo.size() - 1).getTen().trim().compareTo(_GiaTriTraVe.getTen().trim()) == 0)
return -1;
//Không phát hiện trường hợp false trả về false.
return -2;
}
/**
*
* @param str_ChuoiDuocNhap Chuổi người dùng nhập vào cần kiểm tra xem chuổi nhập có lổi không
* @return Lổi của chuổi
*/
public jClass_Loi jKiemTraLoiCuaBieuThucDuocNhap (String str_ChuoiDuocNhap){
//Kiểm tra định dạng chuổi
if (!jKiemTraChuoiHopDinhDang(str_ChuoiDuocNhap))
return new jClass_Loi(jEnum_Loi.ChuoiKhaiBaoSaiDinhDang, 0, "");
jCapNhatTuChuoi(str_ChuoiDuocNhap);
//Kiểm tra các biến không trùng tên
int i_ViTriCuaBienTrungTenVoiBienTruocDo = jKiemTraCacBienKhongTrungTen();
if (i_ViTriCuaBienTrungTenVoiBienTruocDo != -2)//Nếu có lỗi
return new jClass_Loi(jEnum_Loi.CacBienTrungTen, 0, String.valueOf(i_ViTriCuaBienTrungTenVoiBienTruocDo));
//Kiểm tra kiểu dữ liệu
int i_ViTriCuaKieuDuLieuKhongHoTroDauTien = jKiemTraCacKieuDuLieuDuocHoTro();
if (i_ViTriCuaKieuDuLieuKhongHoTroDauTien != -2)//Nếu có lỗi
return new jClass_Loi(jEnum_Loi.KieuDuLieuKhongDuocHoTro, 0, String.valueOf(i_ViTriCuaKieuDuLieuKhongHoTroDauTien));
return new jClass_Loi();
}
/**
* Kiểm tra xem có kiệu dữ liệu không được hổ trợ không.
* @return số thứ tự của kiểu dữ liệu đầu tiên không được hổ trợ,
* hoặc -1 nếu là kết quả trả về, -2 nếu không có kiểu dữ liệu không được hộ trở.
*/
public int jKiemTraCacKieuDuLieuDuocHoTro () {
ArrayList<jClass_Bien> jBArr_CacThamSo= getCacThamSo();
//Từ tham số đầu tiên đến tham số kế cuối (đã loại bỏ trường hợp tham số cuối cùng ở phía dưới)
for (int i = 0; i < jBArr_CacThamSo.size(); i++)
if (!jBArr_CacThamSo.get(i).jKiemTraKieuDuLieu())
return i;
//Nếu kiểu dữ liệu của giá trị trả về có lỗi trả về -1
if (!_GiaTriTraVe.getKieuDuLieu().equals("") && !_GiaTriTraVe.jKiemTraKieuDuLieu())
return -1;
//Không phát hiện trường hợp lỗi trả về -2;
return -2;
}
public String jCSharpCode(int DoLui) {
jClass_PhanKhaiBao jPKB_KhaiBao = this;
//Lùi code và một đoạn hợp lý (dựa vào cấp độ) và thêm kiểu dữ liệu trả về và " ("
String str_KetQua = "";
str_KetQua += jClass_BoTaoCode.jTaoCapDo(DoLui) + " static "+
jClass_BoTaoCode.jChuyenKieuDuLieuCS(jPKB_KhaiBao.getGiaTriTraVe().getKieuDuLieu()) +
" " ;
str_KetQua += jPKB_KhaiBao.getTenHam()+" "+ "(";
//ví dụ đoạn code hiện tại: int (
//Them ten ham
//Thêm danh sách tham số
for (jClass_Bien bien : jPKB_KhaiBao.getCacThamSo()){
//Thêm kiểu dữ liệu và ' '
str_KetQua += jClass_BoTaoCode.jChuyenKieuDuLieuCS(bien.getKieuDuLieu()) + " ";
//Thêm tên biến và ", "
str_KetQua += bien.getTen() + ","+
" ";
//ví dụ đoạn code hiện tại "int (int a, "
}
//ví dụ đoạn code hiện tại "int (int a, int b, "
//Loại bỏ ", " dư (nếu có)
if (str_KetQua.contains("," + " "))
str_KetQua = str_KetQua.substring(0, str_KetQua.lastIndexOf("," +
" "));
//Thêm ') '
str_KetQua += ")";
//ví dụ đoạn code hiện tại "int (int a, int b)"
//Thêm dấu xuống dòng, "{" và dấu xuống dòng
//str_KetQua += jClass_BoTaoCode.jTaoCapDo(DoLui) + "\n{\n";
/**ví dụ đoạn code hiện tại "int (int a, int b)
* {
* "
* Kể từ đây vì chỉ minh họa từng dòng code
*/
//-------------------Đoạn code thực hiện chương trình-------------------
//Tăng cấp độ
/*DoLui++;
//Khai báo biến trả về (nếu có) ví dụ: "int result = 0;\n"
if (jPKB_KhaiBao.getGiaTriTraVe().getTen().length() != 0)
str_KetQua += jClass_BoTaoCode.jTaoCapDo(DoLui) + jClass_BoTaoCode.jTaoKhaiBaoBien(jPKB_KhaiBao.getGiaTriTraVe()) + "\n";
//Tạo phần trả về ví dụ: "return result;\"
str_KetQua += jClass_BoTaoCode.jTaoCapDo(DoLui) + "return " + jPKB_KhaiBao.getGiaTriTraVe().getTen() + ";\n";
//-----------------Kết thục đoạn code thực hiện chương trình------------
//Giảm cấp độ và tạo dấu "}"
str_KetQua += jClass_BoTaoCode.jTaoCapDo(--DoLui) + "}";
*/return str_KetQua;
}
public String jToCCode(int DoLui) {
jClass_PhanKhaiBao jPKB_KhaiBao = this;
//Lùi code và một đoạn hợp lý (dựa vào cấp độ) và thêm kiểu dữ liệu trả về và " ("
String str_KetQua = "";
str_KetQua += jClass_BoTaoCode.jTaoCapDo(DoLui) +
jClass_BoTaoCode.jChuyenKieuDuLieu(jPKB_KhaiBao.getGiaTriTraVe().getKieuDuLieu()) +
" " ;
str_KetQua += jPKB_KhaiBao.getTenHam()+" "+ "(";
//ví dụ đoạn code hiện tại: int (
//Them ten ham
//Thêm danh sách tham số
for (jClass_Bien bien : jPKB_KhaiBao.getCacThamSo()){
//Thêm kiểu dữ liệu và ' '
str_KetQua += jClass_BoTaoCode.jChuyenKieuDuLieu(bien.getKieuDuLieu()) + " ";
//Thêm tên biến và ", "
str_KetQua += bien.getTen() + ","+
" ";
//ví dụ đoạn code hiện tại "int (int a, "
}
//ví dụ đoạn code hiện tại "int (int a, int b, "
//Loại bỏ ", " dư (nếu có)
if (str_KetQua.contains("," + " "))
str_KetQua = str_KetQua.substring(0, str_KetQua.lastIndexOf("," +
" "));
//Thêm ') '
str_KetQua += ")";
return str_KetQua;
}
public String jVBNetCode(int DoLui) {
jClass_PhanKhaiBao jPKB_KhaiBao = this;
//Lùi code và một đoạn hợp lý (dựa vào cấp độ) và thêm kiểu dữ liệu trả về và " ("
String str_KetQua = "";
str_KetQua += jPKB_KhaiBao.getTenHam()+" "+ "(";
//ví dụ đoạn code hiện tại: int (
//Thêm danh sách tham số
for (jClass_Bien bien : jPKB_KhaiBao.getCacThamSo()){
//Thêm kiểu dữ liệu và ' '
str_KetQua += jClass_BoTaoCode.jChuyenKieuDuLieu(bien.getKieuDuLieu()) + " ";
//Thêm tên biến và ", "
str_KetQua += "AS ";
str_KetQua += bien.getTen() + ","+
" ";
//ví dụ đoạn code hiện tại "int (int a, "
}
//ví dụ đoạn code hiện tại "int (int a, int b, "
//Loại bỏ ", " dư (nếu có)
if (str_KetQua.contains("," + " "))
str_KetQua = str_KetQua.substring(0, str_KetQua.lastIndexOf("," +
" "));
//Thêm ') '
str_KetQua += ")";
str_KetQua += " AS ";
str_KetQua += jClass_BoTaoCode.jTaoCapDo(DoLui) +
jClass_BoTaoCode.jChuyenKieuDuLieu(jPKB_KhaiBao.getGiaTriTraVe().getKieuDuLieu()) +
" " ;
return str_KetQua;
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package _bai02_phantichphankhaibao;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JOptionPane;
/**
*
* @author Administrator
*/
public class jClass_PhanPost implements Interface_CacThanhPhanDacTa{
private int _Bai = 1;
private jClass_Bien _GiaTriTraVe = new jClass_Bien();
private jClass_TruongHopDacTa[] _CacTruongHop = new jClass_TruongHopDacTa[0];
private jClass_BieuThucLuongTu _BieuThucLuongTu;
/* private static String _BieuThucDinhDang = "(" + jClass_TruongHopDacTa.getBieuThucDinhDang() + ")|("+
"\\(\\s*(\\(\\s*" + jClass_TruongHopDacTa.getBieuThucDinhDang() + "\\s*\\)\\s*\\\\/\\s*)+\\))";
* */
private static String _BieuThucDinhDang = "(.*)|("+
"(\\(\\s*.*\\s*\\)\\s*\\\\/\\s*)+)";
public jClass_PhanPost (jClass_Bien giaTriTraVe){
_GiaTriTraVe = giaTriTraVe;
}
/**
* @return the _GiaTriTraVe
*/
public jClass_Bien getGiaTriTraVe() {
return _GiaTriTraVe;
}
/**
* @param GiaTriTraVe the _GiaTriTraVe to set
*/
public void setGiaTriTraVe(jClass_Bien GiaTriTraVe) {
this._GiaTriTraVe = GiaTriTraVe;
}
//private static String _BieuThucDinhDang = "a" + "|"+
//"\\((" + "b" + "\\\\/)+" + "b" +"\\)";
// <editor-fold defaultstate="collapsed" desc="getter and setter">
/**
* @return the _BieuThucDinhDang
*/
public static String getBieuThucDinhDang() {
return _BieuThucDinhDang;
}
// </editor-fold>
public Boolean jKiemTraChuoiHopDinhDang (String str_ChuoiCanKienTra) {
String str_ChuoiDaBoSungDauPhanCach = str_ChuoiCanKienTra;
if (str_ChuoiDaBoSungDauPhanCach.contains("\\/"))
str_ChuoiDaBoSungDauPhanCach = str_ChuoiCanKienTra.substring(0, str_ChuoiCanKienTra.length() - 1) + "\\/)";
Pattern pat=Pattern.compile(getBieuThucDinhDang());
Matcher matcher =pat.matcher(str_ChuoiDaBoSungDauPhanCach);
return matcher.matches();
}
public void jCapNhatTuChuoi(String Str_Post) {
//int i_SoTruongHop = Str_Post.
if (!jKiemTraChuoiHopDinhDang(Str_Post)){
String mess = "Chuoi:\n" + Str_Post + "\n khong hop dinh dang cua mot phan Post!!!";
JOptionPane.showMessageDialog(null, mess);
throw new ExceptionInInitializerError(Str_Post);
}
Str_Post = Str_Post.trim();
if (Str_Post.startsWith("(")){
if (Str_Post.contains("\\/")){
//Str_Post = Str_Post.trim().substring(1, Str_Post.length() - 1);
String[] Str_CacTruongHop = Str_Post.split("\\\\/");
_CacTruongHop = new jClass_TruongHopDacTa[Str_CacTruongHop.length];
for (int i = 0; i < Str_CacTruongHop.length; i++){
String str_TruongHop = Str_CacTruongHop[i];
str_TruongHop = str_TruongHop.trim();
str_TruongHop = str_TruongHop.substring(1, str_TruongHop.length() - 1);
jClass_TruongHopDacTa truongHopDacTa = new jClass_TruongHopDacTa();
truongHopDacTa.jCapNhatTuChuoi(str_TruongHop);
_CacTruongHop[i] = truongHopDacTa;
}
}
else{
_CacTruongHop = new jClass_TruongHopDacTa[1];
jClass_TruongHopDacTa truongHopDacTa = new jClass_TruongHopDacTa();
truongHopDacTa.jCapNhatTuChuoi(Str_Post);
_CacTruongHop[1] = truongHopDacTa;
}
}
else{
setBai(2);
Str_Post = Str_Post.split("=",2)[1];
Str_Post = Str_Post.trim();
_BieuThucLuongTu = new jClass_BieuThucLuongTu(_GiaTriTraVe);
_BieuThucLuongTu.jCapNhatTuChuoi(Str_Post);
}
//_CacTruongHop = new jClass_TruongHopDacTa[]
}
/**
* @return the _CacTruongHop
*/
public jClass_TruongHopDacTa[] getCacTruongHop() {
return _CacTruongHop;
}
/**
* @param CacTruongHop the _CacTruongHop to set
*/
public void setCacTruongHop(jClass_TruongHopDacTa[] CacTruongHop) {
this._CacTruongHop = CacTruongHop;
}
public String jToCCode(int DoLui) {
//throw new UnsupportedOperationException("Not supported yet.");
String str_Kq = "";
if (getBai() == 1){
for (jClass_TruongHopDacTa truongHopDacTa : _CacTruongHop)
str_Kq += truongHopDacTa.jToCCode(DoLui) + "\n\n";
str_Kq = str_Kq.substring(0, str_Kq.lastIndexOf("\n\n"));
}
else if(getBai() == 2){
str_Kq = _BieuThucLuongTu.jToCCode(DoLui);
}
return str_Kq;
}
public String jCSharpCode(int DoLui) {
//throw new UnsupportedOperationException("Not supported yet.");
String str_Kq = "";
if (getBai() == 1){
for (jClass_TruongHopDacTa truongHopDacTa : _CacTruongHop)
str_Kq += truongHopDacTa.jToCCode(DoLui) + "\n\n";
str_Kq = str_Kq.substring(0, str_Kq.lastIndexOf("\n\n"));
}
else if(getBai() == 2){
str_Kq = _BieuThucLuongTu.jToCCode(DoLui);
}
return str_Kq;
}
public String jVBNetCode(int DoLui) {
String str_Kq = "";
for (jClass_TruongHopDacTa truongHopDacTa : _CacTruongHop)
str_Kq += truongHopDacTa.jVBNetCode(DoLui) + "\n\n";
str_Kq = str_Kq.substring(0, str_Kq.lastIndexOf("\n\n"));
return str_Kq;
}
/**
* @return the _Bai
*/
public int getBai() {
return _Bai;
}
/**
* @param Bai the _Bai to set
*/
public void setBai(int Bai) {
this._Bai = Bai;
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package _bai02_phantichphankhaibao;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
*
* @author Administrator
*/
public class jClass_Bien {
private String _Ten;
private String _KieuDuLieu;
/**
* @return the _Ten
*/
public String getTen() {
return _Ten;
}
/**
* @param Ten the _Ten to set
*/
public void setTen(String Ten) {
this._Ten = Ten;
}
/**
* @return the _KieuDuLieu
*/
public String getKieuDuLieu() {
return _KieuDuLieu;
}
/**
* @param KieuDuLieu the _KieuDuLieu to set
*/
public void setKieuDuLieu(String KieuDuLieu) {
this._KieuDuLieu = KieuDuLieu;
}
public jClass_Bien() {
_Ten = "";
_KieuDuLieu = "";
}
public jClass_Bien(String Str_Ten, String Str_KieuDuLieu){
_Ten = Str_Ten;
_KieuDuLieu = Str_KieuDuLieu;
}
/**
*
* @return có dạng "Tên biến: x Kiểu dữ liệu: N"
*/
@Override
public String toString(){
if (getTen().equals(""))
return jEnum_ThongTinBoSung.KhongTraVe.value();
//Đưa tên biến vào chuổi: Tên biến: x
String Str_KetQua = jEnum_ThongTinBoSung.TenBien.value();
Str_KetQua += jEnum_ThongTinBoSung.KhoangCachNho.value();
Str_KetQua += getTen();
Str_KetQua += jEnum_ThongTinBoSung.KhoangCachTrongMotPhan.value();
//Đưa kiểu dữ liệu vào
Str_KetQua += jEnum_ThongTinBoSung.KieuDuLieu.value();
Str_KetQua += jEnum_ThongTinBoSung.KhoangCachNho.value();
Str_KetQua += getKieuDuLieu();
return Str_KetQua;
}
/**
* @param ChuoiDuocDinhDang vi du: x:N
* @param Str_ChuoiDuocDinhDang
*/
public void jCapNhatTuChuoi(String Str_ChuoiDuocDinhDang) {
setTen(Str_ChuoiDuocDinhDang.split(jEnum_DauPhanCach.TenBien_KieuDuLieu.value())[0]);
setKieuDuLieu(Str_ChuoiDuocDinhDang.split(jEnum_DauPhanCach.TenBien_KieuDuLieu.value())[1]);
}
/**
* Kiểm tra xem kiểu dữ liệu có hợp lệ không
* @return true nếu hợp lệ, false nếu không hợp lệ
*/
public Boolean jKiemTraKieuDuLieu (){
Pattern pat=Pattern.compile(jEnum_ChuoiDinhDang.CacKieuDuLieuDuocHoTro.value());
Matcher matcher =pat.matcher(_KieuDuLieu.trim());
return matcher.matches();
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package _bai02_phantichphankhaibao;
/**
*
* @author Administrator
*/
public enum jEnum_ThongTinBoSung {
/**
* ví dụ: dấu tab giửa: Tên hàm: 'và' abc
*/
KhoangCachTrongMotPhan("\t"),
/**
* ví dụ: xuống dòng hai lần
*/
KhoangCachGiuaCacPhan("\n\n"),
/**
* ví dụ: xuống dòng một lần
*/
KhoangCachGiuaChaCon("\n"),
/**
* Thường thì cấp độ con lùi vào một khoảng so với cấp độ cha
* ví dụ: \t
*/
KhoangCachLuiGiuaChaCon("\t"),
/**
* ví dụ: ' ' khoảng trắng giửa: Kiểu dữ liệu:'&' tên biến
*/
KhoangCachNho(" "),
TenHam("Tên hàm:"),
TenBien("Tên:"),
KieuDuLieu("Kiểu:"),
CacThamSo("Chi tiết:"),
SoLuongThamSo("Số tham số:"),
KhongTraVe("void"),
GiaTriTraVe("Trả về:");
private final String value;
jEnum_ThongTinBoSung(String value) {
this.value = value;
}
public String value() {
return value;
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package _bai02_phantichphankhaibao;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.text.html.HTMLDocument;
import javax.swing.text.html.HTMLWriter;
/**
* Phần đặc tả cần phát sinh code, bao gồm phần khai báo, phần pre và phần post
* @author Administrator
*/
public class jClass_PhanDacTa implements Interface_CacThanhPhanDacTa{
// jClass_TruongHopDacTa[] _CacTruongHop;
private jClass_PhanKhaiBao _phanKhaiBao = new jClass_PhanKhaiBao();
private jCLass_PhanPre _phanPre = new jCLass_PhanPre();
private jClass_PhanPost _phanPost;// = new jClass_PhanPost();
private String _BieuThucDinhDang = ".*"+"/n"+"pre\\s+"+".*"+"/n"+"post\\s+"+".*";
/**
* @return the _phanKhaiBao
*/
public jClass_PhanDacTa(){
setPhanKhaiBao(_phanKhaiBao);
_phanPost = new jClass_PhanPost(_phanKhaiBao.getGiaTriTraVe());
setPhanPre(_phanPre);
_BieuThucDinhDang = ".*"+"/n"+"pre\\s+"+".*"+"/n"+"post\\s+"+".*";
}
public jClass_PhanDacTa(jClass_PhanKhaiBao phanKhaiBao, jCLass_PhanPre phanPre,jClass_PhanPost phanPost ){
setPhanKhaiBao(phanKhaiBao);
setPhanPost(phanPost);
setPhanPre(phanPre);
_BieuThucDinhDang = ".*"+"/n"+"pre\\s+"+".*"+"/n"+"post\\s+"+".*";
}
public void jCapNhatTuChuoi(String Str_Dacta) {
String Str_KhaiBao;
String Str_Pre;
String Str_Post;
String s [] = new String[5];
s = Str_Dacta.split("pre", 2);
Str_KhaiBao = s[0].trim();
s = s[1].split("post", 2);
Str_Pre = s[0].trim();
Str_Post = s[1].trim();
getPhanKhaiBao().jCapNhatTuChuoi(Str_KhaiBao);
getPhanPost().setGiaTriTraVe(getPhanKhaiBao().getGiaTriTraVe());
getPhanPre().jCapNhatTuChuoi(Str_Pre);
getPhanPost().jCapNhatTuChuoi(Str_Post);
}
public Boolean jKiemTraChuoiHopDinhDang(String str_ChuoiCanKienTra) {
String str_ChuoiDaBoSungDauPhanCach = str_ChuoiCanKienTra;
Pattern pat=Pattern.compile(getBieuThucDinhDang());
Matcher matcher =pat.matcher(str_ChuoiDaBoSungDauPhanCach);
return matcher.matches();
}
public String taoCPre(int DoLui){
String Str_KetQua = "";
Str_KetQua += "bool KiemTraDuLieuNhap_"+_phanKhaiBao.getTenHam()+"(";
for (jClass_Bien bien : _phanKhaiBao.getCacThamSo()){
//Thêm kiểu dữ liệu và ' '
Str_KetQua += jClass_BoTaoCode.jChuyenKieuDuLieu(bien.getKieuDuLieu()) + " ";
//Thêm tên biến và ", "
Str_KetQua += bien.getTen() + ","+
" ";
//ví dụ đoạn code hiện tại "int (int a, "
}
//ví dụ đoạn code hiện tại "int (int a, int b, "
//Loại bỏ ", " dư (nếu có)
if (Str_KetQua.contains("," + " "))
Str_KetQua = Str_KetQua.substring(0, Str_KetQua.lastIndexOf("," +
" "));
//Thêm ') '
Str_KetQua += ")";
Str_KetQua+="\n"+jClass_BoTaoCode.jTaoCapDo(DoLui++) + "{\n";
// Str_KetQua += "Boolean KetQua;\n";
Str_KetQua += _phanPre.jToCCode(DoLui);
// Str_KetQua += "return KetQua;";
Str_KetQua+="\n"+jClass_BoTaoCode.jTaoCapDo(--DoLui) + "}\n";
return Str_KetQua;
}
public String taoCCode(int DoLui){
String Str_KetQua = "#include \"stdafx.h\"\n//Copy các đoạn sau vào phía dưới phần \"#include:...\" trong file Ten_Project.cpp\n";
jClass_PhanDacTa phanDacTa = new jClass_PhanDacTa(_phanKhaiBao,_phanPre,_phanPost);
Str_KetQua += taoCPre(DoLui);
Str_KetQua += "\n";
Str_KetQua += _phanKhaiBao.jToCCode(DoLui);
Str_KetQua+="\n"+jClass_BoTaoCode.jTaoCapDo(DoLui++) + "{\n";
//DoLui++;
if (getPhanPost().getBai() == 1)
Str_KetQua += jClass_BoTaoCode.jTaoKhaiBaoBien(DoLui,_phanKhaiBao.getGiaTriTraVe())+ "\n";
Str_KetQua += _phanPost.jToCCode(DoLui) + "\n";
Str_KetQua += jClass_BoTaoCode.jTaoCapDo(DoLui)+"return "+_phanKhaiBao.getGiaTriTraVe().getTen()+ ";\n";
//DoLui--;
Str_KetQua+=jClass_BoTaoCode.jTaoCapDo(--DoLui) + "}\n";
Str_KetQua += jClass_BoTaoCode.jTaoCodeC(phanDacTa) ;
//Str_KetQua += "/n}/n";
Str_KetQua += "\n";
return Str_KetQua;
}
public String jToCCode(int DoLui) {
return taoCCode(DoLui);
}
public String taoCSharpPre(int DoLui){
String Str_KetQua = jClass_BoTaoCode.jTaoCapDo(DoLui);
Str_KetQua += "public static bool KiemTraDuLieuNhap_"+_phanKhaiBao.getTenHam()+"(";
for (jClass_Bien bien : _phanKhaiBao.getCacThamSo()){
//Thêm kiểu dữ liệu và ' '
Str_KetQua += jClass_BoTaoCode.jChuyenKieuDuLieuCS(bien.getKieuDuLieu()) + " ";
//Thêm tên biến và ", "
Str_KetQua += bien.getTen() + ","+
" ";
//ví dụ đoạn code hiện tại "int (int a, "
}
//ví dụ đoạn code hiện tại "int (int a, int b, "
//Loại bỏ ", " dư (nếu có)
if (Str_KetQua.contains("," + " "))
Str_KetQua = Str_KetQua.substring(0, Str_KetQua.lastIndexOf("," +
" "));
//Thêm ') '
Str_KetQua += ")";
Str_KetQua+="\n"+jClass_BoTaoCode.jTaoCapDo(DoLui++) + "{\n";
// Str_KetQua += "Boolean KetQua;\n";
Str_KetQua += _phanPre.jCSharpCode(DoLui);
// Str_KetQua += "return KetQua;";
Str_KetQua+="\n"+jClass_BoTaoCode.jTaoCapDo(--DoLui) + "}\n";
return Str_KetQua;
}
public String taoCSharpCode(int DoLui){
String Str_KetQua = jClass_BoTaoCode.jTaoCapDo(DoLui) + "using System;\nnamespace " + _phanKhaiBao.getTenHam().trim() + "_namespaces\n";
Str_KetQua += jClass_BoTaoCode.jTaoCapDo(DoLui++) + "{\n";
Str_KetQua += jClass_BoTaoCode.jTaoCapDo(DoLui) + "class Program \n{\n";
DoLui++;
jClass_PhanDacTa phanDacTa = new jClass_PhanDacTa(_phanKhaiBao,_phanPre,_phanPost);
Str_KetQua += taoCSharpPre(DoLui);
Str_KetQua += "\n";
Str_KetQua += _phanKhaiBao.jCSharpCode(DoLui);
Str_KetQua+="\n"+jClass_BoTaoCode.jTaoCapDo(DoLui++) + "{\n";
//DoLui++;
Str_KetQua += jClass_BoTaoCode.jTaoKhaiBaoBien(DoLui,_phanKhaiBao.getGiaTriTraVe())+ "\n";
Str_KetQua += _phanPost.jCSharpCode(DoLui) + "\n";
Str_KetQua += jClass_BoTaoCode.jTaoCapDo(DoLui)+"return "+_phanKhaiBao.getGiaTriTraVe().getTen()+ ";\n";
//DoLui--;
Str_KetQua+=jClass_BoTaoCode.jTaoCapDo(--DoLui) + "}\n";
//Str_KetQua += "/n}/n";
Str_KetQua += "\n";
Str_KetQua += jClass_BoTaoCode.jTaoCodeCSharp(phanDacTa) ;
Str_KetQua+=jClass_BoTaoCode.jTaoCapDo(--DoLui) + "}\n";
Str_KetQua+=jClass_BoTaoCode.jTaoCapDo(--DoLui) + "}\n";
return Str_KetQua;
}
public String jCSharpCode(int DoLui) {
return taoCSharpCode(DoLui);
}
public String taoVBPre(int DoLui){
String Str_KetQua = "";
Str_KetQua += "function KiemTraDuLieuNhap_"+_phanKhaiBao.getTenHam()+"(";
for (jClass_Bien bien : _phanKhaiBao.getCacThamSo()){
//Thêm kiểu dữ liệu và ' '
Str_KetQua += jClass_BoTaoCode.jChuyenKieuDuLieu(bien.getKieuDuLieu()) + " ";
//Thêm tên biến và ", "
Str_KetQua += " AS ";
Str_KetQua += bien.getTen() + ","+
" ";
//ví dụ đoạn code hiện tại "int (int a, "
}
//ví dụ đoạn code hiện tại "int (int a, int b, "
//Loại bỏ ", " dư (nếu có)
if (Str_KetQua.contains("," + " "))
Str_KetQua = Str_KetQua.substring(0, Str_KetQua.lastIndexOf("," +
" "));
//Thêm ') '
Str_KetQua += ") AS Boonlean";
Str_KetQua+="\n"+jClass_BoTaoCode.jTaoCapDo(DoLui++) + "\n";
// Str_KetQua += "Boolean KetQua;\n";
Str_KetQua += _phanPre.jVBNetCode(DoLui);
// Str_KetQua += "return KetQua;";
Str_KetQua+="\n"+jClass_BoTaoCode.jTaoCapDo(--DoLui) + "End funtion\n";
return Str_KetQua;
}
public String taoVBCode(int DoLui){
String Str_KetQua = "";
jClass_PhanDacTa phanDacTa = new jClass_PhanDacTa(_phanKhaiBao,_phanPre,_phanPost);
Str_KetQua += jClass_BoTaoCode.jTaoCodeC(phanDacTa) ;
Str_KetQua += taoVBPre(DoLui);
Str_KetQua += "\n";
Str_KetQua += _phanKhaiBao.jVBNetCode(DoLui);
Str_KetQua+="\n"+jClass_BoTaoCode.jTaoCapDo(DoLui++) + "{\n";
//DoLui++;
Str_KetQua += jClass_BoTaoCode.jTaoKhaiBaoBien(DoLui,_phanKhaiBao.getGiaTriTraVe())+ "\n";
Str_KetQua += _phanPost.jVBNetCode(DoLui) + "\n";
Str_KetQua += jClass_BoTaoCode.jTaoCapDo(DoLui)+"return "+_phanKhaiBao.getGiaTriTraVe().getTen()+ ";\n";
//DoLui--;
Str_KetQua+=jClass_BoTaoCode.jTaoCapDo(--DoLui) + "}\n";
//Str_KetQua += "/n}/n";
Str_KetQua += "\n";
return Str_KetQua;
}
public String jVBNetCode(int DoLui) {
return taoVBCode(DoLui);
}
/**
* @return the _phanPre
*/
public jCLass_PhanPre getPhanPre() {
return _phanPre;
}
/**
* @param phanPre the _phanPre to set
*/
public void setPhanPre(jCLass_PhanPre phanPre) {
this._phanPre = phanPre;
}
/**
* @return the _phanPost
*/
public jClass_PhanPost getPhanPost() {
return _phanPost;
}
/**
* @param phanPost the _phanPost to set
*/
public void setPhanPost(jClass_PhanPost phanPost) {
this._phanPost = phanPost;
}
private String getBieuThucDinhDang() {
throw new UnsupportedOperationException("Not yet implemented");
}
/**
* @return the _phanKhaiBao
*/
public jClass_PhanKhaiBao getPhanKhaiBao() {
return _phanKhaiBao;
}
/**
* @param phanKhaiBao the _phanKhaiBao to set
*/
public void setPhanKhaiBao(jClass_PhanKhaiBao phanKhaiBao) {
this._phanKhaiBao = phanKhaiBao;
}
/**
* @param BieuThucDinhDang the _BieuThucDinhDang to set
*/
public void setBieuThucDinhDang(String BieuThucDinhDang) {
this._BieuThucDinhDang = BieuThucDinhDang;
}
public String taoChuoiHTML ()
{
String Kq = "";
Kq += "<html><head><title></title></head><body></body></html>";
return Kq;
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package _bai02_phantichphankhaibao;
import java.awt.Color;
import javax.swing.text.MutableAttributeSet;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
/**
*
* @author Administrator
*/
public class jClass_CacStyleChuoi {
public MutableAttributeSet mChuThuong;
public MutableAttributeSet mTenHam;
public MutableAttributeSet mTenBien;
public MutableAttributeSet mKieuDuLieu;
public jClass_CacStyleChuoi() {
//Tạo AttributeSet chữ bình thường
mChuThuong = new SimpleAttributeSet();
StyleConstants.setForeground(mChuThuong, Color.BLACK);
StyleConstants.setItalic(mChuThuong, false);
StyleConstants.setBold(mChuThuong, false);
//Tạo AttributeSet tên hàm
mTenHam = new SimpleAttributeSet();
StyleConstants.setForeground(mTenHam, Color.BLACK);
StyleConstants.setBold(mTenHam, true);
//Tạo AttributeSet tên biến
mTenBien = new SimpleAttributeSet();
StyleConstants.setForeground(mTenBien, Color.MAGENTA);
//Tạo AttributeSet kiểu dữ liệu
mKieuDuLieu = new SimpleAttributeSet();
StyleConstants.setForeground(mKieuDuLieu, Color.BLUE);
}
}
| Java |
/* NFCard is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
NFCard is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Wget. If not, see <http://www.gnu.org/licenses/>.
Additional permission under GNU GPL version 3 section 7 */
package com.sinpo.xnfc.card.pboc;
import java.util.ArrayList;
import android.content.res.Resources;
import com.sinpo.xnfc.R;
import com.sinpo.xnfc.Util;
import com.sinpo.xnfc.tech.Iso7816;
final class YangchengTong extends PbocCard {
private final static byte[] DFN_SRV = { (byte) 'P', (byte) 'A', (byte) 'Y',
(byte) '.', (byte) 'A', (byte) 'P', (byte) 'P', (byte) 'Y', };
private final static byte[] DFN_SRV_S1 = { (byte) 'P', (byte) 'A',
(byte) 'Y', (byte) '.', (byte) 'P', (byte) 'A', (byte) 'S',
(byte) 'D', };
private final static byte[] DFN_SRV_S2 = { (byte) 'P', (byte) 'A',
(byte) 'Y', (byte) '.', (byte) 'T', (byte) 'I', (byte) 'C',
(byte) 'L', };
private YangchengTong(Iso7816.Tag tag, Resources res) {
super(tag);
name = res.getString(R.string.name_lnt);
}
@SuppressWarnings("unchecked")
final static YangchengTong load(Iso7816.Tag tag, Resources res) {
/*--------------------------------------------------------------*/
// select PSF (1PAY.SYS.DDF01)
/*--------------------------------------------------------------*/
if (tag.selectByName(DFN_PSE).isOkey()) {
Iso7816.Response INFO, CASH;
/*--------------------------------------------------------------*/
// select Main Application
/*--------------------------------------------------------------*/
if (tag.selectByName(DFN_SRV).isOkey()) {
/*--------------------------------------------------------------*/
// read card info file, binary (21)
/*--------------------------------------------------------------*/
INFO = tag.readBinary(SFI_EXTRA);
/*--------------------------------------------------------------*/
// read balance
/*--------------------------------------------------------------*/
CASH = tag.getBalance(true);
/*--------------------------------------------------------------*/
// read log file, record (24)
/*--------------------------------------------------------------*/
ArrayList<byte[]> LOG1 = (tag.selectByName(DFN_SRV_S1).isOkey()) ? readLog(
tag, SFI_LOG) : null;
ArrayList<byte[]> LOG2 = (tag.selectByName(DFN_SRV_S2).isOkey()) ? readLog(
tag, SFI_LOG) : null;
/*--------------------------------------------------------------*/
// build result string
/*--------------------------------------------------------------*/
final YangchengTong ret = new YangchengTong(tag, res);
ret.parseBalance(CASH);
ret.parseInfo(INFO);
ret.parseLog(LOG1, LOG2);
return ret;
}
}
return null;
}
private void parseInfo(Iso7816.Response info) {
if (!info.isOkey() || info.size() < 50) {
serl = version = date = count = null;
return;
}
final byte[] d = info.getBytes();
serl = Util.toHexString(d, 11, 5);
version = String.format("%02X.%02X", d[44], d[45]);
date = String.format("%02X%02X.%02X.%02X - %02X%02X.%02X.%02X", d[23],
d[24], d[25], d[26], d[27], d[28], d[29], d[30]);
count = null;
}
}
| Java |
/* NFCard is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
NFCard is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Wget. If not, see <http://www.gnu.org/licenses/>.
Additional permission under GNU GPL version 3 section 7 */
package com.sinpo.xnfc.card.pboc;
import java.util.ArrayList;
import java.util.Arrays;
import android.content.res.Resources;
import android.nfc.tech.IsoDep;
import com.sinpo.xnfc.R;
import com.sinpo.xnfc.Util;
import com.sinpo.xnfc.card.CardManager;
import com.sinpo.xnfc.tech.Iso7816;
public class PbocCard {
protected final static byte[] DFI_MF = { (byte) 0x3F, (byte) 0x00 };
protected final static byte[] DFI_EP = { (byte) 0x10, (byte) 0x01 };
protected final static byte[] DFN_PSE = { (byte) '1', (byte) 'P',
(byte) 'A', (byte) 'Y', (byte) '.', (byte) 'S', (byte) 'Y',
(byte) 'S', (byte) '.', (byte) 'D', (byte) 'D', (byte) 'F',
(byte) '0', (byte) '1', };
protected final static byte[] DFN_PXX = { (byte) 'P' };
protected final static int MAX_LOG = 10;
protected final static int SFI_EXTRA = 21;
protected final static int SFI_LOG = 24;
protected final static byte TRANS_CSU = 6;
protected final static byte TRANS_CSU_CPX = 9;
protected String name;
protected String id;
protected String serl;
protected String version;
protected String date;
protected String count;
protected String cash;
protected String log;
public static String load(IsoDep tech, Resources res) {
final Iso7816.Tag tag = new Iso7816.Tag(tech);
tag.connect();
PbocCard card = null;
do {
if ((card = ShenzhenTong.load(tag, res)) != null)
break;
if ((card = BeijingMunicipal.load(tag, res)) != null)
break;
if ((card = ChanganTong.load(tag, res)) != null)
break;
if ((card = WuhanTong.load(tag, res)) != null)
break;
if ((card = YangchengTong.load(tag, res)) != null)
break;
if ((card = HardReader.load(tag, res)) != null)
break;
} while (false);
tag.close();
return (card != null) ? card.toString(res) : null;
}
protected PbocCard(Iso7816.Tag tag) {
id = tag.getID().toString();
}
protected void parseInfo(Iso7816.Response data, int dec, boolean bigEndian) {
if (!data.isOkey() || data.size() < 30) {
serl = version = date = count = null;
return;
}
final byte[] d = data.getBytes();
if (dec < 1 || dec > 10) {
serl = Util.toHexString(d, 10, 10);
} else {
final int sn = bigEndian ? Util.toIntR(d, 19, dec) : Util.toInt(d,
20 - dec, dec);
serl = String.format("%d", 0xFFFFFFFFL & sn);
}
version = (d[9] != 0) ? String.valueOf(d[9]) : null;
date = String.format("%02X%02X.%02X.%02X - %02X%02X.%02X.%02X", d[20],
d[21], d[22], d[23], d[24], d[25], d[26], d[27]);
count = null;
}
protected static boolean addLog(final Iso7816.Response r,
ArrayList<byte[]> l) {
if (!r.isOkey())
return false;
final byte[] raw = r.getBytes();
final int N = raw.length - 23;
if (N < 0)
return false;
for (int s = 0, e = 0; s <= N; s = e) {
l.add(Arrays.copyOfRange(raw, s, (e = s + 23)));
}
return true;
}
protected static ArrayList<byte[]> readLog(Iso7816.Tag tag, int sfi) {
final ArrayList<byte[]> ret = new ArrayList<byte[]>(MAX_LOG);
final Iso7816.Response rsp = tag.readRecord(sfi);
if (rsp.isOkey()) {
addLog(rsp, ret);
} else {
for (int i = 1; i <= MAX_LOG; ++i) {
if (!addLog(tag.readRecord(sfi, i), ret))
break;
}
}
return ret;
}
protected void parseLog(ArrayList<byte[]>... logs) {
final StringBuilder r = new StringBuilder();
for (final ArrayList<byte[]> log : logs) {
if (log == null)
continue;
if (r.length() > 0)
r.append("<br />--------------");
for (final byte[] v : log) {
final int cash = Util.toInt(v, 5, 4);
if (cash > 0) {
r.append("<br />").append(
String.format("%02X%02X.%02X.%02X %02X:%02X ",
v[16], v[17], v[18], v[19], v[20], v[21],
v[22]));
final char t = (v[9] == TRANS_CSU || v[9] == TRANS_CSU_CPX) ? '-'
: '+';
r.append(t).append(Util.toAmountString(cash / 100.0f));
final int over = Util.toInt(v, 2, 3);
if (over > 0)
r.append(" [o:")
.append(Util.toAmountString(over / 100.0f))
.append(']');
r.append(" [").append(Util.toHexString(v, 10, 6))
.append(']');
}
}
}
this.log = r.toString();
}
protected void parseBalance(Iso7816.Response data) {
if (!data.isOkey() || data.size() < 4) {
cash = null;
return;
}
int n = Util.toInt(data.getBytes(), 0, 4);
if (n > 100000 || n < -100000)
n -= 0x80000000;
cash = Util.toAmountString(n / 100.0f);
}
protected String formatInfo(Resources res) {
if (serl == null)
return null;
final StringBuilder r = new StringBuilder();
r.append(res.getString(R.string.lab_serl)).append(' ').append(serl);
if (version != null) {
final String sv = res.getString(R.string.lab_ver);
r.append("<br />").append(sv).append(' ').append(version);
}
if (date != null) {
final String sd = res.getString(R.string.lab_date);
r.append("<br />").append(sd).append(' ').append(date);
}
if (count != null) {
final String so = res.getString(R.string.lab_op);
final String st = res.getString(R.string.lab_op_time);
r.append("<br />").append(so).append(' ').append(count).append(st);
}
return r.toString();
}
protected String formatLog(Resources res) {
if (log == null || log.length() < 1)
return null;
final StringBuilder ret = new StringBuilder();
final String sl = res.getString(R.string.lab_log);
ret.append("<b>").append(sl).append("</b><small>");
ret.append(log).append("</small>");
return ret.toString();
}
protected String formatBalance(Resources res) {
if (cash == null || cash.length() < 1)
return null;
final String s = res.getString(R.string.lab_balance);
final String c = res.getString(R.string.lab_cur_cny);
return new StringBuilder("<b>").append(s)
.append("<font color=\"teal\"> ").append(cash).append(' ')
.append(c).append("</font></b>").toString();
}
protected String toString(Resources res) {
final String info = formatInfo(res);
final String hist = formatLog(res);
final String cash = formatBalance(res);
return CardManager.buildResult(name, info, cash, hist);
}
}
| Java |
/* NFCard is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
NFCard is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Wget. If not, see <http://www.gnu.org/licenses/>.
Additional permission under GNU GPL version 3 section 7 */
package com.sinpo.xnfc.card.pboc;
import java.util.ArrayList;
import android.content.res.Resources;
import com.sinpo.xnfc.R;
import com.sinpo.xnfc.Util;
import com.sinpo.xnfc.tech.Iso7816;
final class WuhanTong extends PbocCard {
private final static int SFI_INFO = 5;
private final static int SFI_SERL = 10;
private final static byte[] DFN_SRV = { (byte) 0x41, (byte) 0x50,
(byte) 0x31, (byte) 0x2E, (byte) 0x57, (byte) 0x48, (byte) 0x43,
(byte) 0x54, (byte) 0x43, };
private WuhanTong(Iso7816.Tag tag, Resources res) {
super(tag);
name = res.getString(R.string.name_wht);
}
@SuppressWarnings("unchecked")
final static WuhanTong load(Iso7816.Tag tag, Resources res) {
/*--------------------------------------------------------------*/
// select PSF (1PAY.SYS.DDF01)
/*--------------------------------------------------------------*/
if (tag.selectByName(DFN_PSE).isOkey()) {
Iso7816.Response SERL, INFO, CASH;
/*--------------------------------------------------------------*/
// read card info file, binary (5, 10)
/*--------------------------------------------------------------*/
if (!(SERL = tag.readBinary(SFI_SERL)).isOkey())
return null;
if (!(INFO = tag.readBinary(SFI_INFO)).isOkey())
return null;
CASH = tag.getBalance(true);
/*--------------------------------------------------------------*/
// select Main Application
/*--------------------------------------------------------------*/
if (tag.selectByName(DFN_SRV).isOkey()) {
/*--------------------------------------------------------------*/
// read balance
/*--------------------------------------------------------------*/
if (!CASH.isOkey())
CASH = tag.getBalance(true);
/*--------------------------------------------------------------*/
// read log file, record (24)
/*--------------------------------------------------------------*/
ArrayList<byte[]> LOG = readLog(tag, SFI_LOG);
/*--------------------------------------------------------------*/
// build result string
/*--------------------------------------------------------------*/
final WuhanTong ret = new WuhanTong(tag, res);
ret.parseBalance(CASH);
ret.parseInfo(SERL, INFO);
ret.parseLog(LOG);
return ret;
}
}
return null;
}
private void parseInfo(Iso7816.Response sn, Iso7816.Response info) {
if (sn.size() < 27 || info.size() < 27) {
serl = version = date = count = null;
return;
}
final byte[] d = info.getBytes();
serl = Util.toHexString(sn.getBytes(), 0, 5);
version = String.format("%02d", d[24]);
date = String.format("%02X%02X.%02X.%02X - %02X%02X.%02X.%02X", d[20],
d[21], d[22], d[23], d[16], d[17], d[18], d[19]);
count = null;
}
}
| Java |
/* NFCard is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
NFCard is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Wget. If not, see <http://www.gnu.org/licenses/>.
Additional permission under GNU GPL version 3 section 7 */
package com.sinpo.xnfc.card.pboc;
import java.util.ArrayList;
import android.content.res.Resources;
import com.sinpo.xnfc.R;
import com.sinpo.xnfc.Util;
import com.sinpo.xnfc.tech.Iso7816;
final class BeijingMunicipal extends PbocCard {
private final static int SFI_EXTRA_LOG = 4;
private final static int SFI_EXTRA_CNT = 5;
private BeijingMunicipal(Iso7816.Tag tag, Resources res) {
super(tag);
name = res.getString(R.string.name_bj);
}
@SuppressWarnings("unchecked")
final static BeijingMunicipal load(Iso7816.Tag tag, Resources res) {
/*--------------------------------------------------------------*/
// select PSF (1PAY.SYS.DDF01)
/*--------------------------------------------------------------*/
if (tag.selectByName(DFN_PSE).isOkey()) {
Iso7816.Response INFO, CNT, CASH;
/*--------------------------------------------------------------*/
// read card info file, binary (4)
/*--------------------------------------------------------------*/
INFO = tag.readBinary(SFI_EXTRA_LOG);
if (INFO.isOkey()) {
/*--------------------------------------------------------------*/
// read card operation file, binary (5)
/*--------------------------------------------------------------*/
CNT = tag.readBinary(SFI_EXTRA_CNT);
/*--------------------------------------------------------------*/
// select Main Application
/*--------------------------------------------------------------*/
if (tag.selectByID(DFI_EP).isOkey()) {
/*--------------------------------------------------------------*/
// read balance
/*--------------------------------------------------------------*/
CASH = tag.getBalance(true);
/*--------------------------------------------------------------*/
// read log file, record (24)
/*--------------------------------------------------------------*/
ArrayList<byte[]> LOG = readLog(tag, SFI_LOG);
/*--------------------------------------------------------------*/
// build result string
/*--------------------------------------------------------------*/
final BeijingMunicipal ret = new BeijingMunicipal(tag, res);
ret.parseBalance(CASH);
ret.parseInfo(INFO, CNT);
ret.parseLog(LOG);
return ret;
}
}
}
return null;
}
private void parseInfo(Iso7816.Response info, Iso7816.Response cnt) {
if (!info.isOkey() || info.size() < 32) {
serl = version = date = count = null;
return;
}
final byte[] d = info.getBytes();
serl = Util.toHexString(d, 0, 8);
version = String.format("%02X.%02X%02X", d[8], d[9], d[10]);
date = String.format("%02X%02X.%02X.%02X - %02X%02X.%02X.%02X", d[24],
d[25], d[26], d[27], d[28], d[29], d[30], d[31]);
count = null;
if (cnt != null && cnt.isOkey() && cnt.size() > 4) {
byte[] e = cnt.getBytes();
final int n = Util.toInt(e, 1, 4);
if (e[0] == 0)
count = String.format("%d ", n);
else
count = String.format("%d* ", n);
}
}
}
| Java |
/* NFCard is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
NFCard is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Wget. If not, see <http://www.gnu.org/licenses/>.
Additional permission under GNU GPL version 3 section 7 */
package com.sinpo.xnfc.card.pboc;
import java.util.ArrayList;
import android.content.res.Resources;
import com.sinpo.xnfc.R;
import com.sinpo.xnfc.tech.Iso7816;
final class ChanganTong extends PbocCard {
private final static byte[] DFN_SRV = { (byte) 0xA0, (byte) 0x00,
(byte) 0x00, (byte) 0x00, (byte) 0x03, (byte) 0x86, (byte) 0x98,
(byte) 0x07, (byte) 0x01, };
private ChanganTong(Iso7816.Tag tag, Resources res) {
super(tag);
name = res.getString(R.string.name_cac);
}
@SuppressWarnings("unchecked")
final static ChanganTong load(Iso7816.Tag tag, Resources res) {
/*--------------------------------------------------------------*/
// select PSF (1PAY.SYS.DDF01)
/*--------------------------------------------------------------*/
if (tag.selectByName(DFN_PSE).isOkey()) {
Iso7816.Response INFO, CASH;
/*--------------------------------------------------------------*/
// select Main Application
/*--------------------------------------------------------------*/
if (tag.selectByName(DFN_SRV).isOkey()) {
/*--------------------------------------------------------------*/
// read card info file, binary (21)
/*--------------------------------------------------------------*/
INFO = tag.readBinary(SFI_EXTRA);
/*--------------------------------------------------------------*/
// read balance
/*--------------------------------------------------------------*/
CASH = tag.getBalance(true);
/*--------------------------------------------------------------*/
// read log file, record (24)
/*--------------------------------------------------------------*/
ArrayList<byte[]> LOG = readLog(tag, SFI_LOG);
/*--------------------------------------------------------------*/
// build result string
/*--------------------------------------------------------------*/
final ChanganTong ret = new ChanganTong(tag, res);
ret.parseBalance(CASH);
ret.parseInfo(INFO, 4, false);
ret.parseLog(LOG);
return ret;
}
}
return null;
}
}
| Java |
/* NFCard is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
NFCard is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Wget. If not, see <http://www.gnu.org/licenses/>.
Additional permission under GNU GPL version 3 section 7 */
package com.sinpo.xnfc.card.pboc;
import java.util.ArrayList;
import android.content.res.Resources;
import com.sinpo.xnfc.R;
import com.sinpo.xnfc.Util;
import com.sinpo.xnfc.tech.Iso7816;
import com.sinpo.xnfc.tech.Iso7816.BerT;
final class HardReader extends PbocCard {
public static final byte TMPL_PDR = 0x70; // Payment Directory Entry Record
public static final byte TMPL_PDE = 0x61; // Payment Directory Entry
private HardReader(Iso7816.Tag tag, byte[] name, Resources res) {
super(tag);
this.name = (name != null) ? Util.toHexString(name, 0, name.length)
: res.getString(R.string.name_unknowntag);
}
@SuppressWarnings("unchecked")
final static HardReader load(Iso7816.Tag tag, Resources res) {
/*--------------------------------------------------------------*/
// select PSF (1PAY.SYS.DDF01)
/*--------------------------------------------------------------*/
if (!tag.selectByName(DFN_PSE).isOkey() && !tag.selectByID(DFI_MF).isOkey())
return null;
/*--------------------------------------------------------------*/
// read balance
/*--------------------------------------------------------------*/
Iso7816.Response CASH = getBalance(tag);
Iso7816.Response INFO = null;
ArrayList<byte[]> LOG = new ArrayList<byte[]>();
byte[] name = null;
/*--------------------------------------------------------------*/
// try to find AID list
/*--------------------------------------------------------------*/
ArrayList<byte[]> AIDs = findAIDs(tag);
for (final byte[] aid : AIDs) {
/*--------------------------------------------------------------*/
// select Main Application
/*--------------------------------------------------------------*/
if ((name = selectAID(tag, aid)) != null) {
/*--------------------------------------------------------------*/
// read balance
/*--------------------------------------------------------------*/
if (!CASH.isOkey())
CASH = getBalance(tag);
/*--------------------------------------------------------------*/
// read card info file, binary (21)
/*--------------------------------------------------------------*/
if (INFO == null || !INFO.isOkey())
INFO = tag.readBinary(SFI_EXTRA);
/*--------------------------------------------------------------*/
// read log file, record (24)
/*--------------------------------------------------------------*/
LOG.addAll(readLog(tag, SFI_LOG));
}
}
/*--------------------------------------------------------------*/
// try to PXX AID
/*--------------------------------------------------------------*/
if ((INFO == null || !INFO.isOkey())
&& ((name = selectAID(tag, DFN_PXX)) != null)) {
if (!CASH.isOkey())
CASH = getBalance(tag);
INFO = tag.readBinary(SFI_EXTRA);
LOG.addAll(readLog(tag, SFI_LOG));
}
/*--------------------------------------------------------------*/
// try to 0x1001 AID
/*--------------------------------------------------------------*/
if ((INFO == null || !INFO.isOkey()) && tag.selectByID(DFI_EP).isOkey()) {
name = DFI_EP;
if (!CASH.isOkey())
CASH = getBalance(tag);
INFO = tag.readBinary(SFI_EXTRA);
LOG.addAll(readLog(tag, SFI_LOG));
}
if (!CASH.isOkey() && INFO == null && LOG.isEmpty() && name == null)
return null;
/*--------------------------------------------------------------*/
// build result string
/*--------------------------------------------------------------*/
final HardReader ret = new HardReader(tag, name, res);
ret.parseBalance(CASH);
if (INFO != null)
ret.parseInfo(INFO, 0, false);
ret.parseLog(LOG);
return ret;
}
private static byte[] selectAID(Iso7816.Tag tag, byte[] aid) {
if (!tag.selectByName(DFN_PSE).isOkey()
&& !tag.selectByID(DFI_MF).isOkey())
return null;
final Iso7816.Response rsp = tag.selectByName(aid);
if (!rsp.isOkey())
return null;
Iso7816.BerTLV tlv = Iso7816.BerTLV.read(rsp);
if (tlv.t.match(Iso7816.BerT.TMPL_FCI)) {
tlv = tlv.getChildByTag(Iso7816.BerT.CLASS_DFN);
if (tlv != null)
return tlv.v.getBytes();
}
return aid;
}
private static ArrayList<byte[]> findAIDs(Iso7816.Tag tag) {
ArrayList<byte[]> ret = new ArrayList<byte[]>();
for (int i = 1; i <= 31; ++i) {
Iso7816.Response r = tag.readRecord(i, 1);
for (int p = 2; r.isOkey(); ++p) {
byte[] aid = findAID(r);
if (aid == null)
break;
ret.add(aid);
r = tag.readRecord(i, p);
}
}
return ret;
}
private static byte[] findAID(Iso7816.Response record) {
Iso7816.BerTLV tlv = Iso7816.BerTLV.read(record);
if (tlv.t.match(TMPL_PDR)) {
tlv = tlv.getChildByTag(BerT.CLASS_ADO);
if (tlv != null) {
tlv = tlv.getChildByTag(BerT.CLASS_AID);
return (tlv != null) ? tlv.v.getBytes() : null;
}
}
return null;
}
private static Iso7816.Response getBalance(Iso7816.Tag tag) {
final Iso7816.Response rsp = tag.getBalance(true);
return rsp.isOkey() ? rsp : tag.getBalance(false);
}
}
| Java |
/* NFCard is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
NFCard is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Wget. If not, see <http://www.gnu.org/licenses/>.
Additional permission under GNU GPL version 3 section 7 */
package com.sinpo.xnfc.card.pboc;
import java.util.ArrayList;
import android.content.res.Resources;
import com.sinpo.xnfc.R;
import com.sinpo.xnfc.tech.Iso7816;
final class ShenzhenTong extends PbocCard {
private final static byte[] DFN_SRV = { (byte) 'P', (byte) 'A', (byte) 'Y',
(byte) '.', (byte) 'S', (byte) 'Z', (byte) 'T' };
private ShenzhenTong(Iso7816.Tag tag, Resources res) {
super(tag);
name = res.getString(R.string.name_szt);
}
@SuppressWarnings("unchecked")
final static ShenzhenTong load(Iso7816.Tag tag, Resources res) {
/*--------------------------------------------------------------*/
// select PSF (1PAY.SYS.DDF01)
/*--------------------------------------------------------------*/
if (tag.selectByName(DFN_PSE).isOkey()) {
Iso7816.Response INFO, CASH;
/*--------------------------------------------------------------*/
// select Main Application
/*--------------------------------------------------------------*/
if (tag.selectByName(DFN_SRV).isOkey()) {
/*--------------------------------------------------------------*/
// read card info file, binary (21)
/*--------------------------------------------------------------*/
INFO = tag.readBinary(SFI_EXTRA);
/*--------------------------------------------------------------*/
// read balance
/*--------------------------------------------------------------*/
CASH = tag.getBalance(true);
/*--------------------------------------------------------------*/
// read log file, record (24)
/*--------------------------------------------------------------*/
ArrayList<byte[]> LOG = readLog(tag, SFI_LOG);
/*--------------------------------------------------------------*/
// build result string
/*--------------------------------------------------------------*/
final ShenzhenTong ret = new ShenzhenTong(tag, res);
ret.parseBalance(CASH);
ret.parseInfo(INFO, 4, true);
ret.parseLog(LOG);
return ret;
}
}
return null;
}
}
| Java |
/* NFCard is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
NFCard is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Wget. If not, see <http://www.gnu.org/licenses/>.
Additional permission under GNU GPL version 3 section 7 */
package com.sinpo.xnfc.card;
import com.sinpo.xnfc.card.pboc.PbocCard;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.IsoDep;
import android.nfc.tech.NfcF;
import android.nfc.tech.NfcV;
import android.os.Parcelable;
public final class CardManager {
private static final String SP = "<br/><img src=\"spliter\"/><br/>";
public static String[][] TECHLISTS;
public static IntentFilter[] FILTERS;
static {
try {
TECHLISTS = new String[][] { { IsoDep.class.getName() },
{ NfcV.class.getName() }, { NfcF.class.getName() }, };
FILTERS = new IntentFilter[] { new IntentFilter(
NfcAdapter.ACTION_TECH_DISCOVERED, "*/*") };
} catch (Exception e) {
}
}
public static String buildResult(String n, String i, String d, String x) {
if (n == null)
return null;
final StringBuilder s = new StringBuilder();
s.append("<br/><b>").append(n).append("</b>");
if (i != null)
s.append(SP).append(i);
if (d != null)
s.append(SP).append(d);
if (x != null)
s.append(SP).append(x);
return s.append("<br/><br/>").toString();
}
public static String load(Parcelable parcelable, Resources res) {
final Tag tag = (Tag) parcelable;
final IsoDep isodep = IsoDep.get(tag);
if (isodep != null) {
return PbocCard.load(isodep, res);
}
final NfcV nfcv = NfcV.get(tag);
if (nfcv != null) {
return VicinityCard.load(nfcv, res);
}
final NfcF nfcf = NfcF.get(tag);
if (nfcf != null) {
return OctopusCard.load(nfcf, res);
}
return null;
}
}
| Java |
/* NFCard is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
NFCard is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Wget. If not, see <http://www.gnu.org/licenses/>.
Additional permission under GNU GPL version 3 section 7 */
package com.sinpo.xnfc.card;
import android.content.res.Resources;
import android.nfc.tech.NfcV;
import com.sinpo.xnfc.R;
import com.sinpo.xnfc.Util;
final class VicinityCard {
private static final int SYS_UNKNOWN = 0x00000000;
private static final int SYS_SZLIB = 0x00010000;
private static final int DEP_SZLIB_CENTER = 0x0100;
private static final int DEP_SZLIB_NANSHAN = 0x0200;
private static final int SRV_USER = 0x0001;
private static final int SRV_BOOK = 0x0002;
public static final int SW1_OK = 0x00;
static String load(NfcV tech, Resources res) {
String data = null;
try {
tech.connect();
int pos, BLKSIZE, BLKCNT;
byte cmd[], rsp[], ID[], RAW[], STA[], flag, DSFID;
ID = tech.getTag().getId();
if (ID == null || ID.length != 8)
throw new Exception();
/*--------------------------------------------------------------*/
// get system information
/*--------------------------------------------------------------*/
cmd = new byte[10];
cmd[0] = (byte) 0x22; // flag
cmd[1] = (byte) 0x2B; // command
System.arraycopy(ID, 0, cmd, 2, ID.length); // UID
rsp = tech.transceive(cmd);
if (rsp[0] != SW1_OK)
throw new Exception();
pos = 10;
flag = rsp[1];
DSFID = ((flag & 0x01) == 0x01) ? rsp[pos++] : 0;
if ((flag & 0x02) == 0x02)
pos++;
if ((flag & 0x04) == 0x04) {
BLKCNT = rsp[pos++] + 1;
BLKSIZE = (rsp[pos++] & 0xF) + 1;
} else {
BLKCNT = BLKSIZE = 0;
}
/*--------------------------------------------------------------*/
// read first 8 block
/*--------------------------------------------------------------*/
cmd = new byte[12];
cmd[0] = (byte) 0x22; // flag
cmd[1] = (byte) 0x23; // command
System.arraycopy(ID, 0, cmd, 2, ID.length); // UID
cmd[10] = (byte) 0x00; // index of first block to get
cmd[11] = (byte) 0x07; // block count, one less! (see ISO15693-3)
rsp = tech.transceive(cmd);
if (rsp[0] != SW1_OK)
throw new Exception();
RAW = rsp;
/*--------------------------------------------------------------*/
// read last block
/*--------------------------------------------------------------*/
cmd[10] = (byte) (BLKCNT - 1); // index of first block to get
cmd[11] = (byte) 0x00; // block count, one less! (see ISO15693-3)
rsp = tech.transceive(cmd);
if (rsp[0] != SW1_OK)
throw new Exception();
STA = rsp;
data = Util.toHexString(rsp, 0, rsp.length);
/*--------------------------------------------------------------*/
// build result string
/*--------------------------------------------------------------*/
final int type = parseType(DSFID, RAW, BLKSIZE);
final String name = parseName(type, res);
final String info = parseInfo(ID, res);
final String extra = parseData(type, RAW, STA, BLKSIZE, res);
data = CardManager.buildResult(name, info, extra, null);
} catch (Exception e) {
data = null;
// data = e.getMessage();
}
try {
tech.close();
} catch (Exception e) {
}
return data;
}
private static int parseType(byte dsfid, byte[] raw, int blkSize) {
int ret = SYS_UNKNOWN;
if (blkSize == 4 && (raw[4] & 0x10) == 0x10 && (raw[14] & 0xAB) == 0xAB
&& (raw[13] & 0xE0) == 0xE0) {
ret = SYS_SZLIB;
if ((raw[13] & 0x0F) == 0x05)
ret |= DEP_SZLIB_CENTER;
else
ret |= DEP_SZLIB_NANSHAN;
if (raw[4] == 0x12)
ret |= SRV_USER;
else
ret |= SRV_BOOK;
}
return ret;
}
private static String parseName(int type, Resources res) {
if ((type & SYS_SZLIB) == SYS_SZLIB) {
final String dep;
if ((type & DEP_SZLIB_CENTER) == DEP_SZLIB_CENTER)
dep = res.getString(R.string.name_szlib_center);
else if ((type & DEP_SZLIB_NANSHAN) == DEP_SZLIB_NANSHAN)
dep = res.getString(R.string.name_szlib_nanshan);
else
dep = null;
final String srv;
if ((type & SRV_BOOK) == SRV_BOOK)
srv = res.getString(R.string.name_lib_booktag);
else if ((type & SRV_USER) == SRV_USER)
srv = res.getString(R.string.name_lib_readercard);
else
srv = null;
if (dep != null && srv != null)
return dep + " " + srv;
}
return res.getString(R.string.name_unknowntag);
}
private static String parseInfo(byte[] id, Resources res) {
final StringBuilder r = new StringBuilder();
final String i = res.getString(R.string.lab_id);
r.append("<b>").append(i).append("</b> ")
.append(Util.toHexStringR(id, 0, id.length));
return r.toString();
}
private static String parseData(int type, byte[] raw, byte[] sta,
int blkSize, Resources res) {
if ((type & SYS_SZLIB) == SYS_SZLIB) {
return parseSzlibData(type, raw, sta, blkSize, res);
}
return null;
}
private static String parseSzlibData(int type, byte[] raw, byte[] sta,
int blkSize, Resources res) {
long id = 0;
for (int i = 3; i > 0; --i)
id = (id <<= 8) | (0x000000FF & raw[i]);
for (int i = 8; i > 4; --i)
id = (id <<= 8) | (0x000000FF & raw[i]);
final String sid;
if ((type & SRV_USER) == SRV_USER)
sid = res.getString(R.string.lab_user_id);
else
sid = res.getString(R.string.lab_bktg_sn);
final StringBuilder r = new StringBuilder();
r.append("<b>").append(sid).append(" <font color=\"teal\">");
r.append(String.format("%013d", id)).append("</font></b><br />");
final String scat;
if ((type & SRV_BOOK) == SRV_BOOK) {
final byte cat = raw[12];
if ((type & DEP_SZLIB_NANSHAN) == DEP_SZLIB_NANSHAN) {
if (cat == 0x10)
scat = res.getString(R.string.name_bkcat_soc);
else if (cat == 0x20) {
if (raw[11] == (byte) 0x84)
scat = res.getString(R.string.name_bkcat_ltr);
else
scat = res.getString(R.string.name_bkcat_sci);
} else
scat = null;
} else {
scat = null;
}
if (scat != null) {
final String scl = res.getString(R.string.lab_bkcat);
r.append("<b>").append(scl).append("</b> ").append(scat)
.append("<br />");
}
}
// final int len = raw.length;
// for (int i = 1, n = 0; i < len; i += blkSize) {
// final String blk = Util.toHexString(raw, i, blkSize);
// r.append("<br />").append(n++).append(": ").append(blk);
// }
// final String blk = Util.toHexString(sta, 0, blkSize);
// r.append("<br />S: ").append(blk);
return r.toString();
}
}
| Java |
/* NFCard is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
NFCard is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Wget. If not, see <http://www.gnu.org/licenses/>.
Additional permission under GNU GPL version 3 section 7 */
package com.sinpo.xnfc.card;
import android.content.res.Resources;
import android.nfc.tech.NfcF;
import com.sinpo.xnfc.R;
import com.sinpo.xnfc.Util;
import com.sinpo.xnfc.tech.FeliCa;
final class OctopusCard {
private static final int SYS_SZT = 0x8005;
private static final int SRV_SZT = 0x0118;
private static final int SYS_OCTOPUS = 0x8008;
private static final int SRV_OCTOPUS = 0x0117;
static String load(NfcF tech, Resources res) {
final FeliCa.Tag tag = new FeliCa.Tag(tech);
/*--------------------------------------------------------------*/
// check card system
/*--------------------------------------------------------------*/
final int system = tag.getSystemCode();
final FeliCa.ServiceCode service;
if (system == SYS_OCTOPUS)
service = new FeliCa.ServiceCode(SRV_OCTOPUS);
else if (system == SYS_SZT)
service = new FeliCa.ServiceCode(SRV_SZT);
else
return null;
tag.connect();
/*--------------------------------------------------------------*/
// read service data without encryption
/*--------------------------------------------------------------*/
final float[] data = new float[] { 0, 0, 0 };
final int N = data.length;
int p = 0;
for (byte i = 0; p < N; ++i) {
final FeliCa.ReadResponse r = tag.readWithoutEncryption(service, i);
if (!r.isOkey())
break;
data[p++] = (Util.toInt(r.getBlockData(), 0, 4) - 350) / 10.0f;
}
tag.close();
/*--------------------------------------------------------------*/
// build result string
/*--------------------------------------------------------------*/
final String name = parseName(system, res);
final String info = parseInfo(tag, res);
final String hist = parseLog(null, res);
final String cash = parseBalance(data, p, res);
return CardManager.buildResult(name, info, cash, hist);
}
private static String parseName(int system, Resources res) {
if (system == SYS_OCTOPUS)
return res.getString(R.string.name_octopuscard);
if (system == SYS_SZT)
return res.getString(R.string.name_szt_f);
return null;
}
private static String parseInfo(FeliCa.Tag tag, Resources res) {
final StringBuilder r = new StringBuilder();
final String i = res.getString(R.string.lab_id);
final String p = res.getString(R.string.lab_pmm);
r.append("<b>").append(i).append("</b> ")
.append(tag.getIDm().toString());
r.append("<br />").append(p).append(' ')
.append(tag.getPMm().toString());
return r.toString();
}
private static String parseBalance(float[] value, int count, Resources res) {
if (count < 1)
return null;
final StringBuilder r = new StringBuilder();
final String s = res.getString(R.string.lab_balance);
final String c = res.getString(R.string.lab_cur_hkd);
r.append("<b>").append(s).append(" <font color=\"teal\">");
for (int i = 0; i < count; ++i)
r.append(Util.toAmountString(value[i])).append(' ');
return r.append(c).append("</font></b>").toString();
}
private static String parseLog(byte[] data, Resources res) {
return null;
}
}
| Java |
/* NFCard is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
NFCard is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Wget. If not, see <http://www.gnu.org/licenses/>.
Additional permission under GNU GPL version 3 section 7 */
package com.sinpo.xnfc;
public final class Util {
private final static char[] HEX = { '0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
private Util() {
}
public static byte[] toBytes(int a) {
return new byte[] { (byte) (0x000000ff & (a >>> 24)),
(byte) (0x000000ff & (a >>> 16)),
(byte) (0x000000ff & (a >>> 8)), (byte) (0x000000ff & (a)) };
}
public static int toInt(byte[] b, int s, int n) {
int ret = 0;
final int e = s + n;
for (int i = s; i < e; ++i) {
ret <<= 8;
ret |= b[i] & 0xFF;
}
return ret;
}
public static int toIntR(byte[] b, int s, int n) {
int ret = 0;
for (int i = s; (i >= 0 && n > 0); --i, --n) {
ret <<= 8;
ret |= b[i] & 0xFF;
}
return ret;
}
public static int toInt(byte... b) {
int ret = 0;
for (final byte a : b) {
ret <<= 8;
ret |= a & 0xFF;
}
return ret;
}
public static String toHexString(byte[] d, int s, int n) {
final char[] ret = new char[n * 2];
final int e = s + n;
int x = 0;
for (int i = s; i < e; ++i) {
final byte v = d[i];
ret[x++] = HEX[0x0F & (v >> 4)];
ret[x++] = HEX[0x0F & v];
}
return new String(ret);
}
public static String toHexStringR(byte[] d, int s, int n) {
final char[] ret = new char[n * 2];
int x = 0;
for (int i = s + n - 1; i >= s; --i) {
final byte v = d[i];
ret[x++] = HEX[0x0F & (v >> 4)];
ret[x++] = HEX[0x0F & v];
}
return new String(ret);
}
public static int parseInt(String txt, int radix, int def) {
int ret;
try {
ret = Integer.valueOf(txt, radix);
} catch (Exception e) {
ret = def;
}
return ret;
}
public static String toAmountString(float value) {
return String.format("%.2f", value);
}
}
| Java |
/* NFCard is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
NFCard is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Wget. If not, see <http://www.gnu.org/licenses/>.
Additional permission under GNU GPL version 3 section 7 */
package com.sinpo.xnfc.tech;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import android.nfc.tech.NfcF;
import com.sinpo.xnfc.Util;
public class FeliCa {
public static final byte[] EMPTY = {};
protected byte[] data;
protected FeliCa() {
}
protected FeliCa(byte[] bytes) {
data = (bytes == null) ? FeliCa.EMPTY : bytes;
}
public int size() {
return data.length;
}
public byte[] getBytes() {
return data;
}
@Override
public String toString() {
return Util.toHexString(data, 0, data.length);
}
public final static class IDm extends FeliCa {
public static final byte[] EMPTY = { 0, 0, 0, 0, 0, 0, 0, 0, };
public IDm(byte[] bytes) {
super((bytes == null || bytes.length < 8) ? IDm.EMPTY : bytes);
}
public final String getManufactureCode() {
return Util.toHexString(data, 0, 2);
}
public final String getCardIdentification() {
return Util.toHexString(data, 2, 6);
}
public boolean isEmpty() {
final byte[] d = data;
for (final byte v : d) {
if (v != 0)
return false;
}
return true;
}
}
public final static class PMm extends FeliCa {
public static final byte[] EMPTY = { 0, 0, 0, 0, 0, 0, 0, 0, };
public PMm(byte[] bytes) {
super((bytes == null || bytes.length < 8) ? PMm.EMPTY : bytes);
}
public final String getIcCode() {
return Util.toHexString(data, 0, 2);
}
public final String getMaximumResponseTime() {
return Util.toHexString(data, 2, 6);
}
}
public final static class SystemCode extends FeliCa {
public static final byte[] EMPTY = { 0, 0, };
public SystemCode(byte[] sc) {
super((sc == null || sc.length < 2) ? SystemCode.EMPTY : sc);
}
public int toInt() {
return toInt(data);
}
public static int toInt(byte[] data) {
return 0x0000FFFF & ((data[0] << 8) | (0x000000FF & data[1]));
}
}
public final static class ServiceCode extends FeliCa {
public static final byte[] EMPTY = { 0, 0, };
public static final int T_UNKNOWN = 0;
public static final int T_RANDOM = 1;
public static final int T_CYCLIC = 2;
public static final int T_PURSE = 3;
public ServiceCode(byte[] sc) {
super((sc == null || sc.length < 2) ? ServiceCode.EMPTY : sc);
}
public ServiceCode(int code) {
this(new byte[] { (byte) (code & 0xFF), (byte) (code >> 8) });
}
public boolean isEncrypt() {
return (data[0] & 0x1) == 0;
}
public boolean isWritable() {
final int f = data[0] & 0x3F;
return (f & 0x2) == 0 || f == 0x13 || f == 0x12;
}
public int getAccessAttr() {
return data[0] & 0x3F;
}
public int getDataType() {
final int f = data[0] & 0x3F;
if ((f & 0x10) == 0)
return T_PURSE;
return ((f & 0x04) == 0) ? T_RANDOM : T_CYCLIC;
}
}
public final static class Block extends FeliCa {
public Block() {
data = new byte[16];
}
public Block(byte[] bytes) {
super((bytes == null || bytes.length < 16) ? new byte[16] : bytes);
}
}
public final static class BlockListElement extends FeliCa {
private static final byte LENGTH_2_BYTE = (byte) 0x80;
private static final byte LENGTH_3_BYTE = (byte) 0x00;
// private static final byte ACCESSMODE_DECREMENT = (byte) 0x00;
// private static final byte ACCESSMODE_CACHEBACK = (byte) 0x01;
private final byte lengthAndaccessMode;
private final byte serviceCodeListOrder;
public BlockListElement(byte mode, byte order, byte... blockNumber) {
if (blockNumber.length > 1) {
lengthAndaccessMode = (byte) (mode | LENGTH_2_BYTE & 0xFF);
} else {
lengthAndaccessMode = (byte) (mode | LENGTH_3_BYTE & 0xFF);
}
serviceCodeListOrder = (byte) (order & 0x0F);
data = (blockNumber == null) ? FeliCa.EMPTY : blockNumber;
}
@Override
public byte[] getBytes() {
if ((this.lengthAndaccessMode & LENGTH_2_BYTE) == 1) {
ByteBuffer buff = ByteBuffer.allocate(2);
buff.put(
(byte) ((this.lengthAndaccessMode | this.serviceCodeListOrder) & 0xFF))
.put(data[0]);
return buff.array();
} else {
ByteBuffer buff = ByteBuffer.allocate(3);
buff.put(
(byte) ((this.lengthAndaccessMode | this.serviceCodeListOrder) & 0xFF))
.put(data[1]).put(data[0]);
return buff.array();
}
}
}
public final static class MemoryConfigurationBlock extends FeliCa {
public MemoryConfigurationBlock(byte[] bytes) {
super((bytes == null || bytes.length < 4) ? new byte[4] : bytes);
}
public boolean isNdefSupport() {
return (data == null) ? false : (data[3] & (byte) 0xff) == 1;
}
public void setNdefSupport(boolean ndefSupport) {
data[3] = (byte) (ndefSupport ? 1 : 0);
}
public boolean isWritable(int... addrs) {
if (data == null)
return false;
boolean result = true;
for (int a : addrs) {
byte b = (byte) ((a & 0xff) + 1);
if (a < 8) {
result &= (data[0] & b) == b;
continue;
} else if (a < 16) {
result &= (data[1] & b) == b;
continue;
} else
result &= (data[2] & b) == b;
}
return result;
}
}
public final static class Service extends FeliCa {
private final ServiceCode[] serviceCodes;
private final BlockListElement[] blockListElements;
public Service(ServiceCode[] codes, BlockListElement... blocks) {
serviceCodes = (codes == null) ? new ServiceCode[0] : codes;
blockListElements = (blocks == null) ? new BlockListElement[0]
: blocks;
}
@Override
public byte[] getBytes() {
int length = 0;
for (ServiceCode s : this.serviceCodes) {
length += s.getBytes().length;
}
for (BlockListElement b : blockListElements) {
length += b.getBytes().length;
}
ByteBuffer buff = ByteBuffer.allocate(length);
for (ServiceCode s : this.serviceCodes) {
buff.put(s.getBytes());
}
for (BlockListElement b : blockListElements) {
buff.put(b.getBytes());
}
return buff.array();
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (ServiceCode s : serviceCodes) {
sb.append(s.toString());
}
for (BlockListElement b : blockListElements) {
sb.append(b.toString());
}
return sb.toString();
}
}
public final static class Command extends FeliCa {
private final int length;
private final byte code;
private final IDm idm;
public Command(final byte[] bytes) {
this(bytes[0], Arrays.copyOfRange(bytes, 1, bytes.length));
}
public Command(byte code, final byte... bytes) {
this.code = code;
if (bytes.length >= 8) {
idm = new IDm(Arrays.copyOfRange(bytes, 0, 8));
data = Arrays.copyOfRange(bytes, 8, bytes.length);
} else {
idm = null;
data = bytes;
}
length = bytes.length + 2;
}
public Command(byte code, IDm idm, final byte... bytes) {
this.code = code;
this.idm = idm;
this.data = bytes;
this.length = idm.getBytes().length + data.length + 2;
}
public Command(byte code, byte[] idm, final byte... bytes) {
this.code = code;
this.idm = new IDm(idm);
this.data = bytes;
this.length = idm.length + data.length + 2;
}
@Override
public byte[] getBytes() {
ByteBuffer buff = ByteBuffer.allocate(length);
byte length = (byte) this.length;
if (idm != null) {
buff.put(length).put(code).put(idm.getBytes()).put(data);
} else {
buff.put(length).put(code).put(data);
}
return buff.array();
}
}
public static class Response extends FeliCa {
protected final int length;
protected final byte code;
protected final IDm idm;
public Response(byte[] bytes) {
if (bytes != null && bytes.length >= 10) {
length = bytes[0] & 0xff;
code = bytes[1];
idm = new IDm(Arrays.copyOfRange(bytes, 2, 10));
data = bytes;
} else {
length = 0;
code = 0;
idm = new IDm(null);
data = FeliCa.EMPTY;
}
}
public IDm getIDm() {
return idm;
}
}
public final static class PollingResponse extends Response {
private final PMm pmm;
public PollingResponse(byte[] bytes) {
super(bytes);
if (size() >= 18) {
pmm = new PMm(Arrays.copyOfRange(data, 10, 18));
} else {
pmm = new PMm(null);
}
}
public PMm getPMm() {
return pmm;
}
}
public final static class ReadResponse extends Response {
public static final byte[] EMPTY = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
(byte) 0xFF, (byte) 0xFF };
private final byte[] blockData;
public ReadResponse(byte[] rsp) {
super((rsp == null || rsp.length < 12) ? ReadResponse.EMPTY : rsp);
if (getStatusFlag1() == STA1_NORMAL && getBlockCount() > 0) {
blockData = Arrays.copyOfRange(data, 13, data.length);
} else {
blockData = FeliCa.EMPTY;
}
}
public int getStatusFlag1() {
return data[10];
}
public int getStatusFlag2() {
return data[11];
}
public int getBlockCount() {
return (data.length > 12) ? (0xFF & data[12]) : 0;
}
public byte[] getBlockData() {
return blockData;
}
public boolean isOkey() {
return getStatusFlag1() == STA1_NORMAL;
}
}
public final static class WriteResponse extends Response {
public WriteResponse(byte[] rsp) {
super((rsp == null || rsp.length < 12) ? ReadResponse.EMPTY : rsp);
}
public int getStatusFlag1() {
return data[0];
}
public int getStatusFlag2() {
return data[1];
}
public boolean isOkey() {
return getStatusFlag1() == STA1_NORMAL;
}
}
public final static class Tag {
private final NfcF nfcTag;
private boolean isFeliCaLite;
private int sys;
private IDm idm;
private PMm pmm;
public Tag(NfcF tag) {
nfcTag = tag;
sys = SystemCode.toInt(tag.getSystemCode());
idm = new IDm(tag.getTag().getId());
pmm = new PMm(tag.getManufacturer());
}
public int getSystemCode() {
return sys;
}
public IDm getIDm() {
return idm;
}
public PMm getPMm() {
return pmm;
}
public boolean checkFeliCaLite() {
isFeliCaLite = !polling(SYS_FELICA_LITE).getIDm().isEmpty();
return isFeliCaLite;
}
public boolean isFeliCaLite() {
return isFeliCaLite;
}
public PollingResponse polling(int systemCode) {
Command cmd = new Command(CMD_POLLING, new byte[] {
(byte) (systemCode >> 8), (byte) (systemCode & 0xff),
(byte) 0x01, (byte) 0x00 });
PollingResponse r = new PollingResponse(transceive(cmd));
idm = r.getIDm();
pmm = r.getPMm();
return r;
}
public PollingResponse polling() {
Command cmd = new Command(CMD_POLLING, new byte[] {
(byte) (SYS_FELICA_LITE >> 8),
(byte) (SYS_FELICA_LITE & 0xff), (byte) 0x01, (byte) 0x00 });
PollingResponse r = new PollingResponse(transceive(cmd));
idm = r.getIDm();
pmm = r.getPMm();
return r;
}
public final SystemCode[] getSystemCodeList() {
final Command cmd = new Command(CMD_REQUEST_SYSTEMCODE, idm);
final byte[] bytes = transceive(cmd);
final int num = (int) bytes[10];
final SystemCode ret[] = new SystemCode[num];
for (int i = 0; i < num; ++i) {
ret[i] = new SystemCode(Arrays.copyOfRange(bytes, 11 + i * 2,
13 + i * 2));
}
return ret;
}
public ServiceCode[] getServiceCodeList() {
ArrayList<ServiceCode> ret = new ArrayList<ServiceCode>();
int index = 1;
while (true) {
byte[] bytes = searchServiceCode(index);
if (bytes.length != 2 && bytes.length != 4)
break;
if (bytes.length == 2) {
if (bytes[0] == (byte) 0xff && bytes[1] == (byte) 0xff)
break;
ret.add(new ServiceCode(bytes));
}
++index;
}
return ret.toArray(new ServiceCode[ret.size()]);
}
private byte[] searchServiceCode(int index) {
Command cmd = new Command(CMD_SEARCH_SERVICECODE, idm, new byte[] {
(byte) (index & 0xff), (byte) (index >> 8) });
byte[] bytes = transceive(cmd);
if (bytes == null || bytes.length < 12 || bytes[1] != (byte) 0x0b) {
return FeliCa.EMPTY;
}
return Arrays.copyOfRange(bytes, 10, bytes.length);
}
public ReadResponse readWithoutEncryption(ServiceCode code, byte addr) {
byte[] bytes = code.getBytes();
Command cmd = new Command(CMD_READ_WO_ENCRYPTION, idm, new byte[] {
(byte) 0x01, (byte) bytes[0], (byte) bytes[1], (byte) 0x01,
(byte) 0x80, addr });
return new ReadResponse(transceive(cmd));
}
public ReadResponse readWithoutEncryption(byte addr) {
Command cmd = new Command(CMD_READ_WO_ENCRYPTION, idm, new byte[] {
(byte) 0x01, (byte) (SRV_FELICA_LITE_READONLY >> 8),
(byte) (SRV_FELICA_LITE_READONLY & 0xff), (byte) 0x01,
(byte) 0x80, addr });
return new ReadResponse(transceive(cmd));
}
public WriteResponse writeWithoutEncryption(ServiceCode code,
byte addr, byte[] buff) {
byte[] bytes = code.getBytes();
ByteBuffer b = ByteBuffer.allocate(22);
b.put(new byte[] { (byte) 0x01, (byte) bytes[0], (byte) bytes[1],
(byte) 0x01, (byte) 0x80, (byte) addr });
b.put(buff, 0, buff.length > 16 ? 16 : buff.length);
Command cmd = new Command(CMD_WRITE_WO_ENCRYPTION, idm, b.array());
return new WriteResponse(transceive(cmd));
}
public WriteResponse writeWithoutEncryption(byte addr, byte[] buff) {
ByteBuffer b = ByteBuffer.allocate(22);
b.put(new byte[] { (byte) 0x01,
(byte) (SRV_FELICA_LITE_READWRITE >> 8),
(byte) (SRV_FELICA_LITE_READWRITE & 0xff), (byte) 0x01,
(byte) 0x80, addr });
b.put(buff, 0, buff.length > 16 ? 16 : buff.length);
Command cmd = new Command(CMD_WRITE_WO_ENCRYPTION, idm, b.array());
return new WriteResponse(transceive(cmd));
}
public MemoryConfigurationBlock getMemoryConfigBlock() {
ReadResponse r = readWithoutEncryption((byte) 0x88);
return (r != null) ? new MemoryConfigurationBlock(r.getBlockData())
: null;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
if (idm != null) {
sb.append(idm.toString());
if (pmm != null)
sb.append(pmm.toString());
}
return sb.toString();
}
public void connect() {
try {
nfcTag.connect();
} catch (Exception e) {
}
}
public void close() {
try {
nfcTag.close();
} catch (Exception e) {
}
}
public byte[] transceive(Command cmd) {
try {
return nfcTag.transceive(cmd.getBytes());
} catch (Exception e) {
return Response.EMPTY;
}
}
}
// polling
public static final byte CMD_POLLING = 0x00;
public static final byte RSP_POLLING = 0x01;
// request service
public static final byte CMD_REQUEST_SERVICE = 0x02;
public static final byte RSP_REQUEST_SERVICE = 0x03;
// request RESPONSE
public static final byte CMD_REQUEST_RESPONSE = 0x04;
public static final byte RSP_REQUEST_RESPONSE = 0x05;
// read without encryption
public static final byte CMD_READ_WO_ENCRYPTION = 0x06;
public static final byte RSP_READ_WO_ENCRYPTION = 0x07;
// write without encryption
public static final byte CMD_WRITE_WO_ENCRYPTION = 0x08;
public static final byte RSP_WRITE_WO_ENCRYPTION = 0x09;
// search service code
public static final byte CMD_SEARCH_SERVICECODE = 0x0a;
public static final byte RSP_SEARCH_SERVICECODE = 0x0b;
// request system code
public static final byte CMD_REQUEST_SYSTEMCODE = 0x0c;
public static final byte RSP_REQUEST_SYSTEMCODE = 0x0d;
// authentication 1
public static final byte CMD_AUTHENTICATION1 = 0x10;
public static final byte RSP_AUTHENTICATION1 = 0x11;
// authentication 2
public static final byte CMD_AUTHENTICATION2 = 0x12;
public static final byte RSP_AUTHENTICATION2 = 0x13;
// read
public static final byte CMD_READ = 0x14;
public static final byte RSP_READ = 0x15;
// write
public static final byte CMD_WRITE = 0x16;
public static final byte RSP_WRITE = 0x17;
public static final int SYS_ANY = 0xffff;
public static final int SYS_FELICA_LITE = 0x88b4;
public static final int SYS_COMMON = 0xfe00;
public static final int SRV_FELICA_LITE_READONLY = 0x0b00;
public static final int SRV_FELICA_LITE_READWRITE = 0x0900;
public static final int STA1_NORMAL = 0x00;
public static final int STA1_ERROR = 0xff;
public static final int STA2_NORMAL = 0x00;
public static final int STA2_ERROR_LENGTH = 0x01;
public static final int STA2_ERROR_FLOWN = 0x02;
public static final int STA2_ERROR_MEMORY = 0x70;
public static final int STA2_ERROR_WRITELIMIT = 0x71;
}
| Java |
/* NFCard is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
NFCard is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Wget. If not, see <http://www.gnu.org/licenses/>.
Additional permission under GNU GPL version 3 section 7 */
package com.sinpo.xnfc.tech;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import android.nfc.tech.IsoDep;
import com.sinpo.xnfc.Util;
public class Iso7816 {
public static final byte[] EMPTY = { 0 };
protected byte[] data;
protected Iso7816() {
data = Iso7816.EMPTY;
}
protected Iso7816(byte[] bytes) {
data = (bytes == null) ? Iso7816.EMPTY : bytes;
}
public boolean match(byte[] bytes) {
return match(bytes, 0);
}
public boolean match(byte[] bytes, int start) {
final byte[] data = this.data;
if (data.length <= bytes.length - start) {
for (final byte v : data) {
if (v != bytes[start++])
return false;
}
}
return true;
}
public boolean match(byte tag) {
return (data.length == 1 && data[0] == tag);
}
public boolean match(short tag) {
final byte[] data = this.data;
if (data.length == 2) {
final byte d0 = (byte) (0x000000FF & tag);
final byte d1 = (byte) (0x000000FF & (tag >> 8));
return (data[0] == d0 && data[1] == d1);
}
return false;
}
public int size() {
return data.length;
}
public byte[] getBytes() {
return data;
}
@Override
public String toString() {
return Util.toHexString(data, 0, data.length);
}
public final static class ID extends Iso7816 {
public ID(byte[] bytes) {
super(bytes);
}
}
public final static class Response extends Iso7816 {
public static final byte[] EMPTY = {};
public static final byte[] ERROR = { 0x6F, 0x00 }; // SW_UNKNOWN
public Response(byte[] bytes) {
super((bytes == null || bytes.length < 2) ? Response.ERROR : bytes);
}
public byte getSw1() {
return data[data.length - 2];
}
public byte getSw2() {
return data[data.length - 1];
}
public short getSw12() {
final byte[] d = this.data;
int n = d.length;
return (short) ((d[n - 2] << 8) | (0xFF & d[n - 1]));
}
public boolean isOkey() {
return equalsSw12(SW_NO_ERROR);
}
public boolean equalsSw12(short val) {
return getSw12() == val;
}
public int size() {
return data.length - 2;
}
public byte[] getBytes() {
return isOkey() ? Arrays.copyOfRange(data, 0, size())
: Response.EMPTY;
}
}
public final static class BerT extends Iso7816 {
// tag template
public static final byte TMPL_FCP = 0x62; // File Control Parameters
public static final byte TMPL_FMD = 0x64; // File Management Data
public static final byte TMPL_FCI = 0x6F; // FCP and FMD
// proprietary information
public final static BerT CLASS_PRI = new BerT((byte) 0xA5);
// short EF identifier
public final static BerT CLASS_SFI = new BerT((byte) 0x88);
// dedicated file name
public final static BerT CLASS_DFN = new BerT((byte) 0x84);
// application data object
public final static BerT CLASS_ADO = new BerT((byte) 0x61);
// application id
public final static BerT CLASS_AID = new BerT((byte) 0x4F);
public static int test(byte[] bytes, int start) {
int len = 1;
if ((bytes[start] & 0x1F) == 0x1F) {
while ((bytes[start + len] & 0x80) == 0x80)
++len;
++len;
}
return len;
}
public static BerT read(byte[] bytes, int start) {
return new BerT(Arrays.copyOfRange(bytes, start,
start + test(bytes, start)));
}
public BerT(byte tag) {
this(new byte[] { tag });
}
public BerT(short tag) {
this(new byte[] { (byte) (0x000000FF & (tag >> 8)),
(byte) (0x000000FF & tag) });
}
public BerT(byte[] bytes) {
super(bytes);
}
public boolean hasChild() {
return ((data[0] & 0x20) == 0x20);
}
}
public final static class BerL extends Iso7816 {
private final int val;
public static int test(byte[] bytes, int start) {
int len = 1;
if ((bytes[start] & 0x80) == 0x80) {
len += bytes[start] & 0x07;
}
return len;
}
public static int calc(byte[] bytes, int start) {
if ((bytes[start] & 0x80) == 0x80) {
int v = 0;
int e = start + bytes[start] & 0x07;
while (++start <= e) {
v <<= 8;
v |= bytes[start] & 0xFF;
}
return v;
}
return bytes[start];
}
public static BerL read(byte[] bytes, int start) {
return new BerL(Arrays.copyOfRange(bytes, start,
start + test(bytes, start)));
}
public BerL(byte[] bytes) {
super(bytes);
val = calc(bytes, 0);
}
public int toInt() {
return val;
}
}
public final static class BerV extends Iso7816 {
public static BerV read(byte[] bytes, int start, int len) {
return new BerV(Arrays.copyOfRange(bytes, start, start + len));
}
public BerV(byte[] bytes) {
super(bytes);
}
}
public final static class BerTLV extends Iso7816 {
public static int test(byte[] bytes, int start) {
final int lt = BerT.test(bytes, start);
final int ll = BerL.test(bytes, start + lt);
final int lv = BerL.calc(bytes, start + lt);
return lt + ll + lv;
}
public static BerTLV read(Iso7816 obj) {
return read(obj.getBytes(), 0);
}
public static BerTLV read(byte[] bytes, int start) {
int s = start;
final BerT t = BerT.read(bytes, s);
s += t.size();
final BerL l = BerL.read(bytes, s);
s += l.size();
final BerV v = BerV.read(bytes, s, l.toInt());
s += v.size();
final BerTLV tlv = new BerTLV(t, l, v);
tlv.data = Arrays.copyOfRange(bytes, start, s);
return tlv;
}
public static ArrayList<BerTLV> readList(Iso7816 obj) {
return readList(obj.getBytes());
}
public static ArrayList<BerTLV> readList(final byte[] data) {
final ArrayList<BerTLV> ret = new ArrayList<BerTLV>();
int start = 0;
int end = data.length - 3;
while (start < end) {
final BerTLV tlv = read(data, start);
ret.add(tlv);
start += tlv.size();
}
return ret;
}
public final BerT t;
public final BerL l;
public final BerV v;
public BerTLV(BerT t, BerL l, BerV v) {
this.t = t;
this.l = l;
this.v = v;
}
public BerTLV getChildByTag(BerT tag) {
if (t.hasChild()) {
final byte[] raw = v.getBytes();
int start = 0;
int end = raw.length;
while (start < end) {
if (tag.match(raw, start))
return read(raw, start);
start += test(raw, start);
}
}
return null;
}
public BerTLV getChild(int index) {
if (t.hasChild()) {
final byte[] raw = v.getBytes();
int start = 0;
int end = raw.length;
int i = 0;
while (start < end) {
if (i++ == index)
return read(raw, start);
start += test(raw, start);
}
}
return null;
}
}
public final static class Tag {
private final IsoDep nfcTag;
private ID id;
public Tag(IsoDep tag) {
nfcTag = tag;
id = new ID(tag.getTag().getId());
}
public ID getID() {
return id;
}
public Response verify() {
final byte[] cmd = { (byte) 0x00, // CLA Class
(byte) 0x20, // INS Instruction
(byte) 0x00, // P1 Parameter 1
(byte) 0x00, // P2 Parameter 2
(byte) 0x02, // Lc
(byte) 0x12, (byte) 0x34, };
return new Response(transceive(cmd));
}
public Response initPurchase(boolean isEP) {
final byte[] cmd = {
(byte) 0x80, // CLA Class
(byte) 0x50, // INS Instruction
(byte) 0x01, // P1 Parameter 1
(byte) (isEP ? 2 : 1), // P2 Parameter 2
(byte) 0x0B, // Lc
(byte) 0x01, (byte) 0x00, (byte) 0x00, (byte) 0x00,
(byte) 0x00, (byte) 0x11, (byte) 0x22, (byte) 0x33,
(byte) 0x44, (byte) 0x55, (byte) 0x66, (byte) 0x0F, // Le
};
return new Response(transceive(cmd));
}
public Response getBalance(boolean isEP) {
final byte[] cmd = { (byte) 0x80, // CLA Class
(byte) 0x5C, // INS Instruction
(byte) 0x00, // P1 Parameter 1
(byte) (isEP ? 2 : 1), // P2 Parameter 2
(byte) 0x04, // Le
};
return new Response(transceive(cmd));
}
public Response readRecord(int sfi, int index) {
final byte[] cmd = { (byte) 0x00, // CLA Class
(byte) 0xB2, // INS Instruction
(byte) index, // P1 Parameter 1
(byte) ((sfi << 3) | 0x04), // P2 Parameter 2
(byte) 0x00, // Le
};
return new Response(transceive(cmd));
}
public Response readRecord(int sfi) {
final byte[] cmd = { (byte) 0x00, // CLA Class
(byte) 0xB2, // INS Instruction
(byte) 0x01, // P1 Parameter 1
(byte) ((sfi << 3) | 0x05), // P2 Parameter 2
(byte) 0x00, // Le
};
return new Response(transceive(cmd));
}
public Response readBinary(int sfi) {
final byte[] cmd = { (byte) 0x00, // CLA Class
(byte) 0xB0, // INS Instruction
(byte) (0x00000080 | (sfi & 0x1F)), // P1 Parameter 1
(byte) 0x00, // P2 Parameter 2
(byte) 0x00, // Le
};
return new Response(transceive(cmd));
}
public Response readData(int sfi) {
final byte[] cmd = { (byte) 0x80, // CLA Class
(byte) 0xCA, // INS Instruction
(byte) 0x00, // P1 Parameter 1
(byte) (sfi & 0x1F), // P2 Parameter 2
(byte) 0x00, // Le
};
return new Response(transceive(cmd));
}
public Response selectByID(byte... name) {
ByteBuffer buff = ByteBuffer.allocate(name.length + 6);
buff.put((byte) 0x00) // CLA Class
.put((byte) 0xA4) // INS Instruction
.put((byte) 0x00) // P1 Parameter 1
.put((byte) 0x00) // P2 Parameter 2
.put((byte) name.length) // Lc
.put(name).put((byte) 0x00); // Le
return new Response(transceive(buff.array()));
}
public Response selectByName(byte... name) {
ByteBuffer buff = ByteBuffer.allocate(name.length + 6);
buff.put((byte) 0x00) // CLA Class
.put((byte) 0xA4) // INS Instruction
.put((byte) 0x04) // P1 Parameter 1
.put((byte) 0x00) // P2 Parameter 2
.put((byte) name.length) // Lc
.put(name).put((byte) 0x00); // Le
return new Response(transceive(buff.array()));
}
public void connect() {
try {
nfcTag.connect();
} catch (Exception e) {
}
}
public void close() {
try {
nfcTag.close();
} catch (Exception e) {
}
}
public byte[] transceive(final byte[] cmd) {
try {
return nfcTag.transceive(cmd);
} catch (Exception e) {
return Response.ERROR;
}
}
}
public static final short SW_NO_ERROR = (short) 0x9000;
public static final short SW_BYTES_REMAINING_00 = 0x6100;
public static final short SW_WRONG_LENGTH = 0x6700;
public static final short SW_SECURITY_STATUS_NOT_SATISFIED = 0x6982;
public static final short SW_FILE_INVALID = 0x6983;
public static final short SW_DATA_INVALID = 0x6984;
public static final short SW_CONDITIONS_NOT_SATISFIED = 0x6985;
public static final short SW_COMMAND_NOT_ALLOWED = 0x6986;
public static final short SW_APPLET_SELECT_FAILED = 0x6999;
public static final short SW_WRONG_DATA = 0x6A80;
public static final short SW_FUNC_NOT_SUPPORTED = 0x6A81;
public static final short SW_FILE_NOT_FOUND = 0x6A82;
public static final short SW_RECORD_NOT_FOUND = 0x6A83;
public static final short SW_INCORRECT_P1P2 = 0x6A86;
public static final short SW_WRONG_P1P2 = 0x6B00;
public static final short SW_CORRECT_LENGTH_00 = 0x6C00;
public static final short SW_INS_NOT_SUPPORTED = 0x6D00;
public static final short SW_CLA_NOT_SUPPORTED = 0x6E00;
public static final short SW_UNKNOWN = 0x6F00;
public static final short SW_FILE_FULL = 0x6A84;
}
| Java |
/* NFCard is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
NFCard is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Wget. If not, see <http://www.gnu.org/licenses/>.
Additional permission under GNU GPL version 3 section 7 */
package com.sinpo.xnfc;
import java.util.Arrays;
import org.xml.sax.XMLReader;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.nfc.NfcAdapter;
import android.os.Bundle;
import android.os.Parcelable;
import android.text.ClipboardManager;
import android.text.Editable;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.Toast;
import com.sinpo.xnfc.card.CardManager;
public final class NFCard extends Activity implements OnClickListener,
Html.ImageGetter, Html.TagHandler {
private NfcAdapter nfcAdapter;
private PendingIntent pendingIntent;
private Resources res;
private TextView board;
private enum ContentType {
HINT, DATA, MSG
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.nfcard);
final Resources res = getResources();
this.res = res;
final View decor = getWindow().getDecorView();
final TextView board = (TextView) decor.findViewById(R.id.board);
this.board = board;
decor.findViewById(R.id.btnCopy).setOnClickListener(this);
decor.findViewById(R.id.btnNfc).setOnClickListener(this);
decor.findViewById(R.id.btnExit).setOnClickListener(this);
board.setMovementMethod(LinkMovementMethod.getInstance());
board.setFocusable(false);
board.setClickable(false);
board.setLongClickable(false);
nfcAdapter = NfcAdapter.getDefaultAdapter(this);
pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,
getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
onNewIntent(getIntent());
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.clear:
showData(null);
return true;
case R.id.help:
showHelp(R.string.info_help);
return true;
case R.id.about:
showHelp(R.string.info_about);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
protected void onPause() {
super.onPause();
if (nfcAdapter != null)
nfcAdapter.disableForegroundDispatch(this);
}
@Override
protected void onResume() {
super.onResume();
if (nfcAdapter != null)
nfcAdapter.enableForegroundDispatch(this, pendingIntent,
CardManager.FILTERS, CardManager.TECHLISTS);
refreshStatus();
}
@Override
protected void onNewIntent(Intent intent) {
final Parcelable p = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
showData((p != null) ? CardManager.load(p, res) : null);
}
@Override
public void onClick(final View v) {
switch (v.getId()) {
case R.id.btnCopy: {
copyData();
break;
}
case R.id.btnNfc: {
startActivityForResult(new Intent(
android.provider.Settings.ACTION_WIRELESS_SETTINGS), 0);
break;
}
case R.id.btnExit: {
finish();
break;
}
default:
break;
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
refreshStatus();
}
private void refreshStatus() {
final Resources r = this.res;
final String tip;
if (nfcAdapter == null)
tip = r.getString(R.string.tip_nfc_notfound);
else if (nfcAdapter.isEnabled())
tip = r.getString(R.string.tip_nfc_enabled);
else
tip = r.getString(R.string.tip_nfc_disabled);
final StringBuilder s = new StringBuilder(
r.getString(R.string.app_name));
s.append(" -- ").append(tip);
setTitle(s);
final CharSequence text = board.getText();
if (text == null || board.getTag() == ContentType.HINT)
showHint();
}
private void copyData() {
final CharSequence text = board.getText();
if (text == null || board.getTag() != ContentType.DATA)
return;
((ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE))
.setText(text);
final String msg = res.getString(R.string.msg_copied);
final Toast toast = Toast.makeText(this, msg, Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
private void showData(String data) {
if (data == null || data.length() == 0) {
showHint();
return;
}
final TextView board = this.board;
final Resources res = this.res;
final int padding = res.getDimensionPixelSize(R.dimen.pnl_margin);
board.setPadding(padding, padding, padding, padding);
board.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
board.setTextSize(res.getDimension(R.dimen.text_small));
board.setTextColor(res.getColor(R.color.text_default));
board.setGravity(Gravity.NO_GRAVITY);
board.setTag(ContentType.DATA);
board.setText(Html.fromHtml(data, this, null));
}
private void showHelp(int id) {
final TextView board = this.board;
final Resources res = this.res;
final int padding = res.getDimensionPixelSize(R.dimen.pnl_margin);
board.setPadding(padding, padding, padding, padding);
board.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
board.setTextSize(res.getDimension(R.dimen.text_small));
board.setTextColor(res.getColor(R.color.text_default));
board.setGravity(Gravity.NO_GRAVITY);
board.setTag(ContentType.MSG);
board.setText(Html.fromHtml(res.getString(id), this, this));
}
private void showHint() {
final TextView board = this.board;
final Resources res = this.res;
final String hint;
if (nfcAdapter == null)
hint = res.getString(R.string.msg_nonfc);
else if (nfcAdapter.isEnabled())
hint = res.getString(R.string.msg_nocard);
else
hint = res.getString(R.string.msg_nfcdisabled);
final int padding = res.getDimensionPixelSize(R.dimen.text_middle);
board.setPadding(padding, padding, padding, padding);
board.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD_ITALIC));
board.setTextSize(res.getDimension(R.dimen.text_middle));
board.setTextColor(res.getColor(R.color.text_tip));
board.setGravity(Gravity.CENTER_VERTICAL);
board.setTag(ContentType.HINT);
board.setText(Html.fromHtml(hint));
}
@Override
public void handleTag(boolean opening, String tag, Editable output,
XMLReader xmlReader) {
if (!opening && "version".equals(tag)) {
try {
output.append(getPackageManager().getPackageInfo(
getPackageName(), 0).versionName);
} catch (NameNotFoundException e) {
}
}
}
private Drawable spliter;
@Override
public Drawable getDrawable(String source) {
final Resources res = this.res;
final Drawable ret;
if (source.startsWith("spliter")) {
if (spliter == null) {
final int w = res.getDisplayMetrics().widthPixels;
final int h = (int) (res.getDisplayMetrics().densityDpi / 72f + 0.5f);
final int[] pix = new int[w * h];
Arrays.fill(pix, res.getColor(R.color.bg_default));
spliter = new BitmapDrawable(Bitmap.createBitmap(pix, w, h,
Bitmap.Config.ARGB_8888));
spliter.setBounds(0, 3 * h, w, 4 * h);
}
ret = spliter;
} else if (source.startsWith("icon_main")) {
ret = res.getDrawable(R.drawable.ic_app_main);
final String[] params = source.split(",");
final float f = res.getDisplayMetrics().densityDpi / 72f;
final float w = Util.parseInt(params[1], 10, 16) * f + 0.5f;
final float h = Util.parseInt(params[2], 10, 16) * f + 0.5f;
ret.setBounds(0, 0, (int) w, (int) h);
} else {
ret = null;
}
return ret;
}
}
| Java |
package org.sshtunnel;
import java.util.List;
import org.sshtunnel.db.Profile;
import org.sshtunnel.db.ProfileFactory;
import org.sshtunnel.utils.Constraints;
import org.sshtunnel.utils.Utils;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.telephony.TelephonyManager;
import android.util.Log;
import com.ksmaze.android.preference.ListPreferenceMultiSelect;
public class ConnectivityBroadcastReceiver extends BroadcastReceiver {
private static final String TAG = "ConnectivityBroadcastReceiver";
public String onlineSSID(Context context, String ssid) {
String ssids[] = ListPreferenceMultiSelect.parseStoredValue(ssid);
if (ssids == null)
return null;
if (ssids.length < 1)
return null;
ConnectivityManager manager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
if (networkInfo == null)
return null;
if (!networkInfo.getTypeName().equals("WIFI")) {
for (String item : ssids) {
if (item.equals(Constraints.WIFI_AND_3G))
return item;
if (item.equals(Constraints.ONLY_3G))
return item;
}
return null;
}
WifiManager wm = (WifiManager) context
.getSystemService(Context.WIFI_SERVICE);
WifiInfo wInfo = wm.getConnectionInfo();
if (wInfo == null)
return null;
String current = wInfo.getSSID();
if (current == null || current.equals(""))
return null;
for (String item : ssids) {
if (item.equals(Constraints.WIFI_AND_3G))
return item;
if (item.equals(Constraints.ONLY_WIFI))
return item;
if (item.equals(current))
return item;
}
return null;
}
@Override
public synchronized void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (!action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Log.w(TAG, "onReceived() called uncorrectly");
return;
}
Log.d(TAG, "Connection Test");
SharedPreferences settings = PreferenceManager
.getDefaultSharedPreferences(context);
if (SSHTunnelService.isConnecting)
return;
// only switching profiles when needed
ConnectivityManager manager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
if (networkInfo == null) {
if (Utils.isWorked()) {
context.stopService(new Intent(context, SSHTunnelService.class));
}
}
// Save current settings first
ProfileFactory.getProfile();
ProfileFactory.loadFromPreference();
String curSSID = null;
List<Profile> profileList = ProfileFactory.loadAllProfilesFromDao();
int profileId = -1;
if (profileList == null)
return;
// Test on each profile
for (Profile profile : profileList) {
curSSID = onlineSSID(context, profile.getSsid());
if (profile.isAutoConnect() && curSSID != null) {
// Then switch profile values
profileId = profile.getId();
break;
}
}
if (curSSID != null && profileId != -1) {
if (!Utils.isWorked()) {
Editor ed = settings.edit();
ed.putString("lastSSID", curSSID);
ed.commit();
while (SSHTunnelService.isStopping) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
break;
}
}
Utils.notifyConnect();
Intent it = new Intent(context, SSHTunnelService.class);
Bundle bundle = new Bundle();
bundle.putInt(Constraints.ID, profileId);
it.putExtras(bundle);
context.startService(it);
}
}
}
} | Java |
/* sshtunnel - SSH Tunnel App for Android
* Copyright (C) 2011 Max Lv <max.c.lv@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* ___====-_ _-====___
* _--^^^#####// \\#####^^^--_
* _-^##########// ( ) \\##########^-_
* -############// |\^^/| \\############-
* _/############// (@::@) \\############\_
* /#############(( \\// ))#############\
* -###############\\ (oo) //###############-
* -#################\\ / VV \ //#################-
* -###################\\/ \//###################-
* _#/|##########/\######( /\ )######/\##########|\#_
* |/ |#/\#/\#/\/ \#/\##\ | | /##/\#/ \/\#/\#/\#| \|
* ` |/ V V ` V \#\| | | |/#/ V ' V V \| '
* ` ` ` ` / | | | | \ ' ' ' '
* ( | | | | )
* __\ | | | | /__
* (vvv(VVV)(VVV)vvv)
*
* HERE BE DRAGONS
*
*/
package org.sshtunnel;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.ref.WeakReference;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.URL;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.sshtunnel.db.Profile;
import org.sshtunnel.db.ProfileFactory;
import org.sshtunnel.utils.Constraints;
import org.sshtunnel.utils.ProxyedApp;
import org.sshtunnel.utils.Utils;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.media.AudioManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RemoteViews;
import android.widget.TextView;
import com.flurry.android.FlurryAgent;
import com.trilead.ssh2.Connection;
import com.trilead.ssh2.ConnectionMonitor;
import com.trilead.ssh2.DynamicPortForwarder;
import com.trilead.ssh2.HTTPProxyData;
import com.trilead.ssh2.InteractiveCallback;
import com.trilead.ssh2.KnownHosts;
import com.trilead.ssh2.LocalPortForwarder;
import com.trilead.ssh2.ServerHostKeyVerifier;
public class SSHTunnelService extends Service implements ServerHostKeyVerifier,
InteractiveCallback, ConnectionMonitor {
// ConnectivityBroadcastReceiver stateChanged = null;
private Notification notification;
private NotificationManager notificationManager;
private Intent intent;
private PendingIntent pendIntent;
private static final String TAG = "SSHTunnel";
private static final int MSG_CONNECT_START = 0;
private static final int MSG_CONNECT_FINISH = 1;
private static final int MSG_CONNECT_SUCCESS = 2;
private static final int MSG_CONNECT_FAIL = 3;
private static final int MSG_DISCONNECT_FINISH = 4;
private static final String AUTH_PUBLICKEY = "publickey",
AUTH_PASSWORD = "password",
AUTH_KEYBOARDINTERACTIVE = "keyboard-interactive";
// Global settings
private SharedPreferences settings = null;
// Current profile
private Profile profile;
// Host IP address
private String hostAddress = null;
// Upstream proxy
private HTTPProxyData proxyData = null;
// DNS proxy option
private boolean enableDNSProxy = true;
// DNS proxy
private DNSServer dnsServer = null;
private int dnsPort = 0;
// Fingerprint Checker
private boolean fingerPrintChecker = false;
private Object fingerPrintLock = new Object();
// Port forwarding
private LocalPortForwarder lpf = null;
private LocalPortForwarder dnspf = null;
private DynamicPortForwarder dpf = null;
// Connecting / Stopping lock
public volatile static boolean isConnecting = false;
public volatile static boolean isStopping = false;
private final static int AUTH_TRIES = 1;
private final static int RECONNECT_TRIES = 2;
private Connection connection;
private volatile boolean connected = false;
private ProxyedApp apps[] = null;
public final static String BASE = "/data/data/org.sshtunnel/";
final static String CMD_IPTABLES_REDIRECT_ADD = BASE
+ "iptables -t nat -A SSHTUNNEL -p tcp --dport 80 -j REDIRECT --to 8123\n"
+ BASE
+ "iptables -t nat -A SSHTUNNEL -p tcp --dport 443 -j REDIRECT --to 8124\n";
final static String CMD_IPTABLES_DNAT_ADD = BASE
+ "iptables -t nat -A SSHTUNNEL -p tcp --dport 80 -j DNAT --to-destination 127.0.0.1:8123\n"
+ BASE
+ "iptables -t nat -A SSHTUNNEL -p tcp --dport 443 -j DNAT --to-destination 127.0.0.1:8124\n";
final static String CMD_IPTABLES_REDIRECT_ADD_SOCKS = BASE
+ "iptables -t nat -A SSHTUNNEL -p tcp -j REDIRECT --to 8123\n";
final static String CMD_IPTABLES_DNAT_ADD_SOCKS = BASE
+ "iptables -t nat -A SSHTUNNEL -p tcp -j DNAT --to-destination 127.0.0.1:8123\n";
final static String CMD_IPTABLES_RETURN = BASE
+ "iptables -t nat -A OUTPUT -p tcp -d 0.0.0.0 -j RETURN\n";
public static boolean runRootCommand(String command) {
Process process = null;
DataOutputStream os = null;
Log.d(TAG, command);
try {
process = Runtime.getRuntime().exec("su");
os = new DataOutputStream(process.getOutputStream());
os.writeBytes(command + "\n");
os.writeBytes("exit\n");
os.flush();
process.waitFor();
} catch (Exception e) {
Log.e(TAG, e.getMessage());
return false;
} finally {
try {
if (os != null) {
os.close();
}
process.destroy();
} catch (Exception e) {
// nothing
}
}
return true;
}
/*
* This is a hack see
* http://www.mail-archive.com/android-developers@googlegroups
* .com/msg18298.html we are not really able to decide if the service was
* started. So we remember a week reference to it. We set it if we are
* running and clear it if we are stopped. If anything goes wrong, the
* reference will hopefully vanish
*/
private static WeakReference<SSHTunnelService> sRunningInstance = null;
public final static boolean isServiceStarted() {
final boolean isServiceStarted;
if (sRunningInstance == null) {
isServiceStarted = false;
} else if (sRunningInstance.get() == null) {
isServiceStarted = false;
sRunningInstance = null;
} else {
isServiceStarted = true;
}
return isServiceStarted;
}
private void markServiceStarted() {
sRunningInstance = new WeakReference<SSHTunnelService>(this);
}
private void markServiceStopped() {
sRunningInstance = null;
}
// Flag indicating if this is an ARMv6 device (-1: unknown, 0: no, 1: yes)
private boolean hasRedirectSupport = true;
private String reason = null;
private static final Class<?>[] mStartForegroundSignature = new Class[] {
int.class, Notification.class };
private static final Class<?>[] mStopForegroundSignature = new Class[] { boolean.class };
private Method mStartForeground;
private Method mStopForeground;
private Object[] mStartForegroundArgs = new Object[2];
private Object[] mStopForegroundArgs = new Object[1];
final Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
Editor ed = settings.edit();
switch (msg.what) {
case MSG_CONNECT_START:
ed.putBoolean("isConnecting", true);
break;
case MSG_CONNECT_FINISH:
ed.putBoolean("isConnecting", false);
ed.putBoolean("isSwitching", false);
break;
case MSG_CONNECT_SUCCESS:
ed.putBoolean("isRunning", true);
// stateChanged = new ConnectivityBroadcastReceiver();
// registerReceiver(stateChanged, new IntentFilter(
// ConnectivityManager.CONNECTIVITY_ACTION));
break;
case MSG_CONNECT_FAIL:
ed.putBoolean("isRunning", false);
break;
case MSG_DISCONNECT_FINISH:
ed.putBoolean("isRunning", false);
ed.putBoolean("isSwitching", false);
try {
notificationManager.cancel(0);
notificationManager.cancel(1);
} catch (Exception ignore) {
// Nothing
}
// for widget, maybe exception here
try {
RemoteViews views = new RemoteViews(getPackageName(),
R.layout.sshtunnel_appwidget);
views.setImageViewResource(R.id.serviceToggle,
R.drawable.off);
AppWidgetManager awm = AppWidgetManager
.getInstance(SSHTunnelService.this);
awm.updateAppWidget(awm.getAppWidgetIds(new ComponentName(
SSHTunnelService.this,
SSHTunnelWidgetProvider.class)), views);
} catch (Exception ignore) {
// Nothing
}
break;
}
ed.commit();
super.handleMessage(msg);
}
};
final BroadcastReceiver hostKeyReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Constraints.FINGER_PRINT_ACTION)) {
if (intent.getBooleanExtra(
Constraints.FINGER_PRINT_ACTION_ACCEPT, false)) {
fingerPrintChecker = true;
synchronized (fingerPrintLock) {
fingerPrintLock.notifyAll();
}
} else {
fingerPrintChecker = false;
synchronized (fingerPrintLock) {
fingerPrintLock.notifyAll();
}
}
}
unregisterReceiver(hostKeyReceiver);
}
};
final Handler hostKeyHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
Bundle bundle = msg.getData();
Intent i = new Intent(SSHTunnelService.this,
FingerPrintDialog.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtras(bundle);
startActivity(i);
IntentFilter filter = new IntentFilter(
Constraints.FINGER_PRINT_ACTION);
registerReceiver(hostKeyReceiver, filter);
}
};
private void authenticate() {
try {
if (connection.authenticateWithNone(profile.getUser())) {
Log.d(TAG, "Authenticate with none");
return;
}
} catch (Exception e) {
Log.d(TAG, "Host does not support 'none' authentication.");
}
try {
if (connection.isAuthMethodAvailable(profile.getUser(),
AUTH_PUBLICKEY)) {
File f = new File(profile.getKeyPath());
if (f.exists())
if (profile.getPassword().equals(""))
profile.setPassword(null);
if (connection.authenticateWithPublicKey(profile.getUser(), f,
profile.getPassword())) {
Log.d(TAG, "Authenticate with public key");
return;
}
}
} catch (Exception e) {
Log.d(TAG, "Host does not support 'Public key' authentication.");
}
try {
if (connection.isAuthMethodAvailable(profile.getUser(),
AUTH_PASSWORD)) {
if (connection.authenticateWithPassword(profile.getUser(),
profile.getPassword())) {
Log.d(TAG, "Authenticate with password");
return;
}
}
} catch (IllegalStateException e) {
Log.e(TAG,
"Connection went away while we were trying to authenticate",
e);
} catch (Exception e) {
Log.e(TAG, "Problem during handleAuthentication()", e);
}
// TODO: Need verification
try {
if (connection.isAuthMethodAvailable(profile.getUser(),
AUTH_KEYBOARDINTERACTIVE)) {
if (connection.authenticateWithKeyboardInteractive(
profile.getUser(), this))
return;
}
} catch (Exception e) {
Log.d(TAG,
"Host does not support 'Keyboard-Interactive' authentication.");
}
}
public boolean connect() {
// try {
//
// connection.setCompression(true);
// connection.setTCPNoDelay(true);
//
// } catch (IOException e) {
// Log.e(TAG, "Could not enable compression!", e);
// }
// initialize the upstream proxy
if (profile.isUpstreamProxy()) {
try {
if (profile.getUpstreamProxy() == null
|| profile.getUpstreamProxy().equals(""))
throw new Exception();
String[] proxyInfo = profile.getUpstreamProxy().split("@");
if (proxyInfo.length == 1) {
String[] hostInfo = proxyInfo[0].split(":");
if (hostInfo.length != 2)
throw new Exception();
proxyData = new HTTPProxyData(hostInfo[0],
Integer.valueOf(hostInfo[1]));
} else if (proxyInfo.length == 2) {
String[] userInfo = proxyInfo[0].split(":");
if (userInfo.length != 2)
throw new Exception();
String[] hostInfo = proxyInfo[1].split(":");
if (hostInfo.length != 2)
throw new Exception();
proxyData = new HTTPProxyData(hostInfo[0],
Integer.valueOf(hostInfo[1]), userInfo[0],
userInfo[1]);
} else {
throw new Exception();
}
} catch (Exception e) {
if (reason == null)
reason = getString(R.string.upstream_format_error);
return false;
}
}
// get the host ip address
if (proxyData != null) {
try {
hostAddress = InetAddress.getByName(proxyData.proxyHost)
.getHostAddress();
} catch (UnknownHostException e) {
hostAddress = null;
}
} else {
try {
hostAddress = InetAddress.getByName(profile.getHost())
.getHostAddress();
} catch (UnknownHostException e) {
hostAddress = null;
}
}
// fail to connect if the dns lookup failed
if (hostAddress == null) {
if (reason == null)
reason = getString(R.string.fail_to_connect);
return false;
}
// begin to connect
try {
connection = new Connection(profile.getHost(), profile.getPort());
if (proxyData != null)
connection.setProxyData(proxyData);
connection.addConnectionMonitor(this);
/*
* Uncomment when debugging SSH protocol:
*/
/*
* DebugLogger logger = new DebugLogger() {
*
* public void log(int level, String className, String message) {
* Log.d("SSH", message); }
*
* };
*
* Logger.enabled = true; Logger.logger = logger;
*/
connection.connect(this, 10 * 1000, 20 * 1000);
connected = true;
} catch (Exception e) {
Log.e(TAG, "Problem in SSH connection thread during connecting", e);
// Display the reason in the text.
if (reason == null)
reason = getString(R.string.fail_to_connect);
return false;
}
try {
// enter a loop to keep trying until authentication
int tries = 0;
while (connected && !connection.isAuthenticationComplete()
&& tries++ < AUTH_TRIES) {
authenticate();
// sleep to make sure we dont kill system
Thread.sleep(1000);
}
} catch (Exception e) {
Log.e(TAG,
"Problem in SSH connection thread during authentication", e);
if (reason == null)
reason = getString(R.string.fail_to_authenticate);
return false;
}
try {
if (connection.isAuthenticationComplete()) {
return enablePortForward();
}
} catch (Exception e) {
Log.e(TAG, "Problem in SSH connection thread during enabling port",
e);
if (reason == null)
reason = getString(R.string.fail_to_connect);
return false;
}
if (reason == null)
reason = getString(R.string.fail_to_authenticate);
Log.e(TAG, "Cannot authenticate");
return false;
}
@Override
public void connectionLost(Throwable reason) {
Log.d(TAG, "Connection Lost");
SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");
if (isConnecting || isStopping) {
return;
}
if (!isOnline()) {
stopReconnect(df);
return;
}
if (reason != null) {
if (reason.getMessage().contains(
"There was a problem during connect")) {
Log.e(TAG, "connection lost", reason);
return;
} else if (reason.getMessage().contains(
"Closed due to user request")) {
Log.e(TAG, "connection lost", reason);
return;
} else if (reason.getMessage().contains(
"The connect timeout expired")) {
stopReconnect(df);
return;
}
Log.e(TAG, "connection lost: " + reason.getMessage());
} else {
stopReconnect(df);
return;
}
if (profile.isAutoReconnect() && connected) {
for (int reconNum = 1; reconNum <= RECONNECT_TRIES; reconNum++) {
Log.d(TAG, "Reconnect tries: " + reconNum);
onDisconnect();
if (!connect()) {
try {
Thread.sleep(2000 * reconNum);
} catch (Exception ignore) {
// Nothing
}
continue;
}
notifyAlert(
getString(R.string.reconnect_success) + " "
+ df.format(new Date()),
getString(R.string.reconnect_success));
return;
}
}
stopReconnect(df);
}
public boolean enablePortForward() {
/*
* DynamicPortForwarder dpf = null;
*
* try { dpf = connection.createDynamicPortForwarder(new
* InetSocketAddress( InetAddress.getLocalHost(), 1984)); } catch
* (Exception e) { Log.e(TAG, "Could not create dynamic port forward",
* e); return false; }
*/
// LocalPortForwarder lpf1 = null;
try {
dnspf = connection.createLocalPortForwarder(8053, "www.google.com",
80);
if (profile.isSocks()) {
dpf = connection.createDynamicPortForwarder(profile
.getLocalPort());
} else {
lpf = connection.createLocalPortForwarder(
profile.getLocalPort(), profile.getRemoteAddress(),
profile.getRemotePort());
}
} catch (Exception e) {
Log.e(TAG, "Could not create local port forward", e);
if (reason == null)
reason = getString(R.string.fail_to_forward);
return false;
}
return true;
}
/**
* Internal method to request actual PTY terminal once we've finished
* authentication. If called before authenticated, it will just fail.
*/
private void finishConnection() {
Log.e(TAG, "Forward Successful");
if (profile.isSocks())
runRootCommand(BASE + "proxy_socks.sh start "
+ profile.getLocalPort());
else
runRootCommand(BASE + "proxy_http.sh start "
+ profile.getLocalPort());
StringBuffer cmd = new StringBuffer();
cmd.append(BASE + "iptables -t nat -N SSHTUNNEL\n");
cmd.append(BASE + "iptables -t nat -F SSHTUNNEL\n");
if (enableDNSProxy) {
cmd.append(BASE + "iptables -t nat -N SSHTUNNELDNS\n");
cmd.append(BASE + "iptables -t nat -F SSHTUNNELDNS\n");
if (hasRedirectSupport)
cmd.append(BASE
+ "iptables "
+ "-t nat -A SSHTUNNELDNS -p udp --dport 53 -j REDIRECT --to "
+ dnsPort + "\n");
else
cmd.append(BASE
+ "iptables "
+ "-t nat -A SSHTUNNELDNS -p udp --dport 53 -j DNAT --to-destination 127.0.0.1:"
+ dnsPort + "\n");
cmd.append(BASE
+ "iptables -t nat -A OUTPUT -p udp -j SSHTUNNELDNS\n");
}
if (profile.isSocks())
cmd.append(hasRedirectSupport ? CMD_IPTABLES_REDIRECT_ADD_SOCKS
: CMD_IPTABLES_DNAT_ADD_SOCKS);
else
cmd.append(hasRedirectSupport ? CMD_IPTABLES_REDIRECT_ADD
: CMD_IPTABLES_DNAT_ADD);
cmd.append(CMD_IPTABLES_RETURN.replace("0.0.0.0", hostAddress));
if (profile.isGFWList()) {
String[] gfw_list = getResources().getStringArray(R.array.gfw_list);
for (String item : gfw_list) {
cmd.append(BASE + "iptables -t nat -A OUTPUT -p tcp -d " + item
+ " -j SSHTUNNEL\n");
}
} else if (profile.isAutoSetProxy()) {
cmd.append(BASE + "iptables -t nat -A OUTPUT -p tcp -j SSHTUNNEL\n");
} else {
// for proxy specified apps
if (apps == null || apps.length <= 0)
apps = AppManager
.getProxyedApps(this, profile.getProxyedApps());
for (int i = 0; i < apps.length; i++) {
if (apps[i].isProxyed()) {
cmd.append(BASE + "iptables "
+ "-t nat -m owner --uid-owner " + apps[i].getUid()
+ " -A OUTPUT -p tcp -j SSHTUNNEL\n");
}
}
}
String rules = cmd.toString();
if (hostAddress != null)
rules = rules.replace("--dport 443",
"! -d " + hostAddress + " --dport 443").replace(
"--dport 80", "! -d " + hostAddress + " --dport 80");
if (profile.isSocks())
runRootCommand(rules.replace("8124", "8123"));
else
runRootCommand(rules);
}
private void flushIptables() {
StringBuffer cmd = new StringBuffer();
cmd.append(BASE + "iptables -t nat -F SSHTUNNEL\n");
cmd.append(BASE + "iptables -t nat -X SSHTUNNEL\n");
cmd.append((CMD_IPTABLES_RETURN.replace("0.0.0.0", hostAddress))
.replace("-A", "-D"));
if (enableDNSProxy) {
cmd.append(BASE + "iptables -t nat -F SSHTUNNELDNS\n");
cmd.append(BASE + "iptables -t nat -X SSHTUNNELDNS\n");
cmd.append(BASE
+ "iptables -t nat -D OUTPUT -p udp -j SSHTUNNELDNS\n");
}
if (profile.isGFWList()) {
String[] gfw_list = getResources().getStringArray(R.array.gfw_list);
for (String item : gfw_list) {
cmd.append(BASE + "iptables -t nat -D OUTPUT -p tcp -d " + item
+ " -j SSHTUNNEL\n");
}
} else if (profile.isAutoSetProxy()) {
cmd.append(BASE + "iptables -t nat -D OUTPUT -p tcp -j SSHTUNNEL\n");
} else {
// for proxy specified apps
if (apps == null || apps.length <= 0)
apps = AppManager
.getProxyedApps(this, profile.getProxyedApps());
for (int i = 0; i < apps.length; i++) {
if (apps[i].isProxyed()) {
cmd.append(BASE + "iptables "
+ "-t nat -m owner --uid-owner " + apps[i].getUid()
+ " -D OUTPUT -p tcp -j SSHTUNNEL\n");
}
}
}
String rules = cmd.toString();
runRootCommand(rules);
if (profile.isSocks())
runRootCommand(BASE + "proxy_socks.sh stop");
else
runRootCommand(BASE + "proxy_http.sh stop");
}
private void initHasRedirectSupported() {
Process process = null;
DataOutputStream os = null;
DataInputStream es = null;
String command;
String line = null;
command = BASE
+ "iptables -t nat -A OUTPUT -p udp --dport 54 -j REDIRECT --to 8154";
try {
process = Runtime.getRuntime().exec("su");
es = new DataInputStream(process.getErrorStream());
os = new DataOutputStream(process.getOutputStream());
os.writeBytes(command + "\n");
os.writeBytes("exit\n");
os.flush();
process.waitFor();
while (null != (line = es.readLine())) {
Log.d(TAG, line);
if (line.contains("No chain/target/match")) {
this.hasRedirectSupport = false;
break;
}
}
} catch (Exception e) {
Log.e(TAG, e.getMessage());
} finally {
try {
if (os != null) {
os.close();
}
if (es != null)
es.close();
process.destroy();
} catch (Exception e) {
// nothing
}
}
// flush the check command
runRootCommand(command.replace("-A", "-D"));
}
private void initSoundVibrateLights(Notification notification) {
final String ringtone = settings.getString(
"settings_key_notif_ringtone", null);
AudioManager audioManager = (AudioManager) this
.getSystemService(Context.AUDIO_SERVICE);
if (audioManager.getStreamVolume(AudioManager.STREAM_RING) == 0) {
notification.sound = null;
} else if (ringtone != null)
notification.sound = Uri.parse(ringtone);
else
notification.defaults |= Notification.DEFAULT_SOUND;
if (settings.getBoolean("settings_key_notif_icon", true)) {
notification.icon = R.drawable.ic_stat;
} else {
notification.icon = R.drawable.ic_stat_trans;
}
if (settings.getBoolean("settings_key_notif_vibrate", false)) {
long[] vibrate = { 0, 1000, 500, 1000, 500, 1000 };
notification.vibrate = vibrate;
}
notification.defaults |= Notification.DEFAULT_LIGHTS;
}
void invokeMethod(Method method, Object[] args) {
try {
method.invoke(this, mStartForegroundArgs);
} catch (InvocationTargetException e) {
// Should not happen.
Log.w("ApiDemos", "Unable to invoke method", e);
} catch (IllegalAccessException e) {
// Should not happen.
Log.w("ApiDemos", "Unable to invoke method", e);
}
}
public boolean isOnline() {
ConnectivityManager manager = (ConnectivityManager) this
.getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
if (networkInfo == null) {
if (reason == null)
reason = getString(R.string.fail_to_online);
return false;
}
return true;
}
private void notifyAlert(String title, String info) {
notification.tickerText = title;
notification.flags = Notification.FLAG_ONGOING_EVENT;
// notification.defaults = Notification.DEFAULT_SOUND;
initSoundVibrateLights(notification);
notification.setLatestEventInfo(this, getString(R.string.app_name)
+ " | " + Utils.getProfileName(profile), info, pendIntent);
notificationManager.cancel(1);
startForegroundCompat(1, notification);
}
private void notifyAlert(String title, String info, int flags) {
notification.tickerText = title;
notification.flags = flags;
initSoundVibrateLights(notification);
notification.setLatestEventInfo(this, getString(R.string.app_name)
+ " | " + Utils.getProfileName(profile), info, pendIntent);
notificationManager.cancel(0);
notificationManager.notify(0, notification);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
settings = PreferenceManager.getDefaultSharedPreferences(this);
notificationManager = (NotificationManager) this
.getSystemService(NOTIFICATION_SERVICE);
intent = new Intent(this, SSHTunnel.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
pendIntent = PendingIntent.getActivity(this, 0, intent, 0);
notification = new Notification();
try {
mStartForeground = getClass().getMethod("startForeground",
mStartForegroundSignature);
mStopForeground = getClass().getMethod("stopForeground",
mStopForegroundSignature);
} catch (NoSuchMethodException e) {
// Running on an older platform.
mStartForeground = mStopForeground = null;
}
if (reason == null)
reason = getString(R.string.fail_to_connect);
}
/** Called when the activity is closed. */
@Override
public void onDestroy() {
if (profile == null) {
return;
}
isStopping = true;
stopForegroundCompat(1);
FlurryAgent.onEndSession(this);
if (connected) {
notifyAlert(getString(R.string.forward_stop),
getString(R.string.service_stopped),
Notification.FLAG_AUTO_CANCEL);
}
if (enableDNSProxy) {
try {
if (dnsServer != null) {
dnsServer.close();
dnsServer = null;
}
} catch (Exception e) {
Log.e(TAG, "DNS Server close unexpected");
}
}
new Thread() {
@Override
public void run() {
// Make sure the connection is closed, important here
onDisconnect();
isStopping = false;
handler.sendEmptyMessage(MSG_DISCONNECT_FINISH);
}
}.start();
flushIptables();
super.onDestroy();
markServiceStopped();
}
private void onDisconnect() {
connected = false;
try {
if (lpf != null) {
lpf.close();
lpf = null;
}
} catch (IOException ignore) {
// Nothing
}
try {
if (dpf != null) {
dpf.close();
dpf = null;
}
} catch (IOException ignore) {
// Nothing
}
try {
if (dnspf != null) {
dnspf.close();
dnspf = null;
}
} catch (IOException ignore) {
// Nothing
}
if (connection != null) {
connection.close();
connection = null;
}
}
// This is the old onStart method that will be called on the pre-2.0
// platform. On 2.0 or later we override onStartCommand() so this
// method will not be called.
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
FlurryAgent.onStartSession(this, "MBY4JL18FQK1DPEJ5Y39");
Log.d(TAG, "Service Start");
Bundle bundle = intent.getExtras();
int id = bundle.getInt(Constraints.ID);
profile = ProfileFactory.loadProfileFromDao(id);
Log.d(TAG, profile.toString());
new Thread(new Runnable() {
@Override
public void run() {
handler.sendEmptyMessage(MSG_CONNECT_START);
isConnecting = true;
enableDNSProxy = profile.isDNSProxy();
try {
URL url = new URL("http://gae-ip-country.appspot.com/");
HttpURLConnection conn = (HttpURLConnection) url
.openConnection();
conn.setConnectTimeout(2000);
conn.setReadTimeout(5000);
conn.connect();
InputStream is = conn.getInputStream();
BufferedReader input = new BufferedReader(
new InputStreamReader(is));
String code = input.readLine();
if (code != null && code.length() > 0 && code.length() < 3) {
Log.d(TAG, "Location: " + code);
if (!code.contains("CN") && !code.contains("ZZ"))
enableDNSProxy = false;
}
} catch (Exception e) {
Log.d(TAG, "Cannot get country code");
// Nothing
}
if (enableDNSProxy) {
if (dnsServer == null) {
// dnsServer = new DNSServer("DNS Server", "8.8.4.4",
// 53,
// SSHTunnelService.this);
dnsServer = new DNSServer("DNS Server", "127.0.0.1",
8053, SSHTunnelService.this);
dnsServer.setBasePath("/data/data/org.sshtunnel");
dnsPort = dnsServer.init();
}
}
// Test for Redirect Support
initHasRedirectSupported();
if (isOnline() && connect()) {
// Connection and forward successful
finishConnection();
if (enableDNSProxy) {
// Start DNS Proxy
Thread dnsThread = new Thread(dnsServer);
dnsThread.setDaemon(true);
dnsThread.start();
}
notifyAlert(getString(R.string.forward_success),
getString(R.string.service_running));
handler.sendEmptyMessage(MSG_CONNECT_FINISH);
handler.sendEmptyMessage(MSG_CONNECT_SUCCESS);
// for widget, maybe exception here
try {
RemoteViews views = new RemoteViews(getPackageName(),
R.layout.sshtunnel_appwidget);
views.setImageViewResource(R.id.serviceToggle,
R.drawable.on);
AppWidgetManager awm = AppWidgetManager
.getInstance(SSHTunnelService.this);
awm.updateAppWidget(awm
.getAppWidgetIds(new ComponentName(
SSHTunnelService.this,
SSHTunnelWidgetProvider.class)), views);
} catch (Exception ignore) {
// Nothing
}
} else {
// Connection or forward unsuccessful
notifyAlert(getString(R.string.forward_fail) + ": "
+ reason, getString(R.string.service_failed),
Notification.FLAG_AUTO_CANCEL);
handler.sendEmptyMessage(MSG_CONNECT_FINISH);
handler.sendEmptyMessage(MSG_CONNECT_FAIL);
try {
Thread.sleep(1000);
} catch (InterruptedException ignore) {
// Nothing
}
connected = false;
stopSelf();
}
isConnecting = false;
}
}).start();
markServiceStarted();
}
// XXX: Is it right?
@Override
public String[] replyToChallenge(String name, String instruction,
int numPrompts, String[] prompt, boolean[] echo) throws Exception {
String[] responses = new String[numPrompts];
for (int i = 0; i < numPrompts; i++) {
// request response from user for each prompt
if (prompt[i].toLowerCase().contains("password"))
responses[i] = profile.getPassword();
}
return responses;
}
/**
* This is a wrapper around the new startForeground method, using the older
* APIs if it is not available.
*/
void startForegroundCompat(int id, Notification notification) {
// If we have the new startForeground API, then use it.
if (mStartForeground != null) {
mStartForegroundArgs[0] = Integer.valueOf(id);
mStartForegroundArgs[1] = notification;
invokeMethod(mStartForeground, mStartForegroundArgs);
return;
}
// Fall back on the old API.
setForeground(true);
notificationManager.notify(id, notification);
}
/**
* This is a wrapper around the new stopForeground method, using the older
* APIs if it is not available.
*/
void stopForegroundCompat(int id) {
// If we have the new stopForeground API, then use it.
if (mStopForeground != null) {
mStopForegroundArgs[0] = Boolean.TRUE;
try {
mStopForeground.invoke(this, mStopForegroundArgs);
} catch (InvocationTargetException e) {
// Should not happen.
Log.w("ApiDemos", "Unable to invoke stopForeground", e);
} catch (IllegalAccessException e) {
// Should not happen.
Log.w("ApiDemos", "Unable to invoke stopForeground", e);
}
return;
}
// Fall back on the old API. Note to cancel BEFORE changing the
// foreground state, since we could be killed at that point.
notificationManager.cancel(id);
setForeground(false);
}
public void stopReconnect(SimpleDateFormat df) {
connected = false;
notifyAlert(
getString(R.string.reconnect_fail) + " "
+ df.format(new Date()),
getString(R.string.reconnect_fail),
Notification.FLAG_AUTO_CANCEL);
stopSelf();
}
@Override
public boolean verifyServerHostKey(String hostname, int port,
String serverHostKeyAlgorithm, byte[] serverHostKey)
throws Exception {
String fingerPrint = KnownHosts.createHexFingerprint(
serverHostKeyAlgorithm, serverHostKey);
int fingerPrintStatus = Constraints.FINGER_PRINT_CHANGED;
if (profile.getFingerPrintType() == null
|| profile.getFingerPrintType().equals("")) {
fingerPrintStatus = Constraints.FINGER_PRINT_INIITIALIZE;
reason = getString(R.string.finger_print_unknown);
} else {
if (profile.getFingerPrintType().equals(serverHostKeyAlgorithm)
&& profile.getFingerPrint() != null
&& profile.getFingerPrint().equals(fingerPrint)) {
return true;
} else {
fingerPrintStatus = Constraints.FINGER_PRINT_CHANGED;
reason = getString(R.string.finger_print_mismatch);
}
}
Log.d(TAG, "Finger Print: " + profile.getFingerPrint());
Log.d(TAG, "Finger Print Type: " + profile.getFingerPrintType());
Bundle bundle = new Bundle();
bundle.putInt(Constraints.ID, profile.getId());
bundle.putInt(Constraints.FINGER_PRINT_STATUS, fingerPrintStatus);
bundle.putString(Constraints.FINGER_PRINT, fingerPrint);
bundle.putString(Constraints.FINGER_PRINT_TYPE, serverHostKeyAlgorithm);
Message msg = new Message();
msg.setData(bundle);
hostKeyHandler.sendMessage(msg);
synchronized (fingerPrintLock) {
fingerPrintLock.wait();
}
return fingerPrintChecker;
}
}
| Java |
package org.sshtunnel;
public class Option implements Comparable<Option>{
private String name;
private String data;
private String path;
public Option(String n,String d,String p)
{
name = n;
data = d;
path = p;
}
@Override
public int compareTo(Option o) {
if(this.name != null)
return this.name.toLowerCase().compareTo(o.getName().toLowerCase());
else
throw new IllegalArgumentException();
}
public String getData()
{
return data;
}
public String getName()
{
return name;
}
public String getPath()
{
return path;
}
}
| Java |
/* sshtunnel - SSH Tunnel App for Android
* Copyright (C) 2011 Max Lv <max.c.lv@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* ___====-_ _-====___
* _--^^^#####// \\#####^^^--_
* _-^##########// ( ) \\##########^-_
* -############// |\^^/| \\############-
* _/############// (@::@) \\############\_
* /#############(( \\// ))#############\
* -###############\\ (oo) //###############-
* -#################\\ / VV \ //#################-
* -###################\\/ \//###################-
* _#/|##########/\######( /\ )######/\##########|\#_
* |/ |#/\#/\#/\/ \#/\##\ | | /##/\#/ \/\#/\#/\#| \|
* ` |/ V V ` V \#\| | | |/#/ V ' V V \| '
* ` ` ` ` / | | | | \ ' ' ' '
* ( | | | | )
* __\ | | | | /__
* (vvv(VVV)(VVV)vvv)
*
* HERE BE DRAGONS
*
*/
package org.sshtunnel;
import java.util.ArrayList;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.RemoteViews;
public class SSHTunnelWidgetProvider extends AppWidgetProvider {
public static final String PROXY_SWITCH_ACTION = "org.sshtunnel.SSHTunnelWidgetProvider.PROXY_SWITCH_ACTION";
public static final String SERVICE_NAME = "org.sshtunnel.SSHTunnelService";
public static final String TAG = "SSHTunnelWidgetProvider";
public boolean isWorked(Context context, String service) {
ActivityManager myManager = (ActivityManager) context
.getSystemService(Context.ACTIVITY_SERVICE);
ArrayList<RunningServiceInfo> runningService = (ArrayList<RunningServiceInfo>) myManager
.getRunningServices(30);
for (int i = 0; i < runningService.size(); i++) {
if (runningService.get(i).service.getClassName().toString()
.equals(service)) {
return true;
}
}
return false;
}
@Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
if (intent.getAction().equals(PROXY_SWITCH_ACTION)) {
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
if (settings.getBoolean("isSwitching", false))
return;
Editor ed = settings.edit();
ed.putBoolean("isSwitching", true);
ed.commit();
RemoteViews views = new RemoteViews(context.getPackageName(),
R.layout.sshtunnel_appwidget);
try {
views.setImageViewResource(R.id.serviceToggle, R.drawable.ing);
AppWidgetManager awm = AppWidgetManager.getInstance(context);
awm.updateAppWidget(awm.getAppWidgetIds(new ComponentName(
context, SSHTunnelWidgetProvider.class)), views);
} catch (Exception ignore) {
// Nothing
}
Log.d(TAG, "Proxy switch action");
// do some really cool stuff here
if (isWorked(context, SERVICE_NAME)) {
// Service is working, so stop it
try {
context.stopService(new Intent(context,
SSHTunnelService.class));
} catch (Exception e) {
// Nothing
}
} else {
SSHTunnelReceiver sshr = new SSHTunnelReceiver();
sshr.onReceive(context, intent, true);
}
}
}
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
final int N = appWidgetIds.length;
// Perform this loop procedure for each App Widget that belongs to this
// provider
for (int i = 0; i < N; i++) {
int appWidgetId = appWidgetIds[i];
// Create an Intent to launch ExampleActivity
Intent intent = new Intent(context, SSHTunnelWidgetProvider.class);
intent.setAction(PROXY_SWITCH_ACTION);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context,
0, intent, 0);
// Get the layout for the App Widget and attach an on-click listener
// to the button
RemoteViews views = new RemoteViews(context.getPackageName(),
R.layout.sshtunnel_appwidget);
views.setOnClickPendingIntent(R.id.serviceToggle, pendingIntent);
if (isWorked(context, SERVICE_NAME)) {
views.setImageViewResource(R.id.serviceToggle, R.drawable.on);
Log.d(TAG, "Service running");
} else {
views.setImageViewResource(R.id.serviceToggle, R.drawable.off);
Log.d(TAG, "Service stopped");
}
// Tell the AppWidgetManager to perform an update on the current App
// Widget
appWidgetManager.updateAppWidget(appWidgetId, views);
}
}
}
| Java |
package org.sshtunnel.utils;
import android.graphics.drawable.Drawable;
public class ProxyedApp {
private boolean enabled;
private int uid;
private String username;
private String procname;
private String name;
private boolean proxyed = false;
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @return the procname
*/
public String getProcname() {
return procname;
}
/**
* @return the uid
*/
public int getUid() {
return uid;
}
/**
* @return the username
*/
public String getUsername() {
return username;
}
/**
* @return the enabled
*/
public boolean isEnabled() {
return enabled;
}
/**
* @return the proxyed
*/
public boolean isProxyed() {
return proxyed;
}
/**
* @param enabled the enabled to set
*/
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @param procname the procname to set
*/
public void setProcname(String procname) {
this.procname = procname;
}
/**
* @param proxyed the proxyed to set
*/
public void setProxyed(boolean proxyed) {
this.proxyed = proxyed;
}
/**
* @param uid the uid to set
*/
public void setUid(int uid) {
this.uid = uid;
}
/**
* @param username the username to set
*/
public void setUsername(String username) {
this.username = username;
}
} | Java |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sshtunnel.utils;
import java.io.Serializable;
import java.util.Arrays;
import java.util.List;
/**
* <p><b>Domain name</b> validation routines.</p>
*
* <p>
* This validator provides methods for validating Internet domain names
* and top-level domains.
* </p>
*
* <p>Domain names are evaluated according
* to the standards <a href="http://www.ietf.org/rfc/rfc1034.txt">RFC1034</a>,
* section 3, and <a href="http://www.ietf.org/rfc/rfc1123.txt">RFC1123</a>,
* section 2.1. No accomodation is provided for the specialized needs of
* other applications; if the domain name has been URL-encoded, for example,
* validation will fail even though the equivalent plaintext version of the
* same name would have passed.
* </p>
*
* <p>
* Validation is also provided for top-level domains (TLDs) as defined and
* maintained by the Internet Assigned Numbers Authority (IANA):
* </p>
*
* <ul>
* <li>{@link #isValidInfrastructureTld} - validates infrastructure TLDs
* (<code>.arpa</code>, etc.)</li>
* <li>{@link #isValidGenericTld} - validates generic TLDs
* (<code>.com, .org</code>, etc.)</li>
* <li>{@link #isValidCountryCodeTld} - validates country code TLDs
* (<code>.us, .uk, .cn</code>, etc.)</li>
* </ul>
*
* <p>
* (<b>NOTE</b>: This class does not provide IP address lookup for domain names or
* methods to ensure that a given domain name matches a specific IP; see
* {@link java.net.InetAddress} for that functionality.)
* </p>
*
* @version $Revision$ $Date$
* @since Validator 1.4
*/
public class DomainValidator implements Serializable {
// Regular expression strings for hostnames (derived from RFC2396 and RFC 1123)
private static final String DOMAIN_LABEL_REGEX = "\\p{Alnum}(?>[\\p{Alnum}-]*\\p{Alnum})*";
private static final String TOP_LABEL_REGEX = "\\p{Alpha}{2,}";
private static final String DOMAIN_NAME_REGEX =
"^(?:" + DOMAIN_LABEL_REGEX + "\\.)+" + "(" + TOP_LABEL_REGEX + ")$";
/**
* Singleton instance of this validator.
*/
private static final DomainValidator DOMAIN_VALIDATOR = new DomainValidator();
private static final String[] INFRASTRUCTURE_TLDS = new String[] {
"arpa", // internet infrastructure
"root" // diagnostic marker for non-truncated root zone
};
private static final String[] GENERIC_TLDS = new String[] {
"aero", // air transport industry
"asia", // Pan-Asia/Asia Pacific
"biz", // businesses
"cat", // Catalan linguistic/cultural community
"com", // commercial enterprises
"coop", // cooperative associations
"info", // informational sites
"jobs", // Human Resource managers
"mobi", // mobile products and services
"museum", // museums, surprisingly enough
"name", // individuals' sites
"net", // internet support infrastructure/business
"org", // noncommercial organizations
"pro", // credentialed professionals and entities
"tel", // contact data for businesses and individuals
"travel", // entities in the travel industry
"gov", // United States Government
"edu", // accredited postsecondary US education entities
"mil", // United States Military
"int" // organizations established by international treaty
};
private static final String[] COUNTRY_CODE_TLDS = new String[] {
"ac", // Ascension Island
"ad", // Andorra
"ae", // United Arab Emirates
"af", // Afghanistan
"ag", // Antigua and Barbuda
"ai", // Anguilla
"al", // Albania
"am", // Armenia
"an", // Netherlands Antilles
"ao", // Angola
"aq", // Antarctica
"ar", // Argentina
"as", // American Samoa
"at", // Austria
"au", // Australia (includes Ashmore and Cartier Islands and Coral Sea Islands)
"aw", // Aruba
"ax", // 脙鈥and
"az", // Azerbaijan
"ba", // Bosnia and Herzegovina
"bb", // Barbados
"bd", // Bangladesh
"be", // Belgium
"bf", // Burkina Faso
"bg", // Bulgaria
"bh", // Bahrain
"bi", // Burundi
"bj", // Benin
"bm", // Bermuda
"bn", // Brunei Darussalam
"bo", // Bolivia
"br", // Brazil
"bs", // Bahamas
"bt", // Bhutan
"bv", // Bouvet Island
"bw", // Botswana
"by", // Belarus
"bz", // Belize
"ca", // Canada
"cc", // Cocos (Keeling) Islands
"cd", // Democratic Republic of the Congo (formerly Zaire)
"cf", // Central African Republic
"cg", // Republic of the Congo
"ch", // Switzerland
"ci", // C脙麓te d'Ivoire
"ck", // Cook Islands
"cl", // Chile
"cm", // Cameroon
"cn", // China, mainland
"co", // Colombia
"cr", // Costa Rica
"cu", // Cuba
"cv", // Cape Verde
"cx", // Christmas Island
"cy", // Cyprus
"cz", // Czech Republic
"de", // Germany
"dj", // Djibouti
"dk", // Denmark
"dm", // Dominica
"do", // Dominican Republic
"dz", // Algeria
"ec", // Ecuador
"ee", // Estonia
"eg", // Egypt
"er", // Eritrea
"es", // Spain
"et", // Ethiopia
"eu", // European Union
"fi", // Finland
"fj", // Fiji
"fk", // Falkland Islands
"fm", // Federated States of Micronesia
"fo", // Faroe Islands
"fr", // France
"ga", // Gabon
"gb", // Great Britain (United Kingdom)
"gd", // Grenada
"ge", // Georgia
"gf", // French Guiana
"gg", // Guernsey
"gh", // Ghana
"gi", // Gibraltar
"gl", // Greenland
"gm", // The Gambia
"gn", // Guinea
"gp", // Guadeloupe
"gq", // Equatorial Guinea
"gr", // Greece
"gs", // South Georgia and the South Sandwich Islands
"gt", // Guatemala
"gu", // Guam
"gw", // Guinea-Bissau
"gy", // Guyana
"hk", // Hong Kong
"hm", // Heard Island and McDonald Islands
"hn", // Honduras
"hr", // Croatia (Hrvatska)
"ht", // Haiti
"hu", // Hungary
"id", // Indonesia
"ie", // Ireland (脙鈥癷re)
"il", // Israel
"im", // Isle of Man
"in", // India
"io", // British Indian Ocean Territory
"iq", // Iraq
"ir", // Iran
"is", // Iceland
"it", // Italy
"je", // Jersey
"jm", // Jamaica
"jo", // Jordan
"jp", // Japan
"ke", // Kenya
"kg", // Kyrgyzstan
"kh", // Cambodia (Khmer)
"ki", // Kiribati
"km", // Comoros
"kn", // Saint Kitts and Nevis
"kp", // North Korea
"kr", // South Korea
"kw", // Kuwait
"ky", // Cayman Islands
"kz", // Kazakhstan
"la", // Laos (currently being marketed as the official domain for Los Angeles)
"lb", // Lebanon
"lc", // Saint Lucia
"li", // Liechtenstein
"lk", // Sri Lanka
"lr", // Liberia
"ls", // Lesotho
"lt", // Lithuania
"lu", // Luxembourg
"lv", // Latvia
"ly", // Libya
"ma", // Morocco
"mc", // Monaco
"md", // Moldova
"me", // Montenegro
"mg", // Madagascar
"mh", // Marshall Islands
"mk", // Republic of Macedonia
"ml", // Mali
"mm", // Myanmar
"mn", // Mongolia
"mo", // Macau
"mp", // Northern Mariana Islands
"mq", // Martinique
"mr", // Mauritania
"ms", // Montserrat
"mt", // Malta
"mu", // Mauritius
"mv", // Maldives
"mw", // Malawi
"mx", // Mexico
"my", // Malaysia
"mz", // Mozambique
"na", // Namibia
"nc", // New Caledonia
"ne", // Niger
"nf", // Norfolk Island
"ng", // Nigeria
"ni", // Nicaragua
"nl", // Netherlands
"no", // Norway
"np", // Nepal
"nr", // Nauru
"nu", // Niue
"nz", // New Zealand
"om", // Oman
"pa", // Panama
"pe", // Peru
"pf", // French Polynesia With Clipperton Island
"pg", // Papua New Guinea
"ph", // Philippines
"pk", // Pakistan
"pl", // Poland
"pm", // Saint-Pierre and Miquelon
"pn", // Pitcairn Islands
"pr", // Puerto Rico
"ps", // Palestinian territories (PA-controlled West Bank and Gaza Strip)
"pt", // Portugal
"pw", // Palau
"py", // Paraguay
"qa", // Qatar
"re", // R脙漏union
"ro", // Romania
"rs", // Serbia
"ru", // Russia
"rw", // Rwanda
"sa", // Saudi Arabia
"sb", // Solomon Islands
"sc", // Seychelles
"sd", // Sudan
"se", // Sweden
"sg", // Singapore
"sh", // Saint Helena
"si", // Slovenia
"sj", // Svalbard and Jan Mayen Islands Not in use (Norwegian dependencies; see .no)
"sk", // Slovakia
"sl", // Sierra Leone
"sm", // San Marino
"sn", // Senegal
"so", // Somalia
"sr", // Suriname
"st", // S脙拢o Tom脙漏 and Pr脙颅ncipe
"su", // Soviet Union (deprecated)
"sv", // El Salvador
"sy", // Syria
"sz", // Swaziland
"tc", // Turks and Caicos Islands
"td", // Chad
"tf", // French Southern and Antarctic Lands
"tg", // Togo
"th", // Thailand
"tj", // Tajikistan
"tk", // Tokelau
"tl", // East Timor (deprecated old code)
"tm", // Turkmenistan
"tn", // Tunisia
"to", // Tonga
"tp", // East Timor
"tr", // Turkey
"tt", // Trinidad and Tobago
"tv", // Tuvalu
"tw", // Taiwan, Republic of China
"tz", // Tanzania
"ua", // Ukraine
"ug", // Uganda
"uk", // United Kingdom
"um", // United States Minor Outlying Islands
"us", // United States of America
"uy", // Uruguay
"uz", // Uzbekistan
"va", // Vatican City State
"vc", // Saint Vincent and the Grenadines
"ve", // Venezuela
"vg", // British Virgin Islands
"vi", // U.S. Virgin Islands
"vn", // Vietnam
"vu", // Vanuatu
"wf", // Wallis and Futuna
"ws", // Samoa (formerly Western Samoa)
"ye", // Yemen
"yt", // Mayotte
"yu", // Serbia and Montenegro (originally Yugoslavia)
"za", // South Africa
"zm", // Zambia
"zw", // Zimbabwe
};
private static final List INFRASTRUCTURE_TLD_LIST = Arrays.asList(INFRASTRUCTURE_TLDS);
private static final List GENERIC_TLD_LIST = Arrays.asList(GENERIC_TLDS);
private static final List COUNTRY_CODE_TLD_LIST = Arrays.asList(COUNTRY_CODE_TLDS);
/**
* Returns the singleton instance of this validator.
* @return the singleton instance of this validator
*/
public static DomainValidator getInstance() {
return DOMAIN_VALIDATOR;
}
/**
* RegexValidator for matching domains.
*/
private final RegexValidator domainRegex =
new RegexValidator(DOMAIN_NAME_REGEX);
/** Private constructor. */
private DomainValidator() {}
// ---------------------------------------------
// ----- TLDs defined by IANA
// ----- Authoritative and comprehensive list at:
// ----- http://data.iana.org/TLD/tlds-alpha-by-domain.txt
private String chompLeadingDot(String str) {
if (str.startsWith(".")) {
return str.substring(1);
} else {
return str;
}
}
/**
* Returns true if the specified <code>String</code> parses
* as a valid domain name with a recognized top-level domain.
* The parsing is case-sensitive.
* @param domain the parameter to check for domain name syntax
* @return true if the parameter is a valid domain name
*/
public boolean isValid(String domain) {
String[] groups = domainRegex.match(domain);
if (groups != null && groups.length > 0) {
return isValidTld(groups[0]);
} else {
return false;
}
}
/**
* Returns true if the specified <code>String</code> matches any
* IANA-defined country code top-level domain. Leading dots are
* ignored if present. The search is case-sensitive.
* @param ccTld the parameter to check for country code TLD status
* @return true if the parameter is a country code TLD
*/
public boolean isValidCountryCodeTld(String ccTld) {
return COUNTRY_CODE_TLD_LIST.contains(chompLeadingDot(ccTld.toLowerCase()));
}
/**
* Returns true if the specified <code>String</code> matches any
* IANA-defined generic top-level domain. Leading dots are ignored
* if present. The search is case-sensitive.
* @param gTld the parameter to check for generic TLD status
* @return true if the parameter is a generic TLD
*/
public boolean isValidGenericTld(String gTld) {
return GENERIC_TLD_LIST.contains(chompLeadingDot(gTld.toLowerCase()));
}
/**
* Returns true if the specified <code>String</code> matches any
* IANA-defined infrastructure top-level domain. Leading dots are
* ignored if present. The search is case-sensitive.
* @param iTld the parameter to check for infrastructure TLD status
* @return true if the parameter is an infrastructure TLD
*/
public boolean isValidInfrastructureTld(String iTld) {
return INFRASTRUCTURE_TLD_LIST.contains(chompLeadingDot(iTld.toLowerCase()));
}
/**
* Returns true if the specified <code>String</code> matches any
* IANA-defined top-level domain. Leading dots are ignored if present.
* The search is case-sensitive.
* @param tld the parameter to check for TLD status
* @return true if the parameter is a TLD
*/
public boolean isValidTld(String tld) {
return isValidInfrastructureTld(tld)
|| isValidGenericTld(tld)
|| isValidCountryCodeTld(tld);
}
}
| Java |
package org.sshtunnel.utils;
/**
* <p>Encodes and decodes to and from Base64 notation.</p>
* <p>Homepage: <a href="http://iharder.net/base64">http://iharder.net/base64</a>.</p>
*
* <p>Example:</p>
*
* <code>String encoded = Base64.encode( myByteArray );</code>
* <br />
* <code>byte[] myByteArray = Base64.decode( encoded );</code>
*
* <p>The <tt>options</tt> parameter, which appears in a few places, is used to pass
* several pieces of information to the encoder. In the "higher level" methods such as
* encodeBytes( bytes, options ) the options parameter can be used to indicate such
* things as first gzipping the bytes before encoding them, not inserting linefeeds,
* and encoding using the URL-safe and Ordered dialects.</p>
*
* <p>Note, according to <a href="http://www.faqs.org/rfcs/rfc3548.html">RFC3548</a>,
* Section 2.1, implementations should not add line feeds unless explicitly told
* to do so. I've got Base64 set to this behavior now, although earlier versions
* broke lines by default.</p>
*
* <p>The constants defined in Base64 can be OR-ed together to combine options, so you
* might make a call like this:</p>
*
* <code>String encoded = Base64.encodeBytes( mybytes, Base64.GZIP | Base64.DO_BREAK_LINES );</code>
* <p>to compress the data before encoding it and then making the output have newline characters.</p>
* <p>Also...</p>
* <code>String encoded = Base64.encodeBytes( crazyString.getBytes() );</code>
*
*
*
* <p>
* Change Log:
* </p>
* <ul>
* <li>v2.3.7 - Fixed subtle bug when base 64 input stream contained the
* value 01111111, which is an invalid base 64 character but should not
* throw an ArrayIndexOutOfBoundsException either. Led to discovery of
* mishandling (or potential for better handling) of other bad input
* characters. You should now get an IOException if you try decoding
* something that has bad characters in it.</li>
* <li>v2.3.6 - Fixed bug when breaking lines and the final byte of the encoded
* string ended in the last column; the buffer was not properly shrunk and
* contained an extra (null) byte that made it into the string.</li>
* <li>v2.3.5 - Fixed bug in {@link #encodeFromFile} where estimated buffer size
* was wrong for files of size 31, 34, and 37 bytes.</li>
* <li>v2.3.4 - Fixed bug when working with gzipped streams whereby flushing
* the Base64.OutputStream closed the Base64 encoding (by padding with equals
* signs) too soon. Also added an option to suppress the automatic decoding
* of gzipped streams. Also added experimental support for specifying a
* class loader when using the
* {@link #decodeToObject(java.lang.String, int, java.lang.ClassLoader)}
* method.</li>
* <li>v2.3.3 - Changed default char encoding to US-ASCII which reduces the internal Java
* footprint with its CharEncoders and so forth. Fixed some javadocs that were
* inconsistent. Removed imports and specified things like java.io.IOException
* explicitly inline.</li>
* <li>v2.3.2 - Reduced memory footprint! Finally refined the "guessing" of how big the
* final encoded data will be so that the code doesn't have to create two output
* arrays: an oversized initial one and then a final, exact-sized one. Big win
* when using the {@link #encodeBytesToBytes(byte[])} family of methods (and not
* using the gzip options which uses a different mechanism with streams and stuff).</li>
* <li>v2.3.1 - Added {@link #encodeBytesToBytes(byte[], int, int, int)} and some
* similar helper methods to be more efficient with memory by not returning a
* String but just a byte array.</li>
* <li>v2.3 - <strong>This is not a drop-in replacement!</strong> This is two years of comments
* and bug fixes queued up and finally executed. Thanks to everyone who sent
* me stuff, and I'm sorry I wasn't able to distribute your fixes to everyone else.
* Much bad coding was cleaned up including throwing exceptions where necessary
* instead of returning null values or something similar. Here are some changes
* that may affect you:
* <ul>
* <li><em>Does not break lines, by default.</em> This is to keep in compliance with
* <a href="http://www.faqs.org/rfcs/rfc3548.html">RFC3548</a>.</li>
* <li><em>Throws exceptions instead of returning null values.</em> Because some operations
* (especially those that may permit the GZIP option) use IO streams, there
* is a possiblity of an java.io.IOException being thrown. After some discussion and
* thought, I've changed the behavior of the methods to throw java.io.IOExceptions
* rather than return null if ever there's an error. I think this is more
* appropriate, though it will require some changes to your code. Sorry,
* it should have been done this way to begin with.</li>
* <li><em>Removed all references to System.out, System.err, and the like.</em>
* Shame on me. All I can say is sorry they were ever there.</li>
* <li><em>Throws NullPointerExceptions and IllegalArgumentExceptions</em> as needed
* such as when passed arrays are null or offsets are invalid.</li>
* <li>Cleaned up as much javadoc as I could to avoid any javadoc warnings.
* This was especially annoying before for people who were thorough in their
* own projects and then had gobs of javadoc warnings on this file.</li>
* </ul>
* <li>v2.2.1 - Fixed bug using URL_SAFE and ORDERED encodings. Fixed bug
* when using very small files (~< 40 bytes).</li>
* <li>v2.2 - Added some helper methods for encoding/decoding directly from
* one file to the next. Also added a main() method to support command line
* encoding/decoding from one file to the next. Also added these Base64 dialects:
* <ol>
* <li>The default is RFC3548 format.</li>
* <li>Calling Base64.setFormat(Base64.BASE64_FORMAT.URLSAFE_FORMAT) generates
* URL and file name friendly format as described in Section 4 of RFC3548.
* http://www.faqs.org/rfcs/rfc3548.html</li>
* <li>Calling Base64.setFormat(Base64.BASE64_FORMAT.ORDERED_FORMAT) generates
* URL and file name friendly format that preserves lexical ordering as described
* in http://www.faqs.org/qa/rfcc-1940.html</li>
* </ol>
* Special thanks to Jim Kellerman at <a href="http://www.powerset.com/">http://www.powerset.com/</a>
* for contributing the new Base64 dialects.
* </li>
*
* <li>v2.1 - Cleaned up javadoc comments and unused variables and methods. Added
* some convenience methods for reading and writing to and from files.</li>
* <li>v2.0.2 - Now specifies UTF-8 encoding in places where the code fails on systems
* with other encodings (like EBCDIC).</li>
* <li>v2.0.1 - Fixed an error when decoding a single byte, that is, when the
* encoded data was a single byte.</li>
* <li>v2.0 - I got rid of methods that used booleans to set options.
* Now everything is more consolidated and cleaner. The code now detects
* when data that's being decoded is gzip-compressed and will decompress it
* automatically. Generally things are cleaner. You'll probably have to
* change some method calls that you were making to support the new
* options format (<tt>int</tt>s that you "OR" together).</li>
* <li>v1.5.1 - Fixed bug when decompressing and decoding to a
* byte[] using <tt>decode( String s, boolean gzipCompressed )</tt>.
* Added the ability to "suspend" encoding in the Output Stream so
* you can turn on and off the encoding if you need to embed base64
* data in an otherwise "normal" stream (like an XML file).</li>
* <li>v1.5 - Output stream pases on flush() command but doesn't do anything itself.
* This helps when using GZIP streams.
* Added the ability to GZip-compress objects before encoding them.</li>
* <li>v1.4 - Added helper methods to read/write files.</li>
* <li>v1.3.6 - Fixed OutputStream.flush() so that 'position' is reset.</li>
* <li>v1.3.5 - Added flag to turn on and off line breaks. Fixed bug in input stream
* where last buffer being read, if not completely full, was not returned.</li>
* <li>v1.3.4 - Fixed when "improperly padded stream" error was thrown at the wrong time.</li>
* <li>v1.3.3 - Fixed I/O streams which were totally messed up.</li>
* </ul>
*
* <p>
* I am placing this code in the Public Domain. Do with it as you will.
* This software comes with no guarantees or warranties but with
* plenty of well-wishing instead!
* Please visit <a href="http://iharder.net/base64">http://iharder.net/base64</a>
* periodically to check for updates or to contribute improvements.
* </p>
*
* @author Robert Harder
* @author rob@iharder.net
* @version 2.3.7
*/
public class Base64
{
/* ******** P U B L I C F I E L D S ******** */
/**
* A {@link Base64.InputStream} will read data from another
* <tt>java.io.InputStream</tt>, given in the constructor,
* and encode/decode to/from Base64 notation on the fly.
*
* @see Base64
* @since 1.3
*/
public static class InputStream extends java.io.FilterInputStream {
private boolean encode; // Encoding or decoding
private int position; // Current position in the buffer
private byte[] buffer; // Small buffer holding converted data
private int bufferLength; // Length of buffer (3 or 4)
private int numSigBytes; // Number of meaningful bytes in the buffer
private int lineLength;
private boolean breakLines; // Break lines at less than 80 characters
private int options; // Record options used to create the stream.
private byte[] decodabet; // Local copies to avoid extra method calls
/**
* Constructs a {@link Base64.InputStream} in DECODE mode.
*
* @param in the <tt>java.io.InputStream</tt> from which to read data.
* @since 1.3
*/
public InputStream( java.io.InputStream in ) {
this( in, DECODE );
} // end constructor
/**
* Constructs a {@link Base64.InputStream} in
* either ENCODE or DECODE mode.
* <p>
* Valid options:<pre>
* ENCODE or DECODE: Encode or Decode as data is read.
* DO_BREAK_LINES: break lines at 76 characters
* (only meaningful when encoding)</i>
* </pre>
* <p>
* Example: <code>new Base64.InputStream( in, Base64.DECODE )</code>
*
*
* @param in the <tt>java.io.InputStream</tt> from which to read data.
* @param options Specified options
* @see Base64#ENCODE
* @see Base64#DECODE
* @see Base64#DO_BREAK_LINES
* @since 2.0
*/
public InputStream( java.io.InputStream in, int options ) {
super( in );
this.options = options; // Record for later
this.breakLines = (options & DO_BREAK_LINES) > 0;
this.encode = (options & ENCODE) > 0;
this.bufferLength = encode ? 4 : 3;
this.buffer = new byte[ bufferLength ];
this.position = -1;
this.lineLength = 0;
this.decodabet = getDecodabet(options);
} // end constructor
/**
* Reads enough of the input stream to convert
* to/from Base64 and returns the next byte.
*
* @return next byte
* @since 1.3
*/
@Override
public int read() throws java.io.IOException {
// Do we need to get data?
if( position < 0 ) {
if( encode ) {
byte[] b3 = new byte[3];
int numBinaryBytes = 0;
for( int i = 0; i < 3; i++ ) {
int b = in.read();
// If end of stream, b is -1.
if( b >= 0 ) {
b3[i] = (byte)b;
numBinaryBytes++;
} else {
break; // out of for loop
} // end else: end of stream
} // end for: each needed input byte
if( numBinaryBytes > 0 ) {
encode3to4( b3, 0, numBinaryBytes, buffer, 0, options );
position = 0;
numSigBytes = 4;
} // end if: got data
else {
return -1; // Must be end of stream
} // end else
} // end if: encoding
// Else decoding
else {
byte[] b4 = new byte[4];
int i = 0;
for( i = 0; i < 4; i++ ) {
// Read four "meaningful" bytes:
int b = 0;
do{ b = in.read(); }
while( b >= 0 && decodabet[ b & 0x7f ] <= WHITE_SPACE_ENC );
if( b < 0 ) {
break; // Reads a -1 if end of stream
} // end if: end of stream
b4[i] = (byte)b;
} // end for: each needed input byte
if( i == 4 ) {
numSigBytes = decode4to3( b4, 0, buffer, 0, options );
position = 0;
} // end if: got four characters
else if( i == 0 ){
return -1;
} // end else if: also padded correctly
else {
// Must have broken out from above.
throw new java.io.IOException( "Improperly padded Base64 input." );
} // end
} // end else: decode
} // end else: get data
// Got data?
if( position >= 0 ) {
// End of relevant data?
if( /*!encode &&*/ position >= numSigBytes ){
return -1;
} // end if: got data
if( encode && breakLines && lineLength >= MAX_LINE_LENGTH ) {
lineLength = 0;
return '\n';
} // end if
else {
lineLength++; // This isn't important when decoding
// but throwing an extra "if" seems
// just as wasteful.
int b = buffer[ position++ ];
if( position >= bufferLength ) {
position = -1;
} // end if: end
return b & 0xFF; // This is how you "cast" a byte that's
// intended to be unsigned.
} // end else
} // end if: position >= 0
// Else error
else {
throw new java.io.IOException( "Error in Base64 code reading stream." );
} // end else
} // end read
/**
* Calls {@link #read()} repeatedly until the end of stream
* is reached or <var>len</var> bytes are read.
* Returns number of bytes read into array or -1 if
* end of stream is encountered.
*
* @param dest array to hold values
* @param off offset for array
* @param len max number of bytes to read into array
* @return bytes read into array or -1 if end of stream is encountered.
* @since 1.3
*/
@Override
public int read( byte[] dest, int off, int len )
throws java.io.IOException {
int i;
int b;
for( i = 0; i < len; i++ ) {
b = read();
if( b >= 0 ) {
dest[off + i] = (byte) b;
}
else if( i == 0 ) {
return -1;
}
else {
break; // Out of 'for' loop
} // Out of 'for' loop
} // end for: each byte read
return i;
} // end read
} // end inner class InputStream
/**
* A {@link Base64.OutputStream} will write data to another
* <tt>java.io.OutputStream</tt>, given in the constructor,
* and encode/decode to/from Base64 notation on the fly.
*
* @see Base64
* @since 1.3
*/
public static class OutputStream extends java.io.FilterOutputStream {
private boolean encode;
private int position;
private byte[] buffer;
private int bufferLength;
private int lineLength;
private boolean breakLines;
private byte[] b4; // Scratch used in a few places
private boolean suspendEncoding;
private int options; // Record for later
private byte[] decodabet; // Local copies to avoid extra method calls
/**
* Constructs a {@link Base64.OutputStream} in ENCODE mode.
*
* @param out the <tt>java.io.OutputStream</tt> to which data will be written.
* @since 1.3
*/
public OutputStream( java.io.OutputStream out ) {
this( out, ENCODE );
} // end constructor
/**
* Constructs a {@link Base64.OutputStream} in
* either ENCODE or DECODE mode.
* <p>
* Valid options:<pre>
* ENCODE or DECODE: Encode or Decode as data is read.
* DO_BREAK_LINES: don't break lines at 76 characters
* (only meaningful when encoding)</i>
* </pre>
* <p>
* Example: <code>new Base64.OutputStream( out, Base64.ENCODE )</code>
*
* @param out the <tt>java.io.OutputStream</tt> to which data will be written.
* @param options Specified options.
* @see Base64#ENCODE
* @see Base64#DECODE
* @see Base64#DO_BREAK_LINES
* @since 1.3
*/
public OutputStream( java.io.OutputStream out, int options ) {
super( out );
this.breakLines = (options & DO_BREAK_LINES) != 0;
this.encode = (options & ENCODE) != 0;
this.bufferLength = encode ? 3 : 4;
this.buffer = new byte[ bufferLength ];
this.position = 0;
this.lineLength = 0;
this.suspendEncoding = false;
this.b4 = new byte[4];
this.options = options;
this.decodabet = getDecodabet(options);
} // end constructor
/**
* Flushes and closes (I think, in the superclass) the stream.
*
* @since 1.3
*/
@Override
public void close() throws java.io.IOException {
// 1. Ensure that pending characters are written
flushBase64();
// 2. Actually close the stream
// Base class both flushes and closes.
super.close();
buffer = null;
out = null;
} // end close
/**
* Method added by PHIL. [Thanks, PHIL. -Rob]
* This pads the buffer without closing the stream.
* @throws java.io.IOException if there's an error.
*/
public void flushBase64() throws java.io.IOException {
if( position > 0 ) {
if( encode ) {
out.write( encode3to4( b4, buffer, position, options ) );
position = 0;
} // end if: encoding
else {
throw new java.io.IOException( "Base64 input not properly padded." );
} // end else: decoding
} // end if: buffer partially full
} // end flush
/**
* Resumes encoding of the stream.
* May be helpful if you need to embed a piece of
* base64-encoded data in a stream.
*
* @since 1.5.1
*/
public void resumeEncoding() {
this.suspendEncoding = false;
} // end resumeEncoding
/**
* Suspends encoding of the stream.
* May be helpful if you need to embed a piece of
* base64-encoded data in a stream.
*
* @throws java.io.IOException if there's an error flushing
* @since 1.5.1
*/
public void suspendEncoding() throws java.io.IOException {
flushBase64();
this.suspendEncoding = true;
} // end suspendEncoding
/**
* Calls {@link #write(int)} repeatedly until <var>len</var>
* bytes are written.
*
* @param theBytes array from which to read bytes
* @param off offset for array
* @param len max number of bytes to read into array
* @since 1.3
*/
@Override
public void write( byte[] theBytes, int off, int len )
throws java.io.IOException {
// Encoding suspended?
if( suspendEncoding ) {
this.out.write( theBytes, off, len );
return;
} // end if: supsended
for( int i = 0; i < len; i++ ) {
write( theBytes[ off + i ] );
} // end for: each byte written
} // end write
/**
* Writes the byte to the output stream after
* converting to/from Base64 notation.
* When encoding, bytes are buffered three
* at a time before the output stream actually
* gets a write() call.
* When decoding, bytes are buffered four
* at a time.
*
* @param theByte the byte to write
* @since 1.3
*/
@Override
public void write(int theByte)
throws java.io.IOException {
// Encoding suspended?
if( suspendEncoding ) {
this.out.write( theByte );
return;
} // end if: supsended
// Encode?
if( encode ) {
buffer[ position++ ] = (byte)theByte;
if( position >= bufferLength ) { // Enough to encode.
this.out.write( encode3to4( b4, buffer, bufferLength, options ) );
lineLength += 4;
if( breakLines && lineLength >= MAX_LINE_LENGTH ) {
this.out.write( NEW_LINE );
lineLength = 0;
} // end if: end of line
position = 0;
} // end if: enough to output
} // end if: encoding
// Else, Decoding
else {
// Meaningful Base64 character?
if( decodabet[ theByte & 0x7f ] > WHITE_SPACE_ENC ) {
buffer[ position++ ] = (byte)theByte;
if( position >= bufferLength ) { // Enough to output.
int len = Base64.decode4to3( buffer, 0, b4, 0, options );
out.write( b4, 0, len );
position = 0;
} // end if: enough to output
} // end if: meaningful base64 character
else if( decodabet[ theByte & 0x7f ] != WHITE_SPACE_ENC ) {
throw new java.io.IOException( "Invalid character in Base64 data." );
} // end else: not white space either
} // end else: decoding
} // end write
} // end inner class OutputStream
/** No options specified. Value is zero. */
public final static int NO_OPTIONS = 0;
/** Specify encoding in first bit. Value is one. */
public final static int ENCODE = 1;
/** Specify decoding in first bit. Value is zero. */
public final static int DECODE = 0;
/** Specify that data should be gzip-compressed in second bit. Value is two. */
public final static int GZIP = 2;
/** Specify that gzipped data should <em>not</em> be automatically gunzipped. */
public final static int DONT_GUNZIP = 4;
/** Do break lines when encoding. Value is 8. */
public final static int DO_BREAK_LINES = 8;
/* ******** P R I V A T E F I E L D S ******** */
/**
* Encode using Base64-like encoding that is URL- and Filename-safe as described
* in Section 4 of RFC3548:
* <a href="http://www.faqs.org/rfcs/rfc3548.html">http://www.faqs.org/rfcs/rfc3548.html</a>.
* It is important to note that data encoded this way is <em>not</em> officially valid Base64,
* or at the very least should not be called Base64 without also specifying that is
* was encoded using the URL- and Filename-safe dialect.
*/
public final static int URL_SAFE = 16;
/**
* Encode using the special "ordered" dialect of Base64 described here:
* <a href="http://www.faqs.org/qa/rfcc-1940.html">http://www.faqs.org/qa/rfcc-1940.html</a>.
*/
public final static int ORDERED = 32;
/** Maximum line length (76) of Base64 output. */
private final static int MAX_LINE_LENGTH = 76;
/** The equals sign (=) as a byte. */
private final static byte EQUALS_SIGN = (byte)'=';
/** The new line character (\n) as a byte. */
private final static byte NEW_LINE = (byte)'\n';
/** Preferred encoding. */
private final static String PREFERRED_ENCODING = "US-ASCII";
/* ******** S T A N D A R D B A S E 6 4 A L P H A B E T ******** */
private final static byte WHITE_SPACE_ENC = -5; // Indicates white space in encoding
private final static byte EQUALS_SIGN_ENC = -1; // Indicates equals sign in encoding
/* ******** U R L S A F E B A S E 6 4 A L P H A B E T ******** */
/** The 64 valid Base64 values. */
/* Host platform me be something funny like EBCDIC, so we hardcode these values. */
private final static byte[] _STANDARD_ALPHABET = {
(byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G',
(byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N',
(byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U',
(byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z',
(byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g',
(byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n',
(byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u',
(byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z',
(byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5',
(byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'+', (byte)'/'
};
/**
* Translates a Base64 value to either its 6-bit reconstruction value
* or a negative number indicating some other meaning.
**/
private final static byte[] _STANDARD_DECODABET = {
-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8
-5,-5, // Whitespace: Tab and Linefeed
-9,-9, // Decimal 11 - 12
-5, // Whitespace: Carriage Return
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26
-9,-9,-9,-9,-9, // Decimal 27 - 31
-5, // Whitespace: Space
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42
62, // Plus sign at decimal 43
-9,-9,-9, // Decimal 44 - 46
63, // Slash at decimal 47
52,53,54,55,56,57,58,59,60,61, // Numbers zero through nine
-9,-9,-9, // Decimal 58 - 60
-1, // Equals sign at decimal 61
-9,-9,-9, // Decimal 62 - 64
0,1,2,3,4,5,6,7,8,9,10,11,12,13, // Letters 'A' through 'N'
14,15,16,17,18,19,20,21,22,23,24,25, // Letters 'O' through 'Z'
-9,-9,-9,-9,-9,-9, // Decimal 91 - 96
26,27,28,29,30,31,32,33,34,35,36,37,38, // Letters 'a' through 'm'
39,40,41,42,43,44,45,46,47,48,49,50,51, // Letters 'n' through 'z'
-9,-9,-9,-9,-9 // Decimal 123 - 127
,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 128 - 139
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255
};
/* ******** O R D E R E D B A S E 6 4 A L P H A B E T ******** */
/**
* Used in the URL- and Filename-safe dialect described in Section 4 of RFC3548:
* <a href="http://www.faqs.org/rfcs/rfc3548.html">http://www.faqs.org/rfcs/rfc3548.html</a>.
* Notice that the last two bytes become "hyphen" and "underscore" instead of "plus" and "slash."
*/
private final static byte[] _URL_SAFE_ALPHABET = {
(byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G',
(byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N',
(byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U',
(byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z',
(byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g',
(byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n',
(byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u',
(byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z',
(byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5',
(byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'-', (byte)'_'
};
/**
* Used in decoding URL- and Filename-safe dialects of Base64.
*/
private final static byte[] _URL_SAFE_DECODABET = {
-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8
-5,-5, // Whitespace: Tab and Linefeed
-9,-9, // Decimal 11 - 12
-5, // Whitespace: Carriage Return
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26
-9,-9,-9,-9,-9, // Decimal 27 - 31
-5, // Whitespace: Space
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42
-9, // Plus sign at decimal 43
-9, // Decimal 44
62, // Minus sign at decimal 45
-9, // Decimal 46
-9, // Slash at decimal 47
52,53,54,55,56,57,58,59,60,61, // Numbers zero through nine
-9,-9,-9, // Decimal 58 - 60
-1, // Equals sign at decimal 61
-9,-9,-9, // Decimal 62 - 64
0,1,2,3,4,5,6,7,8,9,10,11,12,13, // Letters 'A' through 'N'
14,15,16,17,18,19,20,21,22,23,24,25, // Letters 'O' through 'Z'
-9,-9,-9,-9, // Decimal 91 - 94
63, // Underscore at decimal 95
-9, // Decimal 96
26,27,28,29,30,31,32,33,34,35,36,37,38, // Letters 'a' through 'm'
39,40,41,42,43,44,45,46,47,48,49,50,51, // Letters 'n' through 'z'
-9,-9,-9,-9,-9 // Decimal 123 - 127
,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 128 - 139
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255
};
/* ******** D E T E R M I N E W H I C H A L H A B E T ******** */
/**
* I don't get the point of this technique, but someone requested it,
* and it is described here:
* <a href="http://www.faqs.org/qa/rfcc-1940.html">http://www.faqs.org/qa/rfcc-1940.html</a>.
*/
private final static byte[] _ORDERED_ALPHABET = {
(byte)'-',
(byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4',
(byte)'5', (byte)'6', (byte)'7', (byte)'8', (byte)'9',
(byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G',
(byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N',
(byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U',
(byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z',
(byte)'_',
(byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g',
(byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n',
(byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u',
(byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z'
};
/**
* Used in decoding the "ordered" dialect of Base64.
*/
private final static byte[] _ORDERED_DECODABET = {
-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8
-5,-5, // Whitespace: Tab and Linefeed
-9,-9, // Decimal 11 - 12
-5, // Whitespace: Carriage Return
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26
-9,-9,-9,-9,-9, // Decimal 27 - 31
-5, // Whitespace: Space
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42
-9, // Plus sign at decimal 43
-9, // Decimal 44
0, // Minus sign at decimal 45
-9, // Decimal 46
-9, // Slash at decimal 47
1,2,3,4,5,6,7,8,9,10, // Numbers zero through nine
-9,-9,-9, // Decimal 58 - 60
-1, // Equals sign at decimal 61
-9,-9,-9, // Decimal 62 - 64
11,12,13,14,15,16,17,18,19,20,21,22,23, // Letters 'A' through 'M'
24,25,26,27,28,29,30,31,32,33,34,35,36, // Letters 'N' through 'Z'
-9,-9,-9,-9, // Decimal 91 - 94
37, // Underscore at decimal 95
-9, // Decimal 96
38,39,40,41,42,43,44,45,46,47,48,49,50, // Letters 'a' through 'm'
51,52,53,54,55,56,57,58,59,60,61,62,63, // Letters 'n' through 'z'
-9,-9,-9,-9,-9 // Decimal 123 - 127
,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 128 - 139
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255
};
/**
* Low-level access to decoding ASCII characters in
* the form of a byte array. <strong>Ignores GUNZIP option, if
* it's set.</strong> This is not generally a recommended method,
* although it is used internally as part of the decoding process.
* Special case: if len = 0, an empty array is returned. Still,
* if you need more speed and reduced memory footprint (and aren't
* gzipping), consider this method.
*
* @param source The Base64 encoded data
* @return decoded data
* @since 2.3.1
*/
public static byte[] decode( byte[] source )
throws java.io.IOException {
byte[] decoded = null;
// try {
decoded = decode( source, 0, source.length, Base64.NO_OPTIONS );
// } catch( java.io.IOException ex ) {
// assert false : "IOExceptions only come from GZipping, which is turned off: " + ex.getMessage();
// }
return decoded;
}
/* ******** E N C O D I N G M E T H O D S ******** */
/**
* Low-level access to decoding ASCII characters in
* the form of a byte array. <strong>Ignores GUNZIP option, if
* it's set.</strong> This is not generally a recommended method,
* although it is used internally as part of the decoding process.
* Special case: if len = 0, an empty array is returned. Still,
* if you need more speed and reduced memory footprint (and aren't
* gzipping), consider this method.
*
* @param source The Base64 encoded data
* @param off The offset of where to begin decoding
* @param len The length of characters to decode
* @param options Can specify options such as alphabet type to use
* @return decoded data
* @throws java.io.IOException If bogus characters exist in source data
* @since 1.3
*/
public static byte[] decode( byte[] source, int off, int len, int options )
throws java.io.IOException {
// Lots of error checking and exception throwing
if( source == null ){
throw new NullPointerException( "Cannot decode null source array." );
} // end if
if( off < 0 || off + len > source.length ){
throw new IllegalArgumentException( String.format(
"Source array with length %d cannot have offset of %d and process %d bytes.", source.length, off, len ) );
} // end if
if( len == 0 ){
return new byte[0];
}else if( len < 4 ){
throw new IllegalArgumentException(
"Base64-encoded string must have at least four characters, but length specified was " + len );
} // end if
byte[] DECODABET = getDecodabet( options );
int len34 = len * 3 / 4; // Estimate on array size
byte[] outBuff = new byte[ len34 ]; // Upper limit on size of output
int outBuffPosn = 0; // Keep track of where we're writing
byte[] b4 = new byte[4]; // Four byte buffer from source, eliminating white space
int b4Posn = 0; // Keep track of four byte input buffer
int i = 0; // Source array counter
byte sbiDecode = 0; // Special value from DECODABET
for( i = off; i < off+len; i++ ) { // Loop through source
sbiDecode = DECODABET[ source[i]&0xFF ];
// White space, Equals sign, or legit Base64 character
// Note the values such as -5 and -9 in the
// DECODABETs at the top of the file.
if( sbiDecode >= WHITE_SPACE_ENC ) {
if( sbiDecode >= EQUALS_SIGN_ENC ) {
b4[ b4Posn++ ] = source[i]; // Save non-whitespace
if( b4Posn > 3 ) { // Time to decode?
outBuffPosn += decode4to3( b4, 0, outBuff, outBuffPosn, options );
b4Posn = 0;
// If that was the equals sign, break out of 'for' loop
if( source[i] == EQUALS_SIGN ) {
break;
} // end if: equals sign
} // end if: quartet built
} // end if: equals sign or better
} // end if: white space, equals sign or better
else {
// There's a bad input character in the Base64 stream.
throw new java.io.IOException( String.format(
"Bad Base64 input character decimal %d in array position %d", source[i]&0xFF, i ) );
} // end else:
} // each input character
byte[] out = new byte[ outBuffPosn ];
System.arraycopy( outBuff, 0, out, 0, outBuffPosn );
return out;
} // end decode
/**
* Decodes data from Base64 notation, automatically
* detecting gzip-compressed data and decompressing it.
*
* @param s the string to decode
* @return the decoded data
* @throws java.io.IOException If there is a problem
* @since 1.4
*/
public static byte[] decode( String s ) throws java.io.IOException {
return decode( s, NO_OPTIONS );
}
/**
* Decodes data from Base64 notation, automatically
* detecting gzip-compressed data and decompressing it.
*
* @param s the string to decode
* @param options encode options such as URL_SAFE
* @return the decoded data
* @throws java.io.IOException if there is an error
* @throws NullPointerException if <tt>s</tt> is null
* @since 1.4
*/
public static byte[] decode( String s, int options ) throws java.io.IOException {
if( s == null ){
throw new NullPointerException( "Input string was null." );
} // end if
byte[] bytes;
try {
bytes = s.getBytes( PREFERRED_ENCODING );
} // end try
catch( java.io.UnsupportedEncodingException uee ) {
bytes = s.getBytes();
} // end catch
//</change>
// Decode
bytes = decode( bytes, 0, bytes.length, options );
// Check to see if it's gzip-compressed
// GZIP Magic Two-Byte Number: 0x8b1f (35615)
boolean dontGunzip = (options & DONT_GUNZIP) != 0;
if( (bytes != null) && (bytes.length >= 4) && (!dontGunzip) ) {
int head = (bytes[0] & 0xff) | ((bytes[1] << 8) & 0xff00);
if( java.util.zip.GZIPInputStream.GZIP_MAGIC == head ) {
java.io.ByteArrayInputStream bais = null;
java.util.zip.GZIPInputStream gzis = null;
java.io.ByteArrayOutputStream baos = null;
byte[] buffer = new byte[2048];
int length = 0;
try {
baos = new java.io.ByteArrayOutputStream();
bais = new java.io.ByteArrayInputStream( bytes );
gzis = new java.util.zip.GZIPInputStream( bais );
while( ( length = gzis.read( buffer ) ) >= 0 ) {
baos.write(buffer,0,length);
} // end while: reading input
// No error? Get new bytes.
bytes = baos.toByteArray();
} // end try
catch( java.io.IOException e ) {
e.printStackTrace();
// Just return originally-decoded bytes
} // end catch
finally {
try{ baos.close(); } catch( Exception e ){}
try{ gzis.close(); } catch( Exception e ){}
try{ bais.close(); } catch( Exception e ){}
} // end finally
} // end if: gzipped
} // end if: bytes.length >= 2
return bytes;
} // end decode
/**
* Decodes four bytes from array <var>source</var>
* and writes the resulting bytes (up to three of them)
* to <var>destination</var>.
* The source and destination arrays can be manipulated
* anywhere along their length by specifying
* <var>srcOffset</var> and <var>destOffset</var>.
* This method does not check to make sure your arrays
* are large enough to accomodate <var>srcOffset</var> + 4 for
* the <var>source</var> array or <var>destOffset</var> + 3 for
* the <var>destination</var> array.
* This method returns the actual number of bytes that
* were converted from the Base64 encoding.
* <p>This is the lowest level of the decoding methods with
* all possible parameters.</p>
*
*
* @param source the array to convert
* @param srcOffset the index where conversion begins
* @param destination the array to hold the conversion
* @param destOffset the index where output will be put
* @param options alphabet type is pulled from this (standard, url-safe, ordered)
* @return the number of decoded bytes converted
* @throws NullPointerException if source or destination arrays are null
* @throws IllegalArgumentException if srcOffset or destOffset are invalid
* or there is not enough room in the array.
* @since 1.3
*/
private static int decode4to3(
byte[] source, int srcOffset,
byte[] destination, int destOffset, int options ) {
// Lots of error checking and exception throwing
if( source == null ){
throw new NullPointerException( "Source array was null." );
} // end if
if( destination == null ){
throw new NullPointerException( "Destination array was null." );
} // end if
if( srcOffset < 0 || srcOffset + 3 >= source.length ){
throw new IllegalArgumentException( String.format(
"Source array with length %d cannot have offset of %d and still process four bytes.", source.length, srcOffset ) );
} // end if
if( destOffset < 0 || destOffset +2 >= destination.length ){
throw new IllegalArgumentException( String.format(
"Destination array with length %d cannot have offset of %d and still store three bytes.", destination.length, destOffset ) );
} // end if
byte[] DECODABET = getDecodabet( options );
// Example: Dk==
if( source[ srcOffset + 2] == EQUALS_SIGN ) {
// Two ways to do the same thing. Don't know which way I like best.
//int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
// | ( ( DECODABET[ source[ srcOffset + 1] ] << 24 ) >>> 12 );
int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 )
| ( ( DECODABET[ source[ srcOffset + 1] ] & 0xFF ) << 12 );
destination[ destOffset ] = (byte)( outBuff >>> 16 );
return 1;
}
// Example: DkL=
else if( source[ srcOffset + 3 ] == EQUALS_SIGN ) {
// Two ways to do the same thing. Don't know which way I like best.
//int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
// | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 )
// | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 );
int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 )
| ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 )
| ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6 );
destination[ destOffset ] = (byte)( outBuff >>> 16 );
destination[ destOffset + 1 ] = (byte)( outBuff >>> 8 );
return 2;
}
// Example: DkLE
else {
// Two ways to do the same thing. Don't know which way I like best.
//int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
// | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 )
// | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 )
// | ( ( DECODABET[ source[ srcOffset + 3 ] ] << 24 ) >>> 24 );
int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 )
| ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 )
| ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6)
| ( ( DECODABET[ source[ srcOffset + 3 ] ] & 0xFF ) );
destination[ destOffset ] = (byte)( outBuff >> 16 );
destination[ destOffset + 1 ] = (byte)( outBuff >> 8 );
destination[ destOffset + 2 ] = (byte)( outBuff );
return 3;
}
} // end decodeToBytes
/**
* Reads <tt>infile</tt> and decodes it to <tt>outfile</tt>.
*
* @param infile Input file
* @param outfile Output file
* @throws java.io.IOException if there is an error
* @since 2.2
*/
public static void decodeFileToFile( String infile, String outfile )
throws java.io.IOException {
byte[] decoded = Base64.decodeFromFile( infile );
java.io.OutputStream out = null;
try{
out = new java.io.BufferedOutputStream(
new java.io.FileOutputStream( outfile ) );
out.write( decoded );
} // end try
catch( java.io.IOException e ) {
throw e; // Catch and release to execute finally{}
} // end catch
finally {
try { out.close(); }
catch( Exception ex ){}
} // end finally
} // end decodeFileToFile
/**
* Convenience method for reading a base64-encoded
* file and decoding it.
*
* <p>As of v 2.3, if there is a error,
* the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
* In earlier versions, it just returned false, but
* in retrospect that's a pretty poor way to handle it.</p>
*
* @param filename Filename for reading encoded data
* @return decoded byte array
* @throws java.io.IOException if there is an error
* @since 2.1
*/
public static byte[] decodeFromFile( String filename )
throws java.io.IOException {
byte[] decodedData = null;
Base64.InputStream bis = null;
try
{
// Set up some useful variables
java.io.File file = new java.io.File( filename );
byte[] buffer = null;
int length = 0;
int numBytes = 0;
// Check for size of file
if( file.length() > Integer.MAX_VALUE )
{
throw new java.io.IOException( "File is too big for this convenience method (" + file.length() + " bytes)." );
} // end if: file too big for int index
buffer = new byte[ (int)file.length() ];
// Open a stream
bis = new Base64.InputStream(
new java.io.BufferedInputStream(
new java.io.FileInputStream( file ) ), Base64.DECODE );
// Read until done
while( ( numBytes = bis.read( buffer, length, 4096 ) ) >= 0 ) {
length += numBytes;
} // end while
// Save in a variable to return
decodedData = new byte[ length ];
System.arraycopy( buffer, 0, decodedData, 0, length );
} // end try
catch( java.io.IOException e ) {
throw e; // Catch and release to execute finally{}
} // end catch: java.io.IOException
finally {
try{ bis.close(); } catch( Exception e) {}
} // end finally
return decodedData;
} // end decodeFromFile
/**
* Convenience method for decoding data to a file.
*
* <p>As of v 2.3, if there is a error,
* the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
* In earlier versions, it just returned false, but
* in retrospect that's a pretty poor way to handle it.</p>
*
* @param dataToDecode Base64-encoded data as a string
* @param filename Filename for saving decoded data
* @throws java.io.IOException if there is an error
* @since 2.1
*/
public static void decodeToFile( String dataToDecode, String filename )
throws java.io.IOException {
Base64.OutputStream bos = null;
try{
bos = new Base64.OutputStream(
new java.io.FileOutputStream( filename ), Base64.DECODE );
bos.write( dataToDecode.getBytes( PREFERRED_ENCODING ) );
} // end try
catch( java.io.IOException e ) {
throw e; // Catch and throw to execute finally{} block
} // end catch: java.io.IOException
finally {
try{ bos.close(); } catch( Exception e ){}
} // end finally
} // end decodeToFile
/**
* Attempts to decode Base64 data and deserialize a Java
* Object within. Returns <tt>null</tt> if there was an error.
*
* @param encodedObject The Base64 data to decode
* @return The decoded and deserialized object
* @throws NullPointerException if encodedObject is null
* @throws java.io.IOException if there is a general error
* @throws ClassNotFoundException if the decoded object is of a
* class that cannot be found by the JVM
* @since 1.5
*/
public static Object decodeToObject( String encodedObject )
throws java.io.IOException, java.lang.ClassNotFoundException {
return decodeToObject(encodedObject,NO_OPTIONS,null);
}
/**
* Attempts to decode Base64 data and deserialize a Java
* Object within. Returns <tt>null</tt> if there was an error.
* If <tt>loader</tt> is not null, it will be the class loader
* used when deserializing.
*
* @param encodedObject The Base64 data to decode
* @param options Various parameters related to decoding
* @param loader Optional class loader to use in deserializing classes.
* @return The decoded and deserialized object
* @throws NullPointerException if encodedObject is null
* @throws java.io.IOException if there is a general error
* @throws ClassNotFoundException if the decoded object is of a
* class that cannot be found by the JVM
* @since 2.3.4
*/
public static Object decodeToObject(
String encodedObject, int options, final ClassLoader loader )
throws java.io.IOException, java.lang.ClassNotFoundException {
// Decode and gunzip if necessary
byte[] objBytes = decode( encodedObject, options );
java.io.ByteArrayInputStream bais = null;
java.io.ObjectInputStream ois = null;
Object obj = null;
try {
bais = new java.io.ByteArrayInputStream( objBytes );
// If no custom class loader is provided, use Java's builtin OIS.
if( loader == null ){
ois = new java.io.ObjectInputStream( bais );
} // end if: no loader provided
// Else make a customized object input stream that uses
// the provided class loader.
else {
ois = new java.io.ObjectInputStream(bais){
@Override
public Class<?> resolveClass(java.io.ObjectStreamClass streamClass)
throws java.io.IOException, ClassNotFoundException {
Class c = Class.forName(streamClass.getName(), false, loader);
if( c == null ){
return super.resolveClass(streamClass);
} else {
return c; // Class loader knows of this class.
} // end else: not null
} // end resolveClass
}; // end ois
} // end else: no custom class loader
obj = ois.readObject();
} // end try
catch( java.io.IOException e ) {
throw e; // Catch and throw in order to execute finally{}
} // end catch
catch( java.lang.ClassNotFoundException e ) {
throw e; // Catch and throw in order to execute finally{}
} // end catch
finally {
try{ bais.close(); } catch( Exception e ){}
try{ ois.close(); } catch( Exception e ){}
} // end finally
return obj;
} // end decodeObject
/**
* Performs Base64 encoding on the <code>raw</code> ByteBuffer,
* writing it to the <code>encoded</code> ByteBuffer.
* This is an experimental feature. Currently it does not
* pass along any options (such as {@link #DO_BREAK_LINES}
* or {@link #GZIP}.
*
* @param raw input buffer
* @param encoded output buffer
* @since 2.3
*/
public static void encode( java.nio.ByteBuffer raw, java.nio.ByteBuffer encoded ){
byte[] raw3 = new byte[3];
byte[] enc4 = new byte[4];
while( raw.hasRemaining() ){
int rem = Math.min(3,raw.remaining());
raw.get(raw3,0,rem);
Base64.encode3to4(enc4, raw3, rem, Base64.NO_OPTIONS );
encoded.put(enc4);
} // end input remaining
}
/**
* Performs Base64 encoding on the <code>raw</code> ByteBuffer,
* writing it to the <code>encoded</code> CharBuffer.
* This is an experimental feature. Currently it does not
* pass along any options (such as {@link #DO_BREAK_LINES}
* or {@link #GZIP}.
*
* @param raw input buffer
* @param encoded output buffer
* @since 2.3
*/
public static void encode( java.nio.ByteBuffer raw, java.nio.CharBuffer encoded ){
byte[] raw3 = new byte[3];
byte[] enc4 = new byte[4];
while( raw.hasRemaining() ){
int rem = Math.min(3,raw.remaining());
raw.get(raw3,0,rem);
Base64.encode3to4(enc4, raw3, rem, Base64.NO_OPTIONS );
for( int i = 0; i < 4; i++ ){
encoded.put( (char)(enc4[i] & 0xFF) );
}
} // end input remaining
}
/**
* Encodes up to the first three bytes of array <var>threeBytes</var>
* and returns a four-byte array in Base64 notation.
* The actual number of significant bytes in your array is
* given by <var>numSigBytes</var>.
* The array <var>threeBytes</var> needs only be as big as
* <var>numSigBytes</var>.
* Code can reuse a byte array by passing a four-byte array as <var>b4</var>.
*
* @param b4 A reusable byte array to reduce array instantiation
* @param threeBytes the array to convert
* @param numSigBytes the number of significant bytes in your array
* @return four byte array in Base64 notation.
* @since 1.5.1
*/
private static byte[] encode3to4( byte[] b4, byte[] threeBytes, int numSigBytes, int options ) {
encode3to4( threeBytes, 0, numSigBytes, b4, 0, options );
return b4;
} // end encode3to4
/* ******** D E C O D I N G M E T H O D S ******** */
/**
* <p>Encodes up to three bytes of the array <var>source</var>
* and writes the resulting four Base64 bytes to <var>destination</var>.
* The source and destination arrays can be manipulated
* anywhere along their length by specifying
* <var>srcOffset</var> and <var>destOffset</var>.
* This method does not check to make sure your arrays
* are large enough to accomodate <var>srcOffset</var> + 3 for
* the <var>source</var> array or <var>destOffset</var> + 4 for
* the <var>destination</var> array.
* The actual number of significant bytes in your array is
* given by <var>numSigBytes</var>.</p>
* <p>This is the lowest level of the encoding methods with
* all possible parameters.</p>
*
* @param source the array to convert
* @param srcOffset the index where conversion begins
* @param numSigBytes the number of significant bytes in your array
* @param destination the array to hold the conversion
* @param destOffset the index where output will be put
* @return the <var>destination</var> array
* @since 1.3
*/
private static byte[] encode3to4(
byte[] source, int srcOffset, int numSigBytes,
byte[] destination, int destOffset, int options ) {
byte[] ALPHABET = getAlphabet( options );
// 1 2 3
// 01234567890123456789012345678901 Bit position
// --------000000001111111122222222 Array position from threeBytes
// --------| || || || | Six bit groups to index ALPHABET
// >>18 >>12 >> 6 >> 0 Right shift necessary
// 0x3f 0x3f 0x3f Additional AND
// Create buffer with zero-padding if there are only one or two
// significant bytes passed in the array.
// We have to shift left 24 in order to flush out the 1's that appear
// when Java treats a value as negative that is cast from a byte to an int.
int inBuff = ( numSigBytes > 0 ? ((source[ srcOffset ] << 24) >>> 8) : 0 )
| ( numSigBytes > 1 ? ((source[ srcOffset + 1 ] << 24) >>> 16) : 0 )
| ( numSigBytes > 2 ? ((source[ srcOffset + 2 ] << 24) >>> 24) : 0 );
switch( numSigBytes )
{
case 3:
destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ];
destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ];
destination[ destOffset + 2 ] = ALPHABET[ (inBuff >>> 6) & 0x3f ];
destination[ destOffset + 3 ] = ALPHABET[ (inBuff ) & 0x3f ];
return destination;
case 2:
destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ];
destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ];
destination[ destOffset + 2 ] = ALPHABET[ (inBuff >>> 6) & 0x3f ];
destination[ destOffset + 3 ] = EQUALS_SIGN;
return destination;
case 1:
destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ];
destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ];
destination[ destOffset + 2 ] = EQUALS_SIGN;
destination[ destOffset + 3 ] = EQUALS_SIGN;
return destination;
default:
return destination;
} // end switch
} // end encode3to4
/**
* Encodes a byte array into Base64 notation.
* Does not GZip-compress data.
*
* @param source The data to convert
* @return The data in Base64-encoded form
* @throws NullPointerException if source array is null
* @since 1.4
*/
public static String encodeBytes( byte[] source ) {
// Since we're not going to have the GZIP encoding turned on,
// we're not going to have an java.io.IOException thrown, so
// we should not force the user to have to catch it.
String encoded = null;
try {
encoded = encodeBytes(source, 0, source.length, NO_OPTIONS);
} catch (java.io.IOException ex) {
assert false : ex.getMessage();
} // end catch
assert encoded != null;
return encoded;
} // end encodeBytes
/**
* Encodes a byte array into Base64 notation.
* <p>
* Example options:<pre>
* GZIP: gzip-compresses object before encoding it.
* DO_BREAK_LINES: break lines at 76 characters
* <i>Note: Technically, this makes your encoding non-compliant.</i>
* </pre>
* <p>
* Example: <code>encodeBytes( myData, Base64.GZIP )</code> or
* <p>
* Example: <code>encodeBytes( myData, Base64.GZIP | Base64.DO_BREAK_LINES )</code>
*
*
* <p>As of v 2.3, if there is an error with the GZIP stream,
* the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
* In earlier versions, it just returned a null value, but
* in retrospect that's a pretty poor way to handle it.</p>
*
*
* @param source The data to convert
* @param options Specified options
* @return The Base64-encoded data as a String
* @see Base64#GZIP
* @see Base64#DO_BREAK_LINES
* @throws java.io.IOException if there is an error
* @throws NullPointerException if source array is null
* @since 2.0
*/
public static String encodeBytes( byte[] source, int options ) throws java.io.IOException {
return encodeBytes( source, 0, source.length, options );
} // end encodeBytes
/**
* Encodes a byte array into Base64 notation.
* Does not GZip-compress data.
*
* <p>As of v 2.3, if there is an error,
* the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
* In earlier versions, it just returned a null value, but
* in retrospect that's a pretty poor way to handle it.</p>
*
*
* @param source The data to convert
* @param off Offset in array where conversion should begin
* @param len Length of data to convert
* @return The Base64-encoded data as a String
* @throws NullPointerException if source array is null
* @throws IllegalArgumentException if source array, offset, or length are invalid
* @since 1.4
*/
public static String encodeBytes( byte[] source, int off, int len ) {
// Since we're not going to have the GZIP encoding turned on,
// we're not going to have an java.io.IOException thrown, so
// we should not force the user to have to catch it.
String encoded = null;
try {
encoded = encodeBytes( source, off, len, NO_OPTIONS );
} catch (java.io.IOException ex) {
assert false : ex.getMessage();
} // end catch
assert encoded != null;
return encoded;
} // end encodeBytes
/**
* Encodes a byte array into Base64 notation.
* <p>
* Example options:<pre>
* GZIP: gzip-compresses object before encoding it.
* DO_BREAK_LINES: break lines at 76 characters
* <i>Note: Technically, this makes your encoding non-compliant.</i>
* </pre>
* <p>
* Example: <code>encodeBytes( myData, Base64.GZIP )</code> or
* <p>
* Example: <code>encodeBytes( myData, Base64.GZIP | Base64.DO_BREAK_LINES )</code>
*
*
* <p>As of v 2.3, if there is an error with the GZIP stream,
* the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
* In earlier versions, it just returned a null value, but
* in retrospect that's a pretty poor way to handle it.</p>
*
*
* @param source The data to convert
* @param off Offset in array where conversion should begin
* @param len Length of data to convert
* @param options Specified options
* @return The Base64-encoded data as a String
* @see Base64#GZIP
* @see Base64#DO_BREAK_LINES
* @throws java.io.IOException if there is an error
* @throws NullPointerException if source array is null
* @throws IllegalArgumentException if source array, offset, or length are invalid
* @since 2.0
*/
public static String encodeBytes( byte[] source, int off, int len, int options ) throws java.io.IOException {
byte[] encoded = encodeBytesToBytes( source, off, len, options );
// Return value according to relevant encoding.
try {
return new String( encoded, PREFERRED_ENCODING );
} // end try
catch (java.io.UnsupportedEncodingException uue) {
return new String( encoded );
} // end catch
} // end encodeBytes
/**
* Similar to {@link #encodeBytes(byte[])} but returns
* a byte array instead of instantiating a String. This is more efficient
* if you're working with I/O streams and have large data sets to encode.
*
*
* @param source The data to convert
* @return The Base64-encoded data as a byte[] (of ASCII characters)
* @throws NullPointerException if source array is null
* @since 2.3.1
*/
public static byte[] encodeBytesToBytes( byte[] source ) {
byte[] encoded = null;
try {
encoded = encodeBytesToBytes( source, 0, source.length, Base64.NO_OPTIONS );
} catch( java.io.IOException ex ) {
assert false : "IOExceptions only come from GZipping, which is turned off: " + ex.getMessage();
}
return encoded;
}
/**
* Similar to {@link #encodeBytes(byte[], int, int, int)} but returns
* a byte array instead of instantiating a String. This is more efficient
* if you're working with I/O streams and have large data sets to encode.
*
*
* @param source The data to convert
* @param off Offset in array where conversion should begin
* @param len Length of data to convert
* @param options Specified options
* @return The Base64-encoded data as a String
* @see Base64#GZIP
* @see Base64#DO_BREAK_LINES
* @throws java.io.IOException if there is an error
* @throws NullPointerException if source array is null
* @throws IllegalArgumentException if source array, offset, or length are invalid
* @since 2.3.1
*/
public static byte[] encodeBytesToBytes( byte[] source, int off, int len, int options ) throws java.io.IOException {
if( source == null ){
throw new NullPointerException( "Cannot serialize a null array." );
} // end if: null
if( off < 0 ){
throw new IllegalArgumentException( "Cannot have negative offset: " + off );
} // end if: off < 0
if( len < 0 ){
throw new IllegalArgumentException( "Cannot have length offset: " + len );
} // end if: len < 0
if( off + len > source.length ){
throw new IllegalArgumentException(
String.format( "Cannot have offset of %d and length of %d with array of length %d", off,len,source.length));
} // end if: off < 0
// Compress?
if( (options & GZIP) != 0 ) {
java.io.ByteArrayOutputStream baos = null;
java.util.zip.GZIPOutputStream gzos = null;
Base64.OutputStream b64os = null;
try {
// GZip -> Base64 -> ByteArray
baos = new java.io.ByteArrayOutputStream();
b64os = new Base64.OutputStream( baos, ENCODE | options );
gzos = new java.util.zip.GZIPOutputStream( b64os );
gzos.write( source, off, len );
gzos.close();
} // end try
catch( java.io.IOException e ) {
// Catch it and then throw it immediately so that
// the finally{} block is called for cleanup.
throw e;
} // end catch
finally {
try{ gzos.close(); } catch( Exception e ){}
try{ b64os.close(); } catch( Exception e ){}
try{ baos.close(); } catch( Exception e ){}
} // end finally
return baos.toByteArray();
} // end if: compress
// Else, don't compress. Better not to use streams at all then.
else {
boolean breakLines = (options & DO_BREAK_LINES) != 0;
//int len43 = len * 4 / 3;
//byte[] outBuff = new byte[ ( len43 ) // Main 4:3
// + ( (len % 3) > 0 ? 4 : 0 ) // Account for padding
// + (breakLines ? ( len43 / MAX_LINE_LENGTH ) : 0) ]; // New lines
// Try to determine more precisely how big the array needs to be.
// If we get it right, we don't have to do an array copy, and
// we save a bunch of memory.
int encLen = ( len / 3 ) * 4 + ( len % 3 > 0 ? 4 : 0 ); // Bytes needed for actual encoding
if( breakLines ){
encLen += encLen / MAX_LINE_LENGTH; // Plus extra newline characters
}
byte[] outBuff = new byte[ encLen ];
int d = 0;
int e = 0;
int len2 = len - 2;
int lineLength = 0;
for( ; d < len2; d+=3, e+=4 ) {
encode3to4( source, d+off, 3, outBuff, e, options );
lineLength += 4;
if( breakLines && lineLength >= MAX_LINE_LENGTH )
{
outBuff[e+4] = NEW_LINE;
e++;
lineLength = 0;
} // end if: end of line
} // en dfor: each piece of array
if( d < len ) {
encode3to4( source, d+off, len - d, outBuff, e, options );
e += 4;
} // end if: some padding needed
// Only resize array if we didn't guess it right.
if( e <= outBuff.length - 1 ){
// If breaking lines and the last byte falls right at
// the line length (76 bytes per line), there will be
// one extra byte, and the array will need to be resized.
// Not too bad of an estimate on array size, I'd say.
byte[] finalOut = new byte[e];
System.arraycopy(outBuff,0, finalOut,0,e);
//System.err.println("Having to resize array from " + outBuff.length + " to " + e );
return finalOut;
} else {
//System.err.println("No need to resize array.");
return outBuff;
}
} // end else: don't compress
} // end encodeBytesToBytes
/**
* Reads <tt>infile</tt> and encodes it to <tt>outfile</tt>.
*
* @param infile Input file
* @param outfile Output file
* @throws java.io.IOException if there is an error
* @since 2.2
*/
public static void encodeFileToFile( String infile, String outfile )
throws java.io.IOException {
String encoded = Base64.encodeFromFile( infile );
java.io.OutputStream out = null;
try{
out = new java.io.BufferedOutputStream(
new java.io.FileOutputStream( outfile ) );
out.write( encoded.getBytes("US-ASCII") ); // Strict, 7-bit output.
} // end try
catch( java.io.IOException e ) {
throw e; // Catch and release to execute finally{}
} // end catch
finally {
try { out.close(); }
catch( Exception ex ){}
} // end finally
} // end encodeFileToFile
/**
* Convenience method for reading a binary file
* and base64-encoding it.
*
* <p>As of v 2.3, if there is a error,
* the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
* In earlier versions, it just returned false, but
* in retrospect that's a pretty poor way to handle it.</p>
*
* @param filename Filename for reading binary data
* @return base64-encoded string
* @throws java.io.IOException if there is an error
* @since 2.1
*/
public static String encodeFromFile( String filename )
throws java.io.IOException {
String encodedData = null;
Base64.InputStream bis = null;
try
{
// Set up some useful variables
java.io.File file = new java.io.File( filename );
byte[] buffer = new byte[ Math.max((int)(file.length() * 1.4+1),40) ]; // Need max() for math on small files (v2.2.1); Need +1 for a few corner cases (v2.3.5)
int length = 0;
int numBytes = 0;
// Open a stream
bis = new Base64.InputStream(
new java.io.BufferedInputStream(
new java.io.FileInputStream( file ) ), Base64.ENCODE );
// Read until done
while( ( numBytes = bis.read( buffer, length, 4096 ) ) >= 0 ) {
length += numBytes;
} // end while
// Save in a variable to return
encodedData = new String( buffer, 0, length, Base64.PREFERRED_ENCODING );
} // end try
catch( java.io.IOException e ) {
throw e; // Catch and release to execute finally{}
} // end catch: java.io.IOException
finally {
try{ bis.close(); } catch( Exception e) {}
} // end finally
return encodedData;
} // end encodeFromFile
/**
* Serializes an object and returns the Base64-encoded
* version of that serialized object.
*
* <p>As of v 2.3, if the object
* cannot be serialized or there is another error,
* the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
* In earlier versions, it just returned a null value, but
* in retrospect that's a pretty poor way to handle it.</p>
*
* The object is not GZip-compressed before being encoded.
*
* @param serializableObject The object to encode
* @return The Base64-encoded object
* @throws java.io.IOException if there is an error
* @throws NullPointerException if serializedObject is null
* @since 1.4
*/
public static String encodeObject( java.io.Serializable serializableObject )
throws java.io.IOException {
return encodeObject( serializableObject, NO_OPTIONS );
} // end encodeObject
/**
* Serializes an object and returns the Base64-encoded
* version of that serialized object.
*
* <p>As of v 2.3, if the object
* cannot be serialized or there is another error,
* the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
* In earlier versions, it just returned a null value, but
* in retrospect that's a pretty poor way to handle it.</p>
*
* The object is not GZip-compressed before being encoded.
* <p>
* Example options:<pre>
* GZIP: gzip-compresses object before encoding it.
* DO_BREAK_LINES: break lines at 76 characters
* </pre>
* <p>
* Example: <code>encodeObject( myObj, Base64.GZIP )</code> or
* <p>
* Example: <code>encodeObject( myObj, Base64.GZIP | Base64.DO_BREAK_LINES )</code>
*
* @param serializableObject The object to encode
* @param options Specified options
* @return The Base64-encoded object
* @see Base64#GZIP
* @see Base64#DO_BREAK_LINES
* @throws java.io.IOException if there is an error
* @since 2.0
*/
public static String encodeObject( java.io.Serializable serializableObject, int options )
throws java.io.IOException {
if( serializableObject == null ){
throw new NullPointerException( "Cannot serialize a null object." );
} // end if: null
// Streams
java.io.ByteArrayOutputStream baos = null;
java.io.OutputStream b64os = null;
java.util.zip.GZIPOutputStream gzos = null;
java.io.ObjectOutputStream oos = null;
try {
// ObjectOutputStream -> (GZIP) -> Base64 -> ByteArrayOutputStream
baos = new java.io.ByteArrayOutputStream();
b64os = new Base64.OutputStream( baos, ENCODE | options );
if( (options & GZIP) != 0 ){
// Gzip
gzos = new java.util.zip.GZIPOutputStream(b64os);
oos = new java.io.ObjectOutputStream( gzos );
} else {
// Not gzipped
oos = new java.io.ObjectOutputStream( b64os );
}
oos.writeObject( serializableObject );
} // end try
catch( java.io.IOException e ) {
// Catch it and then throw it immediately so that
// the finally{} block is called for cleanup.
throw e;
} // end catch
finally {
try{ oos.close(); } catch( Exception e ){}
try{ gzos.close(); } catch( Exception e ){}
try{ b64os.close(); } catch( Exception e ){}
try{ baos.close(); } catch( Exception e ){}
} // end finally
// Return value according to relevant encoding.
try {
return new String( baos.toByteArray(), PREFERRED_ENCODING );
} // end try
catch (java.io.UnsupportedEncodingException uue){
// Fall back to some Java default
return new String( baos.toByteArray() );
} // end catch
} // end encode
/**
* Convenience method for encoding data to a file.
*
* <p>As of v 2.3, if there is a error,
* the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
* In earlier versions, it just returned false, but
* in retrospect that's a pretty poor way to handle it.</p>
*
* @param dataToEncode byte array of data to encode in base64 form
* @param filename Filename for saving encoded data
* @throws java.io.IOException if there is an error
* @throws NullPointerException if dataToEncode is null
* @since 2.1
*/
public static void encodeToFile( byte[] dataToEncode, String filename )
throws java.io.IOException {
if( dataToEncode == null ){
throw new NullPointerException( "Data to encode was null." );
} // end iff
Base64.OutputStream bos = null;
try {
bos = new Base64.OutputStream(
new java.io.FileOutputStream( filename ), Base64.ENCODE );
bos.write( dataToEncode );
} // end try
catch( java.io.IOException e ) {
throw e; // Catch and throw to execute finally{} block
} // end catch: java.io.IOException
finally {
try{ bos.close(); } catch( Exception e ){}
} // end finally
} // end encodeToFile
/**
* Returns one of the _SOMETHING_ALPHABET byte arrays depending on
* the options specified.
* It's possible, though silly, to specify ORDERED <b>and</b> URLSAFE
* in which case one of them will be picked, though there is
* no guarantee as to which one will be picked.
*/
private final static byte[] getAlphabet( int options ) {
if ((options & URL_SAFE) == URL_SAFE) {
return _URL_SAFE_ALPHABET;
} else if ((options & ORDERED) == ORDERED) {
return _ORDERED_ALPHABET;
} else {
return _STANDARD_ALPHABET;
}
} // end getAlphabet
/* ******** I N N E R C L A S S I N P U T S T R E A M ******** */
/**
* Returns one of the _SOMETHING_DECODABET byte arrays depending on
* the options specified.
* It's possible, though silly, to specify ORDERED and URL_SAFE
* in which case one of them will be picked, though there is
* no guarantee as to which one will be picked.
*/
private final static byte[] getDecodabet( int options ) {
if( (options & URL_SAFE) == URL_SAFE) {
return _URL_SAFE_DECODABET;
} else if ((options & ORDERED) == ORDERED) {
return _ORDERED_DECODABET;
} else {
return _STANDARD_DECODABET;
}
} // end getAlphabet
/* ******** I N N E R C L A S S O U T P U T S T R E A M ******** */
/** Defeats instantiation. */
private Base64(){}
} // end class Base64
| Java |
package org.sshtunnel.utils;
import org.sshtunnel.R;
import org.sshtunnel.SSHTunnel;
import org.sshtunnel.SSHTunnelContext;
import org.sshtunnel.SSHTunnelService;
import org.sshtunnel.db.Profile;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.drawable.Drawable;
import android.util.Log;
public class Utils {
public static final String SERVICE_NAME = "org.sshtunnel.SSHTunnelService";
public static final String TAG = "SSHTunnelUtils";
public static String getProfileName(Profile profile) {
if (profile.getName() == null || profile.getName().equals("")) {
return SSHTunnelContext.getAppContext().getString(R.string.profile_base) + " "
+ profile.getId();
}
return profile.getName();
}
public static Drawable getAppIcon(Context c, int uid) {
PackageManager pm = c.getPackageManager();
Drawable appIcon = c.getResources().getDrawable(R.drawable.sym_def_app_icon);
String[] packages = pm.getPackagesForUid(uid);
if (packages != null) {
if (packages.length == 1) {
try {
ApplicationInfo appInfo = pm.getApplicationInfo(packages[0], 0);
appIcon = pm.getApplicationIcon(appInfo);
} catch (NameNotFoundException e) {
Log.e(TAG, "No package found matching with the uid " + uid);
}
}
} else {
Log.e(TAG, "Package not found for uid " + uid);
}
return appIcon;
}
public static boolean isWorked() {
return SSHTunnelService.isServiceStarted();
}
public static void notifyConnect() {
Context context = SSHTunnelContext.getAppContext();
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification();
Intent intent = new Intent(context, SSHTunnel.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendIntent = PendingIntent.getActivity(context, 0,
intent, 0);
notification.icon = R.drawable.ic_stat;
notification.tickerText = context.getString(R.string.auto_connecting);
notification.flags = Notification.FLAG_ONGOING_EVENT;
notification.setLatestEventInfo(context,
context.getString(R.string.app_name),
context.getString(R.string.auto_connecting), pendIntent);
notificationManager.notify(1, notification);
}
} | Java |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sshtunnel.utils;
import java.io.Serializable;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* <b>Regular Expression</b> validation (using JDK 1.4+ regex support).
* <p>
* Construct the validator either for a single regular expression or a set (array) of
* regular expressions. By default validation is <i>case sensitive</i> but constructors
* are provided to allow <i>case in-sensitive</i> validation. For example to create
* a validator which does <i>case in-sensitive</i> validation for a set of regular
* expressions:
* <pre>
* String[] regexs = new String[] {...};
* RegexValidator validator = new RegexValidator(regexs, false);
* </pre>
* <p>
* <ul>
* <li>Validate <code>true</code> or <code>false</code>:</li>
* <ul>
* <li><code>boolean valid = validator.isValid(value);</code></li>
* </ul>
* <li>Validate returning an aggregated String of the matched groups:</li>
* <ul>
* <li><code>String result = validator.validate(value);</code></li>
* </ul>
* <li>Validate returning the matched groups:</li>
* <ul>
* <li><code>String[] result = validator.match(value);</code></li>
* </ul>
* </ul>
* <p>
* Cached instances pre-compile and re-use {@link Pattern}(s) - which according
* to the {@link Pattern} API are safe to use in a multi-threaded environment.
*
* @version $Revision$ $Date$
* @since Validator 1.4
*/
public class RegexValidator implements Serializable {
private final Pattern[] patterns;
/**
* Construct a <i>case sensitive</i> validator for a single
* regular expression.
*
* @param regex The regular expression this validator will
* validate against
*/
public RegexValidator(String regex) {
this(regex, true);
}
/**
* Construct a validator for a single regular expression
* with the specified case sensitivity.
*
* @param regex The regular expression this validator will
* validate against
* @param caseSensitive when <code>true</code> matching is <i>case
* sensitive</i>, otherwise matching is <i>case in-sensitive</i>
*/
public RegexValidator(String regex, boolean caseSensitive) {
this(new String[] {regex}, caseSensitive);
}
/**
* Construct a <i>case sensitive</i> validator that matches any one
* of the set of regular expressions.
*
* @param regexs The set of regular expressions this validator will
* validate against
*/
public RegexValidator(String[] regexs) {
this(regexs, true);
}
/**
* Construct a validator that matches any one of the set of regular
* expressions with the specified case sensitivity.
*
* @param regexs The set of regular expressions this validator will
* validate against
* @param caseSensitive when <code>true</code> matching is <i>case
* sensitive</i>, otherwise matching is <i>case in-sensitive</i>
*/
public RegexValidator(String[] regexs, boolean caseSensitive) {
if (regexs == null || regexs.length == 0) {
throw new IllegalArgumentException("Regular expressions are missing");
}
patterns = new Pattern[regexs.length];
int flags = (caseSensitive ? 0: Pattern.CASE_INSENSITIVE);
for (int i = 0; i < regexs.length; i++) {
if (regexs[i] == null || regexs[i].length() == 0) {
throw new IllegalArgumentException("Regular expression[" + i + "] is missing");
}
patterns[i] = Pattern.compile(regexs[i], flags);
}
}
/**
* Validate a value against the set of regular expressions.
*
* @param value The value to validate.
* @return <code>true</code> if the value is valid
* otherwise <code>false</code>.
*/
public boolean isValid(String value) {
if (value == null) {
return false;
}
for (int i = 0; i < patterns.length; i++) {
if (patterns[i].matcher(value).matches()) {
return true;
}
}
return false;
}
/**
* Validate a value against the set of regular expressions
* returning the array of matched groups.
*
* @param value The value to validate.
* @return String array of the <i>groups</i> matched if
* valid or <code>null</code> if invalid
*/
public String[] match(String value) {
if (value == null) {
return null;
}
for (int i = 0; i < patterns.length; i++) {
Matcher matcher = patterns[i].matcher(value);
if (matcher.matches()) {
int count = matcher.groupCount();
String[] groups = new String[count];
for (int j = 0; j < count; j++) {
groups[j] = matcher.group(j+1);
}
return groups;
}
}
return null;
}
/**
* Provide a String representation of this validator.
* @return A String representation of this validator
*/
@Override
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append("RegexValidator{");
for (int i = 0; i < patterns.length; i++) {
if (i > 0) {
buffer.append(",");
}
buffer.append(patterns[i].pattern());
}
buffer.append("}");
return buffer.toString();
}
/**
* Validate a value against the set of regular expressions
* returning a String value of the aggregated groups.
*
* @param value The value to validate.
* @return Aggregated String value comprised of the
* <i>groups</i> matched if valid or <code>null</code> if invalid
*/
public String validate(String value) {
if (value == null) {
return null;
}
for (int i = 0; i < patterns.length; i++) {
Matcher matcher = patterns[i].matcher(value);
if (matcher.matches()) {
int count = matcher.groupCount();
if (count == 1) {
return matcher.group(1);
}
StringBuffer buffer = new StringBuffer();
for (int j = 0; j < count; j++) {
String component = matcher.group(j+1);
if (component != null) {
buffer.append(component);
}
}
return buffer.toString();
}
}
return null;
}
} | Java |
package org.sshtunnel.utils;
import java.io.IOException;
import java.net.Socket;
import android.util.Log;
public class InnerSocketBuilder {
private String proxyHost = "127.0.0.1";
private int proxyPort = 1053;
private Socket innerSocket = null;
private boolean isConnected = false;
private final String TAG = "CMWRAP->InnerSocketBuilder";
/**
* 建立经由代理服务器至目标服务器的连接
*
* @param proxyHost
* 代理服务器地址
* @param proxyPort
* 代理服务器端口
* @param target
* 目标服务器
*/
public InnerSocketBuilder(String proxyHost, int proxyPort, String target) {
this.proxyHost = proxyHost;
this.proxyPort = proxyPort;
connect();
}
private void connect() {
// starTime = System.currentTimeMillis();
Log.v(TAG, "建立通道");
try {
innerSocket = new Socket(proxyHost, proxyPort);
// innerSocket.setKeepAlive(true);
innerSocket.setTcpNoDelay(true);
innerSocket.setSoTimeout(60 * 1000);
isConnected = true;
} catch (IOException e) {
Log.e(TAG, "建立隧道失败:" + e.getLocalizedMessage());
}
}
public Socket getSocket() {
return innerSocket;
}
public boolean isConnected() {
return this.isConnected;
}
}
| Java |
package org.sshtunnel.utils;
public class Constraints {
public static final String ID = "profile_id";
public static final String NAME = "name";
public static final String USER = "user";
public static final String PASSWORD = "password";
public static final String HOST = "host";
public static final String SSID = "ssid";
public static final String REMOTE_ADDRESS = "remoteAddress";
public static final String KEY_PATH = "keyPath";
public static final String PROXYED_APPS = "proxyedApps";
public static final String UPSTREAM_PROXY = "upstreamProxy";
public static final String IS_AUTO_RECONNECT = "isAutoReconnect";
public static final String IS_AUTO_CONNECT = "isAutoConnect";
public static final String IS_AUTO_SETPROXY = "isAutoSetProxy";
public static final String IS_GFW_LIST = "isGFWList";
public static final String IS_SOCKS = "isSocks";
public static final String IS_DNS_PROXY = "isDNSProxy";
public static final String IS_ACTIVE = "isActive";
public static final String IS_UPSTREAM_PROXY = "isUpstreamProxy";
public static final String PORT = "port";
public static final String REMOTE_PORT = "remotePort";
public static final String LOCAL_PORT = "localPort";
public static final String DEFAULT_KEY_PATH = "/sdcard/sshtunnel/key";
public static final String DEFAULT_REMOTE_ADDRESS = "127.0.0.1";
public static final String ONLY_3G = "3G";
public static final String ONLY_WIFI = "WIFI";
public static final String WIFI_AND_3G = "WIFI/3G";
public static final String FINGER_PRINT_STATUS = "fingerPrintStatus";
public static final String FINGER_PRINT_TYPE = "fingerPrintType";
public static final String FINGER_PRINT = "fingerPrint";
public static final int FINGER_PRINT_INIITIALIZE = 1;
public static final int FINGER_PRINT_CHANGED = 2;
public static final int FINGER_PRINT_ACCEPT = 3;
public static final int FINGER_PRINT_DENY = 4;
public static final String FINGER_PRINT_ACTION_ACCEPT = "org.sshtunnel.fingerprint.ACCEPT";
public static final String FINGER_PRINT_ACTION_DENY = "org.sshtunnel.fingerprint.DENY";
public static final String FINGER_PRINT_ACTION = "org.sshtunnel.fingerprint.ACTION";
}
| Java |
package org.sshtunnel;
import java.io.IOException;
public interface WrapServer extends Runnable {
public abstract void close() throws IOException;
public abstract int getServPort();
public abstract boolean isClosed();
public abstract void setProxyHost(String host);
public abstract void setProxyPort(int port);
/**
* 设置此服务的目的地址
*
* @param target
*/
public abstract void setTarget(String target);
}
| Java |
/* sshtunnel - SSH Tunnel App for Android
* Copyright (C) 2011 Max Lv <max.c.lv@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* ___====-_ _-====___
* _--^^^#####// \\#####^^^--_
* _-^##########// ( ) \\##########^-_
* -############// |\^^/| \\############-
* _/############// (@::@) \\############\_
* /#############(( \\// ))#############\
* -###############\\ (oo) //###############-
* -#################\\ / VV \ //#################-
* -###################\\/ \//###################-
* _#/|##########/\######( /\ )######/\##########|\#_
* |/ |#/\#/\#/\/ \#/\##\ | | /##/\#/ \/\#/\#/\#| \|
* ` |/ V V ` V \#\| | | |/#/ V ' V V \| '
* ` ` ` ` / | | | | \ ' ' ' '
* ( | | | | )
* __\ | | | | /__
* (vvv(VVV)(VVV)vvv)
*
* HERE BE DRAGONS
*
*/
package org.sshtunnel;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import org.sshtunnel.db.Profile;
import org.sshtunnel.db.ProfileFactory;
import org.sshtunnel.utils.Constraints;
import org.sshtunnel.utils.Utils;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.AssetManager;
import android.net.ConnectivityManager;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.CheckBoxPreference;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.preference.PreferenceScreen;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.flurry.android.FlurryAgent;
import com.ksmaze.android.preference.ListPreferenceMultiSelect;
public class SSHTunnel extends PreferenceActivity implements
OnSharedPreferenceChangeListener {
private static final String TAG = "SSHTunnel";
public static boolean runCommand(String command) {
Process process = null;
try {
process = Runtime.getRuntime().exec(command);
process.waitFor();
} catch (Exception e) {
Log.e(TAG, e.getMessage());
return false;
} finally {
try {
process.destroy();
} catch (Exception e) {
// nothing
}
}
return true;
}
public static boolean runRootCommand(String command) {
Process process = null;
DataOutputStream os = null;
try {
process = Runtime.getRuntime().exec("su");
os = new DataOutputStream(process.getOutputStream());
os.writeBytes(command + "\n");
os.writeBytes("exit\n");
os.flush();
process.waitFor();
} catch (Exception e) {
Log.e(TAG, e.getMessage());
return false;
} finally {
try {
if (os != null) {
os.close();
}
process.destroy();
} catch (Exception e) {
// nothing
}
}
return true;
}
private BroadcastReceiver ssidReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (!action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Log.w(TAG, "onReceived() called uncorrectly");
return;
}
loadNetworkList();
}
};
private ProgressDialog pd = null;
private static boolean isRoot = false;
private List<Profile> profileList;
private CheckBoxPreference isAutoConnectCheck;
private CheckBoxPreference isAutoReconnectCheck;
private CheckBoxPreference isAutoSetProxyCheck;
private CheckBoxPreference isSocksCheck;
private CheckBoxPreference isGFWListCheck;
private CheckBoxPreference isDNSProxyCheck;
private CheckBoxPreference isUpstreamProxyCheck;
private ListPreference profileListPreference;
private EditTextPreference hostText;
private EditTextPreference portText;
private EditTextPreference userText;
private EditTextPreference passwordText;
private EditTextPreference localPortText;
private EditTextPreference remotePortText;
private EditTextPreference remoteAddressText;
private EditTextPreference upstreamProxyText;
private CheckBoxPreference isRunningCheck;
private Preference proxyedApps;
private ListPreferenceMultiSelect ssidListPreference;
private static final int MSG_UPDATE_FINISHED = 0;
final Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_UPDATE_FINISHED:
Toast.makeText(SSHTunnel.this,
getString(R.string.update_finished), Toast.LENGTH_LONG)
.show();
break;
}
super.handleMessage(msg);
}
};
private void CopyAssets() {
AssetManager assetManager = getAssets();
String[] files = null;
try {
files = assetManager.list("");
} catch (IOException e) {
Log.e(TAG, e.getMessage());
}
for (int i = 0; i < files.length; i++) {
InputStream in = null;
OutputStream out = null;
try {
// if (!(new File("/data/data/org.sshtunnel/" +
// files[i])).exists()) {
in = assetManager.open(files[i]);
out = new FileOutputStream("/data/data/org.sshtunnel/"
+ files[i]);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
// }
} catch (Exception e) {
Log.e(TAG, "Assets error", e);
}
}
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
}
private void delProfile() {
if (profileList.size() > 1) {
// del current profile
boolean result = ProfileFactory.delFromDao();
if (result == false)
Log.e(TAG, "del profile error");
// refresh profile list
loadProfileList();
// save the next profile to preference
ProfileFactory.saveToPreference();
// switch to the last profile
Profile profile = ProfileFactory.getProfile();
int id = profile.getId();
SharedPreferences settings = PreferenceManager
.getDefaultSharedPreferences(this);
Editor ed = settings.edit();
ed.putString(Constraints.ID, Integer.toString(id));
ed.commit();
// change the profile list value
profileListPreference.setValue(Integer.toString(id));
}
}
public boolean detectRoot() {
try {
Process proc = Runtime.getRuntime().exec("su");
if (proc == null)
return false;
proc.destroy();
} catch (Exception e) {
return false;
}
return true;
}
private void disableAll() {
hostText.setEnabled(false);
portText.setEnabled(false);
userText.setEnabled(false);
passwordText.setEnabled(false);
localPortText.setEnabled(false);
remotePortText.setEnabled(false);
remoteAddressText.setEnabled(false);
proxyedApps.setEnabled(false);
profileListPreference.setEnabled(false);
ssidListPreference.setEnabled(false);
upstreamProxyText.setEnabled(false);
isSocksCheck.setEnabled(false);
isAutoSetProxyCheck.setEnabled(false);
isAutoConnectCheck.setEnabled(false);
isAutoReconnectCheck.setEnabled(false);
isGFWListCheck.setEnabled(false);
isDNSProxyCheck.setEnabled(false);
isUpstreamProxyCheck.setEnabled(false);
}
private void enableAll() {
hostText.setEnabled(true);
portText.setEnabled(true);
userText.setEnabled(true);
passwordText.setEnabled(true);
localPortText.setEnabled(true);
if (!isSocksCheck.isChecked()) {
remotePortText.setEnabled(true);
remoteAddressText.setEnabled(true);
}
if (!isGFWListCheck.isChecked()) {
isAutoSetProxyCheck.setEnabled(true);
if (!isAutoSetProxyCheck.isChecked())
proxyedApps.setEnabled(true);
}
if (isAutoConnectCheck.isChecked()) {
ssidListPreference.setEnabled(true);
}
if (isUpstreamProxyCheck.isChecked()) {
upstreamProxyText.setEnabled(true);
}
profileListPreference.setEnabled(true);
isGFWListCheck.setEnabled(true);
isSocksCheck.setEnabled(true);
isAutoConnectCheck.setEnabled(true);
isAutoReconnectCheck.setEnabled(true);
isDNSProxyCheck.setEnabled(true);
isUpstreamProxyCheck.setEnabled(true);
}
private String getVersionName() {
try {
return getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
} catch (NameNotFoundException e) {
return "NONE";
}
}
private void initProfileList() {
profileList = ProfileFactory.loadAllProfilesFromDao();
if (profileList == null || profileList.size() == 0) {
ProfileFactory.newProfile();
Profile profile = ProfileFactory.getProfile();
profile.setName(getString(R.string.profile_default));
ProfileFactory.saveToDao();
ProfileFactory.saveToPreference();
}
loadProfileList();
}
private boolean isTextEmpty(String s, String msg) {
if (s == null || s.length() <= 0) {
showAToast(msg);
return true;
}
return false;
}
private void loadNetworkList() {
WifiManager wm = (WifiManager) this
.getSystemService(Context.WIFI_SERVICE);
List<WifiConfiguration> wcs = wm.getConfiguredNetworks();
String[] ssidEntries = new String[wcs.size() + 3];
ssidEntries[0] = Constraints.WIFI_AND_3G;
ssidEntries[1] = Constraints.ONLY_WIFI;
ssidEntries[2] = Constraints.ONLY_3G;
int n = 3;
for (WifiConfiguration wc : wcs) {
if (wc != null && wc.SSID != null)
ssidEntries[n++] = wc.SSID.replace("\"", "");
else
ssidEntries[n++] = "unknown";
}
ssidListPreference.setEntries(ssidEntries);
ssidListPreference.setEntryValues(ssidEntries);
}
private void loadProfileList() {
profileList = ProfileFactory.loadAllProfilesFromDao();
String[] profileEntries = new String[profileList.size() + 1];
String[] profileValues = new String[profileList.size() + 1];
int index = 0;
for (Profile profile : profileList) {
profileEntries[index] = Utils.getProfileName(profile);
profileValues[index] = Integer.toString(profile.getId());
index++;
}
profileEntries[index] = getString(R.string.profile_new);
profileValues[index] = Integer.toString(-1);
profileListPreference.setEntries(profileEntries);
profileListPreference.setEntryValues(profileValues);
}
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.main_pre);
hostText = (EditTextPreference) findPreference("host");
portText = (EditTextPreference) findPreference("port");
userText = (EditTextPreference) findPreference("user");
passwordText = (EditTextPreference) findPreference("password");
localPortText = (EditTextPreference) findPreference("localPort");
remotePortText = (EditTextPreference) findPreference("remotePort");
remoteAddressText = (EditTextPreference) findPreference("remoteAddress");
upstreamProxyText = (EditTextPreference) findPreference("upstreamProxy");
proxyedApps = findPreference("proxyedApps");
profileListPreference = (ListPreference) findPreference("profile_id");
ssidListPreference = (ListPreferenceMultiSelect) findPreference("ssid");
isRunningCheck = (CheckBoxPreference) findPreference("isRunning");
isAutoSetProxyCheck = (CheckBoxPreference) findPreference("isAutoSetProxy");
isSocksCheck = (CheckBoxPreference) findPreference("isSocks");
isAutoConnectCheck = (CheckBoxPreference) findPreference("isAutoConnect");
isAutoReconnectCheck = (CheckBoxPreference) findPreference("isAutoReconnect");
isGFWListCheck = (CheckBoxPreference) findPreference("isGFWList");
isDNSProxyCheck = (CheckBoxPreference) findPreference("isDNSProxy");
isUpstreamProxyCheck = (CheckBoxPreference) findPreference("isUpstreamProxy");
registerReceiver(ssidReceiver, new IntentFilter(
android.net.ConnectivityManager.CONNECTIVITY_ACTION));
loadNetworkList();
SharedPreferences settings = PreferenceManager
.getDefaultSharedPreferences(this);
Editor edit = settings.edit();
if (Utils.isWorked()) {
edit.putBoolean("isRunning", true);
} else {
if (settings.getBoolean("isRunning", false)) {
// showAToast(getString(R.string.crash_alert));
recovery();
}
edit.putBoolean("isRunning", false);
}
edit.commit();
if (settings.getBoolean("isRunning", false)) {
isRunningCheck.setChecked(true);
disableAll();
} else {
isRunningCheck.setChecked(false);
enableAll();
}
if (!detectRoot()) {
isRoot = false;
} else {
isRoot = true;
}
if (!isRoot) {
isAutoSetProxyCheck.setChecked(false);
isAutoSetProxyCheck.setEnabled(false);
proxyedApps.setEnabled(false);
showAToast(getString(R.string.require_root_alert));
}
initProfileList();
if (!settings.getBoolean(getVersionName(), false)) {
new Thread() {
@Override
public void run() {
CopyAssets();
runCommand("chmod 755 /data/data/org.sshtunnel/iptables");
runCommand("chmod 755 /data/data/org.sshtunnel/redsocks");
runCommand("chmod 755 /data/data/org.sshtunnel/proxy_http.sh");
runCommand("chmod 755 /data/data/org.sshtunnel/proxy_socks.sh");
SharedPreferences settings = PreferenceManager
.getDefaultSharedPreferences(SSHTunnel.this);
String versionName = getVersionName();
Editor edit = settings.edit();
edit = settings.edit();
edit.putBoolean(versionName, true);
edit.commit();
handler.sendEmptyMessage(MSG_UPDATE_FINISHED);
}
}.start();
}
}
// 点击Menu时,系统调用当前Activity的onCreateOptionsMenu方法,并传一个实现了一个Menu接口的menu对象供你使用
@Override
public boolean onCreateOptionsMenu(Menu menu) {
/*
* add()方法的四个参数,依次是: 1、组别,如果不分组的话就写Menu.NONE,
* 2、Id,这个很重要,Android根据这个Id来确定不同的菜单 3、顺序,那个菜单现在在前面由这个参数的大小决定
* 4、文本,菜单的显示文本
*/
menu.add(Menu.NONE, Menu.FIRST + 3, 1, getString(R.string.about))
.setIcon(android.R.drawable.ic_menu_info_details);
menu.add(Menu.NONE, Menu.FIRST + 4, 2, getString(R.string.key_manager))
.setIcon(android.R.drawable.ic_menu_manage);
menu.add(Menu.NONE, Menu.FIRST + 1, 3, getString(R.string.recovery))
.setIcon(android.R.drawable.ic_menu_close_clear_cancel);
menu.add(Menu.NONE, Menu.FIRST + 5, 4, getString(R.string.change_name))
.setIcon(android.R.drawable.ic_menu_edit);
menu.add(Menu.NONE, Menu.FIRST + 2, 5, getString(R.string.profile_del))
.setIcon(android.R.drawable.ic_menu_delete);
// return true才会起作用
return true;
}
/** Called when the activity is closed. */
@Override
public void onDestroy() {
unregisterReceiver(ssidReceiver);
super.onDestroy();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) { // 按下的如果是BACK,同时没有重复
try {
finish();
} catch (Exception ignore) {
// Nothing
}
return true;
}
return super.onKeyDown(keyCode, event);
}
// 菜单项被选择事件
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case Menu.FIRST + 1:
CopyAssets();
runCommand("chmod 755 /data/data/org.sshtunnel/iptables");
runCommand("chmod 755 /data/data/org.sshtunnel/redsocks");
runCommand("chmod 755 /data/data/org.sshtunnel/proxy_http.sh");
runCommand("chmod 755 /data/data/org.sshtunnel/proxy_socks.sh");
recovery();
break;
case Menu.FIRST + 2:
delProfile();
break;
case Menu.FIRST + 3:
String versionName = "";
try {
versionName = getPackageManager().getPackageInfo(
getPackageName(), 0).versionName;
} catch (NameNotFoundException e) {
versionName = "";
}
showAToast(getString(R.string.about) + " (" + versionName + ")"
+ getString(R.string.copy_rights));
break;
case Menu.FIRST + 4:
Intent intent = new Intent(this, FileChooser.class);
startActivity(intent);
break;
case Menu.FIRST + 5:
rename();
break;
}
return true;
}
@Override
protected void onPause() {
super.onPause();
// Unregister the listener whenever a key changes
getPreferenceScreen().getSharedPreferences()
.unregisterOnSharedPreferenceChangeListener(this);
}
@Override
public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen,
Preference preference) {
if (preference.getKey() != null
&& preference.getKey().equals("proxyedApps")) {
Intent intent = new Intent(this, AppManager.class);
startActivity(intent);
} else if (preference.getKey() != null
&& preference.getKey().equals("isRunning")) {
if (!serviceStart()) {
SharedPreferences settings = PreferenceManager
.getDefaultSharedPreferences(SSHTunnel.this);
Editor edit = settings.edit();
edit.putBoolean("isRunning", false);
edit.commit();
enableAll();
}
}
return super.onPreferenceTreeClick(preferenceScreen, preference);
}
@Override
protected void onResume() {
super.onResume();
SharedPreferences settings = PreferenceManager
.getDefaultSharedPreferences(this);
if (settings.getBoolean("isGFWList", false)) {
isAutoSetProxyCheck.setEnabled(false);
proxyedApps.setEnabled(false);
} else {
isAutoSetProxyCheck.setEnabled(true);
if (settings.getBoolean("isAutoSetProxy", false))
proxyedApps.setEnabled(false);
else
proxyedApps.setEnabled(true);
}
if (settings.getBoolean("isSocks", false)) {
remotePortText.setEnabled(false);
remoteAddressText.setEnabled(false);
} else {
remotePortText.setEnabled(true);
remoteAddressText.setEnabled(true);
}
if (settings.getBoolean("isConnecting", false)) {
if (pd != null) {
pd.dismiss();
pd = null;
}
}
Editor edit = settings.edit();
if (Utils.isWorked()) {
if (settings.getBoolean("isConnecting", false))
isRunningCheck.setEnabled(false);
edit.putBoolean("isRunning", true);
} else {
if (settings.getBoolean("isRunning", false)) {
showAToast(getString(R.string.crash_alert));
recovery();
}
edit.putBoolean("isRunning", false);
}
edit.commit();
if (settings.getBoolean("isAutoConnecting", false)) {
ssidListPreference.setEnabled(true);
} else {
ssidListPreference.setEnabled(false);
}
if (settings.getBoolean("isUpstreamProxy", false)) {
upstreamProxyText.setEnabled(true);
} else {
upstreamProxyText.setEnabled(false);
}
if (settings.getBoolean("isRunning", false)) {
isRunningCheck.setChecked(true);
disableAll();
} else {
isRunningCheck.setChecked(false);
enableAll();
}
// Setup the initial values
Profile profile = ProfileFactory.getProfile();
profileListPreference.setValue(Integer.toString(profile.getId()));
profileListPreference.setSummary(Utils.getProfileName(profile));
if (!settings.getString("ssid", "").equals(""))
ssidListPreference.setSummary(settings.getString("ssid", ""));
if (!settings.getString("user", "").equals(""))
userText.setSummary(settings.getString("user",
getString(R.string.user_summary)));
if (!settings.getString("port", "").equals(""))
portText.setSummary(settings.getString("port",
getString(R.string.port_summary)));
if (!settings.getString("host", "").equals(""))
hostText.setSummary(settings.getString("host",
getString(R.string.host_summary)));
if (!settings.getString("password", "").equals(""))
passwordText.setSummary("*********");
if (!settings.getString("localPort", "").equals(""))
localPortText.setSummary(settings.getString("localPort",
getString(R.string.local_port_summary)));
if (!settings.getString("remotePort", "").equals(""))
remotePortText.setSummary(settings.getString("remotePort",
getString(R.string.remote_port_summary)));
if (!settings.getString("remoteAddress", "").equals(""))
remoteAddressText.setSummary(settings.getString("remoteAddress",
getString(R.string.remote_port_summary)));
if (!settings.getString("upstreamProxy", "").equals(""))
upstreamProxyText.setSummary(settings.getString("upstreamProxy",
getString(R.string.upstream_proxy_summary)));
// Set up a listener whenever a key changes
getPreferenceScreen().getSharedPreferences()
.registerOnSharedPreferenceChangeListener(this);
}
private void updateValue(Profile profile) {
hostText.setText(profile.getHost());
userText.setText(profile.getUser());
passwordText.setText(profile.getPassword());
remoteAddressText.setText(profile.getRemoteAddress());
ssidListPreference.setValue(profile.getSsid());
upstreamProxyText.setText(profile.getUpstreamProxy());
portText.setText(Integer.toString(profile.getPort()));
localPortText.setText(Integer.toString(profile.getLocalPort()));
remotePortText.setText(Integer.toString(profile.getRemotePort()));
isAutoReconnectCheck.setChecked(profile.isAutoReconnect());
isDNSProxyCheck.setChecked(profile.isDNSProxy());
}
@Override
public void onSharedPreferenceChanged(SharedPreferences settings, String key) {
// Let's do something a preference value changes
if (key.equals(Constraints.ID)) {
ProfileFactory.loadFromPreference();
String id = settings.getString(Constraints.ID, "-1");
if (id.equals("-1")) {
// Create a new profile
ProfileFactory.newProfile();
// refresh profile list
loadProfileList();
// save the new profile to preference
ProfileFactory.saveToPreference();
// switch profile again
Profile profile = ProfileFactory.getProfile();
String profileId = Integer.toString(profile.getId());
Editor ed = settings.edit();
ed.putString(Constraints.ID, profileId);
ed.commit();
// change profile list value
profileListPreference.setValue(profileId);
} else {
int profileId;
try {
profileId = Integer.valueOf(id);
} catch (NumberFormatException e) {
profileList = ProfileFactory.loadAllProfilesFromDao();
profileId = profileList.get(0).getId();
}
ProfileFactory.switchToProfile(profileId);
Profile profile = ProfileFactory.getProfile();
profileListPreference.setSummary(Utils.getProfileName(profile));
updateValue(profile);
}
}
if (key.equals("isConnecting")) {
if (settings.getBoolean("isConnecting", false)) {
Log.d(TAG, "Connecting start");
isRunningCheck.setEnabled(false);
pd = ProgressDialog.show(this, "",
getString(R.string.connecting), true, true);
} else {
Log.d(TAG, "Connecting finish");
if (pd != null) {
pd.dismiss();
pd = null;
}
isRunningCheck.setEnabled(true);
}
}
if (key.equals("isSocks")) {
if (settings.getBoolean("isSocks", false)) {
isSocksCheck.setChecked(true);
remotePortText.setEnabled(false);
remoteAddressText.setEnabled(false);
} else {
isSocksCheck.setChecked(false);
remotePortText.setEnabled(true);
remoteAddressText.setEnabled(true);
}
}
if (key.equals("isGFWList")) {
if (settings.getBoolean("isGFWList", false)) {
isGFWListCheck.setChecked(true);
isAutoSetProxyCheck.setEnabled(false);
proxyedApps.setEnabled(false);
} else {
isGFWListCheck.setChecked(false);
isAutoSetProxyCheck.setEnabled(true);
if (settings.getBoolean("isAutoSetProxy", false))
proxyedApps.setEnabled(false);
else
proxyedApps.setEnabled(true);
}
}
if (key.equals("isAutoConnect")) {
if (settings.getBoolean("isAutoConnect", false)) {
isAutoConnectCheck.setChecked(true);
ssidListPreference.setEnabled(true);
} else {
isAutoConnectCheck.setChecked(false);
ssidListPreference.setEnabled(false);
}
}
if (key.equals("isAutoSetProxy")) {
if (!settings.getBoolean("isGFWList", false)) {
if (settings.getBoolean("isAutoSetProxy", false)) {
isAutoSetProxyCheck.setChecked(true);
proxyedApps.setEnabled(false);
} else {
isAutoSetProxyCheck.setChecked(false);
proxyedApps.setEnabled(true);
}
}
}
if (key.equals("isUpstreamProxy")) {
if (settings.getBoolean("isUpstreamProxy", false)) {
isUpstreamProxyCheck.setChecked(true);
upstreamProxyText.setEnabled(true);
} else {
isUpstreamProxyCheck.setChecked(false);
upstreamProxyText.setEnabled(false);
}
}
if (key.equals("isRunning")) {
if (settings.getBoolean("isRunning", false)) {
disableAll();
isRunningCheck.setChecked(true);
} else {
enableAll();
isRunningCheck.setChecked(false);
}
}
if (key.equals("ssid"))
if (settings.getString("ssid", "").equals(""))
ssidListPreference.setSummary(getString(R.string.ssid_summary));
else
ssidListPreference.setSummary(settings.getString("ssid", ""));
else if (key.equals("user"))
if (settings.getString("user", "").equals(""))
userText.setSummary(getString(R.string.user_summary));
else
userText.setSummary(settings.getString("user", ""));
else if (key.equals("port"))
if (settings.getString("port", "").equals(""))
portText.setSummary(getString(R.string.port_summary));
else
portText.setSummary(settings.getString("port", ""));
else if (key.equals("host"))
if (settings.getString("host", "").equals(""))
hostText.setSummary(getString(R.string.host_summary));
else
hostText.setSummary(settings.getString("host", ""));
else if (key.equals("localPort"))
if (settings.getString("localPort", "").equals(""))
localPortText
.setSummary(getString(R.string.local_port_summary));
else
localPortText.setSummary(settings.getString("localPort", ""));
else if (key.equals("remotePort"))
if (settings.getString("remotePort", "").equals(""))
remotePortText
.setSummary(getString(R.string.remote_port_summary));
else
remotePortText.setSummary(settings.getString("remotePort", ""));
else if (key.equals("remoteAddress"))
if (settings.getString("remoteAddress", "").equals(""))
remoteAddressText
.setSummary(getString(R.string.remote_port_summary));
else
remoteAddressText.setSummary(settings.getString(
"remoteAddress", ""));
else if (key.equals("password"))
if (!settings.getString("password", "").equals(""))
passwordText.setSummary("*********");
else
passwordText.setSummary(getString(R.string.password_summary));
else if (key.equals("upstreamProxy"))
if (settings.getString("upstreamProxy", "").equals(""))
upstreamProxyText
.setSummary(getString(R.string.upstream_proxy_summary));
else
upstreamProxyText.setSummary(settings.getString(
"upstreamProxy", ""));
}
@Override
public void onStart() {
super.onStart();
FlurryAgent.onStartSession(this, "MBY4JL18FQK1DPEJ5Y39");
}
@Override
public void onStop() {
super.onStop();
FlurryAgent.onEndSession(this);
}
private void recovery() {
new Thread() {
@Override
public void run() {
try {
stopService(new Intent(SSHTunnel.this,
SSHTunnelService.class));
} catch (Exception e) {
// Nothing
}
try {
File cache = new File(SSHTunnelService.BASE
+ "cache/dnscache");
if (cache.exists())
cache.delete();
} catch (Exception ignore) {
// Nothing
}
runRootCommand(SSHTunnelService.BASE
+ "iptables -t nat -F OUTPUT");
runRootCommand(SSHTunnelService.BASE + "proxy_http.sh stop");
}
}.start();
}
private void rename() {
LayoutInflater factory = LayoutInflater.from(this);
final View textEntryView = factory.inflate(
R.layout.alert_dialog_text_entry, null);
final EditText profileName = (EditText) textEntryView
.findViewById(R.id.profile_name_edit);
final Profile profile = ProfileFactory.getProfile();
profileName.setText(Utils.getProfileName(profile));
AlertDialog ad = new AlertDialog.Builder(this)
.setTitle(R.string.change_name)
.setView(textEntryView)
.setPositiveButton(R.string.alert_dialog_ok,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int whichButton) {
EditText profileName = (EditText) textEntryView
.findViewById(R.id.profile_name_edit);
String name = profileName.getText().toString();
if (name == null)
return;
name = name.replace("|", "");
if (name.length() <= 0)
return;
profile.setName(name);
ProfileFactory.saveToDao();
SharedPreferences settings = PreferenceManager
.getDefaultSharedPreferences(SSHTunnel.this);
Editor ed = settings.edit();
ed.putString(Constraints.NAME,
profile.getName());
ed.commit();
profileListPreference.setSummary(Utils
.getProfileName(profile));
loadProfileList();
}
})
.setNegativeButton(R.string.alert_dialog_cancel,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int whichButton) {
/* User clicked cancel so do some stuff */
}
}).create();
ad.show();
}
/** Called when connect button is clicked. */
public boolean serviceStart() {
if (Utils.isWorked()) {
try {
stopService(new Intent(SSHTunnel.this, SSHTunnelService.class));
} catch (Exception e) {
// Nothing
}
return false;
}
Profile profile = ProfileFactory.getProfile();
ProfileFactory.loadFromPreference();
if (isTextEmpty(profile.getHost(), getString(R.string.host_empty)))
return false;
if (isTextEmpty(profile.getUser(), getString(R.string.user_empty)))
return false;
try {
if (isTextEmpty(Integer.toString(profile.getPort()),
getString(R.string.port_empty)))
return false;
if (isTextEmpty(Integer.toString(profile.getLocalPort()),
getString(R.string.local_port_empty)))
return false;
if (profile.getLocalPort() <= 1024)
this.showAToast(getString(R.string.port_alert));
if (!profile.isSocks()) {
if (isTextEmpty(Integer.toString(profile.getRemotePort()),
getString(R.string.remote_port_empty)))
return false;
}
} catch (NullPointerException e) {
showAToast(getString(R.string.number_alert));
Log.e(TAG, "wrong number", e);
return false;
}
try {
Intent it = new Intent(SSHTunnel.this, SSHTunnelService.class);
Bundle bundle = new Bundle();
bundle.putInt(Constraints.ID, profile.getId());
it.putExtras(bundle);
startService(it);
} catch (Exception ignore) {
// Nothing
return false;
}
return true;
}
private void showAToast(String msg) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(msg)
.setCancelable(false)
.setNegativeButton(getString(R.string.ok_iknow),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
} | Java |
package org.sshtunnel;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketException;
import java.net.URL;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Random;
import org.sshtunnel.utils.Base64;
import org.sshtunnel.utils.DomainValidator;
import org.sshtunnel.utils.InnerSocketBuilder;
import org.sshtunnel.utils.Utils;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.util.Log;
/**
* 此类封装了一个Dns回应
*
* @author biaji
*
*/
class DnsResponse implements Serializable {
private static final long serialVersionUID = -6693216674221293274L;
private String request = null;
private long timestamp = System.currentTimeMillis();;
private int reqTimes = 0;
private byte[] dnsResponse = null;
public DnsResponse(String request) {
this.request = request;
}
/**
* @return the dnsResponse
*/
public byte[] getDnsResponse() {
this.reqTimes++;
return dnsResponse;
}
/**
* @return IP string
*/
public String getIPString() {
String ip = null;
int i;
if (dnsResponse == null) {
return null;
}
i = dnsResponse.length - 4;
if (i < 0) {
return null;
}
ip = "" + (dnsResponse[i] & 0xFF); /* Unsigned byte to int */
for (i++; i < dnsResponse.length; i++) {
ip += "." + (dnsResponse[i] & 0xFF);
}
return ip;
}
/**
* @return the reqTimes
*/
public int getReqTimes() {
return reqTimes;
}
public String getRequest() {
return this.request;
}
/**
* @return the timestamp
*/
public long getTimestamp() {
return timestamp;
}
/**
* @param dnsResponse
* the dnsResponse to set
*/
public void setDnsResponse(byte[] dnsResponse) {
this.dnsResponse = dnsResponse;
}
}
/**
* 此类实现了DNS代理
*
* @author biaji
*
*/
public class DNSServer implements WrapServer {
public static byte[] int2byte(int res) {
byte[] targets = new byte[4];
targets[0] = (byte) (res & 0xff);// 最低位
targets[1] = (byte) ((res >> 8) & 0xff);// 次低位
targets[2] = (byte) ((res >> 16) & 0xff);// 次高位
targets[3] = (byte) (res >>> 24);// 最高位,无符号右移。
return targets;
}
private final String TAG = "SSHTunnel";
private String homePath;
private final String CACHE_PATH = "/cache";
private final String CACHE_FILE = "/dnscache";
private DatagramSocket srvSocket;
private int srvPort = 0;
private String name;
protected String dnsHost;
protected int dnsPort;
protected Context context;
private volatile int threadNum = 0;
private final static int MAX_THREAD_NUM = 5;
public HashSet<String> domains;
final protected int DNS_PKG_HEADER_LEN = 12;
final private int[] DNS_HEADERS = { 0, 0, 0x81, 0x80, 0, 0, 0, 0, 0, 0, 0,
0 };
final private int[] DNS_PAYLOAD = { 0xc0, 0x0c, 0x00, 0x01, 0x00, 0x01,
0x00, 0x00, 0x00, 0x3c, 0x00, 0x04 };
final private int IP_SECTION_LEN = 4;
private boolean inService = false;
private Hashtable<String, DnsResponse> dnsCache = new Hashtable<String, DnsResponse>();
/**
* 内建自定义缓存
*
*/
private Hashtable<String, String> orgCache = new Hashtable<String, String>();
private String target = "8.8.8.8:53";
private static final String CANT_RESOLVE = "Error";
public DNSServer(String name, String dnsHost, int dnsPort, Context context) {
this.name = name;
this.dnsHost = dnsHost;
this.dnsPort = dnsPort;
this.context = context;
domains = new HashSet<String>();
if (dnsHost != null && !dnsHost.equals(""))
target = dnsHost + ":" + dnsPort;
}
/**
* 在缓存中添加一个域名解析
*
* @param questDomainName
* 域名
* @param answer
* 解析结果
*/
private synchronized void addToCache(String questDomainName, byte[] answer) {
DnsResponse response = new DnsResponse(questDomainName);
response.setDnsResponse(answer);
dnsCache.put(questDomainName, response);
saveCache();
}
@Override
public void close() throws IOException {
inService = false;
if (srvSocket != null) {
srvSocket.close();
srvSocket = null;
}
saveCache();
Log.i(TAG, "DNS服务关闭");
}
/*
* Create a DNS response packet, which will send back to application.
*
* @author yanghong
*
* Reference to:
*
* Mini Fake DNS server (Python)
* http://code.activestate.com/recipes/491264-mini-fake-dns-server/
*
* DOMAIN NAMES - IMPLEMENTATION AND SPECIFICATION
* http://www.ietf.org/rfc/rfc1035.txt
*/
protected byte[] createDNSResponse(byte[] quest, byte[] ips) {
byte[] response = null;
int start = 0;
response = new byte[128];
for (int val : DNS_HEADERS) {
response[start] = (byte) val;
start++;
}
System.arraycopy(quest, 0, response, 0, 2); /* 0:2 */
System.arraycopy(quest, 4, response, 4, 2); /* 4:6 -> 4:6 */
System.arraycopy(quest, 4, response, 6, 2); /* 4:6 -> 7:9 */
System.arraycopy(quest, DNS_PKG_HEADER_LEN, response, start,
quest.length - DNS_PKG_HEADER_LEN); /* 12:~ -> 15:~ */
start += quest.length - DNS_PKG_HEADER_LEN;
for (int val : DNS_PAYLOAD) {
response[start] = (byte) val;
start++;
}
/* IP address in response */
for (byte ip : ips) {
response[start] = ip;
start++;
}
byte[] result = new byte[start];
System.arraycopy(response, 0, result, 0, start);
Log.d(TAG, "DNS Response package size: " + start);
return result;
}
/**
* 由上级DNS通过TCP取得解析
*
* @param quest
* 原始DNS请求
* @return
*/
protected byte[] fetchAnswer(byte[] quest) {
Socket innerSocket = new InnerSocketBuilder("8.8.4.4", 53, "8.8.4.4:53")
.getSocket();
DataInputStream in;
DataOutputStream out;
byte[] result = null;
try {
if (innerSocket != null && innerSocket.isConnected()) {
// 构造TCP DNS包
int dnsqLength = quest.length;
byte[] tcpdnsq = new byte[dnsqLength + 2];
System.arraycopy(int2byte(dnsqLength), 0, tcpdnsq, 1, 1);
System.arraycopy(quest, 0, tcpdnsq, 2, dnsqLength);
// 转发DNS
in = new DataInputStream(innerSocket.getInputStream());
out = new DataOutputStream(innerSocket.getOutputStream());
out.write(tcpdnsq);
out.flush();
ByteArrayOutputStream bout = new ByteArrayOutputStream();
int b = -1;
while ((b = in.read()) != -1) {
bout.write(b);
}
byte[] tcpdnsr = bout.toByteArray();
if (tcpdnsr != null && tcpdnsr.length > 2) {
result = new byte[tcpdnsr.length - 2];
System.arraycopy(tcpdnsr, 2, result, 0, tcpdnsr.length - 2);
}
innerSocket.close();
}
} catch (IOException e) {
Log.e(TAG, "", e);
}
return result;
}
public byte[] fetchAnswerHTTP(byte[] quest) {
byte[] result = null;
String domain = getRequestDomain(quest);
String ip = null;
DomainValidator dv = DomainValidator.getInstance();
/* Not support reverse domain name query */
if (domain.endsWith("in-addr.arpa") || !dv.isValid(domain)) {
return createDNSResponse(quest, parseIPString("127.0.0.1"));
// return null;
}
ip = resolveDomainName(domain);
if (ip == null) {
Log.e(TAG, "Failed to resolve domain name: " + domain);
return null;
}
if (ip.equals(CANT_RESOLVE)) {
return null;
}
byte[] ips = parseIPString(ip);
if (ips != null) {
result = createDNSResponse(quest, ips);
}
return result;
}
/**
* 获取UDP DNS请求的域名
*
* @param request
* dns udp包
* @return 请求的域名
*/
protected String getRequestDomain(byte[] request) {
String requestDomain = "";
int reqLength = request.length;
if (reqLength > 13) { // 包含包体
byte[] question = new byte[reqLength - 12];
System.arraycopy(request, 12, question, 0, reqLength - 12);
requestDomain = parseDomain(question);
if (requestDomain.length() > 1)
requestDomain = requestDomain.substring(0,
requestDomain.length() - 1);
}
return requestDomain;
}
@Override
public int getServPort() {
return this.srvPort;
}
public int init() {
try {
srvSocket = new DatagramSocket(0,
InetAddress.getByName("127.0.0.1"));
inService = true;
srvPort = srvSocket.getLocalPort();
Log.e(TAG, this.name + "启动于端口: " + srvPort);
} catch (SocketException e) {
Log.e(TAG, "DNSServer初始化错误,端口号" + srvPort, e);
} catch (UnknownHostException e) {
Log.e(TAG, "DNSServer初始化错误,端口号" + srvPort, e);
}
return srvPort;
}
@Override
public boolean isClosed() {
return srvSocket.isClosed();
}
public boolean isInService() {
return inService;
}
/**
* 由缓存载入域名解析缓存
*/
private void loadCache() {
ObjectInputStream ois = null;
File cache = new File(homePath + CACHE_PATH + CACHE_FILE);
try {
if (!cache.exists())
return;
ois = new ObjectInputStream(new FileInputStream(cache));
dnsCache = (Hashtable<String, DnsResponse>) ois.readObject();
ois.close();
ois = null;
Hashtable<String, DnsResponse> tmpCache = (Hashtable<String, DnsResponse>) dnsCache
.clone();
for (DnsResponse resp : dnsCache.values()) {
// 检查缓存时效(五天)
if ((System.currentTimeMillis() - resp.getTimestamp()) > 432000000L) {
Log.d(TAG, "删除" + resp.getRequest() + "记录");
tmpCache.remove(resp.getRequest());
}
}
dnsCache = tmpCache;
tmpCache = null;
} catch (ClassCastException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
} catch (FileNotFoundException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
} catch (IOException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
} catch (ClassNotFoundException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
} finally {
try {
if (ois != null)
ois.close();
} catch (IOException e) {
}
}
}
/**
* 解析域名
*
* @param request
* @return
*/
private String parseDomain(byte[] request) {
String result = "";
int length = request.length;
int partLength = request[0];
if (partLength == 0)
return result;
try {
byte[] left = new byte[length - partLength - 1];
System.arraycopy(request, partLength + 1, left, 0, length
- partLength - 1);
result = new String(request, 1, partLength) + ".";
result += parseDomain(left);
} catch (Exception e) {
Log.e(TAG, e.getLocalizedMessage());
}
return result;
}
/*
* Parse IP string into byte, do validation.
*
* @param ip IP string
*
* @return IP in byte array
*/
protected byte[] parseIPString(String ip) {
byte[] result = null;
int value;
int i = 0;
String[] ips = null;
ips = ip.split("\\.");
Log.d(TAG, "Start parse ip string: " + ip + ", Sectons: " + ips.length);
if (ips.length != IP_SECTION_LEN) {
Log.e(TAG, "Malformed IP string number of sections is: "
+ ips.length);
return null;
}
result = new byte[IP_SECTION_LEN];
for (String section : ips) {
try {
value = Integer.parseInt(section);
/* 0.*.*.* and *.*.*.0 is invalid */
if ((i == 0 || i == 3) && value == 0) {
return null;
}
result[i] = (byte) value;
i++;
} catch (NumberFormatException e) {
Log.e(TAG, "Malformed IP string section: " + section);
return null;
}
}
return result;
}
/*
* Resolve host name by access a DNSRelay running on GAE:
*
* Example:
*
* http://www.hosts.dotcloud.com/lookup.php?(domain name encoded)
* http://gaednsproxy.appspot.com/?d=(domain name encoded)
*/
private String resolveDomainName(String domain) {
String ip = null;
InputStream is;
String encode_host = URLEncoder.encode(Base64.encodeBytes(Base64
.encodeBytesToBytes(domain.getBytes())));
String url = "http://gaednsproxy.appspot.com:" + dnsPort + "/?d="
+ encode_host;
Random random = new Random(System.currentTimeMillis());
int n = random.nextInt(2);
if (n == 1)
url = "http://gaednsproxy1.appspot.com:" + dnsPort + "/?d="
+ encode_host;
Log.d(TAG, "DNS Relay URL: " + url);
try {
URL aURL = new URL(url);
HttpURLConnection conn = (HttpURLConnection) aURL.openConnection();
conn.setConnectTimeout(2000);
conn.setConnectTimeout(5000);
conn.connect();
is = conn.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
ip = br.readLine();
} catch (SocketException e) {
Log.e(TAG, "Failed to request URI: " + url, e);
} catch (IOException e) {
Log.e(TAG, "Failed to request URI: " + url, e);
} catch (NullPointerException e) {
Log.e(TAG, "Failed to request URI: " + url, e);
}
return ip;
}
/*
* Implement with http based DNS.
*/
@Override
public void run() {
loadCache();
byte[] qbuffer = new byte[576];
SharedPreferences settings = PreferenceManager
.getDefaultSharedPreferences(context);
threadNum = 0;
while (true) {
try {
final DatagramPacket dnsq = new DatagramPacket(qbuffer,
qbuffer.length);
if (!settings.getBoolean("isRunning", false))
break;
srvSocket.receive(dnsq);
// 连接外部DNS进行解析。
byte[] data = dnsq.getData();
int dnsqLength = dnsq.getLength();
final byte[] udpreq = new byte[dnsqLength];
System.arraycopy(data, 0, udpreq, 0, dnsqLength);
// 尝试从缓存读取域名解析
final String questDomain = getRequestDomain(udpreq);
Log.d(TAG, "解析" + questDomain);
if (dnsCache.containsKey(questDomain)) {
sendDns(dnsCache.get(questDomain).getDnsResponse(), dnsq,
srvSocket);
Log.d(TAG, "命中缓存");
} else if (orgCache.containsKey(questDomain)) { // 如果为自定义域名解析
byte[] ips = parseIPString(orgCache.get(questDomain));
byte[] answer = createDNSResponse(udpreq, ips);
addToCache(questDomain, answer);
sendDns(answer, dnsq, srvSocket);
Log.d(TAG, "自定义解析" + orgCache);
} else if (questDomain.toLowerCase().contains("appspot.com")) { // for
// gaednsproxy.appspot.com
byte[] ips = parseIPString("127.0.0.1");
byte[] answer = createDNSResponse(udpreq, ips);
addToCache(questDomain, answer);
sendDns(answer, dnsq, srvSocket);
Log.d(TAG, "Custom DNS resolver gaednsproxy.appspot.com");
} else {
synchronized (this) {
if (domains.contains(questDomain))
continue;
else
domains.add(questDomain);
}
while (threadNum >= MAX_THREAD_NUM) {
Thread.sleep(2000);
}
threadNum++;
new Thread() {
@Override
public void run() {
long startTime = System.currentTimeMillis();
try {
byte[] answer;
answer = fetchAnswerHTTP(udpreq);
if (answer != null && answer.length != 0) {
addToCache(questDomain, answer);
sendDns(answer, dnsq, srvSocket);
Log.d(TAG,
"正确返回DNS解析,长度:"
+ answer.length
+ " 耗时:"
+ (System
.currentTimeMillis() - startTime)
/ 1000 + "s");
} else {
Log.e(TAG, "返回DNS包长为0");
}
} catch (Exception e) {
// Nothing
}
synchronized (DNSServer.this) {
domains.remove(questDomain);
}
threadNum--;
}
}.start();
}
/* For test, validate dnsCache */
/*
* if (dnsCache.size() > 0) { Log.d(TAG, "Domains in cache:");
*
* Enumeration<String> enu = dnsCache.keys(); while
* (enu.hasMoreElements()) { String domain = (String)
* enu.nextElement(); DnsResponse resp = dnsCache.get(domain);
*
* Log.d(TAG, domain + " : " + resp.getIPString()); } }
*/
} catch (IOException e) {
Log.e(TAG, "IO Exception", e);
} catch (NullPointerException e) {
Log.e(TAG, "Srvsocket wrong", e);
break;
} catch (InterruptedException e) {
Log.e(TAG, "Interuppted");
break;
}
}
if (srvSocket != null) {
srvSocket.close();
srvSocket = null;
}
if (Utils.isWorked()) {
try {
context.stopService(new Intent(context, SSHTunnelService.class));
} catch (Exception e) {
// Nothing
}
}
}
/**
* 保存域名解析内容缓存
*/
private void saveCache() {
ObjectOutputStream oos = null;
File cache = new File(homePath + CACHE_PATH + CACHE_FILE);
try {
if (!cache.exists()) {
File cacheDir = new File(homePath + CACHE_PATH);
if (!cacheDir.exists()) { // android的createNewFile这个方法真够恶心的啊
cacheDir.mkdir();
}
cache.createNewFile();
}
oos = new ObjectOutputStream(new FileOutputStream(cache));
oos.writeObject(dnsCache);
oos.flush();
oos.close();
oos = null;
} catch (FileNotFoundException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
} catch (IOException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
} finally {
try {
if (oos != null)
oos.close();
} catch (IOException e) {
}
}
}
/**
* 向来源发送dns应答
*
* @param response
* 应答包
* @param dnsq
* 请求包
* @param srvSocket
* 侦听Socket
*/
private void sendDns(byte[] response, DatagramPacket dnsq,
DatagramSocket srvSocket) {
// 同步identifier
System.arraycopy(dnsq.getData(), 0, response, 0, 2);
DatagramPacket resp = new DatagramPacket(response, 0, response.length);
resp.setPort(dnsq.getPort());
resp.setAddress(dnsq.getAddress());
try {
srvSocket.send(resp);
} catch (IOException e) {
Log.e(TAG, "", e);
}
}
public void setBasePath(String path) {
this.homePath = path;
}
@Override
public void setProxyHost(String host) {
// TODO Auto-generated method stub
}
@Override
public void setProxyPort(int port) {
// TODO Auto-generated method stub
}
@Override
public void setTarget(String target) {
this.target = target;
}
public boolean test(String domain, String ip) {
boolean ret = true;
// TODO: Implement test case
return ret;
}
}
| Java |
package org.sshtunnel;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Stack;
import org.sshtunnel.utils.Utils;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.widget.ImageView;
public class ImageLoader {
// Used to display bitmap in the UI thread
class BitmapDisplayer implements Runnable {
Bitmap bitmap;
ImageView imageView;
public BitmapDisplayer(Bitmap b, ImageView i) {
bitmap = b;
imageView = i;
}
@Override
public void run() {
if (bitmap != null)
imageView.setImageBitmap(bitmap);
else
imageView.setImageResource(stub_id);
}
}
class PhotosLoader extends Thread {
@Override
public void run() {
try {
while (true) {
// thread waits until there are any images to load in the
// queue
if (photosQueue.photosToLoad.size() == 0)
synchronized (photosQueue.photosToLoad) {
photosQueue.photosToLoad.wait();
}
if (photosQueue.photosToLoad.size() != 0) {
PhotoToLoad photoToLoad;
synchronized (photosQueue.photosToLoad) {
photoToLoad = photosQueue.photosToLoad.pop();
}
Bitmap bmp = getBitmap(photoToLoad.uid);
cache.put(photoToLoad.uid, bmp);
Object tag = photoToLoad.imageView.getTag();
if (tag != null
&& ((Integer) tag) == photoToLoad.uid) {
BitmapDisplayer bd = new BitmapDisplayer(bmp,
photoToLoad.imageView);
Activity a = (Activity) photoToLoad.imageView
.getContext();
a.runOnUiThread(bd);
}
}
if (Thread.interrupted())
break;
}
} catch (InterruptedException e) {
// allow thread to exit
}
}
}
// stores list of photos to download
class PhotosQueue {
private Stack<PhotoToLoad> photosToLoad = new Stack<PhotoToLoad>();
// removes all instances of this ImageView
public void Clean(ImageView image) {
for (int j = 0; j < photosToLoad.size();) {
if (photosToLoad.get(j).imageView == image)
photosToLoad.remove(j);
else
++j;
}
}
}
// Task for the queue
private class PhotoToLoad {
public int uid;
public ImageView imageView;
public PhotoToLoad(int u, ImageView i) {
uid = u;
imageView = i;
}
}
// the simplest in-memory cache implementation. This should be replaced with
// something like SoftReference or BitmapOptions.inPurgeable(since 1.6)
private HashMap<Integer, Bitmap> cache = new HashMap<Integer, Bitmap>();
private File cacheDir;
private Context context;
final int stub_id = R.drawable.sym_def_app_icon;
PhotosQueue photosQueue = new PhotosQueue();
PhotosLoader photoLoaderThread = new PhotosLoader();
public ImageLoader(Context c) {
// Make the background thead low priority. This way it will not affect
// the UI performance
photoLoaderThread.setPriority(Thread.NORM_PRIORITY - 1);
context = c;
// Find the dir to save cached images
cacheDir = context.getCacheDir();
}
public void clearCache() {
// clear memory cache
cache.clear();
// clear SD cache
File[] files = cacheDir.listFiles();
for (File f : files)
f.delete();
}
// decodes image and scales it to reduce memory consumption
private Bitmap decodeFile(File f) {
try {
// decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f), null, o);
// Find the correct scale value. It should be the power of 2.
final int REQUIRED_SIZE = 70;
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp / 2 < REQUIRED_SIZE
|| height_tmp / 2 < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {
}
return null;
}
public void DisplayImage(int uid, Activity activity, ImageView imageView) {
if (cache.containsKey(uid))
imageView.setImageBitmap(cache.get(uid));
else {
queuePhoto(uid, activity, imageView);
imageView.setImageResource(stub_id);
}
}
private Bitmap getBitmap(int uid) {
// I identify images by hashcode. Not a perfect solution, good for the
// demo.
String filename = String.valueOf(uid);
File f = new File(cacheDir, filename);
// from SD cache
Bitmap b = decodeFile(f);
if (b != null)
return b;
// from web
try {
BitmapDrawable icon = (BitmapDrawable) Utils.getAppIcon(context,
uid);
return icon.getBitmap();
} catch (Exception ex) {
return null;
}
}
private void queuePhoto(int uid, Activity activity, ImageView imageView) {
// This ImageView may be used for other images before. So there may be
// some old tasks in the queue. We need to discard them.
photosQueue.Clean(imageView);
PhotoToLoad p = new PhotoToLoad(uid, imageView);
synchronized (photosQueue.photosToLoad) {
photosQueue.photosToLoad.push(p);
photosQueue.photosToLoad.notifyAll();
}
// start thread if it's not started yet
if (photoLoaderThread.getState() == Thread.State.NEW)
photoLoaderThread.start();
}
public void stopThread() {
photoLoaderThread.interrupt();
}
}
| Java |
package org.sshtunnel;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.sshtunnel.utils.Constraints;
import android.app.ListActivity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;
public class FileChooser extends ListActivity {
private File currentDir;
private FileArrayAdapter adapter;
private void fill(File f) {
File[] dirs = f.listFiles();
this.setTitle(getString(R.string.current_dir) + ": " + f.getName());
List<Option> dir = new ArrayList<Option>();
List<Option> fls = new ArrayList<Option>();
try {
for (File ff : dirs) {
if (ff.isDirectory())
dir.add(new Option(ff.getName(),
getString(R.string.folder), ff.getAbsolutePath()));
else {
fls.add(new Option(ff.getName(),
getString(R.string.file_size) + ff.length(), ff
.getAbsolutePath()));
}
}
} catch (Exception e) {
}
Collections.sort(dir);
Collections.sort(fls);
dir.addAll(fls);
if (!f.getName().equalsIgnoreCase("sdcard"))
dir.add(0,
new Option("..", getString(R.string.parent_dir), f
.getParent()));
adapter = new FileArrayAdapter(FileChooser.this, R.layout.file_view,
dir);
this.setListAdapter(adapter);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
currentDir = new File("/sdcard/");
fill(currentDir);
}
private void onFileClick(Option o) {
SharedPreferences settings = PreferenceManager
.getDefaultSharedPreferences(this);
Editor ed = settings.edit();
ed.putString(Constraints.KEY_PATH, o.getPath());
ed.commit();
Toast.makeText(this, getString(R.string.file_toast) + o.getPath(),
Toast.LENGTH_SHORT).show();
finish();
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Option o = adapter.getItem(position);
if (o.getData().equalsIgnoreCase(getString(R.string.folder))
|| o.getData().equalsIgnoreCase(getString(R.string.parent_dir))) {
currentDir = new File(o.getPath());
fill(currentDir);
} else {
onFileClick(o);
}
}
} | Java |
package org.sshtunnel;
import org.sshtunnel.db.Profile;
import org.sshtunnel.db.ProfileFactory;
import org.sshtunnel.utils.Constraints;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class FingerPrintDialog extends Activity {
private Profile profile = null;
private String fingerPrint = "";
private String fingerPrintType = "";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.layout_finger_print_dialog);
Bundle bundle = getIntent().getExtras();
int status = bundle.getInt(Constraints.FINGER_PRINT_STATUS);
fingerPrint = bundle.getString(Constraints.FINGER_PRINT);
fingerPrintType = bundle.getString(Constraints.FINGER_PRINT_TYPE);
int profileId = bundle.getInt(Constraints.ID);
SharedPreferences settings = PreferenceManager
.getDefaultSharedPreferences(this);
String id = settings.getString(Constraints.ID, "-1");
if (id.equals(Integer.toString(profileId))) {
profile = ProfileFactory.getProfile();
} else {
profile = ProfileFactory.loadProfileFromDao(profileId);
}
TextView warningText = (TextView) findViewById(R.id.warning_text);
Button acceptButton = (Button) findViewById(R.id.accept);
Button denyButton = (Button) findViewById(R.id.deny);
acceptButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
accept();
}
});
denyButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
deny();
}
});
StringBuffer sb = new StringBuffer();
switch (status) {
case Constraints.FINGER_PRINT_INIITIALIZE:
sb.append(getString(R.string.finger_print_first) + "\n\n");
break;
case Constraints.FINGER_PRINT_CHANGED:
sb.append(getString(R.string.finger_print_changed) + "\n\n");
break;
}
sb.append(fingerPrintType + " " + getString(R.string.finger_print)
+ "\n" + fingerPrint);
warningText.setText(sb.toString());
}
private void accept() {
if (profile != null) {
profile.setFingerPrintType(fingerPrintType);
profile.setFingerPrint(fingerPrint);
ProfileFactory.saveToDao(profile);
}
Intent intent = new Intent(
Constraints.FINGER_PRINT_ACTION);
intent.putExtra(Constraints.FINGER_PRINT_ACTION_ACCEPT, true);
sendBroadcast(intent);
finish();
}
private void deny() {
Intent intent = new Intent(
Constraints.FINGER_PRINT_ACTION);
intent.putExtra(Constraints.FINGER_PRINT_ACTION_ACCEPT, false);
sendBroadcast(intent);
finish();
}
}
| Java |
package org.sshtunnel.db;
import java.util.List;
import org.sshtunnel.SSHTunnelContext;
import org.sshtunnel.utils.Constraints;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.preference.PreferenceManager;
import android.util.Log;
import com.j256.ormlite.android.apptools.OpenHelperManager;
import com.j256.ormlite.dao.Dao;
public class ProfileFactory {
private static Profile profile;
private static final String TAG = "SSHTunnelDB";
private static DatabaseHelper helper;
static {
OpenHelperManager.setOpenHelperClass(DatabaseHelper.class);
if (helper == null) {
helper = ((DatabaseHelper) OpenHelperManager
.getHelper(SSHTunnelContext.getAppContext()));
}
}
public static boolean delFromDao() {
try {
// try to remove profile from dao
Dao<Profile, Integer> profileDao = helper.getProfileDao();
int result = profileDao.delete(profile);
if (result != 1)
return false;
// reload the current profile
profile = getActiveProfile();
// ensure current profile is active
profile.setActive(true);
saveToDao();
return true;
} catch (Exception e) {
Log.e(TAG, "Cannot open DAO");
return false;
}
}
public static Profile getProfile() {
if (profile == null) {
initProfile();
}
return profile;
}
private static Profile getActiveProfile() {
try {
Dao<Profile, Integer> profileDao = helper.getProfileDao();
List<Profile> list = profileDao.queryForAll();
if (list == null || list.size() == 0)
return null;
Profile tmp = list.get(0);
for (Profile p : list) {
if (p.isActive) {
tmp = p;
break;
}
}
return tmp;
} catch (Exception e) {
Log.e(TAG, "Cannot open DAO");
return null;
}
}
private static void initProfile() {
profile = getActiveProfile();
if (profile == null) {
profile = new Profile();
profile.setActive(true);
saveToPreference();
saveToDao();
}
}
public static List<Profile> loadAllProfilesFromDao() {
try {
Dao<Profile, Integer> profileDao = helper.getProfileDao();
List<Profile> list = profileDao.queryForAll();
return list;
} catch (Exception e) {
Log.e(TAG, "Cannot open DAO");
}
return null;
}
public static void switchToProfile(int profileId) {
// current profile should not be null
if (profile == null)
return;
// first save any changes to dao
saveToDao();
// deactive all profiles
deactiveAllProfiles();
// query for new profile
Profile tmp = loadProfileFromDao(profileId);
if (tmp != null) {
profile = tmp;
saveToPreference();
}
profile.setActive(true);
saveToDao();
}
private static void deactiveAllProfiles() {
List<Profile> list = loadAllProfilesFromDao();
for (Profile p : list) {
p.setActive(false);
try {
Dao<Profile, Integer> profileDao = helper.getProfileDao();
profileDao.createOrUpdate(p);
} catch (Exception e) {
Log.e(TAG, "Cannot open DAO");
}
}
}
public static void loadFromPreference() {
SharedPreferences settings = PreferenceManager
.getDefaultSharedPreferences(SSHTunnelContext.getAppContext());
profile.name = settings.getString(Constraints.NAME, "");
profile.host = settings.getString(Constraints.HOST, "");
profile.user = settings.getString(Constraints.USER, "");
profile.password = settings.getString(Constraints.PASSWORD, "");
profile.remoteAddress = settings.getString(Constraints.REMOTE_ADDRESS,
Constraints.DEFAULT_REMOTE_ADDRESS);
profile.ssid = settings.getString(Constraints.SSID, "");
profile.proxyedApps = settings.getString(Constraints.PROXYED_APPS, "");
profile.keyPath = settings.getString(Constraints.KEY_PATH,
Constraints.DEFAULT_KEY_PATH);
profile.upstreamProxy = settings.getString(Constraints.UPSTREAM_PROXY, "");
profile.isAutoConnect = settings.getBoolean(
Constraints.IS_AUTO_CONNECT, false);
profile.isAutoReconnect = settings.getBoolean(
Constraints.IS_AUTO_RECONNECT, false);
profile.isAutoSetProxy = settings.getBoolean(
Constraints.IS_AUTO_SETPROXY, false);
profile.isSocks = settings.getBoolean(Constraints.IS_SOCKS, false);
profile.isGFWList = settings.getBoolean(Constraints.IS_GFW_LIST, false);
profile.isDNSProxy = settings
.getBoolean(Constraints.IS_DNS_PROXY, true);
profile.isUpstreamProxy = settings.getBoolean(Constraints.IS_UPSTREAM_PROXY, false);
try {
profile.port = Integer.valueOf(settings.getString(Constraints.PORT,
"22"));
profile.localPort = Integer.valueOf(settings.getString(
Constraints.LOCAL_PORT, "1984"));
profile.remotePort = Integer.valueOf(settings.getString(
Constraints.REMOTE_PORT, "3128"));
} catch (NumberFormatException e) {
Log.e(TAG, "Exception when get preferences");
profile = null;
return;
}
saveToDao();
}
public static Profile loadProfileFromDao(int profileId) {
try {
Dao<Profile, Integer> profileDao = helper.getProfileDao();
Profile mProfile = profileDao.queryForId(profileId);
return mProfile;
} catch (Exception e) {
Log.e(TAG, "Cannot open DAO");
}
return null;
}
public static void newProfile() {
profile = new Profile();
saveToDao();
}
public static void saveToDao() {
try {
Dao<Profile, Integer> profileDao = helper.getProfileDao();
profileDao.createOrUpdate(profile);
} catch (Exception e) {
Log.e(TAG, "Cannot open DAO");
}
}
public static void saveToDao(Profile mProfile) {
try {
Dao<Profile, Integer> profileDao = helper.getProfileDao();
profileDao.createOrUpdate(mProfile);
} catch (Exception e) {
Log.e(TAG, "Cannot open DAO");
}
}
public static void saveToPreference() {
if (profile == null)
return;
SharedPreferences settings = PreferenceManager
.getDefaultSharedPreferences(SSHTunnelContext.getAppContext());
Editor ed = settings.edit();
ed = settings.edit();
ed.putString(Constraints.NAME, profile.name);
ed.putString(Constraints.HOST, profile.host);
ed.putString(Constraints.USER, profile.user);
ed.putString(Constraints.PASSWORD, profile.password);
ed.putString(Constraints.REMOTE_ADDRESS, profile.remoteAddress);
ed.putString(Constraints.SSID, profile.ssid);
ed.putString(Constraints.KEY_PATH, profile.proxyedApps);
ed.putString(Constraints.KEY_PATH, profile.keyPath);
ed.putString(Constraints.UPSTREAM_PROXY, profile.upstreamProxy);
ed.putString(Constraints.PORT, Integer.toString(profile.port));
ed.putString(Constraints.LOCAL_PORT,
Integer.toString(profile.localPort));
ed.putString(Constraints.REMOTE_PORT,
Integer.toString(profile.remotePort));
ed.putBoolean(Constraints.IS_AUTO_CONNECT, profile.isAutoConnect);
ed.putBoolean(Constraints.IS_AUTO_RECONNECT, profile.isAutoReconnect);
ed.putBoolean(Constraints.IS_AUTO_SETPROXY, profile.isAutoSetProxy);
ed.putBoolean(Constraints.IS_SOCKS, profile.isSocks);
ed.putBoolean(Constraints.IS_GFW_LIST, profile.isGFWList);
ed.putBoolean(Constraints.IS_DNS_PROXY, profile.isDNSProxy);
ed.putBoolean(Constraints.IS_UPSTREAM_PROXY, profile.isUpstreamProxy);
ed.commit();
}
}
| Java |
package org.sshtunnel.db;
import java.sql.SQLException;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
/**
* Database helper class used to manage the creation and upgrading of your
* database. This class also usually provides the DAOs used by the other
* classes.
*/
public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
// name of the database file for your application -- change to something
// appropriate for your app
private static final String DATABASE_NAME = "sshtunnel.db";
// any time you make changes to your database objects, you may have to
// increase the database version
private static final int DATABASE_VERSION = 5;
// the DAO object we use to access the SimpleData table
private Dao<Profile, Integer> profileDao = null;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
/**
* Close the database connections and clear any cached DAOs.
*/
@Override
public void close() {
super.close();
profileDao = null;
}
/**
* Returns the Database Access Object (DAO) for our SimpleData class. It
* will create it or just give the cached value.
*/
public Dao<Profile, Integer> getProfileDao() throws SQLException {
if (profileDao == null) {
profileDao = getDao(Profile.class);
}
return profileDao;
}
/**
* This is called when the database is first created. Usually you should
* call createTable statements here to create the tables that will store
* your data.
*/
@Override
public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource) {
try {
Log.i(DatabaseHelper.class.getName(), "onCreate");
TableUtils.createTable(connectionSource, Profile.class);
} catch (SQLException e) {
Log.e(DatabaseHelper.class.getName(), "Can't create database", e);
throw new RuntimeException(e);
}
}
/**
* This is called when your application is upgraded and it has a higher
* version number. This allows you to adjust the various data to match the
* new version number.
*/
@Override
public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource,
int oldVersion, int newVersion) {
switch (oldVersion) {
case 1:
db.execSQL("ALTER TABLE Profile ADD COLUMN isDNSProxy BOOLEAN");
db.execSQL("UPDATE Profile SET isDNSProxy=1");
case 2:
db.execSQL("ALTER TABLE Profile ADD COLUMN isActive BOOLEAN");
db.execSQL("UPDATE Profile SET isActive=0");
case 3:
db.execSQL("ALTER TABLE Profile ADD COLUMN isUpstreamProxy BOOLEAN");
db.execSQL("UPDATE Profile SET isUpstreamProxy=0");
db.execSQL("ALTER TABLE Profile ADD COLUMN upstreamProxy VARCHAR");
db.execSQL("UPDATE Profile SET upstreamProxy=''");
case 4:
db.execSQL("ALTER TABLE Profile ADD COLUMN fingerPrint VARCHAR");
db.execSQL("UPDATE Profile SET fingerPrint=''");
db.execSQL("ALTER TABLE Profile ADD COLUMN fingerPrintType VARCHAR");
db.execSQL("UPDATE Profile SET fingerPrintType=''");
break;
default:
try {
Log.i(DatabaseHelper.class.getName(), "onUpgrade");
TableUtils.dropTable(connectionSource, Profile.class, true);
// after we drop the old databases, we create the new ones
onCreate(db, connectionSource);
} catch (SQLException e) {
Log.e(DatabaseHelper.class.getName(), "Can't drop databases", e);
throw new RuntimeException(e);
}
}
}
}
| Java |
/* sshtunnel - SSH Tunnel App for Android
* Copyright (C) 2011 Max Lv <max.c.lv@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* ___====-_ _-====___
* _--^^^#####// \\#####^^^--_
* _-^##########// ( ) \\##########^-_
* -############// |\^^/| \\############-
* _/############// (@::@) \\############\_
* /#############(( \\// ))#############\
* -###############\\ (oo) //###############-
* -#################\\ / VV \ //#################-
* -###################\\/ \//###################-
* _#/|##########/\######( /\ )######/\##########|\#_
* |/ |#/\#/\#/\/ \#/\##\ | | /##/\#/ \/\#/\#/\#| \|
* ` |/ V V ` V \#\| | | |/#/ V ' V V \| '
* ` ` ` ` / | | | | \ ' ' ' '
* ( | | | | )
* __\ | | | | /__
* (vvv(VVV)(VVV)vvv)
*
* HERE BE DRAGONS
*
*/
package org.sshtunnel;
import org.sshtunnel.db.Profile;
import org.sshtunnel.db.ProfileFactory;
import org.sshtunnel.utils.Constraints;
import org.sshtunnel.utils.Utils;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
public class SSHTunnelReceiver {
private static final String TAG = "SSHTunnelReceiver";
public void onReceive(Context context, Intent intent, boolean enable) {
Profile profile = ProfileFactory.getProfile();
ProfileFactory.loadFromPreference();
if (profile == null) {
Log.e(TAG, "Exception when get preferences");
return;
}
if (profile.isAutoConnect() || enable) {
Utils.notifyConnect();
Intent it = new Intent(context, SSHTunnelService.class);
Bundle bundle = new Bundle();
bundle.putInt(Constraints.ID, profile.getId());
it.putExtras(bundle);
context.startService(it);
}
}
}
| Java |
package org.sshtunnel;
import java.util.List;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class FileArrayAdapter extends ArrayAdapter<Option>{
private Context c;
private int id;
private List<Option>items;
public FileArrayAdapter(Context context, int textViewResourceId,
List<Option> objects) {
super(context, textViewResourceId, objects);
c = context;
id = textViewResourceId;
items = objects;
}
@Override
public Option getItem(int i)
{
return items.get(i);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater)c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(id, null);
}
final Option o = items.get(position);
if (o != null) {
TextView t1 = (TextView) v.findViewById(R.id.TextView01);
TextView t2 = (TextView) v.findViewById(R.id.TextView02);
if(t1!=null)
t1.setText(o.getName());
if(t2!=null)
t2.setText(o.getData());
}
return v;
}
}
| Java |
package org.sshtunnel;
import android.app.Application;
import android.content.Context;
public class SSHTunnelContext extends Application {
private static Context context;
public void onCreate() {
SSHTunnelContext.context = getApplicationContext();
}
public static Context getAppContext() {
return context;
}
}
| Java |
/* Copyright (c) 2009, Nathan Freitas, Orbot / The Guardian Project - http://openideals.com/guardian */
/* See LICENSE for licensing information */
package org.sshtunnel;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;
import java.util.Vector;
import org.sshtunnel.utils.Constraints;
import org.sshtunnel.utils.ProxyedApp;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class AppManager extends Activity implements OnCheckedChangeListener,
OnClickListener {
private static class ListEntry {
private CheckBox box;
private TextView text;
private ImageView icon;
}
public static ProxyedApp[] getProxyedApps(Context context,
String tordAppString) {
String[] tordApps;
StringTokenizer st = new StringTokenizer(tordAppString, "|");
tordApps = new String[st.countTokens()];
int tordIdx = 0;
while (st.hasMoreTokens()) {
tordApps[tordIdx++] = st.nextToken();
}
Arrays.sort(tordApps);
// else load the apps up
PackageManager pMgr = context.getPackageManager();
List<ApplicationInfo> lAppInfo = pMgr.getInstalledApplications(0);
Iterator<ApplicationInfo> itAppInfo = lAppInfo.iterator();
ProxyedApp[] apps = new ProxyedApp[lAppInfo.size()];
ApplicationInfo aInfo = null;
int appIdx = 0;
while (itAppInfo.hasNext()) {
aInfo = itAppInfo.next();
apps[appIdx] = new ProxyedApp();
apps[appIdx].setUid(aInfo.uid);
apps[appIdx].setUsername(pMgr.getNameForUid(apps[appIdx].getUid()));
// check if this application is allowed
if (Arrays.binarySearch(tordApps, apps[appIdx].getUsername()) >= 0) {
apps[appIdx].setProxyed(true);
} else {
apps[appIdx].setProxyed(false);
}
appIdx++;
}
return apps;
}
private ProxyedApp[] apps = null;
private ListView listApps;
private AppManager mAppManager;
private TextView overlay;
private ProgressDialog pd = null;
private ListAdapter adapter;
private ImageLoader dm;
private static final int MSG_LOAD_START = 1;
private static final int MSG_LOAD_FINISH = 2;
private boolean appsLoaded = false;
final Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_LOAD_START:
pd = ProgressDialog.show(AppManager.this, "",
getString(R.string.loading), true, true);
break;
case MSG_LOAD_FINISH:
listApps.setAdapter(adapter);
listApps.setOnScrollListener(new OnScrollListener() {
boolean visible;
@Override
public void onScroll(AbsListView view,
int firstVisibleItem, int visibleItemCount,
int totalItemCount) {
if (visible) {
String name = apps[firstVisibleItem].getName();
if (name != null && name.length() > 1)
overlay.setText(apps[firstVisibleItem]
.getName().substring(0, 1));
else
overlay.setText("*");
overlay.setVisibility(View.VISIBLE);
}
}
@Override
public void onScrollStateChanged(AbsListView view,
int scrollState) {
visible = true;
if (scrollState == ListView.OnScrollListener.SCROLL_STATE_IDLE) {
overlay.setVisibility(View.INVISIBLE);
}
}
});
if (pd != null) {
pd.dismiss();
pd = null;
}
break;
}
super.handleMessage(msg);
}
};
public void getApps(Context context) {
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(context);
String tordAppString = prefs.getString(Constraints.PROXYED_APPS, "");
String[] tordApps;
StringTokenizer st = new StringTokenizer(tordAppString, "|");
tordApps = new String[st.countTokens()];
int tordIdx = 0;
while (st.hasMoreTokens()) {
tordApps[tordIdx++] = st.nextToken();
}
Arrays.sort(tordApps);
Vector<ProxyedApp> vectorApps = new Vector<ProxyedApp>();
// else load the apps up
PackageManager pMgr = context.getPackageManager();
List<ApplicationInfo> lAppInfo = pMgr.getInstalledApplications(0);
Iterator<ApplicationInfo> itAppInfo = lAppInfo.iterator();
ApplicationInfo aInfo = null;
while (itAppInfo.hasNext()) {
aInfo = itAppInfo.next();
if (aInfo.processName == null)
continue;
if (pMgr.getApplicationLabel(aInfo) == null
|| pMgr.getApplicationLabel(aInfo).toString().equals(""))
continue;
if (pMgr.getApplicationIcon(aInfo) == null)
continue;
ProxyedApp tApp = new ProxyedApp();
tApp.setEnabled(aInfo.enabled);
tApp.setUid(aInfo.uid);
tApp.setUsername(pMgr.getNameForUid(tApp.getUid()));
tApp.setProcname(aInfo.processName);
tApp.setName(pMgr.getApplicationLabel(aInfo).toString());
// check if this application is allowed
if (Arrays.binarySearch(tordApps, tApp.getUsername()) >= 0) {
tApp.setProxyed(true);
} else {
tApp.setProxyed(false);
}
vectorApps.add(tApp);
}
apps = new ProxyedApp[lAppInfo.size()];
vectorApps.toArray(apps);
}
private void loadApps() {
getApps(this);
Arrays.sort(apps, new Comparator<ProxyedApp>() {
@Override
public int compare(ProxyedApp o1, ProxyedApp o2) {
if (o1 == null || o2 == null)
return 1;
if (o1.isProxyed() == o2.isProxyed())
return o1.getName().compareTo(o2.getName());
if (o1.isProxyed())
return -1;
return 1;
}
});
final LayoutInflater inflater = getLayoutInflater();
adapter = new ArrayAdapter<ProxyedApp>(this, R.layout.layout_apps_item,
R.id.itemtext, apps) {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ListEntry entry;
if (convertView == null) {
// Inflate a new view
convertView = inflater.inflate(R.layout.layout_apps_item,
parent, false);
entry = new ListEntry();
entry.icon = (ImageView) convertView
.findViewById(R.id.itemicon);
entry.box = (CheckBox) convertView
.findViewById(R.id.itemcheck);
entry.text = (TextView) convertView
.findViewById(R.id.itemtext);
entry.text.setOnClickListener(mAppManager);
convertView.setTag(entry);
entry.box.setOnCheckedChangeListener(mAppManager);
} else {
// Convert an existing view
entry = (ListEntry) convertView.getTag();
}
final ProxyedApp app = apps[position];
entry.icon.setTag(app.getUid());
dm.DisplayImage(app.getUid(),
(Activity) convertView.getContext(), entry.icon);
entry.text.setText(app.getName());
final CheckBox box = entry.box;
box.setTag(app);
box.setChecked(app.isProxyed());
entry.text.setTag(box);
return convertView;
}
};
appsLoaded = true;
}
/**
* Called an application is check/unchecked
*/
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
final ProxyedApp app = (ProxyedApp) buttonView.getTag();
if (app != null) {
app.setProxyed(isChecked);
}
saveAppSettings(this);
}
@Override
public void onClick(View v) {
CheckBox cbox = (CheckBox) v.getTag();
final ProxyedApp app = (ProxyedApp) cbox.getTag();
if (app != null) {
app.setProxyed(!app.isProxyed());
cbox.setChecked(app.isProxyed());
}
saveAppSettings(this);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.layout_apps);
dm = ImageLoaderFactory.getImageLoader(this);
this.overlay = (TextView) View.inflate(this, R.layout.overlay, null);
getWindowManager()
.addView(
overlay,
new WindowManager.LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_APPLICATION,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
PixelFormat.TRANSLUCENT));
mAppManager = this;
}
@Override
protected void onResume() {
super.onResume();
new Thread() {
@Override
public void run() {
handler.sendEmptyMessage(MSG_LOAD_START);
listApps = (ListView) findViewById(R.id.applistview);
if (!appsLoaded)
loadApps();
handler.sendEmptyMessage(MSG_LOAD_FINISH);
}
}.start();
}
/*
* (non-Javadoc)
*
* @see android.app.Activity#onStop()
*/
@Override
protected void onStop() {
super.onStop();
// Log.d(getClass().getName(),"Exiting Preferences");
}
public void saveAppSettings(Context context) {
if (apps == null)
return;
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(this);
StringBuilder tordApps = new StringBuilder();
for (int i = 0; i < apps.length; i++) {
if (apps[i].isProxyed()) {
tordApps.append(apps[i].getUsername());
tordApps.append("|");
}
}
Editor edit = prefs.edit();
edit.putString(Constraints.PROXYED_APPS, tordApps.toString());
edit.commit();
}
}
| Java |
// dbartists - Douban artists client for Android
// Copyright (C) 2011 Max Lv <max.c.lv@gmail.com>
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy
// of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations
// under the License.
//
//
// ___====-_ _-====___
// _--^^^#####// \\#####^^^--_
// _-^##########// ( ) \\##########^-_
// -############// |\^^/| \\############-
// _/############// (@::@) \\############\_
// /#############(( \\// ))#############\
// -###############\\ (oo) //###############-
// -#################\\ / VV \ //#################-
// -###################\\/ \//###################-
// _#/|##########/\######( /\ )######/\##########|\#_
// |/ |#/\#/\#/\/ \#/\##\ | | /##/\#/ \/\#/\#/\#| \|
// ` |/ V V ` V \#\| | | |/#/ V ' V V \| '
// ` ` ` ` / | | | | \ ' ' ' '
// ( | | | | )
// __\ | | | | /__
// (vvv(VVV)(VVV)vvv)
//
// HERE BE DRAGONS
package org.sshtunnel;
import android.content.Context;
public class ImageLoaderFactory {
private static ImageLoader il = null;
public static ImageLoader getImageLoader(Context context) {
if (il == null) {
il = new ImageLoader(context);
}
return il;
}
}
| Java |
package net.sourceforge.jsocks;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.io.PrintStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import net.sourceforge.jsocks.server.ServerAuthenticator;
/**
* UDP Relay server, used by ProxyServer to perform udp forwarding.
*/
class UDPRelayServer implements Runnable {
DatagramSocket client_sock;
DatagramSocket remote_sock;
Socket controlConnection;
int relayPort;
InetAddress relayIP;
Thread pipe_thread1, pipe_thread2;
Thread master_thread;
ServerAuthenticator auth;
long lastReadTime;
static PrintStream log = null;
static Proxy proxy = null;
static int datagramSize = 0xFFFF;// 64K, a bit more than max udp size
static int iddleTimeout = 180000;// 3 minutes
static private void log(String s) {
if (log != null) {
log.println(s);
log.flush();
}
}
// Public methods
// ///////////////
/**
* Sets the size of the datagrams used in the UDPRelayServer.<br>
* Default size is 64K, a bit more than maximum possible size of the
* datagram.
*/
static public void setDatagramSize(int size) {
datagramSize = size;
}
/**
* Sets the timeout for UDPRelay server.<br>
* Zero timeout implies infinity.<br>
* Default timeout is 3 minutes.
*/
static public void setTimeout(int timeout) {
iddleTimeout = timeout;
}
/**
* Constructs UDP relay server to communicate with client on given ip and
* port.
*
* @param clientIP
* Address of the client from whom datagrams will be recieved and
* to whom they will be forwarded.
* @param clientPort
* Clients port.
* @param master_thread
* Thread which will be interrupted, when UDP relay server
* stoppes for some reason.
* @param controlConnection
* Socket which will be closed, before interrupting the master
* thread, it is introduced due to a bug in windows JVM which
* does not throw InterruptedIOException in threads which block
* in I/O operation.
*/
public UDPRelayServer(InetAddress clientIP, int clientPort,
Thread master_thread, Socket controlConnection,
ServerAuthenticator auth) throws IOException {
this.master_thread = master_thread;
this.controlConnection = controlConnection;
this.auth = auth;
client_sock = new Socks5DatagramSocket(true,
auth.getUdpEncapsulation(), clientIP, clientPort);
relayPort = client_sock.getLocalPort();
relayIP = client_sock.getLocalAddress();
if (relayIP.getHostAddress().equals("0.0.0.0"))
relayIP = InetAddress.getLocalHost();
if (proxy == null)
remote_sock = new DatagramSocket();
else
remote_sock = new Socks5DatagramSocket(proxy, 0, null);
}
// Private methods
// ///////////////
private synchronized void abort() {
if (pipe_thread1 == null)
return;
log("Aborting UDP Relay Server");
remote_sock.close();
client_sock.close();
if (controlConnection != null)
try {
controlConnection.close();
} catch (IOException ioe) {
}
if (master_thread != null)
master_thread.interrupt();
pipe_thread1.interrupt();
pipe_thread2.interrupt();
pipe_thread1 = null;
}
/**
* IP address to which client should send datagrams for association.
*/
public InetAddress getRelayIP() {
return relayIP;
}
/**
* Port to which client should send datagram for association.
*/
public int getRelayPort() {
return relayPort;
}
private void pipe(DatagramSocket from, DatagramSocket to, boolean out)
throws IOException {
byte[] data = new byte[datagramSize];
DatagramPacket dp = new DatagramPacket(data, data.length);
while (true) {
try {
from.receive(dp);
lastReadTime = System.currentTimeMillis();
if (auth.checkRequest(dp, out))
to.send(dp);
} catch (UnknownHostException uhe) {
log("Dropping datagram for unknown host");
} catch (InterruptedIOException iioe) {
// log("Interrupted: "+iioe);
// If we were interrupted by other thread.
if (iddleTimeout == 0)
return;
// If last datagram was received, long time ago, return.
long timeSinceRead = System.currentTimeMillis() - lastReadTime;
if (timeSinceRead >= iddleTimeout - 100) // -100 for adjustment
return;
}
dp.setLength(data.length);
}
}
// Runnable interface
// //////////////////
@Override
public void run() {
try {
if (Thread.currentThread().getName().equals("pipe1"))
pipe(remote_sock, client_sock, false);
else
pipe(client_sock, remote_sock, true);
} catch (IOException ioe) {
} finally {
abort();
log("UDP Pipe thread " + Thread.currentThread().getName()
+ " stopped.");
}
}
/**
* Starts udp relay server. Spawns two threads of execution and returns.
*/
public void start() throws IOException {
remote_sock.setSoTimeout(iddleTimeout);
client_sock.setSoTimeout(iddleTimeout);
log("Starting UDP relay server on " + relayIP + ":" + relayPort);
log("Remote socket " + remote_sock.getLocalAddress() + ":"
+ remote_sock.getLocalPort());
pipe_thread1 = new Thread(this, "pipe1");
pipe_thread2 = new Thread(this, "pipe2");
lastReadTime = System.currentTimeMillis();
pipe_thread1.start();
pipe_thread2.start();
}
/**
* Stops Relay server.
* <p>
* Does not close control connection, does not interrupt master_thread.
*/
public synchronized void stop() {
master_thread = null;
controlConnection = null;
abort();
}
}
| Java |
package net.sourceforge.jsocks;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
/**
* Proxy which describes SOCKS4 proxy.
*/
public class Socks4Proxy extends Proxy implements Cloneable {
// Data members
String user;
// Public Constructors
// ====================
/**
* Creates the SOCKS4 proxy
*
* @param proxyIP
* Address of the proxy server.
* @param proxyPort
* Port of the proxy server
* @param user
* User name to use for identification purposes.
*/
public Socks4Proxy(InetAddress proxyIP, int proxyPort, String user) {
this(null, proxyIP, proxyPort, user);
}
/**
* Creates the SOCKS4 proxy
*
* @param p
* Proxy to use to connect to this proxy, allows proxy chaining.
* @param proxyIP
* Address of the proxy server.
* @param proxyPort
* Port of the proxy server
* @param user
* User name to use for identification purposes.
*/
public Socks4Proxy(Proxy p, InetAddress proxyIP, int proxyPort, String user) {
super(p, proxyIP, proxyPort);
this.user = new String(user);
version = 4;
}
/**
* Creates the SOCKS4 proxy
*
* @param p
* Proxy to use to connect to this proxy, allows proxy chaining.
* @param proxyHost
* Address of the proxy server.
* @param proxyPort
* Port of the proxy server
* @param user
* User name to use for identification purposes.
* @throws UnknownHostException
* If proxyHost can't be resolved.
*/
public Socks4Proxy(String proxyHost, int proxyPort, String user)
throws UnknownHostException {
super(proxyHost, proxyPort);
this.user = new String(user);
version = 4;
}
// Public instance methods
// ========================
/**
* Creates a clone of this proxy. Changes made to the clone should not
* affect this object.
*/
@Override
public Object clone() {
Socks4Proxy newProxy = new Socks4Proxy(proxyIP, proxyPort, user);
newProxy.chainProxy = chainProxy;
return newProxy;
}
// Public Static(Class) Methods
// ==============================
// Protected Methods
// =================
@Override
protected Proxy copy() {
Socks4Proxy copy = new Socks4Proxy(proxyIP, proxyPort, user);
copy.chainProxy = chainProxy;
return copy;
}
@Override
protected ProxyMessage formMessage(InputStream in) throws SocksException,
IOException {
return new Socks4Message(in, true);
}
@Override
protected ProxyMessage formMessage(int cmd, InetAddress ip, int port) {
switch (cmd) {
case SOCKS_CMD_CONNECT:
cmd = Socks4Message.REQUEST_CONNECT;
break;
case SOCKS_CMD_BIND:
cmd = Socks4Message.REQUEST_BIND;
break;
default:
return null;
}
return new Socks4Message(cmd, ip, port, user);
}
@Override
protected ProxyMessage formMessage(int cmd, String host, int port)
throws UnknownHostException {
return formMessage(cmd, InetAddress.getByName(host), port);
}
}
| Java |
package net.sourceforge.jsocks;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
/**
* SOCKS5 request/response message.
*/
public class Socks5Message extends ProxyMessage {
/** Address type of given message */
public int addrType;
byte[] data;
// SOCKS5 constants
public static final int SOCKS_VERSION = 5;
public static final int SOCKS_ATYP_IPV4 = 0x1; // Where is 2??
public static final int SOCKS_ATYP_DOMAINNAME = 0x3; // !!!!rfc1928
public static final int SOCKS_ATYP_IPV6 = 0x4;
public static final int SOCKS_IPV6_LENGTH = 16;
static boolean doResolveIP = true;
/**
* Wether to resolve hostIP returned from SOCKS server that is wether to
* create InetAddress object from the hostName string
*/
static public boolean resolveIP() {
return doResolveIP;
}
/**
* Wether to resolve hostIP returned from SOCKS server that is wether to
* create InetAddress object from the hostName string
*
* @param doResolve
* Wether to resolve hostIP from SOCKS server.
* @return Previous value.
*/
static public boolean resolveIP(boolean doResolve) {
boolean old = doResolveIP;
doResolveIP = doResolve;
return old;
}
/**
* Initialises Message from the stream. Reads server response from given
* stream.
*
* @param in
* Input stream to read response from.
* @throws SocksException
* If server response code is not SOCKS_SUCCESS(0), or if any
* error with protocol occurs.
* @throws IOException
* If any error happens with I/O.
*/
public Socks5Message(InputStream in) throws SocksException, IOException {
this(in, true);
}
/**
* Initialises Message from the stream. Reads server response or client
* request from given stream.
*
* @param in
* Input stream to read response from.
* @param clinetMode
* If true read server response, else read client request.
* @throws SocksException
* If server response code is not SOCKS_SUCCESS(0) and reading
* in client mode, or if any error with protocol occurs.
* @throws IOException
* If any error happens with I/O.
*/
public Socks5Message(InputStream in, boolean clientMode)
throws SocksException, IOException {
read(in, clientMode);
}
/**
* Server error response.
*
* @param cmd
* Error code.
*/
public Socks5Message(int cmd) {
super(cmd, null, 0);
data = new byte[3];
data[0] = SOCKS_VERSION; // Version.
data[1] = (byte) cmd; // Reply code for some kind of failure.
data[2] = 0; // Reserved byte.
}
/**
* Construct client request or server response.
*
* @param cmd
* - Request/Response code.
* @param ip
* - IP field.
* @paarm port - port field.
*/
public Socks5Message(int cmd, InetAddress ip, int port) {
super(cmd, ip, port);
this.host = ip == null ? "0.0.0.0" : ip.getHostName();
this.version = SOCKS_VERSION;
byte[] addr;
if (ip == null) {
addr = new byte[4];
addr[0] = addr[1] = addr[2] = addr[3] = 0;
} else
addr = ip.getAddress();
addrType = addr.length == 4 ? SOCKS_ATYP_IPV4 : SOCKS_ATYP_IPV6;
data = new byte[6 + addr.length];
data[0] = (byte) SOCKS_VERSION; // Version
data[1] = (byte) command; // Command
data[2] = (byte) 0; // Reserved byte
data[3] = (byte) addrType; // Address type
// Put Address
System.arraycopy(addr, 0, data, 4, addr.length);
// Put port
data[data.length - 2] = (byte) (port >> 8);
data[data.length - 1] = (byte) (port);
}
/*
* private static final void debug(String s){ if(DEBUG) System.out.print(s);
* } private static final boolean DEBUG = false;
*/
/**
* Construct client request or server response.
*
* @param cmd
* - Request/Response code.
* @param hostName
* - IP field as hostName, uses ADDR_TYPE of HOSTNAME.
* @paarm port - port field.
*/
public Socks5Message(int cmd, String hostName, int port) {
super(cmd, null, port);
this.host = hostName;
this.version = SOCKS_VERSION;
// System.out.println("Doing ATYP_DOMAINNAME");
addrType = SOCKS_ATYP_DOMAINNAME;
byte addr[] = hostName.getBytes();
data = new byte[7 + addr.length];
data[0] = (byte) SOCKS_VERSION; // Version
data[1] = (byte) command; // Command
data[2] = (byte) 0; // Reserved byte
data[3] = (byte) SOCKS_ATYP_DOMAINNAME; // Address type
data[4] = (byte) addr.length; // Length of the address
// Put Address
System.arraycopy(addr, 0, data, 5, addr.length);
// Put port
data[data.length - 2] = (byte) (port >> 8);
data[data.length - 1] = (byte) (port);
}
/**
* Returns IP field of the message as IP, if the message was created with
* ATYP of HOSTNAME, it will attempt to resolve the hostname, which might
* fail.
*
* @throws UnknownHostException
* if host can't be resolved.
*/
@Override
public InetAddress getInetAddress() throws UnknownHostException {
if (ip != null)
return ip;
return (ip = InetAddress.getByName(host));
}
/**
* Initialises Message from the stream. Reads server response from given
* stream.
*
* @param in
* Input stream to read response from.
* @throws SocksException
* If server response code is not SOCKS_SUCCESS(0), or if any
* error with protocol occurs.
* @throws IOException
* If any error happens with I/O.
*/
@Override
public void read(InputStream in) throws SocksException, IOException {
read(in, true);
}
/**
* Initialises Message from the stream. Reads server response or client
* request from given stream.
*
* @param in
* Input stream to read response from.
* @param clinetMode
* If true read server response, else read client request.
* @throws SocksException
* If server response code is not SOCKS_SUCCESS(0) and reading
* in client mode, or if any error with protocol occurs.
* @throws IOException
* If any error happens with I/O.
*/
@Override
public void read(InputStream in, boolean clientMode) throws SocksException,
IOException {
data = null;
ip = null;
DataInputStream di = new DataInputStream(in);
version = di.readUnsignedByte();
command = di.readUnsignedByte();
if (clientMode && command != 0)
throw new SocksException(command);
@SuppressWarnings("unused")
int reserved = di.readUnsignedByte();
addrType = di.readUnsignedByte();
byte addr[];
switch (addrType) {
case SOCKS_ATYP_IPV4:
addr = new byte[4];
di.readFully(addr);
host = bytes2IPV4(addr, 0);
break;
case SOCKS_ATYP_IPV6:
addr = new byte[SOCKS_IPV6_LENGTH];// I believe it is 16 bytes,huge!
di.readFully(addr);
host = bytes2IPV6(addr, 0);
break;
case SOCKS_ATYP_DOMAINNAME:
// System.out.println("Reading ATYP_DOMAINNAME");
addr = new byte[di.readUnsignedByte()];// Next byte shows the length
di.readFully(addr);
host = new String(addr);
break;
default:
throw (new SocksException(Proxy.SOCKS_JUST_ERROR));
}
port = di.readUnsignedShort();
if (addrType != SOCKS_ATYP_DOMAINNAME && doResolveIP) {
try {
ip = InetAddress.getByName(host);
} catch (UnknownHostException uh_ex) {
}
}
}
/**
* Returns string representation of the message.
*/
@Override
public String toString() {
String s = "Socks5Message:" + "\n" + "VN " + version + "\n" + "CMD "
+ command + "\n" + "ATYP " + addrType + "\n" + "ADDR " + host
+ "\n" + "PORT " + port + "\n";
return s;
}
/**
* Writes the message to the stream.
*
* @param out
* Output stream to which message should be written.
*/
@Override
public void write(OutputStream out) throws SocksException, IOException {
if (data == null) {
Socks5Message msg;
if (addrType == SOCKS_ATYP_DOMAINNAME)
msg = new Socks5Message(command, host, port);
else {
if (ip == null) {
try {
ip = InetAddress.getByName(host);
} catch (UnknownHostException uh_ex) {
throw new SocksException(Proxy.SOCKS_JUST_ERROR);
}
}
msg = new Socks5Message(command, ip, port);
}
data = msg.data;
}
out.write(data);
}
}
| Java |
package net.sourceforge.jsocks;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
/**
* SOCKS4 Reply/Request message.
*/
public class Socks4Message extends ProxyMessage {
private byte[] msgBytes;
private int msgLength;
static final String[] replyMessage = { "Request Granted",
"Request Rejected or Failed",
"Failed request, can't connect to Identd",
"Failed request, bad user name" };
static final int SOCKS_VERSION = 4;
public final static int REQUEST_CONNECT = 1;
public final static int REQUEST_BIND = 2;
public final static int REPLY_OK = 90;
public final static int REPLY_REJECTED = 91;
public final static int REPLY_NO_CONNECT = 92;
public final static int REPLY_BAD_IDENTD = 93;
// Class methods
static InetAddress bytes2IP(byte[] addr) {
String s = bytes2IPV4(addr, 0);
try {
return InetAddress.getByName(s);
} catch (UnknownHostException uh_ex) {
return null;
}
}
// Constants
/**
* Initialise from the stream If clientMode is true attempts to read a
* server response otherwise reads a client request see read for more detail
*/
public Socks4Message(InputStream in, boolean clientMode) throws IOException {
msgBytes = null;
read(in, clientMode);
}
/**
* Server failed reply, cmd command for failed request
*/
public Socks4Message(int cmd) {
super(cmd, null, 0);
this.user = null;
msgLength = 2;
msgBytes = new byte[2];
msgBytes[0] = (byte) 0;
msgBytes[1] = (byte) command;
}
/**
* Server successfull reply
*/
public Socks4Message(int cmd, InetAddress ip, int port) {
this(0, cmd, ip, port, null);
}
/**
* Client request
*/
public Socks4Message(int cmd, InetAddress ip, int port, String user) {
this(SOCKS_VERSION, cmd, ip, port, user);
}
/**
* Most general constructor
*/
public Socks4Message(int version, int cmd, InetAddress ip, int port,
String user) {
super(cmd, ip, port);
this.user = user;
this.version = version;
msgLength = user == null ? 8 : 9 + user.length();
msgBytes = new byte[msgLength];
msgBytes[0] = (byte) version;
msgBytes[1] = (byte) command;
msgBytes[2] = (byte) (port >> 8);
msgBytes[3] = (byte) port;
byte[] addr;
if (ip != null)
addr = ip.getAddress();
else {
addr = new byte[4];
addr[0] = addr[1] = addr[2] = addr[3] = 0;
}
System.arraycopy(addr, 0, msgBytes, 4, 4);
if (user != null) {
byte[] buf = user.getBytes();
System.arraycopy(buf, 0, msgBytes, 8, buf.length);
msgBytes[msgBytes.length - 1] = 0;
}
}
@Override
public void read(InputStream in) throws IOException {
read(in, true);
}
@Override
public void read(InputStream in, boolean clientMode) throws IOException {
boolean mode4a = false;
DataInputStream d_in = new DataInputStream(in);
version = d_in.readUnsignedByte();
command = d_in.readUnsignedByte();
if (clientMode && command != REPLY_OK) {
String errMsg;
if (command > REPLY_OK && command < REPLY_BAD_IDENTD)
errMsg = replyMessage[command - REPLY_OK];
else
errMsg = "Unknown Reply Code";
throw new SocksException(command, errMsg);
}
port = d_in.readUnsignedShort();
byte[] addr = new byte[4];
d_in.readFully(addr);
if (addr[0] == 0 && addr[1] == 0 && addr[2] == 0 && addr[3] != 0)
mode4a = true;
else {
ip = bytes2IP(addr);
host = ip.getHostName();
}
if (!clientMode) {
StringBuilder sb = new StringBuilder();
int b;
while ((b = in.read()) != 0)
sb.append((char) b);
user = sb.toString();
if (mode4a) {
sb.setLength(0);
while ((b = in.read()) != 0)
sb.append((char) b);
host = sb.toString();
}
}
}
@Override
public void write(OutputStream out) throws IOException {
if (msgBytes == null) {
Socks4Message msg = new Socks4Message(version, command, ip, port,
user);
msgBytes = msg.msgBytes;
msgLength = msg.msgLength;
}
out.write(msgBytes);
}
}
| Java |
package net.sourceforge.jsocks;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
/**
* Abstract class which describes SOCKS4/5 response/request.
*/
public abstract class ProxyMessage {
static final String bytes2IPV4(byte[] addr, int offset) {
String hostName = "" + (addr[offset] & 0xFF);
for (int i = offset + 1; i < offset + 4; ++i)
hostName += "." + (addr[i] & 0xFF);
return hostName;
}
static final String bytes2IPV6(byte[] addr, int offset) {
// Have no idea how they look like!
return null;
}
/** Host as an IP address */
public InetAddress ip = null;
/** SOCKS version, or version of the response for SOCKS4 */
public int version;
/** Port field of the request/response */
public int port;
/** Request/response code as an int */
public int command;
/** Host as string. */
public String host = null;
/** User field for SOCKS4 request messages */
public String user = null;
ProxyMessage() {
}
ProxyMessage(int command, InetAddress ip, int port) {
this.command = command;
this.ip = ip;
this.port = port;
}
/**
* Get the Address field of this message as InetAddress object.
*
* @return Host address or null, if one can't be determined.
*/
public InetAddress getInetAddress() throws UnknownHostException {
return ip;
}
/**
* Initialises Message from the stream. Reads server response from given
* stream.
*
* @param in
* Input stream to read response from.
* @throws SocksException
* If server response code is not SOCKS_SUCCESS(0), or if any
* error with protocol occurs.
* @throws IOException
* If any error happens with I/O.
*/
public abstract void read(InputStream in) throws SocksException,
IOException;
/**
* Initialises Message from the stream. Reads server response or client
* request from given stream.
*
* @param in
* Input stream to read response from.
* @param clinetMode
* If true read server response, else read client request.
* @throws SocksException
* If server response code is not SOCKS_SUCCESS(0) and reading
* in client mode, or if any error with protocol occurs.
* @throws IOException
* If any error happens with I/O.
*/
public abstract void read(InputStream in, boolean client_mode)
throws SocksException, IOException;
// Package methods
// ////////////////
/**
* Get string representaion of this message.
*
* @return string representation of this message.
*/
@Override
public String toString() {
return "Proxy Message:\n" + "Version:" + version + "\n" + "Command:"
+ command + "\n" + "IP: " + ip + "\n" + "Port: " + port
+ "\n" + "User: " + user + "\n";
}
/**
* Writes the message to the stream.
*
* @param out
* Output stream to which message should be written.
*/
public abstract void write(OutputStream out) throws SocksException,
IOException;
}
| Java |
package net.sourceforge.jsocks;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;
import java.util.Hashtable;
/**
* SOCKS5 Proxy.
*/
public class Socks5Proxy extends Proxy implements Cloneable {
// Data members
private Hashtable<Integer, Authentication> authMethods = new Hashtable<Integer, Authentication>();
private int selectedMethod;
boolean resolveAddrLocally = true;
UDPEncapsulation udp_encapsulation = null;
// Public Constructors
// ====================
/**
* Creates SOCKS5 proxy.
*
* @param proxyIP
* Host on which a Proxy server runs.
* @param proxyPort
* Port on which a Proxy server listens for connections.
*/
public Socks5Proxy(InetAddress proxyIP, int proxyPort) {
super(proxyIP, proxyPort);
version = 5;
setAuthenticationMethod(0, new AuthenticationNone());
}
/**
* Creates SOCKS5 proxy.
*
* @param proxyHost
* Host on which a Proxy server runs.
* @param proxyPort
* Port on which a Proxy server listens for connections.
* @throws UnknownHostException
* If proxyHost can't be resolved.
*/
public Socks5Proxy(String proxyHost, int proxyPort)
throws UnknownHostException {
super(proxyHost, proxyPort);
version = 5;
setAuthenticationMethod(0, new AuthenticationNone());
}
// Public instance methods
// ========================
/**
* Creates a clone of this Proxy.
*/
@Override
@SuppressWarnings("unchecked")
public Object clone() {
Socks5Proxy newProxy = new Socks5Proxy(proxyIP, proxyPort);
newProxy.authMethods = (Hashtable<Integer, Authentication>) this.authMethods
.clone();
newProxy.resolveAddrLocally = resolveAddrLocally;
newProxy.chainProxy = chainProxy;
return newProxy;
}
@Override
protected Proxy copy() {
Socks5Proxy copy = new Socks5Proxy(proxyIP, proxyPort);
copy.authMethods = this.authMethods; // same Hash, no copy
copy.chainProxy = this.chainProxy;
copy.resolveAddrLocally = this.resolveAddrLocally;
return copy;
}
@Override
protected ProxyMessage formMessage(InputStream in) throws SocksException,
IOException {
return new Socks5Message(in);
}
@Override
protected ProxyMessage formMessage(int cmd, InetAddress ip, int port) {
return new Socks5Message(cmd, ip, port);
}
@Override
protected ProxyMessage formMessage(int cmd, String host, int port)
throws UnknownHostException {
if (resolveAddrLocally)
return formMessage(cmd, InetAddress.getByName(host), port);
else
return new Socks5Message(cmd, host, port);
}
// Public Static(Class) Methods
// ==============================
// Protected Methods
// =================
/**
* Get authentication method, which corresponds to given method id
*
* @param methodId
* Authentication method id.
* @return Implementation for given method or null, if one was not set.
*/
public Authentication getAuthenticationMethod(int methodId) {
Object method = authMethods.get(new Integer(methodId));
if (method == null)
return null;
return (Authentication) method;
}
/**
* Get current setting on how the addresses should be handled.
*
* @return Current setting for address resolution.
* @see Socks5Proxy#resolveAddrLocally(boolean doResolve)
*/
public boolean resolveAddrLocally() {
return resolveAddrLocally;
}
/**
* Wether to resolve address locally or to let proxy do so.
* <p>
* SOCKS5 protocol allows to send host names rather then IPs in the
* requests, this option controls wether the hostnames should be send to the
* proxy server as names, or should they be resolved locally.
*
* @param doResolve
* Wether to perform resolution locally.
* @return Previous settings.
*/
public boolean resolveAddrLocally(boolean doResolve) {
boolean old = resolveAddrLocally;
resolveAddrLocally = doResolve;
return old;
}
/**
* Adds another authentication method.
*
* @param methodId
* Authentication method id, see rfc1928
* @param method
* Implementation of Authentication
* @see Authentication
*/
public boolean setAuthenticationMethod(int methodId, Authentication method) {
if (methodId < 0 || methodId > 255)
return false;
if (method == null) {
// Want to remove a particular method
return (authMethods.remove(new Integer(methodId)) != null);
} else {// Add the method, or rewrite old one
authMethods.put(new Integer(methodId), method);
}
return true;
}
/**
*
*
*/
@Override
protected void startSession() throws SocksException {
super.startSession();
Authentication auth;
Socket ps = proxySocket; // The name is too long
try {
byte nMethods = (byte) authMethods.size(); // Number of methods
byte[] buf = new byte[2 + nMethods]; // 2 is for VER,NMETHODS
buf[0] = (byte) version;
buf[1] = nMethods; // Number of methods
int i = 2;
Enumeration<Integer> ids = authMethods.keys();
while (ids.hasMoreElements())
buf[i++] = (byte) ids.nextElement().intValue();
out.write(buf);
out.flush();
int versionNumber = in.read();
selectedMethod = in.read();
if (versionNumber < 0 || selectedMethod < 0) {
// EOF condition was reached
endSession();
throw (new SocksException(SOCKS_PROXY_IO_ERROR,
"Connection to proxy lost."));
}
if (versionNumber < version) {
// What should we do??
}
if (selectedMethod == 0xFF) { // No method selected
ps.close();
throw (new SocksException(SOCKS_AUTH_NOT_SUPPORTED));
}
auth = getAuthenticationMethod(selectedMethod);
if (auth == null) {
// This shouldn't happen, unless method was removed by other
// thread, or the server stuffed up
throw (new SocksException(SOCKS_JUST_ERROR,
"Speciefied Authentication not found!"));
}
Object[] in_out = auth.doSocksAuthentication(selectedMethod, ps);
if (in_out == null) {
// Authentication failed by some reason
throw (new SocksException(SOCKS_AUTH_FAILURE));
}
// Most authentication methods are expected to return
// simply the input/output streams associated with
// the socket. However if the auth. method requires
// some kind of encryption/decryption being done on the
// connection it should provide classes to handle I/O.
in = (InputStream) in_out[0];
out = (OutputStream) in_out[1];
if (in_out.length > 2)
udp_encapsulation = (UDPEncapsulation) in_out[2];
} catch (SocksException s_ex) {
throw s_ex;
} catch (UnknownHostException uh_ex) {
throw (new SocksException(SOCKS_PROXY_NO_CONNECT));
} catch (SocketException so_ex) {
throw (new SocksException(SOCKS_PROXY_NO_CONNECT));
} catch (IOException io_ex) {
// System.err.println(io_ex);
throw (new SocksException(SOCKS_PROXY_IO_ERROR, "" + io_ex));
}
}
}
| Java |
package net.sourceforge.jsocks;
/**
* The Authentication interface provides for performing method specific
* authentication for SOCKS5 connections.
*/
public interface Authentication {
/**
* This method is called when SOCKS5 server have selected a particular
* authentication method, for whch an implementaion have been registered.
*
* <p>
* This method should return an array {inputstream,outputstream
* [,UDPEncapsulation]}. The reason for that is that SOCKS5 protocol allows
* to have method specific encapsulation of data on the socket for purposes
* of integrity or security. And this encapsulation should be performed by
* those streams returned from the method. It is also possible to
* encapsulate datagrams. If authentication method supports such
* encapsulation an instance of the UDPEncapsulation interface should be
* returned as third element of the array, otherwise either null should be
* returned as third element, or array should contain only 2 elements.
*
* @param methodId
* Authentication method selected by the server.
* @param proxySocket
* Socket used to conect to the proxy.
* @return Two or three element array containing Input/Output streams which
* should be used on this connection. Third argument is optional and
* should contain an instance of UDPEncapsulation. It should be
* provided if the authentication method used requires any
* encapsulation to be done on the datagrams.
*/
Object[] doSocksAuthentication(int methodId, java.net.Socket proxySocket)
throws java.io.IOException;
}
| Java |
package net.sourceforge.jsocks;
/**
* SOCKS5 none authentication. Dummy class does almost nothing.
*/
public class AuthenticationNone implements Authentication {
@Override
public Object[] doSocksAuthentication(int methodId,
java.net.Socket proxySocket) throws java.io.IOException {
if (methodId != 0)
return null;
return new Object[] { proxySocket.getInputStream(),
proxySocket.getOutputStream() };
}
}
| Java |
package net.sourceforge.jsocks;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
/**
* SocksSocket tryies to look very similar to normal Socket, while allowing
* connections through the SOCKS4 or 5 proxy. To use this class you will have to
* identify proxy you need to use, Proxy class allows you to set default proxy,
* which will be used by all Socks aware sockets. You can also create either
* Socks4Proxy or Socks5Proxy, and use them by passing to the appropriate
* constructors.
* <P>
* Using Socks package can be as easy as that:
*
* <pre>
* <tt>
*
* import Socks.*;
* ....
*
* try{
* //Specify SOCKS5 proxy
* Proxy.setDefaultProxy("socks-proxy",1080);
*
* //OR you still use SOCKS4
* //Code below uses SOCKS4 proxy
* //Proxy.setDefaultProxy("socks-proxy",1080,userName);
*
* Socket s = SocksSocket("some.host.of.mine",13);
* readTimeFromSock(s);
* }catch(SocksException sock_ex){
* //Usually it will turn in more or less meaningfull message
* System.err.println("SocksException:"+sock_ex);
* }
*
* </tt>
* </pre>
* <P>
* However if the need exist for more control, like resolving addresses
* remotely, or using some non-trivial authentication schemes, it can be done.
*/
public class SocksSocket extends Socket {
// Data members
protected Proxy proxy;
protected String localHost, remoteHost;
protected InetAddress localIP, remoteIP;
protected int localPort, remotePort;
private Socket directSock = null;
/**
* Connects to given ip and port using given Proxy server.
*
* @param p
* Proxy to use.
* @param ip
* Machine to connect to.
* @param port
* Port to which to connect.
*/
public SocksSocket(InetAddress ip, int port) throws SocksException {
this.remoteIP = ip;
this.remotePort = port;
this.remoteHost = ip.getHostName();
doDirect();
}
protected SocksSocket(InetAddress ip, int port, Proxy proxy) {
remoteIP = ip;
remotePort = port;
this.proxy = proxy;
this.localIP = proxy.proxySocket.getLocalAddress();
this.localPort = proxy.proxySocket.getLocalPort();
remoteHost = remoteIP.getHostName();
}
/**
* Connects to host port using given proxy server.
*
* @param p
* Proxy to use.
* @param host
* Machine to connect to.
* @param port
* Port to which to connect.
* @throws UnknownHostException
* If one of the following happens:
* <ol>
*
* <li>Proxy settings say that address should be resolved
* locally, but this fails.
* <li>Proxy settings say that the host should be contacted
* directly but host name can't be resolved.
* </ol>
* @throws SocksException
* If one of the following happens:
* <ul>
* <li>Proxy is is null.
* <li>Proxy settings say that the host should be contacted
* directly but this fails.
* <li>Socks Server can't be contacted.
* <li>Authentication fails.
* <li>Connection is not allowed by the SOCKS proxy.
* <li>SOCKS proxy can't establish the connection.
* <li>Any IO error occured.
* <li>Any protocol error occured.
* </ul>
* @throws IOexception
* if anything is wrong with I/O.
* @see Socks5Proxy#resolveAddrLocally
*/
public SocksSocket(Proxy p, String host, int port) throws SocksException,
UnknownHostException {
remoteHost = host;
remotePort = port;
remoteIP = InetAddress.getByName(host);
doDirect();
}
/**
* Tryies to connect to given host and port using default proxy. If no
* default proxy speciefied it throws SocksException with error code
* SOCKS_NO_PROXY.
*
* @param host
* Machine to connect to.
* @param port
* Port to which to connect.
* @see SocksSocket#SocksSocket(Proxy,String,int)
* @see Socks5Proxy#resolveAddrLocally
*/
public SocksSocket(String host, int port) throws SocksException,
UnknownHostException {
this(Proxy.defaultProxy, host, port);
}
/**
* These 2 constructors are used by the SocksServerSocket. This socket
* simply overrides remoteHost, remotePort
*/
protected SocksSocket(String host, int port, Proxy proxy) {
this.remotePort = port;
this.proxy = proxy;
this.localIP = proxy.proxySocket.getLocalAddress();
this.localPort = proxy.proxySocket.getLocalPort();
this.remoteHost = host;
}
/**
* Same as Socket
*/
@Override
public void close() throws IOException {
if (proxy != null)
proxy.endSession();
proxy = null;
}
private void doDirect() throws SocksException {
try {
// System.out.println("IP:"+remoteIP+":"+remotePort);
directSock = new Socket(remoteIP, remotePort);
proxy.out = directSock.getOutputStream();
proxy.in = directSock.getInputStream();
proxy.proxySocket = directSock;
localIP = directSock.getLocalAddress();
localPort = directSock.getLocalPort();
} catch (IOException io_ex) {
throw new SocksException(Proxy.SOCKS_DIRECT_FAILED,
"Direct connect failed:" + io_ex);
}
}
/**
* Returns remote host name, it is usefull in cases when addresses are
* resolved by proxy, and we can't create InetAddress object.
*
* @return The name of the host this socket is connected to.
*/
public String getHost() {
return remoteHost;
}
/**
* Get remote host as InetAddress object, might return null if addresses are
* resolved by proxy, and it is not possible to resolve it locally
*
* @return Ip address of the host this socket is connected to, or null if
* address was returned by the proxy as DOMAINNAME and can't be
* resolved locally.
*/
@Override
public InetAddress getInetAddress() {
if (remoteIP == null) {
try {
remoteIP = InetAddress.getByName(remoteHost);
} catch (UnknownHostException e) {
return null;
}
}
return remoteIP;
}
/**
* Same as Socket
*/
@Override
public InputStream getInputStream() {
return proxy.in;
}
/**
* Get address assigned by proxy to make a remote connection, it might be
* different from the host specified for the proxy. Can return null if socks
* server returned this address as hostname and it can't be resolved
* locally, use getLocalHost() then.
*
* @return Address proxy is using to make a connection.
*/
@Override
public InetAddress getLocalAddress() {
if (localIP == null) {
try {
localIP = InetAddress.getByName(localHost);
} catch (UnknownHostException e) {
return null;
}
}
return localIP;
}
/**
* Get name of the host, proxy has assigned to make a remote connection for
* this socket. This method is usefull when proxy have returned address as
* hostname, and we can't resolve it on this machine.
*
* @return The name of the host proxy is using to make a connection.
*/
public String getLocalHost() {
return localHost;
}
/**
* Get the port assigned by the proxy for the socket, not the port on locall
* machine as in Socket.
*
* @return Port of the socket used on the proxy server.
*/
@Override
public int getLocalPort() {
return localPort;
}
/**
* Same as Socket
*/
@Override
public OutputStream getOutputStream() {
return proxy.out;
}
/**
* Same as Socket
*/
@Override
public int getPort() {
return remotePort;
}
/**
* Same as socket.
*/
public int getSoLinger(int timeout) throws SocketException {
return proxy.proxySocket.getSoLinger();
}
/**
* Same as socket.
*/
public int getSoTimeout(int timeout) throws SocketException {
return proxy.proxySocket.getSoTimeout();
}
/**
* Same as socket.
*/
@Override
public boolean getTcpNoDelay() throws SocketException {
return proxy.proxySocket.getTcpNoDelay();
}
/**
* Same as socket.
*/
@Override
public void setSoLinger(boolean on, int val) throws SocketException {
proxy.proxySocket.setSoLinger(on, val);
}
/**
* Same as socket.
*/
@Override
public void setSoTimeout(int timeout) throws SocketException {
proxy.proxySocket.setSoTimeout(timeout);
}
/**
* Same as socket.
*/
@Override
public void setTcpNoDelay(boolean on) throws SocketException {
proxy.proxySocket.setTcpNoDelay(on);
}
// Private Methods
// ////////////////
/**
* Get string representation of the socket.
*/
@Override
public String toString() {
if (directSock != null)
return "Direct connection:" + directSock;
return ("Proxy:" + proxy + ";" + "addr:" + remoteHost + ",port:"
+ remotePort + ",localport:" + localPort);
}
}
| Java |
package net.sourceforge.jsocks;
/**
* This interface provides for datagram encapsulation for SOCKSv5 protocol.
* <p>
* SOCKSv5 allows for datagrams to be encapsulated for purposes of integrity
* and/or authenticity. How it should be done is aggreed during the
* authentication stage, and is authentication dependent. This interface is
* provided to allow this encapsulation.
*
* @see Authentication
*/
public interface UDPEncapsulation {
/**
* This method should provide any authentication depended transformation on
* datagrams being send from/to the client.
*
* @param data
* Datagram data (including any SOCKS related bytes), to be
* encapsulated/decapsulated.
* @param out
* Wether the data is being send out. If true method should
* encapsulate/encrypt data, otherwise it should decapsulate/
* decrypt data.
* @throw IOException if for some reason data can be transformed correctly.
* @return Should return byte array containing data after transformation. It
* is possible to return same array as input, if transformation only
* involves bit mangling, and no additional data is being added or
* removed.
*/
byte[] udpEncapsulate(byte[] data, boolean out) throws java.io.IOException;
}
| Java |
package net.sourceforge.jsocks;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.PushbackInputStream;
import java.net.ConnectException;
import java.net.InetAddress;
import java.net.NoRouteToHostException;
import java.net.ServerSocket;
import java.net.Socket;
import net.sourceforge.jsocks.server.ServerAuthenticator;
/**
* SOCKS4 and SOCKS5 proxy, handles both protocols simultaniously. Implements
* all SOCKS commands, including UDP relaying.
* <p>
* In order to use it you will need to implement ServerAuthenticator interface.
* There is an implementation of this interface which does no authentication
* ServerAuthenticatorNone, but it is very dangerous to use, as it will give
* access to your local network to anybody in the world. One should never use
* this authentication scheme unless one have pretty good reason to do so. There
* is a couple of other authentication schemes in socks.server package.
*
* @see socks.server.ServerAuthenticator
*/
public class ProxyServer implements Runnable {
ServerAuthenticator auth;
ProxyMessage msg = null;
Socket sock = null, remote_sock = null;
ServerSocket ss = null;
UDPRelayServer relayServer = null;
InputStream in, remote_in;
OutputStream out, remote_out;
int mode;
static final int START_MODE = 0;
static final int ACCEPT_MODE = 1;
static final int PIPE_MODE = 2;
static final int ABORT_MODE = 3;
static final int BUF_SIZE = 8192;
Thread pipe_thread1, pipe_thread2;
long lastReadTime;
protected static int iddleTimeout = 180000; // 3 minutes
static int acceptTimeout = 180000; // 3 minutes
static PrintStream log = null;
static Proxy proxy;
// Public Constructors
// ///////////////////
static final String command_names[] = { "CONNECT", "BIND", "UDP_ASSOCIATE" };
// Other constructors
// //////////////////
static final String command2String(int cmd) {
if (cmd > 0 && cmd < 4)
return command_names[cmd - 1];
else
return "Unknown Command " + cmd;
}
// Public methods
// ///////////////
/**
* Get proxy.
*
* @return Proxy wich is used to handle user requests.
*/
public static Proxy getProxy() {
return proxy;
}
static final void log(ProxyMessage msg) {
log("Request version:" + msg.version + "\tCommand: "
+ command2String(msg.command));
log("IP:" + msg.ip + "\tPort:" + msg.port
+ (msg.version == 4 ? "\tUser:" + msg.user : ""));
}
static final void log(String s) {
if (log != null) {
log.println(s);
log.flush();
}
}
/**
* Sets the timeout for BIND command, how long the server should wait for
* the incoming connection.<br>
* Zero timeout implies infinity.<br>
* Default timeout is 3 minutes.
*/
public static void setAcceptTimeout(int timeout) {
acceptTimeout = timeout;
}
/**
* Sets the size of the datagrams used in the UDPRelayServer.<br>
* Default size is 64K, a bit more than maximum possible size of the
* datagram.
*/
public static void setDatagramSize(int size) {
UDPRelayServer.setDatagramSize(size);
}
/**
* Sets the timeout for connections, how long shoud server wait for data to
* arrive before dropping the connection.<br>
* Zero timeout implies infinity.<br>
* Default timeout is 3 minutes.
*/
public static void setIddleTimeout(int timeout) {
iddleTimeout = timeout;
}
/**
* Set the logging stream. Specifying null disables logging.
*/
public static void setLog(OutputStream out) {
if (out == null) {
log = null;
} else {
log = new PrintStream(out, true);
}
UDPRelayServer.log = log;
}
/**
* Set proxy.
* <p>
* Allows Proxy chaining so that one Proxy server is connected to another
* and so on. If proxy supports SOCKSv4, then only some SOCKSv5 requests can
* be handled, UDP would not work, however CONNECT and BIND will be
* translated.
*
* @param p
* Proxy which should be used to handle user requests.
*/
public static void setProxy(Proxy p) {
proxy = p;
UDPRelayServer.proxy = proxy;
}
/**
* Sets the timeout for UDPRelay server.<br>
* Zero timeout implies infinity.<br>
* Default timeout is 3 minutes.
*/
public static void setUDPTimeout(int timeout) {
UDPRelayServer.setTimeout(timeout);
}
/**
* Creates a proxy server with given Authentication scheme.
*
* @param auth
* Authentication scheme to be used.
*/
public ProxyServer(ServerAuthenticator auth) {
this.auth = auth;
}
protected ProxyServer(ServerAuthenticator auth, Socket s) {
this.auth = auth;
this.sock = s;
mode = START_MODE;
}
private synchronized void abort() {
if (mode == ABORT_MODE)
return;
mode = ABORT_MODE;
try {
log("Aborting operation");
if (remote_sock != null)
remote_sock.close();
if (sock != null)
sock.close();
if (relayServer != null)
relayServer.stop();
if (ss != null)
ss.close();
if (pipe_thread1 != null)
pipe_thread1.interrupt();
if (pipe_thread2 != null)
pipe_thread2.interrupt();
} catch (IOException ioe) {
}
}
private void doAccept() throws IOException {
Socket s;
long startTime = System.currentTimeMillis();
while (true) {
s = ss.accept();
if (s.getInetAddress().equals(msg.ip)) {
// got the connection from the right host
// Close listenning socket.
ss.close();
break;
} else if (ss instanceof SocksServerSocket) {
// We can't accept more then one connection
s.close();
ss.close();
throw new SocksException(Proxy.SOCKS_FAILURE);
} else {
if (acceptTimeout != 0) { // If timeout is not infinit
int newTimeout = acceptTimeout
- (int) (System.currentTimeMillis() - startTime);
if (newTimeout <= 0)
throw new InterruptedIOException("In doAccept()");
ss.setSoTimeout(newTimeout);
}
s.close(); // Drop all connections from other hosts
}
}
// Accepted connection
remote_sock = s;
remote_in = s.getInputStream();
remote_out = s.getOutputStream();
// Set timeout
remote_sock.setSoTimeout(iddleTimeout);
log("Accepted from " + s.getInetAddress() + ":" + s.getPort());
ProxyMessage response;
if (msg.version == 5)
response = new Socks5Message(Proxy.SOCKS_SUCCESS,
s.getInetAddress(), s.getPort());
else
response = new Socks4Message(Socks4Message.REPLY_OK,
s.getInetAddress(), s.getPort());
response.write(out);
}
private void handleException(IOException ioe) {
// If we couldn't read the request, return;
if (msg == null)
return;
// If have been aborted by other thread
if (mode == ABORT_MODE)
return;
// If the request was successfully completed, but exception happened
// later
if (mode == PIPE_MODE)
return;
int error_code = Proxy.SOCKS_FAILURE;
if (ioe instanceof SocksException)
error_code = ((SocksException) ioe).errCode;
else if (ioe instanceof NoRouteToHostException)
error_code = Proxy.SOCKS_HOST_UNREACHABLE;
else if (ioe instanceof ConnectException)
error_code = Proxy.SOCKS_CONNECTION_REFUSED;
else if (ioe instanceof InterruptedIOException)
error_code = Proxy.SOCKS_TTL_EXPIRE;
if (error_code > Proxy.SOCKS_ADDR_NOT_SUPPORTED || error_code < 0) {
error_code = Proxy.SOCKS_FAILURE;
}
sendErrorMessage(error_code);
}
protected void handleRequest(ProxyMessage msg) throws IOException {
if (!auth.checkRequest(msg))
throw new SocksException(Proxy.SOCKS_FAILURE);
if (msg.ip == null) {
if (msg instanceof Socks5Message) {
msg.ip = InetAddress.getByName(msg.host);
} else
throw new SocksException(Proxy.SOCKS_FAILURE);
}
log(msg);
switch (msg.command) {
case Proxy.SOCKS_CMD_CONNECT:
onConnect(msg);
break;
case Proxy.SOCKS_CMD_BIND:
onBind(msg);
break;
case Proxy.SOCKS_CMD_UDP_ASSOCIATE:
onUDP(msg);
break;
default:
throw new SocksException(Proxy.SOCKS_CMD_NOT_SUPPORTED);
}
}
private void onBind(ProxyMessage msg) throws IOException {
ProxyMessage response = null;
if (proxy == null)
ss = new ServerSocket(0);
else
ss = new SocksServerSocket(proxy, msg.ip, msg.port);
ss.setSoTimeout(acceptTimeout);
log("Trying accept on " + ss.getInetAddress() + ":" + ss.getLocalPort());
if (msg.version == 5)
response = new Socks5Message(Proxy.SOCKS_SUCCESS,
ss.getInetAddress(), ss.getLocalPort());
else
response = new Socks4Message(Socks4Message.REPLY_OK,
ss.getInetAddress(), ss.getLocalPort());
response.write(out);
mode = ACCEPT_MODE;
pipe_thread1 = Thread.currentThread();
pipe_thread2 = new Thread(this);
pipe_thread2.start();
// Make timeout infinit.
sock.setSoTimeout(0);
int eof = 0;
try {
while ((eof = in.read()) >= 0) {
if (mode != ACCEPT_MODE) {
if (mode != PIPE_MODE)
return;// Accept failed
remote_out.write(eof);
break;
}
}
} catch (EOFException eofe) {
// System.out.println("EOF exception");
return;// Connection closed while we were trying to accept.
} catch (InterruptedIOException iioe) {
// Accept thread interrupted us.
// System.out.println("Interrupted");
if (mode != PIPE_MODE)
return;// If accept thread was not successfull return.
} finally {
// System.out.println("Finnaly!");
}
if (eof < 0)// Connection closed while we were trying to accept;
return;
// Do not restore timeout, instead timeout is set on the
// remote socket. It does not make any difference.
pipe(in, remote_out);
}
private void onConnect(ProxyMessage msg) throws IOException {
Socket s;
ProxyMessage response = null;
s = new Socket(msg.ip, msg.port);
log("Connected to " + s.getInetAddress() + ":" + s.getPort());
if (msg instanceof Socks5Message) {
response = new Socks5Message(Proxy.SOCKS_SUCCESS,
s.getLocalAddress(), s.getLocalPort());
} else {
response = new Socks4Message(Socks4Message.REPLY_OK,
s.getLocalAddress(), s.getLocalPort());
}
response.write(out);
startPipe(s);
}
// Private methods
// ////////////////
private void onUDP(ProxyMessage msg) throws IOException {
if (msg.ip.getHostAddress().equals("0.0.0.0"))
msg.ip = sock.getInetAddress();
log("Creating UDP relay server for " + msg.ip + ":" + msg.port);
relayServer = new UDPRelayServer(msg.ip, msg.port,
Thread.currentThread(), sock, auth);
ProxyMessage response;
response = new Socks5Message(Proxy.SOCKS_SUCCESS, relayServer.relayIP,
relayServer.relayPort);
response.write(out);
relayServer.start();
// Make timeout infinit.
sock.setSoTimeout(0);
try {
while (in.read() >= 0)
/* do nothing */;
} catch (EOFException eofe) {
}
}
private void pipe(InputStream in, OutputStream out) throws IOException {
lastReadTime = System.currentTimeMillis();
byte[] buf = new byte[BUF_SIZE];
int len = 0;
while (len >= 0) {
try {
if (len != 0) {
out.write(buf, 0, len);
out.flush();
}
len = in.read(buf);
lastReadTime = System.currentTimeMillis();
} catch (InterruptedIOException iioe) {
if (iddleTimeout == 0)
return;// Other thread interrupted us.
long timeSinceRead = System.currentTimeMillis() - lastReadTime;
if (timeSinceRead >= iddleTimeout - 1000) // -1s for adjustment.
return;
len = 0;
}
}
}
protected ProxyMessage readMsg(InputStream in) throws IOException {
PushbackInputStream push_in;
if (in instanceof PushbackInputStream)
push_in = (PushbackInputStream) in;
else
push_in = new PushbackInputStream(in);
int version = push_in.read();
push_in.unread(version);
ProxyMessage msg;
if (version == 5) {
msg = new Socks5Message(push_in, false);
} else if (version == 4) {
msg = new Socks4Message(push_in, false);
} else {
throw new SocksException(Proxy.SOCKS_FAILURE);
}
return msg;
}
// Runnable interface
// //////////////////
@Override
public void run() {
switch (mode) {
case START_MODE:
try {
startSession();
} catch (IOException ioe) {
handleException(ioe);
// ioe.printStackTrace();
} finally {
abort();
if (auth != null)
auth.endSession();
log("Main thread(client->remote)stopped.");
}
break;
case ACCEPT_MODE:
try {
doAccept();
mode = PIPE_MODE;
pipe_thread1.interrupt(); // Tell other thread that connection
// have
// been accepted.
pipe(remote_in, out);
} catch (IOException ioe) {
// log("Accept exception:"+ioe);
handleException(ioe);
} finally {
abort();
log("Accept thread(remote->client) stopped");
}
break;
case PIPE_MODE:
try {
pipe(remote_in, out);
} catch (IOException ioe) {
} finally {
abort();
log("Support thread(remote->client) stopped");
}
break;
case ABORT_MODE:
break;
default:
log("Unexpected MODE " + mode);
}
}
private void sendErrorMessage(int error_code) {
ProxyMessage err_msg;
if (msg instanceof Socks4Message)
err_msg = new Socks4Message(Socks4Message.REPLY_REJECTED);
else
err_msg = new Socks5Message(error_code);
try {
err_msg.write(out);
} catch (IOException ioe) {
}
}
/**
* Start the Proxy server at given port.<br>
* This methods blocks.
*/
public void start(int port) {
start(port, 5, null);
}
/**
* Create a server with the specified port, listen backlog, and local IP
* address to bind to. The localIP argument can be used on a multi-homed
* host for a ServerSocket that will only accept connect requests to one of
* its addresses. If localIP is null, it will default accepting connections
* on any/all local addresses. The port must be between 0 and 65535,
* inclusive. <br>
* This methods blocks.
*/
public void start(int port, int backlog, InetAddress localIP) {
try {
ss = new ServerSocket(port, backlog, localIP);
log("Starting SOCKS Proxy on:"
+ ss.getInetAddress().getHostAddress() + ":"
+ ss.getLocalPort());
while (true) {
Socket s = ss.accept();
log("Accepted from:" + s.getInetAddress().getHostName() + ":"
+ s.getPort());
ProxyServer ps = new ProxyServer(auth, s);
(new Thread(ps)).start();
}
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
}
}
private void startPipe(Socket s) {
mode = PIPE_MODE;
remote_sock = s;
try {
remote_in = s.getInputStream();
remote_out = s.getOutputStream();
pipe_thread1 = Thread.currentThread();
pipe_thread2 = new Thread(this);
pipe_thread2.start();
pipe(in, remote_out);
} catch (IOException ioe) {
}
}
// Private methods
// ///////////////
private void startSession() throws IOException {
sock.setSoTimeout(iddleTimeout);
try {
auth = auth.startSession(sock);
} catch (IOException ioe) {
log("Auth throwed exception:" + ioe);
auth = null;
return;
}
if (auth == null) { // Authentication failed
log("Authentication failed");
return;
}
in = auth.getInputStream();
out = auth.getOutputStream();
msg = readMsg(in);
handleRequest(msg);
}
/**
* Stop server operation.It would be wise to interrupt thread running the
* server afterwards.
*/
public void stop() {
try {
if (ss != null)
ss.close();
} catch (IOException ioe) {
}
}
}
| Java |
package net.sourceforge.jsocks;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
/**
* SocksServerSocket allows to accept connections from one particular host
* through the SOCKS4 or SOCKS5 proxy.
*/
public class SocksServerSocket extends ServerSocket {
// Data members
protected Proxy proxy;
protected String localHost;
protected InetAddress localIP;
protected int localPort;
boolean doing_direct = false;
InetAddress remoteAddr;
/**
* Creates ServerSocket capable of accepting one connection through the
* firewall, uses default Proxy.
*
* @param ip
* Host from which the connection should be recieved.
* @param port
* Port number of the primary connection.
*/
public SocksServerSocket(InetAddress ip, int port) throws SocksException,
IOException {
this(Proxy.defaultProxy, ip, port);
}
/**
* Creates ServerSocket capable of accepting one connection through the
* firewall, uses given proxy.
*
* @param ip
* Host from which the connection should be recieved.
* @param port
* Port number of the primary connection.
*/
public SocksServerSocket(Proxy p, InetAddress ip, int port)
throws SocksException, IOException {
super(0);
remoteAddr = ip;
doDirect();
}
/**
* Creates ServerSocket capable of accepting one connection through the
* firewall, uses given proxy.
*
* @param host
* Host from which the connection should be recieved.
* @param port
* Port number of the primary connection.
*/
public SocksServerSocket(String host, int port) throws SocksException,
UnknownHostException, IOException {
super(0);
remoteAddr = InetAddress.getByName(host);
doDirect();
}
/**
* Accepts the incoming connection.
*/
@Override
public Socket accept() throws IOException {
Socket s;
if (!doing_direct) {
if (proxy == null)
return null;
ProxyMessage msg = proxy.accept();
s = msg.ip == null ? new SocksSocket(msg.host, msg.port, proxy)
: new SocksSocket(msg.ip, msg.port, proxy);
// Set timeout back to 0
proxy.proxySocket.setSoTimeout(0);
} else { // Direct Connection
// Mimic the proxy behaviour,
// only accept connections from the speciefed host.
while (true) {
s = super.accept();
if (s.getInetAddress().equals(remoteAddr)) {
// got the connection from the right host
// Close listenning socket.
break;
} else
s.close(); // Drop all connections from other hosts
}
}
proxy = null;
// Return accepted socket
return s;
}
/**
* Closes the connection to proxy if socket have not been accepted, if the
* direct connection is used, closes direct ServerSocket. If the client
* socket have been allready accepted, does nothing.
*/
@Override
public void close() throws IOException {
super.close();
if (proxy != null)
proxy.endSession();
proxy = null;
}
private void doDirect() {
doing_direct = true;
localPort = super.getLocalPort();
localIP = super.getInetAddress();
localHost = localIP.getHostName();
}
/**
* Get the name of the host proxy is using to listen for incoming
* connection.
* <P>
* Usefull when address is returned by proxy as the hostname.
*
* @return the hostname of the address proxy is using to listen for incoming
* connection.
*/
public String getHost() {
return localHost;
}
/**
* Get address assigned by proxy to listen for incomming connections, or the
* local machine address if doing direct connection.
*/
@Override
public InetAddress getInetAddress() {
if (localIP == null) {
try {
localIP = InetAddress.getByName(localHost);
} catch (UnknownHostException e) {
return null;
}
}
return localIP;
}
/**
* Get port assigned by proxy to listen for incoming connections, or the
* port chosen by local system, if accepting directly.
*/
@Override
public int getLocalPort() {
return localPort;
}
// Private Methods
// ////////////////
/**
* Set Timeout.
*
* @param timeout
* Amount of time in milliseconds, accept should wait for
* incoming connection before failing with exception. Zero
* timeout implies infinity.
*/
@Override
public void setSoTimeout(int timeout) throws SocketException {
super.setSoTimeout(timeout);
if (!doing_direct)
proxy.proxySocket.setSoTimeout(timeout);
}
}
| Java |
package net.sourceforge.jsocks.server;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PushbackInputStream;
import java.net.Socket;
import net.sourceforge.jsocks.ProxyMessage;
import net.sourceforge.jsocks.UDPEncapsulation;
/**
* An implementation of ServerAuthenticator, which does <b>not</b> do any
* authentication.
* <P>
* <FONT size="+3" color ="FF0000"> Warning!!</font><br>
* Should not be used on machines which are not behind the firewall.
* <p>
* It is only provided to make implementing other authentication schemes easier.
* <br>
* For Example: <tt><pre>
class MyAuth extends socks.server.ServerAuthenticator{
...
public ServerAuthenticator startSession(java.net.Socket s){
if(!checkHost(s.getInetAddress()) return null;
return super.startSession(s);
}
boolean checkHost(java.net.Inetaddress addr){
boolean allow;
//Do it somehow
return allow;
}
}
</pre></tt>
*/
public class ServerAuthenticatorNone implements ServerAuthenticator {
static final byte[] socks5response = { 5, 0 };
/**
* Convinience routine for selecting SOCKSv5 authentication.
* <p>
* This method reads in authentication methods that client supports, checks
* wether it supports given method. If it does, the notification method is
* written back to client, that this method have been chosen for
* authentication. If given method was not found, authentication failure
* message is send to client ([5,FF]).
*
* @param in
* Input stream, version byte should be removed from the stream
* before calling this method.
* @param out
* Output stream.
* @param methodId
* Method which should be selected.
* @return true if methodId was found, false otherwise.
*/
static public boolean selectSocks5Authentication(InputStream in,
OutputStream out, int methodId) throws IOException {
int num_methods = in.read();
if (num_methods <= 0)
return false;
byte method_ids[] = new byte[num_methods];
byte response[] = new byte[2];
boolean found = false;
response[0] = (byte) 5; // SOCKS version
response[1] = (byte) 0xFF; // Not found, we are pessimistic
int bread = 0; // bytes read so far
while (bread < num_methods)
bread += in.read(method_ids, bread, num_methods - bread);
for (int i = 0; i < num_methods; ++i)
if (method_ids[i] == methodId) {
found = true;
response[1] = (byte) methodId;
break;
}
out.write(response);
return found;
}
InputStream in;
OutputStream out;
/**
* Creates new instance of the ServerAuthenticatorNone.
*/
public ServerAuthenticatorNone() {
this.in = null;
this.out = null;
}
/**
* Constructs new ServerAuthenticatorNone object suitable for returning from
* the startSession function.
*
* @param in
* Input stream to return from getInputStream method.
* @param out
* Output stream to return from getOutputStream method.
*/
public ServerAuthenticatorNone(InputStream in, OutputStream out) {
this.in = in;
this.out = out;
}
/**
* Allways returns true.
*/
@Override
public boolean checkRequest(java.net.DatagramPacket dp, boolean out) {
return true;
}
/**
* Allways returns true.
*/
@Override
public boolean checkRequest(ProxyMessage msg) {
return true;
}
/**
* Does nothing.
*/
@Override
public void endSession() {
}
/**
* Get input stream.
*
* @return Input stream speciefied in the constructor.
*/
@Override
public InputStream getInputStream() {
return in;
}
/**
* Get output stream.
*
* @return Output stream speciefied in the constructor.
*/
@Override
public OutputStream getOutputStream() {
return out;
}
/**
* Allways returns null.
*
* @return null
*/
@Override
public UDPEncapsulation getUdpEncapsulation() {
return null;
}
/**
* Grants access to everyone.Removes authentication related bytes from the
* stream, when a SOCKS5 connection is being made, selects an authentication
* NONE.
*/
@Override
public ServerAuthenticator startSession(Socket s) throws IOException {
PushbackInputStream in = new PushbackInputStream(s.getInputStream());
OutputStream out = s.getOutputStream();
int version = in.read();
if (version == 5) {
if (!selectSocks5Authentication(in, out, 0))
return null;
} else if (version == 4) {
// Else it is the request message allready, version 4
in.unread(version);
} else
return null;
return new ServerAuthenticatorNone(in, out);
}
}
| Java |
package net.sourceforge.jsocks.server;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.DatagramPacket;
import java.net.Socket;
import net.sourceforge.jsocks.ProxyMessage;
import net.sourceforge.jsocks.UDPEncapsulation;
/**
* Classes implementing this interface should provide socks server with
* authentication and authorization of users.
**/
public interface ServerAuthenticator {
/**
* This method is called when datagram is received by the server.
* <p>
* Implementaions should decide wether it should be forwarded or dropped. It
* is expecteed that implementation will use datagram address and port
* information to make a decision, as well as anything else. Address and
* port of the datagram are always correspond to remote machine. It is
* either destination or source address. If out is true address is
* destination address, else it is a source address, address of the machine
* from which datagram have been received for the client.
* <p>
* Implementaions should return true if the datagram is to be forwarded, and
* false if the datagram should be dropped.
* <p>
* This method is called on the object returned from the startSession
* function.
*
* @param out
* If true the datagram is being send out(from the client),
* otherwise it is an incoming datagram.
* @return True to forward datagram false drop it silently.
*/
boolean checkRequest(DatagramPacket dp, boolean out);
/**
* This method is called when a request have been read.
* <p>
* Implementation should decide wether to grant request or not. Returning
* true implies granting the request, false means request should be
* rejected.
* <p>
* This method is called on the object returned from the startSession
* function.
*
* @param msg
* Request message.
* @return true to grant request, false to reject it.
*/
boolean checkRequest(ProxyMessage msg);
/**
* This method is called when session is completed. Either due to normal
* termination or due to any error condition.
* <p>
* This method is called on the object returned from the startSession
* function.
*/
void endSession();
/**
* This method should return input stream which should be used on the
* accepted socket.
* <p>
* SOCKSv5 allows to have multiple authentication methods, and these methods
* might require some kind of transformations being made on the data.
* <p>
* This method is called on the object returned from the startSession
* function.
*/
InputStream getInputStream();
/**
* This method should return output stream to use to write to the accepted
* socket.
* <p>
* SOCKSv5 allows to have multiple authentication methods, and these methods
* might require some kind of transformations being made on the data.
* <p>
* This method is called on the object returned from the startSession
* function.
*/
OutputStream getOutputStream();
/**
* This method should return UDPEncapsulation, which should be used on the
* datagrams being send in/out.
* <p>
* If no transformation should be done on the datagrams, this method should
* return null.
* <p>
* This method is called on the object returned from the startSession
* function.
*/
UDPEncapsulation getUdpEncapsulation();
/**
* This method is called when a new connection accepted by the server.
* <p>
* At this point no data have been extracted from the connection. It is
* responsibility of this method to ensure that the next byte in the stream
* after this method have been called is the first byte of the socks request
* message. For SOCKSv4 there is no authentication data and the first byte
* in the stream is part of the request. With SOCKSv5 however there is an
* authentication data first. It is expected that implementaions will
* process this authentication data.
* <p>
* If authentication was successful an instance of ServerAuthentication
* should be returned, it later will be used by the server to perform
* authorization and some other things. If authentication fails null should
* be returned, or an exception may be thrown.
*
* @param s
* Accepted Socket.
* @return An instance of ServerAuthenticator to be used for this connection
* or null
*/
ServerAuthenticator startSession(Socket s) throws IOException;
}
| Java |
package net.sourceforge.jsocks;
import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
/**
* Abstract class Proxy, base for classes Socks4Proxy and Socks5Proxy. Defines
* methods for specifying default proxy, to be used by all classes of this
* package.
*/
public abstract class Proxy {
// Data members
// protected InetRange directHosts = new InetRange();
public static final int SOCKS_SUCCESS = 0;
public static final int SOCKS_FAILURE = 1;
public static final int SOCKS_BADCONNECT = 2;
public static final int SOCKS_BADNETWORK = 3;
public static final int SOCKS_HOST_UNREACHABLE = 4;
public static final int SOCKS_CONNECTION_REFUSED = 5;
public static final int SOCKS_TTL_EXPIRE = 6;
public static final int SOCKS_CMD_NOT_SUPPORTED = 7;
public static final int SOCKS_ADDR_NOT_SUPPORTED = 8;
public static final int SOCKS_NO_PROXY = 1 << 16;
public static final int SOCKS_PROXY_NO_CONNECT = 2 << 16;
public static final int SOCKS_PROXY_IO_ERROR = 3 << 16;
public static final int SOCKS_AUTH_NOT_SUPPORTED = 4 << 16;
// Public instance methods
// ========================
public static final int SOCKS_AUTH_FAILURE = 5 << 16;
public static final int SOCKS_JUST_ERROR = 6 << 16;
public static final int SOCKS_DIRECT_FAILED = 7 << 16;
// Public Static(Class) Methods
// ==============================
public static final int SOCKS_METHOD_NOTSUPPORTED = 8 << 16;
public static final int SOCKS_CMD_CONNECT = 0x1;
static final int SOCKS_CMD_BIND = 0x2;
static final int SOCKS_CMD_UDP_ASSOCIATE = 0x3;
/**
* Get current default proxy.
*
* @return Current default proxy, or null if none is set.
*/
public static Proxy getDefaultProxy() {
return defaultProxy;
}
/**
* Parses strings in the form: host[:port:user:password], and creates proxy
* from information obtained from parsing.
* <p>
* Defaults: port = 1080.<br>
* If user specified but not password, creates Socks4Proxy, if user not
* specified creates Socks5Proxy, if both user and password are speciefied
* creates Socks5Proxy with user/password authentication.
*
* @param proxy_entry
* String in the form host[:port:user:password]
* @return Proxy created from the string, null if entry was somehow
* invalid(host unknown for example, or empty string)
*/
public static Proxy parseProxy(String proxy_entry) {
String proxy_host;
int proxy_port = 1080;
String proxy_user = null;
String proxy_password = null;
Proxy proxy;
java.util.StringTokenizer st = new java.util.StringTokenizer(
proxy_entry, ":");
if (st.countTokens() < 1)
return null;
proxy_host = st.nextToken();
if (st.hasMoreTokens())
try {
proxy_port = Integer.parseInt(st.nextToken().trim());
} catch (NumberFormatException nfe) {
}
if (st.hasMoreTokens())
proxy_user = st.nextToken();
if (st.hasMoreTokens())
proxy_password = st.nextToken();
try {
if (proxy_user == null)
proxy = new Socks5Proxy(proxy_host, proxy_port);
else if (proxy_password == null)
proxy = new Socks4Proxy(proxy_host, proxy_port, proxy_user);
else {
proxy = new Socks5Proxy(proxy_host, proxy_port);
/*
* UserPasswordAuthentication upa = new
* UserPasswordAuthentication( proxy_user, proxy_password);
*
* ((Socks5Proxy)proxy).setAuthenticationMethod(upa.METHOD_ID,upa
* );
*/
}
} catch (UnknownHostException uhe) {
return null;
}
return proxy;
}
/**
* Sets SOCKS5 proxy as default. Default proxy only supports
* no-authentication.
*
* @param ipAddress
* Host address on which SOCKS5 server is running.
* @param port
* Port on which SOCKS5 server is running.
*/
public static void setDefaultProxy(InetAddress ipAddress, int port) {
defaultProxy = new Socks5Proxy(ipAddress, port);
}
// Protected Methods
// =================
/**
* Sets SOCKS4 proxy as default.
*
* @param ipAddress
* Host address on which SOCKS4 server is running.
* @param port
* Port on which SOCKS4 server is running.
* @param user
* Username to use for communications with proxy.
*/
public static void setDefaultProxy(InetAddress ipAddress, int port,
String user) {
defaultProxy = new Socks4Proxy(ipAddress, port, user);
}
/**
* Sets default proxy.
*
* @param p
* Proxy to use as default proxy.
*/
public static void setDefaultProxy(Proxy p) {
defaultProxy = p;
}
/**
* Sets SOCKS5 proxy as default. Default proxy only supports
* no-authentication.
*
* @param hostName
* Host name on which SOCKS5 server is running.
* @param port
* Port on which SOCKS5 server is running.
*/
public static void setDefaultProxy(String hostName, int port)
throws UnknownHostException {
defaultProxy = new Socks5Proxy(hostName, port);
}
/**
* Sets SOCKS4 proxy as default.
*
* @param hostName
* Host name on which SOCKS4 server is running.
* @param port
* Port on which SOCKS4 server is running.
* @param user
* Username to use for communications with proxy.
*/
public static void setDefaultProxy(String hostName, int port, String user)
throws UnknownHostException {
defaultProxy = new Socks4Proxy(hostName, port, user);
}
protected InetAddress proxyIP = null;
protected String proxyHost = null;
protected int proxyPort;
protected Socket proxySocket = null;
protected InputStream in;
protected OutputStream out;
protected int version;
protected Proxy chainProxy = null;
// Protected static/class variables
protected static Proxy defaultProxy = null;
Proxy(InetAddress proxyIP, int proxyPort) {
this.proxyIP = proxyIP;
this.proxyPort = proxyPort;
}
Proxy(Proxy p) {
this.proxyIP = p.proxyIP;
this.proxyPort = p.proxyPort;
this.version = p.version;
}
Proxy(Proxy chainProxy, InetAddress proxyIP, int proxyPort) {
this.chainProxy = chainProxy;
this.proxyIP = proxyIP;
this.proxyPort = proxyPort;
}
// Private methods
// ===============
// Constants
// Constructors
// ====================
Proxy(String proxyHost, int proxyPort) throws UnknownHostException {
this.proxyHost = proxyHost;
this.proxyIP = InetAddress.getByName(proxyHost);
this.proxyPort = proxyPort;
}
protected ProxyMessage accept() throws IOException, SocksException {
ProxyMessage msg;
try {
msg = formMessage(in);
} catch (InterruptedIOException iioe) {
throw iioe;
} catch (IOException io_ex) {
endSession();
throw new SocksException(SOCKS_PROXY_IO_ERROR,
"While Trying accept:" + io_ex);
}
return msg;
}
protected ProxyMessage bind(InetAddress ip, int port) throws SocksException {
try {
startSession();
ProxyMessage request = formMessage(SOCKS_CMD_BIND, ip, port);
return exchange(request);
} catch (SocksException se) {
endSession();
throw se;
}
}
protected ProxyMessage bind(String host, int port)
throws UnknownHostException, SocksException {
try {
startSession();
ProxyMessage request = formMessage(SOCKS_CMD_BIND, host, port);
return exchange(request);
} catch (SocksException se) {
endSession();
throw se;
}
}
protected ProxyMessage connect(InetAddress ip, int port)
throws SocksException {
try {
startSession();
ProxyMessage request = formMessage(SOCKS_CMD_CONNECT, ip, port);
return exchange(request);
} catch (SocksException se) {
endSession();
throw se;
}
}
protected ProxyMessage connect(String host, int port)
throws UnknownHostException, SocksException {
try {
startSession();
ProxyMessage request = formMessage(SOCKS_CMD_CONNECT, host, port);
return exchange(request);
} catch (SocksException se) {
endSession();
throw se;
}
}
protected abstract Proxy copy();
protected void endSession() {
try {
if (proxySocket != null)
proxySocket.close();
proxySocket = null;
} catch (IOException io_ex) {
}
}
/**
* Sends the request reads reply and returns it throws exception if
* something wrong with IO or the reply code is not zero
*/
protected ProxyMessage exchange(ProxyMessage request) throws SocksException {
ProxyMessage reply;
try {
request.write(out);
reply = formMessage(in);
} catch (SocksException s_ex) {
throw s_ex;
} catch (IOException ioe) {
throw (new SocksException(SOCKS_PROXY_IO_ERROR, "" + ioe));
}
return reply;
}
protected abstract ProxyMessage formMessage(InputStream in)
throws SocksException, IOException;
protected abstract ProxyMessage formMessage(int cmd, InetAddress ip,
int port);
protected abstract ProxyMessage formMessage(int cmd, String host, int port)
throws UnknownHostException;
/**
* Get the ip address of the proxy server host.
*
* @return Proxy InetAddress.
*/
public InetAddress getInetAddress() {
return proxyIP;
}
/**
* Get the port on which proxy server is running.
*
* @return Proxy port.
*/
public int getPort() {
return proxyPort;
}
/**
* Reads the reply from the SOCKS server
*/
protected ProxyMessage readMsg() throws SocksException, IOException {
return formMessage(in);
}
/**
* Sends the request to SOCKS server
*/
protected void sendMsg(ProxyMessage msg) throws SocksException, IOException {
msg.write(out);
}
protected void startSession() throws SocksException {
try {
proxySocket = new Socket(proxyIP, proxyPort);
in = proxySocket.getInputStream();
out = proxySocket.getOutputStream();
} catch (SocksException se) {
throw se;
} catch (IOException io_ex) {
throw new SocksException(SOCKS_PROXY_IO_ERROR, "" + io_ex);
}
}
/**
* Get string representation of this proxy.
*
* @returns string in the form:proxyHost:proxyPort \t Version versionNumber
*/
@Override
public String toString() {
return ("" + proxyIP.getHostName() + ":" + proxyPort + "\tVersion " + version);
}
protected ProxyMessage udpAssociate(InetAddress ip, int port)
throws SocksException {
try {
startSession();
ProxyMessage request = formMessage(SOCKS_CMD_UDP_ASSOCIATE, ip,
port);
if (request != null)
return exchange(request);
} catch (SocksException se) {
endSession();
throw se;
}
// Only get here if request was null
endSession();
throw new SocksException(SOCKS_METHOD_NOTSUPPORTED,
"This version of proxy does not support UDP associate, use version 5");
}
protected ProxyMessage udpAssociate(String host, int port)
throws UnknownHostException, SocksException {
try {
startSession();
ProxyMessage request = formMessage(SOCKS_CMD_UDP_ASSOCIATE, host,
port);
if (request != null)
return exchange(request);
} catch (SocksException se) {
endSession();
throw se;
}
// Only get here if request was null
endSession();
throw new SocksException(SOCKS_METHOD_NOTSUPPORTED,
"This version of proxy does not support UDP associate, use version 5");
}
}
| Java |
package net.sourceforge.jsocks;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
/**
* Datagram socket to interract through the firewall.<BR>
* Can be used same way as the normal DatagramSocket. One should be carefull
* though with the datagram sizes used, as additional data is present in both
* incomming and outgoing datagrams.
* <p>
* SOCKS5 protocol allows to send host address as either:
* <ul>
* <li>IPV4, normal 4 byte address. (10 bytes header size)
* <li>IPV6, version 6 ip address (not supported by Java as for now). 22 bytes
* header size.
* <li>Host name,(7+length of the host name bytes header size).
* </ul>
* As with other Socks equivalents, direct addresses are handled transparently,
* that is data will be send directly when required by the proxy settings.
* <p>
* <b>NOTE:</b><br>
* Unlike other SOCKS Sockets, it <b>does not</b> support proxy chaining, and
* will throw an exception if proxy has a chain proxy attached. The reason for
* that is not my laziness, but rather the restrictions of the SOCKSv5 protocol.
* Basicaly SOCKSv5 proxy server, needs to know from which host:port datagrams
* will be send for association, and returns address to which datagrams should
* be send by the client, but it does not inform client from which host:port it
* is going to send datagrams, in fact there is even no guarantee they will be
* send at all and from the same address each time.
*/
public class Socks5DatagramSocket extends DatagramSocket {
InetAddress relayIP;
int relayPort;
Socks5Proxy proxy;
private boolean server_mode = false;
UDPEncapsulation encapsulation;
/**
* Construct Datagram socket for communication over SOCKS5 proxy server.
* This constructor uses default proxy, the one set with
* Proxy.setDefaultProxy() method. If default proxy is not set or it is set
* to version4 proxy, which does not support datagram forwarding, throws
* SocksException.
*/
public Socks5DatagramSocket() throws SocksException, IOException {
this(Proxy.defaultProxy, 0, null);
}
/**
* Used by UDPRelayServer.
*/
Socks5DatagramSocket(boolean server_mode, UDPEncapsulation encapsulation,
InetAddress relayIP, int relayPort) throws IOException {
super();
this.server_mode = server_mode;
this.relayIP = relayIP;
this.relayPort = relayPort;
this.encapsulation = encapsulation;
this.proxy = null;
}
/**
* Construct Datagram socket for communication over SOCKS5 proxy server. And
* binds it to the specified local port. This constructor uses default
* proxy, the one set with Proxy.setDefaultProxy() method. If default proxy
* is not set or it is set to version4 proxy, which does not support
* datagram forwarding, throws SocksException.
*/
public Socks5DatagramSocket(int port) throws SocksException, IOException {
this(Proxy.defaultProxy, port, null);
}
/**
* Construct Datagram socket for communication over SOCKS5 proxy server. And
* binds it to the specified local port and address. This constructor uses
* default proxy, the one set with Proxy.setDefaultProxy() method. If
* default proxy is not set or it is set to version4 proxy, which does not
* support datagram forwarding, throws SocksException.
*/
public Socks5DatagramSocket(int port, InetAddress ip)
throws SocksException, IOException {
this(Proxy.defaultProxy, port, ip);
}
/**
* Constructs datagram socket for communication over specified proxy. And
* binds it to the given local address and port. Address of null and port of
* 0, signify any availabale port/address. Might throw SocksException, if:
* <ol>
* <li>Given version of proxy does not support UDP_ASSOCIATE.
* <li>Proxy can't be reached.
* <li>Authorization fails.
* <li>Proxy does not want to perform udp forwarding, for any reason.
* </ol>
* Might throw IOException if binding dtagram socket to given address/port
* fails. See java.net.DatagramSocket for more details.
*/
public Socks5DatagramSocket(Proxy p, int port, InetAddress ip)
throws SocksException, IOException {
super(port, ip);
if (p == null)
throw new SocksException(Proxy.SOCKS_NO_PROXY);
if (!(p instanceof Socks5Proxy))
throw new SocksException(-1,
"Datagram Socket needs Proxy version 5");
if (p.chainProxy != null)
throw new SocksException(Proxy.SOCKS_JUST_ERROR,
"Datagram Sockets do not support proxy chaining.");
proxy = (Socks5Proxy) p.copy();
ProxyMessage msg = proxy.udpAssociate(super.getLocalAddress(),
super.getLocalPort());
relayIP = msg.ip;
if (relayIP.getHostAddress().equals("0.0.0.0"))
relayIP = proxy.proxyIP;
relayPort = msg.port;
encapsulation = proxy.udp_encapsulation;
// debug("Datagram Socket:"+getLocalAddress()+":"+getLocalPort()+"\n");
// debug("Socks5Datagram: "+relayIP+":"+relayPort+"\n");
}
/**
* Closes datagram socket, and proxy connection.
*/
@Override
public void close() {
if (!server_mode)
proxy.endSession();
super.close();
}
private byte[] formHeader(InetAddress ip, int port) {
Socks5Message request = new Socks5Message(0, ip, port);
request.data[0] = 0;
return request.data;
}
/**
* Address assigned by the proxy, to which datagrams are send for relay. It
* is not necesseraly the same address, to which other party should send
* datagrams.
*
* @return Address to which datagrams are send for association.
*/
@Override
public InetAddress getLocalAddress() {
if (server_mode)
return super.getLocalAddress();
return relayIP;
}
/**
* Returns port assigned by the proxy, to which datagrams are relayed. It is
* not the same port to which other party should send datagrams.
*
* @return Port assigned by socks server to which datagrams are send for
* association.
*/
@Override
public int getLocalPort() {
if (server_mode)
return super.getLocalPort();
return relayPort;
}
/**
* This method checks wether proxy still runs udp forwarding service for
* this socket.
* <p>
* This methods checks wether the primary connection to proxy server is
* active. If it is, chances are that proxy continues to forward datagrams
* being send from this socket. If it was closed, most likely datagrams are
* no longer being forwarded by the server.
* <p>
* Proxy might decide to stop forwarding datagrams, in which case it should
* close primary connection. This method allows to check, wether this have
* been done.
* <p>
* You can specify timeout for which we should be checking EOF condition on
* the primary connection. Timeout is in milliseconds. Specifying 0 as
* timeout implies infinity, in which case method will block, until
* connection to proxy is closed or an error happens, and then return false.
* <p>
* One possible scenario is to call isProxyactive(0) in separate thread, and
* once it returned notify other threads about this event.
*
* @param timeout
* For how long this method should block, before returning.
* @return true if connection to proxy is active, false if eof or error
* condition have been encountered on the connection.
*/
public boolean isProxyAlive(int timeout) {
if (server_mode)
return false;
if (proxy != null) {
try {
proxy.proxySocket.setSoTimeout(timeout);
int eof = proxy.in.read();
if (eof < 0)
return false; // EOF encountered.
else
return true; // This really should not happen
} catch (InterruptedIOException iioe) {
return true; // read timed out.
} catch (IOException ioe) {
return false;
}
}
return false;
}
/**
* Receives udp packet. If packet have arrived from the proxy relay server,
* it is processed and address and port of the packet are set to the address
* and port of sending host.<BR>
* If the packet arrived from anywhere else it is not changed.<br>
* <B> NOTE: </B> DatagramPacket size should be at least 10 bytes bigger
* than the largest packet you expect (this is for IPV4 addresses). For
* hostnames and IPV6 it is even more.
*
* @param dp
* Datagram in which all relevent information will be copied.
*/
@Override
public void receive(DatagramPacket dp) throws IOException {
super.receive(dp);
if (server_mode) {
// Drop all datagrams not from relayIP/relayPort
int init_length = dp.getLength();
int initTimeout = getSoTimeout();
long startTime = System.currentTimeMillis();
while (!relayIP.equals(dp.getAddress())
|| relayPort != dp.getPort()) {
// Restore datagram size
dp.setLength(init_length);
// If there is a non-infinit timeout on this socket
// Make sure that it happens no matter how often unexpected
// packets arrive.
if (initTimeout != 0) {
int newTimeout = initTimeout
- (int) (System.currentTimeMillis() - startTime);
if (newTimeout <= 0)
throw new InterruptedIOException(
"In Socks5DatagramSocket->receive()");
setSoTimeout(newTimeout);
}
super.receive(dp);
}
// Restore timeout settings
if (initTimeout != 0)
setSoTimeout(initTimeout);
} else if (!relayIP.equals(dp.getAddress())
|| relayPort != dp.getPort())
return; // Recieved direct packet
// If the datagram is not from the relay server, return it it as is.
byte[] data;
data = dp.getData();
if (encapsulation != null)
data = encapsulation.udpEncapsulate(data, false);
int offset = 0; // Java 1.1
// int offset = dp.getOffset(); //Java 1.2
ByteArrayInputStream bIn = new ByteArrayInputStream(data, offset,
dp.getLength());
ProxyMessage msg = new Socks5Message(bIn);
dp.setPort(msg.port);
dp.setAddress(msg.getInetAddress());
// what wasn't read by the Message is the data
int data_length = bIn.available();
// Shift data to the left
System.arraycopy(data, offset + dp.getLength() - data_length, data,
offset, data_length);
dp.setLength(data_length);
}
/**
* Sends the Datagram either through the proxy or directly depending on
* current proxy settings and destination address. <BR>
*
* <B> NOTE: </B> DatagramPacket size should be at least 10 bytes less than
* the systems limit.
*
* <P>
* See documentation on java.net.DatagramSocket for full details on how to
* use this method.
*
* @param dp
* Datagram to send.
* @throws IOException
* If error happens with I/O.
*/
@Override
public void send(DatagramPacket dp) throws IOException {
// If the host should be accessed directly, send it as is.
if (!server_mode) {
super.send(dp);
// debug("Sending directly:");
return;
}
byte[] head = formHeader(dp.getAddress(), dp.getPort());
byte[] buf = new byte[head.length + dp.getLength()];
byte[] data = dp.getData();
// Merge head and data
System.arraycopy(head, 0, buf, 0, head.length);
// System.arraycopy(data,dp.getOffset(),buf,head.length,dp.getLength());
System.arraycopy(data, 0, buf, head.length, dp.getLength());
if (encapsulation != null)
buf = encapsulation.udpEncapsulate(buf, true);
super.send(new DatagramPacket(buf, buf.length, relayIP, relayPort));
}
// PRIVATE METHODS
// ////////////////
/**
* This method allows to send datagram packets with address type DOMAINNAME.
* SOCKS5 allows to specify host as names rather than ip addresses.Using
* this method one can send udp datagrams through the proxy, without having
* to know the ip address of the destination host.
* <p>
* If proxy specified for that socket has an option resolveAddrLocally set
* to true host will be resolved, and the datagram will be send with address
* type IPV4, if resolve fails, UnknownHostException is thrown.
*
* @param dp
* Datagram to send, it should contain valid port and data
* @param host
* Host name to which datagram should be send.
* @throws IOException
* If error happens with I/O, or the host can't be resolved when
* proxy settings say that hosts should be resolved locally.
* @see Socks5Proxy#resolveAddrLocally(boolean)
*/
public void send(DatagramPacket dp, String host) throws IOException {
dp.setAddress(InetAddress.getByName(host));
super.send(dp);
}
/*
* ======================================================================
*
* //Mainly Test functions //////////////////////
*
* private String bytes2String(byte[] b){ String s=""; char[] hex_digit = {
* '0','1','2','3','4','5','6','7','8','9', 'A','B','C','D','E','F'};
* for(int i=0;i<b.length;++i){ int i1 = (b[i] & 0xF0) >> 4; int i2 = b[i] &
* 0xF; s+=hex_digit[i1]; s+=hex_digit[i2]; s+=" "; } return s; } private
* static final void debug(String s){ if(DEBUG) System.out.print(s); }
*
* private static final boolean DEBUG = true;
*
*
* public static void usage(){ System.err.print(
* "Usage: java Socks.SocksDatagramSocket host port [socksHost socksPort]\n"
* ); }
*
* static final int defaultProxyPort = 1080; //Default Port static final
* String defaultProxyHost = "www-proxy"; //Default proxy
*
* public static void main(String args[]){ int port; String host; int
* proxyPort; String proxyHost; InetAddress ip;
*
* if(args.length > 1 && args.length < 5){ try{
*
* host = args[0]; port = Integer.parseInt(args[1]);
*
* proxyPort =(args.length > 3)? Integer.parseInt(args[3]) :
* defaultProxyPort;
*
* host = args[0]; ip = InetAddress.getByName(host);
*
* proxyHost =(args.length > 2)? args[2] : defaultProxyHost;
*
* Proxy.setDefaultProxy(proxyHost,proxyPort); Proxy p =
* Proxy.getDefaultProxy(); p.addDirect("lux");
*
*
* DatagramSocket ds = new Socks5DatagramSocket();
*
*
* BufferedReader in = new BufferedReader( new
* InputStreamReader(System.in)); String s;
*
* System.out.print("Enter line:"); s = in.readLine();
*
* while(s != null){ byte[] data = (s+"\r\n").getBytes(); DatagramPacket dp
* = new DatagramPacket(data,0,data.length, ip,port);
* System.out.println("Sending to: "+ip+":"+port); ds.send(dp); dp = new
* DatagramPacket(new byte[1024],1024);
*
* System.out.println("Trying to recieve on port:"+ ds.getLocalPort());
* ds.receive(dp); System.out.print("Recieved:\n"+
* "From:"+dp.getAddress()+":"+dp.getPort()+ "\n\n"+ new
* String(dp.getData(),dp.getOffset(),dp.getLength())+"\n" );
* System.out.print("Enter line:"); s = in.readLine();
*
* } ds.close(); System.exit(1);
*
* }catch(SocksException s_ex){ System.err.println("SocksException:"+s_ex);
* s_ex.printStackTrace(); System.exit(1); }catch(IOException io_ex){
* io_ex.printStackTrace(); System.exit(1); }catch(NumberFormatException
* num_ex){ usage(); num_ex.printStackTrace(); System.exit(1); }
*
* }else{ usage(); } }
*/
}
| Java |
package net.sourceforge.jsocks;
/**
* Exception thrown by various socks classes to indicate errors with protocol or
* unsuccessful server responses.
*/
public class SocksException extends java.io.IOException {
private static final long serialVersionUID = 6141184566248512277L;
static final String UNASSIGNED_ERROR_MESSAGE = "Unknown error message";
static final String serverReplyMessage[] = { "Succeeded",
"General SOCKS server failure",
"Connection not allowed by ruleset", "Network unreachable",
"Host unreachable", "Connection refused", "TTL expired",
"Command not supported", "Address type not supported" };
static final String localErrorMessage[] = { "SOCKS server not specified",
"Unable to contact SOCKS server", "IO error",
"None of Authentication methods are supported",
"Authentication failed", "General SOCKS fault" };
String errString;
public int errCode;
/**
* Construct a SocksException with given error code.
* <p>
* Tries to look up message which corresponds to this error code.
*
* @param errCode
* Error code for this exception.
*/
public SocksException(int errCode) {
this.errCode = errCode;
if ((errCode >> 16) == 0) {
// Server reply error message
errString = errCode <= serverReplyMessage.length ? serverReplyMessage[errCode]
: UNASSIGNED_ERROR_MESSAGE;
} else {
// Local error
errCode = (errCode >> 16) - 1;
errString = errCode <= localErrorMessage.length ? localErrorMessage[errCode]
: UNASSIGNED_ERROR_MESSAGE;
}
}
/**
* Constructs a SocksException with given error code and message.
*
* @param errCode
* Error code.
* @param errString
* Error Message.
*/
public SocksException(int errCode, String errString) {
this.errCode = errCode;
this.errString = errString;
}
/**
* Get the error code associated with this exception.
*
* @return Error code associated with this exception.
*/
public int getErrorCode() {
return errCode;
}
/**
* Get human readable representation of this exception.
*
* @return String represntation of this exception.
*/
@Override
public String toString() {
return errString;
}
}// End of SocksException class
| Java |
package com.trilead.ssh2;
/**
* An abstract marker interface implemented by all proxy data implementations.
*
* @see HTTPProxyData
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: ProxyData.java,v 1.1 2007/10/15 12:49:56 cplattne Exp $
*/
public abstract interface ProxyData {
}
| Java |
package com.trilead.ssh2;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Vector;
import com.trilead.ssh2.packets.TypesReader;
import com.trilead.ssh2.packets.TypesWriter;
import com.trilead.ssh2.sftp.AttribFlags;
import com.trilead.ssh2.sftp.ErrorCodes;
import com.trilead.ssh2.sftp.Packet;
/**
* A <code>SFTPv3Client</code> represents a SFTP (protocol version 3) client
* connection tunnelled over a SSH-2 connection. This is a very simple
* (synchronous) implementation.
* <p>
* Basically, most methods in this class map directly to one of the packet types
* described in draft-ietf-secsh-filexfer-02.txt.
* <p>
* Note: this is experimental code.
* <p>
* Error handling: the methods of this class throw IOExceptions. However, unless
* there is catastrophic failure, exceptions of the type {@link SFTPv3Client}
* will be thrown (a subclass of IOException). Therefore, you can implement more
* verbose behavior by checking if a thrown exception if of this type. If yes,
* then you can cast the exception and access detailed information about the
* failure.
* <p>
* Notes about file names, directory names and paths, copy-pasted from the
* specs:
* <ul>
* <li>SFTP v3 represents file names as strings. File names are assumed to use
* the slash ('/') character as a directory separator.</li>
* <li>File names starting with a slash are "absolute", and are relative to the
* root of the file system. Names starting with any other character are relative
* to the user's default directory (home directory).</li>
* <li>Servers SHOULD interpret a path name component ".." as referring to the
* parent directory, and "." as referring to the current directory. If the
* server implementation limits access to certain parts of the file system, it
* must be extra careful in parsing file names when enforcing such restrictions.
* There have been numerous reported security bugs where a ".." in a path name
* has allowed access outside the intended area.</li>
* <li>An empty path name is valid, and it refers to the user's default
* directory (usually the user's home directory).</li>
* </ul>
* <p>
* If you are still not tired then please go on and read the comment for
* {@link #setCharset(String)}.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: SFTPv3Client.java,v 1.3 2008/04/01 12:38:09 cplattne Exp $
*/
public class SFTPv3Client {
final Connection conn;
final Session sess;
final PrintStream debug;
boolean flag_closed = false;
InputStream is;
OutputStream os;
int protocol_version = 0;
HashMap server_extensions = new HashMap();
int next_request_id = 1000;
String charsetName = null;
/**
* Create a SFTP v3 client.
*
* @param conn
* The underlying SSH-2 connection to be used.
* @throws IOException
*/
public SFTPv3Client(Connection conn) throws IOException {
this(conn, null);
}
/**
* Create a SFTP v3 client.
*
* @param conn
* The underlying SSH-2 connection to be used.
* @param debug
* @throws IOException
*
* @deprecated this constructor (debug version) will disappear in the
* future, use {@link #SFTPv3Client(Connection)} instead.
*/
@Deprecated
public SFTPv3Client(Connection conn, PrintStream debug) throws IOException {
if (conn == null)
throw new IllegalArgumentException("Cannot accept null argument!");
this.conn = conn;
this.debug = debug;
if (debug != null)
debug.println("Opening session and starting SFTP subsystem.");
sess = conn.openSession();
sess.startSubSystem("sftp");
is = sess.getStdout();
os = new BufferedOutputStream(sess.getStdin(), 2048);
if ((is == null) || (os == null))
throw new IOException(
"There is a problem with the streams of the underlying channel.");
init();
}
/**
* Have the server canonicalize any given path name to an absolute path.
* This is useful for converting path names containing ".." components or
* relative pathnames without a leading slash into absolute paths.
*
* @param path
* See the {@link SFTPv3Client comment} for the class for more
* details.
* @return An absolute path.
* @throws IOException
*/
public String canonicalPath(String path) throws IOException {
int req_id = generateNextRequestID();
TypesWriter tw = new TypesWriter();
tw.writeString(path, charsetName);
if (debug != null) {
debug.println("Sending SSH_FXP_REALPATH...");
debug.flush();
}
sendMessage(Packet.SSH_FXP_REALPATH, req_id, tw.getBytes());
byte[] resp = receiveMessage(34000);
if (debug != null) {
debug.println("Got REPLY.");
debug.flush();
}
TypesReader tr = new TypesReader(resp);
int t = tr.readByte();
int rep_id = tr.readUINT32();
if (rep_id != req_id)
throw new IOException("The server sent an invalid id field.");
if (t == Packet.SSH_FXP_NAME) {
int count = tr.readUINT32();
if (count != 1)
throw new IOException(
"The server sent an invalid SSH_FXP_NAME packet.");
return tr.readString(charsetName);
}
if (t != Packet.SSH_FXP_STATUS)
throw new IOException(
"The SFTP server sent an unexpected packet type (" + t
+ ")");
int errorCode = tr.readUINT32();
throw new SFTPException(tr.readString(), errorCode);
}
private final void checkHandleValidAndOpen(SFTPv3FileHandle handle)
throws IOException {
if (handle.client != this)
throw new IOException(
"The file handle was created with another SFTPv3FileHandle instance.");
if (handle.isClosed == true)
throw new IOException("The file handle is closed.");
}
/**
* Close this SFTP session. NEVER forget to call this method to free up
* resources - even if you got an exception from one of the other methods.
* Sometimes these other methods may throw an exception, saying that the
* underlying channel is closed (this can happen, e.g., if the other server
* sent a close message.) However, as long as you have not called the
* <code>close()</code> method, you are likely wasting resources.
*
*/
public void close() {
sess.close();
}
/**
* Close a file.
*
* @param handle
* a SFTPv3FileHandle handle
* @throws IOException
*/
public void closeFile(SFTPv3FileHandle handle) throws IOException {
if (handle == null)
throw new IllegalArgumentException(
"the handle argument may not be null");
try {
if (handle.isClosed == false) {
closeHandle(handle.fileHandle);
}
} finally {
handle.isClosed = true;
}
}
private final void closeHandle(byte[] handle) throws IOException {
int req_id = generateNextRequestID();
TypesWriter tw = new TypesWriter();
tw.writeString(handle, 0, handle.length);
sendMessage(Packet.SSH_FXP_CLOSE, req_id, tw.getBytes());
expectStatusOKMessage(req_id);
}
private byte[] createAttrs(SFTPv3FileAttributes attr) {
TypesWriter tw = new TypesWriter();
int attrFlags = 0;
if (attr == null) {
tw.writeUINT32(0);
} else {
if (attr.size != null)
attrFlags = attrFlags | AttribFlags.SSH_FILEXFER_ATTR_SIZE;
if ((attr.uid != null) && (attr.gid != null))
attrFlags = attrFlags | AttribFlags.SSH_FILEXFER_ATTR_V3_UIDGID;
if (attr.permissions != null)
attrFlags = attrFlags
| AttribFlags.SSH_FILEXFER_ATTR_PERMISSIONS;
if ((attr.atime != null) && (attr.mtime != null))
attrFlags = attrFlags
| AttribFlags.SSH_FILEXFER_ATTR_V3_ACMODTIME;
tw.writeUINT32(attrFlags);
if (attr.size != null)
tw.writeUINT64(attr.size.longValue());
if ((attr.uid != null) && (attr.gid != null)) {
tw.writeUINT32(attr.uid.intValue());
tw.writeUINT32(attr.gid.intValue());
}
if (attr.permissions != null)
tw.writeUINT32(attr.permissions.intValue());
if ((attr.atime != null) && (attr.mtime != null)) {
tw.writeUINT32(attr.atime.intValue());
tw.writeUINT32(attr.mtime.intValue());
}
}
return tw.getBytes();
}
/**
* Create a file and open it for reading and writing. Same as
* {@link #createFile(String, SFTPv3FileAttributes) createFile(fileName,
* null)}.
*
* @param fileName
* See the {@link SFTPv3Client comment} for the class for more
* details.
* @return a SFTPv3FileHandle handle
* @throws IOException
*/
public SFTPv3FileHandle createFile(String fileName) throws IOException {
return createFile(fileName, null);
}
/**
* Create a file and open it for reading and writing. You can specify the
* default attributes of the file (the server may or may not respect your
* wishes).
*
* @param fileName
* See the {@link SFTPv3Client comment} for the class for more
* details.
* @param attr
* may be <code>null</code> to use server defaults. Probably only
* the <code>uid</code>, <code>gid</code> and
* <code>permissions</code> (remember the server may apply a
* umask) entries of the {@link SFTPv3FileHandle} structure make
* sense. You need only to set those fields where you want to
* override the server's defaults.
* @return a SFTPv3FileHandle handle
* @throws IOException
*/
public SFTPv3FileHandle createFile(String fileName,
SFTPv3FileAttributes attr) throws IOException {
return openFile(fileName, 0x00000008 | 0x00000003, attr); // SSH_FXF_CREAT
// |
// SSH_FXF_READ
// |
// SSH_FXF_WRITE
}
/**
* Create a file (truncate it if it already exists) and open it for reading
* and writing. Same as
* {@link #createFileTruncate(String, SFTPv3FileAttributes)
* createFileTruncate(fileName, null)}.
*
* @param fileName
* See the {@link SFTPv3Client comment} for the class for more
* details.
* @return a SFTPv3FileHandle handle
* @throws IOException
*/
public SFTPv3FileHandle createFileTruncate(String fileName)
throws IOException {
return createFileTruncate(fileName, null);
}
/**
* reate a file (truncate it if it already exists) and open it for reading
* and writing. You can specify the default attributes of the file (the
* server may or may not respect your wishes).
*
* @param fileName
* See the {@link SFTPv3Client comment} for the class for more
* details.
* @param attr
* may be <code>null</code> to use server defaults. Probably only
* the <code>uid</code>, <code>gid</code> and
* <code>permissions</code> (remember the server may apply a
* umask) entries of the {@link SFTPv3FileHandle} structure make
* sense. You need only to set those fields where you want to
* override the server's defaults.
* @return a SFTPv3FileHandle handle
* @throws IOException
*/
public SFTPv3FileHandle createFileTruncate(String fileName,
SFTPv3FileAttributes attr) throws IOException {
return openFile(fileName, 0x00000018 | 0x00000003, attr); // SSH_FXF_CREAT
// |
// SSH_FXF_TRUNC
// |
// SSH_FXF_READ
// |
// SSH_FXF_WRITE
}
/**
* Create a symbolic link on the server. Creates a link "src" that points to
* "target".
*
* @param src
* See the {@link SFTPv3Client comment} for the class for more
* details.
* @param target
* See the {@link SFTPv3Client comment} for the class for more
* details.
* @throws IOException
*/
public void createSymlink(String src, String target) throws IOException {
int req_id = generateNextRequestID();
/*
* Either I am too stupid to understand the SFTP draft or the OpenSSH
* guys changed the semantics of src and target.
*/
TypesWriter tw = new TypesWriter();
tw.writeString(target, charsetName);
tw.writeString(src, charsetName);
if (debug != null) {
debug.println("Sending SSH_FXP_SYMLINK...");
debug.flush();
}
sendMessage(Packet.SSH_FXP_SYMLINK, req_id, tw.getBytes());
expectStatusOKMessage(req_id);
}
private final String expandString(byte[] b, int off, int len) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < len; i++) {
int c = b[off + i] & 0xff;
if ((c >= 32) && (c <= 126)) {
sb.append((char) c);
} else {
sb.append("{0x" + Integer.toHexString(c) + "}");
}
}
return sb.toString();
}
private void expectStatusOKMessage(int id) throws IOException {
byte[] resp = receiveMessage(34000);
if (debug != null) {
debug.println("Got REPLY.");
debug.flush();
}
TypesReader tr = new TypesReader(resp);
int t = tr.readByte();
int rep_id = tr.readUINT32();
if (rep_id != id)
throw new IOException("The server sent an invalid id field.");
if (t != Packet.SSH_FXP_STATUS)
throw new IOException(
"The SFTP server sent an unexpected packet type (" + t
+ ")");
int errorCode = tr.readUINT32();
if (errorCode == ErrorCodes.SSH_FX_OK)
return;
throw new SFTPException(tr.readString(), errorCode);
}
/**
* Modify the attributes of a file. Used for operations such as changing the
* ownership, permissions or access times, as well as for truncating a file.
*
* @param handle
* a SFTPv3FileHandle handle
* @param attr
* A SFTPv3FileAttributes object. Specifies the modifications to
* be made to the attributes of the file. Empty fields will be
* ignored.
* @throws IOException
*/
public void fsetstat(SFTPv3FileHandle handle, SFTPv3FileAttributes attr)
throws IOException {
checkHandleValidAndOpen(handle);
int req_id = generateNextRequestID();
TypesWriter tw = new TypesWriter();
tw.writeString(handle.fileHandle, 0, handle.fileHandle.length);
tw.writeBytes(createAttrs(attr));
if (debug != null) {
debug.println("Sending SSH_FXP_FSETSTAT...");
debug.flush();
}
sendMessage(Packet.SSH_FXP_FSETSTAT, req_id, tw.getBytes());
expectStatusOKMessage(req_id);
}
/**
* Retrieve the file attributes of an open file.
*
* @param handle
* a SFTPv3FileHandle handle.
* @return a SFTPv3FileAttributes object.
* @throws IOException
*/
public SFTPv3FileAttributes fstat(SFTPv3FileHandle handle)
throws IOException {
checkHandleValidAndOpen(handle);
int req_id = generateNextRequestID();
TypesWriter tw = new TypesWriter();
tw.writeString(handle.fileHandle, 0, handle.fileHandle.length);
if (debug != null) {
debug.println("Sending SSH_FXP_FSTAT...");
debug.flush();
}
sendMessage(Packet.SSH_FXP_FSTAT, req_id, tw.getBytes());
byte[] resp = receiveMessage(34000);
if (debug != null) {
debug.println("Got REPLY.");
debug.flush();
}
TypesReader tr = new TypesReader(resp);
int t = tr.readByte();
int rep_id = tr.readUINT32();
if (rep_id != req_id)
throw new IOException("The server sent an invalid id field.");
if (t == Packet.SSH_FXP_ATTRS) {
return readAttrs(tr);
}
if (t != Packet.SSH_FXP_STATUS)
throw new IOException(
"The SFTP server sent an unexpected packet type (" + t
+ ")");
int errorCode = tr.readUINT32();
throw new SFTPException(tr.readString(), errorCode);
}
private final int generateNextRequestID() {
synchronized (this) {
return next_request_id++;
}
}
/**
* The currently used charset for filename encoding/decoding.
*
* @see #setCharset(String)
*
* @return The name of the charset (<code>null</code> if the platform's
* default charset is being used)
*/
public String getCharset() {
return charsetName;
}
/**
* Returns the negotiated SFTP protocol version between the client and the
* server.
*
* @return SFTP protocol version, i.e., "3".
*
*/
public int getProtocolVersion() {
return protocol_version;
}
private void init() throws IOException {
/* Send SSH_FXP_INIT (version 3) */
final int client_version = 3;
if (debug != null)
debug.println("Sending SSH_FXP_INIT (" + client_version + ")...");
TypesWriter tw = new TypesWriter();
tw.writeUINT32(client_version);
sendMessage(Packet.SSH_FXP_INIT, 0, tw.getBytes());
/* Receive SSH_FXP_VERSION */
if (debug != null)
debug.println("Waiting for SSH_FXP_VERSION...");
TypesReader tr = new TypesReader(receiveMessage(34000)); /*
* Should be
* enough for
* any
* reasonable
* server
*/
int type = tr.readByte();
if (type != Packet.SSH_FXP_VERSION) {
throw new IOException(
"The server did not send a SSH_FXP_VERSION packet (got "
+ type + ")");
}
protocol_version = tr.readUINT32();
if (debug != null)
debug.println("SSH_FXP_VERSION: protocol_version = "
+ protocol_version);
if (protocol_version != 3)
throw new IOException("Server version " + protocol_version
+ " is currently not supported");
/* Read and save extensions (if any) for later use */
while (tr.remain() != 0) {
String name = tr.readString();
byte[] value = tr.readByteString();
server_extensions.put(name, value);
if (debug != null)
debug.println("SSH_FXP_VERSION: extension: " + name + " = '"
+ expandString(value, 0, value.length) + "'");
}
}
/**
* List the contents of a directory.
*
* @param dirName
* See the {@link SFTPv3Client comment} for the class for more
* details.
* @return A Vector containing {@link SFTPv3DirectoryEntry} objects.
* @throws IOException
*/
public Vector ls(String dirName) throws IOException {
byte[] handle = openDirectory(dirName);
Vector result = scanDirectory(handle);
closeHandle(handle);
return result;
}
/**
* Retrieve the file attributes of a file. This method does NOT follow
* symbolic links on the server.
*
* @see #stat(String)
*
* @param path
* See the {@link SFTPv3Client comment} for the class for more
* details.
* @return a SFTPv3FileAttributes object.
* @throws IOException
*/
public SFTPv3FileAttributes lstat(String path) throws IOException {
return statBoth(path, Packet.SSH_FXP_LSTAT);
}
/**
* Create a new directory.
*
* @param dirName
* See the {@link SFTPv3Client comment} for the class for more
* details.
* @param posixPermissions
* the permissions for this directory, e.g., "0700" (remember
* that this is octal noation). The server will likely apply a
* umask.
*
* @throws IOException
*/
public void mkdir(String dirName, int posixPermissions) throws IOException {
int req_id = generateNextRequestID();
TypesWriter tw = new TypesWriter();
tw.writeString(dirName, charsetName);
tw.writeUINT32(AttribFlags.SSH_FILEXFER_ATTR_PERMISSIONS);
tw.writeUINT32(posixPermissions);
sendMessage(Packet.SSH_FXP_MKDIR, req_id, tw.getBytes());
expectStatusOKMessage(req_id);
}
/**
* Move a file or directory.
*
* @param oldPath
* See the {@link SFTPv3Client comment} for the class for more
* details.
* @param newPath
* See the {@link SFTPv3Client comment} for the class for more
* details.
* @throws IOException
*/
public void mv(String oldPath, String newPath) throws IOException {
int req_id = generateNextRequestID();
TypesWriter tw = new TypesWriter();
tw.writeString(oldPath, charsetName);
tw.writeString(newPath, charsetName);
sendMessage(Packet.SSH_FXP_RENAME, req_id, tw.getBytes());
expectStatusOKMessage(req_id);
}
private final byte[] openDirectory(String path) throws IOException {
int req_id = generateNextRequestID();
TypesWriter tw = new TypesWriter();
tw.writeString(path, charsetName);
if (debug != null) {
debug.println("Sending SSH_FXP_OPENDIR...");
debug.flush();
}
sendMessage(Packet.SSH_FXP_OPENDIR, req_id, tw.getBytes());
byte[] resp = receiveMessage(34000);
TypesReader tr = new TypesReader(resp);
int t = tr.readByte();
int rep_id = tr.readUINT32();
if (rep_id != req_id)
throw new IOException("The server sent an invalid id field.");
if (t == Packet.SSH_FXP_HANDLE) {
if (debug != null) {
debug.println("Got SSH_FXP_HANDLE.");
debug.flush();
}
byte[] handle = tr.readByteString();
return handle;
}
if (t != Packet.SSH_FXP_STATUS)
throw new IOException(
"The SFTP server sent an unexpected packet type (" + t
+ ")");
int errorCode = tr.readUINT32();
String errorMessage = tr.readString();
throw new SFTPException(errorMessage, errorCode);
}
private SFTPv3FileHandle openFile(String fileName, int flags,
SFTPv3FileAttributes attr) throws IOException {
int req_id = generateNextRequestID();
TypesWriter tw = new TypesWriter();
tw.writeString(fileName, charsetName);
tw.writeUINT32(flags);
tw.writeBytes(createAttrs(attr));
if (debug != null) {
debug.println("Sending SSH_FXP_OPEN...");
debug.flush();
}
sendMessage(Packet.SSH_FXP_OPEN, req_id, tw.getBytes());
byte[] resp = receiveMessage(34000);
TypesReader tr = new TypesReader(resp);
int t = tr.readByte();
int rep_id = tr.readUINT32();
if (rep_id != req_id)
throw new IOException("The server sent an invalid id field.");
if (t == Packet.SSH_FXP_HANDLE) {
if (debug != null) {
debug.println("Got SSH_FXP_HANDLE.");
debug.flush();
}
return new SFTPv3FileHandle(this, tr.readByteString());
}
if (t != Packet.SSH_FXP_STATUS)
throw new IOException(
"The SFTP server sent an unexpected packet type (" + t
+ ")");
int errorCode = tr.readUINT32();
String errorMessage = tr.readString();
throw new SFTPException(errorMessage, errorCode);
}
/**
* Open a file for reading.
*
* @param fileName
* See the {@link SFTPv3Client comment} for the class for more
* details.
* @return a SFTPv3FileHandle handle
* @throws IOException
*/
public SFTPv3FileHandle openFileRO(String fileName) throws IOException {
return openFile(fileName, 0x00000001, null); // SSH_FXF_READ
}
/**
* Open a file for reading and writing.
*
* @param fileName
* See the {@link SFTPv3Client comment} for the class for more
* details.
* @return a SFTPv3FileHandle handle
* @throws IOException
*/
public SFTPv3FileHandle openFileRW(String fileName) throws IOException {
return openFile(fileName, 0x00000003, null); // SSH_FXF_READ |
// SSH_FXF_WRITE
}
/**
* Read bytes from a file. No more than 32768 bytes may be read at once. Be
* aware that the semantics of read() are different than for Java streams.
* <p>
* <ul>
* <li>The server will read as many bytes as it can from the file (up to
* <code>len</code>), and return them.</li>
* <li>If EOF is encountered before reading any data, <code>-1</code> is
* returned.
* <li>If an error occurs, an exception is thrown</li>.
* <li>For normal disk files, it is guaranteed that the server will return
* the specified number of bytes, or up to end of file. For, e.g., device
* files this may return fewer bytes than requested.</li>
* </ul>
*
* @param handle
* a SFTPv3FileHandle handle
* @param fileOffset
* offset (in bytes) in the file
* @param dst
* the destination byte array
* @param dstoff
* offset in the destination byte array
* @param len
* how many bytes to read, 0 < len <= 32768 bytes
* @return the number of bytes that could be read, may be less than
* requested if the end of the file is reached, -1 is returned in
* case of <code>EOF</code>
* @throws IOException
*/
public int read(SFTPv3FileHandle handle, long fileOffset, byte[] dst,
int dstoff, int len) throws IOException {
checkHandleValidAndOpen(handle);
if ((len > 32768) || (len <= 0))
throw new IllegalArgumentException("invalid len argument");
int req_id = generateNextRequestID();
TypesWriter tw = new TypesWriter();
tw.writeString(handle.fileHandle, 0, handle.fileHandle.length);
tw.writeUINT64(fileOffset);
tw.writeUINT32(len);
if (debug != null) {
debug.println("Sending SSH_FXP_READ...");
debug.flush();
}
sendMessage(Packet.SSH_FXP_READ, req_id, tw.getBytes());
byte[] resp = receiveMessage(34000);
TypesReader tr = new TypesReader(resp);
int t = tr.readByte();
int rep_id = tr.readUINT32();
if (rep_id != req_id)
throw new IOException("The server sent an invalid id field.");
if (t == Packet.SSH_FXP_DATA) {
if (debug != null) {
debug.println("Got SSH_FXP_DATA...");
debug.flush();
}
int readLen = tr.readUINT32();
if ((readLen < 0) || (readLen > len))
throw new IOException(
"The server sent an invalid length field.");
tr.readBytes(dst, dstoff, readLen);
return readLen;
}
if (t != Packet.SSH_FXP_STATUS)
throw new IOException(
"The SFTP server sent an unexpected packet type (" + t
+ ")");
int errorCode = tr.readUINT32();
if (errorCode == ErrorCodes.SSH_FX_EOF) {
if (debug != null) {
debug.println("Got SSH_FX_EOF.");
debug.flush();
}
return -1;
}
String errorMessage = tr.readString();
throw new SFTPException(errorMessage, errorCode);
}
private SFTPv3FileAttributes readAttrs(TypesReader tr) throws IOException {
/*
* uint32 flags uint64 size present only if flag SSH_FILEXFER_ATTR_SIZE
* uint32 uid present only if flag SSH_FILEXFER_ATTR_V3_UIDGID uint32
* gid present only if flag SSH_FILEXFER_ATTR_V3_UIDGID uint32
* permissions present only if flag SSH_FILEXFER_ATTR_PERMISSIONS uint32
* atime present only if flag SSH_FILEXFER_ATTR_V3_ACMODTIME uint32
* mtime present only if flag SSH_FILEXFER_ATTR_V3_ACMODTIME uint32
* extended_count present only if flag SSH_FILEXFER_ATTR_EXTENDED string
* extended_type string extended_data ... more extended data
* (extended_type - extended_data pairs), so that number of pairs equals
* extended_count
*/
SFTPv3FileAttributes fa = new SFTPv3FileAttributes();
int flags = tr.readUINT32();
if ((flags & AttribFlags.SSH_FILEXFER_ATTR_SIZE) != 0) {
if (debug != null)
debug.println("SSH_FILEXFER_ATTR_SIZE");
fa.size = new Long(tr.readUINT64());
}
if ((flags & AttribFlags.SSH_FILEXFER_ATTR_V3_UIDGID) != 0) {
if (debug != null)
debug.println("SSH_FILEXFER_ATTR_V3_UIDGID");
fa.uid = new Integer(tr.readUINT32());
fa.gid = new Integer(tr.readUINT32());
}
if ((flags & AttribFlags.SSH_FILEXFER_ATTR_PERMISSIONS) != 0) {
if (debug != null)
debug.println("SSH_FILEXFER_ATTR_PERMISSIONS");
fa.permissions = new Integer(tr.readUINT32());
}
if ((flags & AttribFlags.SSH_FILEXFER_ATTR_V3_ACMODTIME) != 0) {
if (debug != null)
debug.println("SSH_FILEXFER_ATTR_V3_ACMODTIME");
fa.atime = new Long(tr.readUINT32() & 0xffffffffl);
fa.mtime = new Long(tr.readUINT32() & 0xffffffffl);
}
if ((flags & AttribFlags.SSH_FILEXFER_ATTR_EXTENDED) != 0) {
int count = tr.readUINT32();
if (debug != null)
debug.println("SSH_FILEXFER_ATTR_EXTENDED (" + count + ")");
/* Read it anyway to detect corrupt packets */
while (count > 0) {
tr.readByteString();
tr.readByteString();
count--;
}
}
return fa;
}
private final void readBytes(byte[] buff, int pos, int len)
throws IOException {
while (len > 0) {
int count = is.read(buff, pos, len);
if (count < 0)
throw new IOException("Unexpected end of sftp stream.");
if ((count == 0) || (count > len))
throw new IOException(
"Underlying stream implementation is bogus!");
len -= count;
pos += count;
}
}
/**
* Read the target of a symbolic link.
*
* @param path
* See the {@link SFTPv3Client comment} for the class for more
* details.
* @return The target of the link.
* @throws IOException
*/
public String readLink(String path) throws IOException {
int req_id = generateNextRequestID();
TypesWriter tw = new TypesWriter();
tw.writeString(path, charsetName);
if (debug != null) {
debug.println("Sending SSH_FXP_READLINK...");
debug.flush();
}
sendMessage(Packet.SSH_FXP_READLINK, req_id, tw.getBytes());
byte[] resp = receiveMessage(34000);
if (debug != null) {
debug.println("Got REPLY.");
debug.flush();
}
TypesReader tr = new TypesReader(resp);
int t = tr.readByte();
int rep_id = tr.readUINT32();
if (rep_id != req_id)
throw new IOException("The server sent an invalid id field.");
if (t == Packet.SSH_FXP_NAME) {
int count = tr.readUINT32();
if (count != 1)
throw new IOException(
"The server sent an invalid SSH_FXP_NAME packet.");
return tr.readString(charsetName);
}
if (t != Packet.SSH_FXP_STATUS)
throw new IOException(
"The SFTP server sent an unexpected packet type (" + t
+ ")");
int errorCode = tr.readUINT32();
throw new SFTPException(tr.readString(), errorCode);
}
/**
* Read a message and guarantee that the <b>contents</b> is not larger than
* <code>maxlen</code> bytes.
* <p>
* Note: receiveMessage(34000) actually means that the message may be up to
* 34004 bytes (the length attribute preceeding the contents is 4 bytes).
*
* @param maxlen
* @return the message contents
* @throws IOException
*/
private final byte[] receiveMessage(int maxlen) throws IOException {
byte[] msglen = new byte[4];
readBytes(msglen, 0, 4);
int len = (((msglen[0] & 0xff) << 24) | ((msglen[1] & 0xff) << 16)
| ((msglen[2] & 0xff) << 8) | (msglen[3] & 0xff));
if ((len > maxlen) || (len <= 0))
throw new IOException("Illegal sftp packet len: " + len);
byte[] msg = new byte[len];
readBytes(msg, 0, len);
return msg;
}
/**
* Remove a file.
*
* @param fileName
* See the {@link SFTPv3Client comment} for the class for more
* details.
* @throws IOException
*/
public void rm(String fileName) throws IOException {
int req_id = generateNextRequestID();
TypesWriter tw = new TypesWriter();
tw.writeString(fileName, charsetName);
sendMessage(Packet.SSH_FXP_REMOVE, req_id, tw.getBytes());
expectStatusOKMessage(req_id);
}
// Append is broken (already in the specification, because there is no way
// to
// send a write operation (what offset to use??))
// public SFTPv3FileHandle openFileRWAppend(String fileName) throws
// IOException
// {
// return openFile(fileName, 0x00000007, null); // SSH_FXF_READ |
// SSH_FXF_WRITE | SSH_FXF_APPEND
// }
/**
* Remove an empty directory.
*
* @param dirName
* See the {@link SFTPv3Client comment} for the class for more
* details.
* @throws IOException
*/
public void rmdir(String dirName) throws IOException {
int req_id = generateNextRequestID();
TypesWriter tw = new TypesWriter();
tw.writeString(dirName, charsetName);
sendMessage(Packet.SSH_FXP_RMDIR, req_id, tw.getBytes());
expectStatusOKMessage(req_id);
}
private final Vector scanDirectory(byte[] handle) throws IOException {
Vector files = new Vector();
while (true) {
int req_id = generateNextRequestID();
TypesWriter tw = new TypesWriter();
tw.writeString(handle, 0, handle.length);
if (debug != null) {
debug.println("Sending SSH_FXP_READDIR...");
debug.flush();
}
sendMessage(Packet.SSH_FXP_READDIR, req_id, tw.getBytes());
/* Some servers send here a packet with size > 34000 */
/* To whom it may concern: please learn to read the specs. */
byte[] resp = receiveMessage(65536);
if (debug != null) {
debug.println("Got REPLY.");
debug.flush();
}
TypesReader tr = new TypesReader(resp);
int t = tr.readByte();
int rep_id = tr.readUINT32();
if (rep_id != req_id)
throw new IOException("The server sent an invalid id field.");
if (t == Packet.SSH_FXP_NAME) {
int count = tr.readUINT32();
if (debug != null)
debug.println("Parsing " + count + " name entries...");
while (count > 0) {
SFTPv3DirectoryEntry dirEnt = new SFTPv3DirectoryEntry();
dirEnt.filename = tr.readString(charsetName);
dirEnt.longEntry = tr.readString(charsetName);
dirEnt.attributes = readAttrs(tr);
files.addElement(dirEnt);
if (debug != null)
debug.println("File: '" + dirEnt.filename + "'");
count--;
}
continue;
}
if (t != Packet.SSH_FXP_STATUS)
throw new IOException(
"The SFTP server sent an unexpected packet type (" + t
+ ")");
int errorCode = tr.readUINT32();
if (errorCode == ErrorCodes.SSH_FX_EOF)
return files;
throw new SFTPException(tr.readString(), errorCode);
}
}
private final void sendMessage(int type, int requestId, byte[] msg)
throws IOException {
sendMessage(type, requestId, msg, 0, msg.length);
}
private final void sendMessage(int type, int requestId, byte[] msg,
int off, int len) throws IOException {
int msglen = len + 1;
if (type != Packet.SSH_FXP_INIT)
msglen += 4;
os.write(msglen >> 24);
os.write(msglen >> 16);
os.write(msglen >> 8);
os.write(msglen);
os.write(type);
if (type != Packet.SSH_FXP_INIT) {
os.write(requestId >> 24);
os.write(requestId >> 16);
os.write(requestId >> 8);
os.write(requestId);
}
os.write(msg, off, len);
os.flush();
}
/**
* Set the charset used to convert between Java Unicode Strings and byte
* encodings used by the server for paths and file names. Unfortunately, the
* SFTP v3 draft says NOTHING about such conversions (well, with the
* exception of error messages which have to be in UTF-8). Newer drafts
* specify to use UTF-8 for file names (if I remember correctly). However, a
* quick test using OpenSSH serving a EXT-3 filesystem has shown that UTF-8
* seems to be a bad choice for SFTP v3 (tested with filenames containing
* german umlauts). "windows-1252" seems to work better for Europe. Luckily,
* "windows-1252" is the platform default in my case =).
* <p>
* If you don't set anything, then the platform default will be used (this
* is the default behavior).
*
* @see #getCharset()
*
* @param charset
* the name of the charset to be used or <code>null</code> to use
* the platform's default encoding.
* @throws IOException
*/
public void setCharset(String charset) throws IOException {
if (charset == null) {
charsetName = charset;
return;
}
try {
Charset.forName(charset);
} catch (Exception e) {
throw (IOException) new IOException("This charset is not supported")
.initCause(e);
}
charsetName = charset;
}
/**
* Modify the attributes of a file. Used for operations such as changing the
* ownership, permissions or access times, as well as for truncating a file.
*
* @param path
* See the {@link SFTPv3Client comment} for the class for more
* details.
* @param attr
* A SFTPv3FileAttributes object. Specifies the modifications to
* be made to the attributes of the file. Empty fields will be
* ignored.
* @throws IOException
*/
public void setstat(String path, SFTPv3FileAttributes attr)
throws IOException {
int req_id = generateNextRequestID();
TypesWriter tw = new TypesWriter();
tw.writeString(path, charsetName);
tw.writeBytes(createAttrs(attr));
if (debug != null) {
debug.println("Sending SSH_FXP_SETSTAT...");
debug.flush();
}
sendMessage(Packet.SSH_FXP_SETSTAT, req_id, tw.getBytes());
expectStatusOKMessage(req_id);
}
/**
* Retrieve the file attributes of a file. This method follows symbolic
* links on the server.
*
* @see #lstat(String)
*
* @param path
* See the {@link SFTPv3Client comment} for the class for more
* details.
* @return a SFTPv3FileAttributes object.
* @throws IOException
*/
public SFTPv3FileAttributes stat(String path) throws IOException {
return statBoth(path, Packet.SSH_FXP_STAT);
}
private SFTPv3FileAttributes statBoth(String path, int statMethod)
throws IOException {
int req_id = generateNextRequestID();
TypesWriter tw = new TypesWriter();
tw.writeString(path, charsetName);
if (debug != null) {
debug.println("Sending SSH_FXP_STAT/SSH_FXP_LSTAT...");
debug.flush();
}
sendMessage(statMethod, req_id, tw.getBytes());
byte[] resp = receiveMessage(34000);
if (debug != null) {
debug.println("Got REPLY.");
debug.flush();
}
TypesReader tr = new TypesReader(resp);
int t = tr.readByte();
int rep_id = tr.readUINT32();
if (rep_id != req_id)
throw new IOException("The server sent an invalid id field.");
if (t == Packet.SSH_FXP_ATTRS) {
return readAttrs(tr);
}
if (t != Packet.SSH_FXP_STATUS)
throw new IOException(
"The SFTP server sent an unexpected packet type (" + t
+ ")");
int errorCode = tr.readUINT32();
throw new SFTPException(tr.readString(), errorCode);
}
/**
* Write bytes to a file. If <code>len</code> > 32768, then the write
* operation will be split into multiple writes.
*
* @param handle
* a SFTPv3FileHandle handle.
* @param fileOffset
* offset (in bytes) in the file.
* @param src
* the source byte array.
* @param srcoff
* offset in the source byte array.
* @param len
* how many bytes to write.
* @throws IOException
*/
public void write(SFTPv3FileHandle handle, long fileOffset, byte[] src,
int srcoff, int len) throws IOException {
checkHandleValidAndOpen(handle);
while (len > 0) {
int writeRequestLen = len;
if (writeRequestLen > 32768)
writeRequestLen = 32768;
int req_id = generateNextRequestID();
TypesWriter tw = new TypesWriter();
tw.writeString(handle.fileHandle, 0, handle.fileHandle.length);
tw.writeUINT64(fileOffset);
tw.writeString(src, srcoff, writeRequestLen);
if (debug != null) {
debug.println("Sending SSH_FXP_WRITE...");
debug.flush();
}
sendMessage(Packet.SSH_FXP_WRITE, req_id, tw.getBytes());
fileOffset += writeRequestLen;
srcoff += writeRequestLen;
len -= writeRequestLen;
byte[] resp = receiveMessage(34000);
TypesReader tr = new TypesReader(resp);
int t = tr.readByte();
int rep_id = tr.readUINT32();
if (rep_id != req_id)
throw new IOException("The server sent an invalid id field.");
if (t != Packet.SSH_FXP_STATUS)
throw new IOException(
"The SFTP server sent an unexpected packet type (" + t
+ ")");
int errorCode = tr.readUINT32();
if (errorCode == ErrorCodes.SSH_FX_OK)
continue;
String errorMessage = tr.readString();
throw new SFTPException(errorMessage, errorCode);
}
}
}
| Java |
package com.trilead.ssh2;
/**
* An <code>InteractiveCallback</code> is used to respond to challenges sent by
* the server if authentication mode "keyboard-interactive" is selected.
*
* @see Connection#authenticateWithKeyboardInteractive(String, String[],
* InteractiveCallback)
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: InteractiveCallback.java,v 1.1 2007/10/15 12:49:56 cplattne Exp
* $
*/
public interface InteractiveCallback {
/**
* This callback interface is used during a "keyboard-interactive"
* authentication. Every time the server sends a set of challenges (however,
* most often just one challenge at a time), this callback function will be
* called to give your application a chance to talk to the user and to
* determine the response(s).
* <p>
* Some copy-paste information from the standard: a command line interface
* (CLI) client SHOULD print the name and instruction (if non-empty), adding
* newlines. Then for each prompt in turn, the client SHOULD display the
* prompt and read the user input. The name and instruction fields MAY be
* empty strings, the client MUST be prepared to handle this correctly. The
* prompt field(s) MUST NOT be empty strings.
* <p>
* Please refer to draft-ietf-secsh-auth-kbdinteract-XX.txt for the details.
* <p>
* Note: clients SHOULD use control character filtering as discussed in
* RFC4251 to avoid attacks by including terminal control characters in the
* fields to be displayed.
*
* @param name
* the name String sent by the server.
* @param instruction
* the instruction String sent by the server.
* @param numPrompts
* number of prompts - may be zero (in this case, you should just
* return a String array of length zero).
* @param prompt
* an array (length <code>numPrompts</code>) of Strings
* @param echo
* an array (length <code>numPrompts</code>) of booleans. For
* each prompt, the corresponding echo field indicates whether or
* not the user input should be echoed as characters are typed.
* @return an array of reponses - the array size must match the parameter
* <code>numPrompts</code>.
*/
public String[] replyToChallenge(String name, String instruction,
int numPrompts, String[] prompt, boolean[] echo) throws Exception;
}
| Java |
package com.trilead.ssh2;
/**
* A <code>DHGexParameters</code> object can be used to specify parameters for
* the diffie-hellman group exchange.
* <p>
* Depending on which constructor is used, either the use of a
* <code>SSH_MSG_KEX_DH_GEX_REQUEST</code> or
* <code>SSH_MSG_KEX_DH_GEX_REQUEST_OLD</code> can be forced.
*
* @see Connection#setDHGexParameters(DHGexParameters)
* @author Christian Plattner, plattner@trilead.com
* @version $Id: DHGexParameters.java,v 1.1 2007/10/15 12:49:56 cplattne Exp $
*/
public class DHGexParameters {
private final int min_group_len;
private final int pref_group_len;
private final int max_group_len;
private static final int MIN_ALLOWED = 1024;
private static final int MAX_ALLOWED = 8192;
/**
* Same as calling {@link #DHGexParameters(int, int, int)
* DHGexParameters(1024, 1024, 4096)}. This is also the default used by the
* Connection class.
*
*/
public DHGexParameters() {
this(1024, 1024, 4096);
}
/**
* This constructor can be used to force the sending of a
* <code>SSH_MSG_KEX_DH_GEX_REQUEST_OLD</code> request. Internally, the
* minimum and maximum group lengths will be set to zero.
*
* @param pref_group_len
* has to be >= 1024 and <= 8192
*/
public DHGexParameters(int pref_group_len) {
if ((pref_group_len < MIN_ALLOWED) || (pref_group_len > MAX_ALLOWED))
throw new IllegalArgumentException("pref_group_len out of range!");
this.pref_group_len = pref_group_len;
this.min_group_len = 0;
this.max_group_len = 0;
}
/**
* This constructor can be used to force the sending of a
* <code>SSH_MSG_KEX_DH_GEX_REQUEST</code> request.
* <p>
* Note: older OpenSSH servers don't understand this request, in which case
* you should use the {@link #DHGexParameters(int)} constructor.
* <p>
* All values have to be >= 1024 and <= 8192. Furthermore,
* min_group_len <= pref_group_len <= max_group_len.
*
* @param min_group_len
* @param pref_group_len
* @param max_group_len
*/
public DHGexParameters(int min_group_len, int pref_group_len,
int max_group_len) {
if ((min_group_len < MIN_ALLOWED) || (min_group_len > MAX_ALLOWED))
throw new IllegalArgumentException("min_group_len out of range!");
if ((pref_group_len < MIN_ALLOWED) || (pref_group_len > MAX_ALLOWED))
throw new IllegalArgumentException("pref_group_len out of range!");
if ((max_group_len < MIN_ALLOWED) || (max_group_len > MAX_ALLOWED))
throw new IllegalArgumentException("max_group_len out of range!");
if ((pref_group_len < min_group_len)
|| (pref_group_len > max_group_len))
throw new IllegalArgumentException(
"pref_group_len is incompatible with min and max!");
if (max_group_len < min_group_len)
throw new IllegalArgumentException(
"max_group_len must not be smaller than min_group_len!");
this.min_group_len = min_group_len;
this.pref_group_len = pref_group_len;
this.max_group_len = max_group_len;
}
/**
* Get the maximum group length.
*
* @return the maximum group length, may be <code>zero</code> if
* SSH_MSG_KEX_DH_GEX_REQUEST_OLD should be requested
*/
public int getMax_group_len() {
return max_group_len;
}
/**
* Get the minimum group length.
*
* @return minimum group length, may be <code>zero</code> if
* SSH_MSG_KEX_DH_GEX_REQUEST_OLD should be requested
*/
public int getMin_group_len() {
return min_group_len;
}
/**
* Get the preferred group length.
*
* @return the preferred group length
*/
public int getPref_group_len() {
return pref_group_len;
}
}
| Java |
package com.trilead.ssh2;
/**
* A <code>ConnectionMonitor</code> is used to get notified when the underlying
* socket of a connection is closed.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: ConnectionMonitor.java,v 1.1 2007/10/15 12:49:56 cplattne Exp $
*/
public interface ConnectionMonitor {
/**
* This method is called after the connection's underlying socket has been
* closed. E.g., due to the {@link Connection#close()} request of the user,
* if the peer closed the connection, due to a fatal error during connect()
* (also if the socket cannot be established) or if a fatal error occured on
* an established connection.
* <p>
* This is an experimental feature.
* <p>
* You MUST NOT make any assumption about the thread that invokes this
* method.
* <p>
* <b>Please note: if the connection is not connected (e.g., there was no
* successful connect() call), then the invocation of
* {@link Connection#close()} will NOT trigger this method.</b>
*
* @see Connection#addConnectionMonitor(ConnectionMonitor)
*
* @param reason
* Includes an indication why the socket was closed.
*/
public void connectionLost(Throwable reason);
} | Java |
package com.trilead.ssh2;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* A very basic <code>SCPClient</code> that can be used to copy files from/to
* the SSH-2 server. On the server side, the "scp" program must be in the PATH.
* <p>
* This scp client is thread safe - you can download (and upload) different sets
* of files concurrently without any troubles. The <code>SCPClient</code> is
* actually mapping every request to a distinct {@link Session}.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: SCPClient.java,v 1.2 2008/04/01 12:38:09 cplattne Exp $
*/
public class SCPClient {
class LenNamePair {
long length;
String filename;
}
Connection conn;
public SCPClient(Connection conn) {
if (conn == null)
throw new IllegalArgumentException("Cannot accept null argument!");
this.conn = conn;
}
/**
* Download a file from the remote server and pipe its contents into an
* <code>OutputStream</code>. Please note that, to enable flexible usage of
* this method, the <code>OutputStream</code> will not be closed nor
* flushed.
*
* @param remoteFile
* Path and name of the remote file.
* @param target
* OutputStream where the contents of the file will be sent to.
* @throws IOException
*/
public void get(String remoteFile, OutputStream target) throws IOException {
get(new String[] { remoteFile }, new OutputStream[] { target });
}
private void get(String remoteFiles[], OutputStream[] targets)
throws IOException {
Session sess = null;
if ((remoteFiles == null) || (targets == null))
throw new IllegalArgumentException("Null argument.");
if (remoteFiles.length != targets.length)
throw new IllegalArgumentException(
"Length of arguments does not match.");
if (remoteFiles.length == 0)
return;
String cmd = "scp -f";
for (int i = 0; i < remoteFiles.length; i++) {
if (remoteFiles[i] == null)
throw new IllegalArgumentException(
"Cannot accept null filename.");
String tmp = remoteFiles[i].trim();
if (tmp.length() == 0)
throw new IllegalArgumentException(
"Cannot accept empty filename.");
cmd += (" " + tmp);
}
try {
sess = conn.openSession();
sess.execCommand(cmd);
receiveFiles(sess, targets);
} catch (IOException e) {
throw (IOException) new IOException("Error during SCP transfer.")
.initCause(e);
} finally {
if (sess != null)
sess.close();
}
}
/**
* Download a file from the remote server to a local directory.
*
* @param remoteFile
* Path and name of the remote file.
* @param localTargetDirectory
* Local directory to put the downloaded file.
*
* @throws IOException
*/
public void get(String remoteFile, String localTargetDirectory)
throws IOException {
get(new String[] { remoteFile }, localTargetDirectory);
}
/**
* Download a set of files from the remote server to a local directory.
*
* @param remoteFiles
* Paths and names of the remote files.
* @param localTargetDirectory
* Local directory to put the downloaded files.
*
* @throws IOException
*/
public void get(String remoteFiles[], String localTargetDirectory)
throws IOException {
Session sess = null;
if ((remoteFiles == null) || (localTargetDirectory == null))
throw new IllegalArgumentException("Null argument.");
if (remoteFiles.length == 0)
return;
String cmd = "scp -f";
for (int i = 0; i < remoteFiles.length; i++) {
if (remoteFiles[i] == null)
throw new IllegalArgumentException(
"Cannot accept null filename.");
String tmp = remoteFiles[i].trim();
if (tmp.length() == 0)
throw new IllegalArgumentException(
"Cannot accept empty filename.");
cmd += (" " + tmp);
}
try {
sess = conn.openSession();
sess.execCommand(cmd);
receiveFiles(sess, remoteFiles, localTargetDirectory);
} catch (IOException e) {
throw (IOException) new IOException("Error during SCP transfer.")
.initCause(e);
} finally {
if (sess != null)
sess.close();
}
}
private LenNamePair parseCLine(String line) throws IOException {
/* Minimum line: "xxxx y z" ---> 8 chars */
long len;
if (line.length() < 8)
throw new IOException(
"Malformed C line sent by remote SCP binary, line too short.");
if ((line.charAt(4) != ' ') || (line.charAt(5) == ' '))
throw new IOException("Malformed C line sent by remote SCP binary.");
int length_name_sep = line.indexOf(' ', 5);
if (length_name_sep == -1)
throw new IOException("Malformed C line sent by remote SCP binary.");
String length_substring = line.substring(5, length_name_sep);
String name_substring = line.substring(length_name_sep + 1);
if ((length_substring.length() <= 0) || (name_substring.length() <= 0))
throw new IOException("Malformed C line sent by remote SCP binary.");
if ((6 + length_substring.length() + name_substring.length()) != line
.length())
throw new IOException("Malformed C line sent by remote SCP binary.");
try {
len = Long.parseLong(length_substring);
} catch (NumberFormatException e) {
throw new IOException(
"Malformed C line sent by remote SCP binary, cannot parse file length.");
}
if (len < 0)
throw new IOException(
"Malformed C line sent by remote SCP binary, illegal file length.");
LenNamePair lnp = new LenNamePair();
lnp.length = len;
lnp.filename = name_substring;
return lnp;
}
/**
* Create a remote file and copy the contents of the passed byte array into
* it. Uses mode 0600 for creating the remote file.
*
* @param data
* the data to be copied into the remote file.
* @param remoteFileName
* The name of the file which will be created in the remote
* target directory.
* @param remoteTargetDirectory
* Remote target directory. Use an empty string to specify the
* default directory.
* @throws IOException
*/
public void put(byte[] data, String remoteFileName,
String remoteTargetDirectory) throws IOException {
put(data, remoteFileName, remoteTargetDirectory, "0600");
}
/**
* Create a remote file and copy the contents of the passed byte array into
* it. The method use the specified mode when creating the file on the
* remote side.
*
* @param data
* the data to be copied into the remote file.
* @param remoteFileName
* The name of the file which will be created in the remote
* target directory.
* @param remoteTargetDirectory
* Remote target directory. Use an empty string to specify the
* default directory.
* @param mode
* a four digit string (e.g., 0644, see "man chmod", "man open")
* @throws IOException
*/
public void put(byte[] data, String remoteFileName,
String remoteTargetDirectory, String mode) throws IOException {
Session sess = null;
if ((remoteFileName == null) || (remoteTargetDirectory == null)
|| (mode == null))
throw new IllegalArgumentException("Null argument.");
if (mode.length() != 4)
throw new IllegalArgumentException("Invalid mode.");
for (int i = 0; i < mode.length(); i++)
if (Character.isDigit(mode.charAt(i)) == false)
throw new IllegalArgumentException("Invalid mode.");
remoteTargetDirectory = remoteTargetDirectory.trim();
remoteTargetDirectory = (remoteTargetDirectory.length() > 0) ? remoteTargetDirectory
: ".";
String cmd = "scp -t -d " + remoteTargetDirectory;
try {
sess = conn.openSession();
sess.execCommand(cmd);
sendBytes(sess, data, remoteFileName, mode);
} catch (IOException e) {
throw (IOException) new IOException("Error during SCP transfer.")
.initCause(e);
} finally {
if (sess != null)
sess.close();
}
}
/**
* Copy a local file to a remote directory, uses mode 0600 when creating the
* file on the remote side.
*
* @param localFile
* Path and name of local file.
* @param remoteTargetDirectory
* Remote target directory. Use an empty string to specify the
* default directory.
*
* @throws IOException
*/
public void put(String localFile, String remoteTargetDirectory)
throws IOException {
put(new String[] { localFile }, remoteTargetDirectory, "0600");
}
/**
* Copy a local file to a remote directory, uses the specified mode when
* creating the file on the remote side.
*
* @param localFile
* Path and name of local file.
* @param remoteTargetDirectory
* Remote target directory. Use an empty string to specify the
* default directory.
* @param mode
* a four digit string (e.g., 0644, see "man chmod", "man open")
* @throws IOException
*/
public void put(String localFile, String remoteTargetDirectory, String mode)
throws IOException {
put(new String[] { localFile }, remoteTargetDirectory, mode);
}
/**
* Copy a local file to a remote directory, uses the specified mode and
* remote filename when creating the file on the remote side.
*
* @param localFile
* Path and name of local file.
* @param remoteFileName
* The name of the file which will be created in the remote
* target directory.
* @param remoteTargetDirectory
* Remote target directory. Use an empty string to specify the
* default directory.
* @param mode
* a four digit string (e.g., 0644, see "man chmod", "man open")
* @throws IOException
*/
public void put(String localFile, String remoteFileName,
String remoteTargetDirectory, String mode) throws IOException {
put(new String[] { localFile }, new String[] { remoteFileName },
remoteTargetDirectory, mode);
}
/**
* Copy a set of local files to a remote directory, uses mode 0600 when
* creating files on the remote side.
*
* @param localFiles
* Paths and names of local file names.
* @param remoteTargetDirectory
* Remote target directory. Use an empty string to specify the
* default directory.
*
* @throws IOException
*/
public void put(String[] localFiles, String remoteTargetDirectory)
throws IOException {
put(localFiles, remoteTargetDirectory, "0600");
}
/**
* Copy a set of local files to a remote directory, uses the specified mode
* when creating the files on the remote side.
*
* @param localFiles
* Paths and names of the local files.
* @param remoteTargetDirectory
* Remote target directory. Use an empty string to specify the
* default directory.
* @param mode
* a four digit string (e.g., 0644, see "man chmod", "man open")
* @throws IOException
*/
public void put(String[] localFiles, String remoteTargetDirectory,
String mode) throws IOException {
put(localFiles, null, remoteTargetDirectory, mode);
}
public void put(String[] localFiles, String[] remoteFiles,
String remoteTargetDirectory, String mode) throws IOException {
Session sess = null;
/*
* remoteFiles may be null, indicating that the local filenames shall be
* used
*/
if ((localFiles == null) || (remoteTargetDirectory == null)
|| (mode == null))
throw new IllegalArgumentException("Null argument.");
if (mode.length() != 4)
throw new IllegalArgumentException("Invalid mode.");
for (int i = 0; i < mode.length(); i++)
if (Character.isDigit(mode.charAt(i)) == false)
throw new IllegalArgumentException("Invalid mode.");
if (localFiles.length == 0)
return;
remoteTargetDirectory = remoteTargetDirectory.trim();
remoteTargetDirectory = (remoteTargetDirectory.length() > 0) ? remoteTargetDirectory
: ".";
String cmd = "scp -t -d " + remoteTargetDirectory;
for (int i = 0; i < localFiles.length; i++) {
if (localFiles[i] == null)
throw new IllegalArgumentException(
"Cannot accept null filename.");
}
try {
sess = conn.openSession();
sess.execCommand(cmd);
sendFiles(sess, localFiles, remoteFiles, mode);
} catch (IOException e) {
throw (IOException) new IOException("Error during SCP transfer.")
.initCause(e);
} finally {
if (sess != null)
sess.close();
}
}
private void readResponse(InputStream is) throws IOException {
int c = is.read();
if (c == 0)
return;
if (c == -1)
throw new IOException("Remote scp terminated unexpectedly.");
if ((c != 1) && (c != 2))
throw new IOException("Remote scp sent illegal error code.");
if (c == 2)
throw new IOException("Remote scp terminated with error.");
String err = receiveLine(is);
throw new IOException("Remote scp terminated with error (" + err + ").");
}
private void receiveFiles(Session sess, OutputStream[] targets)
throws IOException {
byte[] buffer = new byte[8192];
OutputStream os = new BufferedOutputStream(sess.getStdin(), 512);
InputStream is = new BufferedInputStream(sess.getStdout(), 40000);
os.write(0x0);
os.flush();
for (int i = 0; i < targets.length; i++) {
LenNamePair lnp = null;
while (true) {
int c = is.read();
if (c < 0)
throw new IOException("Remote scp terminated unexpectedly.");
String line = receiveLine(is);
if (c == 'T') {
/* Ignore modification times */
continue;
}
if ((c == 1) || (c == 2))
throw new IOException("Remote SCP error: " + line);
if (c == 'C') {
lnp = parseCLine(line);
break;
}
throw new IOException("Remote SCP error: " + ((char) c) + line);
}
os.write(0x0);
os.flush();
long remain = lnp.length;
while (remain > 0) {
int trans;
if (remain > buffer.length)
trans = buffer.length;
else
trans = (int) remain;
int this_time_received = is.read(buffer, 0, trans);
if (this_time_received < 0) {
throw new IOException(
"Remote scp terminated connection unexpectedly");
}
targets[i].write(buffer, 0, this_time_received);
remain -= this_time_received;
}
readResponse(is);
os.write(0x0);
os.flush();
}
}
private void receiveFiles(Session sess, String[] files, String target)
throws IOException {
byte[] buffer = new byte[8192];
OutputStream os = new BufferedOutputStream(sess.getStdin(), 512);
InputStream is = new BufferedInputStream(sess.getStdout(), 40000);
os.write(0x0);
os.flush();
for (int i = 0; i < files.length; i++) {
LenNamePair lnp = null;
while (true) {
int c = is.read();
if (c < 0)
throw new IOException("Remote scp terminated unexpectedly.");
String line = receiveLine(is);
if (c == 'T') {
/* Ignore modification times */
continue;
}
if ((c == 1) || (c == 2))
throw new IOException("Remote SCP error: " + line);
if (c == 'C') {
lnp = parseCLine(line);
break;
}
throw new IOException("Remote SCP error: " + ((char) c) + line);
}
os.write(0x0);
os.flush();
File f = new File(target + File.separatorChar + lnp.filename);
FileOutputStream fop = null;
try {
fop = new FileOutputStream(f);
long remain = lnp.length;
while (remain > 0) {
int trans;
if (remain > buffer.length)
trans = buffer.length;
else
trans = (int) remain;
int this_time_received = is.read(buffer, 0, trans);
if (this_time_received < 0) {
throw new IOException(
"Remote scp terminated connection unexpectedly");
}
fop.write(buffer, 0, this_time_received);
remain -= this_time_received;
}
} finally {
if (fop != null)
fop.close();
}
readResponse(is);
os.write(0x0);
os.flush();
}
}
private String receiveLine(InputStream is) throws IOException {
StringBuffer sb = new StringBuffer(30);
while (true) {
/*
* This is a random limit - if your path names are longer, then
* adjust it
*/
if (sb.length() > 8192)
throw new IOException("Remote scp sent a too long line");
int c = is.read();
if (c < 0)
throw new IOException("Remote scp terminated unexpectedly.");
if (c == '\n')
break;
sb.append((char) c);
}
return sb.toString();
}
private void sendBytes(Session sess, byte[] data, String fileName,
String mode) throws IOException {
OutputStream os = sess.getStdin();
InputStream is = new BufferedInputStream(sess.getStdout(), 512);
readResponse(is);
String cline = "C" + mode + " " + data.length + " " + fileName + "\n";
os.write(cline.getBytes("ISO-8859-1"));
os.flush();
readResponse(is);
os.write(data, 0, data.length);
os.write(0);
os.flush();
readResponse(is);
os.write("E\n".getBytes("ISO-8859-1"));
os.flush();
}
private void sendFiles(Session sess, String[] files, String[] remoteFiles,
String mode) throws IOException {
byte[] buffer = new byte[8192];
OutputStream os = new BufferedOutputStream(sess.getStdin(), 40000);
InputStream is = new BufferedInputStream(sess.getStdout(), 512);
readResponse(is);
for (int i = 0; i < files.length; i++) {
File f = new File(files[i]);
long remain = f.length();
String remoteName;
if ((remoteFiles != null) && (remoteFiles.length > i)
&& (remoteFiles[i] != null))
remoteName = remoteFiles[i];
else
remoteName = f.getName();
String cline = "C" + mode + " " + remain + " " + remoteName + "\n";
os.write(cline.getBytes("ISO-8859-1"));
os.flush();
readResponse(is);
FileInputStream fis = null;
try {
fis = new FileInputStream(f);
while (remain > 0) {
int trans;
if (remain > buffer.length)
trans = buffer.length;
else
trans = (int) remain;
if (fis.read(buffer, 0, trans) != trans)
throw new IOException(
"Cannot read enough from local file "
+ files[i]);
os.write(buffer, 0, trans);
remain -= trans;
}
} finally {
if (fis != null)
fis.close();
}
os.write(0);
os.flush();
readResponse(is);
}
os.write("E\n".getBytes("ISO-8859-1"));
os.flush();
}
}
| Java |
package com.trilead.ssh2;
import java.io.IOException;
/**
* May be thrown upon connect() if a HTTP proxy is being used.
*
* @see Connection#connect()
* @see Connection#setProxyData(ProxyData)
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: HTTPProxyException.java,v 1.1 2007/10/15 12:49:56 cplattne Exp
* $
*/
public class HTTPProxyException extends IOException {
private static final long serialVersionUID = 2241537397104426186L;
public final String httpResponse;
public final int httpErrorCode;
public HTTPProxyException(String httpResponse, int httpErrorCode) {
super("HTTP Proxy Error (" + httpErrorCode + " " + httpResponse + ")");
this.httpResponse = httpResponse;
this.httpErrorCode = httpErrorCode;
}
}
| Java |
package com.trilead.ssh2.sftp;
/**
*
* SFTP Error Codes
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: ErrorCodes.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*
*/
public class ErrorCodes {
public static final int SSH_FX_OK = 0;
public static final int SSH_FX_EOF = 1;
public static final int SSH_FX_NO_SUCH_FILE = 2;
public static final int SSH_FX_PERMISSION_DENIED = 3;
public static final int SSH_FX_FAILURE = 4;
public static final int SSH_FX_BAD_MESSAGE = 5;
public static final int SSH_FX_NO_CONNECTION = 6;
public static final int SSH_FX_CONNECTION_LOST = 7;
public static final int SSH_FX_OP_UNSUPPORTED = 8;
public static final int SSH_FX_INVALID_HANDLE = 9;
public static final int SSH_FX_NO_SUCH_PATH = 10;
public static final int SSH_FX_FILE_ALREADY_EXISTS = 11;
public static final int SSH_FX_WRITE_PROTECT = 12;
public static final int SSH_FX_NO_MEDIA = 13;
public static final int SSH_FX_NO_SPACE_ON_FILESYSTEM = 14;
public static final int SSH_FX_QUOTA_EXCEEDED = 15;
public static final int SSH_FX_UNKNOWN_PRINCIPAL = 16;
public static final int SSH_FX_LOCK_CONFLICT = 17;
public static final int SSH_FX_DIR_NOT_EMPTY = 18;
public static final int SSH_FX_NOT_A_DIRECTORY = 19;
public static final int SSH_FX_INVALID_FILENAME = 20;
public static final int SSH_FX_LINK_LOOP = 21;
public static final int SSH_FX_CANNOT_DELETE = 22;
public static final int SSH_FX_INVALID_PARAMETER = 23;
public static final int SSH_FX_FILE_IS_A_DIRECTORY = 24;
public static final int SSH_FX_BYTE_RANGE_LOCK_CONFLICT = 25;
public static final int SSH_FX_BYTE_RANGE_LOCK_REFUSED = 26;
public static final int SSH_FX_DELETE_PENDING = 27;
public static final int SSH_FX_FILE_CORRUPT = 28;
public static final int SSH_FX_OWNER_INVALID = 29;
public static final int SSH_FX_GROUP_INVALID = 30;
public static final int SSH_FX_NO_MATCHING_BYTE_RANGE_LOCK = 31;
private static final String[][] messages = {
{ "SSH_FX_OK", "Indicates successful completion of the operation." },
{
"SSH_FX_EOF",
"An attempt to read past the end-of-file was made; or, there are no more directory entries to return." },
{ "SSH_FX_NO_SUCH_FILE",
"A reference was made to a file which does not exist." },
{ "SSH_FX_PERMISSION_DENIED",
"The user does not have sufficient permissions to perform the operation." },
{ "SSH_FX_FAILURE",
"An error occurred, but no specific error code exists to describe the failure." },
{ "SSH_FX_BAD_MESSAGE",
"A badly formatted packet or other SFTP protocol incompatibility was detected." },
{ "SSH_FX_NO_CONNECTION", "There is no connection to the server." },
{ "SSH_FX_CONNECTION_LOST",
"The connection to the server was lost." },
{
"SSH_FX_OP_UNSUPPORTED",
"An attempted operation could not be completed by the server because the server does not support the operation." },
{ "SSH_FX_INVALID_HANDLE", "The handle value was invalid." },
{ "SSH_FX_NO_SUCH_PATH",
"The file path does not exist or is invalid." },
{ "SSH_FX_FILE_ALREADY_EXISTS", "The file already exists." },
{ "SSH_FX_WRITE_PROTECT",
"The file is on read-only media, or the media is write protected." },
{
"SSH_FX_NO_MEDIA",
"The requested operation cannot be completed because there is no media available in the drive." },
{
"SSH_FX_NO_SPACE_ON_FILESYSTEM",
"The requested operation cannot be completed because there is insufficient free space on the filesystem." },
{
"SSH_FX_QUOTA_EXCEEDED",
"The operation cannot be completed because it would exceed the user's storage quota." },
{
"SSH_FX_UNKNOWN_PRINCIPAL",
"A principal referenced by the request (either the 'owner', 'group', or 'who' field of an ACL), was unknown. The error specific data contains the problematic names." },
{ "SSH_FX_LOCK_CONFLICT",
"The file could not be opened because it is locked by another process." },
{ "SSH_FX_DIR_NOT_EMPTY", "The directory is not empty." },
{ "SSH_FX_NOT_A_DIRECTORY",
"The specified file is not a directory." },
{ "SSH_FX_INVALID_FILENAME", "The filename is not valid." },
{
"SSH_FX_LINK_LOOP",
"Too many symbolic links encountered or, an SSH_FXF_NOFOLLOW open encountered a symbolic link as the final component." },
{
"SSH_FX_CANNOT_DELETE",
"The file cannot be deleted. One possible reason is that the advisory READONLY attribute-bit is set." },
{
"SSH_FX_INVALID_PARAMETER",
"One of the parameters was out of range, or the parameters specified cannot be used together." },
{
"SSH_FX_FILE_IS_A_DIRECTORY",
"The specified file was a directory in a context where a directory cannot be used." },
{
"SSH_FX_BYTE_RANGE_LOCK_CONFLICT",
" A read or write operation failed because another process's mandatory byte-range lock overlaps with the request." },
{ "SSH_FX_BYTE_RANGE_LOCK_REFUSED",
"A request for a byte range lock was refused." },
{ "SSH_FX_DELETE_PENDING",
"An operation was attempted on a file for which a delete operation is pending." },
{ "SSH_FX_FILE_CORRUPT",
"The file is corrupt; an filesystem integrity check should be run." },
{ "SSH_FX_OWNER_INVALID",
"The principal specified can not be assigned as an owner of a file." },
{ "SSH_FX_GROUP_INVALID",
"The principal specified can not be assigned as the primary group of a file." },
{
"SSH_FX_NO_MATCHING_BYTE_RANGE_LOCK",
"The requested operation could not be completed because the specifed byte range lock has not been granted." },
};
public static final String[] getDescription(int errorCode) {
if ((errorCode < 0) || (errorCode >= messages.length))
return null;
return messages[errorCode];
}
}
| Java |
package com.trilead.ssh2.sftp;
/**
*
* Values for the 'text-hint' field in the SFTP ATTRS data type.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: AttrTextHints.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*
*/
public class AttrTextHints {
/**
* The server knows the file is a text file, and should be opened using the
* SSH_FXF_ACCESS_TEXT_MODE flag.
*/
public static final int SSH_FILEXFER_ATTR_KNOWN_TEXT = 0x00;
/**
* The server has applied a heuristic or other mechanism and believes that
* the file should be opened with the SSH_FXF_ACCESS_TEXT_MODE flag.
*/
public static final int SSH_FILEXFER_ATTR_GUESSED_TEXT = 0x01;
/**
* The server knows the file has binary content.
*/
public static final int SSH_FILEXFER_ATTR_KNOWN_BINARY = 0x02;
/**
* The server has applied a heuristic or other mechanism and believes has
* binary content, and should not be opened with the
* SSH_FXF_ACCESS_TEXT_MODE flag.
*/
public static final int SSH_FILEXFER_ATTR_GUESSED_BINARY = 0x03;
}
| Java |
package com.trilead.ssh2.sftp;
/**
*
* SFTP Attribute Bits for the "attrib-bits" and "attrib-bits-valid" fields of
* the SFTP ATTR data type.
* <p>
* Yes, these are the "attrib-bits", even though they have "_FLAGS_" in their
* name. Don't ask - I did not invent it.
* <p>
* "<i>These fields, taken together, reflect various attributes of the file or
* directory, on the server. Bits not set in 'attrib-bits-valid' MUST be ignored
* in the 'attrib-bits' field. This allows both the server and the client to
* communicate only the bits it knows about without inadvertently twiddling bits
* they don't understand.</i>"
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: AttribBits.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*
*/
public class AttribBits {
/**
* Advisory, read-only bit. This bit is not part of the access control
* information on the file, but is rather an advisory field indicating that
* the file should not be written.
*/
public static final int SSH_FILEXFER_ATTR_FLAGS_READONLY = 0x00000001;
/**
* The file is part of the operating system.
*/
public static final int SSH_FILEXFER_ATTR_FLAGS_SYSTEM = 0x00000002;
/**
* File SHOULD NOT be shown to user unless specifically requested. For
* example, most UNIX systems SHOULD set this bit if the filename begins
* with a 'period'. This bit may be read-only (see section 5.4 of the SFTP
* standard draft). Most UNIX systems will not allow this to be changed.
*/
public static final int SSH_FILEXFER_ATTR_FLAGS_HIDDEN = 0x00000004;
/**
* This attribute applies only to directories. This attribute is always
* read-only, and cannot be modified. This attribute means that files and
* directory names in this directory should be compared without regard to
* case.
* <p>
* It is recommended that where possible, the server's filesystem be allowed
* to do comparisons. For example, if a client wished to prompt a user
* before overwriting a file, it should not compare the new name with the
* previously retrieved list of names in the directory. Rather, it should
* first try to create the new file by specifying SSH_FXF_CREATE_NEW flag.
* Then, if this fails and returns SSH_FX_FILE_ALREADY_EXISTS, it should
* prompt the user and then retry the create specifying
* SSH_FXF_CREATE_TRUNCATE.
* <p>
* Unless otherwise specified, filenames are assumed to be case sensitive.
*/
public static final int SSH_FILEXFER_ATTR_FLAGS_CASE_INSENSITIVE = 0x00000008;
/**
* The file should be included in backup / archive operations.
*/
public static final int SSH_FILEXFER_ATTR_FLAGS_ARCHIVE = 0x00000010;
/**
* The file is stored on disk using file-system level transparent
* encryption. This flag does not affect the file data on the wire (for
* either READ or WRITE requests.)
*/
public static final int SSH_FILEXFER_ATTR_FLAGS_ENCRYPTED = 0x00000020;
/**
* The file is stored on disk using file-system level transparent
* compression. This flag does not affect the file data on the wire.
*/
public static final int SSH_FILEXFER_ATTR_FLAGS_COMPRESSED = 0x00000040;
/**
* The file is a sparse file; this means that file blocks that have not been
* explicitly written are not stored on disk. For example, if a client
* writes a buffer at 10 M from the beginning of the file, the blocks
* between the previous EOF marker and the 10 M offset would not consume
* physical disk space.
* <p>
* Some servers may store all files as sparse files, in which case this bit
* will be unconditionally set. Other servers may not have a mechanism for
* determining if the file is sparse, and so the file MAY be stored sparse
* even if this flag is not set.
*/
public static final int SSH_FILEXFER_ATTR_FLAGS_SPARSE = 0x00000080;
/**
* Opening the file without either the SSH_FXF_ACCESS_APPEND_DATA or the
* SSH_FXF_ACCESS_APPEND_DATA_ATOMIC flag (see section 8.1.1.3 of the SFTP
* standard draft) MUST result in an SSH_FX_INVALID_PARAMETER error.
*/
public static final int SSH_FILEXFER_ATTR_FLAGS_APPEND_ONLY = 0x00000100;
/**
* The file cannot be deleted or renamed, no hard link can be created to
* this file, and no data can be written to the file.
* <p>
* This bit implies a stronger level of protection than
* SSH_FILEXFER_ATTR_FLAGS_READONLY, the file permission mask or ACLs.
* Typically even the superuser cannot write to immutable files, and only
* the superuser can set or remove the bit.
*/
public static final int SSH_FILEXFER_ATTR_FLAGS_IMMUTABLE = 0x00000200;
/**
* When the file is modified, the changes are written synchronously to the
* disk.
*/
public static final int SSH_FILEXFER_ATTR_FLAGS_SYNC = 0x00000400;
/**
* The server MAY include this bit in a directory listing or realpath
* response. It indicates there was a failure in the translation to UTF-8.
* If this flag is included, the server SHOULD also include the
* UNTRANSLATED_NAME attribute.
*/
public static final int SSH_FILEXFER_ATTR_FLAGS_TRANSLATION_ERR = 0x00000800;
}
| Java |
package com.trilead.ssh2.sftp;
/**
*
* Types for the 'type' field in the SFTP ATTRS data type.
* <p>
* "<i>On a POSIX system, these values would be derived from the mode field of
* the stat structure. SPECIAL should be used for files that are of a known type
* which cannot be expressed in the protocol. UNKNOWN should be used if the type
* is not known.</i>"
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: AttribTypes.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*
*/
public class AttribTypes {
public static final int SSH_FILEXFER_TYPE_REGULAR = 1;
public static final int SSH_FILEXFER_TYPE_DIRECTORY = 2;
public static final int SSH_FILEXFER_TYPE_SYMLINK = 3;
public static final int SSH_FILEXFER_TYPE_SPECIAL = 4;
public static final int SSH_FILEXFER_TYPE_UNKNOWN = 5;
public static final int SSH_FILEXFER_TYPE_SOCKET = 6;
public static final int SSH_FILEXFER_TYPE_CHAR_DEVICE = 7;
public static final int SSH_FILEXFER_TYPE_BLOCK_DEVICE = 8;
public static final int SSH_FILEXFER_TYPE_FIFO = 9;
}
| Java |
package com.trilead.ssh2.sftp;
/**
*
* Attribute Flags. The 'valid-attribute-flags' field in the SFTP ATTRS data
* type specifies which of the fields are actually present.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: AttribFlags.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*
*/
public class AttribFlags {
/**
* Indicates that the 'allocation-size' field is present.
*/
public static final int SSH_FILEXFER_ATTR_SIZE = 0x00000001;
/**
* Protocol version 6: 0x00000002 was used in a previous version of this
* protocol. It is now a reserved value and MUST NOT appear in the mask.
* Some future version of this protocol may reuse this value.
*/
public static final int SSH_FILEXFER_ATTR_V3_UIDGID = 0x00000002;
/**
* Indicates that the 'permissions' field is present.
*/
public static final int SSH_FILEXFER_ATTR_PERMISSIONS = 0x00000004;
/**
* Indicates that the 'atime' and 'mtime' field are present (protocol v3).
*/
public static final int SSH_FILEXFER_ATTR_V3_ACMODTIME = 0x00000008;
/**
* Indicates that the 'atime' field is present.
*/
public static final int SSH_FILEXFER_ATTR_ACCESSTIME = 0x00000008;
/**
* Indicates that the 'createtime' field is present.
*/
public static final int SSH_FILEXFER_ATTR_CREATETIME = 0x00000010;
/**
* Indicates that the 'mtime' field is present.
*/
public static final int SSH_FILEXFER_ATTR_MODIFYTIME = 0x00000020;
/**
* Indicates that the 'acl' field is present.
*/
public static final int SSH_FILEXFER_ATTR_ACL = 0x00000040;
/**
* Indicates that the 'owner' and 'group' fields are present.
*/
public static final int SSH_FILEXFER_ATTR_OWNERGROUP = 0x00000080;
/**
* Indicates that additionally to the 'atime', 'createtime', 'mtime' and
* 'ctime' fields (if present), there is also 'atime-nseconds',
* 'createtime-nseconds', 'mtime-nseconds' and 'ctime-nseconds'.
*/
public static final int SSH_FILEXFER_ATTR_SUBSECOND_TIMES = 0x00000100;
/**
* Indicates that the 'attrib-bits' and 'attrib-bits-valid' fields are
* present.
*/
public static final int SSH_FILEXFER_ATTR_BITS = 0x00000200;
/**
* Indicates that the 'allocation-size' field is present.
*/
public static final int SSH_FILEXFER_ATTR_ALLOCATION_SIZE = 0x00000400;
/**
* Indicates that the 'text-hint' field is present.
*/
public static final int SSH_FILEXFER_ATTR_TEXT_HINT = 0x00000800;
/**
* Indicates that the 'mime-type' field is present.
*/
public static final int SSH_FILEXFER_ATTR_MIME_TYPE = 0x00001000;
/**
* Indicates that the 'link-count' field is present.
*/
public static final int SSH_FILEXFER_ATTR_LINK_COUNT = 0x00002000;
/**
* Indicates that the 'untranslated-name' field is present.
*/
public static final int SSH_FILEXFER_ATTR_UNTRANSLATED_NAME = 0x00004000;
/**
* Indicates that the 'ctime' field is present.
*/
public static final int SSH_FILEXFER_ATTR_CTIME = 0x00008000;
/**
* Indicates that the 'extended-count' field (and probablby some
* 'extensions') is present.
*/
public static final int SSH_FILEXFER_ATTR_EXTENDED = 0x80000000;
}
| Java |
package com.trilead.ssh2.sftp;
/**
*
* SFTP Open Flags.
*
* The following table is provided to assist in mapping POSIX semantics to
* equivalent SFTP file open parameters:
* <p>
* TODO: This comment should be moved to the open method.
* <p>
* <ul>
* <li>O_RDONLY
* <ul>
* <li>desired-access = READ_DATA | READ_ATTRIBUTES</li>
* </ul>
* </li>
* </ul>
* <ul>
* <li>O_WRONLY
* <ul>
* <li>desired-access = WRITE_DATA | WRITE_ATTRIBUTES</li>
* </ul>
* </li>
* </ul>
* <ul>
* <li>O_RDWR
* <ul>
* <li>desired-access = READ_DATA | READ_ATTRIBUTES | WRITE_DATA |
* WRITE_ATTRIBUTES</li>
* </ul>
* </li>
* </ul>
* <ul>
* <li>O_APPEND
* <ul>
* <li>desired-access = WRITE_DATA | WRITE_ATTRIBUTES | APPEND_DATA</li>
* <li>flags = SSH_FXF_ACCESS_APPEND_DATA and or
* SSH_FXF_ACCESS_APPEND_DATA_ATOMIC</li>
* </ul>
* </li>
* </ul>
* <ul>
* <li>O_CREAT
* <ul>
* <li>flags = SSH_FXF_OPEN_OR_CREATE</li>
* </ul>
* </li>
* </ul>
* <ul>
* <li>O_TRUNC
* <ul>
* <li>flags = SSH_FXF_TRUNCATE_EXISTING</li>
* </ul>
* </li>
* </ul>
* <ul>
* <li>O_TRUNC|O_CREATE
* <ul>
* <li>flags = SSH_FXF_CREATE_TRUNCATE</li>
* </ul>
* </li>
* </ul>
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: OpenFlags.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*/
public class OpenFlags {
/**
* Disposition is a 3 bit field that controls how the file is opened. The
* server MUST support these bits (possible enumaration values:
* SSH_FXF_CREATE_NEW, SSH_FXF_CREATE_TRUNCATE, SSH_FXF_OPEN_EXISTING,
* SSH_FXF_OPEN_OR_CREATE or SSH_FXF_TRUNCATE_EXISTING).
*/
public static final int SSH_FXF_ACCESS_DISPOSITION = 0x00000007;
/**
* A new file is created; if the file already exists, the server MUST return
* status SSH_FX_FILE_ALREADY_EXISTS.
*/
public static final int SSH_FXF_CREATE_NEW = 0x00000000;
/**
* A new file is created; if the file already exists, it is opened and
* truncated.
*/
public static final int SSH_FXF_CREATE_TRUNCATE = 0x00000001;
/**
* An existing file is opened. If the file does not exist, the server MUST
* return SSH_FX_NO_SUCH_FILE. If a directory in the path does not exist,
* the server SHOULD return SSH_FX_NO_SUCH_PATH. It is also acceptable if
* the server returns SSH_FX_NO_SUCH_FILE in this case.
*/
public static final int SSH_FXF_OPEN_EXISTING = 0x00000002;
/**
* If the file exists, it is opened. If the file does not exist, it is
* created.
*/
public static final int SSH_FXF_OPEN_OR_CREATE = 0x00000003;
/**
* An existing file is opened and truncated. If the file does not exist, the
* server MUST return the same error codes as defined for
* SSH_FXF_OPEN_EXISTING.
*/
public static final int SSH_FXF_TRUNCATE_EXISTING = 0x00000004;
/**
* Data is always written at the end of the file. The offset field of the
* SSH_FXP_WRITE requests are ignored.
* <p>
* Data is not required to be appended atomically. This means that if
* multiple writers attempt to append data simultaneously, data from the
* first may be lost. However, data MAY be appended atomically.
*/
public static final int SSH_FXF_ACCESS_APPEND_DATA = 0x00000008;
/**
* Data is always written at the end of the file. The offset field of the
* SSH_FXP_WRITE requests are ignored.
* <p>
* Data MUST be written atomically so that there is no chance that multiple
* appenders can collide and result in data being lost.
* <p>
* If both append flags are specified, the server SHOULD use atomic append
* if it is available, but SHOULD use non-atomic appends otherwise. The
* server SHOULD NOT fail the request in this case.
*/
public static final int SSH_FXF_ACCESS_APPEND_DATA_ATOMIC = 0x00000010;
/**
* Indicates that the server should treat the file as text and convert it to
* the canonical newline convention in use. (See Determining Server Newline
* Convention in section 5.3 in the SFTP standard draft).
* <p>
* When a file is opened with this flag, the offset field in the read and
* write functions is ignored.
* <p>
* Servers MUST process multiple, parallel reads and writes correctly in
* this mode. Naturally, it is permissible for them to do this by
* serializing the requests.
* <p>
* Clients SHOULD use the SSH_FXF_ACCESS_APPEND_DATA flag to append data to
* a text file rather then using write with a calculated offset.
*/
public static final int SSH_FXF_ACCESS_TEXT_MODE = 0x00000020;
/**
* The server MUST guarantee that no other handle has been opened with
* ACE4_READ_DATA access, and that no other handle will be opened with
* ACE4_READ_DATA access until the client closes the handle. (This MUST
* apply both to other clients and to other processes on the server.)
* <p>
* If there is a conflicting lock the server MUST return
* SSH_FX_LOCK_CONFLICT. If the server cannot make the locking guarantee, it
* MUST return SSH_FX_OP_UNSUPPORTED.
* <p>
* Other handles MAY be opened for ACE4_WRITE_DATA or any other combination
* of accesses, as long as ACE4_READ_DATA is not included in the mask.
*/
public static final int SSH_FXF_ACCESS_BLOCK_READ = 0x00000040;
/**
* The server MUST guarantee that no other handle has been opened with
* ACE4_WRITE_DATA or ACE4_APPEND_DATA access, and that no other handle will
* be opened with ACE4_WRITE_DATA or ACE4_APPEND_DATA access until the
* client closes the handle. (This MUST apply both to other clients and to
* other processes on the server.)
* <p>
* If there is a conflicting lock the server MUST return
* SSH_FX_LOCK_CONFLICT. If the server cannot make the locking guarantee, it
* MUST return SSH_FX_OP_UNSUPPORTED.
* <p>
* Other handles MAY be opened for ACE4_READ_DATA or any other combination
* of accesses, as long as neither ACE4_WRITE_DATA nor ACE4_APPEND_DATA are
* included in the mask.
*/
public static final int SSH_FXF_ACCESS_BLOCK_WRITE = 0x00000080;
/**
* The server MUST guarantee that no other handle has been opened with
* ACE4_DELETE access, opened with the SSH_FXF_ACCESS_DELETE_ON_CLOSE flag
* set, and that no other handle will be opened with ACE4_DELETE access or
* with the SSH_FXF_ACCESS_DELETE_ON_CLOSE flag set, and that the file
* itself is not deleted in any other way until the client closes the
* handle.
* <p>
* If there is a conflicting lock the server MUST return
* SSH_FX_LOCK_CONFLICT. If the server cannot make the locking guarantee, it
* MUST return SSH_FX_OP_UNSUPPORTED.
*/
public static final int SSH_FXF_ACCESS_BLOCK_DELETE = 0x00000100;
/**
* If this bit is set, the above BLOCK modes are advisory. In advisory mode,
* only other accesses that specify a BLOCK mode need be considered when
* determining whether the BLOCK can be granted, and the server need not
* prevent I/O operations that violate the block mode.
* <p>
* The server MAY perform mandatory locking even if the BLOCK_ADVISORY bit
* is set.
*/
public static final int SSH_FXF_ACCESS_BLOCK_ADVISORY = 0x00000200;
/**
* If the final component of the path is a symlink, then the open MUST fail,
* and the error SSH_FX_LINK_LOOP MUST be returned.
*/
public static final int SSH_FXF_ACCESS_NOFOLLOW = 0x00000400;
/**
* The file should be deleted when the last handle to it is closed. (The
* last handle may not be an sftp-handle.) This MAY be emulated by a server
* if the OS doesn't support it by deleting the file when this handle is
* closed.
* <p>
* It is implementation specific whether the directory entry is removed
* immediately or when the handle is closed.
*/
public static final int SSH_FXF_ACCESS_DELETE_ON_CLOSE = 0x00000800;
}
| Java |
package com.trilead.ssh2.sftp;
/**
*
* SFTP Paket Types
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: Packet.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*
*/
public class Packet {
public static final int SSH_FXP_INIT = 1;
public static final int SSH_FXP_VERSION = 2;
public static final int SSH_FXP_OPEN = 3;
public static final int SSH_FXP_CLOSE = 4;
public static final int SSH_FXP_READ = 5;
public static final int SSH_FXP_WRITE = 6;
public static final int SSH_FXP_LSTAT = 7;
public static final int SSH_FXP_FSTAT = 8;
public static final int SSH_FXP_SETSTAT = 9;
public static final int SSH_FXP_FSETSTAT = 10;
public static final int SSH_FXP_OPENDIR = 11;
public static final int SSH_FXP_READDIR = 12;
public static final int SSH_FXP_REMOVE = 13;
public static final int SSH_FXP_MKDIR = 14;
public static final int SSH_FXP_RMDIR = 15;
public static final int SSH_FXP_REALPATH = 16;
public static final int SSH_FXP_STAT = 17;
public static final int SSH_FXP_RENAME = 18;
public static final int SSH_FXP_READLINK = 19;
public static final int SSH_FXP_SYMLINK = 20;
public static final int SSH_FXP_STATUS = 101;
public static final int SSH_FXP_HANDLE = 102;
public static final int SSH_FXP_DATA = 103;
public static final int SSH_FXP_NAME = 104;
public static final int SSH_FXP_ATTRS = 105;
public static final int SSH_FXP_EXTENDED = 200;
public static final int SSH_FXP_EXTENDED_REPLY = 201;
}
| Java |
package com.trilead.ssh2.sftp;
/**
*
* Permissions for the 'permissions' field in the SFTP ATTRS data type.
* <p>
* "<i>The 'permissions' field contains a bit mask specifying file permissions.
* These permissions correspond to the st_mode field of the stat structure
* defined by POSIX [IEEE.1003-1.1996].</i>"
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: AttribPermissions.java,v 1.1 2007/10/15 12:49:55 cplattne Exp $
*
*/
public class AttribPermissions {
/* Octal values! */
public static final int S_IRUSR = 0400;
public static final int S_IWUSR = 0200;
public static final int S_IXUSR = 0100;
public static final int S_IRGRP = 0040;
public static final int S_IWGRP = 0020;
public static final int S_IXGRP = 0010;
public static final int S_IROTH = 0004;
public static final int S_IWOTH = 0002;
public static final int S_IXOTH = 0001;
public static final int S_ISUID = 04000;
public static final int S_ISGID = 02000;
public static final int S_ISVTX = 01000;
}
| Java |
/*
* ConnectBot: simple, powerful, open-source SSH client for Android
* Copyright 2007 Kenny Root, Jeffrey Sharkey
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.trilead.ssh2.compression;
import com.jcraft.jzlib.JZlib;
import com.jcraft.jzlib.ZStream;
/**
* @author Kenny Root
*
*/
public class Zlib implements ICompressor {
static private final int DEFAULT_BUF_SIZE = 4096;
static private final int LEVEL = 5;
private ZStream deflate;
private byte[] deflate_tmpbuf;
private ZStream inflate;
private byte[] inflate_tmpbuf;
private byte[] inflated_buf;
public Zlib() {
deflate = new ZStream();
inflate = new ZStream();
deflate.deflateInit(LEVEL);
inflate.inflateInit();
deflate_tmpbuf = new byte[DEFAULT_BUF_SIZE];
inflate_tmpbuf = new byte[DEFAULT_BUF_SIZE];
inflated_buf = new byte[DEFAULT_BUF_SIZE];
}
@Override
public boolean canCompressPreauth() {
return true;
}
@Override
public int compress(byte[] buf, int start, int len, byte[] output) {
deflate.next_in = buf;
deflate.next_in_index = start;
deflate.avail_in = len - start;
if ((buf.length + 1024) > deflate_tmpbuf.length) {
deflate_tmpbuf = new byte[buf.length + 1024];
}
deflate.next_out = deflate_tmpbuf;
deflate.next_out_index = 0;
deflate.avail_out = output.length;
if (deflate.deflate(JZlib.Z_PARTIAL_FLUSH) != JZlib.Z_OK) {
System.err.println("compress: compression failure");
}
if (deflate.avail_in > 0) {
System.err.println("compress: deflated data too large");
}
int outputlen = output.length - deflate.avail_out;
System.arraycopy(deflate_tmpbuf, 0, output, 0, outputlen);
return outputlen;
}
@Override
public int getBufferSize() {
return DEFAULT_BUF_SIZE;
}
@Override
public byte[] uncompress(byte[] buffer, int start, int[] length) {
int inflated_end = 0;
inflate.next_in = buffer;
inflate.next_in_index = start;
inflate.avail_in = length[0];
while (true) {
inflate.next_out = inflate_tmpbuf;
inflate.next_out_index = 0;
inflate.avail_out = DEFAULT_BUF_SIZE;
int status = inflate.inflate(JZlib.Z_PARTIAL_FLUSH);
switch (status) {
case JZlib.Z_OK:
if (inflated_buf.length < inflated_end + DEFAULT_BUF_SIZE
- inflate.avail_out) {
byte[] foo = new byte[inflated_end + DEFAULT_BUF_SIZE
- inflate.avail_out];
System.arraycopy(inflated_buf, 0, foo, 0, inflated_end);
inflated_buf = foo;
}
System.arraycopy(inflate_tmpbuf, 0, inflated_buf, inflated_end,
DEFAULT_BUF_SIZE - inflate.avail_out);
inflated_end += (DEFAULT_BUF_SIZE - inflate.avail_out);
length[0] = inflated_end;
break;
case JZlib.Z_BUF_ERROR:
if (inflated_end > buffer.length - start) {
byte[] foo = new byte[inflated_end + start];
System.arraycopy(buffer, 0, foo, 0, start);
System.arraycopy(inflated_buf, 0, foo, start, inflated_end);
buffer = foo;
} else {
System.arraycopy(inflated_buf, 0, buffer, start,
inflated_end);
}
length[0] = inflated_end;
return buffer;
default:
System.err.println("uncompress: inflate returnd " + status);
return null;
}
}
}
}
| Java |
/*
* ConnectBot: simple, powerful, open-source SSH client for Android
* Copyright 2007 Kenny Root, Jeffrey Sharkey
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.trilead.ssh2.compression;
/**
* Defines how zlib@openssh.org compression works. See
* http://www.openssh.org/txt/draft-miller-secsh-compression-delayed-00.txt
* compression is disabled until userauth has occurred.
*
* @author Matt Johnston
*
*/
public class ZlibOpenSSH extends Zlib {
@Override
public boolean canCompressPreauth() {
return false;
}
}
| Java |
/*
* ConnectBot: simple, powerful, open-source SSH client for Android
* Copyright 2007 Kenny Root, Jeffrey Sharkey
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.trilead.ssh2.compression;
import java.util.Vector;
/**
* @author Kenny Root
*
*/
public class CompressionFactory {
static class CompressorEntry {
String type;
String compressorClass;
public CompressorEntry(String type, String compressorClass) {
this.type = type;
this.compressorClass = compressorClass;
}
}
static Vector<CompressorEntry> compressors = new Vector<CompressorEntry>();
static {
/* Higher Priority First */
compressors.addElement(new CompressorEntry("zlib",
"com.trilead.ssh2.compression.Zlib"));
compressors.addElement(new CompressorEntry("zlib@openssh.com",
"com.trilead.ssh2.compression.ZlibOpenSSH"));
compressors.addElement(new CompressorEntry("none", ""));
}
public static void checkCompressorList(String[] compressorCandidates) {
for (int i = 0; i < compressorCandidates.length; i++)
getEntry(compressorCandidates[i]);
}
public static ICompressor createCompressor(String type) {
try {
CompressorEntry ce = getEntry(type);
if ("".equals(ce.compressorClass))
return null;
Class<?> cc = Class.forName(ce.compressorClass);
ICompressor cmp = (ICompressor) cc.newInstance();
return cmp;
} catch (Exception e) {
throw new IllegalArgumentException("Cannot instantiate " + type);
}
}
public static String[] getDefaultCompressorList() {
String list[] = new String[compressors.size()];
for (int i = 0; i < compressors.size(); i++) {
CompressorEntry ce = compressors.elementAt(i);
list[i] = new String(ce.type);
}
return list;
}
private static CompressorEntry getEntry(String type) {
for (int i = 0; i < compressors.size(); i++) {
CompressorEntry ce = compressors.elementAt(i);
if (ce.type.equals(type))
return ce;
}
throw new IllegalArgumentException("Unkown algorithm " + type);
}
}
| Java |
/*
* ConnectBot: simple, powerful, open-source SSH client for Android
* Copyright 2007 Kenny Root, Jeffrey Sharkey
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.trilead.ssh2.compression;
/**
* @author Kenny Root
*
*/
public interface ICompressor {
boolean canCompressPreauth();
int compress(byte[] buf, int start, int len, byte[] output);
int getBufferSize();
byte[] uncompress(byte[] buf, int start, int[] len);
}
| Java |
package com.trilead.ssh2;
/**
* A <code>SFTPv3FileAttributes</code> object represents detail information
* about a file on the server. Not all fields may/must be present.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: SFTPv3FileAttributes.java,v 1.2 2008/04/01 12:38:09 cplattne
* Exp $
*/
public class SFTPv3FileAttributes {
/**
* The SIZE attribute. <code>NULL</code> if not present.
*/
public Long size = null;
/**
* The UID attribute. <code>NULL</code> if not present.
*/
public Integer uid = null;
/**
* The GID attribute. <code>NULL</code> if not present.
*/
public Integer gid = null;
/**
* The POSIX permissions. <code>NULL</code> if not present.
* <p>
* Here is a list:
* <p>
*
* <pre>
* Note: these numbers are all OCTAL.
*
* S_IFMT 0170000 bitmask for the file type bitfields
* S_IFSOCK 0140000 socket
* S_IFLNK 0120000 symbolic link
* S_IFREG 0100000 regular file
* S_IFBLK 0060000 block device
* S_IFDIR 0040000 directory
* S_IFCHR 0020000 character device
* S_IFIFO 0010000 fifo
* S_ISUID 0004000 set UID bit
* S_ISGID 0002000 set GID bit
* S_ISVTX 0001000 sticky bit
*
* S_IRWXU 00700 mask for file owner permissions
* S_IRUSR 00400 owner has read permission
* S_IWUSR 00200 owner has write permission
* S_IXUSR 00100 owner has execute permission
* S_IRWXG 00070 mask for group permissions
* S_IRGRP 00040 group has read permission
* S_IWGRP 00020 group has write permission
* S_IXGRP 00010 group has execute permission
* S_IRWXO 00007 mask for permissions for others (not in group)
* S_IROTH 00004 others have read permission
* S_IWOTH 00002 others have write permisson
* S_IXOTH 00001 others have execute permission
* </pre>
*/
public Integer permissions = null;
/**
* The ATIME attribute. Represented as seconds from Jan 1, 1970 in UTC.
* <code>NULL</code> if not present.
*/
public Long atime = null;
/**
* The MTIME attribute. Represented as seconds from Jan 1, 1970 in UTC.
* <code>NULL</code> if not present.
*/
public Long mtime = null;
/**
* Turn the POSIX permissions into a 7 digit octal representation. Note: the
* returned value is first masked with <code>0177777</code>.
*
* @return <code>NULL</code> if permissions are not available.
*/
public String getOctalPermissions() {
if (permissions == null)
return null;
String res = Integer.toString(permissions.intValue() & 0177777, 8);
StringBuffer sb = new StringBuffer();
int leadingZeros = 7 - res.length();
while (leadingZeros > 0) {
sb.append('0');
leadingZeros--;
}
sb.append(res);
return sb.toString();
}
/**
* Checks if this entry is a directory.
*
* @return Returns true if permissions are available and they indicate that
* this entry represents a directory.
*/
public boolean isDirectory() {
if (permissions == null)
return false;
return ((permissions.intValue() & 0040000) != 0);
}
/**
* Checks if this entry is a regular file.
*
* @return Returns true if permissions are available and they indicate that
* this entry represents a regular file.
*/
public boolean isRegularFile() {
if (permissions == null)
return false;
return ((permissions.intValue() & 0100000) != 0);
}
/**
* Checks if this entry is a a symlink.
*
* @return Returns true if permissions are available and they indicate that
* this entry represents a symlink.
*/
public boolean isSymlink() {
if (permissions == null)
return false;
return ((permissions.intValue() & 0120000) != 0);
}
}
| Java |
package com.trilead.ssh2;
/**
* A <code>SFTPv3FileHandle</code>.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: SFTPv3FileHandle.java,v 1.1 2007/10/15 12:49:56 cplattne Exp $
*/
public class SFTPv3FileHandle {
final SFTPv3Client client;
final byte[] fileHandle;
boolean isClosed = false;
/* The constructor is NOT public */
SFTPv3FileHandle(SFTPv3Client client, byte[] h) {
this.client = client;
this.fileHandle = h;
}
/**
* Get the SFTPv3Client instance which created this handle.
*
* @return A SFTPv3Client instance.
*/
public SFTPv3Client getClient() {
return client;
}
/**
* Check if this handle was closed with the
* {@link SFTPv3Client#closeFile(SFTPv3FileHandle)} method of the
* <code>SFTPv3Client</code> instance which created the handle.
*
* @return if the handle is closed.
*/
public boolean isClosed() {
return isClosed;
}
}
| Java |
package com.trilead.ssh2;
import java.util.Map;
/**
* AuthAgentCallback.
*
* @author Kenny Root
* @version $Id$
*/
public interface AuthAgentCallback {
/**
* @param key
* A <code>RSAPrivateKey</code> or <code>DSAPrivateKey</code>
* containing a DSA or RSA private key of the user in Trilead
* object format.
* @param comment
* comment associated with this key
* @param confirmUse
* whether to prompt before using this key
* @param lifetime
* lifetime in seconds for key to be remembered
* @return success or failure
*/
boolean addIdentity(Object key, String comment, boolean confirmUse,
int lifetime);
/**
* @param publicKey
* byte blob containing the OpenSSH-format encoded public key
* @return A <code>RSAPrivateKey</code> or <code>DSAPrivateKey</code>
* containing a DSA or RSA private key of the user in Trilead object
* format.
*/
Object getPrivateKey(byte[] publicKey);
/**
* @return
*/
boolean isAgentLocked();
/**
* @return success or failure
*/
boolean removeAllIdentities();
/**
* @param publicKey
* byte blob containing the OpenSSH-format encoded public key
* @return success or failure
*/
boolean removeIdentity(byte[] publicKey);
/**
* @param unlockPassphrase
* @return
*/
boolean requestAgentUnlock(String unlockPassphrase);
/**
* @return array of blobs containing the OpenSSH-format encoded public keys
*/
Map<String, byte[]> retrieveIdentities();
/**
* @param lockPassphrase
*/
boolean setAgentLock(String lockPassphrase);
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.