1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911
|
package cli
import (
"encoding/hex"
"errors"
"fmt"
"io/ioutil"
"net/url"
"os"
"os/signal"
"path/filepath"
"strconv"
"strings"
"syscall"
"time"
"github.com/twstrike/coyim/cli/terminal"
"github.com/twstrike/coyim/client"
"github.com/twstrike/coyim/config"
"github.com/twstrike/coyim/servers"
sessions "github.com/twstrike/coyim/session/access"
"github.com/twstrike/coyim/tls"
"github.com/twstrike/coyim/xmpp/data"
xi "github.com/twstrike/coyim/xmpp/interfaces"
"github.com/twstrike/otr3"
"golang.org/x/net/proxy"
)
type cliUI struct {
session sessions.Session
sessionFactory sessions.Factory
dialerFactory func(tls.Verifier) xi.Dialer
events chan interface{}
commands chan interface{}
password string
termControl terminal.Control
oldState interface{}
term terminal.Terminal
input *input
terminate chan bool
RosterEditor
}
// UI is the user interface functionality exposed to main
type UI interface {
Loop()
}
// NewCLI creates a new cliUI instance
func NewCLI(version string, cf terminal.ControlFactory, sf sessions.Factory, df func(tls.Verifier) xi.Dialer) UI {
termControl := cf()
oldState, err := termControl.MakeRaw(0)
if err != nil {
panic(err.Error())
}
term := termControl.NewTerminal(os.Stdin, "")
updateTerminalSize(term, termControl)
term.SetBracketedPasteMode(true)
resizeChan := make(chan os.Signal)
go func() {
for _ = range resizeChan {
updateTerminalSize(term, termControl)
}
}()
signal.Notify(resizeChan, syscall.SIGWINCH)
return &cliUI{
termControl: termControl,
term: term,
oldState: oldState,
terminate: make(chan bool),
input: &input{
tc: termControl,
term: term,
uidComplete: new(priorityList),
},
RosterEditor: RosterEditor{
PendingRosterChan: make(chan *RosterEdit),
},
events: make(chan interface{}),
commands: make(chan interface{}, 5),
sessionFactory: sf,
dialerFactory: df,
}
}
func (c *cliUI) getMasterPassword(params config.EncryptionParameters, previousFailed bool) ([]byte, []byte, bool) {
password, err := c.term.ReadPassword("Master password for configuration file: ")
if err != nil {
c.alert(err.Error())
return nil, nil, false
}
l, r := config.GenerateKeys(password, params)
return l, r, true
}
func findAccount(a *string, acs []*config.Account) *config.Account {
if a != nil && *a != "" {
for _, ac := range acs {
if ac.Account == *a {
return ac
}
}
}
return acs[0]
}
func (c *cliUI) loadConfig(configFile string) error {
accounts, ok, err := config.LoadOrCreate(configFile, config.FunctionKeySupplier(c.getMasterPassword))
if !ok {
c.alert("Couldn't open encrypted file - did you enter your password correctly?")
return errors.New("couldn't open encrypted file - did you supply the wrong password?")
}
if err != nil {
c.alert(err.Error())
acc, e := accounts.AddNewAccount()
if e != nil {
return e
}
if !c.enroll(accounts, acc) {
return errors.New("asked to quit")
}
}
account := findAccount(config.AccountFlag, accounts.Accounts)
var password string
if len(account.Password) == 0 {
var err error
password, err = c.term.ReadPassword(
fmt.Sprintf("Password for %s (will not be saved to disk): ", account.Account),
)
if err != nil {
c.alert(err.Error())
return err
}
} else {
password = account.Password
}
logger := &lineLogger{c.term, c.termControl, nil}
//TODO: call session.ConnectAndRegister() in this case
//var registerCallback xmpp.FormCallback
//if *config.CreateAccount {
// registerCallback = c.RegisterCallback
//}
c.session = c.sessionFactory(accounts, account, c.dialerFactory)
c.session.SetSessionEventHandler(c)
c.session.Subscribe(c.events)
c.session.SetConnectionLogger(logger)
// TODO: this nil is incorrect and will cause failures when trying to use it.
if err := c.session.Connect(password, c.verifier()); err != nil {
c.alert(err.Error())
return err
}
return nil
}
func (c *cliUI) quit() {
c.session.Close()
c.terminate <- true
}
func (c *cliUI) SaveConf() {
c.session.Config().Save(config.FunctionKeySupplier(c.getMasterPassword))
}
func (c *cliUI) Loop() {
defer c.close()
if err := c.loadConfig(*config.ConfigFile); err != nil {
return
}
go c.watchClientCommands()
go c.observeSessionEvents()
go c.watchRosterEdits()
go c.watchInputCommands()
<-c.terminate // wait
}
func (c *cliUI) close() {
if c.oldState != nil {
c.termControl.Restore(0, c.oldState)
}
if c.term != nil {
c.term.SetBracketedPasteMode(false)
}
}
func (c *cliUI) info(m string) {
info(c.term, c.termControl, m)
}
func (c *cliUI) warn(m string) {
warn(c.term, c.termControl, m)
}
func (c *cliUI) alert(m string) {
alert(c.term, c.termControl, m)
}
func (c *cliUI) critical(m string) {
critical(c.term, c.termControl, m)
}
func (c *cliUI) RegisterCallback(title, instructions string, fields []interface{}) error {
user := c.session.GetConfig().Account
return c.promptForForm(user, c.password, title, instructions, fields)
}
func (c *cliUI) printConversationInfo(uid string, conversation client.Conversation) {
s := c.session
fpr := conversation.TheirFingerprint()
fprUID := s.GetConfig().UserIDForVerifiedFingerprint(fpr)
c.info(fmt.Sprintf(" Fingerprint for %s: %X", uid, fpr))
c.info(fmt.Sprintf(" Session ID for %s: %X", uid, conversation.GetSSID()))
if fprUID == uid {
c.info(fmt.Sprintf(" Identity key for %s is verified", uid))
} else if len(fprUID) > 1 {
c.alert(fmt.Sprintf(" Warning: %s is using an identity key which was verified for %s", uid, fprUID))
} else if s.GetConfig().HasFingerprint(uid) {
c.critical(fmt.Sprintf(" Identity key for %s is incorrect", uid))
} else {
c.alert(fmt.Sprintf(" Identity key for %s is not verified. You should use /otr-auth or /otr-authqa or /otr-authoob to verify their identity", uid))
}
}
// promptForForm runs an XEP-0004 form and collects responses from the user.
func (c *cliUI) promptForForm(user, password, title, instructions string, fields []interface{}) error {
c.info("The server has requested the following information. Text that has come from the server will be shown in red.")
// formStringForPrinting takes a string form the form and returns an
// escaped version with codes to make it show as red.
formStringForPrinting := func(s string) string {
var line []byte
line = append(line, c.termControl.Escape(c.term).Red...)
line = appendTerminalEscaped(line, []byte(s))
line = append(line, c.termControl.Escape(c.term).Reset...)
return string(line)
}
write := func(s string) {
c.term.Write([]byte(s))
}
var tmpDir string
showMediaEntries := func(questionNumber int, medias [][]data.Media) {
if len(medias) == 0 {
return
}
write("The following media blobs have been provided by the server with this question:\n")
for i, media := range medias {
for j, rep := range media {
if j == 0 {
write(fmt.Sprintf(" %d. ", i+1))
} else {
write(" ")
}
write(fmt.Sprintf("Data of type %s", formStringForPrinting(rep.MIMEType)))
if len(rep.URI) > 0 {
write(fmt.Sprintf(" at %s\n", formStringForPrinting(rep.URI)))
continue
}
var fileExt string
switch rep.MIMEType {
case "image/png":
fileExt = "png"
case "image/jpeg":
fileExt = "jpeg"
}
if len(tmpDir) == 0 {
var err error
if tmpDir, err = ioutil.TempDir("", "xmppclient"); err != nil {
write(", but failed to create temporary directory in which to save it: " + err.Error() + "\n")
continue
}
}
filename := filepath.Join(tmpDir, fmt.Sprintf("%d-%d-%d", questionNumber, i, j))
if len(fileExt) > 0 {
filename = filename + "." + fileExt
}
out, err := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0600)
if err != nil {
write(", but failed to create file in which to save it: " + err.Error() + "\n")
continue
}
out.Write(rep.Data)
out.Close()
write(", saved in " + filename + "\n")
}
}
write("\n")
}
var err error
if len(title) > 0 {
write(fmt.Sprintf("Title: %s\n", formStringForPrinting(title)))
}
if len(instructions) > 0 {
write(fmt.Sprintf("Instructions: %s\n", formStringForPrinting(instructions)))
}
questionNumber := 0
for _, field := range fields {
questionNumber++
write("\n")
switch field := field.(type) {
case *data.FixedFormField:
write(formStringForPrinting(field.Text))
write("\n")
questionNumber--
case *data.BooleanFormField:
write(fmt.Sprintf("%d. %s\n\n", questionNumber, formStringForPrinting(field.Label)))
showMediaEntries(questionNumber, field.Media)
c.term.SetPrompt("Please enter yes, y, no or n: ")
TryAgain:
for {
answer, err := c.term.ReadLine()
if err != nil {
return err
}
switch answer {
case "yes", "y":
field.Result = true
case "no", "n":
field.Result = false
default:
continue TryAgain
}
break
}
case *data.TextFormField:
switch field.Label {
case "CAPTCHA web page":
if strings.HasPrefix(field.Default, "http") {
// This is a oddity of jabber.ccc.de and maybe
// others. The URL for the capture is provided
// as the default answer to a question. Perhaps
// that was needed with some clients. However,
// we support embedded media and it's confusing
// to ask the question, so we just print the
// URL.
write(fmt.Sprintf("CAPTCHA web page (only if not provided below): %s\n", formStringForPrinting(field.Default)))
questionNumber--
continue
}
case "User":
field.Result = user
questionNumber--
continue
case "Password":
field.Result = password
questionNumber--
continue
}
write(fmt.Sprintf("%d. %s\n\n", questionNumber, formStringForPrinting(field.Label)))
showMediaEntries(questionNumber, field.Media)
if len(field.Default) > 0 {
write(fmt.Sprintf("Please enter response or leave blank for the default, which is '%s'\n", formStringForPrinting(field.Default)))
} else {
write("Please enter response")
}
c.term.SetPrompt("> ")
if field.Private {
field.Result, err = c.term.ReadPassword("> ")
} else {
field.Result, err = c.term.ReadLine()
}
if err != nil {
return err
}
if len(field.Result) == 0 {
field.Result = field.Default
}
case *data.MultiTextFormField:
write(fmt.Sprintf("%d. %s\n\n", questionNumber, formStringForPrinting(field.Label)))
showMediaEntries(questionNumber, field.Media)
write("Please enter one or more responses, terminated by an empty line\n")
c.term.SetPrompt("> ")
for {
line, err := c.term.ReadLine()
if err != nil {
return err
}
if len(line) == 0 {
break
}
field.Results = append(field.Results, line)
}
case *data.SelectionFormField:
write(fmt.Sprintf("%d. %s\n\n", questionNumber, formStringForPrinting(field.Label)))
showMediaEntries(questionNumber, field.Media)
for i, opt := range field.Values {
write(fmt.Sprintf(" %d. %s\n\n", i+1, formStringForPrinting(opt)))
}
c.term.SetPrompt("Please enter the number of your selection: ")
TryAgain2:
for {
answer, err := c.term.ReadLine()
if err != nil {
return err
}
answerNum, err := strconv.Atoi(answer)
answerNum--
if err != nil || answerNum < 0 || answerNum >= len(field.Values) {
write("Cannot parse that reply. Try again.")
continue TryAgain2
}
field.Result = answerNum
break
}
case *data.MultiSelectionFormField:
write(fmt.Sprintf("%d. %s\n\n", questionNumber, formStringForPrinting(field.Label)))
showMediaEntries(questionNumber, field.Media)
for i, opt := range field.Values {
write(fmt.Sprintf(" %d. %s\n\n", i+1, formStringForPrinting(opt)))
}
c.term.SetPrompt("Please enter the numbers of zero or more of the above, separated by spaces: ")
TryAgain3:
for {
answer, err := c.term.ReadLine()
if err != nil {
return err
}
var candidateResults []int
answers := strings.Fields(answer)
for _, answerStr := range answers {
answerNum, err := strconv.Atoi(answerStr)
answerNum--
if err != nil || answerNum < 0 || answerNum >= len(field.Values) {
write("Cannot parse that reply. Please try again.")
continue TryAgain3
}
for _, other := range candidateResults {
if answerNum == other {
write("Cannot have duplicates. Please try again.")
continue TryAgain3
}
}
candidateResults = append(candidateResults, answerNum)
}
field.Results = candidateResults
break
}
}
}
if len(tmpDir) > 0 {
os.RemoveAll(tmpDir)
}
return nil
}
func (c *cliUI) watchRosterEdits() {
for edit := range c.PendingRosterChan {
if !edit.IsComplete {
c.info("Please edit " + edit.FileName + " and run /rostereditdone when complete")
c.PendingRosterEdit = edit
continue
}
parsedRoster, err := parseEditedRoster(edit.Contents)
if err != nil {
c.alert(err.Error())
c.alert("Please reedit file and run /rostereditdone again")
continue
}
toDelete, toEdit, toAdd := diffRoster(parsedRoster, edit.Roster)
//DELETE
for _, jid := range toDelete {
c.info("Deleting roster entry for " + jid)
_, _, err := c.session.Conn().SendIQ("" /* to the server */, "set", data.RosterRequest{
Item: data.RosterRequestItem{
Jid: jid,
Subscription: "remove",
},
})
if err != nil {
c.alert("Failed to remove roster entry: " + err.Error())
}
c.session.GetConfig().RemovePeer(jid)
c.session.CommandManager().ExecuteCmd(client.SaveApplicationConfigCmd{})
}
//EDIT
for _, entry := range toEdit {
c.info("Updating roster entry for " + entry.Jid)
_, _, err := c.session.Conn().SendIQ("" /* to the server */, "set", data.RosterRequest{
Item: data.RosterRequestItem{
Jid: entry.Jid,
Name: entry.Name,
Group: entry.Group,
},
})
if err != nil {
c.alert("Failed to update roster entry: " + err.Error())
}
}
//ADD
for _, entry := range toAdd {
c.info("Adding roster entry for " + entry.Jid)
_, _, err := c.session.Conn().SendIQ("" /* to the server */, "set", data.RosterRequest{
Item: data.RosterRequestItem{
Jid: entry.Jid,
Name: entry.Name,
Group: entry.Group,
},
})
if err != nil {
c.alert("Failed to add roster entry: " + err.Error())
}
}
c.PendingRosterEdit = nil
}
}
func (c *cliUI) watchInputCommands() {
defer c.quit()
commandChan := make(chan interface{})
go c.input.processCommands(commandChan)
c.term.SetPrompt("> ")
s := c.session
conf := s.GetConfig()
var err error
CommandLoop:
for {
select {
case cmd, ok := <-commandChan:
if !ok {
c.warn("Exiting because command channel closed")
break CommandLoop
}
s.SetLastActionTime(time.Now())
switch cmd := cmd.(type) {
case quitCommand:
break CommandLoop
case versionCommand:
replyChan, cookie, err := s.Conn().SendIQ(cmd.User, "get", data.VersionQuery{})
if err != nil {
c.alert("Error sending version request: " + err.Error())
continue
}
s.Timeout(cookie, time.Now().Add(5*time.Second))
go s.AwaitVersionReply(replyChan, cmd.User)
case rosterCommand:
c.info("Current roster:")
maxLen := 0
for _, item := range s.R().ToSlice() {
if maxLen < len(item.Jid) {
maxLen = len(item.Jid)
}
}
for _, item := range s.R().ToSlice() {
state, _, ok := s.R().StateOf(item.Jid)
line := ""
if ok {
line += "[*] "
} else if cmd.OnlineOnly {
continue
} else {
line += "[ ] "
}
line += item.Jid
numSpaces := 1 + (maxLen - len(item.Jid))
for i := 0; i < numSpaces; i++ {
line += " "
}
line += item.Subscription + "\t" + item.Name
if ok {
line += "\t" + state
}
c.info(line)
}
case rosterEditCommand:
if c.PendingRosterEdit != nil {
c.warn("Aborting previous roster edit")
c.PendingRosterEdit = nil
}
currR := s.R().ToSlice()
c.RosterEditor.Roster = make([]data.RosterEntry, len(currR))
rosterCopy := make([]data.RosterEntry, len(currR))
for ix, e := range currR {
c.RosterEditor.Roster[ix] = e.ToEntry()
rosterCopy[ix] = e.ToEntry()
}
go func(rosterCopy []data.RosterEntry) {
err := c.EditRoster(rosterCopy)
if err != nil {
c.alert(err.Error())
}
}(rosterCopy)
case rosterEditDoneCommand:
if c.PendingRosterEdit == nil {
c.warn("No roster edit in progress. Use /rosteredit to start one")
continue
}
go func(edit RosterEdit) {
err := c.LoadEditedRoster(edit)
if err != nil {
c.alert(err.Error())
}
}(*c.PendingRosterEdit)
case toggleStatusUpdatesCommand:
s.GetConfig().HideStatusUpdates = !s.GetConfig().HideStatusUpdates
s.CommandManager().ExecuteCmd(client.SaveApplicationConfigCmd{})
// Tell the user the current state of the statuses
if s.GetConfig().HideStatusUpdates {
c.info("Status updates disabled")
} else {
c.info("Status updates enabled")
}
case confirmCommand:
s.HandleConfirmOrDeny(cmd.User, true /* confirm */)
case denyCommand:
s.HandleConfirmOrDeny(cmd.User, false /* deny */)
case addCommand:
s.RequestPresenceSubscription(cmd.User, "")
case msgCommand:
message := []byte(cmd.msg)
conversation, exists := s.ConversationManager().GetConversationWith(cmd.to, "")
if exists {
isEncrypted := conversation.IsEncrypted()
if cmd.setPromptIsEncrypted != nil {
cmd.setPromptIsEncrypted <- isEncrypted
}
if !isEncrypted && conf.ShouldEncryptTo(cmd.to) {
c.warn(fmt.Sprintf("Did not send: no encryption established with %s", cmd.to))
continue
}
}
_, err := conversation.Send(s, "", message)
if err != nil {
c.alert(err.Error())
break
}
case otrCommand:
conversation, _ := s.ConversationManager().GetConversationWith(string(cmd.User), "")
conversation.StartEncryptedChat(s, "")
case otrInfoCommand:
for _, pk := range s.PrivateKeys() {
c.info(fmt.Sprintf("Your OTR fingerprint is %x", pk.PublicKey().Fingerprint()))
}
for to, conversation := range s.ConversationManager().Conversations() {
if conversation.IsEncrypted() {
c.info(fmt.Sprintf("Secure session with %s underway:", to))
c.printConversationInfo(to, conversation)
}
}
case endOTRCommand:
to := string(cmd.User)
conversation, exists := s.ConversationManager().GetConversationWith(to, "")
if !exists {
c.alert("No secure session established")
break
}
err := conversation.EndEncryptedChat(s, "")
if err != nil {
c.alert("Can't end the conversation - it seems there is no randomness in your system. This could be a significant problem.")
break
}
c.input.SetPromptForTarget(cmd.User, false)
c.warn("OTR conversation ended with " + cmd.User)
case authQACommand:
to := string(cmd.User)
conversation, exists := s.ConversationManager().GetConversationWith(to, "")
if !exists {
c.alert("Can't authenticate without a secure conversation established")
break
}
if s.OtrEventHandler()[to].WaitingForSecret {
s.OtrEventHandler()[to].WaitingForSecret = false
err = conversation.ProvideAuthenticationSecret(s, "", []byte(cmd.Secret))
} else {
err = conversation.StartAuthenticate(s, "", cmd.Question, []byte(cmd.Secret))
}
if err != nil {
c.alert("Error while starting authentication with " + to + ": " + err.Error())
}
case authOobCommand:
fpr, err := hex.DecodeString(cmd.Fingerprint)
if err != nil {
c.alert(fmt.Sprintf("Invalid fingerprint %s - not authenticated", cmd.Fingerprint))
break
}
idForFpr := s.GetConfig().UserIDForVerifiedFingerprint(fpr)
if len(idForFpr) != 0 {
c.alert(fmt.Sprintf("Fingerprint %s already belongs to %s", cmd.Fingerprint, idForFpr))
break
}
s.CommandManager().ExecuteCmd(client.AuthorizeFingerprintCmd{
Account: s.GetConfig(),
Peer: cmd.User,
Fingerprint: fpr,
})
c.info(fmt.Sprintf("Saved manually verified fingerprint %s for %s", cmd.Fingerprint, cmd.User))
case awayCommand:
s.Conn().SignalPresence("away")
case chatCommand:
s.Conn().SignalPresence("chat")
case dndCommand:
s.Conn().SignalPresence("dnd")
case xaCommand:
s.Conn().SignalPresence("xa")
case onlineCommand:
s.Conn().SignalPresence("")
}
}
}
}
func (c *cliUI) enroll(conf *config.ApplicationConfig, currentConf *config.Account) bool {
var err error
c.warn("Enrolling new config file")
var domain string
for {
c.term.SetPrompt("Account (i.e. user@example.com, enter to quit): ")
if currentConf.Account, err = c.term.ReadLine(); err != nil || len(currentConf.Account) == 0 {
return false
}
parts := strings.SplitN(currentConf.Account, "@", 2)
if len(parts) != 2 {
c.alert("invalid username (want user@domain): " + currentConf.Account)
continue
}
domain = parts[1]
break
}
c.term.SetPrompt("Enable debug logging to /tmp/xmpp-client-debug.log? ")
if debugLog, err := c.term.ReadLine(); err != nil || !config.ParseYes(debugLog) {
c.info("Not enabling debug logging...")
} else {
c.info("Debug logging enabled...")
conf.RawLogFile = "/tmp/xmpp-client-debug.log"
}
c.term.SetPrompt("Use Tor?: ")
if useTorQuery, err := c.term.ReadLine(); err != nil || len(useTorQuery) == 0 || !config.ParseYes(useTorQuery) {
c.info("Not using Tor...")
currentConf.Proxies = []string{}
} else {
c.info("Using Tor...")
}
c.term.SetPrompt("File to import libotr private key from (enter to generate): ")
var pkeys []otr3.PrivateKey
for {
importFile, err := c.term.ReadLine()
if err != nil {
return false
}
if len(importFile) > 0 {
privKeyBytes, err := ioutil.ReadFile(importFile)
if err != nil {
c.alert("Failed to open private key file: " + err.Error())
continue
}
var priv otr3.DSAPrivateKey
if !priv.Import(privKeyBytes) {
c.alert("Failed to parse libotr private key file (the parser is pretty simple I'm afraid)")
continue
}
pkeys = append(pkeys, &priv)
break
} else {
c.info("Generating private key...")
pkeys, err = otr3.GenerateMissingKeys([][]byte{})
if err != nil {
c.alert("Failed to generate private key - this implies something is really bad with your system, so we bail out now")
return false
}
break
}
}
currentConf.PrivateKeys = config.SerializedKeys(pkeys)
currentConf.OTRAutoAppendTag = true
currentConf.OTRAutoStartSession = true
currentConf.OTRAutoTearDown = false
// Force Tor for servers with well known Tor hidden services.
if _, ok := servers.Get(domain); ok && currentConf.HasTorAuto() {
const torProxyURL = "socks5://127.0.0.1:9050"
c.info("It appears that you are using a well known server and we will use its Tor hidden service to connect.")
currentConf.Proxies = []string{torProxyURL}
c.term.SetPrompt("> ")
return true
}
var proxyStr string
proxyDefaultPrompt := ", enter for none"
if currentConf.HasTorAuto() {
proxyDefaultPrompt = ", which is the default"
}
c.term.SetPrompt("Proxy (i.e socks5://127.0.0.1:9050" + proxyDefaultPrompt + "): ")
for {
if proxyStr, err = c.term.ReadLine(); err != nil {
return false
}
if len(proxyStr) == 0 {
if !currentConf.HasTorAuto() {
break
} else {
proxyStr = "socks5://127.0.0.1:9050"
}
}
u, err := url.Parse(proxyStr)
if err != nil {
c.alert("Failed to parse " + proxyStr + " as a URL: " + err.Error())
continue
}
if _, err = proxy.FromURL(u, proxy.Direct); err != nil {
c.alert("Failed to parse " + proxyStr + " as a proxy: " + err.Error())
continue
}
break
}
c.term.SetPrompt("> ")
return true
}
|