Compare commits

..

39 Commits

Author SHA1 Message Date
6543
55e159ca5f Changelog v1.14.0 (#15360)
* clean & merge & update v1.14.0 changelog

* backport v1.13.x changelogs
2021-04-11 06:07:02 +02:00
Lunny Xiao
87074ec860 Fix delete nonexist oauth application 500 and prevent deadlock (#15384) (#15396)
* Fix delete nonexist oauth application 500

* Fix test

* Close the session

* Fix more missed sess.Close

* Remove unnecessary blank line

Signed-off-by: Andrew Thornton <art27@cantab.net>
Co-authored-by: Andrew Thornton <art27@cantab.net>
Co-authored-by: 6543 <6543@obermui.de>
2021-04-11 04:57:44 +02:00
zeripath
1fe5fe419e Always set the merge base used to merge the commit (#15352) (#15385)
Backport #15352

The issue is that the TestPatch will reset the PR MergeBase - and it is possible for TestPatch to update the MergeBase whilst a merge is ongoing. The ensuing merge will then complete but it doesn't re-set the MergeBase it used to merge the PR.

Fixes the intermittent error in git test.

Signed-off-by: Andrew Thornton art27@cantab.net
2021-04-10 14:08:30 +02:00
zeripath
67a12b8fac Turn RepoRef and RepoAssignment back into func(*Context) (#15372) (#15377)
Backport #15372

Signed-off-by: Andrew Thornton <art27@cantab.net>

Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
2021-04-09 22:24:40 -04:00
silverwind
e861dcbbaf Dropzone styling improvements (#15291) (#15374)
* Dropzone styling improvements

- Move all dropzone styles to separate file
- Fix white background in arc-green
- Fix rendering of non-square images and previews

* increase thumbnail quality, set contain in js, replace blur effect with opacity

Co-authored-by: techknowlogick <techknowlogick@gitea.io>
2021-04-09 19:43:36 -04:00
zeripath
53c2136a9a Upgrade to bluemonday 1.0.7 (#15379) (#15380)
* Upgrade to bluemonday 1.0.7 (#15379)

Backport #15379

Fix #15349

Signed-off-by: Andrew Thornton <art27@cantab.net>

* resolve CI

Co-authored-by: techknowlogick <techknowlogick@gitea.io>
2021-04-09 19:41:30 -04:00
zeripath
24ebc7e517 Move FCGI req.URL.Path fix-up to the FCGI listener (#15292) (#15361)
Backport #15292

Simplify the web.go FCGI path by moving the req.URL.Path fix-up to listener

Signed-off-by: Andrew Thornton <art27@cantab.net>
2021-04-09 17:45:02 +01:00
6543
b072907987 Fix admin user list (#15358) (#15359)
* Fix `admin user list` (#15358)

* fix routers/api/v1/repo/issue.go
2021-04-09 12:39:40 +02:00
silverwind
942b0360ad Fix button border issue (#15351) 2021-04-09 05:38:06 +02:00
silverwind
1ec4913add Disable cssnano's colormin plugin (#15348)
It produces odd rgba values which also seem to cause issues in monaco's
color parser where the scoll shadow went red for some reason.

Regression by: https://github.com/go-gitea/gitea/pull/15333
2021-04-09 03:54:24 +02:00
zeripath
16e34025b4 Show diff on rename with diff changes (#15338) (#15339)
Backport #15338

More recent versions of git have increased support for detection of renames meaning
that a rename with diff changes is now supported.

Although ParsePatch supports this - our templates do not and the simplest solution
is simply to show the diff.

Fix #15335

Signed-off-by: Andrew Thornton <art27@cantab.net>

Co-authored-by: 6543 <6543@obermui.de>
2021-04-08 15:36:17 -04:00
zeripath
456d63b6cf Prepend AppSubUrl to links for default avatar (#15341) (#15342)
Backport #15341

Fix #15334

Signed-off-by: Andrew Thornton <art27@cantab.net>
2021-04-08 17:51:10 +01:00
zeripath
798ac3f85a Fix handling of logout event (#15323) (#15337)
Backport #15323

It appears that there is a slight bug in the handling of the data of logout event -
the javascript should be testing the data field of the data field for the logout
instruction.

Signed-off-by: Andrew Thornton <art27@cantab.net>
2021-04-08 17:28:30 +02:00
silverwind
460093b952 Monaco improvements (#15333) (#15345)
- Create theme at runtime which follows the CSS variables of the site
- Disable a few opinionated Monaco defaults like minimap and word highlights
- Move styles to separate file
2021-04-08 13:24:23 +02:00
6543
38d184d518 Fix CanCreateRepo check (#15311) (#15321)
Signed-off-by: jolheiser <john.olheiser@gmail.com>
Co-authored-by: John Olheiser <john.olheiser@gmail.com>
2021-04-07 22:14:11 +02:00
6543
80b55263d8 Fix xorm log stack level (#15285) (#15316)
Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
2021-04-07 08:36:15 +01:00
6543
32232db55f Reduce memory usage in testgit (#15306) (#15310)
* reduce memory use in rawtest

* just use hashsum for diffs

Signed-off-by: Andrew Thornton <art27@cantab.net>

Co-authored-by: zeripath <art27@cantab.net>
Co-authored-by: techknowlogick <techknowlogick@gitea.io>
2021-04-07 11:07:39 +08:00
KN4CK3R
cf9b6c281f Close file on invalid range (Addition to #15166) (#15268) (#15308)
* Close file on invalid range.

* Close on seek error

Signed-off-by: Andrew Thornton <art27@cantab.net>

* Moved 'Seek' into server.

* io.ReadSeekCloser is only available in Go 1.16

Co-authored-by: Andrew Thornton <art27@cantab.net>
Co-authored-by: Lauris BH <lauris@nix.lv>
Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>

Co-authored-by: Andrew Thornton <art27@cantab.net>
Co-authored-by: Lauris BH <lauris@nix.lv>
Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
Co-authored-by: techknowlogick <techknowlogick@gitea.io>
2021-04-06 15:25:31 -04:00
6543
a8c6a4a70e Fix bug in Wrap (#15302) (#15309)
Whilst doing other work I have noticed that there is an issue with Wrap when passing an
http.Handler - the next should be the next handler in line not empty.

Signed-off-by: Andrew Thornton <art27@cantab.net>
Co-authored-by: zeripath <art27@cantab.net>
2021-04-06 18:44:24 +02:00
6543
e6050e80f7 Update to bluemonday-1.0.6 (#15294) (#15297)
Signed-off-by: Andrew Thornton <art27@cantab.net>

Co-authored-by: zeripath <art27@cantab.net>
2021-04-06 01:36:58 +01:00
zeripath
3803b15d76 Drop the event source if we are unauthorized (#15275) (#15280)
Backport #15275

A previous commit that sent unauthorized if the user is unauthorized
simply leads to the repeated reopening of the eventsource. #

This PR changes the event returned to tell the client to close the
eventsource and thus prevents the repeated reopening.

Signed-off-by: Andrew Thornton <art27@cantab.net>
2021-04-04 20:39:22 -04:00
zeripath
af73e1ee35 Add size to Save function (#15264) (#15270)
This PR proposes an alternative solution to #15255 - just add the size to the
save function. Yes it is less apparently clean but it may be more correct.

Close #15255
Fix #15253

Signed-off-by: Andrew Thornton <art27@cantab.net>

Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
2021-04-04 12:04:55 -04:00
silverwind
4bc8dfc6a3 Branch page and misc css improvements (#15208) (#15274)
- Improve branches page, increase icon size, use octicons, use css vars
- Style placeholder color via css var
- Slightly increase contrast of input fields and active/hover states
- Add styling for select boxes in arc-green
2021-04-04 16:31:54 +03:00
techknowlogick
33c4e246fe update golang libraries (#15258) (#15259) 2021-04-03 10:42:18 +02:00
KN4CK3R
8ec7beb9f4 Fix graph pagination (#15225) (#15249)
* Fixed invalid HTML tag.

* Fixed pagination.

* Update templates/repo/graph/commits.tmpl

Co-authored-by: zeripath <art27@cantab.net>
2021-04-02 04:29:14 +01:00
a1012112796
c6eb9b30ae response 404 for diff/patch of a commit that not exist (#15221) (#15237)
* response 404 for diff/patch of a commit that not exist

fix #15217

Signed-off-by: a1012112796 <1012112796@qq.com>

* Update routers/repo/commit.go

Co-authored-by: silverwind <me@silverwind.io>

* use ctx.NotFound()

Co-authored-by: zeripath <art27@cantab.net>
Co-authored-by: silverwind <me@silverwind.io>

Co-authored-by: zeripath <art27@cantab.net>
Co-authored-by: silverwind <me@silverwind.io>
Co-authored-by: 6543 <6543@obermui.de>
2021-04-01 19:57:05 -04:00
zeripath
f75a9b27b0 Speed up enry.IsVendor (#15213) (#15245)
Backport #15213

`enry.IsVendor` is kinda slow as it simply iterates across all regexps.
This PR ajdusts the regexps to combine them to make this process a
little quicker.

Related #15143

Signed-off-by: Andrew Thornton <art27@cantab.net>
2021-04-02 01:16:00 +02:00
zeripath
2705696d4d Prevent NPE in CommentMustAsDiff if no hunk header (#15199) (#15200)
Backport #15199

I do not understand how this can happen or why.

There is an apparent possibility for a comment.Patch to be missing a hunk header
- this should not happen and do not understand how. But it appears to happen on
1.13 at least in some case.

This PR will simply add a new section if the cursection is empty
thus preventing the NPE.

Fix #15198

Signed-off-by: Andrew Thornton <art27@cantab.net>

Co-authored-by: 6543 <6543@obermui.de>
2021-04-01 15:14:56 -04:00
mayswind
2b68f66e0e Fix timezone bug when clicking heatmap (#15141) (#15231) 2021-04-01 18:22:54 +08:00
silverwind
5c7d30cf52 Diff box fixes (#15214) (#15227)
- Fix misaligned "Show Outdated" buttons via flexbox
- Add hover effect to "Show Outdated" buttons
- Remove overreaching margin from selector .diff-file-box and handle
  cases individually.

Fixes: https://github.com/go-gitea/gitea/issues/15097

Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
Co-authored-by: 6543 <6543@obermui.de>
Co-authored-by: zeripath <art27@cantab.net>
Co-authored-by: techknowlogick <techknowlogick@gitea.io>
2021-04-01 08:04:47 +03:00
zeripath
e520dff4da Improve /api/v1/repos/issues/search by just getting repo ids (#15179) (#15192)
Backport #15179

/api/v1/repos/issues/search is a highly inefficient search which is unfortunately
the basis for our dependency searching algorithm. In particular it currently loads
all of the repositories and their owners and their primary coding language all of
which is immediately thrown away.

This PR makes one simple change - just get the IDs.

Related #14560
Related #12827

Signed-off-by: Andrew Thornton <art27@cantab.net>
2021-04-01 01:15:08 +02:00
zeripath
2bc759518e Fix regression from #14623 - use debug SVC handler only on interactive sessions (#15210) (#15211)
Backport #15210

Unfortunately #14623 changed from the deprecated IsInteractiveSession to
IsWindowsService without recognising that they are the complement of
each other.

This means that Windows SVC control is not working correctly. This PR
adds some Tracing statements but also fixes the bug.

Fix #15159

Signed-off-by: Andrew Thornton <art27@cantab.net>
2021-03-31 20:49:46 +01:00
a1012112796
92b2883058 add 'fonts' into 'KnownPublicEntries' (#15188) (#15218)
fix #15184

Signed-off-by: a1012112796 <1012112796@qq.com>

Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>

Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
2021-03-31 04:56:19 +02:00
silverwind
0ebfc1405c Fix webhook delivery and issue checklist for arc-green (#15195) (#15204)
Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>

Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
2021-03-30 19:15:12 +08:00
silverwind
fd5c67226e Fix margin between avatars on org pages (#15194) (#15197)
Fixes: https://github.com/go-gitea/gitea/issues/15191
2021-03-29 23:36:00 +02:00
a1012112796
61308825a6 should run RetrieveRepoMetas() for empty pr (#15187) (#15190)
Signed-off-by: a1012112796 <1012112796@qq.com>
2021-03-29 17:02:01 +01:00
Norwin
0cccad04f0 fix org navbar (#15174)
Co-authored-by: Jimmy Praet <jimmy.praet@telenet.be>
2021-03-27 15:57:02 +01:00
zeripath
a0e5c49ac3 Clusterfuzz found another way (#15160) (#15168)
Backport #15160

Clusterfuzz found another way so I found another way to stop it

Signed-off-by: Andrew Thornton <art27@cantab.net>
2021-03-26 22:48:38 -04:00
sotho
3558310c1f Fix wrong user returned in API (#15139) (#15151)
The API call: GET /repos/{owner}/{repo}/pulls/{index}/reviews/{id}/comments
returns always the reviewer, but should return the poster.

Co-authored-by: 6543 <6543@obermui.de>
Co-authored-by: zeripath <art27@cantab.net>
2021-03-26 04:20:52 +01:00
194 changed files with 5448 additions and 3908 deletions

View File

@@ -4,25 +4,16 @@ This changelog goes through all the changes that have been made in each release
without substantial changes to our git log; to see the highlights of what has without substantial changes to our git log; to see the highlights of what has
been added to each release, please refer to the [blog](https://blog.gitea.io). been added to each release, please refer to the [blog](https://blog.gitea.io).
## [1.14.0-RC2](https://github.com/go-gitea/gitea/releases/tag/v1.14.0-rc2) - 2021-03-22 ## [1.14.0](https://github.com/go-gitea/gitea/releases/tag/v1.14.0) - 2021-04-11
* SECURITY
* Fix bug on avatar middleware (#15124) (#15125)
* Fix another clusterfuzz identified issue (#15096) (#15113)
* Update to goldmark 1.3.3 (#15059) (#15060)
* BUGFIXES
* Fix the v176 migration (#15110) (#15111)
* Fix double 'push tag' action feed (#15078) (#15083)
* Remove possible resource leak (#15067) (#15082)
* Handle unauthorized user events gracefully (#15071) (#15074)
## [1.14.0-RC1](https://github.com/go-gitea/gitea/releases/tag/v1.14.0-rc1) - 2021-03-20
* SECURITY * SECURITY
* Respect approved email domain list for externally validated user registration (#15014) * Respect approved email domain list for externally validated user registration (#15014)
* Add reverse proxy configuration support for remote IP address detection (#14959) * Add reverse proxy configuration support for remote IP address detection (#14959)
* Ensure validation occurs on clone addresses too (#14994) * Ensure validation occurs on clone addresses too (#14994)
* BREAKING * BREAKING
* Fix double 'push tag' action feed (#15078) (#15083)
* Remove possible resource leak (#15067) (#15082)
* Handle unauthorized user events gracefully (#15071) (#15074)
* Restore Access.log following migration to Chi framework (Stops access logging of /api/internal routes) (#14475) * Restore Access.log following migration to Chi framework (Stops access logging of /api/internal routes) (#14475)
* Migrate from Macaron to Chi framework (#14293) * Migrate from Macaron to Chi framework (#14293)
* Deprecate building for mips (#14174) * Deprecate building for mips (#14174)
@@ -53,6 +44,7 @@ been added to each release, please refer to the [blog](https://blog.gitea.io).
* Dump github/gitlab/gitea repository data to a local directory and restore to gitea (#12244) * Dump github/gitlab/gitea repository data to a local directory and restore to gitea (#12244)
* Create Rootless Docker image (#10154) * Create Rootless Docker image (#10154)
* API * API
* Speedup issue search (#15179) (#15192)
* Get pull, return head branch sha, even if deleted (#14931) * Get pull, return head branch sha, even if deleted (#14931)
* Export LFS & TimeTracking function status (#14753) * Export LFS & TimeTracking function status (#14753)
* Show Gitea version in swagger (#14654) * Show Gitea version in swagger (#14654)
@@ -77,6 +69,20 @@ been added to each release, please refer to the [blog](https://blog.gitea.io).
* Add more filters to issues search (#13514) * Add more filters to issues search (#13514)
* Add review request api (#11355) * Add review request api (#11355)
* BUGFIXES * BUGFIXES
* Fix delete nonexist oauth application 500 and prevent deadlock (#15384) (#15396)
* Always set the merge base used to merge the commit (#15352) (#15385)
* Upgrade to bluemonday 1.0.7 (#15379) (#15380)
* Turn RepoRef and RepoAssignment back into func(*Context) (#15372) (#15377)
* Move FCGI req.URL.Path fix-up to the FCGI listener (#15292) (#15361)
* Show diff on rename with diff changes (#15338) (#15339)
* Fix handling of logout event (#15323) (#15337)
* Fix CanCreateRepo check (#15311) (#15321)
* Fix xorm log stack level (#15285) (#15316)
* Fix bug in Wrap (#15302) (#15309)
* Drop the event source if we are unauthorized (#15275) (#15280)
* Backport Fix graph pagination (#15225) (#15249)
* Prevent NPE in CommentMustAsDiff if no hunk header (#15199) (#15200)
* should run RetrieveRepoMetas() for empty pr (#15187) (#15190)
* Move setting to enable closing issue via commit in non default branch to repo settings (#14965) * Move setting to enable closing issue via commit in non default branch to repo settings (#14965)
* Show correct issues for team dashboard (#14952) * Show correct issues for team dashboard (#14952)
* Ensure that new pull request button works on forked forks owned by owner of the root and reduce ambiguity (#14932) * Ensure that new pull request button works on forked forks owned by owner of the root and reduce ambiguity (#14932)
@@ -133,6 +139,9 @@ been added to each release, please refer to the [blog](https://blog.gitea.io).
* Use GO variable in go-check target (#13146) (#13147) * Use GO variable in go-check target (#13146) (#13147)
* ENHANCEMENTS * ENHANCEMENTS
* UI style improvements * UI style improvements
* Dropzone styling improvements (#15291) (#15374)
* Add size to Save function (#15264) (#15270)
* Monaco improvements (#15333) (#15345)
* Support .mailmap in code activity stats (#15009) * Support .mailmap in code activity stats (#15009)
* Sort release attachments by name (#15008) * Sort release attachments by name (#15008)
* Add ui.explore settings to control view of explore pages (#14094) * Add ui.explore settings to control view of explore pages (#14094)
@@ -278,6 +287,52 @@ been added to each release, please refer to the [blog](https://blog.gitea.io).
* Reduce make verbosity (#13803) * Reduce make verbosity (#13803)
* Add git command error directory on log (#13194) * Add git command error directory on log (#13194)
## [1.13.7](https://github.com/go-gitea/gitea/releases/tag/v1.13.7) - 2021-04-07
* SECURITY
* Update to bluemonday-1.0.6 (#15294) (#15298)
* Clusterfuzz found another way (#15160) (#15169)
* API
* Fix wrong user returned in API (#15139) (#15150)
* BUGFIXES
* Add 'fonts' into 'KnownPublicEntries' (#15188) (#15317)
* Speed up `enry.IsVendor` (#15213) (#15246)
* Response 404 for diff/patch of a commit that not exist (#15221) (#15238)
* Prevent NPE in CommentMustAsDiff if no hunk header (#15199) (#15201)
* MISC
* Add size to Save function (#15264) (#15271)
## [1.13.6](https://github.com/go-gitea/gitea/releases/tag/v1.13.6) - 2021-03-23
* SECURITY
* Fix bug on avatar middleware (#15124) (#15125)
* Fix another clusterfuzz identified issue (#15096) (#15114)
* API
* Fix nil pointer exception in get pull reviews API (#15106)
* BUGFIXES
* Fix markdown rendering in milestone content (#15056) (#15092)
## [1.13.5](https://github.com/go-gitea/gitea/releases/tag/v1.13.5) - 2021-03-21
* SECURITY
* Update to goldmark 1.3.3 (#15059) (#15061)
* Another clusterfuzz spotted issue (#15032) (#15034)
* API
* Fix set milestone on PR creation (#14981) (#15001)
* Prevent panic when editing forked repos by API (#14960) (#14963)
* BUGFIXES
* Fix bug when upload on web (#15042) (#15055)
* Delete Labels & IssueLabels on Repo Delete too (#15039) (#15051)
* Fix postgres ID sequences broken by recreate-table (#15015) (#15029)
* Fix several render issues (#14986) (#15013)
* Make sure sibling images get a link too (#14979) (#14995)
* Fix Anchor jumping with escaped query components (#14969) (#14977)
* Fix release mail html template (#14976)
* Fix excluding more than two labels on issues list (#14962) (#14973)
* Don't mark each comment poster as OP (#14971) (#14972)
* Add "captcha" to list of reserved usernames (#14930)
* Re-enable import local paths after reversion from #13610 (#14925) (#14927)
## [1.13.4](https://github.com/go-gitea/gitea/releases/tag/v1.13.4) - 2021-03-07 ## [1.13.4](https://github.com/go-gitea/gitea/releases/tag/v1.13.4) - 2021-03-07
* SECURITY * SECURITY

View File

@@ -9,9 +9,11 @@ import (
"net" "net"
"net/http" "net/http"
"net/http/fcgi" "net/http/fcgi"
"strings"
"code.gitea.io/gitea/modules/graceful" "code.gitea.io/gitea/modules/graceful"
"code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/setting"
) )
func runHTTP(network, listenAddr, name string, m http.Handler) error { func runHTTP(network, listenAddr, name string, m http.Handler) error {
@@ -48,7 +50,12 @@ func runFCGI(network, listenAddr, name string, m http.Handler) error {
fcgiServer := graceful.NewServer(network, listenAddr, name) fcgiServer := graceful.NewServer(network, listenAddr, name)
err := fcgiServer.ListenAndServe(func(listener net.Listener) error { err := fcgiServer.ListenAndServe(func(listener net.Listener) error {
return fcgi.Serve(listener, m) return fcgi.Serve(listener, http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
if setting.AppSubURL != "" {
req.URL.Path = strings.TrimPrefix(req.URL.Path, setting.AppSubURL)
}
m.ServeHTTP(resp, req)
}))
}) })
if err != nil { if err != nil {
log.Fatal("Failed to start FCGI main server: %v", err) log.Fatal("Failed to start FCGI main server: %v", err)

8
go.mod
View File

@@ -86,7 +86,7 @@ require (
github.com/mgechev/revive v1.0.3 github.com/mgechev/revive v1.0.3
github.com/mholt/acmez v0.1.3 // indirect github.com/mholt/acmez v0.1.3 // indirect
github.com/mholt/archiver/v3 v3.5.0 github.com/mholt/archiver/v3 v3.5.0
github.com/microcosm-cc/bluemonday v1.0.4 github.com/microcosm-cc/bluemonday v1.0.7
github.com/miekg/dns v1.1.40 // indirect github.com/miekg/dns v1.1.40 // indirect
github.com/minio/md5-simd v1.1.2 // indirect github.com/minio/md5-simd v1.1.2 // indirect
github.com/minio/minio-go/v7 v7.0.10 github.com/minio/minio-go/v7 v7.0.10
@@ -136,9 +136,9 @@ require (
go.uber.org/multierr v1.6.0 // indirect go.uber.org/multierr v1.6.0 // indirect
go.uber.org/zap v1.16.0 // indirect go.uber.org/zap v1.16.0 // indirect
golang.org/x/crypto v0.0.0-20210220033148-5ea612d1eb83 golang.org/x/crypto v0.0.0-20210220033148-5ea612d1eb83
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110 golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4
golang.org/x/oauth2 v0.0.0-20210220000619-9bb904979d93 golang.org/x/oauth2 v0.0.0-20210220000619-9bb904979d93
golang.org/x/sys v0.0.0-20210228012217-479acdf4ea46 golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44
golang.org/x/text v0.3.5 golang.org/x/text v0.3.5
golang.org/x/time v0.0.0-20210220033141-f8bda1e9f3ba // indirect golang.org/x/time v0.0.0-20210220033141-f8bda1e9f3ba // indirect
golang.org/x/tools v0.1.0 golang.org/x/tools v0.1.0
@@ -153,5 +153,3 @@ require (
) )
replace github.com/hashicorp/go-version => github.com/6543/go-version v1.2.4 replace github.com/hashicorp/go-version => github.com/6543/go-version v1.2.4
replace github.com/microcosm-cc/bluemonday => github.com/lunny/bluemonday v1.0.5-0.20201227154428-ca34796141e8

15
go.sum
View File

@@ -196,8 +196,6 @@ github.com/cespare/xxhash/v2 v2.1.1 h1:6MnRN8NT7+YBpUIWxHtefFZOKTAPgGjpQSxqLNn0+
github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/chi-middleware/proxy v1.1.1 h1:4HaXUp8o2+bhHr1OhVy+VjN0+L7/07JDcn6v7YrTjrQ= github.com/chi-middleware/proxy v1.1.1 h1:4HaXUp8o2+bhHr1OhVy+VjN0+L7/07JDcn6v7YrTjrQ=
github.com/chi-middleware/proxy v1.1.1/go.mod h1:jQwMEJct2tz9VmtCELxvnXoMfa+SOdikvbVJVHv/M+0= github.com/chi-middleware/proxy v1.1.1/go.mod h1:jQwMEJct2tz9VmtCELxvnXoMfa+SOdikvbVJVHv/M+0=
github.com/chris-ramon/douceur v0.2.0 h1:IDMEdxlEUUBYBKE4z/mJnFyVXox+MjuEVDJNN27glkU=
github.com/chris-ramon/douceur v0.2.0/go.mod h1:wDW5xjJdeoMm1mRt4sD4c/LbF/mWdEpRXQKjTR8nIBE=
github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI= github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI=
github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI= github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI=
github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU= github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU=
@@ -776,8 +774,6 @@ github.com/libdns/libdns v0.2.0 h1:ewg3ByWrdUrxrje8ChPVMBNcotg7H9LQYg+u5De2RzI=
github.com/libdns/libdns v0.2.0/go.mod h1:yQCXzk1lEZmmCPa857bnk4TsOiqYasqpyOEeSObbb40= github.com/libdns/libdns v0.2.0/go.mod h1:yQCXzk1lEZmmCPa857bnk4TsOiqYasqpyOEeSObbb40=
github.com/lightstep/lightstep-tracer-common/golang/gogo v0.0.0-20190605223551-bc2310a04743/go.mod h1:qklhhLq1aX+mtWk9cPHPzaBjWImj5ULL6C7HFJtXQMM= github.com/lightstep/lightstep-tracer-common/golang/gogo v0.0.0-20190605223551-bc2310a04743/go.mod h1:qklhhLq1aX+mtWk9cPHPzaBjWImj5ULL6C7HFJtXQMM=
github.com/lightstep/lightstep-tracer-go v0.18.1/go.mod h1:jlF1pusYV4pidLvZ+XD0UBX0ZE6WURAspgAczcDHrL4= github.com/lightstep/lightstep-tracer-go v0.18.1/go.mod h1:jlF1pusYV4pidLvZ+XD0UBX0ZE6WURAspgAczcDHrL4=
github.com/lunny/bluemonday v1.0.5-0.20201227154428-ca34796141e8 h1:1omo92DLtxQu6VwVPSZAmduHaK5zssed6cvkHyl1XOg=
github.com/lunny/bluemonday v1.0.5-0.20201227154428-ca34796141e8/go.mod h1:8iwZnFn2CDDNZ0r6UXhF4xawGvzaqzCRa1n3/lO3W2w=
github.com/lunny/dingtalk_webhook v0.0.0-20171025031554-e3534c89ef96 h1:uNwtsDp7ci48vBTTxDuwcoTXz4lwtDTe7TjCQ0noaWY= github.com/lunny/dingtalk_webhook v0.0.0-20171025031554-e3534c89ef96 h1:uNwtsDp7ci48vBTTxDuwcoTXz4lwtDTe7TjCQ0noaWY=
github.com/lunny/dingtalk_webhook v0.0.0-20171025031554-e3534c89ef96/go.mod h1:mmIfjCSQlGYXmJ95jFN84AkQFnVABtKuJL8IrzwvUKQ= github.com/lunny/dingtalk_webhook v0.0.0-20171025031554-e3534c89ef96/go.mod h1:mmIfjCSQlGYXmJ95jFN84AkQFnVABtKuJL8IrzwvUKQ=
github.com/lunny/log v0.0.0-20160921050905-7887c61bf0de/go.mod h1:3q8WtuPQsoRbatJuy3nvq/hRSvuBJrHHr+ybPPiNvHQ= github.com/lunny/log v0.0.0-20160921050905-7887c61bf0de/go.mod h1:3q8WtuPQsoRbatJuy3nvq/hRSvuBJrHHr+ybPPiNvHQ=
@@ -834,6 +830,8 @@ github.com/mholt/acmez v0.1.3 h1:J7MmNIk4Qf9b8mAGqAh4XkNeowv3f1zW816yf4zt7Qk=
github.com/mholt/acmez v0.1.3/go.mod h1:8qnn8QA/Ewx8E3ZSsmscqsIjhhpxuy9vqdgbX2ceceM= github.com/mholt/acmez v0.1.3/go.mod h1:8qnn8QA/Ewx8E3ZSsmscqsIjhhpxuy9vqdgbX2ceceM=
github.com/mholt/archiver/v3 v3.5.0 h1:nE8gZIrw66cu4osS/U7UW7YDuGMHssxKutU8IfWxwWE= github.com/mholt/archiver/v3 v3.5.0 h1:nE8gZIrw66cu4osS/U7UW7YDuGMHssxKutU8IfWxwWE=
github.com/mholt/archiver/v3 v3.5.0/go.mod h1:qqTTPUK/HZPFgFQ/TJ3BzvTpF/dPtFVJXdQbCmeMxwc= github.com/mholt/archiver/v3 v3.5.0/go.mod h1:qqTTPUK/HZPFgFQ/TJ3BzvTpF/dPtFVJXdQbCmeMxwc=
github.com/microcosm-cc/bluemonday v1.0.7 h1:6yAQfk4XT+PI/dk1ZeBp1gr3Q2Hd1DR0O3aEyPUJVTE=
github.com/microcosm-cc/bluemonday v1.0.7/go.mod h1:HOT/6NaBlR0f9XlxD3zolN6Z3N8Lp4pvhp+jLS5ihnI=
github.com/miekg/dns v1.0.14/go.mod h1:W1PPwlIAgtquWBMBEV9nkV9Cazfe8ScdGz/Lj7v3Nrg= github.com/miekg/dns v1.0.14/go.mod h1:W1PPwlIAgtquWBMBEV9nkV9Cazfe8ScdGz/Lj7v3Nrg=
github.com/miekg/dns v1.1.30/go.mod h1:KNUDUusw/aVsxyTYZM1oqvCicbwhgbNgztCETuNZ7xM= github.com/miekg/dns v1.1.30/go.mod h1:KNUDUusw/aVsxyTYZM1oqvCicbwhgbNgztCETuNZ7xM=
github.com/miekg/dns v1.1.40 h1:pyyPFfGMnciYUk/mXpKkVmeMQjfXqt3FAJ2hy7tPiLA= github.com/miekg/dns v1.1.40 h1:pyyPFfGMnciYUk/mXpKkVmeMQjfXqt3FAJ2hy7tPiLA=
@@ -1321,8 +1319,9 @@ golang.org/x/net v0.0.0-20201202161906-c7110b5ffcbb/go.mod h1:sp8m0HH+o8qH0wwXwY
golang.org/x/net v0.0.0-20201209123823-ac852fbbde11/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20201209123823-ac852fbbde11/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20201224014010-6772e930b67b/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20201224014010-6772e930b67b/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20210119194325-5f4716e94777/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210119194325-5f4716e94777/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110 h1:qWPm9rbaAMKs8Bq/9LRpbMqxWRVUAQwMI9fVrssnTfw= golang.org/x/net v0.0.0-20210331212208-0fccb6fa2b5c/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4 h1:4nGaVu0QrbjT/AK2PRLuQfQuh6DJve+pELhqTdAj3x0=
golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM=
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/oauth2 v0.0.0-20181106182150-f42d05182288/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20181106182150-f42d05182288/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
@@ -1418,8 +1417,8 @@ golang.org/x/sys v0.0.0-20210112080510-489259a85091/go.mod h1:h1NjWce9XRLGQEsW7w
golang.org/x/sys v0.0.0-20210119212857-b64e53b001e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210119212857-b64e53b001e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210220050731-9a76102bfb43/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210220050731-9a76102bfb43/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210228012217-479acdf4ea46 h1:V066+OYJ66oTjnhm4Yrn7SXIwSCiDQJxpBxmvqb1N1c= golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44 h1:Bli41pIlzTzf3KEY06n+xnzK/BESIg2ze4Pgfh/aI8c=
golang.org/x/sys v0.0.0-20210228012217-479acdf4ea46/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw= golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1 h1:v+OssWQX+hTHEmOBgwxdZxK4zHq3yOs8F9J7mk0PY8E= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1 h1:v+OssWQX+hTHEmOBgwxdZxK4zHq3yOs8F9J7mk0PY8E=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=

View File

@@ -239,6 +239,26 @@ func doAPICreatePullRequest(ctx APITestContext, owner, repo, baseBranch, headBra
} }
} }
func doAPIGetPullRequest(ctx APITestContext, owner, repo string, index int64) func(*testing.T) (api.PullRequest, error) {
return func(t *testing.T) (api.PullRequest, error) {
urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d?token=%s",
owner, repo, index, ctx.Token)
req := NewRequest(t, http.MethodGet, urlStr)
expected := 200
if ctx.ExpectedCode != 0 {
expected = ctx.ExpectedCode
}
resp := ctx.Session.MakeRequest(t, req, expected)
json := jsoniter.ConfigCompatibleWithStandardLibrary
decoder := json.NewDecoder(resp.Body)
pr := api.PullRequest{}
err := decoder.Decode(&pr)
return pr, err
}
}
func doAPIMergePullRequest(ctx APITestContext, owner, repo string, index int64) func(*testing.T) { func doAPIMergePullRequest(ctx APITestContext, owner, repo string, index int64) func(*testing.T) {
return func(t *testing.T) { return func(t *testing.T) {
urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/merge?token=%s", urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/merge?token=%s",

View File

@@ -92,6 +92,10 @@ func testAPIDeleteOAuth2Application(t *testing.T) {
session.MakeRequest(t, req, http.StatusNoContent) session.MakeRequest(t, req, http.StatusNoContent)
models.AssertNotExistsBean(t, &models.OAuth2Application{UID: oldApp.UID, Name: oldApp.Name}) models.AssertNotExistsBean(t, &models.OAuth2Application{UID: oldApp.UID, Name: oldApp.Name})
// Delete again will return not found
req = NewRequest(t, "DELETE", urlStr)
session.MakeRequest(t, req, http.StatusNotFound)
} }
func testAPIGetOAuth2Application(t *testing.T) { func testAPIGetOAuth2Application(t *testing.T) {

View File

@@ -122,7 +122,7 @@ func TestGetAttachment(t *testing.T) {
t.Run(tc.name, func(t *testing.T) { t.Run(tc.name, func(t *testing.T) {
//Write empty file to be available for response //Write empty file to be available for response
if tc.createFile { if tc.createFile {
_, err := storage.Attachments.Save(models.AttachmentRelativePath(tc.uuid), strings.NewReader("hello world")) _, err := storage.Attachments.Save(models.AttachmentRelativePath(tc.uuid), strings.NewReader("hello world"), -1)
assert.NoError(t, err) assert.NoError(t, err)
} }
//Actual test //Actual test

View File

@@ -5,6 +5,7 @@
package integrations package integrations
import ( import (
"encoding/hex"
"fmt" "fmt"
"io/ioutil" "io/ioutil"
"math/rand" "math/rand"
@@ -208,13 +209,13 @@ func rawTest(t *testing.T, ctx *APITestContext, little, big, littleLFS, bigLFS s
// Request raw paths // Request raw paths
req := NewRequest(t, "GET", path.Join("/", username, reponame, "/raw/branch/master/", little)) req := NewRequest(t, "GET", path.Join("/", username, reponame, "/raw/branch/master/", little))
resp := session.MakeRequest(t, req, http.StatusOK) resp := session.MakeRequestNilResponseRecorder(t, req, http.StatusOK)
assert.Equal(t, littleSize, resp.Body.Len()) assert.Equal(t, littleSize, resp.Length)
setting.CheckLFSVersion() setting.CheckLFSVersion()
if setting.LFS.StartServer { if setting.LFS.StartServer {
req = NewRequest(t, "GET", path.Join("/", username, reponame, "/raw/branch/master/", littleLFS)) req = NewRequest(t, "GET", path.Join("/", username, reponame, "/raw/branch/master/", littleLFS))
resp = session.MakeRequest(t, req, http.StatusOK) resp := session.MakeRequest(t, req, http.StatusOK)
assert.NotEqual(t, littleSize, resp.Body.Len()) assert.NotEqual(t, littleSize, resp.Body.Len())
assert.LessOrEqual(t, resp.Body.Len(), 1024) assert.LessOrEqual(t, resp.Body.Len(), 1024)
if resp.Body.Len() != littleSize && resp.Body.Len() <= 1024 { if resp.Body.Len() != littleSize && resp.Body.Len() <= 1024 {
@@ -224,12 +225,12 @@ func rawTest(t *testing.T, ctx *APITestContext, little, big, littleLFS, bigLFS s
if !testing.Short() { if !testing.Short() {
req = NewRequest(t, "GET", path.Join("/", username, reponame, "/raw/branch/master/", big)) req = NewRequest(t, "GET", path.Join("/", username, reponame, "/raw/branch/master/", big))
resp = session.MakeRequest(t, req, http.StatusOK) resp := session.MakeRequestNilResponseRecorder(t, req, http.StatusOK)
assert.Equal(t, bigSize, resp.Body.Len()) assert.Equal(t, bigSize, resp.Length)
if setting.LFS.StartServer { if setting.LFS.StartServer {
req = NewRequest(t, "GET", path.Join("/", username, reponame, "/raw/branch/master/", bigLFS)) req = NewRequest(t, "GET", path.Join("/", username, reponame, "/raw/branch/master/", bigLFS))
resp = session.MakeRequest(t, req, http.StatusOK) resp := session.MakeRequest(t, req, http.StatusOK)
assert.NotEqual(t, bigSize, resp.Body.Len()) assert.NotEqual(t, bigSize, resp.Body.Len())
if resp.Body.Len() != bigSize && resp.Body.Len() <= 1024 { if resp.Body.Len() != bigSize && resp.Body.Len() <= 1024 {
assert.Contains(t, resp.Body.String(), models.LFSMetaFileIdentifier) assert.Contains(t, resp.Body.String(), models.LFSMetaFileIdentifier)
@@ -450,27 +451,35 @@ func doMergeFork(ctx, baseCtx APITestContext, baseBranch, headBranch string) fun
t.Run("EnsureCanSeePull", doEnsureCanSeePull(baseCtx, pr)) t.Run("EnsureCanSeePull", doEnsureCanSeePull(baseCtx, pr))
// Then get the diff string // Then get the diff string
var diffStr string var diffHash string
var diffLength int
t.Run("GetDiff", func(t *testing.T) { t.Run("GetDiff", func(t *testing.T) {
req := NewRequest(t, "GET", fmt.Sprintf("/%s/%s/pulls/%d.diff", url.PathEscape(baseCtx.Username), url.PathEscape(baseCtx.Reponame), pr.Index)) req := NewRequest(t, "GET", fmt.Sprintf("/%s/%s/pulls/%d.diff", url.PathEscape(baseCtx.Username), url.PathEscape(baseCtx.Reponame), pr.Index))
resp := ctx.Session.MakeRequest(t, req, http.StatusOK) resp := ctx.Session.MakeRequestNilResponseHashSumRecorder(t, req, http.StatusOK)
diffStr = resp.Body.String() diffHash = string(resp.Hash.Sum(nil))
diffLength = resp.Length
}) })
// Now: Merge the PR & make sure that doesn't break the PR page or change its diff // Now: Merge the PR & make sure that doesn't break the PR page or change its diff
t.Run("MergePR", doAPIMergePullRequest(baseCtx, baseCtx.Username, baseCtx.Reponame, pr.Index)) t.Run("MergePR", doAPIMergePullRequest(baseCtx, baseCtx.Username, baseCtx.Reponame, pr.Index))
t.Run("EnsureCanSeePull", doEnsureCanSeePull(baseCtx, pr)) t.Run("EnsureCanSeePull", doEnsureCanSeePull(baseCtx, pr))
t.Run("EnsureDiffNoChange", doEnsureDiffNoChange(baseCtx, pr, diffStr)) t.Run("CheckPR", func(t *testing.T) {
oldMergeBase := pr.MergeBase
pr2, err := doAPIGetPullRequest(baseCtx, baseCtx.Username, baseCtx.Reponame, pr.Index)(t)
assert.NoError(t, err)
assert.Equal(t, oldMergeBase, pr2.MergeBase)
})
t.Run("EnsurDiffNoChange", doEnsureDiffNoChange(baseCtx, pr, diffHash, diffLength))
// Then: Delete the head branch & make sure that doesn't break the PR page or change its diff // Then: Delete the head branch & make sure that doesn't break the PR page or change its diff
t.Run("DeleteHeadBranch", doBranchDelete(baseCtx, baseCtx.Username, baseCtx.Reponame, headBranch)) t.Run("DeleteHeadBranch", doBranchDelete(baseCtx, baseCtx.Username, baseCtx.Reponame, headBranch))
t.Run("EnsureCanSeePull", doEnsureCanSeePull(baseCtx, pr)) t.Run("EnsureCanSeePull", doEnsureCanSeePull(baseCtx, pr))
t.Run("EnsureDiffNoChange", doEnsureDiffNoChange(baseCtx, pr, diffStr)) t.Run("EnsureDiffNoChange", doEnsureDiffNoChange(baseCtx, pr, diffHash, diffLength))
// Delete the head repository & make sure that doesn't break the PR page or change its diff // Delete the head repository & make sure that doesn't break the PR page or change its diff
t.Run("DeleteHeadRepository", doAPIDeleteRepository(ctx)) t.Run("DeleteHeadRepository", doAPIDeleteRepository(ctx))
t.Run("EnsureCanSeePull", doEnsureCanSeePull(baseCtx, pr)) t.Run("EnsureCanSeePull", doEnsureCanSeePull(baseCtx, pr))
t.Run("EnsureDiffNoChange", doEnsureDiffNoChange(baseCtx, pr, diffStr)) t.Run("EnsureDiffNoChange", doEnsureDiffNoChange(baseCtx, pr, diffHash, diffLength))
} }
} }
@@ -514,20 +523,15 @@ func doEnsureCanSeePull(ctx APITestContext, pr api.PullRequest) func(t *testing.
} }
} }
func doEnsureDiffNoChange(ctx APITestContext, pr api.PullRequest, diffStr string) func(t *testing.T) { func doEnsureDiffNoChange(ctx APITestContext, pr api.PullRequest, diffHash string, diffLength int) func(t *testing.T) {
return func(t *testing.T) { return func(t *testing.T) {
req := NewRequest(t, "GET", fmt.Sprintf("/%s/%s/pulls/%d.diff", url.PathEscape(ctx.Username), url.PathEscape(ctx.Reponame), pr.Index)) req := NewRequest(t, "GET", fmt.Sprintf("/%s/%s/pulls/%d.diff", url.PathEscape(ctx.Username), url.PathEscape(ctx.Reponame), pr.Index))
resp := ctx.Session.MakeRequest(t, req, http.StatusOK) resp := ctx.Session.MakeRequestNilResponseHashSumRecorder(t, req, http.StatusOK)
expectedMaxLen := len(diffStr) actual := string(resp.Hash.Sum(nil))
if expectedMaxLen > 800 { actualLength := resp.Length
expectedMaxLen = 800
} equal := diffHash == actual
actual := resp.Body.String() assert.True(t, equal, "Unexpected change in the diff string: expected hash: %s size: %d but was actually: %s size: %d", hex.EncodeToString([]byte(diffHash)), diffLength, hex.EncodeToString([]byte(actual)), actualLength)
actualMaxLen := len(actual)
if actualMaxLen > 800 {
actualMaxLen = 800
}
assert.Equal(t, diffStr, actual, "Unexpected change in the diff string: expected: %s but was actually: %s", diffStr[:expectedMaxLen], actual[:actualMaxLen])
} }
} }

View File

@@ -9,6 +9,8 @@ import (
"context" "context"
"database/sql" "database/sql"
"fmt" "fmt"
"hash"
"hash/fnv"
"io" "io"
"net/http" "net/http"
"net/http/cookiejar" "net/http/cookiejar"
@@ -58,6 +60,26 @@ func NewNilResponseRecorder() *NilResponseRecorder {
} }
} }
type NilResponseHashSumRecorder struct {
httptest.ResponseRecorder
Hash hash.Hash
Length int
}
func (n *NilResponseHashSumRecorder) Write(b []byte) (int, error) {
_, _ = n.Hash.Write(b)
n.Length += len(b)
return len(b), nil
}
// NewRecorder returns an initialized ResponseRecorder.
func NewNilResponseHashSumRecorder() *NilResponseHashSumRecorder {
return &NilResponseHashSumRecorder{
Hash: fnv.New32(),
ResponseRecorder: *httptest.NewRecorder(),
}
}
func TestMain(m *testing.M) { func TestMain(m *testing.M) {
defer log.Close() defer log.Close()
@@ -284,6 +306,23 @@ func (s *TestSession) MakeRequestNilResponseRecorder(t testing.TB, req *http.Req
return resp return resp
} }
func (s *TestSession) MakeRequestNilResponseHashSumRecorder(t testing.TB, req *http.Request, expectedStatus int) *NilResponseHashSumRecorder {
t.Helper()
baseURL, err := url.Parse(setting.AppURL)
assert.NoError(t, err)
for _, c := range s.jar.Cookies(baseURL) {
req.AddCookie(c)
}
resp := MakeRequestNilResponseHashSumRecorder(t, req, expectedStatus)
ch := http.Header{}
ch.Add("Cookie", strings.Join(resp.Header()["Set-Cookie"], ";"))
cr := http.Request{Header: ch}
s.jar.SetCookies(baseURL, cr.Cookies())
return resp
}
const userPassword = "password" const userPassword = "password"
var loginSessionCache = make(map[string]*TestSession, 10) var loginSessionCache = make(map[string]*TestSession, 10)
@@ -429,6 +468,19 @@ func MakeRequestNilResponseRecorder(t testing.TB, req *http.Request, expectedSta
return recorder return recorder
} }
func MakeRequestNilResponseHashSumRecorder(t testing.TB, req *http.Request, expectedStatus int) *NilResponseHashSumRecorder {
t.Helper()
recorder := NewNilResponseHashSumRecorder()
c.ServeHTTP(recorder, req)
if expectedStatus != NoExpectedStatus {
if !assert.EqualValues(t, expectedStatus, recorder.Code,
"Request: %s %s", req.Method, req.URL.String()) {
logUnexpectedResponse(t, &recorder.ResponseRecorder)
}
}
return recorder
}
// logUnexpectedResponse logs the contents of an unexpected response. // logUnexpectedResponse logs the contents of an unexpected response.
func logUnexpectedResponse(t testing.TB, recorder *httptest.ResponseRecorder) { func logUnexpectedResponse(t testing.TB, recorder *httptest.ResponseRecorder) {
t.Helper() t.Helper()

View File

@@ -382,7 +382,7 @@ func activityQueryCondition(opts GetFeedsOptions) (builder.Cond, error) {
} }
if opts.Date != "" { if opts.Date != "" {
dateLow, err := time.Parse("2006-01-02", opts.Date) dateLow, err := time.ParseInLocation("2006-01-02", opts.Date, setting.DefaultUILocation)
if err != nil { if err != nil {
log.Warn("Unable to parse %s, filter not applied: %v", opts.Date, err) log.Warn("Unable to parse %s, filter not applied: %v", opts.Date, err)
} else { } else {

View File

@@ -85,7 +85,7 @@ func (a *Attachment) LinkedRepository() (*Repository, UnitType, error) {
func NewAttachment(attach *Attachment, buf []byte, file io.Reader) (_ *Attachment, err error) { func NewAttachment(attach *Attachment, buf []byte, file io.Reader) (_ *Attachment, err error) {
attach.UUID = gouuid.New().String() attach.UUID = gouuid.New().String()
size, err := storage.Attachments.Save(attach.RelativePath(), io.MultiReader(bytes.NewReader(buf), file)) size, err := storage.Attachments.Save(attach.RelativePath(), io.MultiReader(bytes.NewReader(buf), file), -1)
if err != nil { if err != nil {
return nil, fmt.Errorf("Create: %v", err) return nil, fmt.Errorf("Create: %v", err)
} }

View File

@@ -26,6 +26,8 @@ func NewXORMLogger(showSQL bool) xormlog.Logger {
} }
} }
const stackLevel = 8
// Log a message with defined skip and at logging level // Log a message with defined skip and at logging level
func (l *XORMLogBridge) Log(skip int, level log.Level, format string, v ...interface{}) error { func (l *XORMLogBridge) Log(skip int, level log.Level, format string, v ...interface{}) error {
return l.logger.Log(skip+1, level, format, v...) return l.logger.Log(skip+1, level, format, v...)
@@ -33,42 +35,42 @@ func (l *XORMLogBridge) Log(skip int, level log.Level, format string, v ...inter
// Debug show debug log // Debug show debug log
func (l *XORMLogBridge) Debug(v ...interface{}) { func (l *XORMLogBridge) Debug(v ...interface{}) {
_ = l.Log(2, log.DEBUG, fmt.Sprint(v...)) _ = l.Log(stackLevel, log.DEBUG, fmt.Sprint(v...))
} }
// Debugf show debug log // Debugf show debug log
func (l *XORMLogBridge) Debugf(format string, v ...interface{}) { func (l *XORMLogBridge) Debugf(format string, v ...interface{}) {
_ = l.Log(2, log.DEBUG, format, v...) _ = l.Log(stackLevel, log.DEBUG, format, v...)
} }
// Error show error log // Error show error log
func (l *XORMLogBridge) Error(v ...interface{}) { func (l *XORMLogBridge) Error(v ...interface{}) {
_ = l.Log(2, log.ERROR, fmt.Sprint(v...)) _ = l.Log(stackLevel, log.ERROR, fmt.Sprint(v...))
} }
// Errorf show error log // Errorf show error log
func (l *XORMLogBridge) Errorf(format string, v ...interface{}) { func (l *XORMLogBridge) Errorf(format string, v ...interface{}) {
_ = l.Log(2, log.ERROR, format, v...) _ = l.Log(stackLevel, log.ERROR, format, v...)
} }
// Info show information level log // Info show information level log
func (l *XORMLogBridge) Info(v ...interface{}) { func (l *XORMLogBridge) Info(v ...interface{}) {
_ = l.Log(2, log.INFO, fmt.Sprint(v...)) _ = l.Log(stackLevel, log.INFO, fmt.Sprint(v...))
} }
// Infof show information level log // Infof show information level log
func (l *XORMLogBridge) Infof(format string, v ...interface{}) { func (l *XORMLogBridge) Infof(format string, v ...interface{}) {
_ = l.Log(2, log.INFO, format, v...) _ = l.Log(stackLevel, log.INFO, format, v...)
} }
// Warn show warning log // Warn show warning log
func (l *XORMLogBridge) Warn(v ...interface{}) { func (l *XORMLogBridge) Warn(v ...interface{}) {
_ = l.Log(2, log.WARN, fmt.Sprint(v...)) _ = l.Log(stackLevel, log.WARN, fmt.Sprint(v...))
} }
// Warnf show warnning log // Warnf show warnning log
func (l *XORMLogBridge) Warnf(format string, v ...interface{}) { func (l *XORMLogBridge) Warnf(format string, v ...interface{}) {
_ = l.Log(2, log.WARN, format, v...) _ = l.Log(stackLevel, log.WARN, format, v...)
} }
// Level get logger level // Level get logger level

View File

@@ -39,6 +39,7 @@ func InsertMilestones(ms ...*Milestone) (err error) {
// InsertIssues insert issues to database // InsertIssues insert issues to database
func InsertIssues(issues ...*Issue) error { func InsertIssues(issues ...*Issue) error {
sess := x.NewSession() sess := x.NewSession()
defer sess.Close()
if err := sess.Begin(); err != nil { if err := sess.Begin(); err != nil {
return err return err
} }
@@ -194,6 +195,7 @@ func InsertPullRequests(prs ...*PullRequest) error {
// InsertReleases migrates release // InsertReleases migrates release
func InsertReleases(rels ...*Release) error { func InsertReleases(rels ...*Release) error {
sess := x.NewSession() sess := x.NewSession()
defer sess.Close()
if err := sess.Begin(); err != nil { if err := sess.Begin(); err != nil {
return err return err
} }

View File

@@ -235,7 +235,7 @@ func deleteOAuth2Application(sess *xorm.Session, id, userid int64) error {
if deleted, err := sess.Delete(&OAuth2Application{ID: id, UID: userid}); err != nil { if deleted, err := sess.Delete(&OAuth2Application{ID: id, UID: userid}); err != nil {
return err return err
} else if deleted == 0 { } else if deleted == 0 {
return fmt.Errorf("cannot find oauth2 application") return ErrOAuthApplicationNotFound{ID: id}
} }
codes := make([]*OAuth2AuthorizationCode, 0) codes := make([]*OAuth2AuthorizationCode, 0)
// delete correlating auth codes // delete correlating auth codes
@@ -261,6 +261,7 @@ func deleteOAuth2Application(sess *xorm.Session, id, userid int64) error {
// DeleteOAuth2Application deletes the application with the given id and the grants and auth codes related to it. It checks if the userid was the creator of the app. // DeleteOAuth2Application deletes the application with the given id and the grants and auth codes related to it. It checks if the userid was the creator of the app.
func DeleteOAuth2Application(id, userid int64) error { func DeleteOAuth2Application(id, userid int64) error {
sess := x.NewSession() sess := x.NewSession()
defer sess.Close()
if err := sess.Begin(); err != nil { if err := sess.Begin(); err != nil {
return err return err
} }

View File

@@ -406,7 +406,8 @@ func (pr *PullRequest) SetMerged() (bool, error) {
return false, fmt.Errorf("Issue.changeStatus: %v", err) return false, fmt.Errorf("Issue.changeStatus: %v", err)
} }
if _, err := sess.Where("id = ?", pr.ID).Cols("has_merged, status, merged_commit_id, merger_id, merged_unix").Update(pr); err != nil { // We need to save all of the data used to compute this merge as it may have already been changed by TestPatch. FIXME: need to set some state to prevent TestPatch from running whilst we are merging.
if _, err := sess.Where("id = ?", pr.ID).Cols("has_merged, status, merge_base, merged_commit_id, merger_id, merged_unix").Update(pr); err != nil {
return false, fmt.Errorf("Failed to update pr[%d]: %v", pr.ID, err) return false, fmt.Errorf("Failed to update pr[%d]: %v", pr.ID, err)
} }

View File

@@ -12,6 +12,7 @@ import (
"code.gitea.io/gitea/modules/util" "code.gitea.io/gitea/modules/util"
"xorm.io/builder" "xorm.io/builder"
"xorm.io/xorm"
) )
// RepositoryListDefaultPageSize is the default number of repositories // RepositoryListDefaultPageSize is the default number of repositories
@@ -363,6 +364,35 @@ func SearchRepository(opts *SearchRepoOptions) (RepositoryList, int64, error) {
// SearchRepositoryByCondition search repositories by condition // SearchRepositoryByCondition search repositories by condition
func SearchRepositoryByCondition(opts *SearchRepoOptions, cond builder.Cond, loadAttributes bool) (RepositoryList, int64, error) { func SearchRepositoryByCondition(opts *SearchRepoOptions, cond builder.Cond, loadAttributes bool) (RepositoryList, int64, error) {
sess, count, err := searchRepositoryByCondition(opts, cond)
if err != nil {
return nil, 0, err
}
defer sess.Close()
defaultSize := 50
if opts.PageSize > 0 {
defaultSize = opts.PageSize
}
repos := make(RepositoryList, 0, defaultSize)
if err := sess.Find(&repos); err != nil {
return nil, 0, fmt.Errorf("Repo: %v", err)
}
if opts.PageSize <= 0 {
count = int64(len(repos))
}
if loadAttributes {
if err := repos.loadAttributes(sess); err != nil {
return nil, 0, fmt.Errorf("LoadAttributes: %v", err)
}
}
return repos, count, nil
}
func searchRepositoryByCondition(opts *SearchRepoOptions, cond builder.Cond) (*xorm.Session, int64, error) {
if opts.Page <= 0 { if opts.Page <= 0 {
opts.Page = 1 opts.Page = 1
} }
@@ -376,31 +406,24 @@ func SearchRepositoryByCondition(opts *SearchRepoOptions, cond builder.Cond, loa
} }
sess := x.NewSession() sess := x.NewSession()
defer sess.Close()
count, err := sess. var count int64
Where(cond). if opts.PageSize > 0 {
Count(new(Repository)) var err error
if err != nil { count, err = sess.
return nil, 0, fmt.Errorf("Count: %v", err) Where(cond).
Count(new(Repository))
if err != nil {
_ = sess.Close()
return nil, 0, fmt.Errorf("Count: %v", err)
}
} }
repos := make(RepositoryList, 0, opts.PageSize)
sess.Where(cond).OrderBy(opts.OrderBy.String()) sess.Where(cond).OrderBy(opts.OrderBy.String())
if opts.PageSize > 0 { if opts.PageSize > 0 {
sess.Limit(opts.PageSize, (opts.Page-1)*opts.PageSize) sess.Limit(opts.PageSize, (opts.Page-1)*opts.PageSize)
} }
if err = sess.Find(&repos); err != nil { return sess, count, nil
return nil, 0, fmt.Errorf("Repo: %v", err)
}
if loadAttributes {
if err = repos.loadAttributes(sess); err != nil {
return nil, 0, fmt.Errorf("LoadAttributes: %v", err)
}
}
return repos, count, nil
} }
// accessibleRepositoryCondition takes a user a returns a condition for checking if a repository is accessible // accessibleRepositoryCondition takes a user a returns a condition for checking if a repository is accessible
@@ -456,6 +479,33 @@ func SearchRepositoryByName(opts *SearchRepoOptions) (RepositoryList, int64, err
return SearchRepository(opts) return SearchRepository(opts)
} }
// SearchRepositoryIDs takes keyword and part of repository name to search,
// it returns results in given range and number of total results.
func SearchRepositoryIDs(opts *SearchRepoOptions) ([]int64, int64, error) {
opts.IncludeDescription = false
cond := SearchRepositoryCondition(opts)
sess, count, err := searchRepositoryByCondition(opts, cond)
if err != nil {
return nil, 0, err
}
defer sess.Close()
defaultSize := 50
if opts.PageSize > 0 {
defaultSize = opts.PageSize
}
ids := make([]int64, 0, defaultSize)
err = sess.Select("id").Table("repository").Find(&ids)
if opts.PageSize <= 0 {
count = int64(len(ids))
}
return ids, count, err
}
// AccessibleRepoIDsQuery queries accessible repository ids. Usable as a subquery wherever repo ids need to be filtered. // AccessibleRepoIDsQuery queries accessible repository ids. Usable as a subquery wherever repo ids need to be filtered.
func AccessibleRepoIDsQuery(user *User) *builder.Builder { func AccessibleRepoIDsQuery(user *User) *builder.Builder {
// NB: Please note this code needs to still work if user is nil // NB: Please note this code needs to still work if user is nil

View File

@@ -239,10 +239,10 @@ func (u *User) GetEmail() string {
return u.Email return u.Email
} }
// GetAllUsers returns a slice of all users found in DB. // GetAllUsers returns a slice of all individual users found in DB.
func GetAllUsers() ([]*User, error) { func GetAllUsers() ([]*User, error) {
users := make([]*User, 0) users := make([]*User, 0)
return users, x.OrderBy("id").Find(&users) return users, x.OrderBy("id").Where("type = ?", UserTypeIndividual).Find(&users)
} }
// IsLocal returns true if user login type is LoginPlain. // IsLocal returns true if user login type is LoginPlain.

70
modules/analyze/vendor.go Normal file
View File

@@ -0,0 +1,70 @@
// Copyright 2021 The Gitea Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package analyze
import (
"regexp"
"sort"
"strings"
"github.com/go-enry/go-enry/v2/data"
)
var isVendorRegExp *regexp.Regexp
func init() {
matchers := data.VendorMatchers
caretStrings := make([]string, 0, 10)
caretShareStrings := make([]string, 0, 10)
matcherStrings := make([]string, 0, len(matchers))
for _, matcher := range matchers {
str := matcher.String()
if str[0] == '^' {
caretStrings = append(caretStrings, str[1:])
} else if str[0:5] == "(^|/)" {
caretShareStrings = append(caretShareStrings, str[5:])
} else {
matcherStrings = append(matcherStrings, str)
}
}
sort.Strings(caretShareStrings)
sort.Strings(caretStrings)
sort.Strings(matcherStrings)
sb := &strings.Builder{}
sb.WriteString("(?:^(?:")
sb.WriteString(caretStrings[0])
for _, matcher := range caretStrings[1:] {
sb.WriteString(")|(?:")
sb.WriteString(matcher)
}
sb.WriteString("))")
sb.WriteString("|")
sb.WriteString("(?:(?:^|/)(?:")
sb.WriteString(caretShareStrings[0])
for _, matcher := range caretShareStrings[1:] {
sb.WriteString(")|(?:")
sb.WriteString(matcher)
}
sb.WriteString("))")
sb.WriteString("|")
sb.WriteString("(?:")
sb.WriteString(matcherStrings[0])
for _, matcher := range matcherStrings[1:] {
sb.WriteString(")|(?:")
sb.WriteString(matcher)
}
sb.WriteString(")")
combined := sb.String()
isVendorRegExp = regexp.MustCompile(combined)
}
// IsVendor returns whether or not path is a vendor path.
func IsVendor(path string) bool {
return isVendorRegExp.MatchString(path)
}

View File

@@ -0,0 +1,42 @@
// Copyright 2021 The Gitea Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package analyze
import "testing"
func TestIsVendor(t *testing.T) {
tests := []struct {
path string
want bool
}{
{"cache/", true},
{"random/cache/", true},
{"cache", false},
{"dependencies/", true},
{"Dependencies/", true},
{"dependency/", false},
{"dist/", true},
{"dist", false},
{"random/dist/", true},
{"random/dist", false},
{"deps/", true},
{"configure", true},
{"a/configure", true},
{"config.guess", true},
{"config.guess/", false},
{".vscode/", true},
{"doc/_build/", true},
{"a/docs/_build/", true},
{"a/dasdocs/_build-vsdoc.js", true},
{"a/dasdocs/_build-vsdoc.j", false},
}
for _, tt := range tests {
t.Run(tt.path, func(t *testing.T) {
if got := IsVendor(tt.path); got != tt.want {
t.Errorf("IsVendor() = %v, want %v", got, tt.want)
}
})
}
}

View File

@@ -8,7 +8,6 @@ package context
import ( import (
"fmt" "fmt"
"io/ioutil" "io/ioutil"
"net/http"
"net/url" "net/url"
"path" "path"
"strings" "strings"
@@ -394,238 +393,231 @@ func RepoIDAssignment() func(ctx *Context) {
} }
// RepoAssignment returns a middleware to handle repository assignment // RepoAssignment returns a middleware to handle repository assignment
func RepoAssignment() func(http.Handler) http.Handler { func RepoAssignment(ctx *Context) {
return func(next http.Handler) http.Handler { var (
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { owner *models.User
var ( err error
owner *models.User )
err error
ctx = GetContext(req)
)
userName := ctx.Params(":username") userName := ctx.Params(":username")
repoName := ctx.Params(":reponame") repoName := ctx.Params(":reponame")
repoName = strings.TrimSuffix(repoName, ".git") repoName = strings.TrimSuffix(repoName, ".git")
// Check if the user is the same as the repository owner // Check if the user is the same as the repository owner
if ctx.IsSigned && ctx.User.LowerName == strings.ToLower(userName) { if ctx.IsSigned && ctx.User.LowerName == strings.ToLower(userName) {
owner = ctx.User owner = ctx.User
} else {
owner, err = models.GetUserByName(userName)
if err != nil {
if models.IsErrUserNotExist(err) {
if ctx.Query("go-get") == "1" {
EarlyResponseForGoGetMeta(ctx)
return
}
ctx.NotFound("GetUserByName", nil)
} else { } else {
owner, err = models.GetUserByName(userName) ctx.ServerError("GetUserByName", err)
if err != nil {
if models.IsErrUserNotExist(err) {
if ctx.Query("go-get") == "1" {
EarlyResponseForGoGetMeta(ctx)
return
}
ctx.NotFound("GetUserByName", nil)
} else {
ctx.ServerError("GetUserByName", err)
}
return
}
} }
ctx.Repo.Owner = owner return
ctx.Data["Username"] = ctx.Repo.Owner.Name }
}
ctx.Repo.Owner = owner
ctx.Data["Username"] = ctx.Repo.Owner.Name
// Get repository. // Get repository.
repo, err := models.GetRepositoryByName(owner.ID, repoName) repo, err := models.GetRepositoryByName(owner.ID, repoName)
if err != nil { if err != nil {
if models.IsErrRepoNotExist(err) { if models.IsErrRepoNotExist(err) {
redirectRepoID, err := models.LookupRepoRedirect(owner.ID, repoName) redirectRepoID, err := models.LookupRepoRedirect(owner.ID, repoName)
if err == nil {
RedirectToRepo(ctx, redirectRepoID)
} else if models.IsErrRepoRedirectNotExist(err) {
if ctx.Query("go-get") == "1" {
EarlyResponseForGoGetMeta(ctx)
return
}
ctx.NotFound("GetRepositoryByName", nil)
} else {
ctx.ServerError("LookupRepoRedirect", err)
}
} else {
ctx.ServerError("GetRepositoryByName", err)
}
return
}
repo.Owner = owner
repoAssignment(ctx, repo)
if ctx.Written() {
return
}
ctx.Repo.RepoLink = repo.Link()
ctx.Data["RepoLink"] = ctx.Repo.RepoLink
ctx.Data["RepoRelPath"] = ctx.Repo.Owner.Name + "/" + ctx.Repo.Repository.Name
unit, err := ctx.Repo.Repository.GetUnit(models.UnitTypeExternalTracker)
if err == nil { if err == nil {
ctx.Data["RepoExternalIssuesLink"] = unit.ExternalTrackerConfig().ExternalTrackerURL RedirectToRepo(ctx, redirectRepoID)
} } else if models.IsErrRepoRedirectNotExist(err) {
if ctx.Query("go-get") == "1" {
ctx.Data["NumTags"], err = models.GetReleaseCountByRepoID(ctx.Repo.Repository.ID, models.FindReleasesOptions{ EarlyResponseForGoGetMeta(ctx)
IncludeTags: true,
})
if err != nil {
ctx.ServerError("GetReleaseCountByRepoID", err)
return
}
ctx.Data["NumReleases"], err = models.GetReleaseCountByRepoID(ctx.Repo.Repository.ID, models.FindReleasesOptions{})
if err != nil {
ctx.ServerError("GetReleaseCountByRepoID", err)
return
}
ctx.Data["Title"] = owner.Name + "/" + repo.Name
ctx.Data["Repository"] = repo
ctx.Data["Owner"] = ctx.Repo.Repository.Owner
ctx.Data["IsRepositoryOwner"] = ctx.Repo.IsOwner()
ctx.Data["IsRepositoryAdmin"] = ctx.Repo.IsAdmin()
ctx.Data["RepoOwnerIsOrganization"] = repo.Owner.IsOrganization()
ctx.Data["CanWriteCode"] = ctx.Repo.CanWrite(models.UnitTypeCode)
ctx.Data["CanWriteIssues"] = ctx.Repo.CanWrite(models.UnitTypeIssues)
ctx.Data["CanWritePulls"] = ctx.Repo.CanWrite(models.UnitTypePullRequests)
if ctx.Data["CanSignedUserFork"], err = ctx.Repo.Repository.CanUserFork(ctx.User); err != nil {
ctx.ServerError("CanUserFork", err)
return
}
ctx.Data["DisableSSH"] = setting.SSH.Disabled
ctx.Data["ExposeAnonSSH"] = setting.SSH.ExposeAnonymous
ctx.Data["DisableHTTP"] = setting.Repository.DisableHTTPGit
ctx.Data["RepoSearchEnabled"] = setting.Indexer.RepoIndexerEnabled
ctx.Data["CloneLink"] = repo.CloneLink()
ctx.Data["WikiCloneLink"] = repo.WikiCloneLink()
if ctx.IsSigned {
ctx.Data["IsWatchingRepo"] = models.IsWatching(ctx.User.ID, repo.ID)
ctx.Data["IsStaringRepo"] = models.IsStaring(ctx.User.ID, repo.ID)
}
if repo.IsFork {
RetrieveBaseRepo(ctx, repo)
if ctx.Written() {
return return
} }
ctx.NotFound("GetRepositoryByName", nil)
} else {
ctx.ServerError("LookupRepoRedirect", err)
} }
} else {
ctx.ServerError("GetRepositoryByName", err)
}
return
}
repo.Owner = owner
if repo.IsGenerated() { repoAssignment(ctx, repo)
RetrieveTemplateRepo(ctx, repo) if ctx.Written() {
if ctx.Written() { return
return }
}
}
// Disable everything when the repo is being created ctx.Repo.RepoLink = repo.Link()
if ctx.Repo.Repository.IsBeingCreated() { ctx.Data["RepoLink"] = ctx.Repo.RepoLink
ctx.Data["BranchName"] = ctx.Repo.Repository.DefaultBranch ctx.Data["RepoRelPath"] = ctx.Repo.Owner.Name + "/" + ctx.Repo.Repository.Name
return
}
gitRepo, err := git.OpenRepository(models.RepoPath(userName, repoName)) unit, err := ctx.Repo.Repository.GetUnit(models.UnitTypeExternalTracker)
if err != nil { if err == nil {
ctx.ServerError("RepoAssignment Invalid repo "+models.RepoPath(userName, repoName), err) ctx.Data["RepoExternalIssuesLink"] = unit.ExternalTrackerConfig().ExternalTrackerURL
return }
}
ctx.Repo.GitRepo = gitRepo
// We opened it, we should close it ctx.Data["NumTags"], err = models.GetReleaseCountByRepoID(ctx.Repo.Repository.ID, models.FindReleasesOptions{
defer func() { IncludeTags: true,
// If it's been set to nil then assume someone else has closed it. })
if ctx.Repo.GitRepo != nil { if err != nil {
ctx.Repo.GitRepo.Close() ctx.ServerError("GetReleaseCountByRepoID", err)
} return
}() }
ctx.Data["NumReleases"], err = models.GetReleaseCountByRepoID(ctx.Repo.Repository.ID, models.FindReleasesOptions{})
if err != nil {
ctx.ServerError("GetReleaseCountByRepoID", err)
return
}
// Stop at this point when the repo is empty. ctx.Data["Title"] = owner.Name + "/" + repo.Name
if ctx.Repo.Repository.IsEmpty { ctx.Data["Repository"] = repo
ctx.Data["BranchName"] = ctx.Repo.Repository.DefaultBranch ctx.Data["Owner"] = ctx.Repo.Repository.Owner
next.ServeHTTP(w, req) ctx.Data["IsRepositoryOwner"] = ctx.Repo.IsOwner()
return ctx.Data["IsRepositoryAdmin"] = ctx.Repo.IsAdmin()
} ctx.Data["RepoOwnerIsOrganization"] = repo.Owner.IsOrganization()
ctx.Data["CanWriteCode"] = ctx.Repo.CanWrite(models.UnitTypeCode)
ctx.Data["CanWriteIssues"] = ctx.Repo.CanWrite(models.UnitTypeIssues)
ctx.Data["CanWritePulls"] = ctx.Repo.CanWrite(models.UnitTypePullRequests)
tags, err := ctx.Repo.GitRepo.GetTags() if ctx.Data["CanSignedUserFork"], err = ctx.Repo.Repository.CanUserFork(ctx.User); err != nil {
if err != nil { ctx.ServerError("CanUserFork", err)
ctx.ServerError("GetTags", err) return
return }
}
ctx.Data["Tags"] = tags
brs, _, err := ctx.Repo.GitRepo.GetBranches(0, 0) ctx.Data["DisableSSH"] = setting.SSH.Disabled
if err != nil { ctx.Data["ExposeAnonSSH"] = setting.SSH.ExposeAnonymous
ctx.ServerError("GetBranches", err) ctx.Data["DisableHTTP"] = setting.Repository.DisableHTTPGit
return ctx.Data["RepoSearchEnabled"] = setting.Indexer.RepoIndexerEnabled
} ctx.Data["CloneLink"] = repo.CloneLink()
ctx.Data["Branches"] = brs ctx.Data["WikiCloneLink"] = repo.WikiCloneLink()
ctx.Data["BranchesCount"] = len(brs)
ctx.Data["TagName"] = ctx.Repo.TagName if ctx.IsSigned {
ctx.Data["IsWatchingRepo"] = models.IsWatching(ctx.User.ID, repo.ID)
ctx.Data["IsStaringRepo"] = models.IsStaring(ctx.User.ID, repo.ID)
}
// If not branch selected, try default one. if repo.IsFork {
// If default branch doesn't exists, fall back to some other branch. RetrieveBaseRepo(ctx, repo)
if len(ctx.Repo.BranchName) == 0 { if ctx.Written() {
if len(ctx.Repo.Repository.DefaultBranch) > 0 && gitRepo.IsBranchExist(ctx.Repo.Repository.DefaultBranch) { return
ctx.Repo.BranchName = ctx.Repo.Repository.DefaultBranch }
} else if len(brs) > 0 { }
ctx.Repo.BranchName = brs[0]
}
}
ctx.Data["BranchName"] = ctx.Repo.BranchName
ctx.Data["CommitID"] = ctx.Repo.CommitID
// People who have push access or have forked repository can propose a new pull request. if repo.IsGenerated() {
canPush := ctx.Repo.CanWrite(models.UnitTypeCode) || (ctx.IsSigned && ctx.User.HasForkedRepo(ctx.Repo.Repository.ID)) RetrieveTemplateRepo(ctx, repo)
canCompare := false if ctx.Written() {
return
}
}
// Pull request is allowed if this is a fork repository // Disable everything when the repo is being created
// and base repository accepts pull requests. if ctx.Repo.Repository.IsBeingCreated() {
if repo.BaseRepo != nil && repo.BaseRepo.AllowsPulls() { ctx.Data["BranchName"] = ctx.Repo.Repository.DefaultBranch
canCompare = true return
ctx.Data["BaseRepo"] = repo.BaseRepo }
ctx.Repo.PullRequest.BaseRepo = repo.BaseRepo
ctx.Repo.PullRequest.Allowed = canPush
ctx.Repo.PullRequest.HeadInfo = ctx.Repo.Owner.Name + ":" + ctx.Repo.BranchName
} else if repo.AllowsPulls() {
// Or, this is repository accepts pull requests between branches.
canCompare = true
ctx.Data["BaseRepo"] = repo
ctx.Repo.PullRequest.BaseRepo = repo
ctx.Repo.PullRequest.Allowed = canPush
ctx.Repo.PullRequest.SameRepo = true
ctx.Repo.PullRequest.HeadInfo = ctx.Repo.BranchName
}
ctx.Data["CanCompareOrPull"] = canCompare
ctx.Data["PullRequestCtx"] = ctx.Repo.PullRequest
if ctx.Repo.Repository.Status == models.RepositoryPendingTransfer { gitRepo, err := git.OpenRepository(models.RepoPath(userName, repoName))
repoTransfer, err := models.GetPendingRepositoryTransfer(ctx.Repo.Repository) if err != nil {
if err != nil { ctx.ServerError("RepoAssignment Invalid repo "+models.RepoPath(userName, repoName), err)
ctx.ServerError("GetPendingRepositoryTransfer", err) return
return }
} ctx.Repo.GitRepo = gitRepo
if err := repoTransfer.LoadAttributes(); err != nil { // We opened it, we should close it
ctx.ServerError("LoadRecipient", err) defer func() {
return // If it's been set to nil then assume someone else has closed it.
} if ctx.Repo.GitRepo != nil {
ctx.Repo.GitRepo.Close()
}
}()
ctx.Data["RepoTransfer"] = repoTransfer // Stop at this point when the repo is empty.
if ctx.User != nil { if ctx.Repo.Repository.IsEmpty {
ctx.Data["CanUserAcceptTransfer"] = repoTransfer.CanUserAcceptTransfer(ctx.User) ctx.Data["BranchName"] = ctx.Repo.Repository.DefaultBranch
} return
} }
if ctx.Query("go-get") == "1" { tags, err := ctx.Repo.GitRepo.GetTags()
ctx.Data["GoGetImport"] = ComposeGoGetImport(owner.Name, repo.Name) if err != nil {
prefix := setting.AppURL + path.Join(owner.Name, repo.Name, "src", "branch", ctx.Repo.BranchName) ctx.ServerError("GetTags", err)
ctx.Data["GoDocDirectory"] = prefix + "{/dir}" return
ctx.Data["GoDocFile"] = prefix + "{/dir}/{file}#L{line}" }
} ctx.Data["Tags"] = tags
next.ServeHTTP(w, req)
}) brs, _, err := ctx.Repo.GitRepo.GetBranches(0, 0)
if err != nil {
ctx.ServerError("GetBranches", err)
return
}
ctx.Data["Branches"] = brs
ctx.Data["BranchesCount"] = len(brs)
ctx.Data["TagName"] = ctx.Repo.TagName
// If not branch selected, try default one.
// If default branch doesn't exists, fall back to some other branch.
if len(ctx.Repo.BranchName) == 0 {
if len(ctx.Repo.Repository.DefaultBranch) > 0 && gitRepo.IsBranchExist(ctx.Repo.Repository.DefaultBranch) {
ctx.Repo.BranchName = ctx.Repo.Repository.DefaultBranch
} else if len(brs) > 0 {
ctx.Repo.BranchName = brs[0]
}
}
ctx.Data["BranchName"] = ctx.Repo.BranchName
ctx.Data["CommitID"] = ctx.Repo.CommitID
// People who have push access or have forked repository can propose a new pull request.
canPush := ctx.Repo.CanWrite(models.UnitTypeCode) || (ctx.IsSigned && ctx.User.HasForkedRepo(ctx.Repo.Repository.ID))
canCompare := false
// Pull request is allowed if this is a fork repository
// and base repository accepts pull requests.
if repo.BaseRepo != nil && repo.BaseRepo.AllowsPulls() {
canCompare = true
ctx.Data["BaseRepo"] = repo.BaseRepo
ctx.Repo.PullRequest.BaseRepo = repo.BaseRepo
ctx.Repo.PullRequest.Allowed = canPush
ctx.Repo.PullRequest.HeadInfo = ctx.Repo.Owner.Name + ":" + ctx.Repo.BranchName
} else if repo.AllowsPulls() {
// Or, this is repository accepts pull requests between branches.
canCompare = true
ctx.Data["BaseRepo"] = repo
ctx.Repo.PullRequest.BaseRepo = repo
ctx.Repo.PullRequest.Allowed = canPush
ctx.Repo.PullRequest.SameRepo = true
ctx.Repo.PullRequest.HeadInfo = ctx.Repo.BranchName
}
ctx.Data["CanCompareOrPull"] = canCompare
ctx.Data["PullRequestCtx"] = ctx.Repo.PullRequest
if ctx.Repo.Repository.Status == models.RepositoryPendingTransfer {
repoTransfer, err := models.GetPendingRepositoryTransfer(ctx.Repo.Repository)
if err != nil {
ctx.ServerError("GetPendingRepositoryTransfer", err)
return
}
if err := repoTransfer.LoadAttributes(); err != nil {
ctx.ServerError("LoadRecipient", err)
return
}
ctx.Data["RepoTransfer"] = repoTransfer
if ctx.User != nil {
ctx.Data["CanUserAcceptTransfer"] = repoTransfer.CanUserAcceptTransfer(ctx.User)
}
}
if ctx.Query("go-get") == "1" {
ctx.Data["GoGetImport"] = ComposeGoGetImport(owner.Name, repo.Name)
prefix := setting.AppURL + path.Join(owner.Name, repo.Name, "src", "branch", ctx.Repo.BranchName)
ctx.Data["GoDocDirectory"] = prefix + "{/dir}"
ctx.Data["GoDocFile"] = prefix + "{/dir}/{file}#L{line}"
} }
} }
@@ -651,7 +643,7 @@ const (
// RepoRef handles repository reference names when the ref name is not // RepoRef handles repository reference names when the ref name is not
// explicitly given // explicitly given
func RepoRef() func(http.Handler) http.Handler { func RepoRef() func(*Context) {
// since no ref name is explicitly specified, ok to just use branch // since no ref name is explicitly specified, ok to just use branch
return RepoRefByType(RepoRefBranch) return RepoRefByType(RepoRefBranch)
} }
@@ -730,130 +722,125 @@ func getRefName(ctx *Context, pathType RepoRefType) string {
// RepoRefByType handles repository reference name for a specific type // RepoRefByType handles repository reference name for a specific type
// of repository reference // of repository reference
func RepoRefByType(refType RepoRefType) func(http.Handler) http.Handler { func RepoRefByType(refType RepoRefType) func(*Context) {
return func(next http.Handler) http.Handler { return func(ctx *Context) {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { // Empty repository does not have reference information.
ctx := GetContext(req) if ctx.Repo.Repository.IsEmpty {
// Empty repository does not have reference information. return
if ctx.Repo.Repository.IsEmpty { }
var (
refName string
err error
)
if ctx.Repo.GitRepo == nil {
repoPath := models.RepoPath(ctx.Repo.Owner.Name, ctx.Repo.Repository.Name)
ctx.Repo.GitRepo, err = git.OpenRepository(repoPath)
if err != nil {
ctx.ServerError("RepoRef Invalid repo "+repoPath, err)
return return
} }
// We opened it, we should close it
defer func() {
// If it's been set to nil then assume someone else has closed it.
if ctx.Repo.GitRepo != nil {
ctx.Repo.GitRepo.Close()
}
}()
}
var ( // Get default branch.
refName string if len(ctx.Params("*")) == 0 {
err error refName = ctx.Repo.Repository.DefaultBranch
) ctx.Repo.BranchName = refName
if !ctx.Repo.GitRepo.IsBranchExist(refName) {
if ctx.Repo.GitRepo == nil { brs, _, err := ctx.Repo.GitRepo.GetBranches(0, 0)
repoPath := models.RepoPath(ctx.Repo.Owner.Name, ctx.Repo.Repository.Name)
ctx.Repo.GitRepo, err = git.OpenRepository(repoPath)
if err != nil { if err != nil {
ctx.ServerError("RepoRef Invalid repo "+repoPath, err) ctx.ServerError("GetBranches", err)
return
} else if len(brs) == 0 {
err = fmt.Errorf("No branches in non-empty repository %s",
ctx.Repo.GitRepo.Path)
ctx.ServerError("GetBranches", err)
return return
} }
// We opened it, we should close it refName = brs[0]
defer func() {
// If it's been set to nil then assume someone else has closed it.
if ctx.Repo.GitRepo != nil {
ctx.Repo.GitRepo.Close()
}
}()
} }
ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetBranchCommit(refName)
if err != nil {
ctx.ServerError("GetBranchCommit", err)
return
}
ctx.Repo.CommitID = ctx.Repo.Commit.ID.String()
ctx.Repo.IsViewBranch = true
} else {
refName = getRefName(ctx, refType)
ctx.Repo.BranchName = refName
if refType.RefTypeIncludesBranches() && ctx.Repo.GitRepo.IsBranchExist(refName) {
ctx.Repo.IsViewBranch = true
// Get default branch.
if len(ctx.Params("*")) == 0 {
refName = ctx.Repo.Repository.DefaultBranch
ctx.Repo.BranchName = refName
if !ctx.Repo.GitRepo.IsBranchExist(refName) {
brs, _, err := ctx.Repo.GitRepo.GetBranches(0, 0)
if err != nil {
ctx.ServerError("GetBranches", err)
return
} else if len(brs) == 0 {
err = fmt.Errorf("No branches in non-empty repository %s",
ctx.Repo.GitRepo.Path)
ctx.ServerError("GetBranches", err)
return
}
refName = brs[0]
}
ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetBranchCommit(refName) ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetBranchCommit(refName)
if err != nil { if err != nil {
ctx.ServerError("GetBranchCommit", err) ctx.ServerError("GetBranchCommit", err)
return return
} }
ctx.Repo.CommitID = ctx.Repo.Commit.ID.String() ctx.Repo.CommitID = ctx.Repo.Commit.ID.String()
ctx.Repo.IsViewBranch = true
} else if refType.RefTypeIncludesTags() && ctx.Repo.GitRepo.IsTagExist(refName) {
ctx.Repo.IsViewTag = true
ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetTagCommit(refName)
if err != nil {
ctx.ServerError("GetTagCommit", err)
return
}
ctx.Repo.CommitID = ctx.Repo.Commit.ID.String()
} else if len(refName) >= 7 && len(refName) <= 40 {
ctx.Repo.IsViewCommit = true
ctx.Repo.CommitID = refName
ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetCommit(refName)
if err != nil {
ctx.NotFound("GetCommit", err)
return
}
// If short commit ID add canonical link header
if len(refName) < 40 {
ctx.Header().Set("Link", fmt.Sprintf("<%s>; rel=\"canonical\"",
util.URLJoin(setting.AppURL, strings.Replace(ctx.Req.URL.RequestURI(), refName, ctx.Repo.Commit.ID.String(), 1))))
}
} else { } else {
refName = getRefName(ctx, refType) ctx.NotFound("RepoRef invalid repo", fmt.Errorf("branch or tag not exist: %s", refName))
ctx.Repo.BranchName = refName
if refType.RefTypeIncludesBranches() && ctx.Repo.GitRepo.IsBranchExist(refName) {
ctx.Repo.IsViewBranch = true
ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetBranchCommit(refName)
if err != nil {
ctx.ServerError("GetBranchCommit", err)
return
}
ctx.Repo.CommitID = ctx.Repo.Commit.ID.String()
} else if refType.RefTypeIncludesTags() && ctx.Repo.GitRepo.IsTagExist(refName) {
ctx.Repo.IsViewTag = true
ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetTagCommit(refName)
if err != nil {
ctx.ServerError("GetTagCommit", err)
return
}
ctx.Repo.CommitID = ctx.Repo.Commit.ID.String()
} else if len(refName) >= 7 && len(refName) <= 40 {
ctx.Repo.IsViewCommit = true
ctx.Repo.CommitID = refName
ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetCommit(refName)
if err != nil {
ctx.NotFound("GetCommit", err)
return
}
// If short commit ID add canonical link header
if len(refName) < 40 {
ctx.Header().Set("Link", fmt.Sprintf("<%s>; rel=\"canonical\"",
util.URLJoin(setting.AppURL, strings.Replace(ctx.Req.URL.RequestURI(), refName, ctx.Repo.Commit.ID.String(), 1))))
}
} else {
ctx.NotFound("RepoRef invalid repo", fmt.Errorf("branch or tag not exist: %s", refName))
return
}
if refType == RepoRefLegacy {
// redirect from old URL scheme to new URL scheme
ctx.Redirect(path.Join(
setting.AppSubURL,
strings.TrimSuffix(ctx.Req.URL.Path, ctx.Params("*")),
ctx.Repo.BranchNameSubURL(),
ctx.Repo.TreePath))
return
}
}
ctx.Data["BranchName"] = ctx.Repo.BranchName
ctx.Data["BranchNameSubURL"] = ctx.Repo.BranchNameSubURL()
ctx.Data["CommitID"] = ctx.Repo.CommitID
ctx.Data["TreePath"] = ctx.Repo.TreePath
ctx.Data["IsViewBranch"] = ctx.Repo.IsViewBranch
ctx.Data["IsViewTag"] = ctx.Repo.IsViewTag
ctx.Data["IsViewCommit"] = ctx.Repo.IsViewCommit
ctx.Data["CanCreateBranch"] = ctx.Repo.CanCreateBranch()
ctx.Repo.CommitsCount, err = ctx.Repo.GetCommitsCount()
if err != nil {
ctx.ServerError("GetCommitsCount", err)
return return
} }
ctx.Data["CommitsCount"] = ctx.Repo.CommitsCount
next.ServeHTTP(w, req) if refType == RepoRefLegacy {
}) // redirect from old URL scheme to new URL scheme
ctx.Redirect(path.Join(
setting.AppSubURL,
strings.TrimSuffix(ctx.Req.URL.Path, ctx.Params("*")),
ctx.Repo.BranchNameSubURL(),
ctx.Repo.TreePath))
return
}
}
ctx.Data["BranchName"] = ctx.Repo.BranchName
ctx.Data["BranchNameSubURL"] = ctx.Repo.BranchNameSubURL()
ctx.Data["CommitID"] = ctx.Repo.CommitID
ctx.Data["TreePath"] = ctx.Repo.TreePath
ctx.Data["IsViewBranch"] = ctx.Repo.IsViewBranch
ctx.Data["IsViewTag"] = ctx.Repo.IsViewTag
ctx.Data["IsViewCommit"] = ctx.Repo.IsViewCommit
ctx.Data["CanCreateBranch"] = ctx.Repo.CanCreateBranch()
ctx.Repo.CommitsCount, err = ctx.Repo.GetCommitsCount()
if err != nil {
ctx.ServerError("GetCommitsCount", err)
return
}
ctx.Data["CommitsCount"] = ctx.Repo.CommitsCount
} }
} }

View File

@@ -85,18 +85,17 @@ func ToPullReviewCommentList(review *models.Review, doer *models.User) ([]*api.P
apiComments := make([]*api.PullReviewComment, 0, len(review.CodeComments)) apiComments := make([]*api.PullReviewComment, 0, len(review.CodeComments))
auth := false
if doer != nil {
auth = doer.IsAdmin || doer.ID == review.ReviewerID
}
for _, lines := range review.CodeComments { for _, lines := range review.CodeComments {
for _, comments := range lines { for _, comments := range lines {
for _, comment := range comments { for _, comment := range comments {
auth := false
if doer != nil {
auth = doer.IsAdmin || doer.ID == comment.Poster.ID
}
apiComment := &api.PullReviewComment{ apiComment := &api.PullReviewComment{
ID: comment.ID, ID: comment.ID,
Body: comment.Content, Body: comment.Content,
Reviewer: ToUser(review.Reviewer, doer != nil, auth), Reviewer: ToUser(comment.Poster, doer != nil, auth),
ReviewID: review.ID, ReviewID: review.ID,
Created: comment.CreatedUnix.AsTime(), Created: comment.CreatedUnix.AsTime(),
Updated: comment.UpdatedUnix.AsTime(), Updated: comment.UpdatedUnix.AsTime(),

View File

@@ -47,7 +47,7 @@ func GetRawDiffForFile(repoPath, startCommit, endCommit string, diffType RawDiff
func GetRepoRawDiffForFile(repo *Repository, startCommit, endCommit string, diffType RawDiffType, file string, writer io.Writer) error { func GetRepoRawDiffForFile(repo *Repository, startCommit, endCommit string, diffType RawDiffType, file string, writer io.Writer) error {
commit, err := repo.GetCommit(endCommit) commit, err := repo.GetCommit(endCommit)
if err != nil { if err != nil {
return fmt.Errorf("GetCommit: %v", err) return err
} }
fileArgs := make([]string, 0) fileArgs := make([]string, 0)
if len(file) > 0 { if len(file) > 0 {

View File

@@ -43,7 +43,7 @@ func (repo *Repository) GetLanguageStats(commitID string) (map[string]int64, err
sizes := make(map[string]int64) sizes := make(map[string]int64)
err = tree.Files().ForEach(func(f *object.File) error { err = tree.Files().ForEach(func(f *object.File) error {
if f.Size == 0 || enry.IsVendor(f.Name) || enry.IsDotFile(f.Name) || if f.Size == 0 || analyze.IsVendor(f.Name) || enry.IsDotFile(f.Name) ||
enry.IsDocumentation(f.Name) || enry.IsConfiguration(f.Name) { enry.IsDocumentation(f.Name) || enry.IsConfiguration(f.Name) {
return nil return nil
} }

View File

@@ -67,7 +67,7 @@ func (repo *Repository) GetLanguageStats(commitID string) (map[string]int64, err
for _, f := range entries { for _, f := range entries {
contentBuf.Reset() contentBuf.Reset()
content = contentBuf.Bytes() content = contentBuf.Bytes()
if f.Size() == 0 || enry.IsVendor(f.Name()) || enry.IsDotFile(f.Name()) || if f.Size() == 0 || analyze.IsVendor(f.Name()) || enry.IsDotFile(f.Name()) ||
enry.IsDocumentation(f.Name()) || enry.IsConfiguration(f.Name()) { enry.IsDocumentation(f.Name()) || enry.IsConfiguration(f.Name()) {
continue continue
} }

View File

@@ -68,17 +68,19 @@ func (g *Manager) start() {
// Set the running state // Set the running state
g.setState(stateRunning) g.setState(stateRunning)
if skip, _ := strconv.ParseBool(os.Getenv("SKIP_MINWINSVC")); skip { if skip, _ := strconv.ParseBool(os.Getenv("SKIP_MINWINSVC")); skip {
log.Trace("Skipping SVC check as SKIP_MINWINSVC is set")
return return
} }
// Make SVC process // Make SVC process
run := svc.Run run := svc.Run
isInteractive, err := svc.IsWindowsService() isWindowsService, err := svc.IsWindowsService()
if err != nil { if err != nil {
log.Error("Unable to ascertain if running as an Interactive Session: %v", err) log.Error("Unable to ascertain if running as an Windows Service: %v", err)
return return
} }
if isInteractive { if !isWindowsService {
log.Trace("Not running a service ... using the debug SVC manager")
run = debug.Run run = debug.Run
} }
go func() { go func() {
@@ -94,38 +96,49 @@ func (g *Manager) Execute(args []string, changes <-chan svc.ChangeRequest, statu
status <- svc.Status{State: svc.StartPending, WaitHint: uint32(setting.StartupTimeout / time.Millisecond)} status <- svc.Status{State: svc.StartPending, WaitHint: uint32(setting.StartupTimeout / time.Millisecond)}
} }
log.Trace("Awaiting server start-up")
// Now need to wait for everything to start... // Now need to wait for everything to start...
if !g.awaitServer(setting.StartupTimeout) { if !g.awaitServer(setting.StartupTimeout) {
log.Trace("... start-up failed ... Stopped")
return false, 1 return false, 1
} }
log.Trace("Sending Running state to SVC")
// We need to implement some way of svc.AcceptParamChange/svc.ParamChange // We need to implement some way of svc.AcceptParamChange/svc.ParamChange
status <- svc.Status{ status <- svc.Status{
State: svc.Running, State: svc.Running,
Accepts: svc.AcceptStop | svc.AcceptShutdown | acceptHammerCode, Accepts: svc.AcceptStop | svc.AcceptShutdown | acceptHammerCode,
} }
log.Trace("Started")
waitTime := 30 * time.Second waitTime := 30 * time.Second
loop: loop:
for { for {
select { select {
case <-g.ctx.Done(): case <-g.ctx.Done():
log.Trace("Shutting down")
g.DoGracefulShutdown() g.DoGracefulShutdown()
waitTime += setting.GracefulHammerTime waitTime += setting.GracefulHammerTime
break loop break loop
case <-g.shutdownRequested: case <-g.shutdownRequested:
log.Trace("Shutting down")
waitTime += setting.GracefulHammerTime waitTime += setting.GracefulHammerTime
break loop break loop
case change := <-changes: case change := <-changes:
switch change.Cmd { switch change.Cmd {
case svc.Interrogate: case svc.Interrogate:
log.Trace("SVC sent interrogate")
status <- change.CurrentStatus status <- change.CurrentStatus
case svc.Stop, svc.Shutdown: case svc.Stop, svc.Shutdown:
log.Trace("SVC requested shutdown - shutting down")
g.DoGracefulShutdown() g.DoGracefulShutdown()
waitTime += setting.GracefulHammerTime waitTime += setting.GracefulHammerTime
break loop break loop
case hammerCode: case hammerCode:
log.Trace("SVC requested hammer - shutting down and hammering immediately")
g.DoGracefulShutdown() g.DoGracefulShutdown()
g.DoImmediateHammer() g.DoImmediateHammer()
break loop break loop
@@ -134,6 +147,8 @@ loop:
} }
} }
} }
log.Trace("Sending StopPending state to SVC")
status <- svc.Status{ status <- svc.Status{
State: svc.StopPending, State: svc.StopPending,
WaitHint: uint32(waitTime / time.Millisecond), WaitHint: uint32(waitTime / time.Millisecond),
@@ -145,8 +160,10 @@ hammerLoop:
case change := <-changes: case change := <-changes:
switch change.Cmd { switch change.Cmd {
case svc.Interrogate: case svc.Interrogate:
log.Trace("SVC sent interrogate")
status <- change.CurrentStatus status <- change.CurrentStatus
case svc.Stop, svc.Shutdown, hammerCmd: case svc.Stop, svc.Shutdown, hammerCmd:
log.Trace("SVC requested hammer - hammering immediately")
g.DoImmediateHammer() g.DoImmediateHammer()
break hammerLoop break hammerLoop
default: default:
@@ -156,6 +173,8 @@ hammerLoop:
break hammerLoop break hammerLoop
} }
} }
log.Trace("Stopped")
return false, 0 return false, 0
} }

View File

@@ -178,7 +178,7 @@ func NewBleveIndexer(indexDir string) (*BleveIndexer, bool, error) {
func (b *BleveIndexer) addUpdate(batchWriter *io.PipeWriter, batchReader *bufio.Reader, commitSha string, update fileUpdate, repo *models.Repository, batch rupture.FlushingBatch) error { func (b *BleveIndexer) addUpdate(batchWriter *io.PipeWriter, batchReader *bufio.Reader, commitSha string, update fileUpdate, repo *models.Repository, batch rupture.FlushingBatch) error {
// Ignore vendored files in code search // Ignore vendored files in code search
if setting.Indexer.ExcludeVendored && enry.IsVendor(update.Filename) { if setting.Indexer.ExcludeVendored && analyze.IsVendor(update.Filename) {
return nil return nil
} }

View File

@@ -177,7 +177,7 @@ func (b *ElasticSearchIndexer) init() (bool, error) {
func (b *ElasticSearchIndexer) addUpdate(batchWriter *io.PipeWriter, batchReader *bufio.Reader, sha string, update fileUpdate, repo *models.Repository) ([]elastic.BulkableRequest, error) { func (b *ElasticSearchIndexer) addUpdate(batchWriter *io.PipeWriter, batchReader *bufio.Reader, sha string, update fileUpdate, repo *models.Repository) ([]elastic.BulkableRequest, error) {
// Ignore vendored files in code search // Ignore vendored files in code search
if setting.Indexer.ExcludeVendored && enry.IsVendor(update.Filename) { if setting.Indexer.ExcludeVendored && analyze.IsVendor(update.Filename) {
return nil, nil return nil, nil
} }

View File

@@ -44,24 +44,13 @@ type ContentStore struct {
} }
// Get takes a Meta object and retrieves the content from the store, returning // Get takes a Meta object and retrieves the content from the store, returning
// it as an io.Reader. If fromByte > 0, the reader starts from that byte // it as an io.ReadSeekCloser.
func (s *ContentStore) Get(meta *models.LFSMetaObject, fromByte int64) (io.ReadCloser, error) { func (s *ContentStore) Get(meta *models.LFSMetaObject) (storage.Object, error) {
f, err := s.Open(meta.RelativePath()) f, err := s.Open(meta.RelativePath())
if err != nil { if err != nil {
log.Error("Whilst trying to read LFS OID[%s]: Unable to open Error: %v", meta.Oid, err) log.Error("Whilst trying to read LFS OID[%s]: Unable to open Error: %v", meta.Oid, err)
return nil, err return nil, err
} }
if fromByte > 0 {
if fromByte >= meta.Size {
return nil, ErrRangeNotSatisfiable{
FromByte: fromByte,
}
}
_, err = f.Seek(fromByte, io.SeekStart)
if err != nil {
log.Error("Whilst trying to read LFS OID[%s]: Unable to seek to %d Error: %v", meta.Oid, fromByte, err)
}
}
return f, err return f, err
} }
@@ -74,7 +63,7 @@ func (s *ContentStore) Put(meta *models.LFSMetaObject, r io.Reader) error {
// now pass the wrapped reader to Save - if there is a size mismatch or hash mismatch then // now pass the wrapped reader to Save - if there is a size mismatch or hash mismatch then
// the errors returned by the newHashingReader should percolate up to here // the errors returned by the newHashingReader should percolate up to here
written, err := s.Save(p, wrappedRd) written, err := s.Save(p, wrappedRd, meta.Size)
if err != nil { if err != nil {
log.Error("Whilst putting LFS OID[%s]: Failed to copy to tmpPath: %s Error: %v", meta.Oid, p, err) log.Error("Whilst putting LFS OID[%s]: Failed to copy to tmpPath: %s Error: %v", meta.Oid, p, err)
return err return err

View File

@@ -67,5 +67,5 @@ func IsPointerFile(buf *[]byte) *models.LFSMetaObject {
// ReadMetaObject will read a models.LFSMetaObject and return a reader // ReadMetaObject will read a models.LFSMetaObject and return a reader
func ReadMetaObject(meta *models.LFSMetaObject) (io.ReadCloser, error) { func ReadMetaObject(meta *models.LFSMetaObject) (io.ReadCloser, error) {
contentStore := &ContentStore{ObjectStorage: storage.LFS} contentStore := &ContentStore{ObjectStorage: storage.LFS}
return contentStore.Get(meta, 0) return contentStore.Get(meta)
} }

View File

@@ -175,6 +175,11 @@ func getContentHandler(ctx *context.Context) {
statusCode = 206 statusCode = 206
fromByte, _ = strconv.ParseInt(match[1], 10, 32) fromByte, _ = strconv.ParseInt(match[1], 10, 32)
if fromByte >= meta.Size {
writeStatus(ctx, http.StatusRequestedRangeNotSatisfiable)
return
}
if match[2] != "" { if match[2] != "" {
_toByte, _ := strconv.ParseInt(match[2], 10, 32) _toByte, _ := strconv.ParseInt(match[2], 10, 32)
if _toByte >= fromByte && _toByte < toByte { if _toByte >= fromByte && _toByte < toByte {
@@ -188,18 +193,24 @@ func getContentHandler(ctx *context.Context) {
} }
contentStore := &ContentStore{ObjectStorage: storage.LFS} contentStore := &ContentStore{ObjectStorage: storage.LFS}
content, err := contentStore.Get(meta, fromByte) content, err := contentStore.Get(meta)
if err != nil { if err != nil {
if IsErrRangeNotSatisfiable(err) { // Errors are logged in contentStore.Get
writeStatus(ctx, http.StatusRequestedRangeNotSatisfiable) writeStatus(ctx, http.StatusNotFound)
} else {
// Errors are logged in contentStore.Get
writeStatus(ctx, 404)
}
return return
} }
defer content.Close() defer content.Close()
if fromByte > 0 {
_, err = content.Seek(fromByte, io.SeekStart)
if err != nil {
log.Error("Whilst trying to read LFS OID[%s]: Unable to seek to %d Error: %v", meta.Oid, fromByte, err)
writeStatus(ctx, http.StatusInternalServerError)
return
}
}
contentLength := toByte + 1 - fromByte contentLength := toByte + 1 - fromByte
ctx.Resp.Header().Set("Content-Length", strconv.FormatInt(contentLength, 10)) ctx.Resp.Header().Set("Content-Length", strconv.FormatInt(contentLength, 10))
ctx.Resp.Header().Set("Content-Type", "application/octet-stream") ctx.Resp.Header().Set("Content-Type", "application/octet-stream")

View File

@@ -313,7 +313,7 @@ func RenderEmoji(
return ctx.postProcess(rawHTML) return ctx.postProcess(rawHTML)
} }
var tagCleaner = regexp.MustCompile(`<((?:/?\w+/\w+)|(?:/[\w ]+/)|(/?[hH][tT][mM][lL][ />])|(/?[hH][eE][aA][dD][ />]))`) var tagCleaner = regexp.MustCompile(`<((?:/?\w+/\w+)|(?:/[\w ]+/)|(/?[hH][tT][mM][lL]\b)|(/?[hH][eE][aA][dD]\b))`)
var nulCleaner = strings.NewReplacer("\000", "") var nulCleaner = strings.NewReplacer("\000", "")
func (ctx *postProcessCtx) postProcess(rawHTML []byte) ([]byte, error) { func (ctx *postProcessCtx) postProcess(rawHTML []byte) ([]byte, error) {

View File

@@ -124,7 +124,7 @@ func TestRender_links(t *testing.T) {
`<p><a href="http://www.example.com/wpstyle/?p=364" rel="nofollow">http://www.example.com/wpstyle/?p=364</a></p>`) `<p><a href="http://www.example.com/wpstyle/?p=364" rel="nofollow">http://www.example.com/wpstyle/?p=364</a></p>`)
test( test(
"https://www.example.com/foo/?bar=baz&inga=42&quux", "https://www.example.com/foo/?bar=baz&inga=42&quux",
`<p><a href="https://www.example.com/foo/?bar=baz&inga=42&quux=" rel="nofollow">https://www.example.com/foo/?bar=baz&amp;inga=42&amp;quux</a></p>`) `<p><a href="https://www.example.com/foo/?bar=baz&inga=42&quux" rel="nofollow">https://www.example.com/foo/?bar=baz&amp;inga=42&amp;quux</a></p>`)
test( test(
"http://142.42.1.1/", "http://142.42.1.1/",
`<p><a href="http://142.42.1.1/" rel="nofollow">http://142.42.1.1/</a></p>`) `<p><a href="http://142.42.1.1/" rel="nofollow">http://142.42.1.1/</a></p>`)

View File

@@ -46,7 +46,9 @@ func ReplaceSanitizer() {
sanitizer.policy.AllowAttrs("checked", "disabled").OnElements("input") sanitizer.policy.AllowAttrs("checked", "disabled").OnElements("input")
// Custom URL-Schemes // Custom URL-Schemes
sanitizer.policy.AllowURLSchemes(setting.Markdown.CustomURLSchemes...) if len(setting.Markdown.CustomURLSchemes) > 0 {
sanitizer.policy.AllowURLSchemes(setting.Markdown.CustomURLSchemes...)
}
// Allow keyword markup // Allow keyword markup
sanitizer.policy.AllowAttrs("class").Matching(regexp.MustCompile(`^` + keywordClass + `$`)).OnElements("span") sanitizer.policy.AllowAttrs("class").Matching(regexp.MustCompile(`^` + keywordClass + `$`)).OnElements("span")

View File

@@ -6,6 +6,8 @@
package markup package markup
import ( import (
"html/template"
"strings"
"testing" "testing"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
@@ -50,3 +52,13 @@ func Test_Sanitizer(t *testing.T) {
assert.Equal(t, testCases[i+1], string(SanitizeBytes([]byte(testCases[i])))) assert.Equal(t, testCases[i+1], string(SanitizeBytes([]byte(testCases[i]))))
} }
} }
func TestSanitizeNonEscape(t *testing.T) {
descStr := "<scrİpt>&lt;script&gt;alert(document.domain)&lt;/script&gt;</scrİpt>"
output := template.HTML(Sanitize(string(descStr)))
if strings.Contains(string(output), "<script>") {
t.Errorf("un-escaped <script> in output: %q", output)
}
}

View File

@@ -283,7 +283,7 @@ func (g *GiteaLocalUploader) CreateReleases(releases ...*base.Release) error {
} }
} }
defer rc.Close() defer rc.Close()
_, err = storage.Attachments.Save(attach.RelativePath(), rc) _, err = storage.Attachments.Save(attach.RelativePath(), rc, int64(*asset.Size))
return err return err
}() }()
if err != nil { if err != nil {

View File

@@ -27,6 +27,7 @@ type Options struct {
// KnownPublicEntries list all direct children in the `public` directory // KnownPublicEntries list all direct children in the `public` directory
var KnownPublicEntries = []string{ var KnownPublicEntries = []string{
"css", "css",
"fonts",
"img", "img",
"js", "js",
"serviceworker.js", "serviceworker.js",

View File

@@ -174,6 +174,7 @@ func (m *Manager) FlushAll(baseCtx context.Context, timeout time.Duration) error
default: default:
} }
mqs := m.ManagedQueues() mqs := m.ManagedQueues()
log.Debug("Found %d Managed Queues", len(mqs))
wg := sync.WaitGroup{} wg := sync.WaitGroup{}
wg.Add(len(mqs)) wg.Add(len(mqs))
allEmpty := true allEmpty := true
@@ -184,6 +185,7 @@ func (m *Manager) FlushAll(baseCtx context.Context, timeout time.Duration) error
} }
allEmpty = false allEmpty = false
if flushable, ok := mq.Managed.(Flushable); ok { if flushable, ok := mq.Managed.(Flushable); ok {
log.Debug("Flushing (flushable) queue: %s", mq.Name)
go func(q *ManagedQueue) { go func(q *ManagedQueue) {
localCtx, localCancel := context.WithCancel(ctx) localCtx, localCancel := context.WithCancel(ctx)
pid := q.RegisterWorkers(1, start, hasTimeout, end, localCancel, true) pid := q.RegisterWorkers(1, start, hasTimeout, end, localCancel, true)
@@ -196,7 +198,11 @@ func (m *Manager) FlushAll(baseCtx context.Context, timeout time.Duration) error
wg.Done() wg.Done()
}(mq) }(mq)
} else { } else {
wg.Done() log.Debug("Queue: %s is non-empty but is not flushable - adding 100 millisecond wait", mq.Name)
go func() {
<-time.After(100 * time.Millisecond)
wg.Done()
}()
} }
} }

View File

@@ -66,7 +66,7 @@ func (l *LocalStorage) Open(path string) (Object, error) {
} }
// Save a file // Save a file
func (l *LocalStorage) Save(path string, r io.Reader) (int64, error) { func (l *LocalStorage) Save(path string, r io.Reader, size int64) (int64, error) {
p := filepath.Join(l.dir, path) p := filepath.Join(l.dir, path)
if err := os.MkdirAll(filepath.Dir(p), os.ModePerm); err != nil { if err := os.MkdirAll(filepath.Dir(p), os.ModePerm); err != nil {
return 0, err return 0, err

View File

@@ -131,13 +131,13 @@ func (m *MinioStorage) Open(path string) (Object, error) {
} }
// Save save a file to minio // Save save a file to minio
func (m *MinioStorage) Save(path string, r io.Reader) (int64, error) { func (m *MinioStorage) Save(path string, r io.Reader, size int64) (int64, error) {
uploadInfo, err := m.client.PutObject( uploadInfo, err := m.client.PutObject(
m.ctx, m.ctx,
m.bucket, m.bucket,
m.buildMinioPath(path), m.buildMinioPath(path),
r, r,
-1, size,
minio.PutObjectOptions{ContentType: "application/octet-stream"}, minio.PutObjectOptions{ContentType: "application/octet-stream"},
) )
if err != nil { if err != nil {

View File

@@ -65,7 +65,8 @@ type Object interface {
// ObjectStorage represents an object storage to handle a bucket and files // ObjectStorage represents an object storage to handle a bucket and files
type ObjectStorage interface { type ObjectStorage interface {
Open(path string) (Object, error) Open(path string) (Object, error)
Save(path string, r io.Reader) (int64, error) // Save store a object, if size is unknown set -1
Save(path string, r io.Reader, size int64) (int64, error)
Stat(path string) (os.FileInfo, error) Stat(path string) (os.FileInfo, error)
Delete(path string) error Delete(path string) error
URL(path, name string) (*url.URL, error) URL(path, name string) (*url.URL, error)
@@ -80,7 +81,13 @@ func Copy(dstStorage ObjectStorage, dstPath string, srcStorage ObjectStorage, sr
} }
defer f.Close() defer f.Close()
return dstStorage.Save(dstPath, f) size := int64(-1)
fsinfo, err := f.Stat()
if err == nil {
size = fsinfo.Size()
}
return dstStorage.Save(dstPath, f, size)
} }
// SaveFrom saves data to the ObjectStorage with path p from the callback // SaveFrom saves data to the ObjectStorage with path p from the callback
@@ -94,7 +101,7 @@ func SaveFrom(objStorage ObjectStorage, p string, callback func(w io.Writer) err
} }
}() }()
_, err := objStorage.Save(p, pr) _, err := objStorage.Save(p, pr, -1)
return err return err
} }

View File

@@ -68,10 +68,11 @@ func Wrap(handlers ...interface{}) http.HandlerFunc {
} }
case func(http.Handler) http.Handler: case func(http.Handler) http.Handler:
var next = http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}) var next = http.HandlerFunc(func(http.ResponseWriter, *http.Request) {})
t(next).ServeHTTP(resp, req) if len(handlers) > i+1 {
if r, ok := resp.(context.ResponseWriter); ok && r.Status() > 0 { next = Wrap(handlers[i+1:]...)
return
} }
t(next).ServeHTTP(resp, req)
return
default: default:
panic(fmt.Sprintf("Unsupported handler type: %#v", t)) panic(fmt.Sprintf("Unsupported handler type: %#v", t))
} }

View File

@@ -16,7 +16,6 @@ import (
"code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/context"
"code.gitea.io/gitea/modules/convert" "code.gitea.io/gitea/modules/convert"
issue_indexer "code.gitea.io/gitea/modules/indexer/issues" issue_indexer "code.gitea.io/gitea/modules/indexer/issues"
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/notification" "code.gitea.io/gitea/modules/notification"
"code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/setting"
api "code.gitea.io/gitea/modules/structs" api "code.gitea.io/gitea/modules/structs"
@@ -113,11 +112,7 @@ func SearchIssues(ctx *context.APIContext) {
} }
// find repos user can access (for issue search) // find repos user can access (for issue search)
repoIDs := make([]int64, 0)
opts := &models.SearchRepoOptions{ opts := &models.SearchRepoOptions{
ListOptions: models.ListOptions{
PageSize: 15,
},
Private: false, Private: false,
AllPublic: true, AllPublic: true,
TopicOnly: false, TopicOnly: false,
@@ -132,21 +127,10 @@ func SearchIssues(ctx *context.APIContext) {
opts.AllLimited = true opts.AllLimited = true
} }
for page := 1; ; page++ { repoIDs, _, err := models.SearchRepositoryIDs(opts)
opts.Page = page if err != nil {
repos, count, err := models.SearchRepositoryByName(opts) ctx.Error(http.StatusInternalServerError, "SearchRepositoryByName", err)
if err != nil { return
ctx.Error(http.StatusInternalServerError, "SearchRepositoryByName", err)
return
}
if len(repos) == 0 {
break
}
log.Trace("Processing next %d repos of %d", len(repos), count)
for _, repo := range repos {
repoIDs = append(repoIDs, repo.ID)
}
} }
var issues []*models.Issue var issues []*models.Issue
@@ -157,7 +141,6 @@ func SearchIssues(ctx *context.APIContext) {
keyword = "" keyword = ""
} }
var issueIDs []int64 var issueIDs []int64
var labelIDs []int64
if len(keyword) > 0 && len(repoIDs) > 0 { if len(keyword) > 0 && len(repoIDs) > 0 {
if issueIDs, err = issue_indexer.SearchIssuesByKeyword(repoIDs, keyword); err != nil { if issueIDs, err = issue_indexer.SearchIssuesByKeyword(repoIDs, keyword); err != nil {
ctx.Error(http.StatusInternalServerError, "SearchIssuesByKeyword", err) ctx.Error(http.StatusInternalServerError, "SearchIssuesByKeyword", err)
@@ -192,7 +175,7 @@ func SearchIssues(ctx *context.APIContext) {
// Only fetch the issues if we either don't have a keyword or the search returned issues // Only fetch the issues if we either don't have a keyword or the search returned issues
// This would otherwise return all issues if no issues were found by the search. // This would otherwise return all issues if no issues were found by the search.
if len(keyword) == 0 || len(issueIDs) > 0 || len(labelIDs) > 0 { if len(keyword) == 0 || len(issueIDs) > 0 || len(includedLabelNames) > 0 {
issuesOpt := &models.IssuesOptions{ issuesOpt := &models.IssuesOptions{
ListOptions: models.ListOptions{ ListOptions: models.ListOptions{
Page: ctx.QueryInt("page"), Page: ctx.QueryInt("page"),

View File

@@ -274,7 +274,11 @@ func DeleteOauth2Application(ctx *context.APIContext) {
// "$ref": "#/responses/empty" // "$ref": "#/responses/empty"
appID := ctx.ParamsInt64(":id") appID := ctx.ParamsInt64(":id")
if err := models.DeleteOAuth2Application(appID, ctx.User.ID); err != nil { if err := models.DeleteOAuth2Application(appID, ctx.User.ID); err != nil {
ctx.Error(http.StatusInternalServerError, "DeleteOauth2ApplicationByID", err) if models.IsErrOAuthApplicationNotFound(err) {
ctx.NotFound()
} else {
ctx.Error(http.StatusInternalServerError, "DeleteOauth2ApplicationByID", err)
}
return return
} }

View File

@@ -33,8 +33,8 @@ func Events(ctx *context.Context) {
if !ctx.IsSigned { if !ctx.IsSigned {
// Return unauthorized status event // Return unauthorized status event
event := (&eventsource.Event{ event := (&eventsource.Event{
Name: "unauthorized", Name: "close",
Data: "sorry", Data: "unauthorized",
}) })
_, _ = event.WriteTo(ctx) _, _ = event.WriteTo(ctx)
ctx.Resp.Flush() ctx.Resp.Flush()

View File

@@ -6,6 +6,7 @@
package repo package repo
import ( import (
"errors"
"path" "path"
"strings" "strings"
@@ -389,6 +390,11 @@ func RawDiff(ctx *context.Context) {
git.RawDiffType(ctx.Params(":ext")), git.RawDiffType(ctx.Params(":ext")),
ctx.Resp, ctx.Resp,
); err != nil { ); err != nil {
if git.IsErrNotExist(err) {
ctx.NotFound("GetRawDiff",
errors.New("commit "+ctx.Params(":sha")+" does not exist."))
return
}
ctx.ServerError("GetRawDiff", err) ctx.ServerError("GetRawDiff", err)
return return
} }

View File

@@ -431,11 +431,15 @@ func PrepareCompareDiff(
ctx.Data["IsNothingToCompare"] = true ctx.Data["IsNothingToCompare"] = true
if unit, err := repo.GetUnit(models.UnitTypePullRequests); err == nil { if unit, err := repo.GetUnit(models.UnitTypePullRequests); err == nil {
config := unit.PullRequestsConfig() config := unit.PullRequestsConfig()
if !config.AutodetectManualMerge { if !config.AutodetectManualMerge {
ctx.Data["AllowEmptyPr"] = !(baseBranch == headBranch && ctx.Repo.Repository.Name == headRepo.Name) allowEmptyPr := !(baseBranch == headBranch && ctx.Repo.Repository.Name == headRepo.Name)
} else { ctx.Data["AllowEmptyPr"] = allowEmptyPr
ctx.Data["AllowEmptyPr"] = false
return !allowEmptyPr
} }
ctx.Data["AllowEmptyPr"] = false
} }
return true return true
} }

View File

@@ -192,6 +192,9 @@ func CreatePost(ctx *context.Context) {
ctx.Data["Licenses"] = models.Licenses ctx.Data["Licenses"] = models.Licenses
ctx.Data["Readmes"] = models.Readmes ctx.Data["Readmes"] = models.Readmes
ctx.Data["CanCreateRepo"] = ctx.User.CanCreateRepo()
ctx.Data["MaxCreationLimit"] = ctx.User.MaxCreationLimit()
ctxUser := checkContextUser(ctx, form.UID) ctxUser := checkContextUser(ctx, form.UID)
if ctx.Written() { if ctx.Written() {
return return

View File

@@ -168,15 +168,6 @@ func WebRoutes() *web.Route {
r.Use(h) r.Use(h)
} }
if (setting.Protocol == setting.FCGI || setting.Protocol == setting.FCGIUnix) && setting.AppSubURL != "" {
r.Use(func(next http.Handler) http.Handler {
return http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
req.URL.Path = strings.TrimPrefix(req.URL.Path, setting.AppSubURL)
next.ServeHTTP(resp, req)
})
})
}
mailer.InitMailRender(templates.Mailer()) mailer.InitMailRender(templates.Mailer())
if setting.Service.EnableCaptcha { if setting.Service.EnableCaptcha {
@@ -700,7 +691,7 @@ func RegisterRoutes(m *web.Route) {
}, reqSignIn) }, reqSignIn)
// ***** Release Attachment Download without Signin // ***** Release Attachment Download without Signin
m.Get("/{username}/{reponame}/releases/download/{vTag}/{fileName}", ignSignIn, context.RepoAssignment(), repo.MustBeNotEmpty, repo.RedirectDownload) m.Get("/{username}/{reponame}/releases/download/{vTag}/{fileName}", ignSignIn, context.RepoAssignment, repo.MustBeNotEmpty, repo.RedirectDownload)
m.Group("/{username}/{reponame}", func() { m.Group("/{username}/{reponame}", func() {
m.Group("/settings", func() { m.Group("/settings", func() {
@@ -780,9 +771,9 @@ func RegisterRoutes(m *web.Route) {
ctx.Data["PageIsSettings"] = true ctx.Data["PageIsSettings"] = true
ctx.Data["LFSStartServer"] = setting.LFS.StartServer ctx.Data["LFSStartServer"] = setting.LFS.StartServer
}) })
}, reqSignIn, context.RepoAssignment(), context.UnitTypes(), reqRepoAdmin, context.RepoRef()) }, reqSignIn, context.RepoAssignment, context.UnitTypes(), reqRepoAdmin, context.RepoRef())
m.Post("/{username}/{reponame}/action/{action}", reqSignIn, context.RepoAssignment(), context.UnitTypes(), repo.Action) m.Post("/{username}/{reponame}/action/{action}", reqSignIn, context.RepoAssignment, context.UnitTypes(), repo.Action)
// Grouping for those endpoints not requiring authentication // Grouping for those endpoints not requiring authentication
m.Group("/{username}/{reponame}", func() { m.Group("/{username}/{reponame}", func() {
@@ -792,7 +783,7 @@ func RegisterRoutes(m *web.Route) {
m.Combo("/compare/*", repo.MustBeNotEmpty, reqRepoCodeReader, repo.SetEditorconfigIfExists). m.Combo("/compare/*", repo.MustBeNotEmpty, reqRepoCodeReader, repo.SetEditorconfigIfExists).
Get(ignSignIn, repo.SetDiffViewStyle, repo.SetWhitespaceBehavior, repo.CompareDiff). Get(ignSignIn, repo.SetDiffViewStyle, repo.SetWhitespaceBehavior, repo.CompareDiff).
Post(reqSignIn, context.RepoMustNotBeArchived(), reqRepoPullsReader, repo.MustAllowPulls, bindIgnErr(auth.CreateIssueForm{}), repo.SetWhitespaceBehavior, repo.CompareAndPullRequestPost) Post(reqSignIn, context.RepoMustNotBeArchived(), reqRepoPullsReader, repo.MustAllowPulls, bindIgnErr(auth.CreateIssueForm{}), repo.SetWhitespaceBehavior, repo.CompareAndPullRequestPost)
}, context.RepoAssignment(), context.UnitTypes()) }, context.RepoAssignment, context.UnitTypes())
// Grouping for those endpoints that do require authentication // Grouping for those endpoints that do require authentication
m.Group("/{username}/{reponame}", func() { m.Group("/{username}/{reponame}", func() {
@@ -899,7 +890,7 @@ func RegisterRoutes(m *web.Route) {
m.Post("/restore", repo.RestoreBranchPost) m.Post("/restore", repo.RestoreBranchPost)
}, context.RepoMustNotBeArchived(), reqRepoCodeWriter, repo.MustBeNotEmpty) }, context.RepoMustNotBeArchived(), reqRepoCodeWriter, repo.MustBeNotEmpty)
}, reqSignIn, context.RepoAssignment(), context.UnitTypes()) }, reqSignIn, context.RepoAssignment, context.UnitTypes())
// Releases // Releases
m.Group("/{username}/{reponame}", func() { m.Group("/{username}/{reponame}", func() {
@@ -937,11 +928,11 @@ func RegisterRoutes(m *web.Route) {
} }
ctx.Data["CommitsCount"] = ctx.Repo.CommitsCount ctx.Data["CommitsCount"] = ctx.Repo.CommitsCount
}) })
}, ignSignIn, context.RepoAssignment(), context.UnitTypes(), reqRepoReleaseReader) }, ignSignIn, context.RepoAssignment, context.UnitTypes(), reqRepoReleaseReader)
m.Group("/{username}/{reponame}", func() { m.Group("/{username}/{reponame}", func() {
m.Post("/topics", repo.TopicsPost) m.Post("/topics", repo.TopicsPost)
}, context.RepoAssignment(), context.RepoMustNotBeArchived(), reqRepoAdmin) }, context.RepoAssignment, context.RepoMustNotBeArchived(), reqRepoAdmin)
m.Group("/{username}/{reponame}", func() { m.Group("/{username}/{reponame}", func() {
m.Group("", func() { m.Group("", func() {
@@ -1089,17 +1080,17 @@ func RegisterRoutes(m *web.Route) {
}, context.RepoRef(), reqRepoCodeReader) }, context.RepoRef(), reqRepoCodeReader)
m.Get("/commit/{sha:([a-f0-9]{7,40})}.{ext:patch|diff}", m.Get("/commit/{sha:([a-f0-9]{7,40})}.{ext:patch|diff}",
repo.MustBeNotEmpty, reqRepoCodeReader, repo.RawDiff) repo.MustBeNotEmpty, reqRepoCodeReader, repo.RawDiff)
}, ignSignIn, context.RepoAssignment(), context.UnitTypes()) }, ignSignIn, context.RepoAssignment, context.UnitTypes())
m.Group("/{username}/{reponame}", func() { m.Group("/{username}/{reponame}", func() {
m.Get("/stars", repo.Stars) m.Get("/stars", repo.Stars)
m.Get("/watchers", repo.Watchers) m.Get("/watchers", repo.Watchers)
m.Get("/search", reqRepoCodeReader, repo.Search) m.Get("/search", reqRepoCodeReader, repo.Search)
}, ignSignIn, context.RepoAssignment(), context.RepoRef(), context.UnitTypes()) }, ignSignIn, context.RepoAssignment, context.RepoRef(), context.UnitTypes())
m.Group("/{username}", func() { m.Group("/{username}", func() {
m.Group("/{reponame}", func() { m.Group("/{reponame}", func() {
m.Get("", repo.SetEditorconfigIfExists, repo.Home) m.Get("", repo.SetEditorconfigIfExists, repo.Home)
}, goGet, ignSignIn, context.RepoAssignment(), context.RepoRef(), context.UnitTypes()) }, goGet, ignSignIn, context.RepoAssignment, context.RepoRef(), context.UnitTypes())
m.Group("/{reponame}", func() { m.Group("/{reponame}", func() {
m.Group("/info/lfs", func() { m.Group("/info/lfs", func() {

View File

@@ -1014,6 +1014,11 @@ func parseHunks(curFile *DiffFile, maxLines, maxLineCharacters int, input *bufio
} }
diffLine := &DiffLine{Type: DiffLineAdd, RightIdx: rightLine} diffLine := &DiffLine{Type: DiffLineAdd, RightIdx: rightLine}
rightLine++ rightLine++
if curSection == nil {
// Create a new section to represent this hunk
curSection = &DiffSection{}
curFile.Sections = append(curFile.Sections, curSection)
}
curSection.Lines = append(curSection.Lines, diffLine) curSection.Lines = append(curSection.Lines, diffLine)
case '-': case '-':
curFileLinesCount++ curFileLinesCount++
@@ -1026,6 +1031,11 @@ func parseHunks(curFile *DiffFile, maxLines, maxLineCharacters int, input *bufio
if leftLine > 0 { if leftLine > 0 {
leftLine++ leftLine++
} }
if curSection == nil {
// Create a new section to represent this hunk
curSection = &DiffSection{}
curFile.Sections = append(curFile.Sections, curSection)
}
curSection.Lines = append(curSection.Lines, diffLine) curSection.Lines = append(curSection.Lines, diffLine)
case ' ': case ' ':
curFileLinesCount++ curFileLinesCount++
@@ -1036,6 +1046,11 @@ func parseHunks(curFile *DiffFile, maxLines, maxLineCharacters int, input *bufio
diffLine := &DiffLine{Type: DiffLinePlain, LeftIdx: leftLine, RightIdx: rightLine} diffLine := &DiffLine{Type: DiffLinePlain, LeftIdx: leftLine, RightIdx: rightLine}
leftLine++ leftLine++
rightLine++ rightLine++
if curSection == nil {
// Create a new section to represent this hunk
curSection = &DiffSection{}
curFile.Sections = append(curFile.Sections, curSection)
}
curSection.Lines = append(curSection.Lines, diffLine) curSection.Lines = append(curSection.Lines, diffLine)
default: default:
// This is unexpected // This is unexpected

View File

@@ -64,7 +64,7 @@ func Merge(pr *models.PullRequest, doer *models.User, baseGitRepo *git.Repositor
pr.Merger = doer pr.Merger = doer
pr.MergerID = doer.ID pr.MergerID = doer.ID
if _, err = pr.SetMerged(); err != nil { if _, err := pr.SetMerged(); err != nil {
log.Error("setMerged [%d]: %v", pr.ID, err) log.Error("setMerged [%d]: %v", pr.ID, err)
} }

View File

@@ -8,7 +8,7 @@
<div class="twelve wide field"> <div class="twelve wide field">
<input name="q" value="{{.Keyword}}" placeholder="{{.i18n.Tr "explore.search"}}..." autofocus> <input name="q" value="{{.Keyword}}" placeholder="{{.i18n.Tr "explore.search"}}..." autofocus>
</div> </div>
<div class="two wide field"> <div class="two wide field mx-2">
<select name="t"> <select name="t">
<option value="">{{.i18n.Tr "explore.search.fuzzy"}}</option> <option value="">{{.i18n.Tr "explore.search.fuzzy"}}</option>
<option value="match" {{if eq .queryType "match"}}selected{{end}}>{{.i18n.Tr "explore.search.match"}}</option> <option value="match" {{if eq .queryType "match"}}selected{{end}}>{{.i18n.Tr "explore.search.match"}}</option>

View File

@@ -25,7 +25,7 @@
</td> </td>
<td class="right aligned overflow-visible"> <td class="right aligned overflow-visible">
<div class="ui basic jump dropdown icon button poping up" data-content="{{$.i18n.Tr "repo.branch.download" ($.DefaultBranch)}}" data-variation="tiny inverted" data-position="top right"> <div class="ui basic jump dropdown icon button poping up" data-content="{{$.i18n.Tr "repo.branch.download" ($.DefaultBranch)}}" data-variation="tiny inverted" data-position="top right">
<i class="download icon"></i> {{svg "octicon-download"}}
<div class="menu"> <div class="menu">
<a class="item archive-link" data-url="{{$.RepoLink}}/archive/{{EscapePound $.DefaultBranch}}.zip">{{svg "octicon-file-zip"}}&nbsp;ZIP</a> <a class="item archive-link" data-url="{{$.RepoLink}}/archive/{{EscapePound $.DefaultBranch}}.zip">{{svg "octicon-file-zip"}}&nbsp;ZIP</a>
<a class="item archive-link" data-url="{{$.RepoLink}}/archive/{{EscapePound $.DefaultBranch}}.tar.gz">{{svg "octicon-file-zip"}}&nbsp;TAR.GZ</a> <a class="item archive-link" data-url="{{$.RepoLink}}/archive/{{EscapePound $.DefaultBranch}}.tar.gz">{{svg "octicon-file-zip"}}&nbsp;TAR.GZ</a>
@@ -91,20 +91,20 @@
</a> </a>
{{end}} {{end}}
{{else}} {{else}}
<a href="{{.LatestPullRequest.Issue.HTMLURL}}">{{if not .LatestPullRequest.IsSameRepo}}{{.LatestPullRequest.BaseRepo.FullName}}{{end}}#{{.LatestPullRequest.Issue.Index}}</a> <a href="{{.LatestPullRequest.Issue.HTMLURL}}" class="vm">{{if not .LatestPullRequest.IsSameRepo}}{{.LatestPullRequest.BaseRepo.FullName}}{{end}}#{{.LatestPullRequest.Issue.Index}}</a>
{{if .LatestPullRequest.HasMerged}} {{if .LatestPullRequest.HasMerged}}
<a href="{{.LatestPullRequest.Issue.HTMLURL}}" class="ui text-label purple mini label">{{svg "octicon-git-merge"}} {{$.i18n.Tr "repo.pulls.merged"}}</a> <a href="{{.LatestPullRequest.Issue.HTMLURL}}" class="ui text-label purple large label vm">{{svg "octicon-git-merge" 16 "mr-2"}}{{$.i18n.Tr "repo.pulls.merged"}}</a>
{{else if .LatestPullRequest.Issue.IsClosed}} {{else if .LatestPullRequest.Issue.IsClosed}}
<a href="{{.LatestPullRequest.Issue.HTMLURL}}" class="ui text-label red mini label">{{svg "octicon-git-pull-request"}} {{$.i18n.Tr "repo.issues.closed_title"}}</a> <a href="{{.LatestPullRequest.Issue.HTMLURL}}" class="ui text-label red large label vm">{{svg "octicon-git-pull-request" 16 "mr-2"}}{{$.i18n.Tr "repo.issues.closed_title"}}</a>
{{else}} {{else}}
<a href="{{.LatestPullRequest.Issue.HTMLURL}}" class="ui text-label green mini label">{{svg "octicon-git-pull-request"}} {{$.i18n.Tr "repo.issues.open_title"}}</a> <a href="{{.LatestPullRequest.Issue.HTMLURL}}" class="ui text-label green large label vm">{{svg "octicon-git-pull-request" 16 "mr-2"}}{{$.i18n.Tr "repo.issues.open_title"}}</a>
{{end}} {{end}}
{{end}} {{end}}
</td> </td>
<td class="two wide right aligned overflow-visible"> <td class="two wide right aligned overflow-visible">
{{if (not .IsDeleted)}} {{if (not .IsDeleted)}}
<div class="ui basic jump dropdown icon button poping up" data-content="{{$.i18n.Tr "repo.branch.download" (.Name)}}" data-variation="tiny inverted" data-position="top right"> <div class="ui basic jump dropdown icon button poping up" data-content="{{$.i18n.Tr "repo.branch.download" (.Name)}}" data-variation="tiny inverted" data-position="top right">
<i class="download icon"></i> {{svg "octicon-download"}}
<div class="menu"> <div class="menu">
<a class="item archive-link" data-url="{{$.RepoLink}}/archive/{{EscapePound .Name}}.zip">{{svg "octicon-file-zip"}}&nbsp;ZIP</a> <a class="item archive-link" data-url="{{$.RepoLink}}/archive/{{EscapePound .Name}}.zip">{{svg "octicon-file-zip"}}&nbsp;ZIP</a>
<a class="item archive-link" data-url="{{$.RepoLink}}/archive/{{EscapePound .Name}}.tar.gz">{{svg "octicon-file-zip"}}&nbsp;TAR.GZ</a> <a class="item archive-link" data-url="{{$.RepoLink}}/archive/{{EscapePound .Name}}.tar.gz">{{svg "octicon-file-zip"}}&nbsp;TAR.GZ</a>

View File

@@ -43,15 +43,13 @@
</ol> </ol>
{{range $i, $file := .Diff.Files}} {{range $i, $file := .Diff.Files}}
{{if $file.IsIncomplete}} {{if $file.IsIncomplete}}
<div class="diff-file-box diff-box file-content"> <div class="diff-file-box diff-box file-content mt-3">
<h4 class="ui top attached normal header rounded"> <h4 class="ui top attached normal header rounded">
<a role="button" class="fold-file muted mr-2"> <a role="button" class="fold-file muted mr-2">
{{svg "octicon-chevron-down" 18}} {{svg "octicon-chevron-down" 18}}
</a> </a>
<div class="bold ui left df ac"> <div class="bold ui left df ac">
{{if not $file.IsRenamed}} {{template "repo/diff/stats" dict "file" . "root" $}}
{{template "repo/diff/stats" dict "file" . "root" $}}
{{end}}
</div> </div>
<span class="file mono">{{$file.Name}}</span> <span class="file mono">{{$file.Name}}</span>
<div class="diff-file-header-actions df ac"> <div class="diff-file-header-actions df ac">
@@ -70,7 +68,7 @@
</h4> </h4>
</div> </div>
{{else}} {{else}}
<div class="diff-file-box diff-box file-content {{TabSizeClass $.Editorconfig $file.Name}}" id="diff-{{.Index}}"> <div class="diff-file-box diff-box file-content {{TabSizeClass $.Editorconfig $file.Name}} mt-3" id="diff-{{.Index}}">
<h4 class="diff-file-header sticky-2nd-row ui top attached normal header df ac sb"> <h4 class="diff-file-header sticky-2nd-row ui top attached normal header df ac sb">
<div class="df ac"> <div class="df ac">
{{$isImage := false}} {{$isImage := false}}
@@ -85,7 +83,7 @@
<div class="bold df ac"> <div class="bold df ac">
{{if $file.IsBin}} {{if $file.IsBin}}
{{$.i18n.Tr "repo.diff.bin"}} {{$.i18n.Tr "repo.diff.bin"}}
{{else if not $file.IsRenamed}} {{else}}
{{template "repo/diff/stats" dict "file" . "root" $}} {{template "repo/diff/stats" dict "file" . "root" $}}
{{end}} {{end}}
</div> </div>
@@ -105,30 +103,28 @@
</div> </div>
</h4> </h4>
<div class="diff-file-body ui attached unstackable table segment"> <div class="diff-file-body ui attached unstackable table segment">
{{if ne $file.Type 4}} <div class="file-body file-code has-context-menu{{if not $isImage}} code-diff{{end}}{{if $.IsSplitStyle}} code-diff-split{{else}} code-diff-unified{{end}}{{if $isImage}} py-4{{end}}">
<div class="file-body file-code has-context-menu{{if not $isImage}} code-diff{{end}}{{if $.IsSplitStyle}} code-diff-split{{else}} code-diff-unified{{end}}{{if $isImage}} py-4{{end}}"> <table class="chroma{{if $isImage}} w-100{{end}}">
<table class="chroma{{if $isImage}} w-100{{end}}"> <tbody>
<tbody> {{if $isImage}}
{{if $isImage}} {{template "repo/diff/image_diff" dict "file" . "root" $}}
{{template "repo/diff/image_diff" dict "file" . "root" $}} {{else}}
{{if $.IsSplitStyle}}
{{template "repo/diff/section_split" dict "file" . "root" $}}
{{else}} {{else}}
{{if $.IsSplitStyle}} {{template "repo/diff/section_unified" dict "file" . "root" $}}
{{template "repo/diff/section_split" dict "file" . "root" $}}
{{else}}
{{template "repo/diff/section_unified" dict "file" . "root" $}}
{{end}}
{{end}} {{end}}
</tbody> {{end}}
</table> </tbody>
</div> </table>
{{end}} </div>
</div> </div>
</div> </div>
{{end}} {{end}}
{{end}} {{end}}
{{if .Diff.IsIncomplete}} {{if .Diff.IsIncomplete}}
<div class="diff-file-box diff-box file-content"> <div class="diff-file-box diff-box file-content mt-3">
<h4 class="ui top attached normal header"> <h4 class="ui top attached normal header">
{{$.i18n.Tr "repo.diff.too_many_files"}} {{$.i18n.Tr "repo.diff.too_many_files"}}
</h4> </h4>

View File

@@ -3,7 +3,7 @@
{{ $createdStr:= TimeSinceUnix .CreatedUnix $.root.Lang }} {{ $createdStr:= TimeSinceUnix .CreatedUnix $.root.Lang }}
<div class="comment" id="{{.HashTag}}"> <div class="comment" id="{{.HashTag}}">
{{if .OriginalAuthor }} {{if .OriginalAuthor }}
<span class="avatar"><img src="/img/avatar_default.png"></span> <span class="avatar"><img src="{{AppSubUrl}}/img/avatar_default.png"></span>
{{else}} {{else}}
<a class="avatar" {{if gt .Poster.ID 0}}href="{{.Poster.HomeLink}}"{{end}}> <a class="avatar" {{if gt .Poster.ID 0}}href="{{.Poster.HomeLink}}"{{end}}>
{{avatar .Poster}} {{avatar .Poster}}

View File

@@ -3,16 +3,20 @@
{{$isNotPending := (not (eq (index .comments 0).Review.Type 0))}} {{$isNotPending := (not (eq (index .comments 0).Review.Type 0))}}
<div class="conversation-holder" data-path="{{(index .comments 0).TreePath}}" data-side="{{if lt (index .comments 0).Line 0}}left{{else}}right{{end}}" data-idx="{{(index .comments 0).UnsignedLine}}"> <div class="conversation-holder" data-path="{{(index .comments 0).TreePath}}" data-side="{{if lt (index .comments 0).Line 0}}left{{else}}right{{end}}" data-idx="{{(index .comments 0).UnsignedLine}}">
{{if $resolved}} {{if $resolved}}
<div class="ui attached header resolved-placeholder"> <div class="ui attached header resolved-placeholder df ac sb">
<span class="ui grey text left"><b>{{$resolveDoer.Name}}</b> {{$.i18n.Tr "repo.issues.review.resolved_by"}}</span> <div class="ui grey text">
<button id="show-outdated-{{(index .comments 0).ID}}" data-comment="{{(index .comments 0).ID}}" class="ui tiny right labeled button show-outdated"> <b>{{$resolveDoer.Name}}</b> {{$.i18n.Tr "repo.issues.review.resolved_by"}}
{{svg "octicon-unfold"}} </div>
{{$.i18n.Tr "repo.issues.review.show_resolved"}} <div>
</button> <button id="show-outdated-{{(index .comments 0).ID}}" data-comment="{{(index .comments 0).ID}}" class="ui tiny right labeled button show-outdated df ac">
<button id="hide-outdated-{{(index .comments 0).ID}}" data-comment="{{(index .comments 0).ID}}" class="hide ui tiny right labeled button hide-outdated"> {{svg "octicon-unfold" 16 "mr-3"}}
{{svg "octicon-fold"}} {{$.i18n.Tr "repo.issues.review.show_resolved"}}
{{$.i18n.Tr "repo.issues.review.hide_resolved"}} </button>
</button> <button id="hide-outdated-{{(index .comments 0).ID}}" data-comment="{{(index .comments 0).ID}}" class="hide ui tiny right labeled button hide-outdated df ac">
{{svg "octicon-fold" 16 "mr-3"}}
{{$.i18n.Tr "repo.issues.review.hide_resolved"}}
</button>
</div>
</div> </div>
{{end}} {{end}}
<div id="code-comments-{{(index .comments 0).ID}}" class="field comment-code-cloud {{if $resolved}}hide{{end}}"> <div id="code-comments-{{(index .comments 0).ID}}" class="field comment-code-cloud {{if $resolved}}hide{{end}}">
@@ -32,4 +36,4 @@
</button> </button>
{{end}} {{end}}
</div> </div>
</div> </div>

View File

@@ -1,9 +1,9 @@
<div id="rev-container"> <div id="rev-container">
<ul id="rev-list"> <ul id="rev-list">
{{ range $commitI, $commit := .Graph.Commits }} {{ range $commitI, $commit := .Graph.Commits }}
<li id="commit-{{$commit.Rev}}" data-flow="{{$commit.Flow}}"> <li {{if $commit.Rev}}id="commit-{{$commit.Rev}}"{{end}} data-flow="{{$commit.Flow}}">
{{ if $commit.OnlyRelation }} {{ if $commit.OnlyRelation }}
<span /> <span></span>
{{ else }} {{ else }}
<span class="sha" id="{{$commit.ShortRev}}"> <span class="sha" id="{{$commit.ShortRev}}">
{{$class := "ui sha label"}} {{$class := "ui sha label"}}

View File

@@ -13,7 +13,7 @@
<ui class="ui timeline"> <ui class="ui timeline">
<div id="{{.Issue.HashTag}}" class="timeline-item comment first"> <div id="{{.Issue.HashTag}}" class="timeline-item comment first">
{{if .Issue.OriginalAuthor }} {{if .Issue.OriginalAuthor }}
<span class="timeline-avatar"><img src="/img/avatar_default.png"></span> <span class="timeline-avatar"><img src="{{AppSubUrl}}/img/avatar_default.png"></span>
{{else}} {{else}}
<a class="timeline-avatar" {{if gt .Issue.Poster.ID 0}}href="{{.Issue.Poster.HomeLink}}"{{end}}> <a class="timeline-avatar" {{if gt .Issue.Poster.ID 0}}href="{{.Issue.Poster.HomeLink}}"{{end}}>
{{avatar .Issue.Poster}} {{avatar .Issue.Poster}}

View File

@@ -8,12 +8,12 @@
18 = REMOVED_DEADLINE, 19 = ADD_DEPENDENCY, 20 = REMOVE_DEPENDENCY, 21 = CODE, 18 = REMOVED_DEADLINE, 19 = ADD_DEPENDENCY, 20 = REMOVE_DEPENDENCY, 21 = CODE,
22 = REVIEW, 23 = ISSUE_LOCKED, 24 = ISSUE_UNLOCKED, 25 = TARGET_BRANCH_CHANGED, 22 = REVIEW, 23 = ISSUE_LOCKED, 24 = ISSUE_UNLOCKED, 25 = TARGET_BRANCH_CHANGED,
26 = DELETE_TIME_MANUAL, 27 = REVIEW_REQUEST, 28 = MERGE_PULL_REQUEST, 26 = DELETE_TIME_MANUAL, 27 = REVIEW_REQUEST, 28 = MERGE_PULL_REQUEST,
29 = PULL_PUSH_EVENT, 30 = PROJECT_CHANGED, 31 = PROJECT_BOARD_CHANGED 29 = PULL_PUSH_EVENT, 30 = PROJECT_CHANGED, 31 = PROJECT_BOARD_CHANGED
32 = DISMISSED_REVIEW --> 32 = DISMISSED_REVIEW -->
{{if eq .Type 0}} {{if eq .Type 0}}
<div class="timeline-item comment" id="{{.HashTag}}"> <div class="timeline-item comment" id="{{.HashTag}}">
{{if .OriginalAuthor }} {{if .OriginalAuthor }}
<span class="timeline-avatar"><img src="/img/avatar_default.png"></span> <span class="timeline-avatar"><img src="{{AppSubUrl}}/img/avatar_default.png"></span>
{{else}} {{else}}
<a class="timeline-avatar" {{if gt .Poster.ID 0}}href="{{.Poster.HomeLink}}"{{end}}> <a class="timeline-avatar" {{if gt .Poster.ID 0}}href="{{.Poster.HomeLink}}"{{end}}>
{{avatar .Poster}} {{avatar .Poster}}
@@ -459,35 +459,39 @@
{{ range $filename, $lines := .Review.CodeComments}} {{ range $filename, $lines := .Review.CodeComments}}
{{range $line, $comms := $lines}} {{range $line, $comms := $lines}}
<div class="ui segments"> <div class="ui segments">
<div class="ui segment py-3"> <div class="ui segment py-3 df ac sb">
{{$invalid := (index $comms 0).Invalidated}} {{$invalid := (index $comms 0).Invalidated}}
{{$resolved := (index $comms 0).IsResolved}} {{$resolved := (index $comms 0).IsResolved}}
{{$resolveDoer := (index $comms 0).ResolveDoer}} {{$resolveDoer := (index $comms 0).ResolveDoer}}
{{$isNotPending := (not (eq (index $comms 0).Review.Type 0))}} {{$isNotPending := (not (eq (index $comms 0).Review.Type 0))}}
{{if or $invalid $resolved}} <div class="df ac">
<button id="show-outdated-{{(index $comms 0).ID}}" data-comment="{{(index $comms 0).ID}}" class="{{if not $resolved}}hide {{end}}ui compact right labeled button show-outdated"> <a href="{{(index $comms 0).CodeCommentURL}}" class="file-comment ml-3">{{$filename}}</a>
{{svg "octicon-unfold"}} {{if $invalid }}
{{if $resolved}} <span class="ui label basic small ml-3">
{{$.i18n.Tr "repo.issues.review.show_resolved"}} {{$.i18n.Tr "repo.issues.review.outdated"}}
{{else}} </span>
{{$.i18n.Tr "repo.issues.review.show_outdated"}}
{{end}} {{end}}
</button> </div>
<button id="hide-outdated-{{(index $comms 0).ID}}" data-comment="{{(index $comms 0).ID}}" class="{{if $resolved}}hide {{end}}ui compact right labeled button hide-outdated"> <div>
{{svg "octicon-fold"}} {{if or $invalid $resolved}}
{{if $resolved}} <button id="show-outdated-{{(index $comms 0).ID}}" data-comment="{{(index $comms 0).ID}}" class="{{if not $resolved}}hide {{end}}ui compact right labeled button show-outdated df ac">
{{$.i18n.Tr "repo.issues.review.hide_resolved"}} {{svg "octicon-unfold" 16 "mr-3"}}
{{else}} {{if $resolved}}
{{$.i18n.Tr "repo.issues.review.hide_outdated"}} {{$.i18n.Tr "repo.issues.review.show_resolved"}}
{{else}}
{{$.i18n.Tr "repo.issues.review.show_outdated"}}
{{end}}
</button>
<button id="hide-outdated-{{(index $comms 0).ID}}" data-comment="{{(index $comms 0).ID}}" class="{{if $resolved}}hide {{end}}ui compact right labeled button hide-outdated df ac">
{{svg "octicon-fold" 16 "mr-3"}}
{{if $resolved}}
{{$.i18n.Tr "repo.issues.review.hide_resolved"}}
{{else}}
{{$.i18n.Tr "repo.issues.review.hide_outdated"}}
{{end}}
</button>
{{end}} {{end}}
</button> </div>
{{end}}
<a href="{{(index $comms 0).CodeCommentURL}}" class="file-comment">{{$filename}}</a>
{{if $invalid }}
<span class="ui label basic small yellow">
{{$.i18n.Tr "repo.issues.review.outdated"}}
</span>
{{end}}
</div> </div>
{{$diff := (CommentMustAsDiff (index $comms 0))}} {{$diff := (CommentMustAsDiff (index $comms 0))}}
{{if $diff}} {{if $diff}}

View File

@@ -71,8 +71,8 @@
</div> </div>
</div> </div>
</div> </div>
</div>
{{end}} {{end}}
</div>
{{if .ContextUser.IsOrganization}} {{if .ContextUser.IsOrganization}}
<div class="right stackable menu"> <div class="right stackable menu">
@@ -101,5 +101,6 @@
</div> </div>
</div> </div>
{{end}} {{end}}
</div>
</div> </div>
<div class="ui divider"></div> <div class="ui divider"></div>

View File

@@ -1,22 +0,0 @@
The MIT License (MIT)
Copyright (c) 2015 Aymerick JEHANNE
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.

15
vendor/github.com/microcosm-cc/bluemonday/SECURITY.md generated vendored Normal file
View File

@@ -0,0 +1,15 @@
# Security Policy
## Supported Versions
Latest tag and tip are supported.
Older tags remain present but changes result in new tags and are not back ported... please verify any issue against the latest tag and tip.
## Reporting a Vulnerability
Email: <bluemonday@buro9.com>
Bluemonday is pure OSS and not maintained by a company. As such there is no bug bounty program but security issues will be taken seriously and resolved as soon as possible.
The maintainer lives in the United Kingdom and whilst the email is monitored expect a reply or ACK when the maintainer is awake.

View File

@@ -1,10 +1,9 @@
module github.com/microcosm-cc/bluemonday module github.com/microcosm-cc/bluemonday
go 1.9 go 1.16
require ( require (
github.com/aymerick/douceur v0.2.0 // indirect github.com/aymerick/douceur v0.2.0
github.com/chris-ramon/douceur v0.2.0
github.com/gorilla/css v1.0.0 // indirect github.com/gorilla/css v1.0.0 // indirect
golang.org/x/net v0.0.0-20181220203305-927f97764cc3 golang.org/x/net v0.0.0-20210331212208-0fccb6fa2b5c
) )

View File

@@ -1,8 +1,11 @@
github.com/aymerick/douceur v0.2.0 h1:Mv+mAeH1Q+n9Fr+oyamOlAkUNPWPlA8PPGR0QAaYuPk= github.com/aymerick/douceur v0.2.0 h1:Mv+mAeH1Q+n9Fr+oyamOlAkUNPWPlA8PPGR0QAaYuPk=
github.com/aymerick/douceur v0.2.0/go.mod h1:wlT5vV2O3h55X9m7iVYN0TBM0NH/MmbLnd30/FjWUq4= github.com/aymerick/douceur v0.2.0/go.mod h1:wlT5vV2O3h55X9m7iVYN0TBM0NH/MmbLnd30/FjWUq4=
github.com/chris-ramon/douceur v0.2.0 h1:IDMEdxlEUUBYBKE4z/mJnFyVXox+MjuEVDJNN27glkU=
github.com/chris-ramon/douceur v0.2.0/go.mod h1:wDW5xjJdeoMm1mRt4sD4c/LbF/mWdEpRXQKjTR8nIBE=
github.com/gorilla/css v1.0.0 h1:BQqNyPTi50JCFMTw/b67hByjMVXZRwGha6wxVGkeihY= github.com/gorilla/css v1.0.0 h1:BQqNyPTi50JCFMTw/b67hByjMVXZRwGha6wxVGkeihY=
github.com/gorilla/css v1.0.0/go.mod h1:Dn721qIggHpt4+EFCcTLTU/vk5ySda2ReITrtgBl60c= github.com/gorilla/css v1.0.0/go.mod h1:Dn721qIggHpt4+EFCcTLTU/vk5ySda2ReITrtgBl60c=
golang.org/x/net v0.0.0-20181220203305-927f97764cc3 h1:eH6Eip3UpmR+yM/qI9Ijluzb1bNv/cAU/n+6l8tRSis= golang.org/x/net v0.0.0-20210331212208-0fccb6fa2b5c h1:KHUzaHIpjWVlVVNh65G3hhuj3KB1HnjY6Cq5cTvRQT8=
golang.org/x/net v0.0.0-20181220203305-927f97764cc3/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20210331212208-0fccb6fa2b5c/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=

View File

@@ -26,6 +26,7 @@
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package bluemonday package bluemonday
import ( import (

View File

@@ -69,6 +69,9 @@ type Policy struct {
// Will skip for href="/foo" or href="foo" // Will skip for href="/foo" or href="foo"
requireNoReferrerFullyQualifiedLinks bool requireNoReferrerFullyQualifiedLinks bool
// When true, add crossorigin="anonymous" to HTML audio, img, link, script, and video tags
requireCrossOriginAnonymous bool
// When true add target="_blank" to fully qualified links // When true add target="_blank" to fully qualified links
// Will add for href="http://foo" // Will add for href="http://foo"
// Will skip for href="/foo" or href="foo" // Will skip for href="/foo" or href="foo"
@@ -433,25 +436,25 @@ func (spb *stylePolicyBuilder) OnElements(elements ...string) *Policy {
// and return the updated policy // and return the updated policy
func (spb *stylePolicyBuilder) OnElementsMatching(regex *regexp.Regexp) *Policy { func (spb *stylePolicyBuilder) OnElementsMatching(regex *regexp.Regexp) *Policy {
for _, attr := range spb.propertyNames { for _, attr := range spb.propertyNames {
if _, ok := spb.p.elsMatchingAndStyles[regex]; !ok { if _, ok := spb.p.elsMatchingAndStyles[regex]; !ok {
spb.p.elsMatchingAndStyles[regex] = make(map[string]stylePolicy) spb.p.elsMatchingAndStyles[regex] = make(map[string]stylePolicy)
}
sp := stylePolicy{}
if spb.handler != nil {
sp.handler = spb.handler
} else if len(spb.enum) > 0 {
sp.enum = spb.enum
} else if spb.regexp != nil {
sp.regexp = spb.regexp
} else {
sp.handler = getDefaultHandler(attr)
}
spb.p.elsMatchingAndStyles[regex][attr] = sp
} }
sp := stylePolicy{}
if spb.handler != nil {
sp.handler = spb.handler
} else if len(spb.enum) > 0 {
sp.enum = spb.enum
} else if spb.regexp != nil {
sp.regexp = spb.regexp
} else {
sp.handler = getDefaultHandler(attr)
}
spb.p.elsMatchingAndStyles[regex][attr] = sp
}
return spb.p return spb.p
} }
@@ -558,6 +561,16 @@ func (p *Policy) RequireNoReferrerOnFullyQualifiedLinks(require bool) *Policy {
return p return p
} }
// RequireCrossOriginAnonymous will result in all audio, img, link, script, and
// video tags having a crossorigin="anonymous" added to them if one does not
// already exist
func (p *Policy) RequireCrossOriginAnonymous(require bool) *Policy {
p.requireCrossOriginAnonymous = require
return p
}
// AddTargetBlankToFullyQualifiedLinks will result in all a, area and link tags // AddTargetBlankToFullyQualifiedLinks will result in all a, area and link tags
// that point to a non-local destination (i.e. starts with a protocol and has a // that point to a non-local destination (i.e. starts with a protocol and has a
// host) having a target="_blank" added to them if one does not already exist // host) having a target="_blank" added to them if one does not already exist

View File

@@ -39,7 +39,7 @@ import (
"golang.org/x/net/html" "golang.org/x/net/html"
cssparser "github.com/chris-ramon/douceur/parser" "github.com/aymerick/douceur/parser"
) )
var ( var (
@@ -124,8 +124,9 @@ func escapeUrlComponent(val string) string {
// Query represents a query // Query represents a query
type Query struct { type Query struct {
Key string Key string
Value string Value string
HasValue bool
} }
func parseQuery(query string) (values []Query, err error) { func parseQuery(query string) (values []Query, err error) {
@@ -140,8 +141,10 @@ func parseQuery(query string) (values []Query, err error) {
continue continue
} }
value := "" value := ""
hasValue := false
if i := strings.Index(key, "="); i >= 0 { if i := strings.Index(key, "="); i >= 0 {
key, value = key[:i], key[i+1:] key, value = key[:i], key[i+1:]
hasValue = true
} }
key, err1 := url.QueryUnescape(key) key, err1 := url.QueryUnescape(key)
if err1 != nil { if err1 != nil {
@@ -158,8 +161,9 @@ func parseQuery(query string) (values []Query, err error) {
continue continue
} }
values = append(values, Query{ values = append(values, Query{
Key: key, Key: key,
Value: value, Value: value,
HasValue: hasValue,
}) })
} }
return values, err return values, err
@@ -169,8 +173,10 @@ func encodeQueries(queries []Query) string {
var b strings.Builder var b strings.Builder
for i, query := range queries { for i, query := range queries {
b.WriteString(url.QueryEscape(query.Key)) b.WriteString(url.QueryEscape(query.Key))
b.WriteString("=") if query.HasValue {
b.WriteString(url.QueryEscape(query.Value)) b.WriteString("=")
b.WriteString(url.QueryEscape(query.Value))
}
if i < len(queries)-1 { if i < len(queries)-1 {
b.WriteString("&") b.WriteString("&")
} }
@@ -286,7 +292,7 @@ func (p *Policy) sanitize(r io.Reader) *bytes.Buffer {
case html.StartTagToken: case html.StartTagToken:
mostRecentlyStartedToken = strings.ToLower(token.Data) mostRecentlyStartedToken = normaliseElementName(token.Data)
aps, ok := p.elsAndAttrs[token.Data] aps, ok := p.elsAndAttrs[token.Data]
if !ok { if !ok {
@@ -329,7 +335,7 @@ func (p *Policy) sanitize(r io.Reader) *bytes.Buffer {
case html.EndTagToken: case html.EndTagToken:
if mostRecentlyStartedToken == strings.ToLower(token.Data) { if mostRecentlyStartedToken == normaliseElementName(token.Data) {
mostRecentlyStartedToken = "" mostRecentlyStartedToken = ""
} }
@@ -407,11 +413,11 @@ func (p *Policy) sanitize(r io.Reader) *bytes.Buffer {
if !skipElementContent { if !skipElementContent {
switch mostRecentlyStartedToken { switch mostRecentlyStartedToken {
case "script": case `script`:
// not encouraged, but if a policy allows JavaScript we // not encouraged, but if a policy allows JavaScript we
// should not HTML escape it as that would break the output // should not HTML escape it as that would break the output
buff.WriteString(token.Data) buff.WriteString(token.Data)
case "style": case `style`:
// not encouraged, but if a policy allows CSS styles we // not encouraged, but if a policy allows CSS styles we
// should not HTML escape it as that would break the output // should not HTML escape it as that would break the output
buff.WriteString(token.Data) buff.WriteString(token.Data)
@@ -721,6 +727,26 @@ func (p *Policy) sanitizeAttrs(
} }
} }
if p.requireCrossOriginAnonymous && len(cleanAttrs) > 0 {
switch elementName {
case "audio", "img", "link", "script", "video":
var crossOriginFound bool
for _, htmlAttr := range cleanAttrs {
if htmlAttr.Key == "crossorigin" {
crossOriginFound = true
htmlAttr.Val = "anonymous"
}
}
if !crossOriginFound {
crossOrigin := html.Attribute{}
crossOrigin.Key = "crossorigin"
crossOrigin.Val = "anonymous"
cleanAttrs = append(cleanAttrs, crossOrigin)
}
}
}
return cleanAttrs return cleanAttrs
} }
@@ -744,7 +770,7 @@ func (p *Policy) sanitizeStyles(attr html.Attribute, elementName string) html.At
if len(attr.Val) > 0 && attr.Val[len(attr.Val)-1] != ';' { if len(attr.Val) > 0 && attr.Val[len(attr.Val)-1] != ';' {
attr.Val = attr.Val + ";" attr.Val = attr.Val + ";"
} }
decs, err := cssparser.ParseDeclarations(attr.Val) decs, err := parser.ParseDeclarations(attr.Val)
if err != nil { if err != nil {
attr.Val = "" attr.Val = ""
return attr return attr
@@ -944,3 +970,22 @@ func (p *Policy) matchRegex(elementName string) (map[string]attrPolicy, bool) {
} }
return aps, matched return aps, matched
} }
// normaliseElementName takes a HTML element like <script> which is user input
// and returns a lower case version of it that is immune to UTF-8 to ASCII
// conversion tricks (like the use of upper case cyrillic i scrİpt which a
// strings.ToLower would convert to script). Instead this func will preserve
// all non-ASCII as their escaped equivalent, i.e. \u0130 which reveals the
// characters when lower cased
func normaliseElementName(str string) string {
// that useful QuoteToASCII put quote marks at the start and end
// so those are trimmed off
return strings.TrimSuffix(
strings.TrimPrefix(
strings.ToLower(
strconv.QuoteToASCII(str),
),
`"`),
`"`,
)
}

View File

@@ -17,18 +17,45 @@ type Conn struct {
c syscall.RawConn c syscall.RawConn
} }
// tcpConn is an interface implemented by net.TCPConn.
// It can be used for interface assertions to check if a net.Conn is a TCP connection.
type tcpConn interface {
SyscallConn() (syscall.RawConn, error)
SetLinger(int) error
}
var _ tcpConn = (*net.TCPConn)(nil)
// udpConn is an interface implemented by net.UDPConn.
// It can be used for interface assertions to check if a net.Conn is a UDP connection.
type udpConn interface {
SyscallConn() (syscall.RawConn, error)
ReadMsgUDP(b, oob []byte) (n, oobn, flags int, addr *net.UDPAddr, err error)
}
var _ udpConn = (*net.UDPConn)(nil)
// ipConn is an interface implemented by net.IPConn.
// It can be used for interface assertions to check if a net.Conn is an IP connection.
type ipConn interface {
SyscallConn() (syscall.RawConn, error)
ReadMsgIP(b, oob []byte) (n, oobn, flags int, addr *net.IPAddr, err error)
}
var _ ipConn = (*net.IPConn)(nil)
// NewConn returns a new raw connection. // NewConn returns a new raw connection.
func NewConn(c net.Conn) (*Conn, error) { func NewConn(c net.Conn) (*Conn, error) {
var err error var err error
var cc Conn var cc Conn
switch c := c.(type) { switch c := c.(type) {
case *net.TCPConn: case tcpConn:
cc.network = "tcp" cc.network = "tcp"
cc.c, err = c.SyscallConn() cc.c, err = c.SyscallConn()
case *net.UDPConn: case udpConn:
cc.network = "udp" cc.network = "udp"
cc.c, err = c.SyscallConn() cc.c, err = c.SyscallConn()
case *net.IPConn: case ipConn:
cc.network = "ip" cc.network = "ip"
cc.c, err = c.SyscallConn() cc.c, err = c.SyscallConn()
default: default:

View File

@@ -13,11 +13,13 @@ import (
"golang.org/x/net/internal/iana" "golang.org/x/net/internal/iana"
"golang.org/x/net/internal/socket" "golang.org/x/net/internal/socket"
"golang.org/x/sys/unix"
) )
func marshalPacketInfo(b []byte, cm *ControlMessage) []byte { func marshalPacketInfo(b []byte, cm *ControlMessage) []byte {
m := socket.ControlMessage(b) m := socket.ControlMessage(b)
m.MarshalHeader(iana.ProtocolIP, sysIP_PKTINFO, sizeofInetPktinfo) m.MarshalHeader(iana.ProtocolIP, unix.IP_PKTINFO, sizeofInetPktinfo)
if cm != nil { if cm != nil {
pi := (*inetPktinfo)(unsafe.Pointer(&m.Data(sizeofInetPktinfo)[0])) pi := (*inetPktinfo)(unsafe.Pointer(&m.Data(sizeofInetPktinfo)[0]))
if ip := cm.Src.To4(); ip != nil { if ip := cm.Src.To4(); ip != nil {

View File

@@ -10,11 +10,13 @@ import (
"golang.org/x/net/internal/iana" "golang.org/x/net/internal/iana"
"golang.org/x/net/internal/socket" "golang.org/x/net/internal/socket"
"golang.org/x/sys/unix"
) )
func marshalPacketInfo(b []byte, cm *ControlMessage) []byte { func marshalPacketInfo(b []byte, cm *ControlMessage) []byte {
m := socket.ControlMessage(b) m := socket.ControlMessage(b)
m.MarshalHeader(iana.ProtocolIP, sysIP_PKTINFO, sizeofInetPktinfo) m.MarshalHeader(iana.ProtocolIP, unix.IP_PKTINFO, sizeofInetPktinfo)
if cm != nil { if cm != nil {
pi := (*inetPktinfo)(unsafe.Pointer(&m.Data(sizeofInetPktinfo)[0])) pi := (*inetPktinfo)(unsafe.Pointer(&m.Data(sizeofInetPktinfo)[0]))
if ip := cm.Src.To4(); ip != nil { if ip := cm.Src.To4(); ip != nil {

View File

@@ -14,26 +14,28 @@ import (
"golang.org/x/net/internal/iana" "golang.org/x/net/internal/iana"
"golang.org/x/net/internal/socket" "golang.org/x/net/internal/socket"
"golang.org/x/sys/unix"
) )
var ( var (
ctlOpts = [ctlMax]ctlOpt{ ctlOpts = [ctlMax]ctlOpt{
ctlTTL: {sysIP_RECVTTL, 1, marshalTTL, parseTTL}, ctlTTL: {unix.IP_RECVTTL, 1, marshalTTL, parseTTL},
ctlDst: {sysIP_RECVDSTADDR, net.IPv4len, marshalDst, parseDst}, ctlDst: {unix.IP_RECVDSTADDR, net.IPv4len, marshalDst, parseDst},
ctlInterface: {sysIP_RECVIF, syscall.SizeofSockaddrDatalink, marshalInterface, parseInterface}, ctlInterface: {unix.IP_RECVINTERFACE, syscall.SizeofSockaddrDatalink, marshalInterface, parseInterface},
} }
sockOpts = map[int]*sockOpt{ sockOpts = map[int]*sockOpt{
ssoTOS: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_TOS, Len: 4}}, ssoTOS: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.IP_TOS, Len: 4}},
ssoTTL: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_TTL, Len: 4}}, ssoTTL: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.IP_TTL, Len: 4}},
ssoMulticastTTL: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_MULTICAST_TTL, Len: 1}}, ssoMulticastTTL: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.IP_MULTICAST_TTL, Len: 1}},
ssoMulticastInterface: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_MULTICAST_IF, Len: 4}}, ssoMulticastInterface: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.IP_MULTICAST_IF, Len: 4}},
ssoMulticastLoopback: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_MULTICAST_LOOP, Len: 1}}, ssoMulticastLoopback: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.IP_MULTICAST_LOOP, Len: 1}},
ssoReceiveTTL: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_RECVTTL, Len: 4}}, ssoReceiveTTL: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.IP_RECVTTL, Len: 4}},
ssoReceiveDst: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_RECVDSTADDR, Len: 4}}, ssoReceiveDst: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.IP_RECVDSTADDR, Len: 4}},
ssoReceiveInterface: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_RECVIF, Len: 4}}, ssoReceiveInterface: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.IP_RECVINTERFACE, Len: 4}},
ssoHeaderPrepend: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_HDRINCL, Len: 4}}, ssoHeaderPrepend: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.IP_HDRINCL, Len: 4}},
ssoJoinGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_ADD_MEMBERSHIP, Len: sizeofIPMreq}, typ: ssoTypeIPMreq}, ssoJoinGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.IP_ADD_MEMBERSHIP, Len: sizeofIPMreq}, typ: ssoTypeIPMreq},
ssoLeaveGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_DROP_MEMBERSHIP, Len: sizeofIPMreq}, typ: ssoTypeIPMreq}, ssoLeaveGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.IP_DROP_MEMBERSHIP, Len: sizeofIPMreq}, typ: ssoTypeIPMreq},
} }
) )

View File

@@ -13,26 +13,28 @@ import (
"golang.org/x/net/internal/iana" "golang.org/x/net/internal/iana"
"golang.org/x/net/internal/socket" "golang.org/x/net/internal/socket"
"golang.org/x/sys/unix"
) )
var ( var (
ctlOpts = [ctlMax]ctlOpt{ ctlOpts = [ctlMax]ctlOpt{
ctlTTL: {sysIP_RECVTTL, 1, marshalTTL, parseTTL}, ctlTTL: {unix.IP_RECVTTL, 1, marshalTTL, parseTTL},
ctlDst: {sysIP_RECVDSTADDR, net.IPv4len, marshalDst, parseDst}, ctlDst: {unix.IP_RECVDSTADDR, net.IPv4len, marshalDst, parseDst},
ctlInterface: {sysIP_RECVIF, syscall.SizeofSockaddrDatalink, marshalInterface, parseInterface}, ctlInterface: {unix.IP_RECVIF, syscall.SizeofSockaddrDatalink, marshalInterface, parseInterface},
} }
sockOpts = map[int]*sockOpt{ sockOpts = map[int]*sockOpt{
ssoTOS: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_TOS, Len: 4}}, ssoTOS: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.IP_TOS, Len: 4}},
ssoTTL: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_TTL, Len: 4}}, ssoTTL: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.IP_TTL, Len: 4}},
ssoMulticastTTL: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_MULTICAST_TTL, Len: 1}}, ssoMulticastTTL: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.IP_MULTICAST_TTL, Len: 1}},
ssoMulticastInterface: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_MULTICAST_IF, Len: 4}}, ssoMulticastInterface: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.IP_MULTICAST_IF, Len: 4}},
ssoMulticastLoopback: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_MULTICAST_LOOP, Len: 1}}, ssoMulticastLoopback: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.IP_MULTICAST_LOOP, Len: 1}},
ssoReceiveTTL: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_RECVTTL, Len: 4}}, ssoReceiveTTL: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.IP_RECVTTL, Len: 4}},
ssoReceiveDst: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_RECVDSTADDR, Len: 4}}, ssoReceiveDst: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.IP_RECVDSTADDR, Len: 4}},
ssoReceiveInterface: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_RECVIF, Len: 4}}, ssoReceiveInterface: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.IP_RECVIF, Len: 4}},
ssoHeaderPrepend: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_HDRINCL, Len: 4}}, ssoHeaderPrepend: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.IP_HDRINCL, Len: 4}},
ssoJoinGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_ADD_MEMBERSHIP, Len: sizeofIPMreq}, typ: ssoTypeIPMreq}, ssoJoinGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.IP_ADD_MEMBERSHIP, Len: sizeofIPMreq}, typ: ssoTypeIPMreq},
ssoLeaveGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_DROP_MEMBERSHIP, Len: sizeofIPMreq}, typ: ssoTypeIPMreq}, ssoLeaveGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.IP_DROP_MEMBERSHIP, Len: sizeofIPMreq}, typ: ssoTypeIPMreq},
} }
) )

View File

@@ -11,34 +11,36 @@ import (
"golang.org/x/net/internal/iana" "golang.org/x/net/internal/iana"
"golang.org/x/net/internal/socket" "golang.org/x/net/internal/socket"
"golang.org/x/sys/unix"
) )
var ( var (
ctlOpts = [ctlMax]ctlOpt{ ctlOpts = [ctlMax]ctlOpt{
ctlTTL: {sysIP_RECVTTL, 1, marshalTTL, parseTTL}, ctlTTL: {unix.IP_RECVTTL, 1, marshalTTL, parseTTL},
ctlDst: {sysIP_RECVDSTADDR, net.IPv4len, marshalDst, parseDst}, ctlDst: {unix.IP_RECVDSTADDR, net.IPv4len, marshalDst, parseDst},
ctlInterface: {sysIP_RECVIF, syscall.SizeofSockaddrDatalink, marshalInterface, parseInterface}, ctlInterface: {unix.IP_RECVIF, syscall.SizeofSockaddrDatalink, marshalInterface, parseInterface},
ctlPacketInfo: {sysIP_PKTINFO, sizeofInetPktinfo, marshalPacketInfo, parsePacketInfo}, ctlPacketInfo: {unix.IP_PKTINFO, sizeofInetPktinfo, marshalPacketInfo, parsePacketInfo},
} }
sockOpts = map[int]*sockOpt{ sockOpts = map[int]*sockOpt{
ssoTOS: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_TOS, Len: 4}}, ssoTOS: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.IP_TOS, Len: 4}},
ssoTTL: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_TTL, Len: 4}}, ssoTTL: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.IP_TTL, Len: 4}},
ssoMulticastTTL: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_MULTICAST_TTL, Len: 1}}, ssoMulticastTTL: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.IP_MULTICAST_TTL, Len: 1}},
ssoMulticastInterface: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_MULTICAST_IF, Len: sizeofIPMreqn}, typ: ssoTypeIPMreqn}, ssoMulticastInterface: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.IP_MULTICAST_IF, Len: sizeofIPMreqn}, typ: ssoTypeIPMreqn},
ssoMulticastLoopback: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_MULTICAST_LOOP, Len: 4}}, ssoMulticastLoopback: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.IP_MULTICAST_LOOP, Len: 4}},
ssoReceiveTTL: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_RECVTTL, Len: 4}}, ssoReceiveTTL: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.IP_RECVTTL, Len: 4}},
ssoReceiveDst: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_RECVDSTADDR, Len: 4}}, ssoReceiveDst: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.IP_RECVDSTADDR, Len: 4}},
ssoReceiveInterface: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_RECVIF, Len: 4}}, ssoReceiveInterface: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.IP_RECVIF, Len: 4}},
ssoHeaderPrepend: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_HDRINCL, Len: 4}}, ssoHeaderPrepend: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.IP_HDRINCL, Len: 4}},
ssoStripHeader: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_STRIPHDR, Len: 4}}, ssoStripHeader: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.IP_STRIPHDR, Len: 4}},
ssoJoinGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysMCAST_JOIN_GROUP, Len: sizeofGroupReq}, typ: ssoTypeGroupReq}, ssoJoinGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.MCAST_JOIN_GROUP, Len: sizeofGroupReq}, typ: ssoTypeGroupReq},
ssoLeaveGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysMCAST_LEAVE_GROUP, Len: sizeofGroupReq}, typ: ssoTypeGroupReq}, ssoLeaveGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.MCAST_LEAVE_GROUP, Len: sizeofGroupReq}, typ: ssoTypeGroupReq},
ssoJoinSourceGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysMCAST_JOIN_SOURCE_GROUP, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq}, ssoJoinSourceGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.MCAST_JOIN_SOURCE_GROUP, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq},
ssoLeaveSourceGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysMCAST_LEAVE_SOURCE_GROUP, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq}, ssoLeaveSourceGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.MCAST_LEAVE_SOURCE_GROUP, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq},
ssoBlockSourceGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysMCAST_BLOCK_SOURCE, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq}, ssoBlockSourceGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.MCAST_BLOCK_SOURCE, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq},
ssoUnblockSourceGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysMCAST_UNBLOCK_SOURCE, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq}, ssoUnblockSourceGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.MCAST_UNBLOCK_SOURCE, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq},
ssoPacketInfo: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_RECVPKTINFO, Len: 4}}, ssoPacketInfo: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.IP_RECVPKTINFO, Len: 4}},
} }
) )

View File

@@ -10,26 +10,28 @@ import (
"golang.org/x/net/internal/iana" "golang.org/x/net/internal/iana"
"golang.org/x/net/internal/socket" "golang.org/x/net/internal/socket"
"golang.org/x/sys/unix"
) )
var ( var (
ctlOpts = [ctlMax]ctlOpt{ ctlOpts = [ctlMax]ctlOpt{
ctlTTL: {sysIP_RECVTTL, 1, marshalTTL, parseTTL}, ctlTTL: {unix.IP_RECVTTL, 1, marshalTTL, parseTTL},
ctlDst: {sysIP_RECVDSTADDR, net.IPv4len, marshalDst, parseDst}, ctlDst: {unix.IP_RECVDSTADDR, net.IPv4len, marshalDst, parseDst},
ctlInterface: {sysIP_RECVIF, syscall.SizeofSockaddrDatalink, marshalInterface, parseInterface}, ctlInterface: {unix.IP_RECVIF, syscall.SizeofSockaddrDatalink, marshalInterface, parseInterface},
} }
sockOpts = map[int]*sockOpt{ sockOpts = map[int]*sockOpt{
ssoTOS: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_TOS, Len: 4}}, ssoTOS: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.IP_TOS, Len: 4}},
ssoTTL: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_TTL, Len: 4}}, ssoTTL: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.IP_TTL, Len: 4}},
ssoMulticastTTL: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_MULTICAST_TTL, Len: 1}}, ssoMulticastTTL: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.IP_MULTICAST_TTL, Len: 1}},
ssoMulticastInterface: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_MULTICAST_IF, Len: 4}}, ssoMulticastInterface: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.IP_MULTICAST_IF, Len: 4}},
ssoMulticastLoopback: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_MULTICAST_LOOP, Len: 4}}, ssoMulticastLoopback: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.IP_MULTICAST_LOOP, Len: 4}},
ssoReceiveTTL: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_RECVTTL, Len: 4}}, ssoReceiveTTL: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.IP_RECVTTL, Len: 4}},
ssoReceiveDst: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_RECVDSTADDR, Len: 4}}, ssoReceiveDst: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.IP_RECVDSTADDR, Len: 4}},
ssoReceiveInterface: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_RECVIF, Len: 4}}, ssoReceiveInterface: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.IP_RECVIF, Len: 4}},
ssoHeaderPrepend: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_HDRINCL, Len: 4}}, ssoHeaderPrepend: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.IP_HDRINCL, Len: 4}},
ssoJoinGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_ADD_MEMBERSHIP, Len: sizeofIPMreq}, typ: ssoTypeIPMreq}, ssoJoinGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.IP_ADD_MEMBERSHIP, Len: sizeofIPMreq}, typ: ssoTypeIPMreq},
ssoLeaveGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_DROP_MEMBERSHIP, Len: sizeofIPMreq}, typ: ssoTypeIPMreq}, ssoLeaveGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.IP_DROP_MEMBERSHIP, Len: sizeofIPMreq}, typ: ssoTypeIPMreq},
} }
) )

View File

@@ -13,38 +13,40 @@ import (
"golang.org/x/net/internal/iana" "golang.org/x/net/internal/iana"
"golang.org/x/net/internal/socket" "golang.org/x/net/internal/socket"
"golang.org/x/sys/unix"
) )
var ( var (
ctlOpts = [ctlMax]ctlOpt{ ctlOpts = [ctlMax]ctlOpt{
ctlTTL: {sysIP_RECVTTL, 1, marshalTTL, parseTTL}, ctlTTL: {unix.IP_RECVTTL, 1, marshalTTL, parseTTL},
ctlDst: {sysIP_RECVDSTADDR, net.IPv4len, marshalDst, parseDst}, ctlDst: {unix.IP_RECVDSTADDR, net.IPv4len, marshalDst, parseDst},
ctlInterface: {sysIP_RECVIF, syscall.SizeofSockaddrDatalink, marshalInterface, parseInterface}, ctlInterface: {unix.IP_RECVIF, syscall.SizeofSockaddrDatalink, marshalInterface, parseInterface},
} }
sockOpts = map[int]*sockOpt{ sockOpts = map[int]*sockOpt{
ssoTOS: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_TOS, Len: 4}}, ssoTOS: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.IP_TOS, Len: 4}},
ssoTTL: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_TTL, Len: 4}}, ssoTTL: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.IP_TTL, Len: 4}},
ssoMulticastTTL: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_MULTICAST_TTL, Len: 1}}, ssoMulticastTTL: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.IP_MULTICAST_TTL, Len: 1}},
ssoMulticastInterface: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_MULTICAST_IF, Len: 4}}, ssoMulticastInterface: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.IP_MULTICAST_IF, Len: 4}},
ssoMulticastLoopback: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_MULTICAST_LOOP, Len: 4}}, ssoMulticastLoopback: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.IP_MULTICAST_LOOP, Len: 4}},
ssoReceiveTTL: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_RECVTTL, Len: 4}}, ssoReceiveTTL: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.IP_RECVTTL, Len: 4}},
ssoReceiveDst: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_RECVDSTADDR, Len: 4}}, ssoReceiveDst: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.IP_RECVDSTADDR, Len: 4}},
ssoReceiveInterface: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_RECVIF, Len: 4}}, ssoReceiveInterface: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.IP_RECVIF, Len: 4}},
ssoHeaderPrepend: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_HDRINCL, Len: 4}}, ssoHeaderPrepend: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.IP_HDRINCL, Len: 4}},
ssoJoinGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysMCAST_JOIN_GROUP, Len: sizeofGroupReq}, typ: ssoTypeGroupReq}, ssoJoinGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.MCAST_JOIN_GROUP, Len: sizeofGroupReq}, typ: ssoTypeGroupReq},
ssoLeaveGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysMCAST_LEAVE_GROUP, Len: sizeofGroupReq}, typ: ssoTypeGroupReq}, ssoLeaveGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.MCAST_LEAVE_GROUP, Len: sizeofGroupReq}, typ: ssoTypeGroupReq},
ssoJoinSourceGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysMCAST_JOIN_SOURCE_GROUP, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq}, ssoJoinSourceGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.MCAST_JOIN_SOURCE_GROUP, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq},
ssoLeaveSourceGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysMCAST_LEAVE_SOURCE_GROUP, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq}, ssoLeaveSourceGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.MCAST_LEAVE_SOURCE_GROUP, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq},
ssoBlockSourceGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysMCAST_BLOCK_SOURCE, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq}, ssoBlockSourceGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.MCAST_BLOCK_SOURCE, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq},
ssoUnblockSourceGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysMCAST_UNBLOCK_SOURCE, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq}, ssoUnblockSourceGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.MCAST_UNBLOCK_SOURCE, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq},
} }
) )
func init() { func init() {
freebsdVersion, _ = syscall.SysctlUint32("kern.osreldate") freebsdVersion, _ = syscall.SysctlUint32("kern.osreldate")
if freebsdVersion >= 1000000 { if freebsdVersion >= 1000000 {
sockOpts[ssoMulticastInterface] = &sockOpt{Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_MULTICAST_IF, Len: sizeofIPMreqn}, typ: ssoTypeIPMreqn} sockOpts[ssoMulticastInterface] = &sockOpt{Option: socket.Option{Level: iana.ProtocolIP, Name: unix.IP_MULTICAST_IF, Len: sizeofIPMreqn}, typ: ssoTypeIPMreqn}
} }
if runtime.GOOS == "freebsd" && runtime.GOARCH == "386" { if runtime.GOOS == "freebsd" && runtime.GOARCH == "386" {
archs, _ := syscall.Sysctl("kern.supported_archs") archs, _ := syscall.Sysctl("kern.supported_archs")

View File

@@ -11,31 +11,32 @@ import (
"golang.org/x/net/internal/iana" "golang.org/x/net/internal/iana"
"golang.org/x/net/internal/socket" "golang.org/x/net/internal/socket"
"golang.org/x/sys/unix" "golang.org/x/sys/unix"
) )
var ( var (
ctlOpts = [ctlMax]ctlOpt{ ctlOpts = [ctlMax]ctlOpt{
ctlTTL: {sysIP_TTL, 1, marshalTTL, parseTTL}, ctlTTL: {unix.IP_TTL, 1, marshalTTL, parseTTL},
ctlPacketInfo: {sysIP_PKTINFO, sizeofInetPktinfo, marshalPacketInfo, parsePacketInfo}, ctlPacketInfo: {unix.IP_PKTINFO, sizeofInetPktinfo, marshalPacketInfo, parsePacketInfo},
} }
sockOpts = map[int]*sockOpt{ sockOpts = map[int]*sockOpt{
ssoTOS: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_TOS, Len: 4}}, ssoTOS: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.IP_TOS, Len: 4}},
ssoTTL: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_TTL, Len: 4}}, ssoTTL: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.IP_TTL, Len: 4}},
ssoMulticastTTL: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_MULTICAST_TTL, Len: 4}}, ssoMulticastTTL: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.IP_MULTICAST_TTL, Len: 4}},
ssoMulticastInterface: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_MULTICAST_IF, Len: sizeofIPMreqn}, typ: ssoTypeIPMreqn}, ssoMulticastInterface: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.IP_MULTICAST_IF, Len: sizeofIPMreqn}, typ: ssoTypeIPMreqn},
ssoMulticastLoopback: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_MULTICAST_LOOP, Len: 4}}, ssoMulticastLoopback: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.IP_MULTICAST_LOOP, Len: 4}},
ssoReceiveTTL: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_RECVTTL, Len: 4}}, ssoReceiveTTL: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.IP_RECVTTL, Len: 4}},
ssoPacketInfo: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_PKTINFO, Len: 4}}, ssoPacketInfo: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.IP_PKTINFO, Len: 4}},
ssoHeaderPrepend: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_HDRINCL, Len: 4}}, ssoHeaderPrepend: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.IP_HDRINCL, Len: 4}},
ssoICMPFilter: {Option: socket.Option{Level: iana.ProtocolReserved, Name: sysICMP_FILTER, Len: sizeofICMPFilter}}, ssoICMPFilter: {Option: socket.Option{Level: iana.ProtocolReserved, Name: unix.ICMP_FILTER, Len: sizeofICMPFilter}},
ssoJoinGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysMCAST_JOIN_GROUP, Len: sizeofGroupReq}, typ: ssoTypeGroupReq}, ssoJoinGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.MCAST_JOIN_GROUP, Len: sizeofGroupReq}, typ: ssoTypeGroupReq},
ssoLeaveGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysMCAST_LEAVE_GROUP, Len: sizeofGroupReq}, typ: ssoTypeGroupReq}, ssoLeaveGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.MCAST_LEAVE_GROUP, Len: sizeofGroupReq}, typ: ssoTypeGroupReq},
ssoJoinSourceGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysMCAST_JOIN_SOURCE_GROUP, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq}, ssoJoinSourceGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.MCAST_JOIN_SOURCE_GROUP, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq},
ssoLeaveSourceGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysMCAST_LEAVE_SOURCE_GROUP, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq}, ssoLeaveSourceGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.MCAST_LEAVE_SOURCE_GROUP, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq},
ssoBlockSourceGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysMCAST_BLOCK_SOURCE, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq}, ssoBlockSourceGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.MCAST_BLOCK_SOURCE, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq},
ssoUnblockSourceGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysMCAST_UNBLOCK_SOURCE, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq}, ssoUnblockSourceGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.MCAST_UNBLOCK_SOURCE, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq},
ssoAttachFilter: {Option: socket.Option{Level: unix.SOL_SOCKET, Name: unix.SO_ATTACH_FILTER, Len: unix.SizeofSockFprog}}, ssoAttachFilter: {Option: socket.Option{Level: unix.SOL_SOCKET, Name: unix.SO_ATTACH_FILTER, Len: unix.SizeofSockFprog}},
} }
) )

