Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 28 additions & 2 deletions handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -132,11 +132,37 @@ func (h handler) matchRegexp(data string) bool {

func extractCommand(data string, entity models.MessageEntity) (string, bool) {
// Check the offset before subtracting, avoiding overflow in offset + length.
// A string never has more UTF-16 code units than bytes, so an entity that
// fails this check cannot fit in the text either.
if entity.Offset < 0 || entity.Offset > len(data) || entity.Length <= 1 || entity.Length > len(data)-entity.Offset {
return "", false
}
// Skipping the "/" character at the beginning of the command
return data[entity.Offset+1 : entity.Offset+entity.Length], true
// Telegram counts entity offsets and lengths in UTF-16 code units.
from, okFrom := utf16Index(data, entity.Offset)
to, okTo := utf16Index(data[from:], entity.Length)
if !okFrom || !okTo {
return "", false
}
// Skip the "/" character at the beginning of the command.
return data[from+1 : from+to], true
}

// utf16Index returns the byte index of the n-th UTF-16 code unit in s. It
// reports false when n is negative, falls inside a surrogate pair or is past
// the end of s. An invalid UTF-8 byte counts as one unit, as U+FFFD would.
func utf16Index(s string, n int) (int, bool) {
units := 0
for i, r := range s {
if units >= n {
return i, units == n
}
units++
if r > 0xFFFF {
// Outside the BMP, a rune takes a surrogate pair.
units++
}
}
return len(s), units == n
}

func (h handler) matchCommand(data string, entities []models.MessageEntity) bool {
Expand Down
42 changes: 42 additions & 0 deletions handlers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -834,6 +834,48 @@ func TestExtractCommand(t *testing.T) {
},
want: "",
},
{
name: "after Cyrillic text",
data: "привет /help",
entity: models.MessageEntity{
Type: models.MessageEntityTypeBotCommand,
Offset: 7,
Length: 5,
},
want: "help",
wantOK: true,
},
{
name: "after emoji outside the BMP",
data: "👋 /start now",
entity: models.MessageEntity{
Type: models.MessageEntityTypeBotCommand,
Offset: 3,
Length: 6,
},
want: "start",
wantOK: true,
},
{
name: "offset inside a surrogate pair",
data: "👋/start",
entity: models.MessageEntity{
Type: models.MessageEntityTypeBotCommand,
Offset: 1,
Length: 3,
},
want: "",
},
{
name: "length past end in UTF-16 units",
data: "你好 /start",
entity: models.MessageEntity{
Type: models.MessageEntityTypeBotCommand,
Offset: 3,
Length: 7,
},
want: "",
},
{
name: "length too small",
data: "/",
Expand Down
Loading