Update server dependencies

This commit is contained in:
Hanzei 2018-09-23 08:18:35 +02:00
parent d0df44c109
commit d918262365
No known key found for this signature in database
GPG key ID: 69A2DEFD98937BA0
31 changed files with 1233 additions and 806 deletions

View file

@ -3,63 +3,80 @@
[[projects]]
branch = "master"
digest = "1:bc36a17a513f15717b5fa3dcfd666f5ddb6fd3db06f5f2834ac2f5979d4f5070"
name = "github.com/gorilla/websocket"
packages = ["."]
pruneopts = "UT"
revision = "5ed622c449da6d44c3c8329331ff47a9e5844f71"
[[projects]]
branch = "master"
digest = "1:92014e65d79685825a5625285c7ea0775ce3bf84845c27726d4f58f3c3087d8b"
name = "github.com/mattermost/mattermost-server"
packages = [
"mlog",
"model",
"utils/jsonutils",
"utils/markdown"
"utils/markdown",
]
revision = "90e5e279c175b238d58432acb5eb6422ddfe22e7"
pruneopts = "UT"
revision = "fd21e53365d504155ab87f9bef60b1ab4faeb38d"
version = "v5.3.1"
[[projects]]
digest = "1:07140002dbf37da92090f731b46fa47be4820b82fe5c14a035203b0e813d0ec2"
name = "github.com/nicksnyder/go-i18n"
packages = [
"i18n",
"i18n/bundle",
"i18n/language",
"i18n/translation"
"i18n/translation",
]
pruneopts = "UT"
revision = "0dc1626d56435e9d605a29875701721c54bc9bbd"
version = "v1.10.0"
[[projects]]
digest = "1:361de06aa7ae272616cbe71c3994a654cc6316324e30998e650f7765b20c5b33"
name = "github.com/pborman/uuid"
packages = ["."]
pruneopts = "UT"
revision = "e790cca94e6cc75c7064b1332e63811d4aae1a53"
version = "v1.1"
[[projects]]
digest = "1:95741de3af260a92cc5c7f3f3061e85273f5a81b5db20d4bd68da74bd521675e"
name = "github.com/pelletier/go-toml"
packages = ["."]
pruneopts = "UT"
revision = "c01d1270ff3e442a8a57cddc1c92dc1138598194"
version = "v1.2.0"
[[projects]]
digest = "1:40e195917a951a8bf867cd05de2a46aaf1806c50cf92eebf4c16f78cd196f747"
name = "github.com/pkg/errors"
packages = ["."]
pruneopts = "UT"
revision = "645ef00459ed84a119197bfb8d8205042c6df63d"
version = "v0.8.0"
[[projects]]
digest = "1:3c1a69cdae3501bf75e76d0d86dc6f2b0a7421bc205c0cb7b96b19eed464a34d"
name = "go.uber.org/atomic"
packages = ["."]
pruneopts = "UT"
revision = "1ea20fb1cbb1cc08cbd0d913a96dead89aa18289"
version = "v1.3.2"
[[projects]]
digest = "1:60bf2a5e347af463c42ed31a493d817f8a72f102543060ed992754e689805d1a"
name = "go.uber.org/multierr"
packages = ["."]
pruneopts = "UT"
revision = "3c4937480c32f4c13a875a1829af76c98ca3d40a"
version = "v1.1.0"
[[projects]]
digest = "1:d9a420eae5f76973feeb733fbf58f6a89173255b63b27a7ae4b2124a73dc6c5b"
name = "go.uber.org/zap"
packages = [
".",
@ -67,35 +84,45 @@
"internal/bufferpool",
"internal/color",
"internal/exit",
"zapcore"
"zapcore",
]
pruneopts = "UT"
revision = "4d45f9617f7d90f7a663ff21c7a4321dbe78098b"
version = "v1.9.0"
[[projects]]
branch = "master"
digest = "1:1ecf2a49df33be51e757d0033d5d51d5f784f35f68e5a38f797b2d3f03357d71"
name = "golang.org/x/crypto"
packages = [
"bcrypt",
"blowfish"
"blowfish",
]
pruneopts = "UT"
revision = "c126467f60eb25f8f27e5a981f32a87e3965053f"
[[projects]]
digest = "1:c805e517269b0ba4c21ded5836019ed7d16953d4026cb7d00041d039c7906be9"
name = "gopkg.in/natefinch/lumberjack.v2"
packages = ["."]
pruneopts = "UT"
revision = "a96e63847dc3c67d17befa69c303767e2f84e54f"
version = "v2.1"
[[projects]]
digest = "1:342378ac4dcb378a5448dd723f0784ae519383532f5e70ade24132c4c8693202"
name = "gopkg.in/yaml.v2"
packages = ["."]
pruneopts = "UT"
revision = "5420a8b6744d3b0345ab293f6fcba19c978f1183"
version = "v2.2.1"
[solve-meta]
analyzer-name = "dep"
analyzer-version = 1
inputs-digest = "6dbdeab2586ff88e0f960bde160e43d338fc00d0eb01bb155e30ceae6632ed03"
input-imports = [
"github.com/mattermost/mattermost-server/model",
"github.com/pkg/errors",
]
solver-name = "gps-cdcl"
solver-version = 1

View file

@ -1,38 +1,11 @@
# Gopkg.toml example
#
# Refer to https://github.com/golang/dep/blob/master/docs/Gopkg.toml.md
# for detailed Gopkg.toml documentation.
#
# required = ["github.com/user/thing/cmd/thing"]
# ignored = ["github.com/user/project/pkgX", "bitbucket.org/user/project/pkgA/pkgY"]
#
# [[constraint]]
# name = "github.com/user/project"
# version = "1.0.0"
#
# [[constraint]]
# name = "github.com/user/project2"
# branch = "dev"
# source = "github.com/myfork/project2"
#
# [[override]]
# name = "github.com/x/y"
# version = "2.4.0"
#
# [prune]
# non-go = false
# go-tests = true
# unused-packages = true
[prune]
go-tests = true
unused-packages = true
[[constraint]]
name = "github.com/mattermost/mattermost-server"
branch = "master"
version = "~5.3.0"
[[constraint]]
name = "github.com/pkg/errors"
version = "0.8.0"
[prune]
go-tests = true
unused-packages = true

View file

@ -12,7 +12,7 @@ You may be licensed to use source code to create compiled versions not produced
2. Under a commercial license available from Mattermost, Inc. by contacting commercial@mattermost.com
You are licensed to use the source code in Admin Tools and Configuration Files (templates/, config/, model/,
webapp/client, webapp/fonts, webapp/i18n, webapp/images and all subdirectories thereof) under the Apache License v2.0.
plugin/ and all subdirectories thereof) under the Apache License v2.0.
We promise that we will not enforce the copyleft provisions in AGPL v3.0 against you if your application (a) does not
link to the Mattermost Platform directly, but exclusively uses the Mattermost Admin Tools and Configuration Files, and

View file

