KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > jsch > internal > ui > preference > PreferencePage


1 /*******************************************************************************
2  * Copyright (c) 2000, 2007 IBM Corporation and others.
3  * All rights reserved. This program and the accompanying materials
4  * are made available under the terms of the Eclipse Public License v1.0
5  * which accompanies this distribution, and is available at
6  * http://www.eclipse.org/legal/epl-v10.html
7  *
8  * Contributors:
9  * Atsuhiko Yamanaka, JCraft,Inc. - initial API and implementation.
10  * IBM Corporation - ongoing maintenance
11  *******************************************************************************/

12 package org.eclipse.jsch.internal.ui.preference;
13
14 import java.io.*;
15 import java.util.Iterator JavaDoc;
16
17 import org.eclipse.core.runtime.*;
18 import org.eclipse.jface.dialogs.*;
19 import org.eclipse.jface.dialogs.Dialog;
20 import org.eclipse.jface.viewers.*;
21 import org.eclipse.jsch.core.IJSchService;
22 import org.eclipse.jsch.internal.core.*;
23 import org.eclipse.jsch.internal.ui.JSchUIPlugin;
24 import org.eclipse.jsch.internal.ui.Messages;
25 import org.eclipse.jsch.ui.UserInfoPrompter;
26 import org.eclipse.osgi.util.NLS;
27 import org.eclipse.swt.SWT;
28 import org.eclipse.swt.custom.BusyIndicator;
29 import org.eclipse.swt.custom.TableEditor;
30 import org.eclipse.swt.events.*;
31 import org.eclipse.swt.graphics.Image;
32 import org.eclipse.swt.layout.GridData;
33 import org.eclipse.swt.layout.GridLayout;
34 import org.eclipse.swt.widgets.*;
35 import org.eclipse.ui.*;
36
37 import com.jcraft.jsch.*;
38
39 public class PreferencePage extends org.eclipse.jface.preference.PreferencePage
40     implements IWorkbenchPreferencePage{
41
42   private static final String JavaDoc SSH2_PREFERENCE_PAGE_CONTEXT="org.eclipse.jsch.ui.ssh2_preference_page_context"; //$NON-NLS-1$
43

44   private Label ssh2HomeLabel;
45   private Label privateKeyLabel;
46   Text ssh2HomeText;
47   Text privateKeyText;
48   private Button privateKeyAdd;
49
50   private Button ssh2HomeBrowse;
51   Button keyGenerateDSA;
52   Button keyGenerateRSA;
53   private Button keyLoad;
54   private Button keyExport;
55   Button saveKeyPair;
56   private Label keyCommentLabel;
57   Text keyCommentText;
58   private Label keyFingerPrintLabel;
59   Text keyFingerPrintText;
60   private Label keyPassphrase1Label;
61   Text keyPassphrase1Text;
62   private Label keyPassphrase2Label;
63   Text keyPassphrase2Text;
64   private Label publicKeylabel;
65   Text publicKeyText;
66   KeyPair kpair=null;
67   String JavaDoc kpairComment;
68
69   public static final String JavaDoc AUTH_SCHEME="";//$NON-NLS-1$
70

71   public PreferencePage(){
72     setDescription(Messages.CVSSSH2PreferencePage_18);
73   }
74
75   protected Control createContents(Composite parent){
76     Composite container=new Composite(parent, SWT.NULL);
77     GridLayout layout=new GridLayout();
78     container.setLayout(layout);
79     initializeDialogUnits(container);
80
81     TabFolder tabFolder=new TabFolder(container, SWT.NONE);
82     tabFolder.setLayoutData(new GridData(GridData.FILL_BOTH));
83
84     TabItem tabItem=new TabItem(tabFolder, SWT.NONE);
85     tabItem.setText(Messages.CVSSSH2PreferencePage_19);
86     tabItem.setControl(createGeneralPage(tabFolder));
87
88     tabItem=new TabItem(tabFolder, SWT.NONE);
89     tabItem.setText(Messages.CVSSSH2PreferencePage_21);
90     tabItem.setControl(createKeyManagementPage(tabFolder));
91
92     tabItem=new TabItem(tabFolder, SWT.NONE);
93     tabItem.setText(Messages.CVSSSH2PreferencePage_133);
94     tabItem.setControl(createHostKeyManagementPage(tabFolder));
95
96     initControls();
97
98     Dialog.applyDialogFont(parent);
99     PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(),
100         SSH2_PREFERENCE_PAGE_CONTEXT);
101     return container;
102   }
103
104   private Control createGeneralPage(Composite parent){
105     Composite group=new Composite(parent, SWT.NULL);
106     GridLayout layout=new GridLayout();
107     layout.numColumns=3;
108     layout.marginHeight=convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN);
109     layout.marginWidth=convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN);
110     layout.verticalSpacing=convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING);
111     layout.horizontalSpacing=convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING);
112     group.setLayout(layout);
113     GridData data=new GridData();
114     data.horizontalAlignment=GridData.FILL;
115     group.setLayoutData(data);
116
117     ssh2HomeLabel=new Label(group, SWT.NONE);
118     ssh2HomeLabel.setText(Messages.CVSSSH2PreferencePage_23);
119
120     ssh2HomeText=new Text(group, SWT.SINGLE|SWT.BORDER);
121     ssh2HomeText.setFont(group.getFont());
122     GridData gd=new GridData(GridData.FILL_HORIZONTAL);
123     gd.horizontalSpan=1;
124     ssh2HomeText.setLayoutData(gd);
125
126     ssh2HomeBrowse=new Button(group, SWT.NULL);
127     ssh2HomeBrowse.setText(Messages.CVSSSH2PreferencePage_24);
128     gd=new GridData(GridData.HORIZONTAL_ALIGN_FILL);
129     gd.horizontalSpan=1;
130     ssh2HomeBrowse.setLayoutData(gd);
131
132     createSpacer(group, 3);
133
134     privateKeyLabel=new Label(group, SWT.NONE);
135     privateKeyLabel.setText(Messages.CVSSSH2PreferencePage_25);
136
137     privateKeyText=new Text(group, SWT.SINGLE|SWT.BORDER);
138     privateKeyText.setFont(group.getFont());
139     gd=new GridData(GridData.FILL_HORIZONTAL);
140     gd.horizontalSpan=1;
141     privateKeyText.setLayoutData(gd);
142
143     privateKeyAdd=new Button(group, SWT.NULL);
144     privateKeyAdd.setText(Messages.CVSSSH2PreferencePage_26);
145     gd=new GridData(GridData.HORIZONTAL_ALIGN_FILL);
146     gd.horizontalSpan=1;
147     privateKeyAdd.setLayoutData(gd);
148
149     ssh2HomeBrowse.addSelectionListener(new SelectionAdapter(){
150       public void widgetSelected(SelectionEvent e){
151         String JavaDoc home=ssh2HomeText.getText();
152
153         if(!new File(home).exists()){
154           while(true){
155             int foo=home.lastIndexOf(java.io.File.separator, home.length());
156             if(foo==-1)
157               break;
158             home=home.substring(0, foo);
159             if(new File(home).exists())
160               break;
161           }
162         }
163
164         DirectoryDialog dd=new DirectoryDialog(getShell());
165         dd.setFilterPath(home);
166         dd.setMessage(Messages.CVSSSH2PreferencePage_27);
167         String JavaDoc dir=dd.open();
168         if(dir==null){ // cancel
169
return;
170         }
171         ssh2HomeText.setText(dir);
172       }
173     });
174
175     privateKeyAdd.addSelectionListener(new SelectionAdapter(){
176       public void widgetSelected(SelectionEvent e){
177         String JavaDoc home=ssh2HomeText.getText();
178
179         FileDialog fd=new FileDialog(getShell(), SWT.OPEN|SWT.MULTI);
180         fd.setFilterPath(home);
181         Object JavaDoc o=fd.open();
182         if(o==null){ // cancel
183
return;
184         }
185         String JavaDoc[] files=fd.getFileNames();
186         String JavaDoc keys=privateKeyText.getText();
187         String JavaDoc dir=fd.getFilterPath();
188         if(dir.equals(home)){
189           dir="";} //$NON-NLS-1$
190
else{
191           dir+=java.io.File.separator;
192         }
193
194         for(int i=0; i<files.length; i++){
195           String JavaDoc foo=files[i];
196           if(keys.length()!=0)
197             keys=keys+","; //$NON-NLS-1$
198
keys=keys+dir+foo;
199         }
200         privateKeyText.setText(keys);
201       }
202     });
203
204     return group;
205   }
206
207   private Control createKeyManagementPage(Composite parent){
208     int columnSpan=3;
209     Composite group=new Composite(parent, SWT.NULL);
210     GridLayout layout=new GridLayout();
211     layout.numColumns=3;
212     layout.marginHeight=convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN);
213     layout.marginWidth=convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN);
214     layout.verticalSpacing=convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING);
215     layout.horizontalSpacing=convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING);
216     group.setLayout(layout);
217     GridData gd=new GridData();
218     gd.horizontalAlignment=GridData.FILL;
219     group.setLayoutData(gd);
220
221     keyGenerateDSA=new Button(group, SWT.NULL);
222     keyGenerateDSA.setText(Messages.CVSSSH2PreferencePage_131);
223     gd=new GridData();
224     gd.horizontalSpan=1;
225     keyGenerateDSA.setLayoutData(gd);
226
227     keyGenerateRSA=new Button(group, SWT.NULL);
228     keyGenerateRSA.setText(Messages.CVSSSH2PreferencePage_132);
229     gd=new GridData();
230     gd.horizontalSpan=1;
231     keyGenerateRSA.setLayoutData(gd);
232
233     keyLoad=new Button(group, SWT.NULL);
234     keyLoad.setText(Messages.CVSSSH2PreferencePage_128);
235     gd=new GridData();
236     gd.horizontalSpan=1;
237     keyLoad.setLayoutData(gd);
238
239     publicKeylabel=new Label(group, SWT.NONE);
240     publicKeylabel.setText(Messages.CVSSSH2PreferencePage_39);
241     gd=new GridData();
242     gd.horizontalSpan=columnSpan;
243     publicKeylabel.setLayoutData(gd);
244
245     publicKeyText=new Text(group, SWT.MULTI|SWT.BORDER|SWT.V_SCROLL|SWT.WRAP|SWT.LEFT_TO_RIGHT);
246     publicKeyText.setText(""); //$NON-NLS-1$
247
publicKeyText.setEditable(false);
248     gd=new GridData();
249     gd.horizontalSpan=columnSpan;
250     gd.horizontalAlignment=GridData.FILL;
251     gd.verticalAlignment=GridData.FILL;
252     gd.grabExcessHorizontalSpace=true;
253     gd.grabExcessVerticalSpace=true;
254     publicKeyText.setLayoutData(gd);
255
256     keyFingerPrintLabel=new Label(group, SWT.NONE);
257     keyFingerPrintLabel.setText(Messages.CVSSSH2PreferencePage_41);
258     keyFingerPrintText=new Text(group, SWT.SINGLE|SWT.BORDER|SWT.LEFT_TO_RIGHT);
259     keyFingerPrintText.setFont(group.getFont());
260     keyFingerPrintText.setEditable(false);
261     gd=new GridData(GridData.FILL_HORIZONTAL);
262     gd.horizontalSpan=2;
263     keyFingerPrintText.setLayoutData(gd);
264
265     keyCommentLabel=new Label(group, SWT.NONE);
266     keyCommentLabel.setText(Messages.CVSSSH2PreferencePage_42);
267     keyCommentText=new Text(group, SWT.SINGLE|SWT.BORDER);
268     keyCommentText.setFont(group.getFont());
269     gd=new GridData(GridData.FILL_HORIZONTAL);
270     gd.horizontalSpan=2;
271     keyCommentText.setLayoutData(gd);
272
273     keyCommentText.addModifyListener(new ModifyListener(){
274       public void modifyText(ModifyEvent e){
275         if(kpair==null)
276           return;
277         try{
278           ByteArrayOutputStream out=new ByteArrayOutputStream();
279           kpair.writePublicKey(out, keyCommentText.getText());
280           out.close();
281           publicKeyText.setText(out.toString());
282         }
283         catch(IOException ee){
284           // Ignore
285
}
286       }
287     });
288
289     keyPassphrase1Label=new Label(group, SWT.NONE);
290     keyPassphrase1Label.setText(Messages.CVSSSH2PreferencePage_43);
291     keyPassphrase1Text=new Text(group, SWT.SINGLE|SWT.BORDER);
292     keyPassphrase1Text.setFont(group.getFont());
293     keyPassphrase1Text.setEchoChar('*');
294     gd=new GridData(GridData.FILL_HORIZONTAL);
295     gd.horizontalSpan=2;
296     keyPassphrase1Text.setLayoutData(gd);
297
298     keyPassphrase2Label=new Label(group, SWT.NONE);
299     keyPassphrase2Label.setText(Messages.CVSSSH2PreferencePage_44);
300     keyPassphrase2Text=new Text(group, SWT.SINGLE|SWT.BORDER);
301     keyPassphrase2Text.setFont(group.getFont());
302     keyPassphrase2Text.setEchoChar('*');
303     gd=new GridData(GridData.FILL_HORIZONTAL);
304     gd.horizontalSpan=2;
305     keyPassphrase2Text.setLayoutData(gd);
306
307     keyPassphrase1Text.addModifyListener(new ModifyListener(){
308       public void modifyText(ModifyEvent e){
309         String JavaDoc pass1=keyPassphrase1Text.getText();
310         String JavaDoc pass2=keyPassphrase2Text.getText();
311         if(kpair!=null&&pass1.equals(pass2)){
312           saveKeyPair.setEnabled(true);
313         }
314         else{
315           saveKeyPair.setEnabled(false);
316         }
317         if(pass2.length()==0){
318           setErrorMessage(null);
319           return;
320         }
321         if(pass1.equals(pass2)){
322           setErrorMessage(null);
323         }
324         else{
325           setErrorMessage(Messages.CVSSSH2PreferencePage_48);
326         }
327       }
328     });
329
330     keyPassphrase2Text.addModifyListener(new ModifyListener(){
331       public void modifyText(ModifyEvent e){
332         String JavaDoc pass1=keyPassphrase1Text.getText();
333         String JavaDoc pass2=keyPassphrase2Text.getText();
334         if(kpair!=null&&pass1.equals(pass2)){
335           saveKeyPair.setEnabled(true);
336         }
337         else{
338           saveKeyPair.setEnabled(false);
339         }
340         if(pass2.length()<pass1.length()){
341           if(pass1.startsWith(pass2)){
342             setErrorMessage(null);
343           }
344           else{
345             setErrorMessage(Messages.CVSSSH2PreferencePage_48);
346           }
347           return;
348         }
349         if(pass1.equals(pass2)){
350           setErrorMessage(null);
351         }
352         else{
353           setErrorMessage(Messages.CVSSSH2PreferencePage_48);
354         }
355       }
356     });
357
358     keyPassphrase2Text.addFocusListener(new FocusListener(){
359       public void focusGained(FocusEvent e){
360         String JavaDoc pass1=keyPassphrase1Text.getText();
361         String JavaDoc pass2=keyPassphrase2Text.getText();
362         if(pass2.length()<pass1.length()){
363           if(pass1.startsWith(pass2)){
364             setErrorMessage(null);
365           }
366           else{
367             setErrorMessage(Messages.CVSSSH2PreferencePage_48);
368           }
369           return;
370         }
371         if(pass1.equals(pass2)){
372           setErrorMessage(null);
373         }
374         else{
375           setErrorMessage(Messages.CVSSSH2PreferencePage_48);
376         }
377       }
378
379       public void focusLost(FocusEvent e){
380         String JavaDoc pass1=keyPassphrase1Text.getText();
381         String JavaDoc pass2=keyPassphrase2Text.getText();
382         if(pass1.equals(pass2)){
383           setErrorMessage(null);
384         }
385         else{
386           setErrorMessage(Messages.CVSSSH2PreferencePage_48);
387         }
388       }
389     });
390
391     Composite buttons=new Composite(group, SWT.NONE);
392     layout=new GridLayout(2, true);
393     layout.marginWidth=0;
394     layout.marginHeight=0;
395     layout.horizontalSpacing=convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING);
396     buttons.setLayout(layout);
397     gd=new GridData(GridData.HORIZONTAL_ALIGN_END);
398     gd.horizontalSpan=columnSpan;
399     buttons.setLayoutData(gd);
400
401     keyExport=new Button(buttons, SWT.NULL);
402     keyExport.setText(Messages.CVSSSH2PreferencePage_105);
403     gd=new GridData(GridData.FILL_BOTH);
404     keyExport.setLayoutData(gd);
405
406     saveKeyPair=new Button(buttons, SWT.NULL);
407     saveKeyPair.setText(Messages.CVSSSH2PreferencePage_45);
408     gd=new GridData(GridData.FILL_BOTH);
409     saveKeyPair.setLayoutData(gd);
410
411     SelectionAdapter keygenadapter=new SelectionAdapter(){
412       public void widgetSelected(SelectionEvent e){
413         boolean ok=true;
414         String JavaDoc _type=""; //$NON-NLS-1$
415

416         try{
417           int type=0;
418           if(e.widget==keyGenerateDSA){
419             type=KeyPair.DSA;
420             _type=IConstants.DSA;
421           }
422           else if(e.widget==keyGenerateRSA){
423             type=KeyPair.RSA;
424             _type=IConstants.RSA;
425           }
426           else{
427             return;
428           }
429
430           final KeyPair[] _kpair=new KeyPair[1];
431           final int __type=type;
432           final JSchException[] _e=new JSchException[1];
433           BusyIndicator.showWhile(getShell().getDisplay(), new Runnable JavaDoc(){
434             public void run(){
435               try{
436                 _kpair[0]=KeyPair.genKeyPair(getJSch(), __type);
437               }
438               catch(JSchException e){
439                 _e[0]=e;
440               }
441             }
442           });
443           if(_e[0]!=null){
444             throw _e[0];
445           }
446           kpair=_kpair[0];
447
448           ByteArrayOutputStream out=new ByteArrayOutputStream();
449           kpairComment=_type+"-1024"; //$NON-NLS-1$
450
kpair.writePublicKey(out, kpairComment);
451           out.close();
452           publicKeyText.setText(out.toString());
453           keyFingerPrintText.setText(kpair.getFingerPrint());
454           keyCommentText.setText(kpairComment);
455           keyPassphrase1Text.setText(""); //$NON-NLS-1$
456
keyPassphrase2Text.setText(""); //$NON-NLS-1$
457
updateControls();
458         }
459         catch(IOException ee){
460           ok=false;
461         }
462         catch(JSchException ee){
463           ok=false;
464         }
465         if(!ok){
466           MessageDialog.openError(getShell(),
467               Messages.CVSSSH2PreferencePage_error,
468               Messages.CVSSSH2PreferencePage_47);
469         }
470       }
471     };
472     keyGenerateDSA.addSelectionListener(keygenadapter);
473     keyGenerateRSA.addSelectionListener(keygenadapter);
474
475     keyLoad.addSelectionListener(new SelectionAdapter(){
476       public void widgetSelected(SelectionEvent e){
477         boolean ok=true;
478         String JavaDoc home=ssh2HomeText.getText();
479         FileDialog fd=new FileDialog(getShell(), SWT.OPEN);
480         fd.setFilterPath(home);
481         Object JavaDoc o=fd.open();
482         if(o==null){ // cancel
483
return;
484         }
485         String JavaDoc pkey=fd.getFileName();
486         String JavaDoc pkeyab=(new File(fd.getFilterPath(), pkey)).getAbsolutePath();
487         try{
488           KeyPair _kpair=KeyPair.load(getJSch(), pkeyab);
489           PassphrasePrompt prompt=null;
490           while(_kpair.isEncrypted()){
491             if(prompt==null){
492               prompt=new PassphrasePrompt(NLS.bind(
493                   Messages.CVSSSH2PreferencePage_126, new String JavaDoc[] {pkey}));
494             }
495             Display.getDefault().syncExec(prompt);
496             String JavaDoc passphrase=prompt.getPassphrase();
497             if(passphrase==null)
498               break;
499             if(_kpair.decrypt(passphrase)){
500               break;
501             }
502             MessageDialog.openError(getShell(),
503                 Messages.CVSSSH2PreferencePage_error, NLS.bind(
504                     Messages.CVSSSH2PreferencePage_129, new String JavaDoc[] {pkey}));
505           }
506           if(_kpair.isEncrypted()){
507             return;
508           }
509           kpair=_kpair;
510           String JavaDoc _type=(kpair.getKeyType()==KeyPair.DSA) ? IConstants.DSA
511               : IConstants.RSA;
512           ByteArrayOutputStream out=new ByteArrayOutputStream();
513           kpairComment=_type+"-1024"; //$NON-NLS-1$
514
kpair.writePublicKey(out, kpairComment);
515           out.close();
516           publicKeyText.setText(out.toString());
517           keyFingerPrintText.setText(kpair.getFingerPrint());
518           keyCommentText.setText(kpairComment);
519           keyPassphrase1Text.setText(""); //$NON-NLS-1$
520
keyPassphrase2Text.setText(""); //$NON-NLS-1$
521
updateControls();
522         }
523         catch(IOException ee){
524           ok=false;
525         }
526         catch(JSchException ee){
527           ok=false;
528         }
529         if(!ok){
530           MessageDialog.openError(getShell(),
531               Messages.CVSSSH2PreferencePage_error,
532               Messages.CVSSSH2PreferencePage_130);
533         }
534       }
535     });
536
537     keyExport.addSelectionListener(new SelectionAdapter(){
538       public void widgetSelected(SelectionEvent e){
539         if(kpair==null)
540           return;
541
542         setErrorMessage(null);
543
544         final String JavaDoc[] target=new String JavaDoc[1];
545         final String JavaDoc title=Messages.CVSSSH2PreferencePage_106;
546         final String JavaDoc message=Messages.CVSSSH2PreferencePage_107;
547         Display.getDefault().syncExec(new Runnable JavaDoc(){
548           public void run(){
549             Display display=Display.getCurrent();
550             Shell shell=new Shell(display);
551             ExportDialog dialog=new ExportDialog(shell, title, message);
552             dialog.open();
553             shell.dispose();
554             target[0]=dialog.getTarget();
555           }
556         });
557         if(target[0]==null){
558           return;
559         }
560         String JavaDoc user=""; //$NON-NLS-1$
561
String JavaDoc host=""; //$NON-NLS-1$
562
int port=22;
563
564         if(target[0].indexOf('@')>0){
565           user=target[0].substring(0, target[0].indexOf('@'));
566           host=target[0].substring(target[0].indexOf('@')+1);
567         }
568         if(host.indexOf(':')>0){
569           try{
570             port=Integer.parseInt(host.substring(host.indexOf(':')+1));
571           }
572           catch(NumberFormatException JavaDoc ee){
573             port=-1;
574           }
575           host=host.substring(0, host.indexOf(':'));
576         }
577
578         if(user.length()==0||host.length()==0||port==-1){
579           setErrorMessage(NLS.bind(Messages.CVSSSH2PreferencePage_108,
580               new String JavaDoc[] {target[0]}));
581           return;
582         }
583
584         String JavaDoc options=""; //$NON-NLS-1$
585
try{
586           ByteArrayOutputStream bos=new ByteArrayOutputStream();
587           if(options.length()!=0){
588             try{
589               bos.write((options+" ").getBytes());} //$NON-NLS-1$
590
catch(IOException eeee){
591               // Ignore
592
}
593           }
594           kpair.writePublicKey(bos, kpairComment);
595           bos.close();
596           export_via_sftp(user, host, port, /* ".ssh/authorized_keys", //$NON-NLS-1$ */
597               bos.toByteArray());
598         }
599         catch(IOException ee){
600        // Ignore
601
}
602         catch(JSchException ee){
603           setErrorMessage(Messages.CVSSSH2PreferencePage_111);
604         }
605       }
606     });
607
608     saveKeyPair.addSelectionListener(new SelectionAdapter(){
609       public void widgetSelected(SelectionEvent e){
610         if(kpair==null)
611           return;
612
613         String JavaDoc pass=keyPassphrase1Text.getText();
614         /*
615          * if(!pass.equals(keyPassphrase2Text.getText())){
616          * setErrorMessage(Policy.bind("CVSSSH2PreferencePage.48"));
617          * //$NON-NLS-1$ return; }
618          */

619         if(pass.length()==0){
620           if(!MessageDialog.openConfirm(getShell(),
621               Messages.CVSSSH2PreferencePage_confirmation,
622               Messages.CVSSSH2PreferencePage_49)){
623             return;
624           }
625         }
626
627         kpair.setPassphrase(pass);
628
629         String JavaDoc home=ssh2HomeText.getText();
630
631         File _home=new File(home);
632
633         if(!_home.exists()){
634           if(!MessageDialog.openConfirm(getShell(),
635               Messages.CVSSSH2PreferencePage_confirmation, NLS.bind(
636                   Messages.CVSSSH2PreferencePage_50, new String JavaDoc[] {home}))){
637             return;
638           }
639           if(!_home.mkdirs()){
640             setErrorMessage(Messages.CVSSSH2PreferencePage_100+home);
641             return;
642           }
643         }
644
645         FileDialog fd=new FileDialog(getShell(), SWT.SAVE);
646         fd.setFilterPath(home);
647         String JavaDoc file=(kpair.getKeyType()==KeyPair.RSA) ? "id_rsa" : "id_dsa"; //$NON-NLS-1$ //$NON-NLS-2$
648
fd.setFileName(file);
649         file=fd.open();
650         if(file==null){ // cancel
651
return;
652         }
653
654         if(new File(file).exists()){
655           if(!MessageDialog.openConfirm(getShell(),
656               Messages.CVSSSH2PreferencePage_confirmation, //
657
NLS.bind(Messages.CVSSSH2PreferencePage_53, new String JavaDoc[] {file}))){
658             return;
659           }
660         }
661
662         boolean ok=true;
663         try{
664           kpair.writePrivateKey(file);
665           kpair.writePublicKey(file+".pub", kpairComment); //$NON-NLS-1$
666
}
667         catch(Exception JavaDoc ee){
668           ok=false;
669         }
670
671         if(ok){
672           MessageDialog.openInformation(getShell(),
673               Messages.CVSSSH2PreferencePage_information,
674               Messages.CVSSSH2PreferencePage_55+"\n"+ //$NON-NLS-1$
675
Messages.CVSSSH2PreferencePage_57+file+"\n"+ //$NON-NLS-1$
676
Messages.CVSSSH2PreferencePage_59+file+".pub"); //$NON-NLS-1$
677
}
678         else{
679           return;
680         }
681
682         // The generated key should be added to privateKeyText.
683

684         String JavaDoc dir=fd.getFilterPath();
685         File mypkey=new java.io.File JavaDoc(dir, fd.getFileName());
686         String JavaDoc pkeys=privateKeyText.getText();
687
688         // Check if the generated key has been included in pkeys?
689
String JavaDoc[] pkeysa=pkeys.split(","); //$NON-NLS-1$
690
for(int i=0; i<pkeysa.length; i++){
691           File pkey=new java.io.File JavaDoc(pkeysa[i]);
692           if(!pkey.isAbsolute()){
693             pkey=new java.io.File JavaDoc(home, pkeysa[i]);
694           }
695           if(pkey.equals(mypkey))
696             return;
697         }
698
699         if(dir.equals(home)){
700           dir="";} //$NON-NLS-1$
701
else{
702           dir+=java.io.File.separator;
703         }
704         if(pkeys.length()>0)
705           pkeys+=","; //$NON-NLS-1$
706
pkeys=pkeys+dir+fd.getFileName();
707         privateKeyText.setText(pkeys);
708       }
709     });
710
711     return group;
712   }
713
714   private TableViewer viewer;
715   private Button removeHostKeyButton;
716
717   class TableLabelProvider extends LabelProvider implements ITableLabelProvider{
718     public String JavaDoc getColumnText(Object JavaDoc element, int columnIndex){
719       HostKey entry=(HostKey)element;
720       switch(columnIndex){
721         case 0:
722           return entry.getHost();
723         case 1:
724           return entry.getType();
725         case 2:
726           return entry.getFingerPrint(getJSch());
727         default:
728           return null;
729       }
730     }
731
732     public Image getColumnImage(Object JavaDoc element, int columnIndex){
733       return null;
734     }
735   }
736
737   private Control createHostKeyManagementPage(Composite parent){
738     Composite group=new Composite(parent, SWT.NULL);
739     GridLayout layout=new GridLayout();
740     layout.marginHeight=convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN);
741     layout.marginWidth=convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN);
742     layout.verticalSpacing=convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING);
743     layout.horizontalSpacing=convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING);
744     layout.numColumns=2;
745     group.setLayout(layout);
746     GridData gd=new GridData();
747     gd.horizontalAlignment=GridData.FILL;
748     gd.verticalAlignment=GridData.FILL;
749     group.setLayoutData(gd);
750
751     Label label=new Label(group, SWT.NONE);
752     label.setText(Messages.CVSSSH2PreferencePage_139);
753     gd=new GridData();
754     gd.horizontalSpan=2;
755     label.setLayoutData(gd);
756
757     viewer=new TableViewer(group, SWT.MULTI|SWT.FULL_SELECTION|SWT.H_SCROLL
758         |SWT.V_SCROLL|SWT.BORDER);
759     Table table=viewer.getTable();
760     new TableEditor(table);
761     table.setHeaderVisible(true);
762     table.setLinesVisible(true);
763     gd=new GridData(GridData.FILL_BOTH);
764     gd.widthHint=convertWidthInCharsToPixels(30);
765     /*
766      * The hardcoded hint does not look elegant, but in reality it does not make
767      * anything bound to this 100-pixel value, because in any case the tree on
768      * the left is taller and that's what really determines the height.
769      */

