summaryrefslogtreecommitdiffstats
path: root/vendor/github.com/lrstanley/girc/event.go
blob: 2622f89eb4ce498662bdedb1f669de616789548f (plain) (blame)
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
// Copyright (c) Liam Stanley <me@liamstanley.io>. All rights reserved. Use
// of this source code is governed by the MIT license that can be found in
// the LICENSE file.

package girc

import (
	"bytes"
	"fmt"
	"strings"
	"time"
)

const (
	eventSpace byte = ' ' // Separator.

	// TODO: if state tracking is enabled, we SHOULD be able to use it's known length.

	// Can be overridden by the NICKLEN (or MAXNICKLEN) ISUPPORT parameter. 30 or 31
	// are typical values for this parameter advertised by servers today.
	defaultNickLength = 30
	// The maximum length of <username> may be specified by the USERLEN RPL_ISUPPORT
	// parameter. If this length is advertised, the username MUST be silently truncated
	// to the given length before being used.
	defaultUserLength = 18
	// If a looked-up domain name is longer than this length (or overridden by the
	// HOSTLEN ISUPPORT parameter), the server SHOULD opt to use the IP address instead,
	// so that the hostname is underneath this length.
	defaultHostLength = 63

	// defaultPrefixPadding defaults the estimated prefix padding length of a given
	// event. See also:
	//   [ ":" ( servername / ( nickname [ [ "!" user ] "@" host ] ) ) SPACE ]
	defaultPrefixPadding = 4
)

var (
	// DefaultMaxLineLength is the default maximum length for an event. 510 (+2 for line endings)
	// is used as a default as this is used by many older implementations.
	//
	// See also: RFC 2812
	//   IRC messages are always lines of characters terminated with a CR-LF
	//   (Carriage Return - Line Feed) pair, and these messages SHALL NOT
	//   exceed 512 characters in length, counting all characters including
	//   the trailing CR-LF.
	DefaultMaxLineLength = 510

	// DefaultMaxPrefixLength defines the default max ":nickname!user@host " length
	// that's used to calculate line splitting.
	DefaultMaxPrefixLength = defaultPrefixPadding + defaultNickLength + defaultUserLength + defaultHostLength
)

// cutCRFunc is used to trim CR characters from prefixes/messages.
func cutCRFunc(r rune) bool {
	return r == '\r' || r == '\n'
}

// ParseEvent takes a string and attempts to create a Event struct. Returns
// nil if the Event is invalid.
func ParseEvent(raw string) (e *Event) {
	// Ignore empty events.
	if raw = strings.TrimFunc(raw, cutCRFunc); len(raw) < 2 {
		return nil
	}

	var i, j int
	e = &Event{Timestamp: time.Now()}

	if raw[0] == prefixTag {
		// Tags end with a space.
		i = strings.IndexByte(raw, eventSpace)

		if i < 2 {
			return nil
		}

		e.Tags = ParseTags(raw[1:i])
		if rawServerTime, ok := e.Tags.Get("time"); ok {
			// Attempt to parse server-time. If we can't parse it, we just
			// fall back to the time we received the message (locally.)
			if stime, err := time.Parse(capServerTimeFormat, rawServerTime); err == nil {
				e.Timestamp = stime.Local()
			}
		}
		raw = raw[i+1:]
		i = 0
	}

	if raw != "" && raw[0] == messagePrefix {
		// Prefix ends with a space.
		i = strings.IndexByte(raw, eventSpace)

		// Prefix string must not be empty if the indicator is present.
		if i < 2 {
			return nil
		}

		e.Source = ParseSource(raw[1:i])

		// Skip space at the end of the prefix.
		i++
	}

	// Find end of command.
	j = i + strings.IndexByte(raw[i:], eventSpace)

	if j < i {
		// If there are no proceeding spaces, it's the only thing specified.
		e.Command = strings.ToUpper(raw[i:])
		return e
	}

	e.Command = strings.ToUpper(raw[i:j])

	// Skip the space after the command.
	j++

	// Check if and where the trailing text is within the incoming line.
	var lastIndex, trailerIndex int
	for {
		// We must loop through, as it's possible that the first message
		// prefix is not actually what we want. (e.g, colons are commonly
		// used within ISUPPORT to delegate things like CHANLIMIT or TARGMAX.)
		lastIndex = trailerIndex
		trailerIndex = strings.IndexByte(raw[j+lastIndex:], messagePrefix)

		if trailerIndex == -1 {
			// No trailing argument found, assume the rest is just params.
			e.Params = strings.Fields(raw[j:])
			return e
		}

		// This means we found a prefix that was proceeded by a space, and
		// it's good to assume this is the start of trailing text to the line.
		if raw[j+lastIndex+trailerIndex-1] == eventSpace {
			i = lastIndex + trailerIndex
			break
		}

		// Keep looping through until we either can't find any more prefixes,
		// or we find the one we want.
		trailerIndex += lastIndex + 1
	}

	// Set i to that of the substring we were using before, and where the
	// trailing prefix is.
	i = j + i

	// Check if we need to parse arguments. If so, take everything after the
	// command, and right before the trailing prefix, and cut it up.
	if i > j {
		e.Params = strings.Fields(raw[j : i-1])
	}

	e.Params = append(e.Params, raw[i+1:])

	return e
}

