add bitrix support
This commit is contained in:
1 parent
747f8f2312
commit
5690cf58a9
62 files changed
+4098
-1053
No files matched your search
@@ -0,0 +1,476 @@
|
||||
package bitrix
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"net/http/cookiejar"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"whitelist-bypass/relay/common"
|
||||
)
|
||||
|
||||
const (
|
||||
slbBase = "https://slb.bitrix24.tech/v2/join"
|
||||
signalSDK = "js"
|
||||
signalVersion = "1.6.7"
|
||||
signalProtocol = "8"
|
||||
clientVersion = "1.0.0"
|
||||
clientPlatform = "web"
|
||||
callTypeInstant = 2
|
||||
roomTypeSmall = 1
|
||||
)
|
||||
|
||||
var (
|
||||
reConferenceID = regexp.MustCompile(`conferenceId:\s*'([^']+)'`)
|
||||
reChatID = regexp.MustCompile(`chatId:\s*'([^']+)'`)
|
||||
reAlias = regexp.MustCompile(`alias:\s*'([^']+)'`)
|
||||
reSessid = regexp.MustCompile(`bitrix_sessid["']?\s*[:=]\s*["']([a-f0-9]{8,})`)
|
||||
reUserID = regexp.MustCompile(`"USER_ID"\s*:\s*"?(\d+)`)
|
||||
)
|
||||
|
||||
type Client struct {
|
||||
HTTP *http.Client
|
||||
LogFn func(string, ...any)
|
||||
|
||||
portal string
|
||||
sessid string
|
||||
userAgent string
|
||||
instanceID string
|
||||
email string
|
||||
password string
|
||||
credsPath string
|
||||
}
|
||||
|
||||
type JoinResult struct {
|
||||
RoomData string `json:"roomData"`
|
||||
RoomID string `json:"roomId"`
|
||||
MediaServerURL string `json:"mediaServerUrl"`
|
||||
}
|
||||
|
||||
type conferenceParams struct {
|
||||
ConferenceID string
|
||||
ChatID string
|
||||
Alias string
|
||||
}
|
||||
|
||||
type callInfo struct {
|
||||
UUID string
|
||||
ChatID string
|
||||
CallToken string
|
||||
UserToken string
|
||||
Alias string
|
||||
GuestLink string
|
||||
}
|
||||
|
||||
type slbRequest struct {
|
||||
UserToken string `json:"userToken"`
|
||||
IsOneToOne bool `json:"isOneToOne"`
|
||||
ClientVersion string `json:"clientVersion"`
|
||||
ClientPlatform string `json:"clientPlatform"`
|
||||
CallType int `json:"callType"`
|
||||
RoomType int `json:"roomType"`
|
||||
InstanceID string `json:"instanceId"`
|
||||
CallToken string `json:"callToken"`
|
||||
Provider string `json:"provider"`
|
||||
IsVideo bool `json:"isVideo"`
|
||||
CallUUID string `json:"callUuid"`
|
||||
}
|
||||
|
||||
func NewClient(portal, userAgent string) (*Client, error) {
|
||||
jar, err := cookiejar.New(nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Client{
|
||||
HTTP: &http.Client{Jar: jar},
|
||||
LogFn: log.Printf,
|
||||
portal: strings.TrimRight(portal, "/"),
|
||||
userAgent: userAgent,
|
||||
instanceID: uuid.New().String(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func SignalURL(res JoinResult) string {
|
||||
q := url.Values{}
|
||||
q.Set("auto_subscribe", "1")
|
||||
q.Set("sdk", signalSDK)
|
||||
q.Set("version", signalVersion)
|
||||
q.Set("protocol", signalProtocol)
|
||||
q.Set("roomData", res.RoomData)
|
||||
q.Set("clientVersion", clientVersion)
|
||||
q.Set("clientPlatform", clientPlatform)
|
||||
return res.MediaServerURL + "?" + q.Encode()
|
||||
}
|
||||
|
||||
func (c *Client) JoinAsGuest(alias, displayName string) (JoinResult, error) {
|
||||
var res JoinResult
|
||||
conf, err := c.fetchConference(alias)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
userToken, err := c.registerGuest(conf, displayName)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
info, err := c.tryJoinCall(conf.ChatID)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
info.UserToken = userToken
|
||||
return c.slbJoin(info, false)
|
||||
}
|
||||
|
||||
func (c *Client) JoinAsHost(alias string) (JoinResult, error) {
|
||||
var res JoinResult
|
||||
conf, err := c.fetchConference(alias)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
c.LogFn("[host] conference chatId=%s conferenceId=%s", conf.ChatID, conf.ConferenceID)
|
||||
callToken, userToken, err := c.getCallToken(conf.ChatID)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
info := callInfo{
|
||||
UUID: uuid.New().String(),
|
||||
ChatID: conf.ChatID,
|
||||
CallToken: callToken,
|
||||
UserToken: userToken,
|
||||
}
|
||||
c.LogFn("[host] creating media room callUUID=%s callToken=%dB userToken=%dB", info.UUID, len(info.CallToken), len(info.UserToken))
|
||||
return c.slbJoin(info, true)
|
||||
}
|
||||
|
||||
func (c *Client) CreateAndJoin() (JoinResult, string, error) {
|
||||
var res JoinResult
|
||||
info, err := c.createRoom()
|
||||
if err != nil {
|
||||
return res, "", err
|
||||
}
|
||||
guestLink := info.GuestLink
|
||||
if guestLink == "" {
|
||||
guestLink, err = c.getGuestLink(info.ChatID)
|
||||
if err != nil {
|
||||
return res, "", err
|
||||
}
|
||||
}
|
||||
if info.CallToken == "" {
|
||||
callToken, userToken, err := c.getCallToken(info.ChatID)
|
||||
if err != nil {
|
||||
return res, "", err
|
||||
}
|
||||
info.CallToken = callToken
|
||||
if info.UserToken == "" {
|
||||
info.UserToken = userToken
|
||||
}
|
||||
}
|
||||
res, err = c.slbJoin(info, true)
|
||||
if err != nil {
|
||||
return res, "", err
|
||||
}
|
||||
return res, guestLink, nil
|
||||
}
|
||||
|
||||
func (c *Client) resetJar() error {
|
||||
jar, err := cookiejar.New(nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
c.HTTP.Jar = jar
|
||||
c.sessid = ""
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Client) do(method, endpoint, contentType string, body io.Reader) ([]byte, int, error) {
|
||||
req, err := http.NewRequest(method, endpoint, body)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
req.Header.Set("User-Agent", c.userAgent)
|
||||
req.Header.Set("Accept", "application/json, text/plain, */*")
|
||||
if c.portal != "" {
|
||||
req.Header.Set("Origin", c.portal)
|
||||
req.Header.Set("Referer", c.portal+"/")
|
||||
}
|
||||
if contentType != "" {
|
||||
req.Header.Set("Content-Type", contentType)
|
||||
}
|
||||
resp, err := c.HTTP.Do(req)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
data, err := io.ReadAll(resp.Body)
|
||||
return data, resp.StatusCode, err
|
||||
}
|
||||
|
||||
func (c *Client) restForm(action string, form url.Values) ([]byte, int, error) {
|
||||
endpoint := c.portal + "/rest/" + action + ".json"
|
||||
return c.do("POST", endpoint, "application/x-www-form-urlencoded", strings.NewReader(form.Encode()))
|
||||
}
|
||||
|
||||
func (c *Client) ajaxAction(action string, form url.Values) ([]byte, int, error) {
|
||||
endpoint := c.portal + "/bitrix/services/main/ajax.php?action=" + action
|
||||
if c.sessid != "" {
|
||||
endpoint += "&sessid=" + url.QueryEscape(c.sessid)
|
||||
form.Set("sessid", c.sessid)
|
||||
}
|
||||
return c.do("POST", endpoint, "application/x-www-form-urlencoded", strings.NewReader(form.Encode()))
|
||||
}
|
||||
|
||||
func (c *Client) fetchConference(alias string) (conferenceParams, error) {
|
||||
var p conferenceParams
|
||||
body, status, err := c.do("GET", c.portal+"/video/"+alias, "", nil)
|
||||
if err != nil {
|
||||
return p, err
|
||||
}
|
||||
if status != 200 {
|
||||
return p, fmt.Errorf("fetch conference page: status %d", status)
|
||||
}
|
||||
page := string(body)
|
||||
if m := reConferenceID.FindStringSubmatch(page); m != nil {
|
||||
p.ConferenceID = m[1]
|
||||
}
|
||||
if m := reChatID.FindStringSubmatch(page); m != nil {
|
||||
p.ChatID = m[1]
|
||||
}
|
||||
if m := reAlias.FindStringSubmatch(page); m != nil {
|
||||
p.Alias = m[1]
|
||||
} else {
|
||||
p.Alias = alias
|
||||
}
|
||||
if m := reSessid.FindStringSubmatch(page); m != nil {
|
||||
c.sessid = m[1]
|
||||
}
|
||||
if p.ConferenceID == "" || p.ChatID == "" {
|
||||
return p, fmt.Errorf("conference params not found in page (conferenceId=%q chatId=%q)", p.ConferenceID, p.ChatID)
|
||||
}
|
||||
return p, nil
|
||||
}
|
||||
|
||||
func (c *Client) registerGuest(p conferenceParams, displayName string) (userToken string, err error) {
|
||||
form := url.Values{}
|
||||
form.Set("call_auth_id", "guest")
|
||||
form.Set("videoconf_id", p.ConferenceID)
|
||||
form.Set("call_chat_id", p.ChatID)
|
||||
form.Set("alias", p.Alias)
|
||||
form.Set("user_hash", "")
|
||||
if displayName != "" {
|
||||
form.Set("name", displayName)
|
||||
}
|
||||
body, status, err := c.restForm("call.user.register", form)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
var out struct {
|
||||
Result struct {
|
||||
UserToken string `json:"userToken"`
|
||||
} `json:"result"`
|
||||
Error string `json:"error"`
|
||||
ErrorDescription string `json:"error_description"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &out); err != nil {
|
||||
return "", fmt.Errorf("register guest: %w (status %d, body %s)", err, status, common.BodySnippet(body))
|
||||
}
|
||||
if out.Result.UserToken == "" {
|
||||
return "", fmt.Errorf("register guest: no userToken (status %d, err %s %s)", status, out.Error, out.ErrorDescription)
|
||||
}
|
||||
return out.Result.UserToken, nil
|
||||
}
|
||||
|
||||
func (c *Client) tryJoinCall(chatID string) (callInfo, error) {
|
||||
var info callInfo
|
||||
form := url.Values{}
|
||||
form.Set("entityType", "chat")
|
||||
form.Set("entityId", "chat"+chatID)
|
||||
form.Set("provider", "Bitrix")
|
||||
form.Set("callType", fmt.Sprintf("%d", callTypeInstant))
|
||||
body, status, err := c.withRelogin(func() ([]byte, int, error) {
|
||||
return c.ajaxAction("call.Call.tryJoinCall", form)
|
||||
})
|
||||
if err != nil {
|
||||
return info, err
|
||||
}
|
||||
var out struct {
|
||||
Status string `json:"status"`
|
||||
Data struct {
|
||||
Success bool `json:"success"`
|
||||
Call struct {
|
||||
UUID string `json:"UUID"`
|
||||
ChatID json.Number `json:"CHAT_ID"`
|
||||
} `json:"call"`
|
||||
CallToken string `json:"callToken"`
|
||||
} `json:"data"`
|
||||
Errors []struct {
|
||||
Message string `json:"message"`
|
||||
Code string `json:"code"`
|
||||
} `json:"errors"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &out); err != nil {
|
||||
return info, fmt.Errorf("tryJoinCall: %w (status %d, body %s)", err, status, common.BodySnippet(body))
|
||||
}
|
||||
if out.Status == "success" && !out.Data.Success {
|
||||
return info, fmt.Errorf("tryJoinCall: no active call at chat%s, organizer not in the room", chatID)
|
||||
}
|
||||
if out.Status != "success" || out.Data.Call.UUID == "" {
|
||||
return info, fmt.Errorf("tryJoinCall failed (status %d, %s, errors %+v, body %s)", status, out.Status, out.Errors, common.BodySnippet(body))
|
||||
}
|
||||
info.UUID = out.Data.Call.UUID
|
||||
info.ChatID = out.Data.Call.ChatID.String()
|
||||
info.CallToken = out.Data.CallToken
|
||||
return info, nil
|
||||
}
|
||||
|
||||
func (c *Client) slbJoin(info callInfo, mustCreate bool) (JoinResult, error) {
|
||||
var res JoinResult
|
||||
reqBody := slbRequest{
|
||||
UserToken: info.UserToken,
|
||||
IsOneToOne: false,
|
||||
ClientVersion: clientVersion,
|
||||
ClientPlatform: clientPlatform,
|
||||
CallType: callTypeInstant,
|
||||
RoomType: roomTypeSmall,
|
||||
InstanceID: c.instanceID,
|
||||
CallToken: info.CallToken,
|
||||
Provider: "Bitrix",
|
||||
IsVideo: true,
|
||||
CallUUID: info.UUID,
|
||||
}
|
||||
payload, _ := json.Marshal(reqBody)
|
||||
endpoint := slbBase + "?mustCreate=" + strconv.FormatBool(mustCreate)
|
||||
body, status, err := c.do("POST", endpoint, "text/plain;charset=UTF-8", strings.NewReader(string(payload)))
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
var out struct {
|
||||
Result JoinResult `json:"result"`
|
||||
Error string `json:"error"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &out); err != nil {
|
||||
return res, fmt.Errorf("slb join: %w (status %d, body %s)", err, status, common.BodySnippet(body))
|
||||
}
|
||||
if out.Result.MediaServerURL == "" || out.Result.RoomData == "" {
|
||||
return res, fmt.Errorf("slb join: missing roomData/mediaServerUrl (status %d, err %s)", status, out.Error)
|
||||
}
|
||||
return out.Result, nil
|
||||
}
|
||||
|
||||
func (c *Client) currentUserID() (string, error) {
|
||||
body, status, err := c.do("GET", c.portal+"/online/", "", nil)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if m := reUserID.FindSubmatch(body); m != nil && string(m[1]) != "0" {
|
||||
return string(m[1]), nil
|
||||
}
|
||||
return "", fmt.Errorf("current user id not found (status %d)", status)
|
||||
}
|
||||
|
||||
func (c *Client) createRoom() (callInfo, error) {
|
||||
var info callInfo
|
||||
uid, err := c.currentUserID()
|
||||
if err != nil {
|
||||
return info, fmt.Errorf("createRoom: %w", err)
|
||||
}
|
||||
form := url.Values{}
|
||||
form.Set("fields[entityType]", "VIDEOCONF")
|
||||
form.Set("fields[title]", "")
|
||||
form.Set("fields[memberEntities][0][0]", "user")
|
||||
form.Set("fields[memberEntities][0][1]", uid)
|
||||
form.Set("fields[ownerId]", uid)
|
||||
form.Set("fields[description]", "")
|
||||
form.Set("fields[manageUsersAdd]", "member")
|
||||
form.Set("fields[manageUsersDelete]", "manager")
|
||||
form.Set("fields[manageUi]", "member")
|
||||
form.Set("fields[manageMessages]", "member")
|
||||
form.Set("fields[conferencePassword]", "")
|
||||
body, status, err := c.withRelogin(func() ([]byte, int, error) {
|
||||
return c.ajaxAction("im.v2.Chat.add", form)
|
||||
})
|
||||
if err != nil {
|
||||
return info, err
|
||||
}
|
||||
var out struct {
|
||||
Status string `json:"status"`
|
||||
Data struct {
|
||||
ChatID json.Number `json:"chatId"`
|
||||
Alias string `json:"alias"`
|
||||
Link string `json:"link"`
|
||||
} `json:"data"`
|
||||
Errors []struct {
|
||||
Code json.Number `json:"code"`
|
||||
Message string `json:"message"`
|
||||
} `json:"errors"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &out); err != nil {
|
||||
return info, fmt.Errorf("createRoom: %w (status %d, body %s)", err, status, common.BodySnippet(body))
|
||||
}
|
||||
info.ChatID = out.Data.ChatID.String()
|
||||
info.Alias = out.Data.Alias
|
||||
info.GuestLink = out.Data.Link
|
||||
if info.ChatID == "" {
|
||||
errMsg := ""
|
||||
if len(out.Errors) > 0 {
|
||||
errMsg = out.Errors[0].Code.String() + " " + out.Errors[0].Message
|
||||
}
|
||||
return info, fmt.Errorf("createRoom: no chatId (status %d, status=%q err=%q, body %s)", status, out.Status, errMsg, common.BodySnippet(body))
|
||||
}
|
||||
c.LogFn("[create] videoconf chatId=%s alias=%s", info.ChatID, info.Alias)
|
||||
return info, nil
|
||||
}
|
||||
|
||||
func (c *Client) getGuestLink(chatID string) (string, error) {
|
||||
form := url.Values{}
|
||||
form.Set("chatId", chatID)
|
||||
body, status, err := c.withRelogin(func() ([]byte, int, error) {
|
||||
return c.ajaxAction("call.Call.getGuestLink", form)
|
||||
})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
var out struct {
|
||||
Status string `json:"status"`
|
||||
Data struct {
|
||||
GuestLink string `json:"guestLink"`
|
||||
} `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &out); err != nil {
|
||||
return "", fmt.Errorf("getGuestLink: %w (status %d, body %s)", err, status, common.BodySnippet(body))
|
||||
}
|
||||
if out.Data.GuestLink == "" {
|
||||
return "", fmt.Errorf("getGuestLink: empty (status %d)", status)
|
||||
}
|
||||
return out.Data.GuestLink, nil
|
||||
}
|
||||
|
||||
func (c *Client) getCallToken(chatID string) (callToken, userToken string, err error) {
|
||||
form := url.Values{}
|
||||
form.Set("chatId", chatID)
|
||||
body, status, err := c.withRelogin(func() ([]byte, int, error) {
|
||||
return c.ajaxAction("call.Call.getCallToken", form)
|
||||
})
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
var out struct {
|
||||
Status string `json:"status"`
|
||||
Data struct {
|
||||
CallToken string `json:"callToken"`
|
||||
UserToken string `json:"userToken"`
|
||||
} `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &out); err != nil {
|
||||
return "", "", fmt.Errorf("getCallToken: %w (status %d, body %s)", err, status, common.BodySnippet(body))
|
||||
}
|
||||
if out.Data.CallToken == "" {
|
||||
return "", "", fmt.Errorf("getCallToken: empty (status %d, body %s)", status, common.BodySnippet(body))
|
||||
}
|
||||
return out.Data.CallToken, out.Data.UserToken, nil
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
package bitrix
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"whitelist-bypass/relay/common"
|
||||
)
|
||||
|
||||
const authNetBase = "https://auth2.bitrix24.net"
|
||||
|
||||
var (
|
||||
reFlowCfg = regexp.MustCompile(`b24network\.security\.flowtoken"[^>]*>(\{[^<]*\})</script>`)
|
||||
reJunk = regexp.MustCompile(`[!#$%@~]`)
|
||||
reJSRedirect = regexp.MustCompile(`window\.location\.href\s*=\s*['"]([^'"]+)['"]`)
|
||||
)
|
||||
|
||||
type Credentials struct {
|
||||
Email string `json:"email"`
|
||||
Password string `json:"password"`
|
||||
Portal string `json:"portal"`
|
||||
Cookies []CookieEntry `json:"cookies,omitempty"`
|
||||
}
|
||||
|
||||
func LoadCredentials(path string) (Credentials, error) {
|
||||
var c Credentials
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return c, err
|
||||
}
|
||||
if err := json.Unmarshal(data, &c); err != nil {
|
||||
return c, fmt.Errorf("parse credentials %s: %w", path, err)
|
||||
}
|
||||
c.Email = strings.TrimSpace(c.Email)
|
||||
c.Portal = strings.TrimRight(strings.TrimSpace(c.Portal), "/")
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func (c *Client) loginWithPassword(email, password string) error {
|
||||
if email == "" || password == "" {
|
||||
return fmt.Errorf("login: no email/password")
|
||||
}
|
||||
if err := c.resetJar(); err != nil {
|
||||
return err
|
||||
}
|
||||
flowToken, sessid, currentURI, err := c.bootstrapLogin()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
c.LogFn("[auth] bootstrap: flowToken=%dB sessid=%v authURL=%v", len(flowToken), sessid != "", strings.Contains(currentURI, "auth2.bitrix24.net"))
|
||||
if err := c.authCheckLogin(flowToken, email, sessid, currentURI); err != nil {
|
||||
return err
|
||||
}
|
||||
c.LogFn("[auth] checkLogin OK")
|
||||
if err := c.authCheck(flowToken, email, password, sessid); err != nil {
|
||||
return err
|
||||
}
|
||||
c.LogFn("[auth] check OK")
|
||||
c.email = email
|
||||
c.password = password
|
||||
if err := c.completeOAuth(); err != nil {
|
||||
return err
|
||||
}
|
||||
if c.credsPath != "" {
|
||||
if err := c.saveSession(); err != nil {
|
||||
return fmt.Errorf("login ok but save session failed: %w", err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Client) bootstrapLogin() (flowToken, sessid, currentURI string, err error) {
|
||||
req, err := http.NewRequest("GET", c.portal+"/", nil)
|
||||
if err != nil {
|
||||
return "", "", "", err
|
||||
}
|
||||
req.Header.Set("User-Agent", c.userAgent)
|
||||
req.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
|
||||
req.Header.Set("Accept-Language", "ru,en;q=0.9")
|
||||
req.Header.Set("Upgrade-Insecure-Requests", "1")
|
||||
resp, err := c.HTTP.Do(req)
|
||||
if err != nil {
|
||||
return "", "", "", err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
page := string(body)
|
||||
currentURI = resp.Request.URL.String()
|
||||
if !strings.Contains(currentURI, "auth2.bitrix24.net") {
|
||||
return "", "", "", fmt.Errorf("portal did not redirect to auth2 (landed on %s)", currentURI)
|
||||
}
|
||||
flowToken = computeFlowToken(page)
|
||||
if m := reSessid.FindStringSubmatch(page); m != nil {
|
||||
sessid = m[1]
|
||||
}
|
||||
return flowToken, sessid, currentURI, nil
|
||||
}
|
||||
|
||||
func computeFlowToken(page string) string {
|
||||
m := reFlowCfg.FindStringSubmatch(page)
|
||||
if m == nil {
|
||||
return ""
|
||||
}
|
||||
var cfg struct {
|
||||
FTV string `json:"ftv"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(m[1]), &cfg); err != nil {
|
||||
return ""
|
||||
}
|
||||
return reJunk.ReplaceAllString(cfg.FTV, "")
|
||||
}
|
||||
|
||||
func (c *Client) authCheckLogin(flowToken, login, sessid, currentURI string) error {
|
||||
form := url.Values{}
|
||||
form.Set("flow-token-unique-id", flowToken)
|
||||
form.Set("login", login)
|
||||
form.Set("currentUri", currentURI)
|
||||
form.Set("checkSocserv", "Y")
|
||||
body, status, err := c.authDo("b24network.authorize.checkLogin", form, sessid)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var out struct {
|
||||
Status string `json:"status"`
|
||||
Data []struct {
|
||||
HasAccess bool `json:"HAS_ACCESS"`
|
||||
Captcha interface{} `json:"CAPTCHA"`
|
||||
} `json:"data"`
|
||||
Errors []struct {
|
||||
Message string `json:"message"`
|
||||
} `json:"errors"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &out); err != nil {
|
||||
return fmt.Errorf("checkLogin: %w (status %d, body %s)", err, status, common.BodySnippet(body))
|
||||
}
|
||||
if out.Status != "success" || len(out.Data) == 0 {
|
||||
return fmt.Errorf("login rejected: checkLogin (status %d, errors %+v, body %s)", status, out.Errors, common.BodySnippet(body))
|
||||
}
|
||||
if out.Data[0].Captcha != nil {
|
||||
return fmt.Errorf("login rejected: captcha required at login step")
|
||||
}
|
||||
if !out.Data[0].HasAccess {
|
||||
return fmt.Errorf("login rejected: account has no access")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Client) authCheck(flowToken, login, password, sessid string) error {
|
||||
form := url.Values{}
|
||||
form.Set("flow-token-unique-id", flowToken)
|
||||
form.Set("login", login)
|
||||
form.Set("password", password)
|
||||
form.Set("remember", "Y")
|
||||
body, status, err := c.authDo("b24network.authorize.check", form, sessid)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var out struct {
|
||||
Status string `json:"status"`
|
||||
Errors []struct {
|
||||
Message string `json:"message"`
|
||||
Code string `json:"code"`
|
||||
} `json:"errors"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &out); err != nil {
|
||||
return fmt.Errorf("check: %w (status %d, body %s)", err, status, common.BodySnippet(body))
|
||||
}
|
||||
if out.Status != "success" || len(out.Errors) > 0 {
|
||||
return fmt.Errorf("login rejected: password check (status %d, errors %+v, body %s)", status, out.Errors, common.BodySnippet(body))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Client) authDo(action string, form url.Values, sessid string) ([]byte, int, error) {
|
||||
endpoint := authNetBase + "/bitrix/services/main/ajax.php?action=" + action
|
||||
req, err := http.NewRequest("POST", endpoint, strings.NewReader(form.Encode()))
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
req.Header.Set("User-Agent", c.userAgent)
|
||||
req.Header.Set("Accept", "application/json, text/plain, */*")
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
|
||||
req.Header.Set("Origin", authNetBase)
|
||||
req.Header.Set("Referer", authNetBase+"/authorization/")
|
||||
req.Header.Set("X-Requested-With", "XMLHttpRequest")
|
||||
if sessid != "" {
|
||||
req.Header.Set("X-Bitrix-Csrf-Token", sessid)
|
||||
}
|
||||
resp, err := c.HTTP.Do(req)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
return body, resp.StatusCode, err
|
||||
}
|
||||
|
||||
func (c *Client) getPage(target string) (body, final string, err error) {
|
||||
req, err := http.NewRequest("GET", target, nil)
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
req.Header.Set("User-Agent", c.userAgent)
|
||||
req.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
|
||||
req.Header.Set("Accept-Language", "ru,en;q=0.9")
|
||||
resp, err := c.HTTP.Do(req)
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
raw, _ := io.ReadAll(resp.Body)
|
||||
return string(raw), resp.Request.URL.String(), nil
|
||||
}
|
||||
|
||||
func (c *Client) completeOAuth() error {
|
||||
target := c.portal + "/"
|
||||
for hop := 0; hop < 8; hop++ {
|
||||
body, final, err := c.getPage(target)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
c.LogFn("[auth] oauth hop %d: final=%s len=%d", hop, final, len(body))
|
||||
if next := reJSRedirect.FindStringSubmatch(body); next != nil {
|
||||
target = next[1]
|
||||
continue
|
||||
}
|
||||
if strings.HasPrefix(final, c.portal) {
|
||||
if m := reSessid.FindStringSubmatch(body); m != nil {
|
||||
c.sessid = m[1]
|
||||
return nil
|
||||
}
|
||||
}
|
||||
target = c.portal + "/"
|
||||
body, _, err = c.getPage(target)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if m := reSessid.FindStringSubmatch(body); m != nil {
|
||||
c.sessid = m[1]
|
||||
}
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("oauth handoff did not converge")
|
||||
}
|
||||
@@ -0,0 +1,314 @@
|
||||
package bitrix
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/pion/rtp/codecs"
|
||||
"github.com/pion/webrtc/v4"
|
||||
"whitelist-bypass/relay/common"
|
||||
"whitelist-bypass/relay/livekit"
|
||||
"whitelist-bypass/relay/tunnel"
|
||||
)
|
||||
|
||||
const (
|
||||
TunnelModeAuto = ""
|
||||
TunnelModeVideo = "video"
|
||||
TunnelModeDC = "dc"
|
||||
)
|
||||
|
||||
type MediaParams struct {
|
||||
Signal *Signal
|
||||
Alias string
|
||||
Mode string
|
||||
FPS int
|
||||
Batch int
|
||||
Reliable bool
|
||||
LogFn func(string, ...any)
|
||||
}
|
||||
|
||||
type MediaSession struct {
|
||||
p MediaParams
|
||||
obf *tunnel.TunnelObfuscator
|
||||
sendTrack *webrtc.TrackLocalStaticSample
|
||||
vp8tun *tunnel.VP8DataTunnel
|
||||
|
||||
mu sync.Mutex
|
||||
subReliableDC *webrtc.DataChannel
|
||||
pubDCHooked bool
|
||||
dcStarted bool
|
||||
tunFired bool
|
||||
|
||||
configAcked chan struct{}
|
||||
configAckedOnce sync.Once
|
||||
stopCh chan struct{}
|
||||
|
||||
OnConnected func(tunnel.DataTunnel)
|
||||
}
|
||||
|
||||
func NewMediaSession(p MediaParams) (*MediaSession, error) {
|
||||
if p.LogFn == nil {
|
||||
p.LogFn = log.Printf
|
||||
}
|
||||
obf, err := tunnel.NewTunnelObfuscator(tunnel.DeriveSecretFromJoinLink(p.Alias))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
track, err := webrtc.NewTrackLocalStaticSample(
|
||||
webrtc.RTPCodecCapability{MimeType: webrtc.MimeTypeVP8, ClockRate: 90000},
|
||||
"tunnel", fmt.Sprintf("bitrix-tunnel-%08x", obf.LocalEpoch()))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
s := &MediaSession{
|
||||
p: p,
|
||||
obf: obf,
|
||||
sendTrack: track,
|
||||
vp8tun: tunnel.NewVP8DataTunnel(track, obf, p.LogFn),
|
||||
configAcked: make(chan struct{}),
|
||||
stopCh: make(chan struct{}),
|
||||
}
|
||||
p.Signal.SetOnTrack(func(remote *webrtc.TrackRemote, _ *webrtc.RTPReceiver) {
|
||||
if remote.Codec().MimeType == webrtc.MimeTypeVP8 {
|
||||
go s.readVP8Track(remote)
|
||||
} else {
|
||||
go tunnel.DrainTrack(remote)
|
||||
}
|
||||
})
|
||||
p.Signal.SetOnDataChannel(func(dc *webrtc.DataChannel) {
|
||||
if dc.Label() != "_reliable" {
|
||||
return
|
||||
}
|
||||
s.mu.Lock()
|
||||
s.subReliableDC = dc
|
||||
s.mu.Unlock()
|
||||
dc.OnOpen(func() {
|
||||
s.p.LogFn("[bx] sub _reliable DC open")
|
||||
s.maybeStartDCTunnel()
|
||||
})
|
||||
})
|
||||
return s, nil
|
||||
}
|
||||
|
||||
func (s *MediaSession) MarkConfigAcked() {
|
||||
s.configAckedOnce.Do(func() { close(s.configAcked) })
|
||||
}
|
||||
|
||||
func (s *MediaSession) Stop() {
|
||||
select {
|
||||
case <-s.stopCh:
|
||||
default:
|
||||
close(s.stopCh)
|
||||
}
|
||||
s.vp8tun.Stop()
|
||||
}
|
||||
|
||||
func (s *MediaSession) Start() error {
|
||||
sender, err := s.p.Signal.PublishVP8(s.sendTrack, "tunnel")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
go tunnel.DrainSenderRTCP(sender)
|
||||
s.vp8tun.Start(s.p.FPS, s.p.Batch)
|
||||
s.p.LogFn("[bx] vp8 tunnel started fps=%d batch=%d", s.p.FPS, s.p.Batch)
|
||||
s.hookPubDC()
|
||||
s.startVP8Role()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *MediaSession) hookPubDC() {
|
||||
dc := s.p.Signal.PubReliableDC()
|
||||
if dc == nil {
|
||||
return
|
||||
}
|
||||
s.mu.Lock()
|
||||
if s.pubDCHooked {
|
||||
s.mu.Unlock()
|
||||
return
|
||||
}
|
||||
s.pubDCHooked = true
|
||||
s.mu.Unlock()
|
||||
dc.OnOpen(func() {
|
||||
s.p.LogFn("[bx] pub _reliable DC open")
|
||||
s.maybeStartDCTunnel()
|
||||
})
|
||||
if dc.ReadyState() == webrtc.DataChannelStateOpen {
|
||||
s.maybeStartDCTunnel()
|
||||
}
|
||||
}
|
||||
|
||||
func (s *MediaSession) startVP8Role() {
|
||||
var active tunnel.DataTunnel = s.vp8tun
|
||||
if s.p.Mode == TunnelModeVideo && s.p.Reliable {
|
||||
active = s.wrapReliable(s.vp8tun)
|
||||
}
|
||||
switch s.p.Mode {
|
||||
case TunnelModeVideo:
|
||||
go s.configPingPong(active)
|
||||
s.fireOnConnected(active)
|
||||
case TunnelModeAuto:
|
||||
s.vp8tun.SetOnData(func(payload []byte) { s.activate(s.vp8tun, payload) })
|
||||
}
|
||||
}
|
||||
|
||||
func (s *MediaSession) maybeStartDCTunnel() {
|
||||
if s.p.Mode == TunnelModeVideo {
|
||||
return
|
||||
}
|
||||
s.mu.Lock()
|
||||
subDC := s.subReliableDC
|
||||
s.mu.Unlock()
|
||||
pubDC := s.p.Signal.PubReliableDC()
|
||||
if pubDC == nil || subDC == nil {
|
||||
return
|
||||
}
|
||||
if pubDC.ReadyState() != webrtc.DataChannelStateOpen || subDC.ReadyState() != webrtc.DataChannelStateOpen {
|
||||
return
|
||||
}
|
||||
s.mu.Lock()
|
||||
if s.dcStarted {
|
||||
s.mu.Unlock()
|
||||
return
|
||||
}
|
||||
s.dcStarted = true
|
||||
s.mu.Unlock()
|
||||
|
||||
subRaw, err := subDC.Detach()
|
||||
if err != nil {
|
||||
s.p.LogFn("[bx] detach sub _reliable: %v", err)
|
||||
return
|
||||
}
|
||||
pubRaw, err := pubDC.Detach()
|
||||
if err != nil {
|
||||
s.p.LogFn("[bx] detach pub _reliable: %v", err)
|
||||
return
|
||||
}
|
||||
readWrapped := livekit.NewDataPacketWrapper(subRaw, livekit.DataPacketKindReliable)
|
||||
writeWrapped := livekit.NewDataPacketWrapper(pubRaw, livekit.DataPacketKindReliable)
|
||||
dctun := tunnel.NewChunkedDCTunnelFromRaw(readWrapped, writeWrapped, s.obf, common.DCBufSize, s.p.LogFn)
|
||||
s.p.LogFn("[bx] dc tunnel ready (pub+sub _reliable)")
|
||||
|
||||
switch s.p.Mode {
|
||||
case TunnelModeDC:
|
||||
s.fireOnConnected(dctun)
|
||||
case TunnelModeAuto:
|
||||
dctun.SetOnData(func(payload []byte) { s.activate(dctun, payload) })
|
||||
}
|
||||
}
|
||||
|
||||
func (s *MediaSession) configPingPong(tun tunnel.DataTunnel) {
|
||||
tun.SendData(tunnel.EncodeVP8Config(s.vp8tun.FPS(), s.vp8tun.Batch(), 1))
|
||||
ticker := time.NewTicker(3 * time.Second)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-s.configAcked:
|
||||
return
|
||||
case <-s.stopCh:
|
||||
return
|
||||
case <-ticker.C:
|
||||
s.p.LogFn("[bx] resending vp8 config (no ack yet)")
|
||||
tun.SendData(tunnel.EncodeVP8Config(s.vp8tun.FPS(), s.vp8tun.Batch(), 1))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *MediaSession) fireOnConnected(tun tunnel.DataTunnel) {
|
||||
s.mu.Lock()
|
||||
if s.tunFired {
|
||||
s.mu.Unlock()
|
||||
return
|
||||
}
|
||||
s.tunFired = true
|
||||
s.mu.Unlock()
|
||||
if s.OnConnected != nil {
|
||||
s.OnConnected(tun)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *MediaSession) activate(tun tunnel.DataTunnel, payload []byte) {
|
||||
s.mu.Lock()
|
||||
if s.tunFired {
|
||||
s.mu.Unlock()
|
||||
return
|
||||
}
|
||||
s.tunFired = true
|
||||
s.mu.Unlock()
|
||||
|
||||
var delivered tunnel.DataTunnel = tun
|
||||
useKCP := false
|
||||
if v, ok := tun.(*tunnel.VP8DataTunnel); ok && !tunnel.LooksLikeRelayFrame(payload) {
|
||||
delivered = s.wrapReliable(v)
|
||||
useKCP = true
|
||||
}
|
||||
s.p.LogFn("[bx] auto-detected active tunnel: %T", delivered)
|
||||
if s.OnConnected != nil {
|
||||
s.OnConnected(delivered)
|
||||
}
|
||||
switch v := tun.(type) {
|
||||
case *tunnel.DCTunnel:
|
||||
if fwd := v.OnData(); fwd != nil {
|
||||
fwd(payload)
|
||||
}
|
||||
case *tunnel.VP8DataTunnel:
|
||||
if useKCP {
|
||||
if k, ok := delivered.(*tunnel.MultiTrackKCPTunnel); ok {
|
||||
k.InjectSegment(payload)
|
||||
}
|
||||
} else if v.OnData != nil {
|
||||
v.OnData(payload)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *MediaSession) wrapReliable(vp8 *tunnel.VP8DataTunnel) tunnel.DataTunnel {
|
||||
mt := tunnel.NewMultiTrackTunnel([]*tunnel.VP8DataTunnel{vp8})
|
||||
wrapped := tunnel.NewMultiTrackKCPTunnel(mt, s.p.LogFn)
|
||||
s.p.LogFn("[bx] per-track kcp reliability active over video tunnel")
|
||||
return wrapped
|
||||
}
|
||||
|
||||
func (s *MediaSession) readVP8Track(track *webrtc.TrackRemote) {
|
||||
var vp8Pkt codecs.VP8Packet
|
||||
var frameBuf []byte
|
||||
var lastSeq uint16
|
||||
var haveLastSeq bool
|
||||
frameValid := false
|
||||
for {
|
||||
pkt, _, err := track.ReadRTP()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if pkt == nil {
|
||||
continue
|
||||
}
|
||||
if haveLastSeq && pkt.SequenceNumber != lastSeq+1 {
|
||||
frameValid = false
|
||||
frameBuf = frameBuf[:0]
|
||||
}
|
||||
lastSeq = pkt.SequenceNumber
|
||||
haveLastSeq = true
|
||||
vp8Payload, err := vp8Pkt.Unmarshal(pkt.Payload)
|
||||
if err != nil {
|
||||
frameValid = false
|
||||
frameBuf = frameBuf[:0]
|
||||
continue
|
||||
}
|
||||
if vp8Pkt.S == 1 {
|
||||
frameBuf = frameBuf[:0]
|
||||
frameValid = true
|
||||
}
|
||||
if !frameValid {
|
||||
continue
|
||||
}
|
||||
frameBuf = append(frameBuf, vp8Payload...)
|
||||
if !pkt.Marker {
|
||||
continue
|
||||
}
|
||||
s.vp8tun.HandleFrame(frameBuf)
|
||||
frameBuf = frameBuf[:0]
|
||||
frameValid = false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
package bitrix
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type CookieEntry struct {
|
||||
Name string `json:"name"`
|
||||
Value string `json:"value"`
|
||||
Host string `json:"host"`
|
||||
}
|
||||
|
||||
func (c *Client) LoadSession(path string) error {
|
||||
creds, err := LoadCredentials(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
c.credsPath = path
|
||||
c.email = creds.Email
|
||||
c.password = creds.Password
|
||||
if creds.Portal != "" {
|
||||
c.portal = strings.TrimRight(creds.Portal, "/")
|
||||
}
|
||||
byHost := map[string][]*http.Cookie{}
|
||||
for _, e := range creds.Cookies {
|
||||
host := e.Host
|
||||
if host == "" {
|
||||
host = c.portal
|
||||
}
|
||||
byHost[host] = append(byHost[host], &http.Cookie{Name: e.Name, Value: e.Value, Path: "/"})
|
||||
}
|
||||
for host, cookies := range byHost {
|
||||
u, err := url.Parse(host)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
c.HTTP.Jar.SetCookies(u, cookies)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Client) EnsureLogin() error {
|
||||
if c.checkSession() {
|
||||
c.LogFn("[auth] session valid, reusing saved cookies")
|
||||
return nil
|
||||
}
|
||||
if c.email == "" || c.password == "" {
|
||||
return fmt.Errorf("ensureLogin: no email/password")
|
||||
}
|
||||
c.LogFn("[auth] session dead, re-logging in")
|
||||
return c.loginWithPassword(c.email, c.password)
|
||||
}
|
||||
|
||||
func (c *Client) checkSession() bool {
|
||||
body, final, err := c.getPage(c.portal + "/")
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
if strings.Contains(final, "auth2.bitrix24.net") {
|
||||
return false
|
||||
}
|
||||
if m := reSessid.FindStringSubmatch(body); m != nil {
|
||||
c.sessid = m[1]
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (c *Client) saveSession() error {
|
||||
if c.credsPath == "" {
|
||||
return fmt.Errorf("no creds path")
|
||||
}
|
||||
creds := Credentials{
|
||||
Email: c.email,
|
||||
Password: c.password,
|
||||
Portal: c.portal,
|
||||
Cookies: c.gatherCookies(),
|
||||
}
|
||||
raw, err := json.MarshalIndent(creds, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tmp := c.credsPath + ".tmp"
|
||||
if err := os.WriteFile(tmp, append(raw, '\n'), 0o600); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.Rename(tmp, c.credsPath); err != nil {
|
||||
os.Remove(tmp)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Client) gatherCookies() []CookieEntry {
|
||||
seen := map[string]struct{}{}
|
||||
var out []CookieEntry
|
||||
for _, host := range c.cookieHosts() {
|
||||
u, err := url.Parse(host)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
for _, ck := range c.HTTP.Jar.Cookies(u) {
|
||||
key := host + "|" + ck.Name
|
||||
if _, ok := seen[key]; ok {
|
||||
continue
|
||||
}
|
||||
seen[key] = struct{}{}
|
||||
out = append(out, CookieEntry{Name: ck.Name, Value: ck.Value, Host: host})
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (c *Client) cookieHosts() []string {
|
||||
return []string{c.portal, authNetBase}
|
||||
}
|
||||
|
||||
func (c *Client) withRelogin(do func() ([]byte, int, error)) ([]byte, int, error) {
|
||||
body, status, err := do()
|
||||
if err != nil || !looksUnauth(body, status) {
|
||||
return body, status, err
|
||||
}
|
||||
if c.email == "" || c.password == "" {
|
||||
return body, status, err
|
||||
}
|
||||
c.LogFn("[auth] unauthenticated response (status %d), re-logging in and retrying", status)
|
||||
if lerr := c.loginWithPassword(c.email, c.password); lerr != nil {
|
||||
return body, status, fmt.Errorf("relogin: %w", lerr)
|
||||
}
|
||||
return do()
|
||||
}
|
||||
|
||||
func looksUnauth(body []byte, status int) bool {
|
||||
if status == 401 || status == 403 {
|
||||
return true
|
||||
}
|
||||
s := strings.TrimSpace(string(body))
|
||||
if s == "" || s[0] != '{' {
|
||||
return true
|
||||
}
|
||||
low := strings.ToLower(s)
|
||||
return strings.Contains(low, "not_authorized") ||
|
||||
strings.Contains(low, "unauthorized") ||
|
||||
strings.Contains(low, "invalid_token") ||
|
||||
strings.Contains(low, "user_not_authorized")
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
package bitrix
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/pion/webrtc/v4"
|
||||
"whitelist-bypass/relay/livekit"
|
||||
)
|
||||
|
||||
type SignalConfig struct {
|
||||
SignalURL string
|
||||
Origin string
|
||||
UserAgent string
|
||||
LogFn func(string, ...any)
|
||||
SettingEngine *webrtc.SettingEngine
|
||||
NetDialContext func(ctx context.Context, network, addr string) (net.Conn, error)
|
||||
OnConnected func()
|
||||
OnDataChannel func(*webrtc.DataChannel)
|
||||
OnTrack func(*webrtc.TrackRemote, *webrtc.RTPReceiver)
|
||||
}
|
||||
|
||||
type Signal struct {
|
||||
lk *livekit.Client
|
||||
logFn func(string, ...any)
|
||||
|
||||
mu sync.Mutex
|
||||
onTrack func(*webrtc.TrackRemote, *webrtc.RTPReceiver)
|
||||
onDC func(*webrtc.DataChannel)
|
||||
pendingTracks []remoteTrack
|
||||
pendingDCs []*webrtc.DataChannel
|
||||
pubReliable *webrtc.DataChannel
|
||||
dataChannelsUp bool
|
||||
}
|
||||
|
||||
type remoteTrack struct {
|
||||
track *webrtc.TrackRemote
|
||||
receiver *webrtc.RTPReceiver
|
||||
}
|
||||
|
||||
func ConnectSignal(cfg SignalConfig) (*Signal, error) {
|
||||
logFn := cfg.LogFn
|
||||
if logFn == nil {
|
||||
logFn = func(string, ...any) {}
|
||||
}
|
||||
s := &Signal{
|
||||
logFn: logFn,
|
||||
onTrack: cfg.OnTrack,
|
||||
onDC: cfg.OnDataChannel,
|
||||
}
|
||||
lk, err := livekit.NewClient(livekit.Config{
|
||||
ServerURL: cfg.SignalURL,
|
||||
Origin: cfg.Origin,
|
||||
UserAgent: cfg.UserAgent,
|
||||
Codec: livekit.JSONCodec{},
|
||||
LogFn: logFn,
|
||||
SettingEngine: cfg.SettingEngine,
|
||||
NetDialContext: cfg.NetDialContext,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
s.lk = lk
|
||||
s.lk.OnTrack = s.dispatchTrack
|
||||
s.lk.OnDataChannel = s.dispatchDataChannel
|
||||
s.lk.OnSubConnected = cfg.OnConnected
|
||||
if err := s.lk.Connect(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
go s.lk.PingLoop()
|
||||
return s, nil
|
||||
}
|
||||
|
||||
func (s *Signal) Run() error { return s.lk.ReadLoop() }
|
||||
|
||||
func (s *Signal) Close() { s.lk.Close() }
|
||||
|
||||
func (s *Signal) SetOnTrack(fn func(*webrtc.TrackRemote, *webrtc.RTPReceiver)) {
|
||||
s.mu.Lock()
|
||||
s.onTrack = fn
|
||||
pending := s.pendingTracks
|
||||
s.pendingTracks = nil
|
||||
s.mu.Unlock()
|
||||
if fn == nil {
|
||||
return
|
||||
}
|
||||
for _, t := range pending {
|
||||
fn(t.track, t.receiver)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Signal) SetOnDataChannel(fn func(*webrtc.DataChannel)) {
|
||||
s.mu.Lock()
|
||||
s.onDC = fn
|
||||
pending := s.pendingDCs
|
||||
s.pendingDCs = nil
|
||||
s.mu.Unlock()
|
||||
if fn == nil {
|
||||
return
|
||||
}
|
||||
for _, dc := range pending {
|
||||
fn(dc)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Signal) PubReliableDC() *webrtc.DataChannel {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return s.pubReliable
|
||||
}
|
||||
|
||||
func (s *Signal) PublishVP8(track *webrtc.TrackLocalStaticSample, name string) (*webrtc.RTPSender, error) {
|
||||
select {
|
||||
case <-s.lk.Joined():
|
||||
case <-time.After(30 * time.Second):
|
||||
return nil, fmt.Errorf("join did not arrive")
|
||||
}
|
||||
pubPC := s.lk.PubPC()
|
||||
if pubPC == nil {
|
||||
return nil, fmt.Errorf("pub pc not ready")
|
||||
}
|
||||
if err := s.ensureDataChannels(pubPC); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
transceiver, err := pubPC.AddTransceiverFromTrack(track, webrtc.RTPTransceiverInit{
|
||||
Direction: webrtc.RTPTransceiverDirectionSendonly,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := s.lk.SendAddTrack(track.ID(), name, livekit.TrackTypeVideo, livekit.TrackSourceCamera, 1280, 720); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
s.logFn("[bx] published vp8 track cid=%s name=%s", track.ID(), name)
|
||||
offer, err := pubPC.CreateOffer(nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := pubPC.SetLocalDescription(offer); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := s.lk.SendOffer(offer.SDP); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return transceiver.Sender(), nil
|
||||
}
|
||||
|
||||
func (s *Signal) dispatchTrack(track *webrtc.TrackRemote, receiver *webrtc.RTPReceiver) {
|
||||
s.mu.Lock()
|
||||
fn := s.onTrack
|
||||
if fn == nil {
|
||||
s.pendingTracks = append(s.pendingTracks, remoteTrack{track: track, receiver: receiver})
|
||||
}
|
||||
s.mu.Unlock()
|
||||
if fn != nil {
|
||||
fn(track, receiver)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Signal) dispatchDataChannel(dc *webrtc.DataChannel) {
|
||||
s.mu.Lock()
|
||||
fn := s.onDC
|
||||
if fn == nil {
|
||||
s.pendingDCs = append(s.pendingDCs, dc)
|
||||
}
|
||||
s.mu.Unlock()
|
||||
if fn != nil {
|
||||
fn(dc)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Signal) ensureDataChannels(pubPC *webrtc.PeerConnection) error {
|
||||
s.mu.Lock()
|
||||
if s.dataChannelsUp {
|
||||
s.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
s.dataChannelsUp = true
|
||||
s.mu.Unlock()
|
||||
|
||||
ordered := true
|
||||
reliable, err := pubPC.CreateDataChannel("_reliable", &webrtc.DataChannelInit{Ordered: &ordered})
|
||||
if err != nil {
|
||||
return fmt.Errorf("create _reliable: %w", err)
|
||||
}
|
||||
unordered := false
|
||||
var zero uint16
|
||||
lossy, err := pubPC.CreateDataChannel("_lossy", &webrtc.DataChannelInit{Ordered: &unordered, MaxRetransmits: &zero})
|
||||
if err != nil {
|
||||
return fmt.Errorf("create _lossy: %w", err)
|
||||
}
|
||||
reliable.OnOpen(func() { s.logFn("[bx] pub dc _reliable open") })
|
||||
lossy.OnOpen(func() { s.logFn("[bx] pub dc _lossy open") })
|
||||
|
||||
s.mu.Lock()
|
||||
s.pubReliable = reliable
|
||||
s.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
Reference in new issue
Block a user