770     gd.heightHint=100;
771     table.setLayoutData(gd);
772     table.addListener(SWT.Selection, new Listener(){
773       public void handleEvent(Event e){
774         handleSelection();
775       }
776     });
777     // Create the table columns
778
new TableColumn(table, SWT.NULL);
779     new TableColumn(table, SWT.NULL);
780     new TableColumn(table, SWT.NULL);
781     TableColumn[] columns=table.getColumns();
782     columns[0].setText(Messages.CVSSSH2PreferencePage_134);
783     columns[1].setText(Messages.CVSSSH2PreferencePage_135);
784     columns[2].setText(Messages.CVSSSH2PreferencePage_136);
785     viewer.setColumnProperties(new String JavaDoc[] {
786         Messages.CVSSSH2PreferencePage_134, //
787
Messages.CVSSSH2PreferencePage_135, //
788
Messages.CVSSSH2PreferencePage_136});
789     viewer.setLabelProvider(new TableLabelProvider());
790     viewer.setContentProvider(new IStructuredContentProvider(){
791       public void dispose(){
792         // nothing to do
793
}
794
795       public void inputChanged(Viewer viewer, Object JavaDoc oldInput, Object JavaDoc newInput){
796         // nothing to do
797
}
798
799       public Object JavaDoc[] getElements(Object JavaDoc inputElement){
800         if(inputElement==null)
801           return null;
802         return (Object JavaDoc[])inputElement;
803       }
804     });
805     TableLayout tl=new TableLayout();
806     tl.addColumnData(new ColumnWeightData(30));
807     tl.addColumnData(new ColumnWeightData(20));
808     tl.addColumnData(new ColumnWeightData(70));
809     table.setLayout(tl);
810
811     Composite buttons=new Composite(group, SWT.NULL);
812     buttons.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_BEGINNING));
813     layout=new GridLayout();
814     layout.marginHeight=0;
815     layout.marginWidth=0;
816     buttons.setLayout(layout);
817
818     removeHostKeyButton=new Button(buttons, SWT.PUSH);
819     removeHostKeyButton.setText(Messages.CVSSSH2PreferencePage_138);
820     int buttonWidth=SWTUtils
821         .calculateControlSize(SWTUtils.createDialogPixelConverter(parent),
822             new Button[] {removeHostKeyButton});
823     removeHostKeyButton.setLayoutData(SWTUtils.createGridData(buttonWidth,
824         SWT.DEFAULT, SWT.END, SWT.CENTER, false, false));
825     removeHostKeyButton.setEnabled(false);
826     removeHostKeyButton.addListener(SWT.Selection, new Listener(){
827       public void handleEvent(Event e){
828         removeHostKey();
829       }
830     });
831
832     Dialog.applyDialogFont(parent);
833
834     // JSchSession.loadKnownHosts(JSchContext.getDefaultContext().getJSch());
835
JSchCorePlugin.getPlugin().loadKnownHosts();
836     HostKeyRepository hkr=getJSch().getHostKeyRepository();
837     viewer.setInput(hkr.getHostKey());
838     handleSelection();
839
840     return group;
841   }
842
843   void handleSelection(){
844     boolean empty=viewer.getSelection().isEmpty();
845     removeHostKeyButton.setEnabled(!empty);
846   }
847
848   void removeHostKey(){
849     IStructuredSelection selection=(IStructuredSelection)viewer.getSelection();
850     HostKeyRepository hkr=getJSch().getHostKeyRepository();
851     for(Iterator JavaDoc iterator=selection.iterator(); iterator.hasNext();){
852       HostKey hostkey=(HostKey)iterator.next();
853       hkr.remove(hostkey.getHost(), hostkey.getType());
854       viewer.remove(hostkey);
855     }
856   }
857
858   void export_via_sftp(String JavaDoc user, String JavaDoc host, int port,
859       /* String target, */ byte[] pkey) throws JSchException{
860     try{
861
862       /*
863        * int i=0; String authorized_keys=target; String dir=""; String
864        * separator="/"; i=target.lastIndexOf("/"); if(i<0){
865        * i=target.lastIndexOf("\\"); if(i>=0){ separator="\\"; } } else{ }
866        * if(i>=0){ authorized_keys=target.substring(i+1);
867        * dir=target.substring(0, i+1); }
868        */

869
870       int timeout = 60000;
871       IJSchService service = JSchUIPlugin.getPlugin().getJSchService();
872       if (service == null) {
873         MessageDialog.openInformation(getShell(), Messages.PreferencePage_0, Messages.PreferencePage_1);
874         return;
875       }
876       Session session = service.createSession(host, port, user);
877       new UserInfoPrompter(session);
878       session.setTimeout(timeout);
879       try {
880         service.connect(session, timeout, new NullProgressMonitor());
881           if(session.getServerVersion().indexOf("OpenSSH")==-1){ //$NON-NLS-1$
882
setErrorMessage(Messages.CVSSSH2PreferencePage_110);
883             return;
884           }
885           Channel channel=session.openChannel("sftp"); //$NON-NLS-1$
886
channel.connect();
887           ChannelSftp c=(ChannelSftp)channel;
888
889           /* String pwd= */c.pwd(); // Read off the channel
890
SftpATTRS attr=null;
891     
892           try{
893             attr=c.stat(".ssh");} //$NON-NLS-1$
894
catch(SftpException ee){
895           // Ignore
896
}
897           if(attr==null){
898             try{
899               c.mkdir(".ssh");} //$NON-NLS-1$
900
catch(SftpException ee){
901               setErrorMessage(ee.getMessage());
902               return;
903             }
904           }
905           try{
906             c.cd(".ssh");} //$NON-NLS-1$
907
catch(SftpException ee){
908             setErrorMessage(ee.getMessage());
909             return;
910           }
911
912           try{
913             ByteArrayInputStream bis=new ByteArrayInputStream(pkey);
914             c.put(bis, "authorized_keys", null, ChannelSftp.APPEND); //$NON-NLS-1$
915
bis.close();
916             checkPermission(c, "authorized_keys"); //$NON-NLS-1$
917
checkPermission(c, "."); // .ssh //$NON-NLS-1$
918
c.cd(".."); //$NON-NLS-1$
919
checkPermission(c, "."); // home directory //$NON-NLS-1$
920
}
921           catch(SftpException ee){
922             // setErrorMessage(debug+ee.message);
923
}
924
925           MessageDialog.openInformation(getShell(),
926               Messages.CVSSSH2PreferencePage_information,
927               NLS.bind(Messages.CVSSSH2PreferencePage_109, (user
928                   +"@"+host+(port==22 ? "" : ":"+port)+":~/.ssh/authorized_keys"))); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
929

930           c.disconnect();
931       } finally {
932         session.disconnect();
933       }
934     } catch(IOException eee){
935       setErrorMessage(eee.toString());
936     }
937   }
938
939   private void checkPermission(ChannelSftp c, String JavaDoc path) throws SftpException{
940     SftpATTRS attr=c.stat(path);
941     int permissions=attr.getPermissions();
942     if((permissions&00022)!=0){
943       permissions&=~00022;
944       c.chmod(permissions, path);
945     }
946   }
947
948   void updateControls(){
949     boolean enable=(kpair!=null);
950     publicKeylabel.setEnabled(enable);
951     publicKeyText.setEnabled(enable);
952     keyFingerPrintLabel.setEnabled(enable);
953     keyFingerPrintText.setEnabled(enable);
954     keyCommentLabel.setEnabled(enable);
955     keyCommentText.setEnabled(enable);
956     keyPassphrase1Label.setEnabled(enable);
957     keyPassphrase1Text.setEnabled(enable);
958     keyPassphrase2Label.setEnabled(enable);
959     keyPassphrase2Text.setEnabled(enable);
960     keyExport.setEnabled(enable);
961     saveKeyPair.setEnabled(enable);
962   }
963
964   public void init(IWorkbench workbench){
965     // super.init(workbench);
966
// initControls();
967
}
968
969   public void initialize(){
970     initControls();
971   }
972
973   private void initControls(){
974     // Preferences preferences=JSchCorePlugin.getPlugin().getPreferences();
975
Preferences preferences=JSchCorePlugin.getPlugin().getPluginPreferences();
976     ssh2HomeText.setText(preferences
977         .getString(org.eclipse.jsch.internal.core.IConstants.KEY_SSH2HOME));
978     privateKeyText.setText(preferences
979         .getString(org.eclipse.jsch.internal.core.IConstants.KEY_PRIVATEKEY));
980     updateControls();
981   }
982
983   public boolean performOk(){
984     boolean result=super.performOk();
985     if(result){
986       setErrorMessage(null);
987       String JavaDoc home=ssh2HomeText.getText();
988       File _home=new File(home);
989       if(!_home.exists()){
990         if(MessageDialog.openQuestion(getShell(),
991             Messages.CVSSSH2PreferencePage_question, NLS.bind(
992                 Messages.CVSSSH2PreferencePage_99, new String JavaDoc[] {home}))){
993           if(!(_home.mkdirs())){
994             setErrorMessage(Messages.CVSSSH2PreferencePage_100+home);
995             return false;
996           }
997         }
998       }
999
1000      // Preferences preferences=JSchCorePlugin.getPlugin().getPreferences();
1001
Preferences preferences=JSchCorePlugin.getPlugin().getPluginPreferences();
1002      preferences.setValue(
1003          org.eclipse.jsch.internal.core.IConstants.KEY_SSH2HOME, home);
1004      preferences.setValue(
1005          org.eclipse.jsch.internal.core.IConstants.KEY_PRIVATEKEY,
1006          privateKeyText.getText());
1007    }
1008    JSchCorePlugin.getPlugin().setNeedToLoadKnownHosts(true);
1009    JSchCorePlugin.getPlugin().setNeedToLoadKeys(true);
1010    JSchCorePlugin.getPlugin().savePluginPreferences();
1011    return result;
1012  }
1013
1014  public void performApply(){
1015    performOk();
1016  }
1017
1018  protected void performDefaults(){
1019    super.performDefaults();
1020    // Preferences preferences=JSchCorePlugin.getPlugin().getPreferences();
1021
Preferences preferences=JSchCorePlugin.getPlugin().getPluginPreferences();
1022    ssh2HomeText
1023        .setText(preferences
1024            .getDefaultString(org.eclipse.jsch.internal.core.IConstants.KEY_SSH2HOME));
1025    privateKeyText
1026        .setText(preferences
1027            .getDefaultString(org.eclipse.jsch.internal.core.IConstants.KEY_PRIVATEKEY));
1028    updateControls();
1029  }
1030
1031  protected void createSpacer(Composite composite, int columnSpan){
1032    Label label=new Label(composite, SWT.NONE);
1033    GridData gd=new GridData();
1034    gd.horizontalSpan=columnSpan;
1035    label.setLayoutData(gd);
1036  }
1037
1038  JSch getJSch(){
1039    return JSchCorePlugin.getPlugin().getJSch();
1040  }
1041
1042  class PassphrasePrompt implements Runnable JavaDoc{
1043    private String JavaDoc message;
1044    private String JavaDoc passphrase;
1045
1046    PassphrasePrompt(String JavaDoc message){
1047      this.message=message;
1048    }
1049
1050    public void run(){
1051      Display display=Display.getCurrent();
1052      Shell shell=new Shell(display);
1053      PassphraseDialog dialog=new PassphraseDialog(shell, message);
1054      dialog.open();
1055      shell.dispose();
1056      passphrase=dialog.getPassphrase();
1057    }
1058
1059    public String JavaDoc getPassphrase(){
1060      return passphrase;
1061    }
1062  }
1063}
1064
Popular Tags