Debian Codegraph @

jid.go

raw
1 // Copyright 2014 The Mellium Contributors.
2 // Use of this source code is governed by the BSD-2-clause
3 // license that can be found in the LICENSE-mellium file.
4
5 // Original taken from mellium.im/xmpp/jid (BSD-2-Clause) and adjusted for my needs.
6 // Copyright Martin Dosch
7
8 package main
9
10 import (
11 "fmt"
12 "strings"
13 "unicode/utf8"
14 )
15
16 // MarshalJID checks that JIDs include localpart and serverpart
17 // and return it marshaled. Shamelessly stolen from
18 // mellium.im/xmpp/jid
19 func MarshalJID(input string) (string, error) {
20 var (
21 err error
22 localpart string
23 domainpart string
24 resourcepart string
25 )
26
27 s := input
28
29 // Remove any portion from the first '/' character to the end of the
30 // string (if there is a '/' character present).
31 sep := strings.Index(s, "/")
32
33 if sep == -1 {
34 resourcepart = ""
35 } else {
36 // If the resource part exists, make sure it isn't empty.
37 if sep == len(s)-1 {
38 return input, fmt.Errorf("invalid jid %s: the resourcepart must be larger than 0 bytes", input)
39 }
40 resourcepart = s[sep+1:]
41 s = s[:sep]
42 }
43
44 // Remove any portion from the beginning of the string to the first
45 // '@' character (if there is an '@' character present).
46
47 sep = strings.Index(s, "@")
48
49 switch sep {
50 case -1:
51 // There is no @ sign, and therefore no localpart.
52 domainpart = s
53 case 0:
54 // The JID starts with an @ sign (invalid empty localpart)
55 err = fmt.Errorf("invalid jid: %s", input)
56 return input, err
57 default:
58 domainpart = s[sep+1:]
59 localpart = s[:sep]
60 }
61
62 // We'll throw out any trailing dots on domainparts, since they're ignored:
63 //
64 // If the domainpart includes a final character considered to be a label
65 // separator (dot) by [RFC1034], this character MUST be stripped from
66 // the domainpart before the JID of which it is a part is used for the
67 // purpose of routing an XML stanza, comparing against another JID, or
68 // constructing an XMPP URI or IRI [RFC5122]. In particular, such a
69 // character MUST be stripped before any other canonicalization steps
70 // are taken.
71
72 domainpart = strings.TrimSuffix(domainpart, ".")
73 var jid string
74
75 if !utf8.ValidString(localpart) || !utf8.ValidString(domainpart) || !utf8.ValidString(resourcepart) {
76 return input, fmt.Errorf("invalid jid: %s", input)
77 }
78
79 if domainpart == "" {
80 return input, fmt.Errorf("invalid jid: %s", input)
81 }
82
83 if localpart == "" {
84 jid = domainpart
85 } else {
86 jid = localpart + "@" + domainpart
87 }
88
89 if resourcepart == "" {
90 return jid, err
91 }
92 return jid + "/" + resourcepart, err
93 }