// Event represents an IRC protocol message, see RFC1459 section 2.3.1
//
//	<message>  :: [':' <prefix> <SPACE>] <command> <params> <crlf>
//	<prefix>   :: <servername> | <nick> ['!' <user>] ['@' <host>]
//	<command>  :: <letter>{<letter>} | <number> <number> <number>
//	<SPACE>    :: ' '{' '}
//	<params>   :: <SPACE> [':' <trailing> | <middle> <params>]
//	<middle>   :: <Any *non-empty* sequence of octets not including SPACE or NUL
//	               or CR or LF, the first of which may not be ':'>
//	<trailing> :: <Any, possibly empty, sequence of octets not including NUL or
//	               CR or LF>
//	<crlf>     :: CR LF
type Event struct {
	// Source is the origin of the event.
	Source *Source `json:"source"`
	// Tags are the IRCv3 style message tags for the given event. Only use
	// if network supported.
	Tags Tags `json:"tags"`
	// Timestamp is the time the event was received. This could optionally be
	// used for client-stored sent messages too. If the server supports the
	// "server-time" capability, this is synced to the UTC time that the server
	// specifies.
	Timestamp time.Time `json:"timestamp"`
	// Command that represents the event, e.g. JOIN, PRIVMSG, KILL.
	Command string `json:"command"`
	// Params (parameters/args) to the command. Commonly nickname, channel, etc.
	// The last item in the slice could potentially contain spaces (commonly
	// referred to as the "trailing" parameter).
	Params []string `json:"params"`
	// Sensitive should be true if the message is sensitive (e.g. and should
	// not be logged/shown in debugging output).
	Sensitive bool `json:"sensitive"`
	// If the event is an echo-message response.
	Echo bool `json:"echo"`
}

// Last returns the last parameter in Event.Params if it exists.
func (e *Event) Last() string {
	if len(e.Params) >= 1 {
		return e.Params[len(e.Params)-1]
	}
	return ""
}

// Copy makes a deep copy of a given event, for use with allowing untrusted
// functions/handlers edit the event without causing potential issues with
// other handlers.
func (e *Event) Copy() *Event {
	if e == nil {
		return nil
	}

	newEvent := &Event{
		Timestamp: e.Timestamp,
		Command:   e.Command,
		Sensitive: e.Sensitive,
		Echo:      e.Echo,
	}

	// Copy Source field, as it's a pointer and needs to be dereferenced.
	if e.Source != nil {
		newEvent.Source = e.Source.Copy()
	}

	// Copy Params in order to dereference as well.
	if e.Params != nil {
		newEvent.Params = make([]string, len(e.Params))
		copy(newEvent.Params, e.Params)
	}

	// Copy tags as necessary.
	if e.Tags != nil {
		newEvent.Tags = Tags{}
		for k, v := range e.Tags {
			newEvent.Tags[k] = v
		}
	}

	return newEvent
}