View File

@@ -11,29 +11,31 @@ import (
"golang.org/x/net/internal/iana" "golang.org/x/net/internal/iana"
"golang.org/x/net/internal/socket" "golang.org/x/net/internal/socket"
"golang.org/x/sys/unix"
) )
var ( var (
ctlOpts = [ctlMax]ctlOpt{ ctlOpts = [ctlMax]ctlOpt{
ctlTTL: {sysIP_RECVTTL, 4, marshalTTL, parseTTL}, ctlTTL: {unix.IP_RECVTTL, 4, marshalTTL, parseTTL},
ctlPacketInfo: {sysIP_PKTINFO, sizeofInetPktinfo, marshalPacketInfo, parsePacketInfo}, ctlPacketInfo: {unix.IP_PKTINFO, sizeofInetPktinfo, marshalPacketInfo, parsePacketInfo},
} }
sockOpts = map[int]sockOpt{ sockOpts = map[int]sockOpt{
ssoTOS: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_TOS, Len: 4}}, ssoTOS: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.IP_TOS, Len: 4}},
ssoTTL: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_TTL, Len: 4}}, ssoTTL: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.IP_TTL, Len: 4}},
ssoMulticastTTL: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_MULTICAST_TTL, Len: 1}}, ssoMulticastTTL: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.IP_MULTICAST_TTL, Len: 1}},
ssoMulticastInterface: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_MULTICAST_IF, Len: 4}}, ssoMulticastInterface: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.IP_MULTICAST_IF, Len: 4}},
ssoMulticastLoopback: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_MULTICAST_LOOP, Len: 1}}, ssoMulticastLoopback: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.IP_MULTICAST_LOOP, Len: 1}},
ssoReceiveTTL: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_RECVTTL, Len: 4}}, ssoReceiveTTL: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.IP_RECVTTL, Len: 4}},
ssoPacketInfo: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_RECVPKTINFO, Len: 4}}, ssoPacketInfo: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.IP_RECVPKTINFO, Len: 4}},
ssoHeaderPrepend: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_HDRINCL, Len: 4}}, ssoHeaderPrepend: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.IP_HDRINCL, Len: 4}},
ssoJoinGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysMCAST_JOIN_GROUP, Len: sizeofGroupReq}, typ: ssoTypeGroupReq}, ssoJoinGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.MCAST_JOIN_GROUP, Len: sizeofGroupReq}, typ: ssoTypeGroupReq},
ssoLeaveGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysMCAST_LEAVE_GROUP, Len: sizeofGroupReq}, typ: ssoTypeGroupReq}, ssoLeaveGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.MCAST_LEAVE_GROUP, Len: sizeofGroupReq}, typ: ssoTypeGroupReq},
ssoJoinSourceGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysMCAST_JOIN_SOURCE_GROUP, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq}, ssoJoinSourceGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.MCAST_JOIN_SOURCE_GROUP, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq},
ssoLeaveSourceGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysMCAST_LEAVE_SOURCE_GROUP, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq}, ssoLeaveSourceGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.MCAST_LEAVE_SOURCE_GROUP, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq},
ssoBlockSourceGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysMCAST_BLOCK_SOURCE, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq}, ssoBlockSourceGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.MCAST_BLOCK_SOURCE, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq},
ssoUnblockSourceGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysMCAST_UNBLOCK_SOURCE, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq}, ssoUnblockSourceGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.MCAST_UNBLOCK_SOURCE, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq},
} }
) )