@ -2719,5 +2719,434 @@ Legal Terms
Our home page can be found at
http://www.freetype.org
---
## go-hclog
This product contains a common logging package for HashiCorp tools, built by HashiCorp.
* HOMEPAGE:
* github.com/hashicorp/go-hclog
* LICENSE:
MIT License
Copyright (c) 2017 HashiCorp
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
---
## go-plugin
This product contains a Golang plugin system over RPC, built by HashiCorp.
* HOMEPAGE:
* github.com/hashicorp/go-plugin
* LICENSE:
Mozilla Public License, version 2.0
1. Definitions
1.1. “Contributor”
means each individual or legal entity that creates, contributes to the
creation of, or owns Covered Software.
1.2. “Contributor Version”
means the combination of the Contributions of others (if any) used by a
Contributor and that particular Contributors Contribution.
1.3. “Contribution”
means Covered Software of a particular Contributor.
1.4. “Covered Software”
means Source Code Form to which the initial Contributor has attached the
notice in Exhibit A, the Executable Form of such Source Code Form, and
Modifications of such Source Code Form, in each case including portions
thereof.
1.5. “Incompatible With Secondary Licenses”
means
a. that the initial Contributor has attached the notice described in
Exhibit B to the Covered Software; or
b. that the Covered Software was made available under the terms of version
1.1 or earlier of the License, but not also under the terms of a
Secondary License.
1.6. “Executable Form”
means any form of the work other than Source Code Form.
1.7. “Larger Work”
means a work that combines Covered Software with other material, in a separate
file or files, that is not Covered Software.
1.8. “License”
means this document.
1.9. “Licensable”
means having the right to grant, to the maximum extent possible, whether at the
time of the initial grant or subsequently, any and all of the rights conveyed by
this License.
1.10. “Modifications”
means any of the following:
a. any file in Source Code Form that results from an addition to, deletion
from, or modification of the contents of Covered Software; or
b. any new file in Source Code Form that contains any Covered Software.
1.11. “Patent Claims” of a Contributor
means any patent claim(s), including without limitation, method, process,
and apparatus claims, in any patent Licensable by such Contributor that
would be infringed, but for the grant of the License, by the making,
using, selling, offering for sale, having made, import, or transfer of
either its Contributions or its Contributor Version.
1.12. “Secondary License”
means either the GNU General Public License, Version 2.0, the GNU Lesser
General Public License, Version 2.1, the GNU Affero General Public
License, Version 3.0, or any later versions of those licenses.
1.13. “Source Code Form”
means the form of the work preferred for making modifications.
1.14. “You” (or “Your”)
means an individual or a legal entity exercising rights under this
License. For legal entities, “You” includes any entity that controls, is
controlled by, or is under common control with You. For purposes of this
definition, “control” means (a) the power, direct or indirect, to cause
the direction or management of such entity, whether by contract or
otherwise, or (b) ownership of more than fifty percent (50%) of the
outstanding shares or beneficial ownership of such entity.
2. License Grants and Conditions
2.1. Grants
Each Contributor hereby grants You a world-wide, royalty-free,
non-exclusive license:
a. under intellectual property rights (other than patent or trademark)
Licensable by such Contributor to use, reproduce, make available,
modify, display, perform, distribute, and otherwise exploit its
Contributions, either on an unmodified basis, with Modifications, or as
part of a Larger Work; and
b. under Patent Claims of such Contributor to make, use, sell, offer for
sale, have made, import, and otherwise transfer either its Contributions
or its Contributor Version.
2.2. Effective Date
The licenses granted in Section 2.1 with respect to any Contribution become
effective for each Contribution on the date the Contributor first distributes
such Contribution.
2.3. Limitations on Grant Scope
The licenses granted in this Section 2 are the only rights granted under this
License. No additional rights or licenses will be implied from the distribution
or licensing of Covered Software under this License. Notwithstanding Section
2.1(b) above, no patent license is granted by a Contributor:
a. for any code that a Contributor has removed from Covered Software; or
b. for infringements caused by: (i) Your and any other third partys
modifications of Covered Software, or (ii) the combination of its
Contributions with other software (except as part of its Contributor
Version); or
c. under Patent Claims infringed by Covered Software in the absence of its
Contributions.
This License does not grant any rights in the trademarks, service marks, or
logos of any Contributor (except as may be necessary to comply with the
notice requirements in Section 3.4).
2.4. Subsequent Licenses
No Contributor makes additional grants as a result of Your choice to
distribute the Covered Software under a subsequent version of this License
(see Section 10.2) or under the terms of a Secondary License (if permitted
under the terms of Section 3.3).
2.5. Representation
Each Contributor represents that the Contributor believes its Contributions
are its original creation(s) or it has sufficient rights to grant the
rights to its Contributions conveyed by this License.
2.6. Fair Use
This License is not intended to limit any rights You have under applicable
copyright doctrines of fair use, fair dealing, or other equivalents.
2.7. Conditions
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in
Section 2.1.
3. Responsibilities
3.1. Distribution of Source Form
All distribution of Covered Software in Source Code Form, including any
Modifications that You create or to which You contribute, must be under the
terms of this License. You must inform recipients that the Source Code Form
of the Covered Software is governed by the terms of this License, and how
they can obtain a copy of this License. You may not attempt to alter or
restrict the recipients rights in the Source Code Form.
3.2. Distribution of Executable Form
If You distribute Covered Software in Executable Form then:
a. such Covered Software must also be made available in Source Code Form,
as described in Section 3.1, and You must inform recipients of the
Executable Form how they can obtain a copy of such Source Code Form by
reasonable means in a timely manner, at a charge no more than the cost
of distribution to the recipient; and
b. You may distribute such Executable Form under the terms of this License,
or sublicense it under different terms, provided that the license for
the Executable Form does not attempt to limit or alter the recipients
rights in the Source Code Form under this License.
3.3. Distribution of a Larger Work
You may create and distribute a Larger Work under terms of Your choice,
provided that You also comply with the requirements of this License for the
Covered Software. If the Larger Work is a combination of Covered Software
with a work governed by one or more Secondary Licenses, and the Covered
Software is not Incompatible With Secondary Licenses, this License permits
You to additionally distribute such Covered Software under the terms of
such Secondary License(s), so that the recipient of the Larger Work may, at
their option, further distribute the Covered Software under the terms of
either this License or such Secondary License(s).
3.4. Notices
You may not remove or alter the substance of any license notices (including
copyright notices, patent notices, disclaimers of warranty, or limitations
of liability) contained within the Source Code Form of the Covered
Software, except that You may alter any license notices to the extent
required to remedy known factual inaccuracies.
3.5. Application of Additional Terms
You may choose to offer, and to charge a fee for, warranty, support,
indemnity or liability obligations to one or more recipients of Covered
Software. However, You may do so only on Your own behalf, and not on behalf
of any Contributor. You must make it absolutely clear that any such
warranty, support, indemnity, or liability obligation is offered by You
alone, and You hereby agree to indemnify every Contributor for any
liability incurred by such Contributor as a result of warranty, support,
indemnity or liability terms You offer. You may include additional
disclaimers of warranty and limitations of liability specific to any
jurisdiction.
4. Inability to Comply Due to Statute or Regulation
If it is impossible for You to comply with any of the terms of this License
with respect to some or all of the Covered Software due to statute, judicial
order, or regulation then You must: (a) comply with the terms of this License
to the maximum extent possible; and (b) describe the limitations and the code
they affect. Such description must be placed in a text file included with all
distributions of the Covered Software under this License. Except to the
extent prohibited by statute or regulation, such description must be
sufficiently detailed for a recipient of ordinary skill to be able to
understand it.
5. Termination
5.1. The rights granted under this License will terminate automatically if You
fail to comply with any of its terms. However, if You become compliant,
then the rights granted under this License from a particular Contributor
are reinstated (a) provisionally, unless and until such Contributor
explicitly and finally terminates Your grants, and (b) on an ongoing basis,
if such Contributor fails to notify You of the non-compliance by some
reasonable means prior to 60 days after You have come back into compliance.
Moreover, Your grants from a particular Contributor are reinstated on an
ongoing basis if such Contributor notifies You of the non-compliance by
some reasonable means, this is the first time You have received notice of
non-compliance with this License from such Contributor, and You become
compliant prior to 30 days after Your receipt of the notice.
5.2. If You initiate litigation against any entity by asserting a patent
infringement claim (excluding declaratory judgment actions, counter-claims,
and cross-claims) alleging that a Contributor Version directly or
indirectly infringes any patent, then the rights granted to You by any and
all Contributors for the Covered Software under Section 2.1 of this License
shall terminate.
5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user
license agreements (excluding distributors and resellers) which have been
validly granted by You or Your distributors under this License prior to
termination shall survive termination.
6. Disclaimer of Warranty
Covered Software is provided under this License on an “as is” basis, without
warranty of any kind, either expressed, implied, or statutory, including,
without limitation, warranties that the Covered Software is free of defects,
merchantable, fit for a particular purpose or non-infringing. The entire
risk as to the quality and performance of the Covered Software is with You.
Should any Covered Software prove defective in any respect, You (not any
Contributor) assume the cost of any necessary servicing, repair, or
correction. This disclaimer of warranty constitutes an essential part of this
License. No use of any Covered Software is authorized under this License
except under this disclaimer.
7. Limitation of Liability
Under no circumstances and under no legal theory, whether tort (including
negligence), contract, or otherwise, shall any Contributor, or anyone who
distributes Covered Software as permitted above, be liable to You for any
direct, indirect, special, incidental, or consequential damages of any
character including, without limitation, damages for lost profits, loss of
goodwill, work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses, even if such party shall have been
informed of the possibility of such damages. This limitation of liability
shall not apply to liability for death or personal injury resulting from such
partys negligence to the extent applicable law prohibits such limitation.
Some jurisdictions do not allow the exclusion or limitation of incidental or
consequential damages, so this exclusion and limitation may not apply to You.
8. Litigation
Any litigation relating to this License may be brought only in the courts of
a jurisdiction where the defendant maintains its principal place of business
and such litigation shall be governed by laws of that jurisdiction, without
reference to its conflict-of-law provisions. Nothing in this Section shall
prevent a partys ability to bring cross-claims or counter-claims.
9. Miscellaneous
This License represents the complete agreement concerning the subject matter
hereof. If any provision of this License is held to be unenforceable, such
provision shall be reformed only to the extent necessary to make it
enforceable. Any law or regulation which provides that the language of a
contract shall be construed against the drafter shall not be used to construe
this License against a Contributor.
10. Versions of the License
10.1. New Versions
Mozilla Foundation is the license steward. Except as provided in Section
10.3, no one other than the license steward has the right to modify or
publish new versions of this License. Each version will be given a
distinguishing version number.
10.2. Effect of New Versions
You may distribute the Covered Software under the terms of the version of
the License under which You originally received the Covered Software, or
under the terms of any subsequent version published by the license
steward.
10.3. Modified Versions
If you create software not governed by this License, and you want to
create a new license for such software, you may create and use a modified
version of this License if you rename the license and remove any
references to the name of the license steward (except to note that such
modified license differs from this License).
10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses
If You choose to distribute Source Code Form that is Incompatible With
Secondary Licenses under the terms of this version of the License, the
notice described in Exhibit B of this License must be attached.
Exhibit A - Source Code Form License Notice
This Source Code Form is subject to the
terms of the Mozilla Public License, v.
2.0. If a copy of the MPL was not
distributed with this file, You can
obtain one at
http://mozilla.org/MPL/2.0/.
If it is not possible or desirable to put the notice in a particular file, then
You may include the notice in a location (such as a LICENSE file in a relevant
directory) where a recipient would be likely to look for such a notice.
You may add additional accurate notices of copyright ownership.
Exhibit B - “Incompatible With Secondary Licenses” Notice
This Source Code Form is “Incompatible
With Secondary Licenses”, as defined by
the Mozilla Public License, v. 2.0.
---
## cors
This product contains a Go net/http configurable handler to handle CORS requests, built by Olivier Poitrey.
* HOMEPAGE:
* github.com/rs/cors
* LICENSE:
Copyright (c) 2014 Olivier Poitrey <rs@dailymotion.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
--- end of FTL.TXT ---

View file

@ -1,219 +0,0 @@
// Copyright (c) 2017-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
package app
import (
"crypto/md5"
"fmt"
"net/http"
"strings"
"github.com/mattermost/mattermost-server/mlog"
"github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/utils"
)
func (a *App) LoadLicense() {
a.SetLicense(nil)
licenseId := ""
if result := <-a.Srv.Store.System().Get(); result.Err == nil {
props := result.Data.(model.StringMap)
licenseId = props[model.SYSTEM_ACTIVE_LICENSE_ID]
}
if len(licenseId) != 26 {
// Lets attempt to load the file from disk since it was missing from the DB
license, licenseBytes := utils.GetAndValidateLicenseFileFromDisk(*a.Config().ServiceSettings.LicenseFileLocation)
if license != nil {
if _, err := a.SaveLicense(licenseBytes); err != nil {
mlog.Info(fmt.Sprintf("Failed to save license key loaded from disk err=%v", err.Error()))
} else {
licenseId = license.Id
}
}
}
if result := <-a.Srv.Store.License().Get(licenseId); result.Err == nil {
record := result.Data.(*model.LicenseRecord)
a.ValidateAndSetLicenseBytes([]byte(record.Bytes))
mlog.Info("License key valid unlocking enterprise features.")
} else {
mlog.Info("License key from https://mattermost.com required to unlock enterprise features.")
}
}
func (a *App) SaveLicense(licenseBytes []byte) (*model.License, *model.AppError) {
var license *model.License
if success, licenseStr := utils.ValidateLicense(licenseBytes); success {
license = model.LicenseFromJson(strings.NewReader(licenseStr))
if result := <-a.Srv.Store.User().AnalyticsUniqueUserCount(""); result.Err != nil {
return nil, model.NewAppError("addLicense", "api.license.add_license.invalid_count.app_error", nil, result.Err.Error(), http.StatusBadRequest)
} else {
uniqueUserCount := result.Data.(int64)
if uniqueUserCount > int64(*license.Features.Users) {
return nil, model.NewAppError("addLicense", "api.license.add_license.unique_users.app_error", map[string]interface{}{"Users": *license.Features.Users, "Count": uniqueUserCount}, "", http.StatusBadRequest)
}
}
if ok := a.SetLicense(license); !ok {
return nil, model.NewAppError("addLicense", model.EXPIRED_LICENSE_ERROR, nil, "", http.StatusBadRequest)
}
record := &model.LicenseRecord{}
record.Id = license.Id
record.Bytes = string(licenseBytes)
rchan := a.Srv.Store.License().Save(record)
if result := <-rchan; result.Err != nil {
a.RemoveLicense()
return nil, model.NewAppError("addLicense", "api.license.add_license.save.app_error", nil, "err="+result.Err.Error(), http.StatusInternalServerError)
}
sysVar := &model.System{}
sysVar.Name = model.SYSTEM_ACTIVE_LICENSE_ID
sysVar.Value = license.Id
schan := a.Srv.Store.System().SaveOrUpdate(sysVar)
if result := <-schan; result.Err != nil {
a.RemoveLicense()
return nil, model.NewAppError("addLicense", "api.license.add_license.save_active.app_error", nil, "", http.StatusInternalServerError)
}
} else {
return nil, model.NewAppError("addLicense", model.INVALID_LICENSE_ERROR, nil, "", http.StatusBadRequest)
}
a.ReloadConfig()
a.InvalidateAllCaches()
// start job server if necessary - this handles the edge case where a license file is uploaded, but the job server
// doesn't start until the server is restarted, which prevents the 'run job now' buttons in system console from
// functioning as expected
if *a.Config().JobSettings.RunJobs {
a.Jobs.StartWorkers()
}
if *a.Config().JobSettings.RunScheduler {
a.Jobs.StartSchedulers()
}
return license, nil
}
// License returns the currently active license or nil if the application is unlicensed.
func (a *App) License() *model.License {
license, _ := a.licenseValue.Load().(*model.License)
return license
}
func (a *App) SetLicense(license *model.License) bool {
defer func() {
for _, listener := range a.licenseListeners {
listener()
}
}()
if license != nil {
license.Features.SetDefaults()
if !license.IsExpired() {
a.licenseValue.Store(license)
a.clientLicenseValue.Store(utils.GetClientLicense(license))
return true
}
}
a.licenseValue.Store((*model.License)(nil))
a.clientLicenseValue.Store(map[string]string(nil))
return false
}
func (a *App) ValidateAndSetLicenseBytes(b []byte) {
if success, licenseStr := utils.ValidateLicense(b); success {
license := model.LicenseFromJson(strings.NewReader(licenseStr))
a.SetLicense(license)
return
}
mlog.Warn("No valid enterprise license found")
}
func (a *App) SetClientLicense(m map[string]string) {
a.clientLicenseValue.Store(m)
}
func (a *App) ClientLicense() map[string]string {
if clientLicense, _ := a.clientLicenseValue.Load().(map[string]string); clientLicense != nil {
return clientLicense
}
return map[string]string{"IsLicensed": "false"}
}
func (a *App) RemoveLicense() *model.AppError {
if license, _ := a.licenseValue.Load().(*model.License); license == nil {
return nil
}
sysVar := &model.System{}
sysVar.Name = model.SYSTEM_ACTIVE_LICENSE_ID
sysVar.Value = ""
if result := <-a.Srv.Store.System().SaveOrUpdate(sysVar); result.Err != nil {
return result.Err
}
a.SetLicense(nil)
a.ReloadConfig()
a.InvalidateAllCaches()
return nil
}
func (a *App) AddLicenseListener(listener func()) string {
id := model.NewId()
a.licenseListeners[id] = listener
return id
}
func (a *App) RemoveLicenseListener(id string) {
delete(a.licenseListeners, id)
}
func (a *App) GetClientLicenseEtag(useSanitized bool) string {
value := ""
lic := a.ClientLicense()
if useSanitized {
lic = a.GetSanitizedClientLicense()
}
for k, v := range lic {
value += fmt.Sprintf("%s:%s;", k, v)
}
return model.Etag(fmt.Sprintf("%x", md5.Sum([]byte(value))))
}
func (a *App) GetSanitizedClientLicense() map[string]string {
sanitizedLicense := make(map[string]string)
for k, v := range a.ClientLicense() {
sanitizedLicense[k] = v
}
delete(sanitizedLicense, "Id")
delete(sanitizedLicense, "Name")
delete(sanitizedLicense, "Email")
delete(sanitizedLicense, "PhoneNumber")
delete(sanitizedLicense, "IssuedAt")
delete(sanitizedLicense, "StartsAt")
delete(sanitizedLicense, "ExpiresAt")
return sanitizedLicense
}