// Equals compares two Events for equality.
func (e *Event) Equals(ev *Event) bool {
	if e.Command != ev.Command || len(e.Params) != len(ev.Params) {
		return false
	}

	for i := 0; i < len(e.Params); i++ {
		if e.Params[i] != ev.Params[i] {
			return false
		}
	}

	if !e.Source.Equals(ev.Source) || !e.Tags.Equals(ev.Tags) {
		return false
	}

	return true
}

// split will split a potentially large event that is larger than what the server
// supports, into multiple events. split will ignore events that cannot be split, and
// if the event isn't longer than what the server supports, it will just return an array
// with 1 entry, the original event.
func (e *Event) split(maxLength int) []*Event {
	if len(e.Params) < 1 || (e.Command != PRIVMSG && e.Command != NOTICE) {
		return []*Event{e}
	}

	// Exclude source, even if it does exist, because the server will likely ignore the
	// sent source anyway.
	event := e.Copy()
	event.Source = nil

	if event.LenOpts(false) < maxLength {
		return []*Event{e}
	}

	results := []*Event{}

	// Will force the length check to include " :". This will allow us to get the length
	// of the commands and necessary prefixes.
	text := event.Last()
	event.Params[len(event.Params)-1] = ""
	cmdLen := event.LenOpts(false)

	var ok bool
	var ctcp *CTCPEvent
	if ok, ctcp = e.IsCTCP(); ok {
		if text == "" {
			return []*Event{e}
		}

		text = ctcp.Text

		// ctcpDelim's at start and end, and space between command and trailing text.
		maxLength -= len(ctcp.Command) + 4
	}

	// If the command itself is longer than the limit, there is a problem. PRIVMSG should
	// be 1->1 per RFC. Just return the original message and let it be the user of the
	// libraries problem.
	if cmdLen > maxLength {
		return []*Event{e}
	}

	// Split the text into correctly size segments, and make the necessary number of
	// events that duplicate the original event.
	for _, split := range splitMessage(text, maxLength-cmdLen) {
		if ctcp != nil {
			split = string(ctcpDelim) + ctcp.Command + string(eventSpace) + split + string(ctcpDelim)
		}
		clonedEvent := event.Copy()
		clonedEvent.Source = e.Source
		clonedEvent.Params[len(e.Params)-1] = split
		results = append(results, clonedEvent)
	}

	return results
}

// Len calculates the length of the string representation of event (including tags).
// Note that this will return the true length (even if longer than what IRC supports),
// which may be useful if you are trying to check and see if a message is too long, to
// trim it down yourself.
func (e *Event) Len() (length int) {
	return e.LenOpts(true)
}

// LenOpts calculates the length of the string representation of event (with a toggle
// for tags). Note that this will return the true length (even if longer than what IRC
// supports), which may be useful if you are trying to check and see if a message is
// too long, to trim it down yourself.
func (e *Event) LenOpts(includeTags bool) (length int) {
	if e.Tags != nil {
		// Include tags and trailing space.
		length = e.Tags.Len() + 1
	}
	if e.Source != nil {
		// Include prefix and trailing space.
		length += e.Source.Len() + 2
	}

	length += len(e.Command)

	if len(e.Params) > 0 {
		// Spaces before each param.
		length += len(e.Params)

		for i := 0; i < len(e.Params); i++ {
			length += len(e.Params[i])

			// If param contains a space or it's empty, it's trailing, so it should be
			// prefixed with a colon (:).
			if i == len(e.Params)-1 && (strings.Contains(e.Params[i], " ") || e.Params[i] == "" || strings.HasPrefix(e.Params[i], ":")) {
				length++
			}
		}
	}

	return
}