View File

@@ -7,34 +7,15 @@ package ipv4
import ( import (
"golang.org/x/net/internal/iana" "golang.org/x/net/internal/iana"
"golang.org/x/net/internal/socket" "golang.org/x/net/internal/socket"
"golang.org/x/sys/windows"
) )
const ( const (
// See ws2tcpip.h.
sysIP_OPTIONS = 0x1
sysIP_HDRINCL = 0x2
sysIP_TOS = 0x3
sysIP_TTL = 0x4
sysIP_MULTICAST_IF = 0x9
sysIP_MULTICAST_TTL = 0xa
sysIP_MULTICAST_LOOP = 0xb
sysIP_ADD_MEMBERSHIP = 0xc
sysIP_DROP_MEMBERSHIP = 0xd
sysIP_DONTFRAGMENT = 0xe
sysIP_ADD_SOURCE_MEMBERSHIP = 0xf
sysIP_DROP_SOURCE_MEMBERSHIP = 0x10
sysIP_PKTINFO = 0x13
sizeofInetPktinfo = 0x8
sizeofIPMreq = 0x8 sizeofIPMreq = 0x8
sizeofIPMreqSource = 0xc sizeofIPMreqSource = 0xc
) )
type inetPktinfo struct {
Addr [4]byte
Ifindex int32
}
type ipMreq struct { type ipMreq struct {
Multiaddr [4]byte Multiaddr [4]byte
Interface [4]byte Interface [4]byte
@@ -51,17 +32,13 @@ var (
ctlOpts = [ctlMax]ctlOpt{} ctlOpts = [ctlMax]ctlOpt{}
sockOpts = map[int]*sockOpt{ sockOpts = map[int]*sockOpt{
ssoTOS: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_TOS, Len: 4}}, ssoTOS: {Option: socket.Option{Level: iana.ProtocolIP, Name: windows.IP_TOS, Len: 4}},
ssoTTL: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_TTL, Len: 4}}, ssoTTL: {Option: socket.Option{Level: iana.ProtocolIP, Name: windows.IP_TTL, Len: 4}},
ssoMulticastTTL: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_MULTICAST_TTL, Len: 4}}, ssoMulticastTTL: {Option: socket.Option{Level: iana.ProtocolIP, Name: windows.IP_MULTICAST_TTL, Len: 4}},
ssoMulticastInterface: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_MULTICAST_IF, Len: 4}}, ssoMulticastInterface: {Option: socket.Option{Level: iana.ProtocolIP, Name: windows.IP_MULTICAST_IF, Len: 4}},
ssoMulticastLoopback: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_MULTICAST_LOOP, Len: 4}}, ssoMulticastLoopback: {Option: socket.Option{Level: iana.ProtocolIP, Name: windows.IP_MULTICAST_LOOP, Len: 4}},
ssoHeaderPrepend: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_HDRINCL, Len: 4}}, ssoHeaderPrepend: {Option: socket.Option{Level: iana.ProtocolIP, Name: windows.IP_HDRINCL, Len: 4}},
ssoJoinGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_ADD_MEMBERSHIP, Len: sizeofIPMreq}, typ: ssoTypeIPMreq}, ssoJoinGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: windows.IP_ADD_MEMBERSHIP, Len: sizeofIPMreq}, typ: ssoTypeIPMreq},
ssoLeaveGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_DROP_MEMBERSHIP, Len: sizeofIPMreq}, typ: ssoTypeIPMreq}, ssoLeaveGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: windows.IP_DROP_MEMBERSHIP, Len: sizeofIPMreq}, typ: ssoTypeIPMreq},
} }
) )
func (pi *inetPktinfo) setIfindex(i int) {
pi.Ifindex = int32(i)
}