View file

@ -1,54 +0,0 @@
// Copyright (c) 2016-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
package commands
import (
"errors"
"io/ioutil"
"github.com/spf13/cobra"
)
var LicenseCmd = &cobra.Command{
Use: "license",
Short: "Licensing commands",
}
var UploadLicenseCmd = &cobra.Command{
Use: "upload [license]",
Short: "Upload a license.",
Long: "Upload a license. Replaces current license.",
Example: " license upload /path/to/license/mylicensefile.mattermost-license",
RunE: uploadLicenseCmdF,
}
func init() {
LicenseCmd.AddCommand(UploadLicenseCmd)
RootCmd.AddCommand(LicenseCmd)
}
func uploadLicenseCmdF(command *cobra.Command, args []string) error {
a, err := InitDBCommandContextCobra(command)
if err != nil {
return err
}
defer a.Shutdown()
if len(args) != 1 {
return errors.New("Enter one license file to upload")
}
var fileBytes []byte
if fileBytes, err = ioutil.ReadFile(args[0]); err != nil {
return err
}
if _, err := a.SaveLicense(fileBytes); err != nil {
return err
}
CommandPrettyPrintln("Uploaded license file")
return nil
}

View file

@ -12,6 +12,7 @@ import (
const (
AUTHCODE_EXPIRE_TIME = 60 * 10 // 10 minutes
AUTHCODE_RESPONSE_TYPE = "code"
IMPLICIT_RESPONSE_TYPE = "token"
DEFAULT_SCOPE = "user"
)
@ -58,7 +59,7 @@ func (ad *AuthData) IsValid() *AppError {
return NewAppError("AuthData.IsValid", "model.authorize.is_valid.create_at.app_error", nil, "client_id="+ad.ClientId, http.StatusBadRequest)
}
if len(ad.RedirectUri) == 0 || len(ad.RedirectUri) > 256 || !IsValidHttpUrl(ad.RedirectUri) {
if len(ad.RedirectUri) > 256 || !IsValidHttpUrl(ad.RedirectUri) {
return NewAppError("AuthData.IsValid", "model.authorize.is_valid.redirect_uri.app_error", nil, "client_id="+ad.ClientId, http.StatusBadRequest)
}

View file

@ -59,6 +59,9 @@ type ChannelPatch struct {
func (o *Channel) DeepCopy() *Channel {
copy := *o
if copy.SchemeId != nil {
copy.SchemeId = NewString(*o.SchemeId)
}
return &copy
}

View file

@ -397,6 +397,10 @@ func (c *Client4) GetTotalUsersStatsRoute() string {
return fmt.Sprintf(c.GetUsersRoute() + "/stats")
}
func (c *Client4) GetRedirectLocationRoute() string {
return fmt.Sprintf("/redirect_location")
}
func (c *Client4) DoApiGet(url string, etag string) (*http.Response, *AppError) {
return c.DoApiRequest(http.MethodGet, c.ApiUrl+url, "", etag)
}
@ -1791,6 +1795,15 @@ func (c *Client4) GetChannelByName(channelName, teamId string, etag string) (*Ch
}
}
func (c *Client4) GetChannelByNameIncludeDeleted(channelName, teamId string, etag string) (*Channel, *Response) {
if r, err := c.DoApiGet(c.GetChannelByNameRoute(channelName, teamId)+"?include_deleted=true", etag); err != nil {
return nil, BuildErrorResponse(r, err)
} else {
defer closeBody(r)
return ChannelFromJson(r.Body), BuildResponse(r)
}
}
// GetChannelByNameForTeamName returns a channel based on the provided channel name and team name strings.
func (c *Client4) GetChannelByNameForTeamName(channelName, teamName string, etag string) (*Channel, *Response) {
if r, err := c.DoApiGet(c.GetChannelByNameForTeamNameRoute(channelName, teamName), etag); err != nil {
@ -1801,6 +1814,15 @@ func (c *Client4) GetChannelByNameForTeamName(channelName, teamName string, etag
}
}
func (c *Client4) GetChannelByNameForTeamNameIncludeDeleted(channelName, teamName string, etag string) (*Channel, *Response) {
if r, err := c.DoApiGet(c.GetChannelByNameForTeamNameRoute(channelName, teamName)+"?include_deleted=true", etag); err != nil {
return nil, BuildErrorResponse(r, err)
} else {
defer closeBody(r)
return ChannelFromJson(r.Body), BuildResponse(r)
}
}
// GetChannelMembers gets a page of channel members.
func (c *Client4) GetChannelMembers(channelId string, page, perPage int, etag string) (*ChannelMembers, *Response) {
query := fmt.Sprintf("?page=%v&per_page=%v", page, perPage)
@ -2118,8 +2140,27 @@ func (c *Client4) GetPostsBefore(channelId, postId string, page, perPage int, et
// SearchPosts returns any posts with matching terms string.
func (c *Client4) SearchPosts(teamId string, terms string, isOrSearch bool) (*PostList, *Response) {
params := SearchParameter{
Terms: &terms,
IsOrSearch: &isOrSearch,
}
return c.SearchPostsWithParams(teamId, &params)
}
// SearchPosts returns any posts with matching terms string.
func (c *Client4) SearchPostsWithParams(teamId string, params *SearchParameter) (*PostList, *Response) {
if r, err := c.DoApiPost(c.GetTeamRoute(teamId)+"/posts/search", params.SearchParameterToJson()); err != nil {
return nil, BuildErrorResponse(r, err)
} else {
defer closeBody(r)
return PostListFromJson(r.Body), BuildResponse(r)
}
}
// SearchPosts returns any posts with matching terms string including deleted channels.
func (c *Client4) SearchPostsIncludeDeletedChannels(teamId string, terms string, isOrSearch bool) (*PostList, *Response) {
requestBody := map[string]interface{}{"terms": terms, "is_or_search": isOrSearch}
if r, err := c.DoApiPost(c.GetTeamRoute(teamId)+"/posts/search", StringInterfaceToJson(requestBody)); err != nil {
if r, err := c.DoApiPost(c.GetTeamRoute(teamId)+"/posts/search?include_deleted_channels=true", StringInterfaceToJson(requestBody)); err != nil {
return nil, BuildErrorResponse(r, err)
} else {
defer closeBody(r)
@ -3742,3 +3783,14 @@ func (c *Client4) UpdateTeamScheme(teamId, schemeId string) (bool, *Response) {
return CheckStatusOK(r), BuildResponse(r)
}
}
// GetRedirectLocation retrieves the value of the 'Location' header of an HTTP response for a given URL.
func (c *Client4) GetRedirectLocation(urlParam, etag string) (string, *Response) {
url := fmt.Sprintf("%s?url=%s", c.GetRedirectLocationRoute(), url.QueryEscape(urlParam))
if r, err := c.DoApiGet(url, etag); err != nil {
return "", BuildErrorResponse(r, err)
} else {
defer closeBody(r)
return MapFromJson(r.Body)["location"], BuildResponse(r)
}
}

View file

@ -6,9 +6,12 @@ package model
import (
"encoding/json"
"io"
"math"
"net"
"net/http"
"net/url"
"regexp"
"strconv"
"strings"
"time"
)
@ -117,6 +120,7 @@ const (
LDAP_SETTINGS_DEFAULT_POSITION_ATTRIBUTE = ""
LDAP_SETTINGS_DEFAULT_LOGIN_FIELD_NAME = ""
SAML_SETTINGS_DEFAULT_ID_ATTRIBUTE = ""
SAML_SETTINGS_DEFAULT_FIRST_NAME_ATTRIBUTE = ""
SAML_SETTINGS_DEFAULT_LAST_NAME_ATTRIBUTE = ""
SAML_SETTINGS_DEFAULT_EMAIL_ATTRIBUTE = ""
@ -1122,6 +1126,7 @@ type TeamSettings struct {
MaxNotificationsPerChannel *int64
EnableConfirmNotificationsToChannel *bool
TeammateNameDisplay *string
ExperimentalViewArchivedChannels *bool
ExperimentalEnableAutomaticReplies *bool
ExperimentalHideTownSquareinLHS *bool
ExperimentalTownSquareIsReadOnly *bool
@ -1251,6 +1256,9 @@ func (s *TeamSettings) SetDefaults() {
s.EnableUserCreation = NewBool(true)
}
if s.ExperimentalViewArchivedChannels == nil {
s.ExperimentalViewArchivedChannels = NewBool(false)
}
}
type ClientRequirements struct {
@ -1449,8 +1457,9 @@ func (s *LocalizationSettings) SetDefaults() {
type SamlSettings struct {
// Basic
Enable *bool
EnableSyncWithLdap *bool
Enable *bool
EnableSyncWithLdap *bool
EnableSyncWithLdapIncludeAuth *bool
Verify *bool
Encrypt *bool
@ -1467,6 +1476,7 @@ type SamlSettings struct {
PrivateKeyFile *string
// User Mapping
IdAttribute *string
FirstNameAttribute *string
LastNameAttribute *string
EmailAttribute *string
@ -1491,6 +1501,10 @@ func (s *SamlSettings) SetDefaults() {
s.EnableSyncWithLdap = NewBool(false)
}
if s.EnableSyncWithLdapIncludeAuth == nil {
s.EnableSyncWithLdapIncludeAuth = NewBool(false)
}
if s.Verify == nil {
s.Verify = NewBool(true)
}
@ -1535,6 +1549,10 @@ func (s *SamlSettings) SetDefaults() {
s.LoginButtonText = NewString(USER_AUTH_SERVICE_SAML_TEXT)
}
if s.IdAttribute == nil {
s.IdAttribute = NewString(SAML_SETTINGS_DEFAULT_ID_ATTRIBUTE)
}
if s.FirstNameAttribute == nil {
s.FirstNameAttribute = NewString(SAML_SETTINGS_DEFAULT_FIRST_NAME_ATTRIBUTE)
}
@ -2352,7 +2370,15 @@ func (ss *ServiceSettings) isValid() *AppError {
}
}
if len(*ss.ListenAddress) == 0 {
host, port, err := net.SplitHostPort(*ss.ListenAddress)
var isValidHost bool
if host == "" {
isValidHost = true
} else {
isValidHost = (net.ParseIP(host) != nil) || IsDomainName(host)
}
portInt, err := strconv.Atoi(port)
if err != nil || !isValidHost || portInt < 0 || portInt > math.MaxUint16 {
return NewAppError("Config.IsValid", "model.config.is_valid.listen_address.app_error", nil, "", http.StatusBadRequest)
}

View file

@ -5,6 +5,7 @@ package model
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"os"
@ -151,6 +152,9 @@ type ManifestWebapp struct {
// The path to your webapp bundle. This should be relative to the root of your bundle and the
// location of the manifest file.
BundlePath string `json:"bundle_path" yaml:"bundle_path"`
// BundleHash is the 64-bit FNV-1a hash of the webapp bundle, computed when the plugin is loaded
BundleHash []byte `json:"-"`
}
func (m *Manifest) ToJson() string {
@ -188,7 +192,7 @@ func (m *Manifest) ClientManifest() *Manifest {
if cm.Webapp != nil {
cm.Webapp = new(ManifestWebapp)
*cm.Webapp = *m.Webapp
cm.Webapp.BundlePath = "/static/" + m.Id + "_bundle.js"
cm.Webapp.BundlePath = "/static/" + m.Id + "/" + fmt.Sprintf("%s_%x_bundle.js", m.Id, m.Webapp.BundleHash)
}
return cm
}

View file

@ -109,7 +109,6 @@ func (a *OAuthApp) PreUpdate() {
a.UpdateAt = GetMillis()
}
// ToJson convert a User to a json string
func (a *OAuthApp) ToJson() string {
b, _ := json.Marshal(a)
return string(b)
@ -135,7 +134,6 @@ func (a *OAuthApp) IsValidRedirectURL(url string) bool {
return false
}
// OAuthAppFromJson will decode the input and return a User
func OAuthAppFromJson(data io.Reader) *OAuthApp {
var app *OAuthApp
json.NewDecoder(data).Decode(&app)

View file

@ -50,6 +50,8 @@ const (
PROPS_ADD_CHANNEL_MEMBER = "add_channel_member"
POST_PROPS_ADDED_USER_ID = "addedUserId"
POST_PROPS_DELETE_BY = "deleteBy"
POST_ACTION_TYPE_BUTTON = "button"
POST_ACTION_TYPE_SELECT = "select"
)
type Post struct {
@ -94,6 +96,12 @@ type PostPatch struct {
HasReactions *bool `json:"has_reactions"`
}
type SearchParameter struct {
Terms *string `json:"terms"`
IsOrSearch *bool `json:"is_or_search"`
TimeZoneOffset *int `json:"time_zone_offset"`
}
func (o *PostPatch) WithRewrittenImageURLs(f func(string) string) *PostPatch {
copy := *o
if copy.Message != nil {
@ -108,20 +116,35 @@ type PostForIndexing struct {
ParentCreateAt *int64 `json:"parent_create_at"`
}
type DoPostActionRequest struct {
SelectedOption string `json:"selected_option"`
}
type PostAction struct {
Id string `json:"id"`
Name string `json:"name"`
Type string `json:"type"`
DataSource string `json:"data_source"`
Options []*PostActionOptions `json:"options"`
Integration *PostActionIntegration `json:"integration,omitempty"`
}
type PostActionOptions struct {
Text string `json:"text"`
Value string `json:"value"`
}
type PostActionIntegration struct {
URL string `json:"url,omitempty"`
Context StringInterface `json:"context,omitempty"`
}
type PostActionIntegrationRequest struct {
UserId string `json:"user_id"`
Context StringInterface `json:"context,omitempty"`
UserId string `json:"user_id"`
PostId string `json:"post_id"`
Type string `json:"type"`
DataSource string `json:"data_source"`
Context StringInterface `json:"context,omitempty"`
}
type PostActionIntegrationResponse struct {
@ -342,6 +365,26 @@ func PostPatchFromJson(data io.Reader) *PostPatch {
return &post
}
func (o *SearchParameter) SearchParameterToJson() string {
b, err := json.Marshal(o)
if err != nil {
return ""
}
return string(b)
}
func SearchParameterFromJson(data io.Reader) *SearchParameter {
decoder := json.NewDecoder(data)
var searchParam SearchParameter
err := decoder.Decode(&searchParam)
if err != nil {
return nil
}
return &searchParam
}
func (o *Post) ChannelMentions() []string {
return ChannelMentions(o.Message)
}
@ -351,6 +394,29 @@ func (r *PostActionIntegrationRequest) ToJson() string {
return string(b)
}
func PostActionIntegrationRequesteFromJson(data io.Reader) *PostActionIntegrationRequest {
var o *PostActionIntegrationRequest
err := json.NewDecoder(data).Decode(&o)
if err != nil {
return nil
}
return o
}
func (r *PostActionIntegrationResponse) ToJson() string {
b, _ := json.Marshal(r)
return string(b)
}
func PostActionIntegrationResponseFromJson(data io.Reader) *PostActionIntegrationResponse {
var o *PostActionIntegrationResponse
err := json.NewDecoder(data).Decode(&o)
if err != nil {
return nil
}
return o
}
func (o *Post) Attachments() []*SlackAttachment {
if attachments, ok := o.Props["attachments"].([]*SlackAttachment); ok {
return attachments
@ -431,6 +497,12 @@ func (o *PostEphemeral) ToUnsanitizedJson() string {
return string(b)
}
func DoPostActionRequestFromJson(data io.Reader) *DoPostActionRequest {
var o *DoPostActionRequest
json.NewDecoder(data).Decode(&o)
return o
}
// RewriteImageURLs takes a message and returns a copy that has all of the image URLs replaced
// according to the function f. For each image URL, f will be invoked, and the resulting markdown
// will contain the URL returned by that invocation instead.

View file

@ -6,20 +6,50 @@ package model
import (
"regexp"
"strings"
"time"
)
var searchTermPuncStart = regexp.MustCompile(`^[^\pL\d\s#"]+`)
var searchTermPuncEnd = regexp.MustCompile(`[^\pL\d\s*"]+$`)
type SearchParams struct {
Terms string
IsHashtag bool
InChannels []string
FromUsers []string
OrTerms bool
Terms string
IsHashtag bool
InChannels []string
FromUsers []string
AfterDate string
BeforeDate string
OnDate string
OrTerms bool
IncludeDeletedChannels bool
TimeZoneOffset int
}
var searchFlags = [...]string{"from", "channel", "in"}
// Returns the epoch timestamp of the start of the day specified by SearchParams.AfterDate
func (p *SearchParams) GetAfterDateMillis() int64 {
date := ParseDateFilterToTime(p.AfterDate)
// travel forward 1 day
oneDay := time.Hour * 24
afterDate := date.Add(oneDay)
return GetStartOfDayMillis(afterDate, p.TimeZoneOffset)
}
// Returns the epoch timestamp of the end of the day specified by SearchParams.BeforeDate
func (p *SearchParams) GetBeforeDateMillis() int64 {
date := ParseDateFilterToTime(p.BeforeDate)
// travel back 1 day
oneDay := time.Hour * -24
beforeDate := date.Add(oneDay)
return GetEndOfDayMillis(beforeDate, p.TimeZoneOffset)
}
// Returns the epoch timestamps of the start and end of the day specified by SearchParams.OnDate
func (p *SearchParams) GetOnDateMillis() (int64, int64) {
date := ParseDateFilterToTime(p.OnDate)
return GetStartOfDayMillis(date, p.TimeZoneOffset), GetEndOfDayMillis(date, p.TimeZoneOffset)
}
var searchFlags = [...]string{"from", "channel", "in", "before", "after", "on"}
func splitWords(text string) []string {
words := []string{}
@ -100,7 +130,7 @@ func parseSearchFlags(input []string) ([]string, [][2]string) {
return words, flags
}
func ParseSearchParams(text string) []*SearchParams {
func ParseSearchParams(text string, timeZoneOffset int) []*SearchParams {
words, flags := parseSearchFlags(splitWords(text))
hashtagTermList := []string{}
@ -119,6 +149,9 @@ func ParseSearchParams(text string) []*SearchParams {
inChannels := []string{}
fromUsers := []string{}
afterDate := ""
beforeDate := ""
onDate := ""
for _, flagPair := range flags {
flag := flagPair[0]
@ -128,6 +161,12 @@ func ParseSearchParams(text string) []*SearchParams {
inChannels = append(inChannels, value)
} else if flag == "from" {
fromUsers = append(fromUsers, value)
} else if flag == "after" {
afterDate = value
} else if flag == "before" {
beforeDate = value
} else if flag == "on" {
onDate = value
}
}
@ -135,29 +174,41 @@ func ParseSearchParams(text string) []*SearchParams {
if len(plainTerms) > 0 {
paramsList = append(paramsList, &SearchParams{
Terms: plainTerms,
IsHashtag: false,
InChannels: inChannels,
FromUsers: fromUsers,
Terms: plainTerms,
IsHashtag: false,
InChannels: inChannels,
FromUsers: fromUsers,
AfterDate: afterDate,
BeforeDate: beforeDate,
OnDate: onDate,
TimeZoneOffset: timeZoneOffset,
})
}
if len(hashtagTerms) > 0 {
paramsList = append(paramsList, &SearchParams{
Terms: hashtagTerms,
IsHashtag: true,
InChannels: inChannels,
FromUsers: fromUsers,
Terms: hashtagTerms,
IsHashtag: true,
InChannels: inChannels,
FromUsers: fromUsers,
AfterDate: afterDate,
BeforeDate: beforeDate,
OnDate: onDate,
TimeZoneOffset: timeZoneOffset,
})
}
// special case for when no terms are specified but we still have a filter
if len(plainTerms) == 0 && len(hashtagTerms) == 0 && (len(inChannels) != 0 || len(fromUsers) != 0) {
if len(plainTerms) == 0 && len(hashtagTerms) == 0 && (len(inChannels) != 0 || len(fromUsers) != 0 || len(afterDate) != 0 || len(beforeDate) != 0 || len(onDate) != 0) {
paramsList = append(paramsList, &SearchParams{
Terms: "",
IsHashtag: false,
InChannels: inChannels,
FromUsers: fromUsers,
Terms: "",
IsHashtag: false,
InChannels: inChannels,
FromUsers: fromUsers,
AfterDate: afterDate,
BeforeDate: beforeDate,
OnDate: onDate,
TimeZoneOffset: timeZoneOffset,
})
}

View file

@ -135,6 +135,20 @@ func (me *Session) GetUserRoles() []string {
return strings.Fields(me.Roles)
}
func (me *Session) GenerateCSRF() string {
token := NewId()
me.AddProp("csrf", token)
return token
}
func (me *Session) GetCSRF() string {
if me.Props == nil {
return ""
}
return me.Props["csrf"]
}
func SessionsToJson(o []*Session) string {
if b, err := json.Marshal(o); err != nil {
return "[]"

View file

@ -16,6 +16,7 @@ const (
SYSTEM_ACTIVE_LICENSE_ID = "ActiveLicenseId"
SYSTEM_LAST_COMPLIANCE_TIME = "LastComplianceTime"
SYSTEM_ASYMMETRIC_SIGNING_KEY = "AsymmetricSigningKey"
SYSTEM_INSTALLATION_DATE_KEY = "InstallationDate"
)
type System struct {

View file

@ -47,6 +47,7 @@ type TeamPatch struct {
DisplayName *string `json:"display_name"`
Description *string `json:"description"`
CompanyName *string `json:"company_name"`
AllowedDomains *string `json:"allowed_domains"`
InviteId *string `json:"invite_id"`
AllowOpenInvite *bool `json:"allow_open_invite"`
}
@ -241,7 +242,6 @@ func CleanTeamName(s string) string {
func (o *Team) Sanitize() {
o.Email = ""
o.AllowedDomains = ""
}
func (t *Team) Patch(patch *TeamPatch) {
@ -257,6 +257,10 @@ func (t *Team) Patch(patch *TeamPatch) {
t.CompanyName = *patch.CompanyName
}
if patch.AllowedDomains != nil {
t.AllowedDomains = *patch.AllowedDomains
}
if patch.InviteId != nil {
t.InviteId = *patch.InviteId
}

View file

@ -132,7 +132,7 @@ func (u *User) IsValid() *AppError {
return InvalidUserError("username", u.Id)
}
if len(u.Email) > USER_EMAIL_MAX_LENGTH || len(u.Email) == 0 {
if len(u.Email) > USER_EMAIL_MAX_LENGTH || len(u.Email) == 0 || !IsValidEmail(u.Email) {
return InvalidUserError("email", u.Id)
}

View file

@ -15,11 +15,9 @@ import (
"net/http"
"net/mail"
"net/url"
"reflect"
"regexp"
"strconv"
"strings"
"testing"
"time"
"unicode"
@ -148,6 +146,46 @@ func GetMillis() int64 {
return time.Now().UnixNano() / int64(time.Millisecond)
}
// GetMillisForTime is a convience method to get milliseconds since epoch for provided Time.
func GetMillisForTime(thisTime time.Time) int64 {
return thisTime.UnixNano() / int64(time.Millisecond)
}
// ParseDateFilterToTime is a convience method to get Time from string
func ParseDateFilterToTime(filterString string) time.Time {
resultTime, err := time.Parse("2006-01-02", PadDateStringZeros(filterString))
if err != nil {
return time.Now()
}
return resultTime
}
// PadDateStringZeros is a convience method to pad 2 digit date parts with zeros to meet ISO 8601 format
func PadDateStringZeros(dateString string) string {
parts := strings.Split(dateString, "-")
for index, part := range parts {
if len(part) == 1 {
parts[index] = "0" + part
}
}
dateString = strings.Join(parts[:], "-")
return dateString
}
// GetStartOfDayMillis is a convience method to get milliseconds since epoch for provided date's start of day
func GetStartOfDayMillis(thisTime time.Time, timeZoneOffset int) int64 {
localSearchTimeZone := time.FixedZone("Local Search Time Zone", timeZoneOffset)
resultTime := time.Date(thisTime.Year(), thisTime.Month(), thisTime.Day(), 0, 0, 0, 0, localSearchTimeZone)
return GetMillisForTime(resultTime)
}
// GetEndOfDayMillis is a convience method to get milliseconds since epoch for provided date's end of day
func GetEndOfDayMillis(thisTime time.Time, timeZoneOffset int) int64 {
localSearchTimeZone := time.FixedZone("Local Search Time Zone", timeZoneOffset)
resultTime := time.Date(thisTime.Year(), thisTime.Month(), thisTime.Day(), 23, 59, 59, 999999999, localSearchTimeZone)
return GetMillisForTime(resultTime)
}
func CopyStringMap(originalMap map[string]string) map[string]string {
copyMap := make(map[string]string)
for k, v := range originalMap {
@ -263,7 +301,7 @@ func GetServerIpAddress() string {
} else {
for _, addr := range addrs {
if ip, ok := addr.(*net.IPNet); ok && !ip.IP.IsLoopback() {
if ip, ok := addr.(*net.IPNet); ok && !ip.IP.IsLoopback() && !ip.IP.IsLinkLocalUnicast() && !ip.IP.IsLinkLocalMulticast() {
if ip.IP.To4() != nil {
return ip.IP.String()
}
@ -279,16 +317,18 @@ func IsLower(s string) bool {
}
func IsValidEmail(email string) bool {
if !IsLower(email) {
return false
}
if _, err := mail.ParseAddress(email); err == nil {
return true
if addr, err := mail.ParseAddress(email); err != nil {
return false
} else if addr.Name != "" {
// mail.ParseAddress accepts input of the form "Billy Bob <billy@example.com>" which we don't allow
return false
}
return false
return true
}
var reservedName = []string{
@ -480,59 +520,56 @@ func IsValidId(value string) bool {
return true
}
// checkNowhereNil checks that the given interface value is not nil, and if a struct, that all of
// its public fields are also nowhere nil
func checkNowhereNil(t *testing.T, name string, value interface{}) bool {
if value == nil {
// Copied from https://golang.org/src/net/dnsclient.go#L119
func IsDomainName(s string) bool {
// See RFC 1035, RFC 3696.
// Presentation format has dots before every label except the first, and the
// terminal empty label is optional here because we assume fully-qualified
// (absolute) input. We must therefore reserve space for the first and last
// labels' length octets in wire format, where they are necessary and the
// maximum total length is 255.
// So our _effective_ maximum is 253, but 254 is not rejected if the last
// character is a dot.
l := len(s)
if l == 0 || l > 254 || l == 254 && s[l-1] != '.' {
return false
}
v := reflect.ValueOf(value)
switch v.Type().Kind() {
case reflect.Ptr:
if v.IsNil() {
t.Logf("%s was nil", name)
last := byte('.')
ok := false // Ok once we've seen a letter.
partlen := 0
for i := 0; i < len(s); i++ {
c := s[i]
switch {
default:
return false
}
return checkNowhereNil(t, fmt.Sprintf("(*%s)", name), v.Elem().Interface())
case reflect.Map:
if v.IsNil() {
t.Logf("%s was nil", name)
return false
}
// Don't check map values
return true
case reflect.Struct:
nowhereNil := true
for i := 0; i < v.NumField(); i++ {
f := v.Field(i)
// Ignore unexported fields
if v.Type().Field(i).PkgPath != "" {
continue
case 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z' || c == '_':
ok = true
partlen++
case '0' <= c && c <= '9':
// fine
partlen++
case c == '-':
// Byte before dash cannot be dot.
if last == '.' {
return false
}
nowhereNil = nowhereNil && checkNowhereNil(t, fmt.Sprintf("%s.%s", name, v.Type().Field(i).Name), f.Interface())
partlen++
case c == '.':
// Byte before dot cannot be dot, dash.
if last == '.' || last == '-' {
return false
}
if partlen > 63 || partlen == 0 {
return false
}
partlen = 0
}
return nowhereNil
case reflect.Array:
fallthrough
case reflect.Chan:
fallthrough
case reflect.Func:
fallthrough
case reflect.Interface:
fallthrough
case reflect.UnsafePointer:
t.Logf("unhandled field %s, type: %s", name, v.Type().Kind())
return false
default:
return true
last = c
}
if last == '-' || partlen > 63 {
return false
}
return ok
}

View file

@ -13,6 +13,8 @@ import (
// It should be maintained in chronological order with most current
// release at the front of the list.
var versions = []string{
"5.3.0",
"5.2.0",
"5.1.0",
"5.0.0",
"4.10.0",

View file

@ -1,60 +0,0 @@
// Copyright (c) 2016-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
package sqlstore
import (
"net/http"
"github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/store"
)
type SqlLicenseStore struct {
SqlStore
}
func NewSqlLicenseStore(sqlStore SqlStore) store.LicenseStore {
ls := &SqlLicenseStore{sqlStore}
for _, db := range sqlStore.GetAllConns() {
table := db.AddTableWithName(model.LicenseRecord{}, "Licenses").SetKeys(false, "Id")
table.ColMap("Id").SetMaxSize(26)
table.ColMap("Bytes").SetMaxSize(10000)
}
return ls
}
func (ls SqlLicenseStore) CreateIndexesIfNotExists() {
}
func (ls SqlLicenseStore) Save(license *model.LicenseRecord) store.StoreChannel {
return store.Do(func(result *store.StoreResult) {
license.PreSave()
if result.Err = license.IsValid(); result.Err != nil {
return
}
// Only insert if not exists
if err := ls.GetReplica().SelectOne(&model.LicenseRecord{}, "SELECT * FROM Licenses WHERE Id = :Id", map[string]interface{}{"Id": license.Id}); err != nil {
if err := ls.GetMaster().Insert(license); err != nil {
result.Err = model.NewAppError("SqlLicenseStore.Save", "store.sql_license.save.app_error", nil, "license_id="+license.Id+", "+err.Error(), http.StatusInternalServerError)
} else {
result.Data = license
}
}
})
}
func (ls SqlLicenseStore) Get(id string) store.StoreChannel {
return store.Do(func(result *store.StoreResult) {
if obj, err := ls.GetReplica().Get(model.LicenseRecord{}, id); err != nil {
result.Err = model.NewAppError("SqlLicenseStore.Get", "store.sql_license.get.app_error", nil, "license_id="+id+", "+err.Error(), http.StatusInternalServerError)
} else if obj == nil {
result.Err = model.NewAppError("SqlLicenseStore.Get", "store.sql_license.get.missing.app_error", nil, "license_id="+id, http.StatusNotFound)
} else {
result.Data = obj.(*model.LicenseRecord)
}
})
}

View file

@ -1,56 +0,0 @@
// Copyright (c) 2016-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
package storetest
import (
"testing"
"github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/store"
)
func TestLicenseStore(t *testing.T, ss store.Store) {
t.Run("Save", func(t *testing.T) { testLicenseStoreSave(t, ss) })
t.Run("Get", func(t *testing.T) { testLicenseStoreGet(t, ss) })
}
func testLicenseStoreSave(t *testing.T, ss store.Store) {
l1 := model.LicenseRecord{}
l1.Id = model.NewId()
l1.Bytes = "junk"
if err := (<-ss.License().Save(&l1)).Err; err != nil {
t.Fatal("couldn't save license record", err)
}
if err := (<-ss.License().Save(&l1)).Err; err != nil {
t.Fatal("shouldn't fail on trying to save existing license record", err)
}
l1.Id = ""
if err := (<-ss.License().Save(&l1)).Err; err == nil {
t.Fatal("should fail on invalid license", err)
}
}
func testLicenseStoreGet(t *testing.T, ss store.Store) {
l1 := model.LicenseRecord{}
l1.Id = model.NewId()
l1.Bytes = "junk"
store.Must(ss.License().Save(&l1))
if r := <-ss.License().Get(l1.Id); r.Err != nil {
t.Fatal("couldn't get license", r.Err)
} else {
if r.Data.(*model.LicenseRecord).Bytes != l1.Bytes {
t.Fatal("license bytes didn't match")
}
}
if err := (<-ss.License().Get("missing")).Err; err == nil {
t.Fatal("should fail on get license", err)
}
}

View file

@ -1,46 +0,0 @@
// Code generated by mockery v1.0.0
// Regenerate this file using `make store-mocks`.
package mocks
import mock "github.com/stretchr/testify/mock"
import model "github.com/mattermost/mattermost-server/model"
import store "github.com/mattermost/mattermost-server/store"
// LicenseStore is an autogenerated mock type for the LicenseStore type
type LicenseStore struct {
mock.Mock
}
// Get provides a mock function with given fields: id
func (_m *LicenseStore) Get(id string) store.StoreChannel {
ret := _m.Called(id)
var r0 store.StoreChannel
if rf, ok := ret.Get(0).(func(string) store.StoreChannel); ok {
r0 = rf(id)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(store.StoreChannel)
}
}
return r0
}
// Save provides a mock function with given fields: license
func (_m *LicenseStore) Save(license *model.LicenseRecord) store.StoreChannel {
ret := _m.Called(license)
var r0 store.StoreChannel
if rf, ok := ret.Get(0).(func(*model.LicenseRecord) store.StoreChannel); ok {
r0 = rf(license)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(store.StoreChannel)
}
}
return r0
}

View file

@ -1,157 +0,0 @@
// Copyright (c) 2016-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
package utils
import (
"crypto"
"crypto/rsa"
"crypto/sha512"
"crypto/x509"
"encoding/base64"
"encoding/pem"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strconv"
"strings"
"github.com/mattermost/mattermost-server/mlog"
"github.com/mattermost/mattermost-server/model"
)
var publicKey []byte = []byte(`-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyZmShlU8Z8HdG0IWSZ8r
tSyzyxrXkJjsFUf0Ke7bm/TLtIggRdqOcUF3XEWqQk5RGD5vuq7Rlg1zZqMEBk8N
EZeRhkxyaZW8pLjxwuBUOnXfJew31+gsTNdKZzRjrvPumKr3EtkleuoxNdoatu4E
HrKmR/4Yi71EqAvkhk7ZjQFuF0osSWJMEEGGCSUYQnTEqUzcZSh1BhVpkIkeu8Kk
1wCtptODixvEujgqVe+SrE3UlZjBmPjC/CL+3cYmufpSNgcEJm2mwsdaXp2OPpfn
a0v85XL6i9ote2P+fLZ3wX9EoioHzgdgB7arOxY50QRJO7OyCqpKFKv6lRWTXuSt
hwIDAQAB
-----END PUBLIC KEY-----`)
func ValidateLicense(signed []byte) (bool, string) {
decoded := make([]byte, base64.StdEncoding.DecodedLen(len(signed)))
_, err := base64.StdEncoding.Decode(decoded, signed)
if err != nil {
mlog.Error(fmt.Sprintf("Encountered error decoding license, err=%v", err.Error()))
return false, ""
}
if len(decoded) <= 256 {
mlog.Error("Signed license not long enough")
return false, ""
}
// remove null terminator
for decoded[len(decoded)-1] == byte(0) {
decoded = decoded[:len(decoded)-1]
}
plaintext := decoded[:len(decoded)-256]
signature := decoded[len(decoded)-256:]
block, _ := pem.Decode(publicKey)
public, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
mlog.Error(fmt.Sprintf("Encountered error signing license, err=%v", err.Error()))
return false, ""
}
rsaPublic := public.(*rsa.PublicKey)
h := sha512.New()
h.Write(plaintext)
d := h.Sum(nil)
err = rsa.VerifyPKCS1v15(rsaPublic, crypto.SHA512, d, signature)
if err != nil {
mlog.Error(fmt.Sprintf("Invalid signature, err=%v", err.Error()))
return false, ""
}
return true, string(plaintext)
}
func GetAndValidateLicenseFileFromDisk(location string) (*model.License, []byte) {
fileName := GetLicenseFileLocation(location)
if _, err := os.Stat(fileName); err != nil {
mlog.Debug(fmt.Sprintf("We could not find the license key in the database or on disk at %v", fileName))
return nil, nil
}
mlog.Info(fmt.Sprintf("License key has not been uploaded. Loading license key from disk at %v", fileName))
licenseBytes := GetLicenseFileFromDisk(fileName)
if success, licenseStr := ValidateLicense(licenseBytes); !success {
mlog.Error(fmt.Sprintf("Found license key at %v but it appears to be invalid.", fileName))
return nil, nil
} else {
return model.LicenseFromJson(strings.NewReader(licenseStr)), licenseBytes
}
}
func GetLicenseFileFromDisk(fileName string) []byte {
file, err := os.Open(fileName)
if err != nil {
mlog.Error(fmt.Sprintf("Failed to open license key from disk at %v err=%v", fileName, err.Error()))
return nil
}
defer file.Close()
licenseBytes, err := ioutil.ReadAll(file)
if err != nil {
mlog.Error(fmt.Sprintf("Failed to read license key from disk at %v err=%v", fileName, err.Error()))
return nil
}
return licenseBytes
}
func GetLicenseFileLocation(fileLocation string) string {
if fileLocation == "" {
configDir, _ := FindDir("config")
return filepath.Join(configDir, "mattermost.mattermost-license")
} else {
return fileLocation
}
}
func GetClientLicense(l *model.License) map[string]string {
props := make(map[string]string)
props["IsLicensed"] = strconv.FormatBool(l != nil)
if l != nil {
props["Id"] = l.Id
props["Users"] = strconv.Itoa(*l.Features.Users)
props["LDAP"] = strconv.FormatBool(*l.Features.LDAP)
props["MFA"] = strconv.FormatBool(*l.Features.MFA)
props["SAML"] = strconv.FormatBool(*l.Features.SAML)
props["Cluster"] = strconv.FormatBool(*l.Features.Cluster)
props["Metrics"] = strconv.FormatBool(*l.Features.Metrics)
props["GoogleOAuth"] = strconv.FormatBool(*l.Features.GoogleOAuth)
props["Office365OAuth"] = strconv.FormatBool(*l.Features.Office365OAuth)
props["Compliance"] = strconv.FormatBool(*l.Features.Compliance)
props["MHPNS"] = strconv.FormatBool(*l.Features.MHPNS)
props["Announcement"] = strconv.FormatBool(*l.Features.Announcement)
props["Elasticsearch"] = strconv.FormatBool(*l.Features.Elasticsearch)
props["DataRetention"] = strconv.FormatBool(*l.Features.DataRetention)
props["IssuedAt"] = strconv.FormatInt(l.IssuedAt, 10)
props["StartsAt"] = strconv.FormatInt(l.StartsAt, 10)
props["ExpiresAt"] = strconv.FormatInt(l.ExpiresAt, 10)
props["Name"] = l.Customer.Name
props["Email"] = l.Customer.Email
props["Company"] = l.Customer.Company
props["PhoneNumber"] = l.Customer.PhoneNumber
props["EmailNotificationContents"] = strconv.FormatBool(*l.Features.EmailNotificationContents)
props["MessageExport"] = strconv.FormatBool(*l.Features.MessageExport)
props["CustomPermissionsSchemes"] = strconv.FormatBool(*l.Features.CustomPermissionsSchemes)
}
return props
}

View file

@ -16,27 +16,27 @@ var (
DefaultUrlSchemes = []string{"http", "https", "ftp", "mailto", "tel"}
)
// Given a string with a w at the given position, tries to parse and return a link starting with "www."
// Given a string with a w at the given position, tries to parse and return a range containing a www link.
// if one exists. If the text at the given position isn't a link, returns an empty string. Equivalent to
// www_match from the reference code.
func parseWWWAutolink(data string, position int) string {
func parseWWWAutolink(data string, position int) (Range, bool) {
// Check that this isn't part of another word
if position > 1 {
prevChar := data[position-1]
if !isWhitespaceByte(prevChar) && !isAllowedBeforeWWWLink(prevChar) {
return ""
return Range{}, false
}
}
// Check that this starts with www
if len(data)-position < 4 || !regexp.MustCompile(`^www\d{0,3}\.`).MatchString(data[position:]) {
return ""
return Range{}, false
}
end := checkDomain(data[position:], false)
if end == 0 {
return ""
return Range{}, false
}
end += position
@ -47,12 +47,12 @@ func parseWWWAutolink(data string, position int) string {
}
// Trim trailing punctuation
link := trimTrailingCharactersFromLink(data[position:end])
if link == "" {
return ""
end = trimTrailingCharactersFromLink(data, position, end)
if position == end {
return Range{}, false
}
return link
return Range{position, end}, true
}
func isAllowedBeforeWWWLink(c byte) bool {
@ -64,13 +64,13 @@ func isAllowedBeforeWWWLink(c byte) bool {
}
}
// Given a string with a : at the given position, tried to parse and return a link starting with a URL scheme
// Given a string with a : at the given position, tried to parse and return a range containing a URL scheme
// if one exists. If the text around the given position isn't a link, returns an empty string. Equivalent to
// url_match from the reference code.
func parseURLAutolink(data string, position int) string {
func parseURLAutolink(data string, position int) (Range, bool) {
// Check that a :// exists. This doesn't match the clients that treat the slashes as optional.
if len(data)-position < 4 || data[position+1] != '/' || data[position+2] != '/' {
return ""
return Range{}, false
}
start := position - 1
@ -81,12 +81,12 @@ func parseURLAutolink(data string, position int) string {
// Ensure that the URL scheme is allowed and that at least one character after the scheme is valid.
scheme := data[start:position]
if !isSchemeAllowed(scheme) || !isValidHostCharacter(data[position+3:]) {
return ""
return Range{}, false
}
end := checkDomain(data[position+3:], true)
if end == 0 {
return ""
return Range{}, false
}
end += position
@ -97,12 +97,12 @@ func parseURLAutolink(data string, position int) string {
}
// Trim trailing punctuation
link := trimTrailingCharactersFromLink(data[start:end])
if link == "" {
return ""
end = trimTrailingCharactersFromLink(data, start, end)
if start == end {
return Range{}, false
}
return link
return Range{start, end}, true
}
func isSchemeAllowed(scheme string) bool {
@ -166,9 +166,9 @@ func isValidHostCharacter(link string) bool {
}
// Removes any trailing characters such as punctuation or stray brackets that shouldn't be part of the link.
// Equivalent to autolink_delim from the reference code.
func trimTrailingCharactersFromLink(link string) string {
runes := []rune(link)
// Returns a new end position for the link. Equivalent to autolink_delim from the reference code.
func trimTrailingCharactersFromLink(markdown string, start int, end int) int {
runes := []rune(markdown[start:end])
linkEnd := len(runes)
// Cut off the link before an open angle bracket if it contains one
@ -240,7 +240,7 @@ func trimTrailingCharactersFromLink(link string) string {
}
}
return string(runes[:linkEnd])
return start + len(string(runes[:linkEnd]))
}
func canEndAutolink(c rune) bool {

View file

@ -157,7 +157,7 @@ func RenderInlineHTML(inline Inline) (result string) {
}
result += "</a>"
case *Autolink:
result += `<a href="` + htmlEscaper.Replace(escapeURL(v.Link)) + `">`
result += `<a href="` + htmlEscaper.Replace(escapeURL(v.Destination())) + `">`
for _, inline := range v.Children {
result += RenderInlineHTML(inline)
}

View file

@ -86,7 +86,19 @@ type Autolink struct {
Children []Inline
Link string
RawDestination Range
markdown string
}
func (i *Autolink) Destination() string {
destination := Unescape(i.markdown[i.RawDestination.Position:i.RawDestination.End])
if strings.HasPrefix(destination, "www") {
destination = "http://" + destination
}
return destination
}
type delimiterType int
@ -254,7 +266,7 @@ func (p *inlineParser) parseLinkOrImageDelimiter() {
}
}
func (p *inlineParser) peekAtInlineLinkDestinationAndTitle(position int) (destination, title Range, end int, ok bool) {
func (p *inlineParser) peekAtInlineLinkDestinationAndTitle(position int, isImage bool) (destination, title Range, end int, ok bool) {
if position >= len(p.raw) || p.raw[position] != '(' {
return
}
@ -273,6 +285,23 @@ func (p *inlineParser) peekAtInlineLinkDestinationAndTitle(position int) (destin
}
position = end
if isImage && position < len(p.raw) && isWhitespaceByte(p.raw[position]) {
dimensionsStart := nextNonWhitespace(p.raw, position)
if dimensionsStart >= len(p.raw) {
return
}
if p.raw[dimensionsStart] == '=' {
// Read optional image dimensions even if we don't use them
_, end, ok = parseImageDimensions(p.raw, dimensionsStart)
if !ok {
return
}
position = end
}
}
if position < len(p.raw) && isWhitespaceByte(p.raw[position]) {
titleStart := nextNonWhitespace(p.raw, position)
if titleStart >= len(p.raw) {
@ -281,11 +310,13 @@ func (p *inlineParser) peekAtInlineLinkDestinationAndTitle(position int) (destin
return destination, Range{titleStart, titleStart}, titleStart + 1, true
}
title, end, ok = parseLinkTitle(p.raw, titleStart)
if !ok {
return
if p.raw[titleStart] == '"' || p.raw[titleStart] == '\'' || p.raw[titleStart] == '(' {
title, end, ok = parseLinkTitle(p.raw, titleStart)
if !ok {
return
}
position = end
}
position = end
}
closingPosition := nextNonWhitespace(p.raw, position)
@ -317,9 +348,11 @@ func (p *inlineParser) lookForLinkOrImage() {
break
}
isImage := d.Type == imageOpeningDelimiter
var inline Inline
if destination, title, next, ok := p.peekAtInlineLinkDestinationAndTitle(p.position + 1); ok {
if destination, title, next, ok := p.peekAtInlineLinkDestinationAndTitle(p.position+1, isImage); ok {
destinationMarkdownPosition := relativeToAbsolutePosition(p.ranges, destination.Position)
linkOrImage := InlineLinkOrImage{
Children: append([]Inline(nil), p.inlines[d.TextNode+1:]...),
@ -465,15 +498,18 @@ func (p *inlineParser) parseAutolink(c rune) bool {
}
}
link := ""
text := ""
var link Range
if c == ':' {
text = parseURLAutolink(p.raw, p.position)
link = text
var ok bool
link, ok = parseURLAutolink(p.raw, p.position)
if !ok {
return false
}
// Since the current position is at the colon, we have to rewind the parsing slightly so that
// we don't duplicate the URL scheme
rewind := strings.Index(text, ":")
rewind := strings.Index(p.raw[link.Position:link.End], ":")
if rewind != -1 {
lastInline := p.inlines[len(p.inlines)-1]
lastText, ok := lastInline.(*Text)
@ -491,22 +527,30 @@ func (p *inlineParser) parseAutolink(c rune) bool {
Range: Range{lastText.Range.Position, lastText.Range.End - rewind},
})
p.position -= rewind
}
} else if c == 'w' {
text = parseWWWAutolink(p.raw, p.position)
link = "http://" + text
} else if c == 'w' || c == 'W' {
var ok bool
link, ok = parseWWWAutolink(p.raw, p.position)
if !ok {
return false
}
}
if text == "" {
return false
}
linkMarkdownPosition := relativeToAbsolutePosition(p.ranges, link.Position)
linkRange := Range{linkMarkdownPosition, linkMarkdownPosition + link.End - link.Position}
p.inlines = append(p.inlines, &Autolink{
Link: link,
Children: []Inline{&Text{Text: text}},
Children: []Inline{
&Text{
Text: p.raw[link.Position:link.End],
Range: linkRange,
},
},
RawDestination: linkRange,
markdown: p.markdown,
})
p.position += len(text)
p.position += (link.End - link.Position)
return true
}

View file

@ -128,3 +128,57 @@ func parseLinkLabel(markdown string, position int) (raw Range, next int, ok bool
return
}
// As a non-standard feature, we allow image links to specify dimensions of the image by adding "=WIDTHxHEIGHT"
// after the image destination but before the image title like ![alt](http://example.com/image.png =100x200 "title").
// Both width and height are optional, but at least one of them must be specified.
func parseImageDimensions(markdown string, position int) (raw Range, next int, ok bool) {
if position >= len(markdown) {
return
}
originalPosition := position
// Read =
position += 1
if position >= len(markdown) {
return
}
// Read width
hasWidth := false
for isNumericByte(markdown[position]) {
hasWidth = true
position += 1
}
// Look for early end of dimensions
if isWhitespaceByte(markdown[position]) || markdown[position] == ')' {
return Range{originalPosition, position - 1}, position, true
}
// Read the x
if markdown[position] != 'x' && markdown[position] != 'X' {
return
}
position += 1
// Read height
hasHeight := false
for isNumericByte(markdown[position]) {
hasHeight = true
position += 1
}
// Make sure the there's no trailing characters
if !isWhitespaceByte(markdown[position]) && markdown[position] != ')' {
return
}
if !hasWidth && !hasHeight {
// At least one of width or height is required
return
}
return Range{originalPosition, position - 1}, position, true
}

View file

@ -32,8 +32,16 @@ func isWhitespaceByte(c byte) bool {
return isWhitespace(rune(c))
}
func isNumeric(c rune) bool {
return c >= '0' && c <= '9'
}
func isNumericByte(c byte) bool {
return isNumeric(rune(c))
}
func isHex(c rune) bool {
return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')
return isNumeric(c) || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')
}
func isHexByte(c byte) bool {
@ -41,7 +49,7 @@ func isHexByte(c byte) bool {
}
func isAlphanumeric(c rune) bool {
return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')
return isNumeric(c) || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')
}
func isAlphanumericByte(c byte) bool {

265
server/Gopkg.lock generated
View file

@ -2,105 +2,302 @@
[[projects]]
branch = "master"
digest = "1:b7ffca49e9cfd3dfb04a8e0a59347708c6f78f68476a32c5e0a0edca5d1b258c"
name = "github.com/dustin/go-humanize"
packages = ["."]
pruneopts = "NUT"
revision = "9f541cc9db5d55bce703bd99987c9d5cb8eea45e"
[[projects]]
digest = "1:1b91ae0dc69a41d4c2ed23ea5cffb721ea63f5037ca4b81e6d6771fbb8f45129"
name = "github.com/fsnotify/fsnotify"
packages = ["."]
pruneopts = "NUT"
revision = "c2828203cd70a50dcccfb2761f8b1f8ceef9a8e9"
version = "v1.4.7"
[[projects]]
digest = "1:74d9b0a7b4107b41e0ade759fac64502876f82d29fb23d77b3dd24b194ee3dd5"
name = "github.com/go-ini/ini"
packages = ["."]
pruneopts = "NUT"
revision = "5cf292cae48347c2490ac1a58fe36735fb78df7e"
version = "v1.38.2"
[[projects]]
digest = "1:03e14cff610a8a58b774e36bd337fa979482be86aab01be81fb8bbd6d0f07fc8"
name = "github.com/golang/protobuf"
packages = [
"proto",
"ptypes",
"ptypes/any",
"ptypes/duration",
"ptypes/timestamp"
"ptypes/timestamp",
]
pruneopts = "NUT"
revision = "b4deda0973fb4c70b50d226b1af49f3da59f5265"
version = "v1.1.0"
[[projects]]
branch = "master"
digest = "1:a838a4e94519e82fa33bf3be99885403cabe80d60a0eeda6b302d01d2e30f2e2"
name = "github.com/gorilla/websocket"
packages = ["."]
pruneopts = "NUT"
revision = "5ed622c449da6d44c3c8329331ff47a9e5844f71"
[[projects]]
digest = "1:58ba5285227b0f635652cd4aa82c4cfd00b590191eadd823462f0c9f64e3ae07"
name = "github.com/hashicorp/go-hclog"
packages = ["."]
pruneopts = "NUT"
revision = "69ff559dc25f3b435631604f573a5fa1efdb6433"
[[projects]]
digest = "1:532090ffc3b05a7e4c0229dd2698d79149f2e0683df993224a8b202f607fb605"
name = "github.com/hashicorp/go-plugin"
packages = ["."]
pruneopts = "NUT"
revision = "e8d22c780116115ae5624720c9af0c97afe4f551"
[[projects]]
digest = "1:11c6c696067d3127ecf332b10f89394d386d9083f82baf71f40f2da31841a009"
name = "github.com/hashicorp/hcl"
packages = [
".",
"hcl/ast",
"hcl/parser",
"hcl/printer",
"hcl/scanner",
"hcl/strconv",
"hcl/token",
"json/parser",
"json/scanner",
"json/token",
]
pruneopts = "NUT"
revision = "8cb6e5b959231cc1119e43259c4a608f9c51a241"
version = "v1.0.0"
[[projects]]
branch = "master"
digest = "1:63e0b20cfa3fe456480edf93a7995f776afb610e49da8e3da04d8904472a44cc"
name = "github.com/hashicorp/yamux"
packages = ["."]
pruneopts = "NUT"
revision = "3520598351bb3500a49ae9563f5539666ae0a27c"
[[projects]]
branch = "master"
digest = "1:37eb5dfae485ce9985b61640b6ede63f2a58898efdda6a9a94f1794df62f9147"
name = "github.com/jaytaylor/html2text"
packages = ["."]
pruneopts = "NUT"
revision = "57d518f124b0cf46ea2021f25a01396b3522e6fb"
[[projects]]
digest = "1:d244f8666a838fe6ad70ec8fe77f50ebc29fdc3331a2729ba5886bef8435d10d"
name = "github.com/magiconair/properties"
packages = ["."]
pruneopts = "NUT"
revision = "c2353362d570a7bfa228149c62842019201cfb71"
version = "v1.8.0"
[[projects]]
digest = "1:38ba2dacfd4596f2543e168b03af8f514da5fea53ef43af4a7b95368f759bffb"
name = "github.com/mattermost/mattermost-server"
packages = [
"einterfaces",
"mlog",
"model",
"plugin",
"utils",
"utils/jsonutils",
"utils/markdown"
"utils/markdown",
]
revision = "90e5e279c175b238d58432acb5eb6422ddfe22e7"
pruneopts = "NUT"
revision = "fd21e53365d504155ab87f9bef60b1ab4faeb38d"
version = "v5.3.1"
[[projects]]
branch = "mattermost"
digest = "1:2fe4ce644afe513a2d2455f5d14a79e57345c658a1a1b9214d3f1769bacbdef8"
name = "github.com/mattermost/viper"
packages = ["."]
pruneopts = "NUT"
revision = "1b00ce64485c7a2449f239de3cbc9040a9c46aa0"
source = "https://github.com/mattermost/viper"
[[projects]]
digest = "1:bff482b22ebed387378546ba6a7850fdef87fd47f8ee58a7c62124a8e889a56b"
name = "github.com/mattn/go-runewidth"
packages = ["."]
pruneopts = "NUT"
revision = "ce7b0b5c7b45a81508558cd1dba6bb1e4ddb51bb"
version = "v0.0.3"
[[projects]]
digest = "1:1df80bcac9dcdeca8c3af103b95abff4c0015fa4dd0880eb0af13fdf9f602f89"
name = "github.com/minio/minio-go"
packages = [
".",
"pkg/credentials",
"pkg/encrypt",
"pkg/s3signer",
"pkg/s3utils",
"pkg/set",
]
pruneopts = "NUT"
revision = "e8c97c88468e122f161683409cde02dc89a2961c"
version = "v6.0.7"
[[projects]]
digest = "1:a4df73029d2c42fabcb6b41e327d2f87e685284ec03edf76921c267d9cfc9c23"
name = "github.com/mitchellh/go-homedir"
packages = ["."]
pruneopts = "NUT"
revision = "ae18d6b8b3205b561c79e8e5f69bff09736185f4"
version = "v1.0.0"
[[projects]]
branch = "master"
digest = "1:18b773b92ac82a451c1276bd2776c1e55ce057ee202691ab33c8d6690efcc048"
name = "github.com/mitchellh/go-testing-interface"
packages = ["."]
pruneopts = "NUT"
revision = "a61a99592b77c9ba629d254a693acffaeb4b7e28"
[[projects]]
digest = "1:5fe20cfe4ef484c237cec9f947b2a6fa90bad4b8610fd014f0e4211e13d82d5d"
name = "github.com/mitchellh/mapstructure"
packages = ["."]
pruneopts = "NUT"
revision = "fa473d140ef3c6adf42d6b391fe76707f1f243c8"
version = "v1.0.0"
[[projects]]
digest = "1:07140002dbf37da92090f731b46fa47be4820b82fe5c14a035203b0e813d0ec2"
name = "github.com/nicksnyder/go-i18n"
packages = [
"i18n",
"i18n/bundle",
"i18n/language",
"i18n/translation"
"i18n/translation",
]
pruneopts = "NUT"
revision = "0dc1626d56435e9d605a29875701721c54bc9bbd"
version = "v1.10.0"
[[projects]]
digest = "1:3b517122f3aad1ecce45a630ea912b3092b4729f25532a911d0cb2935a1f9352"
name = "github.com/oklog/run"
packages = ["."]
pruneopts = "NUT"
revision = "4dadeb3030eda0273a12382bb2348ffc7c9d1a39"
version = "v1.0.0"
[[projects]]
branch = "master"
digest = "1:e6baebf0bd20950e285254902a8f2241b4870528fb63fdc10460c67b1f31b1a3"
name = "github.com/olekukonko/tablewriter"
packages = ["."]
pruneopts = "NUT"
revision = "be2c049b30ccd4d3fd795d6bf7dce74e42eeedaa"
[[projects]]
digest = "1:cce3a18fb0b96b5015cd8ca03a57d20a662679de03c4dc4b6ff5f17ea2050fa6"
name = "github.com/pborman/uuid"
packages = ["."]
pruneopts = "NUT"
revision = "e790cca94e6cc75c7064b1332e63811d4aae1a53"
version = "v1.1"
[[projects]]
digest = "1:51ea800cff51752ff68e12e04106f5887b4daec6f9356721238c28019f0b42db"
name = "github.com/pelletier/go-toml"
packages = ["."]
pruneopts = "NUT"
revision = "c01d1270ff3e442a8a57cddc1c92dc1138598194"
version = "v1.2.0"
[[projects]]
digest = "1:5cf3f025cbee5951a4ee961de067c8a89fc95a5adabead774f82822efabab121"
name = "github.com/pkg/errors"
packages = ["."]
pruneopts = "NUT"
revision = "645ef00459ed84a119197bfb8d8205042c6df63d"
version = "v0.8.0"
[[projects]]
digest = "1:b2339e83ce9b5c4f79405f949429a7f68a9a904fed903c672aac1e7ceb7f5f02"
name = "github.com/sirupsen/logrus"
packages = ["."]
pruneopts = "NUT"
revision = "3e01752db0189b9157070a0e1668a620f9a85da2"
version = "v1.0.6"
[[projects]]
digest = "1:330e9062b308ac597e28485699c02223bd052437a6eed32a173c9227dcb9d95a"
name = "github.com/spf13/afero"
packages = [
".",
"mem",
]
pruneopts = "NUT"
revision = "d40851caa0d747393da1ffb28f7f9d8b4eeffebd"
version = "v1.1.2"
[[projects]]
digest = "1:3fa7947ca83b98ae553590d993886e845a4bff19b7b007e869c6e0dd3b9da9cd"
name = "github.com/spf13/cast"
packages = ["."]
pruneopts = "NUT"
revision = "8965335b8c7107321228e3e3702cab9832751bac"
version = "v1.2.0"
[[projects]]
digest = "1:f29f83301ed096daed24a90f4af591b7560cb14b9cc3e1827abbf04db7269ab5"
name = "github.com/spf13/jwalterweatherman"
packages = ["."]
pruneopts = "NUT"
revision = "4a4406e478ca629068e7768fc33f3f044173c0a6"
version = "v1.0.0"
[[projects]]
digest = "1:e3707aeaccd2adc89eba6c062fec72116fe1fc1ba71097da85b4d8ae1668a675"
name = "github.com/spf13/pflag"
packages = ["."]
pruneopts = "NUT"
revision = "9a97c102cda95a86cec2345a6f09f55a939babf5"
version = "v1.0.2"
[[projects]]
branch = "master"
digest = "1:b0bd1fe27879214f4175ca8efdd73e672de8c8c662d705cdd63dcca7cd9c8f14"
name = "github.com/ssor/bom"
packages = ["."]
pruneopts = "NUT"
revision = "6386211fdfcf24c0bfbdaceafd02849ed9a8a509"
[[projects]]
digest = "1:22f696cee54865fb8e9ff91df7b633f6b8f22037a8015253c6b6a71ca82219c7"
name = "go.uber.org/atomic"
packages = ["."]
pruneopts = "NUT"
revision = "1ea20fb1cbb1cc08cbd0d913a96dead89aa18289"
version = "v1.3.2"
[[projects]]
digest = "1:58ca93bdf81bac106ded02226b5395a0595d5346cdc4caa8d9c1f3a5f8f9976e"
name = "go.uber.org/multierr"
packages = ["."]
pruneopts = "NUT"
revision = "3c4937480c32f4c13a875a1829af76c98ca3d40a"
version = "v1.1.0"
[[projects]]
digest = "1:62c528643cd9de4e18c81ae52a5f0ec8a92c276259203bd1f19e33532bcb1af3"
name = "go.uber.org/zap"
packages = [
".",
@ -108,35 +305,58 @@
"internal/bufferpool",
"internal/color",
"internal/exit",
"zapcore"
"zapcore",
]
pruneopts = "NUT"
revision = "4d45f9617f7d90f7a663ff21c7a4321dbe78098b"
version = "v1.9.0"
[[projects]]
branch = "master"
digest = "1:d652c5a89f671eb69b2697f659e83a07a5305958ba9466210f88c62f8fe3c729"
name = "golang.org/x/crypto"
packages = [
"argon2",
"bcrypt",
"blowfish"
"blake2b",
"blowfish",
"ssh/terminal",
]
pruneopts = "NUT"
revision = "c126467f60eb25f8f27e5a981f32a87e3965053f"
[[projects]]
branch = "master"
digest = "1:c5bba5e56117aa149629d69adcc7696156b09cfde1095ea5e6323ab20b83a624"
name = "golang.org/x/net"
packages = [
"context",
"html",
"html/atom",
"http/httpguts",
"http2",
"http2/hpack",
"idna",
"internal/timeseries",
"trace"
"trace",
]
pruneopts = "NUT"
revision = "3673e40ba22529d22c3fd7c93e97b0ce50fa7bdd"
[[projects]]
branch = "master"
digest = "1:f298f3bca4dafa2f16d87d3e12201ea541aa47d107357dace6b5915e374460dc"
name = "golang.org/x/sys"
packages = [
"cpu",
"unix",
"windows",
]
pruneopts = "NUT"
revision = "d47a0f3392421c5624713c9a19fe781f651f8a50"
[[projects]]
digest = "1:e7071ed636b5422cc51c0e3a6cebc229d6c9fffc528814b519a980641422d619"
name = "golang.org/x/text"
packages = [
"collate",
@ -152,18 +372,22 @@
"unicode/bidi",
"unicode/cldr",
"unicode/norm",
"unicode/rangetable"
"unicode/rangetable",
]
pruneopts = "NUT"
revision = "f21a4dfb5e38f5895301dc265a8def02365cc3d0"
version = "v0.3.0"
[[projects]]
branch = "master"
digest = "1:077c1c599507b3b3e9156d17d36e1e61928ee9b53a5b420f10f28ebd4a0b275c"
name = "google.golang.org/genproto"
packages = ["googleapis/rpc/status"]
pruneopts = "NUT"
revision = "2a72893556e4d1f6c795a4c039314c9fa751eedb"
[[projects]]
digest = "1:04403ed28896279b683ae57464170afd8e196c273feeb853f0347fe0015b525c"
name = "google.golang.org/grpc"
packages = [
".",
@ -192,26 +416,47 @@
"stats",
"status",
"tap",
"transport"
"transport",
]
pruneopts = "NUT"
revision = "168a6198bcb0ef175f7dacec0b8691fc141dc9b8"
version = "v1.13.0"
[[projects]]
branch = "v3"
digest = "1:1244a9b3856f70d5ffb74bbfd780fc9d47f93f2049fa265c6fb602878f507bf8"
name = "gopkg.in/alexcesaro/quotedprintable.v3"
packages = ["."]
pruneopts = "NUT"
revision = "2caba252f4dc53eaf6b553000885530023f54623"
[[projects]]
digest = "1:d852dd703c644c976246382fe1539e8585cc20d642d3e68d3dff8de952237497"
name = "gopkg.in/gomail.v2"
packages = ["."]
pruneopts = "NUT"
revision = "41f3572897373c5538c50a2402db15db079fa4fd"
version = "2.0.0"
[[projects]]
digest = "1:80c34337e8a734e190f2d1b716cae774cca74db98315166f92074434e9af0227"
name = "gopkg.in/natefinch/lumberjack.v2"
packages = ["."]
pruneopts = "NUT"
revision = "a96e63847dc3c67d17befa69c303767e2f84e54f"
version = "v2.1"
[[projects]]
digest = "1:7c95b35057a0ff2e19f707173cc1a947fa43a6eb5c4d300d196ece0334046082"
name = "gopkg.in/yaml.v2"
packages = ["."]
pruneopts = "NUT"
revision = "5420a8b6744d3b0345ab293f6fcba19c978f1183"
version = "v2.2.1"
[solve-meta]
analyzer-name = "dep"
analyzer-version = 1
inputs-digest = "c1eff11164e1bf0cb3166b06ee6a00156d50942f28a37251bc905d9dcb9db231"
input-imports = ["github.com/mattermost/mattermost-server/plugin"]
solver-name = "gps-cdcl"
solver-version = 1

View file

@ -1,34 +1,8 @@
# Gopkg.toml example
#
# Refer to https://github.com/golang/dep/blob/master/docs/Gopkg.toml.md
# for detailed Gopkg.toml documentation.
#
# required = ["github.com/user/thing/cmd/thing"]
# ignored = ["github.com/user/project/pkgX", "bitbucket.org/user/project/pkgA/pkgY"]
#
# [[constraint]]
# name = "github.com/user/project"
# version = "1.0.0"
#
# [[constraint]]
# name = "github.com/user/project2"
# branch = "dev"
# source = "github.com/myfork/project2"
#
# [[override]]
# name = "github.com/x/y"
# version = "2.4.0"
#
# [prune]
# non-go = false
# go-tests = true
# unused-packages = true
[prune]
non-go = true
go-tests = true
unused-packages = true
[[constraint]]
name = "github.com/mattermost/mattermost-server"
branch = "master"
[prune]
go-tests = true
unused-packages = true
version = "~5.3.0"