// Bytes returns a []byte representation of event. Strips all newlines and
// carriage returns.
func (e *Event) Bytes() []byte {
	buffer := new(bytes.Buffer)

	// Tags.
	if e.Tags != nil {
		e.Tags.writeTo(buffer)
	}

	// Event prefix.
	if e.Source != nil {
		buffer.WriteByte(messagePrefix)
		e.Source.writeTo(buffer)
		buffer.WriteByte(eventSpace)
	}

	// Command is required.
	buffer.WriteString(e.Command)

	// Space separated list of arguments.
	if len(e.Params) > 0 {
		for i := 0; i < len(e.Params); i++ {
			if i == len(e.Params)-1 && (strings.Contains(e.Params[i], " ") || e.Params[i] == "" || strings.HasPrefix(e.Params[i], ":")) {
				buffer.WriteString(string(eventSpace) + string(messagePrefix) + e.Params[i])
				continue
			}
			buffer.WriteString(string(eventSpace) + e.Params[i])
		}
	}

	// If we truncated in the middle of a utf8 character, we need to remove
	// the other (now invalid) bytes.
	out := bytes.ToValidUTF8(buffer.Bytes(), nil)

	// Strip newlines and carriage returns.
	for i := 0; i < len(out); i++ {
		if out[i] == '\n' || out[i] == '\r' {
			out = append(out[:i], out[i+1:]...)
			i-- // Decrease the index so we can pick up where we left off.
		}
	}

	return out
}

// String returns a string representation of this event. Strips all newlines
// and carriage returns.
func (e *Event) String() string {
	return string(e.Bytes())
}