View File

@@ -11,24 +11,26 @@ import (
"golang.org/x/net/internal/iana" "golang.org/x/net/internal/iana"
"golang.org/x/net/internal/socket" "golang.org/x/net/internal/socket"
"golang.org/x/sys/unix"
) )
var ( var (
ctlOpts = [ctlMax]ctlOpt{ ctlOpts = [ctlMax]ctlOpt{
ctlPacketInfo: {sysIP_PKTINFO, sizeofInetPktinfo, marshalPacketInfo, parsePacketInfo}, ctlPacketInfo: {unix.IP_PKTINFO, sizeofInetPktinfo, marshalPacketInfo, parsePacketInfo},
} }
sockOpts = map[int]*sockOpt{ sockOpts = map[int]*sockOpt{
ssoMulticastTTL: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_MULTICAST_TTL, Len: 1}}, ssoMulticastTTL: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.IP_MULTICAST_TTL, Len: 1}},
ssoMulticastInterface: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_MULTICAST_IF, Len: 4}}, ssoMulticastInterface: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.IP_MULTICAST_IF, Len: 4}},
ssoMulticastLoopback: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_MULTICAST_LOOP, Len: 1}}, ssoMulticastLoopback: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.IP_MULTICAST_LOOP, Len: 1}},
ssoPacketInfo: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysIP_RECVPKTINFO, Len: 4}}, ssoPacketInfo: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.IP_RECVPKTINFO, Len: 4}},
ssoJoinGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysMCAST_JOIN_GROUP, Len: sizeofGroupReq}, typ: ssoTypeGroupReq}, ssoJoinGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.MCAST_JOIN_GROUP, Len: sizeofGroupReq}, typ: ssoTypeGroupReq},
ssoLeaveGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysMCAST_LEAVE_GROUP, Len: sizeofGroupReq}, typ: ssoTypeGroupReq}, ssoLeaveGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.MCAST_LEAVE_GROUP, Len: sizeofGroupReq}, typ: ssoTypeGroupReq},
ssoJoinSourceGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysMCAST_JOIN_SOURCE_GROUP, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq}, ssoJoinSourceGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.MCAST_JOIN_SOURCE_GROUP, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq},
ssoLeaveSourceGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysMCAST_LEAVE_SOURCE_GROUP, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq}, ssoLeaveSourceGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.MCAST_LEAVE_SOURCE_GROUP, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq},
ssoBlockSourceGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysMCAST_BLOCK_SOURCE, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq}, ssoBlockSourceGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.MCAST_BLOCK_SOURCE, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq},
ssoUnblockSourceGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: sysMCAST_UNBLOCK_SOURCE, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq}, ssoUnblockSourceGroup: {Option: socket.Option{Level: iana.ProtocolIP, Name: unix.MCAST_UNBLOCK_SOURCE, Len: sizeofGroupSourceReq}, typ: ssoTypeGroupSourceReq},
} }
) )