// Pretty returns a prettified string of the event. If the event doesn't
// support prettification, ok is false. Pretty is not just useful to make
// an event prettier, but also to filter out events that most don't visually
// see in normal IRC clients. e.g. most clients don't show WHO queries.
func (e *Event) Pretty() (out string, ok bool) {
	if e.Sensitive || e.Echo {
		return "", false
	}

	if e.Command == ERROR {
		return fmt.Sprintf("[*] an error occurred: %s", e.Last()), true
	}

	if e.Source == nil {
		if e.Command != PRIVMSG && e.Command != NOTICE {
			return "", false
		}

		if len(e.Params) > 0 {
			return fmt.Sprintf("[>] writing %s", e.String()), true
		}

		return "", false
	}

	if e.Command == INITIALIZED {
		return fmt.Sprintf("[*] connection to %s initialized", e.Last()), true
	}

	if e.Command == CONNECTED {
		return fmt.Sprintf("[*] successfully connected to %s", e.Last()), true
	}

	if (e.Command == PRIVMSG || e.Command == NOTICE) && len(e.Params) > 0 {
		if ctcp := DecodeCTCP(e); ctcp != nil {
			if ctcp.Reply {
				return
			}

			if ctcp.Command == CTCP_ACTION {
				return fmt.Sprintf("[%s] **%s** %s", strings.Join(e.Params[0:len(e.Params)-1], ","), ctcp.Source.Name, ctcp.Text), true
			}

			return fmt.Sprintf("[*] CTCP query from %s: %s%s", ctcp.Source.Name, ctcp.Command, " "+ctcp.Text), true
		}

		var source string
		if e.Command == PRIVMSG {
			source = fmt.Sprintf("(%s)", e.Source.Name)
		} else { // NOTICE
			source = fmt.Sprintf("--%s--", e.Source.Name)
		}

		return fmt.Sprintf("[%s] %s %s", strings.Join(e.Params[0:len(e.Params)-1], ","), source, e.Last()), true
	}

	if e.Command == RPL_MOTD || e.Command == RPL_MOTDSTART ||
		e.Command == RPL_WELCOME || e.Command == RPL_YOURHOST ||
		e.Command == RPL_CREATED || e.Command == RPL_LUSERCLIENT {
		return "[*] " + e.Last(), true
	}

	if e.Command == JOIN && len(e.Params) > 0 {
		return fmt.Sprintf("[*] %s (%s) has joined %s", e.Source.Name, e.Source.Host, e.Params[0]), true
	}

	if e.Command == PART && len(e.Params) > 0 {
		return fmt.Sprintf("[*] %s (%s) has left %s (%s)", e.Source.Name, e.Source.Host, e.Params[0], e.Last()), true
	}

	if e.Command == QUIT {
		return fmt.Sprintf("[*] %s has quit (%s)", e.Source.Name, e.Last()), true
	}

	if e.Command == INVITE && len(e.Params) == 1 {
		return fmt.Sprintf("[*] %s invited to %s by %s", e.Params[0], e.Last(), e.Source.Name), true
	}

	if e.Command == KICK && len(e.Params) >= 2 {
		return fmt.Sprintf("[%s] *** %s has kicked %s: %s", e.Params[0], e.Source.Name, e.Params[1], e.Last()), true
	}

	if e.Command == NICK {
		return fmt.Sprintf("[*] %s is now known as %s", e.Source.Name, e.Last()), true
	}

	if e.Command == TOPIC && len(e.Params) >= 2 {
		return fmt.Sprintf("[%s] *** %s has set the topic to: %s", e.Params[0], e.Source.Name, e.Last()), true
	}

	if e.Command == RPL_TOPIC && len(e.Params) > 0 {
		if len(e.Params) >= 2 {
			return fmt.Sprintf("[*] topic for %s is: %s", e.Params[1], e.Last()), true
		}
		return fmt.Sprintf("[*] topic for %s is: %s", e.Params[0], e.Last()), true
	}

	if e.Command == MODE && len(e.Params) > 2 {
		return fmt.Sprintf("[%s] *** %s set modes: %s", e.Params[0], e.Source.Name, strings.Join(e.Params[1:], " ")), true
	}

	if e.Command == CAP_AWAY {
		if len(e.Params) > 0 {
			return fmt.Sprintf("[*] %s is now away: %s", e.Source.Name, e.Last()), true
		}

		return fmt.Sprintf("[*] %s is no longer away", e.Source.Name), true
	}

	if e.Command == CAP_CHGHOST && len(e.Params) == 2 {
		return fmt.Sprintf("[*] %s has changed their host to %s (was %s)", e.Source.Name, e.Params[1], e.Source.Host), true
	}

	if e.Command == CAP_ACCOUNT && len(e.Params) == 1 {
		if e.Params[0] == "*" {
			return fmt.Sprintf("[*] %s has become un-authenticated", e.Source.Name), true
		}

		return fmt.Sprintf("[*] %s has authenticated for account: %s", e.Source.Name, e.Params[0]), true
	}

	if e.Command == CAP && len(e.Params) >= 2 && e.Params[1] == CAP_ACK {
		return "[*] enabling capabilities: " + e.Last(), true
	}

	return "", false
}

// IsAction checks to see if the event is an ACTION (/me).
func (e *Event) IsAction() bool {
	if e.Command != PRIVMSG {
		return false
	}

	ok, ctcp := e.IsCTCP()
	return ok && ctcp.Command == CTCP_ACTION
}

// IsCTCP checks to see if the event is a CTCP event, and if so, returns the
// converted CTCP event.
func (e *Event) IsCTCP() (ok bool, ctcp *CTCPEvent) {
	ctcp = DecodeCTCP(e)
	return ctcp != nil, ctcp
}

// IsFromChannel checks to see if a message was from a channel (rather than
// a private message).
func (e *Event) IsFromChannel() bool {
	if e.Source == nil || (e.Command != PRIVMSG && e.Command != NOTICE) || len(e.Params) < 1 {
		return false
	}

	if !IsValidChannel(e.Params[0]) {
		return false
	}

	return true
}

// IsFromUser checks to see if a message was from a user (rather than a
// channel).
func (e *Event) IsFromUser() bool {
	if e.Source == nil || (e.Command != PRIVMSG && e.Command != NOTICE) || len(e.Params) < 1 {
		return false
	}

	if !IsValidNick(e.Params[0]) {
		return false
	}

	return true
}

// StripAction returns the stripped version of the action encoding from a
// PRIVMSG ACTION (/me).
func (e *Event) StripAction() string {
	if !e.IsAction() {
		return e.Last()
	}

	msg := e.Last()
	return msg[8 : len(msg)-1]
}

const (
	messagePrefix byte = ':' // Prefix or last argument.
	prefixIdent   byte = '!' // Username.
	prefixHost    byte = '@' // Hostname.
)

// Source represents the sender of an IRC event, see RFC1459 section 2.3.1.
// <servername> | <nick> [ '!' <user> ] [ '@' <host> ]
type Source struct {
	// Name is the nickname, server name, or service name, in its original
	// non-rfc1459 form.
	Name string `json:"name"`
	// Ident is commonly known as the "user".
	Ident string `json:"ident"`
	// Host is the hostname or IP address of the user/service. Is not accurate
	// due to how IRC servers can spoof hostnames.
	Host string `json:"host"`
}

// ID is the nickname, server name, or service name, in it's converted
// and comparable) form.
func (s *Source) ID() string {
	return ToRFC1459(s.Name)
}

// Equals compares two Sources for equality.
func (s *Source) Equals(ss *Source) bool {
	if s == nil && ss == nil {
		return true
	}
	if s != nil && ss == nil || s == nil && ss != nil {
		return false
	}
	if s.ID() != ss.ID() || s.Ident != ss.Ident || s.Host != ss.Host {
		return false
	}
	return true
}

// Copy returns a deep copy of Source.
func (s *Source) Copy() *Source {
	if s == nil {
		return nil
	}

	newSource := &Source{
		Name:  s.Name,
		Ident: s.Ident,
		Host:  s.Host,
	}

	return newSource
}

// ParseSource takes a string and attempts to create a Source struct.
func ParseSource(raw string) (src *Source) {
	src = new(Source)

	user := strings.IndexByte(raw, prefixIdent)
	host := strings.IndexByte(raw, prefixHost)

	switch {
	case user > 0 && host > user:
		src.Name = raw[:user]
		src.Ident = raw[user+1 : host]
		src.Host = raw[host+1:]
	case user > 0:
		src.Name = raw[:user]
		src.Ident = raw[user+1:]
	case host > 0:
		src.Name = raw[:host]
		src.Host = raw[host+1:]
	default:
		src.Name = raw
	}

	return src
}

// Len calculates the length of the string representation of prefix
func (s *Source) Len() (length int) {
	length = len(s.Name)
	if len(s.Ident) > 0 {
		length = 1 + length + len(s.Ident)
	}
	if len(s.Host) > 0 {
		length = 1 + length + len(s.Host)
	}

	return
}

// Bytes returns a []byte representation of source.
func (s *Source) Bytes() []byte {
	buffer := new(bytes.Buffer)
	s.writeTo(buffer)

	return buffer.Bytes()
}

// String returns a string representation of source.
func (s *Source) String() (out string) {
	out = s.Name
	if len(s.Ident) > 0 {
		out = out + string(prefixIdent) + s.Ident
	}
	if len(s.Host) > 0 {
		out = out + string(prefixHost) + s.Host
	}

	return
}

// IsHostmask returns true if source looks like a user hostmask.
func (s *Source) IsHostmask() bool {
	return len(s.Ident) > 0 && len(s.Host) > 0
}

// IsServer returns true if this source looks like a server name.
func (s *Source) IsServer() bool {
	return s.Ident == "" && s.Host == ""
}

// writeTo is an utility function to write the source to the bytes.Buffer
// in Event.String().
func (s *Source) writeTo(buffer *bytes.Buffer) {
	buffer.WriteString(s.Name)
	if len(s.Ident) > 0 {
		buffer.WriteByte(prefixIdent)
		buffer.WriteString(s.Ident)
	}
	if len(s.Host) > 0 {
		buffer.WriteByte(prefixHost)
		buffer.WriteString(s.Host)
	}
}