View File

@@ -8,23 +8,10 @@
package ipv4 package ipv4
const ( const (
sysIP_OPTIONS = 0x1
sysIP_HDRINCL = 0x2
sysIP_TOS = 0x3
sysIP_TTL = 0x4
sysIP_RECVOPTS = 0x5
sysIP_RECVRETOPTS = 0x6
sysIP_RECVDSTADDR = 0x7 sysIP_RECVDSTADDR = 0x7
sysIP_RETOPTS = 0x8
sysIP_RECVIF = 0x20 sysIP_RECVIF = 0x20
sysIP_RECVTTL = 0x22 sysIP_RECVTTL = 0x22
sysIP_MULTICAST_IF = 0x9
sysIP_MULTICAST_TTL = 0xa
sysIP_MULTICAST_LOOP = 0xb
sysIP_ADD_MEMBERSHIP = 0xc
sysIP_DROP_MEMBERSHIP = 0xd
sizeofIPMreq = 0x8 sizeofIPMreq = 0x8
) )

View File

@@ -4,38 +4,9 @@
package ipv4 package ipv4
const ( const (
sysIP_OPTIONS = 0x1
sysIP_HDRINCL = 0x2
sysIP_TOS = 0x3
sysIP_TTL = 0x4
sysIP_RECVOPTS = 0x5
sysIP_RECVRETOPTS = 0x6
sysIP_RECVDSTADDR = 0x7 sysIP_RECVDSTADDR = 0x7
sysIP_RETOPTS = 0x8
sysIP_RECVIF = 0x14 sysIP_RECVIF = 0x14
sysIP_STRIPHDR = 0x17
sysIP_RECVTTL = 0x18 sysIP_RECVTTL = 0x18
sysIP_BOUND_IF = 0x19
sysIP_PKTINFO = 0x1a
sysIP_RECVPKTINFO = 0x1a
sysIP_MULTICAST_IF = 0x9
sysIP_MULTICAST_TTL = 0xa
sysIP_MULTICAST_LOOP = 0xb
sysIP_ADD_MEMBERSHIP = 0xc
sysIP_DROP_MEMBERSHIP = 0xd
sysIP_MULTICAST_VIF = 0xe
sysIP_MULTICAST_IFINDEX = 0x42
sysIP_ADD_SOURCE_MEMBERSHIP = 0x46
sysIP_DROP_SOURCE_MEMBERSHIP = 0x47
sysIP_BLOCK_SOURCE = 0x48
sysIP_UNBLOCK_SOURCE = 0x49
sysMCAST_JOIN_GROUP = 0x50
sysMCAST_LEAVE_GROUP = 0x51
sysMCAST_JOIN_SOURCE_GROUP = 0x52
sysMCAST_LEAVE_SOURCE_GROUP = 0x53
sysMCAST_BLOCK_SOURCE = 0x54
sysMCAST_UNBLOCK_SOURCE = 0x55
sizeofSockaddrStorage = 0x80 sizeofSockaddrStorage = 0x80
sizeofSockaddrInet = 0x10 sizeofSockaddrInet = 0x10

View File

@@ -4,24 +4,10 @@
package ipv4 package ipv4
const ( const (
sysIP_OPTIONS = 0x1
sysIP_HDRINCL = 0x2
sysIP_TOS = 0x3
sysIP_TTL = 0x4
sysIP_RECVOPTS = 0x5
sysIP_RECVRETOPTS = 0x6
sysIP_RECVDSTADDR = 0x7 sysIP_RECVDSTADDR = 0x7
sysIP_RETOPTS = 0x8
sysIP_RECVIF = 0x14 sysIP_RECVIF = 0x14
sysIP_RECVTTL = 0x41 sysIP_RECVTTL = 0x41
sysIP_MULTICAST_IF = 0x9
sysIP_MULTICAST_TTL = 0xa
sysIP_MULTICAST_LOOP = 0xb
sysIP_MULTICAST_VIF = 0xe
sysIP_ADD_MEMBERSHIP = 0xc
sysIP_DROP_MEMBERSHIP = 0xd
sizeofIPMreq = 0x8 sizeofIPMreq = 0x8
) )

View File

@@ -4,39 +4,9 @@
package ipv4 package ipv4
const ( const (
sysIP_OPTIONS = 0x1
sysIP_HDRINCL = 0x2
sysIP_TOS = 0x3
sysIP_TTL = 0x4
sysIP_RECVOPTS = 0x5
sysIP_RECVRETOPTS = 0x6
sysIP_RECVDSTADDR = 0x7 sysIP_RECVDSTADDR = 0x7
sysIP_SENDSRCADDR = 0x7
sysIP_RETOPTS = 0x8
sysIP_RECVIF = 0x14 sysIP_RECVIF = 0x14
sysIP_ONESBCAST = 0x17
sysIP_BINDANY = 0x18
sysIP_RECVTTL = 0x41 sysIP_RECVTTL = 0x41
sysIP_MINTTL = 0x42
sysIP_DONTFRAG = 0x43
sysIP_RECVTOS = 0x44
sysIP_MULTICAST_IF = 0x9
sysIP_MULTICAST_TTL = 0xa
sysIP_MULTICAST_LOOP = 0xb
sysIP_ADD_MEMBERSHIP = 0xc
sysIP_DROP_MEMBERSHIP = 0xd
sysIP_MULTICAST_VIF = 0xe
sysIP_ADD_SOURCE_MEMBERSHIP = 0x46
sysIP_DROP_SOURCE_MEMBERSHIP = 0x47
sysIP_BLOCK_SOURCE = 0x48
sysIP_UNBLOCK_SOURCE = 0x49
sysMCAST_JOIN_GROUP = 0x50
sysMCAST_LEAVE_GROUP = 0x51
sysMCAST_JOIN_SOURCE_GROUP = 0x52
sysMCAST_LEAVE_SOURCE_GROUP = 0x53
sysMCAST_BLOCK_SOURCE = 0x54
sysMCAST_UNBLOCK_SOURCE = 0x55
sizeofSockaddrStorage = 0x80 sizeofSockaddrStorage = 0x80
sizeofSockaddrInet = 0x10 sizeofSockaddrInet = 0x10

View File

@@ -4,39 +4,9 @@
package ipv4 package ipv4
const ( const (
sysIP_OPTIONS = 0x1
sysIP_HDRINCL = 0x2
sysIP_TOS = 0x3
sysIP_TTL = 0x4
sysIP_RECVOPTS = 0x5
sysIP_RECVRETOPTS = 0x6
sysIP_RECVDSTADDR = 0x7 sysIP_RECVDSTADDR = 0x7
sysIP_SENDSRCADDR = 0x7
sysIP_RETOPTS = 0x8
sysIP_RECVIF = 0x14 sysIP_RECVIF = 0x14
sysIP_ONESBCAST = 0x17
sysIP_BINDANY = 0x18
sysIP_RECVTTL = 0x41 sysIP_RECVTTL = 0x41
sysIP_MINTTL = 0x42
sysIP_DONTFRAG = 0x43
sysIP_RECVTOS = 0x44
sysIP_MULTICAST_IF = 0x9
sysIP_MULTICAST_TTL = 0xa
sysIP_MULTICAST_LOOP = 0xb
sysIP_ADD_MEMBERSHIP = 0xc
sysIP_DROP_MEMBERSHIP = 0xd
sysIP_MULTICAST_VIF = 0xe
sysIP_ADD_SOURCE_MEMBERSHIP = 0x46
sysIP_DROP_SOURCE_MEMBERSHIP = 0x47
sysIP_BLOCK_SOURCE = 0x48
sysIP_UNBLOCK_SOURCE = 0x49
sysMCAST_JOIN_GROUP = 0x50
sysMCAST_LEAVE_GROUP = 0x51
sysMCAST_JOIN_SOURCE_GROUP = 0x52
sysMCAST_LEAVE_SOURCE_GROUP = 0x53
sysMCAST_BLOCK_SOURCE = 0x54
sysMCAST_UNBLOCK_SOURCE = 0x55
sizeofSockaddrStorage = 0x80 sizeofSockaddrStorage = 0x80
sizeofSockaddrInet = 0x10 sizeofSockaddrInet = 0x10

View File

@@ -4,39 +4,9 @@
package ipv4 package ipv4
const ( const (
sysIP_OPTIONS = 0x1
sysIP_HDRINCL = 0x2
sysIP_TOS = 0x3
sysIP_TTL = 0x4
sysIP_RECVOPTS = 0x5
sysIP_RECVRETOPTS = 0x6
sysIP_RECVDSTADDR = 0x7 sysIP_RECVDSTADDR = 0x7
sysIP_SENDSRCADDR = 0x7
sysIP_RETOPTS = 0x8
sysIP_RECVIF = 0x14 sysIP_RECVIF = 0x14
sysIP_ONESBCAST = 0x17
sysIP_BINDANY = 0x18
sysIP_RECVTTL = 0x41 sysIP_RECVTTL = 0x41
sysIP_MINTTL = 0x42
sysIP_DONTFRAG = 0x43
sysIP_RECVTOS = 0x44
sysIP_MULTICAST_IF = 0x9
sysIP_MULTICAST_TTL = 0xa
sysIP_MULTICAST_LOOP = 0xb
sysIP_ADD_MEMBERSHIP = 0xc
sysIP_DROP_MEMBERSHIP = 0xd
sysIP_MULTICAST_VIF = 0xe
sysIP_ADD_SOURCE_MEMBERSHIP = 0x46
sysIP_DROP_SOURCE_MEMBERSHIP = 0x47
sysIP_BLOCK_SOURCE = 0x48
sysIP_UNBLOCK_SOURCE = 0x49
sysMCAST_JOIN_GROUP = 0x50
sysMCAST_LEAVE_GROUP = 0x51
sysMCAST_JOIN_SOURCE_GROUP = 0x52
sysMCAST_LEAVE_SOURCE_GROUP = 0x53
sysMCAST_BLOCK_SOURCE = 0x54
sysMCAST_UNBLOCK_SOURCE = 0x55
sizeofSockaddrStorage = 0x80 sizeofSockaddrStorage = 0x80
sizeofSockaddrInet = 0x10 sizeofSockaddrInet = 0x10

View File

@@ -4,39 +4,9 @@
package ipv4 package ipv4
const ( const (
sysIP_OPTIONS = 0x1
sysIP_HDRINCL = 0x2
sysIP_TOS = 0x3
sysIP_TTL = 0x4
sysIP_RECVOPTS = 0x5
sysIP_RECVRETOPTS = 0x6
sysIP_RECVDSTADDR = 0x7 sysIP_RECVDSTADDR = 0x7
sysIP_SENDSRCADDR = 0x7
sysIP_RETOPTS = 0x8
sysIP_RECVIF = 0x14 sysIP_RECVIF = 0x14
sysIP_ONESBCAST = 0x17
sysIP_BINDANY = 0x18
sysIP_RECVTTL = 0x41 sysIP_RECVTTL = 0x41
sysIP_MINTTL = 0x42
sysIP_DONTFRAG = 0x43
sysIP_RECVTOS = 0x44
sysIP_MULTICAST_IF = 0x9
sysIP_MULTICAST_TTL = 0xa
sysIP_MULTICAST_LOOP = 0xb
sysIP_ADD_MEMBERSHIP = 0xc
sysIP_DROP_MEMBERSHIP = 0xd
sysIP_MULTICAST_VIF = 0xe
sysIP_ADD_SOURCE_MEMBERSHIP = 0x46
sysIP_DROP_SOURCE_MEMBERSHIP = 0x47
sysIP_BLOCK_SOURCE = 0x48
sysIP_UNBLOCK_SOURCE = 0x49
sysMCAST_JOIN_GROUP = 0x50
sysMCAST_LEAVE_GROUP = 0x51
sysMCAST_JOIN_SOURCE_GROUP = 0x52
sysMCAST_LEAVE_SOURCE_GROUP = 0x53
sysMCAST_BLOCK_SOURCE = 0x54
sysMCAST_UNBLOCK_SOURCE = 0x55
sizeofSockaddrStorage = 0x80 sizeofSockaddrStorage = 0x80
sizeofSockaddrInet = 0x10 sizeofSockaddrInet = 0x10

View File

@@ -4,56 +4,7 @@
package ipv4 package ipv4
const ( const (
sysIP_TOS = 0x1 sysIP_RECVTTL = 0xc
sysIP_TTL = 0x2
sysIP_HDRINCL = 0x3
sysIP_OPTIONS = 0x4
sysIP_ROUTER_ALERT = 0x5
sysIP_RECVOPTS = 0x6
sysIP_RETOPTS = 0x7
sysIP_PKTINFO = 0x8
sysIP_PKTOPTIONS = 0x9
sysIP_MTU_DISCOVER = 0xa
sysIP_RECVERR = 0xb
sysIP_RECVTTL = 0xc
sysIP_RECVTOS = 0xd
sysIP_MTU = 0xe
sysIP_FREEBIND = 0xf
sysIP_TRANSPARENT = 0x13
sysIP_RECVRETOPTS = 0x7
sysIP_ORIGDSTADDR = 0x14
sysIP_RECVORIGDSTADDR = 0x14
sysIP_MINTTL = 0x15
sysIP_NODEFRAG = 0x16
sysIP_UNICAST_IF = 0x32
sysIP_MULTICAST_IF = 0x20
sysIP_MULTICAST_TTL = 0x21
sysIP_MULTICAST_LOOP = 0x22
sysIP_ADD_MEMBERSHIP = 0x23
sysIP_DROP_MEMBERSHIP = 0x24
sysIP_UNBLOCK_SOURCE = 0x25
sysIP_BLOCK_SOURCE = 0x26
sysIP_ADD_SOURCE_MEMBERSHIP = 0x27
sysIP_DROP_SOURCE_MEMBERSHIP = 0x28
sysIP_MSFILTER = 0x29
sysMCAST_JOIN_GROUP = 0x2a
sysMCAST_LEAVE_GROUP = 0x2d
sysMCAST_JOIN_SOURCE_GROUP = 0x2e
sysMCAST_LEAVE_SOURCE_GROUP = 0x2f
sysMCAST_BLOCK_SOURCE = 0x2b
sysMCAST_UNBLOCK_SOURCE = 0x2c
sysMCAST_MSFILTER = 0x30
sysIP_MULTICAST_ALL = 0x31
sysICMP_FILTER = 0x1
sysSO_EE_ORIGIN_NONE = 0x0
sysSO_EE_ORIGIN_LOCAL = 0x1
sysSO_EE_ORIGIN_ICMP = 0x2
sysSO_EE_ORIGIN_ICMP6 = 0x3
sysSO_EE_ORIGIN_TXSTATUS = 0x4
sysSO_EE_ORIGIN_TIMESTAMPING = 0x4
sizeofKernelSockaddrStorage = 0x80 sizeofKernelSockaddrStorage = 0x80
sizeofSockaddrInet = 0x10 sizeofSockaddrInet = 0x10

View File

@@ -4,56 +4,7 @@
package ipv4 package ipv4
const ( const (
sysIP_TOS = 0x1 sysIP_RECVTTL = 0xc
sysIP_TTL = 0x2
sysIP_HDRINCL = 0x3
sysIP_OPTIONS = 0x4
sysIP_ROUTER_ALERT = 0x5
sysIP_RECVOPTS = 0x6
sysIP_RETOPTS = 0x7
sysIP_PKTINFO = 0x8
sysIP_PKTOPTIONS = 0x9
sysIP_MTU_DISCOVER = 0xa
sysIP_RECVERR = 0xb
sysIP_RECVTTL = 0xc
sysIP_RECVTOS = 0xd
sysIP_MTU = 0xe
sysIP_FREEBIND = 0xf
sysIP_TRANSPARENT = 0x13
sysIP_RECVRETOPTS = 0x7
sysIP_ORIGDSTADDR = 0x14
sysIP_RECVORIGDSTADDR = 0x14
sysIP_MINTTL = 0x15
sysIP_NODEFRAG = 0x16
sysIP_UNICAST_IF = 0x32
sysIP_MULTICAST_IF = 0x20
sysIP_MULTICAST_TTL = 0x21
sysIP_MULTICAST_LOOP = 0x22
sysIP_ADD_MEMBERSHIP = 0x23
sysIP_DROP_MEMBERSHIP = 0x24
sysIP_UNBLOCK_SOURCE = 0x25
sysIP_BLOCK_SOURCE = 0x26
sysIP_ADD_SOURCE_MEMBERSHIP = 0x27
sysIP_DROP_SOURCE_MEMBERSHIP = 0x28
sysIP_MSFILTER = 0x29
sysMCAST_JOIN_GROUP = 0x2a
sysMCAST_LEAVE_GROUP = 0x2d
sysMCAST_JOIN_SOURCE_GROUP = 0x2e
sysMCAST_LEAVE_SOURCE_GROUP = 0x2f
sysMCAST_BLOCK_SOURCE = 0x2b
sysMCAST_UNBLOCK_SOURCE = 0x2c
sysMCAST_MSFILTER = 0x30
sysIP_MULTICAST_ALL = 0x31
sysICMP_FILTER = 0x1
sysSO_EE_ORIGIN_NONE = 0x0
sysSO_EE_ORIGIN_LOCAL = 0x1
sysSO_EE_ORIGIN_ICMP = 0x2
sysSO_EE_ORIGIN_ICMP6 = 0x3
sysSO_EE_ORIGIN_TXSTATUS = 0x4
sysSO_EE_ORIGIN_TIMESTAMPING = 0x4
sizeofKernelSockaddrStorage = 0x80 sizeofKernelSockaddrStorage = 0x80
sizeofSockaddrInet = 0x10 sizeofSockaddrInet = 0x10

View File

@@ -4,56 +4,7 @@
package ipv4 package ipv4
const ( const (
sysIP_TOS = 0x1 sysIP_RECVTTL = 0xc
sysIP_TTL = 0x2
sysIP_HDRINCL = 0x3
sysIP_OPTIONS = 0x4
sysIP_ROUTER_ALERT = 0x5
sysIP_RECVOPTS = 0x6
sysIP_RETOPTS = 0x7
sysIP_PKTINFO = 0x8
sysIP_PKTOPTIONS = 0x9
sysIP_MTU_DISCOVER = 0xa
sysIP_RECVERR = 0xb
sysIP_RECVTTL = 0xc
sysIP_RECVTOS = 0xd
sysIP_MTU = 0xe
sysIP_FREEBIND = 0xf
sysIP_TRANSPARENT = 0x13
sysIP_RECVRETOPTS = 0x7
sysIP_ORIGDSTADDR = 0x14
sysIP_RECVORIGDSTADDR = 0x14
sysIP_MINTTL = 0x15
sysIP_NODEFRAG = 0x16
sysIP_UNICAST_IF = 0x32
sysIP_MULTICAST_IF = 0x20
sysIP_MULTICAST_TTL = 0x21
sysIP_MULTICAST_LOOP = 0x22
sysIP_ADD_MEMBERSHIP = 0x23
sysIP_DROP_MEMBERSHIP = 0x24
sysIP_UNBLOCK_SOURCE = 0x25
sysIP_BLOCK_SOURCE = 0x26
sysIP_ADD_SOURCE_MEMBERSHIP = 0x27
sysIP_DROP_SOURCE_MEMBERSHIP = 0x28
sysIP_MSFILTER = 0x29
sysMCAST_JOIN_GROUP = 0x2a
sysMCAST_LEAVE_GROUP = 0x2d
sysMCAST_JOIN_SOURCE_GROUP = 0x2e
sysMCAST_LEAVE_SOURCE_GROUP = 0x2f
sysMCAST_BLOCK_SOURCE = 0x2b
sysMCAST_UNBLOCK_SOURCE = 0x2c
sysMCAST_MSFILTER = 0x30
sysIP_MULTICAST_ALL = 0x31
sysICMP_FILTER = 0x1
sysSO_EE_ORIGIN_NONE = 0x0
sysSO_EE_ORIGIN_LOCAL = 0x1
sysSO_EE_ORIGIN_ICMP = 0x2
sysSO_EE_ORIGIN_ICMP6 = 0x3
sysSO_EE_ORIGIN_TXSTATUS = 0x4
sysSO_EE_ORIGIN_TIMESTAMPING = 0x4
sizeofKernelSockaddrStorage = 0x80 sizeofKernelSockaddrStorage = 0x80
sizeofSockaddrInet = 0x10 sizeofSockaddrInet = 0x10

View File

@@ -4,56 +4,7 @@
package ipv4 package ipv4
const ( const (
sysIP_TOS = 0x1 sysIP_RECVTTL = 0xc
sysIP_TTL = 0x2
sysIP_HDRINCL = 0x3
sysIP_OPTIONS = 0x4
sysIP_ROUTER_ALERT = 0x5
sysIP_RECVOPTS = 0x6
sysIP_RETOPTS = 0x7
sysIP_PKTINFO = 0x8
sysIP_PKTOPTIONS = 0x9
sysIP_MTU_DISCOVER = 0xa
sysIP_RECVERR = 0xb
sysIP_RECVTTL = 0xc
sysIP_RECVTOS = 0xd
sysIP_MTU = 0xe
sysIP_FREEBIND = 0xf
sysIP_TRANSPARENT = 0x13
sysIP_RECVRETOPTS = 0x7
sysIP_ORIGDSTADDR = 0x14
sysIP_RECVORIGDSTADDR = 0x14
sysIP_MINTTL = 0x15
sysIP_NODEFRAG = 0x16
sysIP_UNICAST_IF = 0x32
sysIP_MULTICAST_IF = 0x20
sysIP_MULTICAST_TTL = 0x21
sysIP_MULTICAST_LOOP = 0x22
sysIP_ADD_MEMBERSHIP = 0x23
sysIP_DROP_MEMBERSHIP = 0x24
sysIP_UNBLOCK_SOURCE = 0x25
sysIP_BLOCK_SOURCE = 0x26
sysIP_ADD_SOURCE_MEMBERSHIP = 0x27
sysIP_DROP_SOURCE_MEMBERSHIP = 0x28
sysIP_MSFILTER = 0x29
sysMCAST_JOIN_GROUP = 0x2a
sysMCAST_LEAVE_GROUP = 0x2d
sysMCAST_JOIN_SOURCE_GROUP = 0x2e
sysMCAST_LEAVE_SOURCE_GROUP = 0x2f
sysMCAST_BLOCK_SOURCE = 0x2b
sysMCAST_UNBLOCK_SOURCE = 0x2c
sysMCAST_MSFILTER = 0x30
sysIP_MULTICAST_ALL = 0x31
sysICMP_FILTER = 0x1
sysSO_EE_ORIGIN_NONE = 0x0
sysSO_EE_ORIGIN_LOCAL = 0x1
sysSO_EE_ORIGIN_ICMP = 0x2
sysSO_EE_ORIGIN_ICMP6 = 0x3
sysSO_EE_ORIGIN_TXSTATUS = 0x4
sysSO_EE_ORIGIN_TIMESTAMPING = 0x4
sizeofKernelSockaddrStorage = 0x80 sizeofKernelSockaddrStorage = 0x80
sizeofSockaddrInet = 0x10 sizeofSockaddrInet = 0x10

View File

@@ -4,56 +4,7 @@
package ipv4 package ipv4
const ( const (
sysIP_TOS = 0x1 sysIP_RECVTTL = 0xc
sysIP_TTL = 0x2
sysIP_HDRINCL = 0x3
sysIP_OPTIONS = 0x4
sysIP_ROUTER_ALERT = 0x5
sysIP_RECVOPTS = 0x6
sysIP_RETOPTS = 0x7
sysIP_PKTINFO = 0x8
sysIP_PKTOPTIONS = 0x9
sysIP_MTU_DISCOVER = 0xa
sysIP_RECVERR = 0xb
sysIP_RECVTTL = 0xc
sysIP_RECVTOS = 0xd
sysIP_MTU = 0xe
sysIP_FREEBIND = 0xf
sysIP_TRANSPARENT = 0x13
sysIP_RECVRETOPTS = 0x7
sysIP_ORIGDSTADDR = 0x14
sysIP_RECVORIGDSTADDR = 0x14
sysIP_MINTTL = 0x15
sysIP_NODEFRAG = 0x16
sysIP_UNICAST_IF = 0x32
sysIP_MULTICAST_IF = 0x20
sysIP_MULTICAST_TTL = 0x21
sysIP_MULTICAST_LOOP = 0x22
sysIP_ADD_MEMBERSHIP = 0x23
sysIP_DROP_MEMBERSHIP = 0x24
sysIP_UNBLOCK_SOURCE = 0x25
sysIP_BLOCK_SOURCE = 0x26
sysIP_ADD_SOURCE_MEMBERSHIP = 0x27
sysIP_DROP_SOURCE_MEMBERSHIP = 0x28
sysIP_MSFILTER = 0x29
sysMCAST_JOIN_GROUP = 0x2a
sysMCAST_LEAVE_GROUP = 0x2d
sysMCAST_JOIN_SOURCE_GROUP = 0x2e
sysMCAST_LEAVE_SOURCE_GROUP = 0x2f
sysMCAST_BLOCK_SOURCE = 0x2b
sysMCAST_UNBLOCK_SOURCE = 0x2c
sysMCAST_MSFILTER = 0x30
sysIP_MULTICAST_ALL = 0x31
sysICMP_FILTER = 0x1
sysSO_EE_ORIGIN_NONE = 0x0
sysSO_EE_ORIGIN_LOCAL = 0x1
sysSO_EE_ORIGIN_ICMP = 0x2
sysSO_EE_ORIGIN_ICMP6 = 0x3
sysSO_EE_ORIGIN_TXSTATUS = 0x4
sysSO_EE_ORIGIN_TIMESTAMPING = 0x4
sizeofKernelSockaddrStorage = 0x80 sizeofKernelSockaddrStorage = 0x80
sizeofSockaddrInet = 0x10 sizeofSockaddrInet = 0x10

View File

@@ -4,56 +4,7 @@
package ipv4 package ipv4
const ( const (
sysIP_TOS = 0x1 sysIP_RECVTTL = 0xc
sysIP_TTL = 0x2
sysIP_HDRINCL = 0x3
sysIP_OPTIONS = 0x4
sysIP_ROUTER_ALERT = 0x5
sysIP_RECVOPTS = 0x6
sysIP_RETOPTS = 0x7
sysIP_PKTINFO = 0x8
sysIP_PKTOPTIONS = 0x9
sysIP_MTU_DISCOVER = 0xa
sysIP_RECVERR = 0xb
sysIP_RECVTTL = 0xc
sysIP_RECVTOS = 0xd
sysIP_MTU = 0xe
sysIP_FREEBIND = 0xf
sysIP_TRANSPARENT = 0x13
sysIP_RECVRETOPTS = 0x7
sysIP_ORIGDSTADDR = 0x14
sysIP_RECVORIGDSTADDR = 0x14
sysIP_MINTTL = 0x15
sysIP_NODEFRAG = 0x16
sysIP_UNICAST_IF = 0x32
sysIP_MULTICAST_IF = 0x20
sysIP_MULTICAST_TTL = 0x21
sysIP_MULTICAST_LOOP = 0x22
sysIP_ADD_MEMBERSHIP = 0x23
sysIP_DROP_MEMBERSHIP = 0x24
sysIP_UNBLOCK_SOURCE = 0x25
sysIP_BLOCK_SOURCE = 0x26
sysIP_ADD_SOURCE_MEMBERSHIP = 0x27
sysIP_DROP_SOURCE_MEMBERSHIP = 0x28
sysIP_MSFILTER = 0x29
sysMCAST_JOIN_GROUP = 0x2a
sysMCAST_LEAVE_GROUP = 0x2d
sysMCAST_JOIN_SOURCE_GROUP = 0x2e
sysMCAST_LEAVE_SOURCE_GROUP = 0x2f
sysMCAST_BLOCK_SOURCE = 0x2b
sysMCAST_UNBLOCK_SOURCE = 0x2c
sysMCAST_MSFILTER = 0x30
sysIP_MULTICAST_ALL = 0x31
sysICMP_FILTER = 0x1
sysSO_EE_ORIGIN_NONE = 0x0
sysSO_EE_ORIGIN_LOCAL = 0x1
sysSO_EE_ORIGIN_ICMP = 0x2
sysSO_EE_ORIGIN_ICMP6 = 0x3
sysSO_EE_ORIGIN_TXSTATUS = 0x4
sysSO_EE_ORIGIN_TIMESTAMPING = 0x4
sizeofKernelSockaddrStorage = 0x80 sizeofKernelSockaddrStorage = 0x80
sizeofSockaddrInet = 0x10 sizeofSockaddrInet = 0x10

View File

@@ -4,56 +4,7 @@
package ipv4 package ipv4
const ( const (
sysIP_TOS = 0x1 sysIP_RECVTTL = 0xc
sysIP_TTL = 0x2
sysIP_HDRINCL = 0x3
sysIP_OPTIONS = 0x4
sysIP_ROUTER_ALERT = 0x5
sysIP_RECVOPTS = 0x6
sysIP_RETOPTS = 0x7
sysIP_PKTINFO = 0x8
sysIP_PKTOPTIONS = 0x9
sysIP_MTU_DISCOVER = 0xa
sysIP_RECVERR = 0xb
sysIP_RECVTTL = 0xc
sysIP_RECVTOS = 0xd
sysIP_MTU = 0xe
sysIP_FREEBIND = 0xf
sysIP_TRANSPARENT = 0x13
sysIP_RECVRETOPTS = 0x7
sysIP_ORIGDSTADDR = 0x14
sysIP_RECVORIGDSTADDR = 0x14
sysIP_MINTTL = 0x15
sysIP_NODEFRAG = 0x16
sysIP_UNICAST_IF = 0x32
sysIP_MULTICAST_IF = 0x20
sysIP_MULTICAST_TTL = 0x21
sysIP_MULTICAST_LOOP = 0x22
sysIP_ADD_MEMBERSHIP = 0x23
sysIP_DROP_MEMBERSHIP = 0x24
sysIP_UNBLOCK_SOURCE = 0x25
sysIP_BLOCK_SOURCE = 0x26
sysIP_ADD_SOURCE_MEMBERSHIP = 0x27
sysIP_DROP_SOURCE_MEMBERSHIP = 0x28
sysIP_MSFILTER = 0x29
sysMCAST_JOIN_GROUP = 0x2a
sysMCAST_LEAVE_GROUP = 0x2d
sysMCAST_JOIN_SOURCE_GROUP = 0x2e
sysMCAST_LEAVE_SOURCE_GROUP = 0x2f
sysMCAST_BLOCK_SOURCE = 0x2b
sysMCAST_UNBLOCK_SOURCE = 0x2c
sysMCAST_MSFILTER = 0x30
sysIP_MULTICAST_ALL = 0x31
sysICMP_FILTER = 0x1
sysSO_EE_ORIGIN_NONE = 0x0
sysSO_EE_ORIGIN_LOCAL = 0x1
sysSO_EE_ORIGIN_ICMP = 0x2
sysSO_EE_ORIGIN_ICMP6 = 0x3
sysSO_EE_ORIGIN_TXSTATUS = 0x4
sysSO_EE_ORIGIN_TIMESTAMPING = 0x4
sizeofKernelSockaddrStorage = 0x80 sizeofKernelSockaddrStorage = 0x80
sizeofSockaddrInet = 0x10 sizeofSockaddrInet = 0x10

View File

@@ -4,56 +4,7 @@
package ipv4 package ipv4
const ( const (
sysIP_TOS = 0x1 sysIP_RECVTTL = 0xc
sysIP_TTL = 0x2
sysIP_HDRINCL = 0x3
sysIP_OPTIONS = 0x4
sysIP_ROUTER_ALERT = 0x5
sysIP_RECVOPTS = 0x6
sysIP_RETOPTS = 0x7
sysIP_PKTINFO = 0x8
sysIP_PKTOPTIONS = 0x9
sysIP_MTU_DISCOVER = 0xa
sysIP_RECVERR = 0xb
sysIP_RECVTTL = 0xc
sysIP_RECVTOS = 0xd
sysIP_MTU = 0xe
sysIP_FREEBIND = 0xf
sysIP_TRANSPARENT = 0x13
sysIP_RECVRETOPTS = 0x7
sysIP_ORIGDSTADDR = 0x14
sysIP_RECVORIGDSTADDR = 0x14
sysIP_MINTTL = 0x15
sysIP_NODEFRAG = 0x16
sysIP_UNICAST_IF = 0x32
sysIP_MULTICAST_IF = 0x20
sysIP_MULTICAST_TTL = 0x21
sysIP_MULTICAST_LOOP = 0x22
sysIP_ADD_MEMBERSHIP = 0x23
sysIP_DROP_MEMBERSHIP = 0x24
sysIP_UNBLOCK_SOURCE = 0x25
sysIP_BLOCK_SOURCE = 0x26
sysIP_ADD_SOURCE_MEMBERSHIP = 0x27
sysIP_DROP_SOURCE_MEMBERSHIP = 0x28
sysIP_MSFILTER = 0x29
sysMCAST_JOIN_GROUP = 0x2a
sysMCAST_LEAVE_GROUP = 0x2d
sysMCAST_JOIN_SOURCE_GROUP = 0x2e
sysMCAST_LEAVE_SOURCE_GROUP = 0x2f
sysMCAST_BLOCK_SOURCE = 0x2b
sysMCAST_UNBLOCK_SOURCE = 0x2c
sysMCAST_MSFILTER = 0x30
sysIP_MULTICAST_ALL = 0x31
sysICMP_FILTER = 0x1
sysSO_EE_ORIGIN_NONE = 0x0
sysSO_EE_ORIGIN_LOCAL = 0x1
sysSO_EE_ORIGIN_ICMP = 0x2
sysSO_EE_ORIGIN_ICMP6 = 0x3
sysSO_EE_ORIGIN_TXSTATUS = 0x4
sysSO_EE_ORIGIN_TIMESTAMPING = 0x4
sizeofKernelSockaddrStorage = 0x80 sizeofKernelSockaddrStorage = 0x80
sizeofSockaddrInet = 0x10 sizeofSockaddrInet = 0x10

View File

@@ -4,56 +4,7 @@
package ipv4 package ipv4
const ( const (
sysIP_TOS = 0x1 sysIP_RECVTTL = 0xc
sysIP_TTL = 0x2
sysIP_HDRINCL = 0x3
sysIP_OPTIONS = 0x4
sysIP_ROUTER_ALERT = 0x5
sysIP_RECVOPTS = 0x6
sysIP_RETOPTS = 0x7
sysIP_PKTINFO = 0x8
sysIP_PKTOPTIONS = 0x9
sysIP_MTU_DISCOVER = 0xa
sysIP_RECVERR = 0xb
sysIP_RECVTTL = 0xc
sysIP_RECVTOS = 0xd
sysIP_MTU = 0xe
sysIP_FREEBIND = 0xf
sysIP_TRANSPARENT = 0x13
sysIP_RECVRETOPTS = 0x7
sysIP_ORIGDSTADDR = 0x14
sysIP_RECVORIGDSTADDR = 0x14
sysIP_MINTTL = 0x15
sysIP_NODEFRAG = 0x16
sysIP_UNICAST_IF = 0x32
sysIP_MULTICAST_IF = 0x20
sysIP_MULTICAST_TTL = 0x21
sysIP_MULTICAST_LOOP = 0x22
sysIP_ADD_MEMBERSHIP = 0x23
sysIP_DROP_MEMBERSHIP = 0x24
sysIP_UNBLOCK_SOURCE = 0x25
sysIP_BLOCK_SOURCE = 0x26
sysIP_ADD_SOURCE_MEMBERSHIP = 0x27
sysIP_DROP_SOURCE_MEMBERSHIP = 0x28
sysIP_MSFILTER = 0x29
sysMCAST_JOIN_GROUP = 0x2a
sysMCAST_LEAVE_GROUP = 0x2d
sysMCAST_JOIN_SOURCE_GROUP = 0x2e
sysMCAST_LEAVE_SOURCE_GROUP = 0x2f
sysMCAST_BLOCK_SOURCE = 0x2b
sysMCAST_UNBLOCK_SOURCE = 0x2c
sysMCAST_MSFILTER = 0x30
sysIP_MULTICAST_ALL = 0x31
sysICMP_FILTER = 0x1
sysSO_EE_ORIGIN_NONE = 0x0
sysSO_EE_ORIGIN_LOCAL = 0x1
sysSO_EE_ORIGIN_ICMP = 0x2
sysSO_EE_ORIGIN_ICMP6 = 0x3
sysSO_EE_ORIGIN_TXSTATUS = 0x4
sysSO_EE_ORIGIN_TIMESTAMPING = 0x4
sizeofKernelSockaddrStorage = 0x80 sizeofKernelSockaddrStorage = 0x80
sizeofSockaddrInet = 0x10 sizeofSockaddrInet = 0x10

View File

@@ -4,56 +4,7 @@
package ipv4 package ipv4
const ( const (
sysIP_TOS = 0x1 sysIP_RECVTTL = 0xc
sysIP_TTL = 0x2
sysIP_HDRINCL = 0x3
sysIP_OPTIONS = 0x4
sysIP_ROUTER_ALERT = 0x5
sysIP_RECVOPTS = 0x6
sysIP_RETOPTS = 0x7
sysIP_PKTINFO = 0x8
sysIP_PKTOPTIONS = 0x9
sysIP_MTU_DISCOVER = 0xa
sysIP_RECVERR = 0xb
sysIP_RECVTTL = 0xc
sysIP_RECVTOS = 0xd
sysIP_MTU = 0xe
sysIP_FREEBIND = 0xf
sysIP_TRANSPARENT = 0x13
sysIP_RECVRETOPTS = 0x7
sysIP_ORIGDSTADDR = 0x14
sysIP_RECVORIGDSTADDR = 0x14
sysIP_MINTTL = 0x15
sysIP_NODEFRAG = 0x16
sysIP_UNICAST_IF = 0x32
sysIP_MULTICAST_IF = 0x20
sysIP_MULTICAST_TTL = 0x21
sysIP_MULTICAST_LOOP = 0x22
sysIP_ADD_MEMBERSHIP = 0x23
sysIP_DROP_MEMBERSHIP = 0x24
sysIP_UNBLOCK_SOURCE = 0x25
sysIP_BLOCK_SOURCE = 0x26
sysIP_ADD_SOURCE_MEMBERSHIP = 0x27
sysIP_DROP_SOURCE_MEMBERSHIP = 0x28
sysIP_MSFILTER = 0x29
sysMCAST_JOIN_GROUP = 0x2a
sysMCAST_LEAVE_GROUP = 0x2d
sysMCAST_JOIN_SOURCE_GROUP = 0x2e
sysMCAST_LEAVE_SOURCE_GROUP = 0x2f
sysMCAST_BLOCK_SOURCE = 0x2b
sysMCAST_UNBLOCK_SOURCE = 0x2c
sysMCAST_MSFILTER = 0x30
sysIP_MULTICAST_ALL = 0x31
sysICMP_FILTER = 0x1
sysSO_EE_ORIGIN_NONE = 0x0
sysSO_EE_ORIGIN_LOCAL = 0x1
sysSO_EE_ORIGIN_ICMP = 0x2
sysSO_EE_ORIGIN_ICMP6 = 0x3
sysSO_EE_ORIGIN_TXSTATUS = 0x4
sysSO_EE_ORIGIN_TIMESTAMPING = 0x4
sizeofKernelSockaddrStorage = 0x80 sizeofKernelSockaddrStorage = 0x80
sizeofSockaddrInet = 0x10 sizeofSockaddrInet = 0x10

View File

@@ -4,56 +4,7 @@
package ipv4 package ipv4
const ( const (
sysIP_TOS = 0x1 sysIP_RECVTTL = 0xc
sysIP_TTL = 0x2
sysIP_HDRINCL = 0x3
sysIP_OPTIONS = 0x4
sysIP_ROUTER_ALERT = 0x5
sysIP_RECVOPTS = 0x6
sysIP_RETOPTS = 0x7
sysIP_PKTINFO = 0x8
sysIP_PKTOPTIONS = 0x9
sysIP_MTU_DISCOVER = 0xa
sysIP_RECVERR = 0xb
sysIP_RECVTTL = 0xc
sysIP_RECVTOS = 0xd
sysIP_MTU = 0xe
sysIP_FREEBIND = 0xf
sysIP_TRANSPARENT = 0x13
sysIP_RECVRETOPTS = 0x7
sysIP_ORIGDSTADDR = 0x14
sysIP_RECVORIGDSTADDR = 0x14
sysIP_MINTTL = 0x15
sysIP_NODEFRAG = 0x16
sysIP_UNICAST_IF = 0x32
sysIP_MULTICAST_IF = 0x20
sysIP_MULTICAST_TTL = 0x21
sysIP_MULTICAST_LOOP = 0x22
sysIP_ADD_MEMBERSHIP = 0x23
sysIP_DROP_MEMBERSHIP = 0x24
sysIP_UNBLOCK_SOURCE = 0x25
sysIP_BLOCK_SOURCE = 0x26
sysIP_ADD_SOURCE_MEMBERSHIP = 0x27
sysIP_DROP_SOURCE_MEMBERSHIP = 0x28
sysIP_MSFILTER = 0x29
sysMCAST_JOIN_GROUP = 0x2a
sysMCAST_LEAVE_GROUP = 0x2d
sysMCAST_JOIN_SOURCE_GROUP = 0x2e
sysMCAST_LEAVE_SOURCE_GROUP = 0x2f
sysMCAST_BLOCK_SOURCE = 0x2b
sysMCAST_UNBLOCK_SOURCE = 0x2c
sysMCAST_MSFILTER = 0x30
sysIP_MULTICAST_ALL = 0x31
sysICMP_FILTER = 0x1
sysSO_EE_ORIGIN_NONE = 0x0
sysSO_EE_ORIGIN_LOCAL = 0x1
sysSO_EE_ORIGIN_ICMP = 0x2
sysSO_EE_ORIGIN_ICMP6 = 0x3
sysSO_EE_ORIGIN_TXSTATUS = 0x4
sysSO_EE_ORIGIN_TIMESTAMPING = 0x4
sizeofKernelSockaddrStorage = 0x80 sizeofKernelSockaddrStorage = 0x80
sizeofSockaddrInet = 0x10 sizeofSockaddrInet = 0x10

View File

@@ -7,56 +7,7 @@
package ipv4 package ipv4
const ( const (
sysIP_TOS = 0x1 sysIP_RECVTTL = 0xc
sysIP_TTL = 0x2
sysIP_HDRINCL = 0x3
sysIP_OPTIONS = 0x4
sysIP_ROUTER_ALERT = 0x5
sysIP_RECVOPTS = 0x6
sysIP_RETOPTS = 0x7
sysIP_PKTINFO = 0x8
sysIP_PKTOPTIONS = 0x9
sysIP_MTU_DISCOVER = 0xa
sysIP_RECVERR = 0xb
sysIP_RECVTTL = 0xc
sysIP_RECVTOS = 0xd
sysIP_MTU = 0xe
sysIP_FREEBIND = 0xf
sysIP_TRANSPARENT = 0x13
sysIP_RECVRETOPTS = 0x7
sysIP_ORIGDSTADDR = 0x14
sysIP_RECVORIGDSTADDR = 0x14
sysIP_MINTTL = 0x15
sysIP_NODEFRAG = 0x16
sysIP_UNICAST_IF = 0x32
sysIP_MULTICAST_IF = 0x20
sysIP_MULTICAST_TTL = 0x21
sysIP_MULTICAST_LOOP = 0x22
sysIP_ADD_MEMBERSHIP = 0x23
sysIP_DROP_MEMBERSHIP = 0x24
sysIP_UNBLOCK_SOURCE = 0x25
sysIP_BLOCK_SOURCE = 0x26
sysIP_ADD_SOURCE_MEMBERSHIP = 0x27
sysIP_DROP_SOURCE_MEMBERSHIP = 0x28
sysIP_MSFILTER = 0x29
sysMCAST_JOIN_GROUP = 0x2a
sysMCAST_LEAVE_GROUP = 0x2d
sysMCAST_JOIN_SOURCE_GROUP = 0x2e
sysMCAST_LEAVE_SOURCE_GROUP = 0x2f
sysMCAST_BLOCK_SOURCE = 0x2b
sysMCAST_UNBLOCK_SOURCE = 0x2c
sysMCAST_MSFILTER = 0x30
sysIP_MULTICAST_ALL = 0x31
sysICMP_FILTER = 0x1
sysSO_EE_ORIGIN_NONE = 0x0
sysSO_EE_ORIGIN_LOCAL = 0x1
sysSO_EE_ORIGIN_ICMP = 0x2
sysSO_EE_ORIGIN_ICMP6 = 0x3
sysSO_EE_ORIGIN_TXSTATUS = 0x4
sysSO_EE_ORIGIN_TIMESTAMPING = 0x4
sizeofKernelSockaddrStorage = 0x80 sizeofKernelSockaddrStorage = 0x80
sizeofSockaddrInet = 0x10 sizeofSockaddrInet = 0x10

View File

@@ -4,56 +4,7 @@
package ipv4 package ipv4
const ( const (
sysIP_TOS = 0x1 sysIP_RECVTTL = 0xc
sysIP_TTL = 0x2
sysIP_HDRINCL = 0x3
sysIP_OPTIONS = 0x4
sysIP_ROUTER_ALERT = 0x5
sysIP_RECVOPTS = 0x6
sysIP_RETOPTS = 0x7
sysIP_PKTINFO = 0x8
sysIP_PKTOPTIONS = 0x9
sysIP_MTU_DISCOVER = 0xa
sysIP_RECVERR = 0xb
sysIP_RECVTTL = 0xc
sysIP_RECVTOS = 0xd
sysIP_MTU = 0xe
sysIP_FREEBIND = 0xf
sysIP_TRANSPARENT = 0x13
sysIP_RECVRETOPTS = 0x7
sysIP_ORIGDSTADDR = 0x14
sysIP_RECVORIGDSTADDR = 0x14
sysIP_MINTTL = 0x15
sysIP_NODEFRAG = 0x16
sysIP_UNICAST_IF = 0x32
sysIP_MULTICAST_IF = 0x20
sysIP_MULTICAST_TTL = 0x21
sysIP_MULTICAST_LOOP = 0x22
sysIP_ADD_MEMBERSHIP = 0x23
sysIP_DROP_MEMBERSHIP = 0x24
sysIP_UNBLOCK_SOURCE = 0x25
sysIP_BLOCK_SOURCE = 0x26
sysIP_ADD_SOURCE_MEMBERSHIP = 0x27
sysIP_DROP_SOURCE_MEMBERSHIP = 0x28
sysIP_MSFILTER = 0x29
sysMCAST_JOIN_GROUP = 0x2a
sysMCAST_LEAVE_GROUP = 0x2d
sysMCAST_JOIN_SOURCE_GROUP = 0x2e
sysMCAST_LEAVE_SOURCE_GROUP = 0x2f
sysMCAST_BLOCK_SOURCE = 0x2b
sysMCAST_UNBLOCK_SOURCE = 0x2c
sysMCAST_MSFILTER = 0x30
sysIP_MULTICAST_ALL = 0x31
sysICMP_FILTER = 0x1
sysSO_EE_ORIGIN_NONE = 0x0
sysSO_EE_ORIGIN_LOCAL = 0x1
sysSO_EE_ORIGIN_ICMP = 0x2
sysSO_EE_ORIGIN_ICMP6 = 0x3
sysSO_EE_ORIGIN_TXSTATUS = 0x4
sysSO_EE_ORIGIN_TIMESTAMPING = 0x4
sizeofKernelSockaddrStorage = 0x80 sizeofKernelSockaddrStorage = 0x80
sizeofSockaddrInet = 0x10 sizeofSockaddrInet = 0x10

View File

@@ -4,23 +4,10 @@
package ipv4 package ipv4
const ( const (
sysIP_OPTIONS = 0x1
sysIP_HDRINCL = 0x2
sysIP_TOS = 0x3
sysIP_TTL = 0x4
sysIP_RECVOPTS = 0x5
sysIP_RECVRETOPTS = 0x6
sysIP_RECVDSTADDR = 0x7 sysIP_RECVDSTADDR = 0x7
sysIP_RETOPTS = 0x8
sysIP_RECVIF = 0x14 sysIP_RECVIF = 0x14
sysIP_RECVTTL = 0x17 sysIP_RECVTTL = 0x17
sysIP_MULTICAST_IF = 0x9
sysIP_MULTICAST_TTL = 0xa
sysIP_MULTICAST_LOOP = 0xb
sysIP_ADD_MEMBERSHIP = 0xc
sysIP_DROP_MEMBERSHIP = 0xd
sizeofIPMreq = 0x8 sizeofIPMreq = 0x8
) )

Some files were not shown because too many files have changed in this diff Show More