<commit_before>package routetests

var routeTests = map[string][]string{
	// User
	"/user/:nick": {
		"/+Akyoto",
	},

	// "/user/:nick/characters/liked": []string{
	// 	"/+Akyoto/characters/liked",
	// },

	// "/user/:nick/forum/threads": []string{
	// 	"/+Akyoto/forum/threads",
	// },

	// "/user/:nick/forum/posts": []string{
	// 	"/+Akyoto/forum/posts",
	// },

	// "/user/:nick/soundtracks/added": []string{
	// 	"/+Akyoto/soundtracks/added",
	// },

	// "/user/:nick/soundtracks/added/from/:index": []string{
	// 	"/+Akyoto/soundtracks/added/from/3",
	// },

	// "/user/:nick/soundtracks/liked": []string{
	// 	"/+Akyoto/soundtracks/liked",
	// },

	// "/user/:nick/soundtracks/liked/from/:index": []string{
	// 	"/+Akyoto/soundtracks/liked/from/3",
	// },

	// "/user/:nick/quotes/added": []string{
	// 	"/+Scott/quotes/added",
	// },

	// "/user/:nick/quotes/added/from/:index": []string{
	// 	"/+Scott/quotes/added/from/3",
	// },

	// "/user/:nick/quotes/liked": []string{
	// 	"/+Scott/quotes/liked",
	// },

	// "/user/:nick/quotes/liked/from/:index": []string{
	// 	"/+Scott/quotes/liked/from/3",
	// },

	// "/user/:nick/followers": []string{
	// 	"/+Akyoto/followers",
	// },

	// "/user/:nick/stats": []string{
	// 	"/+Akyoto/stats",
	// },

	"/user/:nick/animelist/anime/:id": {
		"/+Akyoto/animelist/anime/74y2cFiiR",
	},

	"/user/:nick/animelist/watching": {
		"/+Akyoto/animelist/watching",
	},

	"/user/:nick/animelist/watching/from/:index": {
		"/+Akyoto/animelist/watching/from/1",
	},

	"/user/:nick/animelist/completed": {
		"/+Akyoto/animelist/completed",
	},

	"/user/:nick/animelist/completed/from/:index": {
		"/+Akyoto/animelist/completed/from/3",
	},

	"/user/:nick/animelist/planned": {
		"/+Akyoto/animelist/planned",
	},

	"/user/:nick/animelist/planned/from/:index": {
		"/+Akyoto/animelist/planned/from/3",
	},

	"/user/:nick/animelist/hold": {
		"/+Akyoto/animelist/hold",
	},

	"/user/:nick/animelist/hold/from/:index": {
		"/+Akyoto/animelist/hold/from/3",
	},

	"/user/:nick/animelist/dropped": {
		"/+Akyoto/animelist/dropped",
	},

	"/user/:nick/animelist/dropped/from/:index": {
		"/+Akyoto/animelist/dropped/from/3",
	},

	"/user/:nick/anime/recommended": {
		"/+Akyoto/anime/recommended",
	},

	"/user/:nick/anime/sequels": {
		"/+Akyoto/anime/sequels",
	},

	"/users/country/:country": {
		"/users/country/japan",
	},

	// Pages
	"/anime/:id": {
		"/anime/74y2cFiiR",
	},

	"/anime/:id/characters": {
		"/anime/74y2cFiiR/characters",
	},

	"/anime/:id/episodes": {
		"/anime/74y2cFiiR/episodes",
	},

	"/anime/:id/comments": {
		"/anime/74y2cFiiR/comments",
	},

	"/anime/:id/tracks": {
		"/anime/74y2cFiiR/tracks",
	},

	"/anime/:id/relations": {
		"/anime/74y2cFiiR/relations",
	},

	"/thread/:id": {
		"/thread/HJgS7c2K",
	},

	"/post/:id": {
		"/post/B1RzshnK",
	},

	"/forum/:tag": {
		"/forum/general",
	},

	"/genre/:name": {
		"/genre/action",
	},

	"/company/:id": {
		"/company/xCAUr7UkRaz",
	},

	"/company/:id/history": {
		"/company/xCAUr7UkRaz/history",
	},

	"/companies/from/:index": {
		"/companies/from/3",
	},

	"/explore/color/:color/anime": {
		"/explore/color/hsl:0.050,0.25,0.5/anime",
	},

	"/explore/color/:color/anime/from/:index": {
		"/explore/color/hsl:0.050,0.25,0.5/anime/from/3",
	},

	"/search/:term": {
		"/search/Dragon Ball",
	},

	"/quote/:id": {
		"/quote/gUZugd6zR",
	},

	"/quote/:id/edit": {
		"/quote/gUZugd6zR/edit",
	},

	"/quote/:id/history": {
		"/quote/gUZugd6zR/history",
	},

	"/quotes/from/:index": {
		"/quotes/from/2",
	},

	"/quotes/best/from/:index": {
		"/quotes/best/from/2",
	},

	"/soundtrack/:id": {
		"/soundtrack/h0ac8sKkg",
	},

	"/soundtrack/:id/lyrics": {
		"/soundtrack/vS64GbpzR/lyrics",
	},

	"/soundtrack/:id/edit": {
		"/soundtrack/h0ac8sKkg/edit",
	},

	"/soundtrack/:id/history": {
		"/soundtrack/h0ac8sKkg/history",
	},

	"/soundtracks": {
		"/soundtracks",
	},

	"/soundtracks/from/:index": {
		"/soundtracks/from/12",
	},

	"/soundtracks/best": {
		"/soundtracks/best",
	},

	"/soundtracks/best/from/:index": {
		"/soundtracks/best/from/12",
	},

	"/soundtracks/tag/:tag": {
		"/soundtracks/tag/moe",
	},

	"/soundtracks/tag/:tag/from/:index": {
		"/soundtracks/tag/moe/from/3",
	},

	"/character/:id": {
		"/character/dfrNQrmmg-",
	},

	"/episode/:id": {
		"/episode/oFlqThKWga",
	},

	// "/kitsu/character/:id": []string{
	// 	"/kitsu/character/6556",
	// },

	// "/mal/character/:id": []string{
	// 	"/mal/character/498",
	// },

	"/compare/animelist/:nick-1/:nick-2": {
		"/compare/animelist/Akyoto/Scott",
	},

	"/explore/anime/:year/:season/:status/:type": {
		"/explore/anime/2011/any/finished/tv",
	},

	// AMV
	"/amv/:id": {
		"/amv/07scvSWmg",
	},

	"/amv/:id/edit": {
		"/amv/07scvSWmg/edit",
	},

	"/amv/:id/history": {
		"/amv/07scvSWmg/history",
	},

	// AMVs
	"/amvs/from/:index": {
		"/amvs/from/3",
	},

	"/amvs/best/from/:index": {
		"/amvs/best/from/3",
	},

	// Redirects
	"/mal/anime/:id": {
		"/mal/anime/33352",
	},

	"/kitsu/anime/:id": {
		"/kitsu/anime/12230",
	},

	"/anilist/anime/:id": {
		"/anilist/anime/21827",
	},

	// API
	"/api/anime/:id": {
		"/api/anime/74y2cFiiR",
	},

	"/api/thread/:id": {
		"/api/thread/HJgS7c2K",
	},

	"/api/post/:id": {
		"/api/post/B1RzshnK",
	},

	"/api/animelist/:id": {
		"/api/animelist/4J6qpK1ve",
	},

	"/api/settings/:id": {
		"/api/settings/4J6qpK1ve",
	},

	"/api/user/:id": {
		"/api/user/4J6qpK1ve",
	},

	"/api/googletouser/:id": {
		"/api/googletouser/106530160120373282283",
	},

	"/api/nicktouser/:id": {
		"/api/nicktouser/Akyoto",
	},

	"/api/soundtrack/:id": {
		"/api/soundtrack/h0ac8sKkg",
	},

	"/api/userfollows/:id": {
		"/api/userfollows/4J6qpK1ve",
	},

	"/api/animecharacters/:id": {
		"/api/animecharacters/74y2cFiiR",
	},

	"/api/animerelations/:id": {
		"/api/animerelations/74y2cFiiR",
	},

	"/api/amv/:id": {
		"/api/amv/07scvSWmg",
	},

	"/api/character/:id": {
		"/api/character/dfrNQrmmg-",
	},

	"/api/company/:id": {
		"/api/company/xCAUr7UkRaz",
	},

	"/api/draftindex/:id": {
		"/api/draftindex/4J6qpK1ve",
	},

	"/api/inventory/:id": {
		"/api/inventory/4J6qpK1ve",
	},

	"/api/shopitem/:id": {
		"/api/shopitem/pro-account-3",
	},

	"/api/notification/:id": {
		"/api/notification/q6Y6eraig",
	},

	"/api/quote/:id": {
		"/api/quote/GXp675zmR",
	},

	"/api/usernotifications/:id": {
		"/api/usernotifications/4J6qpK1ve",
	},

	"/api/pushsubscriptions/:id": {
		"/api/pushsubscriptions/4J6qpK1ve",
	},

	// Images
	"/images/*file": {
		"/images/elements/no-avatar.svg",
	},

	// Extra tests for higher coverage
	"/_/+Akyoto": {
		"/_/+Akyoto",
	},

	"/_/search/dragon": {
		"/_/search/dragon",
	},

	// Disable these tests because they require authorization
	"/auth/google":                                   nil,
	"/auth/google/callback":                          nil,
	"/auth/facebook":                                 nil,
	"/auth/facebook/callback":                        nil,
	"/auth/twitter":                                  nil,
	"/auth/twitter/callback":                         nil,
	"/dashboard":                                     nil,
	"/import":                                        nil,
	"/import/anilist/animelist":                      nil,
	"/import/anilist/animelist/finish":               nil,
	"/import/myanimelist/animelist":                  nil,
	"/import/myanimelist/animelist/finish":           nil,
	"/import/kitsu/animelist":                        nil,
	"/import/kitsu/animelist/finish":                 nil,
	"/animelist/watching":                            nil,
	"/animelist/completed":                           nil,
	"/animelist/planned":                             nil,
	"/animelist/hold":                                nil,
	"/animelist/dropped":                             nil,
	"/notifications":                                 nil,
	"/user/:nick/notifications":                      nil,
	"/user/:nick/edit":                               nil,
	"/user/:nick/log":                                nil,
	"/user/:nick/log/from/:index":                    nil,
	"/editor/soundtracks/file":                       nil,
	"/editor/soundtracks/links":                      nil,
	"/editor/soundtracks/lyrics/missing":             nil,
	"/editor/soundtracks/lyrics/unaligned":           nil,
	"/editor/soundtracks/tags":                       nil,
	"/api/test/notification":                         nil,
	"/api/paypal/payment/create":                     nil,
	"/api/emailtouser/:id":                           nil,
	"/api/userfollows/:id/get/:item":                 nil,
	"/api/userfollows/:id/get/:item/:property":       nil,
	"/api/pushsubscriptions/:id/get/:item":           nil,
	"/api/pushsubscriptions/:id/get/:item/:property": nil,
	"/api/count/notifications/unseen":                nil,
	"/api/mark/notifications/seen":                   nil,
	"/api/sse/events":                                nil,
	"/editor/kitsu/new/anime":                        nil,
	"/paypal/success":                                nil,
	"/paypal/cancel":                                 nil,
	"/anime/:id/edit":                                nil,
	"/anime/:id/edit/images":                         nil,
	"/anime/:id/edit/characters":                     nil,
	"/anime/:id/edit/relations":                      nil,
	"/anime/:id/edit/episodes":                       nil,
	"/anime/:id/edit/history":                        nil,
	"/new/thread":                                    nil,
	"/thread/:id/edit":                               nil,
	"/post/:id/edit":                                 nil,
	"/company/:id/edit":                              nil,
	"/admin/purchases":                               nil,
	"/admin/registrations":                           nil,
	"/admin/payments":                                nil,
	"/editor/anilist":                                nil,
	"/editor/shoboi":                                 nil,
	"/dark-flame-master":                             nil,
	"/groups/joined":                                 nil,
	"/user":                                          nil,
	"/settings":                                      nil,
	"/settings/accounts":                             nil,
	"/settings/notifications":                        nil,
	"/settings/info":                                 nil,
	"/settings/style":                                nil,
	"/settings/extras":                               nil,
	"/shop":                                          nil,
	"/shop/history":                                  nil,
	"/support":                                       nil,
	"/charge":                                        nil,
	"/log":                                           nil,
	"/log/from/:index":                               nil,
	"/inventory":                                     nil,
	"/extension/embed":                               nil,
	"/welcome":                                       nil,
}

// All returns which specific routes to test for a given generic route.
func All() map[string][]string {
	return routeTests
}
<commit_msg>Fixed user follows test<commit_after>package routetests

var routeTests = map[string][]string{
	// User
	"/user/:nick": {
		"/+Akyoto",
	},

	// "/user/:nick/characters/liked": []string{
	// 	"/+Akyoto/characters/liked",
	// },

	// "/user/:nick/forum/threads": []string{
	// 	"/+Akyoto/forum/threads",
	// },

	// "/user/:nick/forum/posts": []string{
	// 	"/+Akyoto/forum/posts",
	// },

	// "/user/:nick/soundtracks/added": []string{
	// 	"/+Akyoto/soundtracks/added",
	// },

	// "/user/:nick/soundtracks/added/from/:index": []string{
	// 	"/+Akyoto/soundtracks/added/from/3",
	// },

	// "/user/:nick/soundtracks/liked": []string{
	// 	"/+Akyoto/soundtracks/liked",
	// },

	// "/user/:nick/soundtracks/liked/from/:index": []string{
	// 	"/+Akyoto/soundtracks/liked/from/3",
	// },

	// "/user/:nick/quotes/added": []string{
	// 	"/+Scott/quotes/added",
	// },

	// "/user/:nick/quotes/added/from/:index": []string{
	// 	"/+Scott/quotes/added/from/3",
	// },

	// "/user/:nick/quotes/liked": []string{
	// 	"/+Scott/quotes/liked",
	// },

	// "/user/:nick/quotes/liked/from/:index": []string{
	// 	"/+Scott/quotes/liked/from/3",
	// },

	// "/user/:nick/followers": []string{
	// 	"/+Akyoto/followers",
	// },

	// "/user/:nick/stats": []string{
	// 	"/+Akyoto/stats",
	// },

	"/user/:nick/animelist/anime/:id": {
		"/+Akyoto/animelist/anime/74y2cFiiR",
	},

	"/user/:nick/animelist/watching": {
		"/+Akyoto/animelist/watching",
	},

	"/user/:nick/animelist/watching/from/:index": {
		"/+Akyoto/animelist/watching/from/1",
	},

	"/user/:nick/animelist/completed": {
		"/+Akyoto/animelist/completed",
	},

	"/user/:nick/animelist/completed/from/:index": {
		"/+Akyoto/animelist/completed/from/3",
	},

	"/user/:nick/animelist/planned": {
		"/+Akyoto/animelist/planned",
	},

	"/user/:nick/animelist/planned/from/:index": {
		"/+Akyoto/animelist/planned/from/3",
	},

	"/user/:nick/animelist/hold": {
		"/+Akyoto/animelist/hold",
	},

	"/user/:nick/animelist/hold/from/:index": {
		"/+Akyoto/animelist/hold/from/3",
	},

	"/user/:nick/animelist/dropped": {
		"/+Akyoto/animelist/dropped",
	},

	"/user/:nick/animelist/dropped/from/:index": {
		"/+Akyoto/animelist/dropped/from/3",
	},

	"/user/:nick/anime/recommended": {
		"/+Akyoto/anime/recommended",
	},

	"/user/:nick/anime/sequels": {
		"/+Akyoto/anime/sequels",
	},

	"/users/country/:country": {
		"/users/country/japan",
	},

	// Pages
	"/anime/:id": {
		"/anime/74y2cFiiR",
	},

	"/anime/:id/characters": {
		"/anime/74y2cFiiR/characters",
	},

	"/anime/:id/episodes": {
		"/anime/74y2cFiiR/episodes",
	},

	"/anime/:id/comments": {
		"/anime/74y2cFiiR/comments",
	},

	"/anime/:id/tracks": {
		"/anime/74y2cFiiR/tracks",
	},

	"/anime/:id/relations": {
		"/anime/74y2cFiiR/relations",
	},

	"/thread/:id": {
		"/thread/HJgS7c2K",
	},

	"/post/:id": {
		"/post/B1RzshnK",
	},

	"/forum/:tag": {
		"/forum/general",
	},

	"/genre/:name": {
		"/genre/action",
	},

	"/company/:id": {
		"/company/xCAUr7UkRaz",
	},

	"/company/:id/history": {
		"/company/xCAUr7UkRaz/history",
	},

	"/companies/from/:index": {
		"/companies/from/3",
	},

	"/explore/color/:color/anime": {
		"/explore/color/hsl:0.050,0.25,0.5/anime",
	},

	"/explore/color/:color/anime/from/:index": {
		"/explore/color/hsl:0.050,0.25,0.5/anime/from/3",
	},

	"/search/:term": {
		"/search/Dragon Ball",
	},

	"/quote/:id": {
		"/quote/gUZugd6zR",
	},

	"/quote/:id/edit": {
		"/quote/gUZugd6zR/edit",
	},

	"/quote/:id/history": {
		"/quote/gUZugd6zR/history",
	},

	"/quotes/from/:index": {
		"/quotes/from/2",
	},

	"/quotes/best/from/:index": {
		"/quotes/best/from/2",
	},

	"/soundtrack/:id": {
		"/soundtrack/h0ac8sKkg",
	},

	"/soundtrack/:id/lyrics": {
		"/soundtrack/vS64GbpzR/lyrics",
	},

	"/soundtrack/:id/edit": {
		"/soundtrack/h0ac8sKkg/edit",
	},

	"/soundtrack/:id/history": {
		"/soundtrack/h0ac8sKkg/history",
	},

	"/soundtracks": {
		"/soundtracks",
	},

	"/soundtracks/from/:index": {
		"/soundtracks/from/12",
	},

	"/soundtracks/best": {
		"/soundtracks/best",
	},

	"/soundtracks/best/from/:index": {
		"/soundtracks/best/from/12",
	},

	"/soundtracks/tag/:tag": {
		"/soundtracks/tag/moe",
	},

	"/soundtracks/tag/:tag/from/:index": {
		"/soundtracks/tag/moe/from/3",
	},

	"/character/:id": {
		"/character/dfrNQrmmg-",
	},

	"/episode/:id": {
		"/episode/oFlqThKWga",
	},

	// "/kitsu/character/:id": []string{
	// 	"/kitsu/character/6556",
	// },

	// "/mal/character/:id": []string{
	// 	"/mal/character/498",
	// },

	"/compare/animelist/:nick-1/:nick-2": {
		"/compare/animelist/Akyoto/Scott",
	},

	"/explore/anime/:year/:season/:status/:type": {
		"/explore/anime/2011/any/finished/tv",
	},

	// AMV
	"/amv/:id": {
		"/amv/07scvSWmg",
	},

	"/amv/:id/edit": {
		"/amv/07scvSWmg/edit",
	},

	"/amv/:id/history": {
		"/amv/07scvSWmg/history",
	},

	// AMVs
	"/amvs/from/:index": {
		"/amvs/from/3",
	},

	"/amvs/best/from/:index": {
		"/amvs/best/from/3",
	},

	// Redirects
	"/mal/anime/:id": {
		"/mal/anime/33352",
	},

	"/kitsu/anime/:id": {
		"/kitsu/anime/12230",
	},

	"/anilist/anime/:id": {
		"/anilist/anime/21827",
	},

	// API
	"/api/anime/:id": {
		"/api/anime/74y2cFiiR",
	},

	"/api/thread/:id": {
		"/api/thread/HJgS7c2K",
	},

	"/api/post/:id": {
		"/api/post/B1RzshnK",
	},

	"/api/animelist/:id": {
		"/api/animelist/4J6qpK1ve",
	},

	"/api/settings/:id": {
		"/api/settings/4J6qpK1ve",
	},

	"/api/user/:id": {
		"/api/user/4J6qpK1ve",
	},

	"/api/googletouser/:id": {
		"/api/googletouser/106530160120373282283",
	},

	"/api/nicktouser/:id": {
		"/api/nicktouser/Akyoto",
	},

	"/api/soundtrack/:id": {
		"/api/soundtrack/h0ac8sKkg",
	},

	"/api/animecharacters/:id": {
		"/api/animecharacters/74y2cFiiR",
	},

	"/api/animerelations/:id": {
		"/api/animerelations/74y2cFiiR",
	},

	"/api/amv/:id": {
		"/api/amv/07scvSWmg",
	},

	"/api/character/:id": {
		"/api/character/dfrNQrmmg-",
	},

	"/api/company/:id": {
		"/api/company/xCAUr7UkRaz",
	},

	"/api/draftindex/:id": {
		"/api/draftindex/4J6qpK1ve",
	},

	"/api/inventory/:id": {
		"/api/inventory/4J6qpK1ve",
	},

	"/api/shopitem/:id": {
		"/api/shopitem/pro-account-3",
	},

	"/api/notification/:id": {
		"/api/notification/q6Y6eraig",
	},

	"/api/quote/:id": {
		"/api/quote/GXp675zmR",
	},

	"/api/usernotifications/:id": {
		"/api/usernotifications/4J6qpK1ve",
	},

	"/api/pushsubscriptions/:id": {
		"/api/pushsubscriptions/4J6qpK1ve",
	},

	// Images
	"/images/*file": {
		"/images/elements/no-avatar.svg",
	},

	// Extra tests for higher coverage
	"/_/+Akyoto": {
		"/_/+Akyoto",
	},

	"/_/search/dragon": {
		"/_/search/dragon",
	},

	// Disable these tests because they require authorization
	"/auth/google":                                   nil,
	"/auth/google/callback":                          nil,
	"/auth/facebook":                                 nil,
	"/auth/facebook/callback":                        nil,
	"/auth/twitter":                                  nil,
	"/auth/twitter/callback":                         nil,
	"/dashboard":                                     nil,
	"/import":                                        nil,
	"/import/anilist/animelist":                      nil,
	"/import/anilist/animelist/finish":               nil,
	"/import/myanimelist/animelist":                  nil,
	"/import/myanimelist/animelist/finish":           nil,
	"/import/kitsu/animelist":                        nil,
	"/import/kitsu/animelist/finish":                 nil,
	"/animelist/watching":                            nil,
	"/animelist/completed":                           nil,
	"/animelist/planned":                             nil,
	"/animelist/hold":                                nil,
	"/animelist/dropped":                             nil,
	"/notifications":                                 nil,
	"/user/:nick/notifications":                      nil,
	"/user/:nick/edit":                               nil,
	"/user/:nick/log":                                nil,
	"/user/:nick/log/from/:index":                    nil,
	"/editor/soundtracks/file":                       nil,
	"/editor/soundtracks/links":                      nil,
	"/editor/soundtracks/lyrics/missing":             nil,
	"/editor/soundtracks/lyrics/unaligned":           nil,
	"/editor/soundtracks/tags":                       nil,
	"/api/test/notification":                         nil,
	"/api/paypal/payment/create":                     nil,
	"/api/emailtouser/:id":                           nil,
	"/api/pushsubscriptions/:id/get/:item":           nil,
	"/api/pushsubscriptions/:id/get/:item/:property": nil,
	"/api/count/notifications/unseen":                nil,
	"/api/mark/notifications/seen":                   nil,
	"/api/sse/events":                                nil,
	"/editor/kitsu/new/anime":                        nil,
	"/paypal/success":                                nil,
	"/paypal/cancel":                                 nil,
	"/anime/:id/edit":                                nil,
	"/anime/:id/edit/images":                         nil,
	"/anime/:id/edit/characters":                     nil,
	"/anime/:id/edit/relations":                      nil,
	"/anime/:id/edit/episodes":                       nil,
	"/anime/:id/edit/history":                        nil,
	"/new/thread":                                    nil,
	"/thread/:id/edit":                               nil,
	"/post/:id/edit":                                 nil,
	"/company/:id/edit":                              nil,
	"/admin/purchases":                               nil,
	"/admin/registrations":                           nil,
	"/admin/payments":                                nil,
	"/editor/anilist":                                nil,
	"/editor/shoboi":                                 nil,
	"/dark-flame-master":                             nil,
	"/groups/joined":                                 nil,
	"/user":                                          nil,
	"/settings":                                      nil,
	"/settings/accounts":                             nil,
	"/settings/notifications":                        nil,
	"/settings/info":                                 nil,
	"/settings/style":                                nil,
	"/settings/extras":                               nil,
	"/shop":                                          nil,
	"/shop/history":                                  nil,
	"/support":                                       nil,
	"/charge":                                        nil,
	"/log":                                           nil,
	"/log/from/:index":                               nil,
	"/inventory":                                     nil,
	"/extension/embed":                               nil,
	"/welcome":                                       nil,
}

// All returns which specific routes to test for a given generic route.
func All() map[string][]string {
	return routeTests
}
<|endoftext|>


<commit_before>/*
Copyright 2016 The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package options

import (
	"crypto/tls"
	"fmt"
	"net"
	"path"
	"strconv"
	"strings"

	"github.com/golang/glog"
	"github.com/spf13/pflag"

	utilnet "k8s.io/apimachinery/pkg/util/net"
	"k8s.io/apiserver/pkg/server"
	utilflag "k8s.io/apiserver/pkg/util/flag"
	certutil "k8s.io/client-go/util/cert"
)

type SecureServingOptions struct {
	BindAddress net.IP
	// BindPort is ignored when Listener is set, will serve https even with 0.
	BindPort int
	// BindNetwork is the type of network to bind to - defaults to "tcp", accepts "tcp",
	// "tcp4", and "tcp6".
	BindNetwork string

	// Listener is the secure server network listener.
	// either Listener or BindAddress/BindPort/BindNetwork is set,
	// if Listener is set, use it and omit BindAddress/BindPort/BindNetwork.
	Listener net.Listener

	// ServerCert is the TLS cert info for serving secure traffic
	ServerCert GeneratableKeyCert
	// SNICertKeys are named CertKeys for serving secure traffic with SNI support.
	SNICertKeys []utilflag.NamedCertKey
	// CipherSuites is the list of allowed cipher suites for the server.
	// Values are from tls package constants (https://golang.org/pkg/crypto/tls/#pkg-constants).
	CipherSuites []string
	// MinTLSVersion is the minimum TLS version supported.
	// Values are from tls package constants (https://golang.org/pkg/crypto/tls/#pkg-constants).
	MinTLSVersion string

	// HTTP2MaxStreamsPerConnection is the limit that the api server imposes on each client.
	// A value of zero means to use the default provided by golang's HTTP/2 support.
	HTTP2MaxStreamsPerConnection int
}

type CertKey struct {
	// CertFile is a file containing a PEM-encoded certificate, and possibly the complete certificate chain
	CertFile string
	// KeyFile is a file containing a PEM-encoded private key for the certificate specified by CertFile
	KeyFile string
}

type GeneratableKeyCert struct {
	CertKey CertKey

	// CertDirectory is a directory that will contain the certificates.  If the cert and key aren't specifically set
	// this will be used to derive a match with the "pair-name"
	CertDirectory string
	// PairName is the name which will be used with CertDirectory to make a cert and key names
	// It becomes CertDirector/PairName.crt and CertDirector/PairName.key
	PairName string
}

func NewSecureServingOptions() *SecureServingOptions {
	return &SecureServingOptions{
		BindAddress: net.ParseIP("0.0.0.0"),
		BindPort:    443,
		ServerCert: GeneratableKeyCert{
			PairName:      "apiserver",
			CertDirectory: "apiserver.local.config/certificates",
		},
	}
}

func (s *SecureServingOptions) DefaultExternalAddress() (net.IP, error) {
	return utilnet.ChooseBindAddress(s.BindAddress)
}

func (s *SecureServingOptions) Validate() []error {
	if s == nil {
		return nil
	}

	errors := []error{}

	if s.BindPort < 0 || s.BindPort > 65535 {
		errors = append(errors, fmt.Errorf("--secure-port %v must be between 0 and 65535, inclusive. 0 for turning off secure port", s.BindPort))
	}

	return errors
}

func (s *SecureServingOptions) AddFlags(fs *pflag.FlagSet) {
	if s == nil {
		return
	}

	fs.IPVar(&s.BindAddress, "bind-address", s.BindAddress, ""+
		"The IP address on which to listen for the --secure-port port. The "+
		"associated interface(s) must be reachable by the rest of the cluster, and by CLI/web "+
		"clients. If blank, all interfaces will be used (0.0.0.0 for all IPv4 interfaces and :: for all IPv6 interfaces).")
	fs.IntVar(&s.BindPort, "secure-port", s.BindPort, ""+
		"The port on which to serve HTTPS with authentication and authorization. If 0, "+
		"don't serve HTTPS at all.")

	fs.StringVar(&s.ServerCert.CertDirectory, "cert-dir", s.ServerCert.CertDirectory, ""+
		"The directory where the TLS certs are located. "+
		"If --tls-cert-file and --tls-private-key-file are provided, this flag will be ignored.")

	fs.StringVar(&s.ServerCert.CertKey.CertFile, "tls-cert-file", s.ServerCert.CertKey.CertFile, ""+
		"File containing the default x509 Certificate for HTTPS. (CA cert, if any, concatenated "+
		"after server cert). If HTTPS serving is enabled, and --tls-cert-file and "+
		"--tls-private-key-file are not provided, a self-signed certificate and key "+
		"are generated for the public address and saved to the directory specified by --cert-dir.")

	fs.StringVar(&s.ServerCert.CertKey.KeyFile, "tls-private-key-file", s.ServerCert.CertKey.KeyFile,
		"File containing the default x509 private key matching --tls-cert-file.")

	tlsCipherPossibleValues := utilflag.TLSCipherPossibleValues()
	fs.StringSliceVar(&s.CipherSuites, "tls-cipher-suites", s.CipherSuites,
		"Comma-separated list of cipher suites for the server. "+
			"If omitted, the default Go cipher suites will be use.  "+
			"Possible values: "+strings.Join(tlsCipherPossibleValues, ","))

	tlsPossibleVersions := utilflag.TLSPossibleVersions()
	fs.StringVar(&s.MinTLSVersion, "tls-min-version", s.MinTLSVersion,
		"Minimum TLS version supported. "+
			"Possible values: "+strings.Join(tlsPossibleVersions, ", "))

	fs.Var(utilflag.NewNamedCertKeyArray(&s.SNICertKeys), "tls-sni-cert-key", ""+
		"A pair of x509 certificate and private key file paths, optionally suffixed with a list of "+
		"domain patterns which are fully qualified domain names, possibly with prefixed wildcard "+
		"segments. If no domain patterns are provided, the names of the certificate are "+
		"extracted. Non-wildcard matches trump over wildcard matches, explicit domain patterns "+
		"trump over extracted names. For multiple key/certificate pairs, use the "+
		"--tls-sni-cert-key multiple times. "+
		"Examples: \"example.crt,example.key\" or \"foo.crt,foo.key:*.foo.com,foo.com\".")

	fs.IntVar(&s.HTTP2MaxStreamsPerConnection, "http2-max-streams-per-connection", s.HTTP2MaxStreamsPerConnection, ""+
		"The limit that the server gives to clients for "+
		"the maximum number of streams in an HTTP/2 connection. "+
		"Zero means to use golang's default.")
}

// ApplyTo fills up serving information in the server configuration.
func (s *SecureServingOptions) ApplyTo(config **server.SecureServingInfo) error {
	if s == nil {
		return nil
	}
	if s.BindPort <= 0 && s.Listener == nil {
		return nil
	}

	if s.Listener == nil {
		var err error
		addr := net.JoinHostPort(s.BindAddress.String(), strconv.Itoa(s.BindPort))
		s.Listener, s.BindPort, err = CreateListener(s.BindNetwork, addr)
		if err != nil {
			return fmt.Errorf("failed to create listener: %v", err)
		}
	} else {
		if _, ok := s.Listener.Addr().(*net.TCPAddr); !ok {
			return fmt.Errorf("failed to parse ip and port from listener")
		}
		s.BindPort = s.Listener.Addr().(*net.TCPAddr).Port
		s.BindAddress = s.Listener.Addr().(*net.TCPAddr).IP
	}

	*config = &server.SecureServingInfo{
		Listener:                     s.Listener,
		HTTP2MaxStreamsPerConnection: s.HTTP2MaxStreamsPerConnection,
	}
	c := *config

	serverCertFile, serverKeyFile := s.ServerCert.CertKey.CertFile, s.ServerCert.CertKey.KeyFile
	// load main cert
	if len(serverCertFile) != 0 || len(serverKeyFile) != 0 {
		tlsCert, err := tls.LoadX509KeyPair(serverCertFile, serverKeyFile)
		if err != nil {
			return fmt.Errorf("unable to load server certificate: %v", err)
		}
		c.Cert = &tlsCert
	}

	if len(s.CipherSuites) != 0 {
		cipherSuites, err := utilflag.TLSCipherSuites(s.CipherSuites)
		if err != nil {
			return err
		}
		c.CipherSuites = cipherSuites
	}

	var err error
	c.MinTLSVersion, err = utilflag.TLSVersion(s.MinTLSVersion)
	if err != nil {
		return err
	}

	// load SNI certs
	namedTLSCerts := make([]server.NamedTLSCert, 0, len(s.SNICertKeys))
	for _, nck := range s.SNICertKeys {
		tlsCert, err := tls.LoadX509KeyPair(nck.CertFile, nck.KeyFile)
		namedTLSCerts = append(namedTLSCerts, server.NamedTLSCert{
			TLSCert: tlsCert,
			Names:   nck.Names,
		})
		if err != nil {
			return fmt.Errorf("failed to load SNI cert and key: %v", err)
		}
	}
	c.SNICerts, err = server.GetNamedCertificateMap(namedTLSCerts)
	if err != nil {
		return err
	}

	return nil
}

func (s *SecureServingOptions) MaybeDefaultWithSelfSignedCerts(publicAddress string, alternateDNS []string, alternateIPs []net.IP) error {
	if s == nil {
		return nil
	}
	keyCert := &s.ServerCert.CertKey
	if len(keyCert.CertFile) != 0 || len(keyCert.KeyFile) != 0 {
		return nil
	}

	keyCert.CertFile = path.Join(s.ServerCert.CertDirectory, s.ServerCert.PairName+".crt")
	keyCert.KeyFile = path.Join(s.ServerCert.CertDirectory, s.ServerCert.PairName+".key")

	canReadCertAndKey, err := certutil.CanReadCertAndKey(keyCert.CertFile, keyCert.KeyFile)
	if err != nil {
		return err
	}
	if !canReadCertAndKey {
		// add either the bind address or localhost to the valid alternates
		bindIP := s.BindAddress.String()
		if bindIP == "0.0.0.0" {
			alternateDNS = append(alternateDNS, "localhost")
		} else {
			alternateIPs = append(alternateIPs, s.BindAddress)
		}

		if cert, key, err := certutil.GenerateSelfSignedCertKey(publicAddress, alternateIPs, alternateDNS); err != nil {
			return fmt.Errorf("unable to generate self signed cert: %v", err)
		} else {
			if err := certutil.WriteCert(keyCert.CertFile, cert); err != nil {
				return err
			}

			if err := certutil.WriteKey(keyCert.KeyFile, key); err != nil {
				return err
			}
			glog.Infof("Generated self-signed cert (%s, %s)", keyCert.CertFile, keyCert.KeyFile)
		}
	}

	return nil
}

func CreateListener(network, addr string) (net.Listener, int, error) {
	if len(network) == 0 {
		network = "tcp"
	}
	ln, err := net.Listen(network, addr)
	if err != nil {
		return nil, 0, fmt.Errorf("failed to listen on %v: %v", addr, err)
	}

	// get port
	tcpAddr, ok := ln.Addr().(*net.TCPAddr)
	if !ok {
		ln.Close()
		return nil, 0, fmt.Errorf("invalid listen address: %q", ln.Addr().String())
	}

	return ln, tcpAddr.Port, nil
}
<commit_msg>apiserver: don't create self-signed certs with disabled secure serving<commit_after>/*
Copyright 2016 The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package options

import (
	"crypto/tls"
	"fmt"
	"net"
	"path"
	"strconv"
	"strings"

	"github.com/golang/glog"
	"github.com/spf13/pflag"

	utilnet "k8s.io/apimachinery/pkg/util/net"
	"k8s.io/apiserver/pkg/server"
	utilflag "k8s.io/apiserver/pkg/util/flag"
	certutil "k8s.io/client-go/util/cert"
)

type SecureServingOptions struct {
	BindAddress net.IP
	// BindPort is ignored when Listener is set, will serve https even with 0.
	BindPort int
	// BindNetwork is the type of network to bind to - defaults to "tcp", accepts "tcp",
	// "tcp4", and "tcp6".
	BindNetwork string

	// Listener is the secure server network listener.
	// either Listener or BindAddress/BindPort/BindNetwork is set,
	// if Listener is set, use it and omit BindAddress/BindPort/BindNetwork.
	Listener net.Listener

	// ServerCert is the TLS cert info for serving secure traffic
	ServerCert GeneratableKeyCert
	// SNICertKeys are named CertKeys for serving secure traffic with SNI support.
	SNICertKeys []utilflag.NamedCertKey
	// CipherSuites is the list of allowed cipher suites for the server.
	// Values are from tls package constants (https://golang.org/pkg/crypto/tls/#pkg-constants).
	CipherSuites []string
	// MinTLSVersion is the minimum TLS version supported.
	// Values are from tls package constants (https://golang.org/pkg/crypto/tls/#pkg-constants).
	MinTLSVersion string

	// HTTP2MaxStreamsPerConnection is the limit that the api server imposes on each client.
	// A value of zero means to use the default provided by golang's HTTP/2 support.
	HTTP2MaxStreamsPerConnection int
}

type CertKey struct {
	// CertFile is a file containing a PEM-encoded certificate, and possibly the complete certificate chain
	CertFile string
	// KeyFile is a file containing a PEM-encoded private key for the certificate specified by CertFile
	KeyFile string
}

type GeneratableKeyCert struct {
	CertKey CertKey

	// CertDirectory is a directory that will contain the certificates.  If the cert and key aren't specifically set
	// this will be used to derive a match with the "pair-name"
	CertDirectory string
	// PairName is the name which will be used with CertDirectory to make a cert and key names
	// It becomes CertDirector/PairName.crt and CertDirector/PairName.key
	PairName string
}

func NewSecureServingOptions() *SecureServingOptions {
	return &SecureServingOptions{
		BindAddress: net.ParseIP("0.0.0.0"),
		BindPort:    443,
		ServerCert: GeneratableKeyCert{
			PairName:      "apiserver",
			CertDirectory: "apiserver.local.config/certificates",
		},
	}
}

func (s *SecureServingOptions) DefaultExternalAddress() (net.IP, error) {
	return utilnet.ChooseBindAddress(s.BindAddress)
}

func (s *SecureServingOptions) Validate() []error {
	if s == nil {
		return nil
	}

	errors := []error{}

	if s.BindPort < 0 || s.BindPort > 65535 {
		errors = append(errors, fmt.Errorf("--secure-port %v must be between 0 and 65535, inclusive. 0 for turning off secure port", s.BindPort))
	}

	return errors
}

func (s *SecureServingOptions) AddFlags(fs *pflag.FlagSet) {
	if s == nil {
		return
	}

	fs.IPVar(&s.BindAddress, "bind-address", s.BindAddress, ""+
		"The IP address on which to listen for the --secure-port port. The "+
		"associated interface(s) must be reachable by the rest of the cluster, and by CLI/web "+
		"clients. If blank, all interfaces will be used (0.0.0.0 for all IPv4 interfaces and :: for all IPv6 interfaces).")
	fs.IntVar(&s.BindPort, "secure-port", s.BindPort, ""+
		"The port on which to serve HTTPS with authentication and authorization. If 0, "+
		"don't serve HTTPS at all.")

	fs.StringVar(&s.ServerCert.CertDirectory, "cert-dir", s.ServerCert.CertDirectory, ""+
		"The directory where the TLS certs are located. "+
		"If --tls-cert-file and --tls-private-key-file are provided, this flag will be ignored.")

	fs.StringVar(&s.ServerCert.CertKey.CertFile, "tls-cert-file", s.ServerCert.CertKey.CertFile, ""+
		"File containing the default x509 Certificate for HTTPS. (CA cert, if any, concatenated "+
		"after server cert). If HTTPS serving is enabled, and --tls-cert-file and "+
		"--tls-private-key-file are not provided, a self-signed certificate and key "+
		"are generated for the public address and saved to the directory specified by --cert-dir.")

	fs.StringVar(&s.ServerCert.CertKey.KeyFile, "tls-private-key-file", s.ServerCert.CertKey.KeyFile,
		"File containing the default x509 private key matching --tls-cert-file.")

	tlsCipherPossibleValues := utilflag.TLSCipherPossibleValues()
	fs.StringSliceVar(&s.CipherSuites, "tls-cipher-suites", s.CipherSuites,
		"Comma-separated list of cipher suites for the server. "+
			"If omitted, the default Go cipher suites will be use.  "+
			"Possible values: "+strings.Join(tlsCipherPossibleValues, ","))

	tlsPossibleVersions := utilflag.TLSPossibleVersions()
	fs.StringVar(&s.MinTLSVersion, "tls-min-version", s.MinTLSVersion,
		"Minimum TLS version supported. "+
			"Possible values: "+strings.Join(tlsPossibleVersions, ", "))

	fs.Var(utilflag.NewNamedCertKeyArray(&s.SNICertKeys), "tls-sni-cert-key", ""+
		"A pair of x509 certificate and private key file paths, optionally suffixed with a list of "+
		"domain patterns which are fully qualified domain names, possibly with prefixed wildcard "+
		"segments. If no domain patterns are provided, the names of the certificate are "+
		"extracted. Non-wildcard matches trump over wildcard matches, explicit domain patterns "+
		"trump over extracted names. For multiple key/certificate pairs, use the "+
		"--tls-sni-cert-key multiple times. "+
		"Examples: \"example.crt,example.key\" or \"foo.crt,foo.key:*.foo.com,foo.com\".")

	fs.IntVar(&s.HTTP2MaxStreamsPerConnection, "http2-max-streams-per-connection", s.HTTP2MaxStreamsPerConnection, ""+
		"The limit that the server gives to clients for "+
		"the maximum number of streams in an HTTP/2 connection. "+
		"Zero means to use golang's default.")
}

// ApplyTo fills up serving information in the server configuration.
func (s *SecureServingOptions) ApplyTo(config **server.SecureServingInfo) error {
	if s == nil {
		return nil
	}
	if s.BindPort <= 0 && s.Listener == nil {
		return nil
	}

	if s.Listener == nil {
		var err error
		addr := net.JoinHostPort(s.BindAddress.String(), strconv.Itoa(s.BindPort))
		s.Listener, s.BindPort, err = CreateListener(s.BindNetwork, addr)
		if err != nil {
			return fmt.Errorf("failed to create listener: %v", err)
		}
	} else {
		if _, ok := s.Listener.Addr().(*net.TCPAddr); !ok {
			return fmt.Errorf("failed to parse ip and port from listener")
		}
		s.BindPort = s.Listener.Addr().(*net.TCPAddr).Port
		s.BindAddress = s.Listener.Addr().(*net.TCPAddr).IP
	}

	*config = &server.SecureServingInfo{
		Listener:                     s.Listener,
		HTTP2MaxStreamsPerConnection: s.HTTP2MaxStreamsPerConnection,
	}
	c := *config

	serverCertFile, serverKeyFile := s.ServerCert.CertKey.CertFile, s.ServerCert.CertKey.KeyFile
	// load main cert
	if len(serverCertFile) != 0 || len(serverKeyFile) != 0 {
		tlsCert, err := tls.LoadX509KeyPair(serverCertFile, serverKeyFile)
		if err != nil {
			return fmt.Errorf("unable to load server certificate: %v", err)
		}
		c.Cert = &tlsCert
	}

	if len(s.CipherSuites) != 0 {
		cipherSuites, err := utilflag.TLSCipherSuites(s.CipherSuites)
		if err != nil {
			return err
		}
		c.CipherSuites = cipherSuites
	}

	var err error
	c.MinTLSVersion, err = utilflag.TLSVersion(s.MinTLSVersion)
	if err != nil {
		return err
	}

	// load SNI certs
	namedTLSCerts := make([]server.NamedTLSCert, 0, len(s.SNICertKeys))
	for _, nck := range s.SNICertKeys {
		tlsCert, err := tls.LoadX509KeyPair(nck.CertFile, nck.KeyFile)
		namedTLSCerts = append(namedTLSCerts, server.NamedTLSCert{
			TLSCert: tlsCert,
			Names:   nck.Names,
		})
		if err != nil {
			return fmt.Errorf("failed to load SNI cert and key: %v", err)
		}
	}
	c.SNICerts, err = server.GetNamedCertificateMap(namedTLSCerts)
	if err != nil {
		return err
	}

	return nil
}

func (s *SecureServingOptions) MaybeDefaultWithSelfSignedCerts(publicAddress string, alternateDNS []string, alternateIPs []net.IP) error {
	if s == nil || (s.BindPort == 0 && s.Listener == nil) {
		return nil
	}
	keyCert := &s.ServerCert.CertKey
	if len(keyCert.CertFile) != 0 || len(keyCert.KeyFile) != 0 {
		return nil
	}

	keyCert.CertFile = path.Join(s.ServerCert.CertDirectory, s.ServerCert.PairName+".crt")
	keyCert.KeyFile = path.Join(s.ServerCert.CertDirectory, s.ServerCert.PairName+".key")

	canReadCertAndKey, err := certutil.CanReadCertAndKey(keyCert.CertFile, keyCert.KeyFile)
	if err != nil {
		return err
	}
	if !canReadCertAndKey {
		// add either the bind address or localhost to the valid alternates
		bindIP := s.BindAddress.String()
		if bindIP == "0.0.0.0" {
			alternateDNS = append(alternateDNS, "localhost")
		} else {
			alternateIPs = append(alternateIPs, s.BindAddress)
		}

		if cert, key, err := certutil.GenerateSelfSignedCertKey(publicAddress, alternateIPs, alternateDNS); err != nil {
			return fmt.Errorf("unable to generate self signed cert: %v", err)
		} else {
			if err := certutil.WriteCert(keyCert.CertFile, cert); err != nil {
				return err
			}

			if err := certutil.WriteKey(keyCert.KeyFile, key); err != nil {
				return err
			}
			glog.Infof("Generated self-signed cert (%s, %s)", keyCert.CertFile, keyCert.KeyFile)
		}
	}

	return nil
}

func CreateListener(network, addr string) (net.Listener, int, error) {
	if len(network) == 0 {
		network = "tcp"
	}
	ln, err := net.Listen(network, addr)
	if err != nil {
		return nil, 0, fmt.Errorf("failed to listen on %v: %v", addr, err)
	}

	// get port
	tcpAddr, ok := ln.Addr().(*net.TCPAddr)
	if !ok {
		ln.Close()
		return nil, 0, fmt.Errorf("invalid listen address: %q", ln.Addr().String())
	}

	return ln, tcpAddr.Port, nil
}
<|endoftext|>


<commit_before>package cloudstack

import (
	"errors"
	"fmt"
	"log"
	"strings"

	"github.com/hashicorp/terraform/helper/schema"
	"github.com/xanzy/go-cloudstack/cloudstack"
)

func resourceCloudStackNetworkACL() *schema.Resource {
	return &schema.Resource{
		Create: resourceCloudStackNetworkACLCreate,
		Read:   resourceCloudStackNetworkACLRead,
		Delete: resourceCloudStackNetworkACLDelete,

		Schema: map[string]*schema.Schema{
			"name": &schema.Schema{
				Type:     schema.TypeString,
				Required: true,
				ForceNew: true,
			},

			"description": &schema.Schema{
				Type:     schema.TypeString,
				Optional: true,
				Computed: true,
				ForceNew: true,
			},

			"vpc_id": &schema.Schema{
				Type:     schema.TypeString,
				Optional: true,
				Computed: true,
				ForceNew: true,
			},

			"vpc": &schema.Schema{
				Type:       schema.TypeString,
				Optional:   true,
				ForceNew:   true,
				Deprecated: "Please use the `vpc_id` field instead",
			},
		},
	}
}

func resourceCloudStackNetworkACLCreate(d *schema.ResourceData, meta interface{}) error {
	cs := meta.(*cloudstack.CloudStackClient)

	name := d.Get("name").(string)

	vpc, ok := d.GetOk("vpc_id")
	if !ok {
		vpc, ok = d.GetOk("vpc")
	}
	if !ok {
		return errors.New("Either `vpc_id` or [deprecated] `vpc` must be provided.")
	}

	// Retrieve the vpc ID
	vpcid, e := retrieveID(cs, "vpc", vpc.(string))
	if e != nil {
		return e.Error()
	}

	// Create a new parameter struct
	p := cs.NetworkACL.NewCreateNetworkACLListParams(name, vpcid)

	// Set the description
	if description, ok := d.GetOk("description"); ok {
		p.SetDescription(description.(string))
	} else {
		p.SetDescription(name)
	}

	// Create the new network ACL list
	r, err := cs.NetworkACL.CreateNetworkACLList(p)
	if err != nil {
		return fmt.Errorf("Error creating network ACL list %s: %s", name, err)
	}

	d.SetId(r.Id)

	return resourceCloudStackNetworkACLRead(d, meta)
}

func resourceCloudStackNetworkACLRead(d *schema.ResourceData, meta interface{}) error {
	cs := meta.(*cloudstack.CloudStackClient)

	// Get the network ACL list details
	f, count, err := cs.NetworkACL.GetNetworkACLListByID(d.Id())
	if err != nil {
		if count == 0 {
			log.Printf(
				"[DEBUG] Network ACL list %s does no longer exist", d.Get("name").(string))
			d.SetId("")
			return nil
		}

		return err
	}

	d.Set("name", f.Name)
	d.Set("description", f.Description)
	d.Set("vpc_id", f.Vpcid)

	return nil
}

func resourceCloudStackNetworkACLDelete(d *schema.ResourceData, meta interface{}) error {
	cs := meta.(*cloudstack.CloudStackClient)

	// Create a new parameter struct
	p := cs.NetworkACL.NewDeleteNetworkACLListParams(d.Id())

	// Delete the network ACL list
	_, err := cs.NetworkACL.DeleteNetworkACLList(p)
	if err != nil {
		// This is a very poor way to be told the ID does no longer exist :(
		if strings.Contains(err.Error(), fmt.Sprintf(
			"Invalid parameter id value=%s due to incorrect long value format, "+
				"or entity does not exist", d.Id())) {
			return nil
		}

		return fmt.Errorf("Error deleting network ACL list %s: %s", d.Get("name").(string), err)
	}

	return nil
}
<commit_msg>Use the new option to list ACLs based on the ID and VPC ID<commit_after>package cloudstack

import (
	"errors"
	"fmt"
	"log"
	"strings"

	"github.com/hashicorp/terraform/helper/schema"
	"github.com/xanzy/go-cloudstack/cloudstack"
)

func resourceCloudStackNetworkACL() *schema.Resource {
	return &schema.Resource{
		Create: resourceCloudStackNetworkACLCreate,
		Read:   resourceCloudStackNetworkACLRead,
		Delete: resourceCloudStackNetworkACLDelete,

		Schema: map[string]*schema.Schema{
			"name": &schema.Schema{
				Type:     schema.TypeString,
				Required: true,
				ForceNew: true,
			},

			"description": &schema.Schema{
				Type:     schema.TypeString,
				Optional: true,
				Computed: true,
				ForceNew: true,
			},

			"vpc_id": &schema.Schema{
				Type:     schema.TypeString,
				Optional: true,
				Computed: true,
				ForceNew: true,
			},

			"vpc": &schema.Schema{
				Type:       schema.TypeString,
				Optional:   true,
				ForceNew:   true,
				Deprecated: "Please use the `vpc_id` field instead",
			},
		},
	}
}

func resourceCloudStackNetworkACLCreate(d *schema.ResourceData, meta interface{}) error {
	cs := meta.(*cloudstack.CloudStackClient)

	name := d.Get("name").(string)

	vpc, ok := d.GetOk("vpc_id")
	if !ok {
		vpc, ok = d.GetOk("vpc")
	}
	if !ok {
		return errors.New("Either `vpc_id` or [deprecated] `vpc` must be provided.")
	}

	// Retrieve the vpc ID
	vpcid, e := retrieveID(cs, "vpc", vpc.(string))
	if e != nil {
		return e.Error()
	}

	// Create a new parameter struct
	p := cs.NetworkACL.NewCreateNetworkACLListParams(name, vpcid)

	// Set the description
	if description, ok := d.GetOk("description"); ok {
		p.SetDescription(description.(string))
	} else {
		p.SetDescription(name)
	}

	// Create the new network ACL list
	r, err := cs.NetworkACL.CreateNetworkACLList(p)
	if err != nil {
		return fmt.Errorf("Error creating network ACL list %s: %s", name, err)
	}

	d.SetId(r.Id)

	return resourceCloudStackNetworkACLRead(d, meta)
}

func resourceCloudStackNetworkACLRead(d *schema.ResourceData, meta interface{}) error {
	cs := meta.(*cloudstack.CloudStackClient)

	vpc, ok := d.GetOk("vpc_id")
	if !ok {
		vpc, ok = d.GetOk("vpc")
	}
	if !ok {
		return errors.New("Either `vpc_id` or [deprecated] `vpc` must be provided.")
	}

	// Retrieve the vpc ID
	vpcid, e := retrieveID(cs, "vpc", vpc.(string))
	if e != nil {
		return e.Error()
	}

	// Get the network ACL list details
	f, count, err := cs.NetworkACL.GetNetworkACLListByID(d.Id(), cloudstack.WithVPCID(vpcid))
	if err != nil {
		if count == 0 {
			log.Printf(
				"[DEBUG] Network ACL list %s does no longer exist", d.Get("name").(string))
			d.SetId("")
			return nil
		}

		return err
	}

	d.Set("name", f.Name)
	d.Set("description", f.Description)
	d.Set("vpc_id", f.Vpcid)

	return nil
}

func resourceCloudStackNetworkACLDelete(d *schema.ResourceData, meta interface{}) error {
	cs := meta.(*cloudstack.CloudStackClient)

	// Create a new parameter struct
	p := cs.NetworkACL.NewDeleteNetworkACLListParams(d.Id())

	// Delete the network ACL list
	_, err := cs.NetworkACL.DeleteNetworkACLList(p)
	if err != nil {
		// This is a very poor way to be told the ID does no longer exist :(
		if strings.Contains(err.Error(), fmt.Sprintf(
			"Invalid parameter id value=%s due to incorrect long value format, "+
				"or entity does not exist", d.Id())) {
			return nil
		}

		return fmt.Errorf("Error deleting network ACL list %s: %s", d.Get("name").(string), err)
	}

	return nil
}
<|endoftext|>


<commit_before>package addrs_test

import (
	"flag"
	"fmt"
	"net"
	"sync"
	"testing"

	"github.com/daaku/go.flag.addrs"
)

var (
	genNameCount int
	genNameMutex sync.Mutex
)

func genName() string {
	genNameMutex.Lock()
	defer genNameMutex.Unlock()
	defer func() { genNameCount++ }()
	return fmt.Sprintf("flag-%d", genNameCount)
}

func TestFlagOne(t *testing.T) {
	t.Parallel()
	name := genName()
	var a1 net.Addr
	addrs.FlagOneVar(&a1, name, "", "")

	const network = "udp"
	const addr = "127.0.0.1:1234"

	if err := flag.Set(name, network+":"+addr); err != nil {
		t.Fatal(err)
	}
	if a1.Network() != network {
		t.Fatal("did not find expected network")
	}
	if a1.String() != addr {
		t.Fatal("did not find expected addr")
	}
}

func TestFlagOneInvalidNetwork(t *testing.T) {
	t.Parallel()
	name := genName()
	var a1 net.Addr
	addrs.FlagOneVar(&a1, name, "", "")

	const network = "foo"
	const addr = "127.0.0.1:1234"

	err := flag.Set(name, network+":"+addr)
	if err == nil {
		t.Fatal("was expecting an error")
	}
	if err.Error() != "unknown network foo" {
		t.Fatal("did not get expected error, got", err)
	}
}

func TestFlagOneDefaultValue(t *testing.T) {
	t.Parallel()
	name := genName()
	var a1 net.Addr
	const network = "udp"
	const addr = "127.0.0.1:1234"
	addrs.FlagOneVar(&a1, name, network+":"+addr, "")
	if a1.Network() != network {
		t.Fatal("did not find expected network")
	}
	if a1.String() != addr {
		t.Fatal("did not find expected addr")
	}
}

func TestFlagOneInvalidDefaultValue(t *testing.T) {
	t.Parallel()
	defer func() {
		if err := recover(); err == nil {
			t.Fatal("was expecting panic")
		}
	}()
	name := genName()
	var a1 net.Addr
	const network = "foo"
	const addr = "127.0.0.1:1234"
	addrs.FlagOneVar(&a1, name, network+":"+addr, "")
}

func TestFlagOneInvalidFormat(t *testing.T) {
	t.Parallel()
	name := genName()
	var a1 net.Addr
	addrs.FlagOneVar(&a1, name, "", "")

	err := flag.Set(name, "foo")
	if err == nil {
		t.Fatal("was expecting an error")
	}
	if err.Error() != `invalid address format, must be "net:host:port": foo` {
		t.Fatal("did not get expected error, got", err)
	}
}

func TestFlagMany(t *testing.T) {
	t.Parallel()
	name := genName()
	var a1 []net.Addr
	addrs.FlagManyVar(&a1, name, "", "")

	const network0 = "tcp"
	const addr0 = "127.0.0.1:1234"
	const network1 = "tcp"
	const addr1 = "127.0.0.1:5678"

	if err := flag.Set(name, network0+":"+addr0+","+network1+":"+addr1); err != nil {
		t.Fatal(err)
	}
	if a1[0].Network() != network0 {
		t.Fatal("did not find expected network")
	}
	if a1[0].String() != addr0 {
		t.Fatal("did not find expected addr")
	}
	if a1[1].Network() != network1 {
		t.Fatal("did not find expected network")
	}
	if a1[1].String() != addr1 {
		t.Fatal("did not find expected addr")
	}
}

func TestFlagManyDefaultValue(t *testing.T) {
	t.Parallel()
	name := genName()
	var a1 []net.Addr
	const network0 = "tcp"
	const addr0 = "127.0.0.1:1234"
	const network1 = "tcp"
	const addr1 = "127.0.0.1:5678"
	addrs.FlagManyVar(&a1, name, network0+":"+addr0+","+network1+":"+addr1, "")

	if a1[0].Network() != network0 {
		t.Fatal("did not find expected network")
	}
	if a1[0].String() != addr0 {
		t.Fatal("did not find expected addr")
	}
	if a1[1].Network() != network1 {
		t.Fatal("did not find expected network")
	}
	if a1[1].String() != addr1 {
		t.Fatal("did not find expected addr")
	}
}

func TestFlagManyInvalidDefaultValue(t *testing.T) {
	t.Parallel()
	defer func() {
		if err := recover(); err == nil {
			t.Fatal("was expecting panic")
		}
	}()
	name := genName()
	var a1 []net.Addr
	const network = "foo"
	const addr = "127.0.0.1:1234"
	addrs.FlagManyVar(&a1, name, network+":"+addr, "")
}
<commit_msg>use new import path in tests<commit_after>package addrs_test

import (
	"flag"
	"fmt"
	"net"
	"sync"
	"testing"

	"github.com/ParsePlatform/go.flag.addrs"
)

var (
	genNameCount int
	genNameMutex sync.Mutex
)

func genName() string {
	genNameMutex.Lock()
	defer genNameMutex.Unlock()
	defer func() { genNameCount++ }()
	return fmt.Sprintf("flag-%d", genNameCount)
}

func TestFlagOne(t *testing.T) {
	t.Parallel()
	name := genName()
	var a1 net.Addr
	addrs.FlagOneVar(&a1, name, "", "")

	const network = "udp"
	const addr = "127.0.0.1:1234"

	if err := flag.Set(name, network+":"+addr); err != nil {
		t.Fatal(err)
	}
	if a1.Network() != network {
		t.Fatal("did not find expected network")
	}
	if a1.String() != addr {
		t.Fatal("did not find expected addr")
	}
}

func TestFlagOneInvalidNetwork(t *testing.T) {
	t.Parallel()
	name := genName()
	var a1 net.Addr
	addrs.FlagOneVar(&a1, name, "", "")

	const network = "foo"
	const addr = "127.0.0.1:1234"

	err := flag.Set(name, network+":"+addr)
	if err == nil {
		t.Fatal("was expecting an error")
	}
	if err.Error() != "unknown network foo" {
		t.Fatal("did not get expected error, got", err)
	}
}

func TestFlagOneDefaultValue(t *testing.T) {
	t.Parallel()
	name := genName()
	var a1 net.Addr
	const network = "udp"
	const addr = "127.0.0.1:1234"
	addrs.FlagOneVar(&a1, name, network+":"+addr, "")
	if a1.Network() != network {
		t.Fatal("did not find expected network")
	}
	if a1.String() != addr {
		t.Fatal("did not find expected addr")
	}
}

func TestFlagOneInvalidDefaultValue(t *testing.T) {
	t.Parallel()
	defer func() {
		if err := recover(); err == nil {
			t.Fatal("was expecting panic")
		}
	}()
	name := genName()
	var a1 net.Addr
	const network = "foo"
	const addr = "127.0.0.1:1234"
	addrs.FlagOneVar(&a1, name, network+":"+addr, "")
}

func TestFlagOneInvalidFormat(t *testing.T) {
	t.Parallel()
	name := genName()
	var a1 net.Addr
	addrs.FlagOneVar(&a1, name, "", "")

	err := flag.Set(name, "foo")
	if err == nil {
		t.Fatal("was expecting an error")
	}
	if err.Error() != `invalid address format, must be "net:host:port": foo` {
		t.Fatal("did not get expected error, got", err)
	}
}

func TestFlagMany(t *testing.T) {
	t.Parallel()
	name := genName()
	var a1 []net.Addr
	addrs.FlagManyVar(&a1, name, "", "")

	const network0 = "tcp"
	const addr0 = "127.0.0.1:1234"
	const network1 = "tcp"
	const addr1 = "127.0.0.1:5678"

	if err := flag.Set(name, network0+":"+addr0+","+network1+":"+addr1); err != nil {
		t.Fatal(err)
	}
	if a1[0].Network() != network0 {
		t.Fatal("did not find expected network")
	}
	if a1[0].String() != addr0 {
		t.Fatal("did not find expected addr")
	}
	if a1[1].Network() != network1 {
		t.Fatal("did not find expected network")
	}
	if a1[1].String() != addr1 {
		t.Fatal("did not find expected addr")
	}
}

func TestFlagManyDefaultValue(t *testing.T) {
	t.Parallel()
	name := genName()
	var a1 []net.Addr
	const network0 = "tcp"
	const addr0 = "127.0.0.1:1234"
	const network1 = "tcp"
	const addr1 = "127.0.0.1:5678"
	addrs.FlagManyVar(&a1, name, network0+":"+addr0+","+network1+":"+addr1, "")

	if a1[0].Network() != network0 {
		t.Fatal("did not find expected network")
	}
	if a1[0].String() != addr0 {
		t.Fatal("did not find expected addr")
	}
	if a1[1].Network() != network1 {
		t.Fatal("did not find expected network")
	}
	if a1[1].String() != addr1 {
		t.Fatal("did not find expected addr")
	}
}

func TestFlagManyInvalidDefaultValue(t *testing.T) {
	t.Parallel()
	defer func() {
		if err := recover(); err == nil {
			t.Fatal("was expecting panic")
		}
	}()
	name := genName()
	var a1 []net.Addr
	const network = "foo"
	const addr = "127.0.0.1:1234"
	addrs.FlagManyVar(&a1, name, network+":"+addr, "")
}
<|endoftext|>


<commit_before>package ai

import (
	"bytes"
	"log"
	"time"

	"github.com/nelhage/taktician/ptn"
	"github.com/nelhage/taktician/tak"
)

const (
	maxEval      int64 = 1 << 30
	minEval            = -maxEval
	winThreshold       = 1 << 29
)

type MinimaxAI struct {
	depth int

	Debug bool

	st stats
}

type stats struct {
	generated uint64
	evaluated uint64
	cutoffs   uint64
}

func formatpv(ms []tak.Move) string {
	var out bytes.Buffer
	out.WriteString("[")
	for i, m := range ms {
		if i != 0 {
			out.WriteString(" ")
		}
		out.WriteString(ptn.FormatMove(&m))
	}
	out.WriteString("]")
	return out.String()
}

func (m *MinimaxAI) GetMove(p *tak.Position) tak.Move {
	ms, _ := m.Analyze(p)
	return ms[0]
}

func (m *MinimaxAI) Analyze(p *tak.Position) ([]tak.Move, int64) {
	var ms []tak.Move
	var v int64
	top := time.Now()
	prevEval := uint64(1)
	for i := 1; i <= m.depth; i++ {
		m.st = stats{}
		start := time.Now()
		ms, v = m.minimax(p, i, ms, minEval-1, maxEval+1)
		if m.Debug {
			log.Printf("[minimax] depth=%d val=%d pv=%s time=%s total=%s evaluated=%d branch=%d",
				i, v, formatpv(ms),
				time.Now().Sub(start),
				time.Now().Sub(top),
				m.st.evaluated,
				m.st.evaluated/prevEval,
			)
		}
		prevEval = m.st.evaluated
		if v > winThreshold || v < -winThreshold {
			break
		}
	}
	return ms, v
}

func (ai *MinimaxAI) minimax(
	p *tak.Position,
	depth int,
	pv []tak.Move,
	α, β int64) ([]tak.Move, int64) {
	over, _ := p.GameOver()
	if depth == 0 || over {
		ai.st.evaluated++
		return nil, ai.evaluate(p)
	}

	if p.MoveNumber() < 2 {
		for _, c := range [][]int{{0, 0}, {p.Size() - 1, 0}, {0, p.Size() - 1}, {p.Size() - 1, p.Size() - 1}} {
			x, y := c[0], c[1]
			if len(p.At(x, y)) == 0 {
				return []tak.Move{{X: x, Y: y, Type: tak.PlaceFlat}}, 0
			}
		}
	}
	moves := p.AllMoves()
	ai.st.generated += uint64(len(moves))
	if len(pv) > 0 {
		for i, m := range moves {
			if m.Equal(&pv[0]) {
				moves[0], moves[i] = moves[i], moves[0]
				break
			}
		}
	}

	best := make([]tak.Move, 0, depth)
	max := minEval - 1
	for _, m := range moves {
		child, e := p.Move(&m)
		if e != nil {
			continue
		}
		var ms []tak.Move
		var v int64
		if len(best) == 0 {
			ms, v = ai.minimax(child, depth-1, nil, -β, -α)
		} else {
			ms, v = ai.minimax(child, depth-1, best[1:], -β, -α)
		}
		v = -v
		if v > max {
			max = v
			best = append(best[:0], m)
			best = append(best, ms...)
		}
		if v > α {
			α = v
			if α >= β {
				ai.st.cutoffs++
				break
			}
		}
	}
	return best, max
}

func imin(a, b int) int {
	if a < b {
		return a
	}
	return b
}

const (
	weightFlat       = 2
	weightCaptured   = 1
	weightControlled = 5
	weightCapstone   = -1
)

func (m *MinimaxAI) evaluate(p *tak.Position) int64 {
	if over, winner := p.GameOver(); over {
		switch winner {
		case tak.NoColor:
			return 0
		case p.ToMove():
			return maxEval - int64(p.MoveNumber())
		default:
			return minEval + int64(p.MoveNumber())
		}
	}
	mine, theirs := 0, 0
	me := p.ToMove()
	addw := func(c tak.Color, w int) {
		if c == me {
			mine += w
		} else {
			theirs += w
		}
	}
	for x := 0; x < p.Size(); x++ {
		for y := 0; y < p.Size(); y++ {
			sq := p.At(x, y)
			if len(sq) == 0 {
				continue
			}
			addw(sq[0].Color(), weightControlled)
			if sq[0].Kind() == tak.Capstone {
				addw(sq[0].Color(), weightCapstone)
			}
			for i, stone := range sq {
				if i > 0 && i < p.Size() {
					addw(sq[0].Color(), weightCaptured)
				}
				if stone.Kind() == tak.Flat {
					addw(stone.Color(), weightFlat)
				}
			}
		}
	}

	return int64(mine - theirs)
}

func NewMinimax(depth int) *MinimaxAI {
	return &MinimaxAI{depth: depth}
}
<commit_msg>fix divide-by-0<commit_after>package ai

import (
	"bytes"
	"log"
	"time"

	"github.com/nelhage/taktician/ptn"
	"github.com/nelhage/taktician/tak"
)

const (
	maxEval      int64 = 1 << 30
	minEval            = -maxEval
	winThreshold       = 1 << 29
)

type MinimaxAI struct {
	depth int

	Debug bool

	st stats
}

type stats struct {
	generated uint64
	evaluated uint64
	cutoffs   uint64
}

func formatpv(ms []tak.Move) string {
	var out bytes.Buffer
	out.WriteString("[")
	for i, m := range ms {
		if i != 0 {
			out.WriteString(" ")
		}
		out.WriteString(ptn.FormatMove(&m))
	}
	out.WriteString("]")
	return out.String()
}

func (m *MinimaxAI) GetMove(p *tak.Position) tak.Move {
	ms, _ := m.Analyze(p)
	return ms[0]
}

func (m *MinimaxAI) Analyze(p *tak.Position) ([]tak.Move, int64) {
	var ms []tak.Move
	var v int64
	top := time.Now()
	var prevEval uint64
	for i := 1; i <= m.depth; i++ {
		m.st = stats{}
		start := time.Now()
		ms, v = m.minimax(p, i, ms, minEval-1, maxEval+1)
		if m.Debug {
			log.Printf("[minimax] depth=%d val=%d pv=%s time=%s total=%s evaluated=%d branch=%d",
				i, v, formatpv(ms),
				time.Now().Sub(start),
				time.Now().Sub(top),
				m.st.evaluated,
				m.st.evaluated/(prevEval+1),
			)
		}
		prevEval = m.st.evaluated
		if v > winThreshold || v < -winThreshold {
			break
		}
	}
	return ms, v
}

func (ai *MinimaxAI) minimax(
	p *tak.Position,
	depth int,
	pv []tak.Move,
	α, β int64) ([]tak.Move, int64) {
	over, _ := p.GameOver()
	if depth == 0 || over {
		ai.st.evaluated++
		return nil, ai.evaluate(p)
	}

	if p.MoveNumber() < 2 {
		for _, c := range [][]int{{0, 0}, {p.Size() - 1, 0}, {0, p.Size() - 1}, {p.Size() - 1, p.Size() - 1}} {
			x, y := c[0], c[1]
			if len(p.At(x, y)) == 0 {
				return []tak.Move{{X: x, Y: y, Type: tak.PlaceFlat}}, 0
			}
		}
	}
	moves := p.AllMoves()
	ai.st.generated += uint64(len(moves))
	if len(pv) > 0 {
		for i, m := range moves {
			if m.Equal(&pv[0]) {
				moves[0], moves[i] = moves[i], moves[0]
				break
			}
		}
	}

	best := make([]tak.Move, 0, depth)
	max := minEval - 1
	for _, m := range moves {
		child, e := p.Move(&m)
		if e != nil {
			continue
		}
		var ms []tak.Move
		var v int64
		if len(best) == 0 {
			ms, v = ai.minimax(child, depth-1, nil, -β, -α)
		} else {
			ms, v = ai.minimax(child, depth-1, best[1:], -β, -α)
		}
		v = -v
		if v > max {
			max = v
			best = append(best[:0], m)
			best = append(best, ms...)
		}
		if v > α {
			α = v
			if α >= β {
				ai.st.cutoffs++
				break
			}
		}
	}
	return best, max
}

func imin(a, b int) int {
	if a < b {
		return a
	}
	return b
}

const (
	weightFlat       = 2
	weightCaptured   = 1
	weightControlled = 5
	weightCapstone   = -1
)

func (m *MinimaxAI) evaluate(p *tak.Position) int64 {
	if over, winner := p.GameOver(); over {
		switch winner {
		case tak.NoColor:
			return 0
		case p.ToMove():
			return maxEval - int64(p.MoveNumber())
		default:
			return minEval + int64(p.MoveNumber())
		}
	}
	mine, theirs := 0, 0
	me := p.ToMove()
	addw := func(c tak.Color, w int) {
		if c == me {
			mine += w
		} else {
			theirs += w
		}
	}
	for x := 0; x < p.Size(); x++ {
		for y := 0; y < p.Size(); y++ {
			sq := p.At(x, y)
			if len(sq) == 0 {
				continue
			}
			addw(sq[0].Color(), weightControlled)
			if sq[0].Kind() == tak.Capstone {
				addw(sq[0].Color(), weightCapstone)
			}
			for i, stone := range sq {
				if i > 0 && i < p.Size() {
					addw(sq[0].Color(), weightCaptured)
				}
				if stone.Kind() == tak.Flat {
					addw(stone.Color(), weightFlat)
				}
			}
		}
	}

	return int64(mine - theirs)
}

func NewMinimax(depth int) *MinimaxAI {
	return &MinimaxAI{depth: depth}
}
<|endoftext|>


<commit_before>package api

import (
	"encoding/json"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/tdewolff/minify"
	"github.com/tdewolff/minify/css"
	"github.com/tdewolff/minify/html"
	"github.com/tdewolff/minify/js"
	jm "github.com/tdewolff/minify/json"

	"strings"

	"io/ioutil"

	"github.com/mundipagg/boleto-api/bank"
	"github.com/mundipagg/boleto-api/boleto"
	"github.com/mundipagg/boleto-api/config"
	"github.com/mundipagg/boleto-api/db"
	"github.com/mundipagg/boleto-api/log"
	"github.com/mundipagg/boleto-api/models"
)

//Regista um boleto em um determinado banco
func registerBoleto(c *gin.Context) {

	if _, hasErr := c.Get("error"); hasErr {
		return
	}
	_boleto, _ := c.Get("boleto")
	_bank, _ := c.Get("bank")
	bol := _boleto.(models.BoletoRequest)
	bank := _bank.(bank.Bank)
	lg := bank.Log()
	lg.Operation = "RegisterBoleto"
	lg.NossoNumero = bol.Title.OurNumber
	lg.Recipient = bol.Recipient.Name
	lg.RequestKey = bol.RequestKey
	lg.BankName = bank.GetBankNameIntegration()

	resp, err := bank.ProcessBoleto(&bol)
	if checkError(c, err, lg) {
		return
	}

	st := http.StatusOK
	if len(resp.Errors) > 0 {

		if resp.StatusCode > 0 {
			st = resp.StatusCode
		} else {
			st = http.StatusBadRequest
		}

	} else {
		mongo, errMongo := db.CreateMongo(lg)

		boView := models.NewBoletoView(bol, resp, bank.GetBankNameIntegration())
		mID, _ := boView.ID.MarshalText()
		resp.ID = string(mID)
		resp.Links = boView.Links

		if errMongo == nil {
			errMongo = mongo.SaveBoleto(boView)
		}

		redis := db.CreateRedis()

		if errMongo != nil {
			b := minifyJSON(boView)

			err = redis.SetBoletoJSON(b, resp.ID, lg)
			if checkError(c, err, lg) {
				return
			}
		}

		bhtml, _ := boleto.HTML(boView, "html")
		s := minifyString(bhtml, "text/html")
		redis.SetBoletoHTML(s, resp.ID, lg)

	}
	c.JSON(st, resp)
	c.Set("boletoResponse", resp)
}

func getBoleto(c *gin.Context) {
	c.Status(200)

	id := c.Query("id")
	fmt := c.Query("fmt")

	log := log.CreateLog()
	log.Operation = "GetBoleto"

	redis := db.CreateRedis()

	b := redis.GetBoletoHTMLByID(id, log)

	if b == "" {
		mongo, errMongo := db.CreateMongo(log)
		if checkError(c, errMongo, log) {
			return
		}

		boView, err := mongo.GetBoletoByID(id)
		if checkError(c, err, log) {
			return
		}

		bhtml, err := boleto.HTML(boView, "html")
		b = minifyString(bhtml, "text/html")

		redis.SetBoletoHTML(b, id, log)
	}

	if fmt == "html" {
		c.Header("Content-Type", "text/html; charset=utf-8")
		c.Writer.WriteString(b)
	} else {
		c.Header("Content-Type", "application/pdf")
		bpdf, err := toPdf(b)

		if err != nil {
			c.Header("Content-Type", "application/json")
			checkError(c, models.NewInternalServerError(err.Error(), "internal error"), log)
			c.Abort()
		} else {
			c.Writer.Write(bpdf)
		}

	}

}

func toPdf(page string) ([]byte, error) {
	url := config.Get().PdfAPIURL
	payload := strings.NewReader(page)
	if req, err := http.NewRequest("POST", url, payload); err != nil {
		return nil, err
	} else if res, err := http.DefaultClient.Do(req); err != nil {
		return nil, err
	} else {
		defer res.Body.Close()
		return ioutil.ReadAll(res.Body)
	}
}

func getBoletoByID(c *gin.Context) {
	id := c.Param("id")
	log := log.CreateLog()
	log.Operation = "GetBoletoV1"

	mongo, errDb := db.CreateMongo(log)
	if errDb != nil {
		checkError(c, models.NewInternalServerError("MP500", "Erro interno"), log)
	}
	boleto, err := mongo.GetBoletoByID(id)
	if err != nil {
		checkError(c, models.NewHTTPNotFound("MP404", "Boleto não encontrado"), nil)
		return
	}
	c.JSON(http.StatusOK, boleto)
}

//minifyJSON converte um model BoletoView para um JSON/STRING
func minifyJSON(m models.BoletoView) string {
	j, _ := json.Marshal(m)

	return minifyString(string(j), "application/json")
}

func minifyString(mString, tp string) string {
	m := minify.New()
	m.Add("text/html", &html.Minifier{
		KeepDocumentTags:        true,
		KeepEndTags:             true,
		KeepWhitespace:          false,
		KeepConditionalComments: true,
	})
	m.AddFunc("text/css", css.Minify)
	m.AddFunc("text/javascript", js.Minify)
	m.AddFunc("application/json", jm.Minify)

	s, err := m.String(tp, mString)

	if err != nil {
		return mString
	} else {
		return s
	}
}
<commit_msg>:sparkles: Remove segundo cache<commit_after>package api

import (
	"encoding/json"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/tdewolff/minify"
	"github.com/tdewolff/minify/css"
	"github.com/tdewolff/minify/html"
	"github.com/tdewolff/minify/js"
	jm "github.com/tdewolff/minify/json"

	"strings"

	"io/ioutil"

	"github.com/mundipagg/boleto-api/bank"
	"github.com/mundipagg/boleto-api/boleto"
	"github.com/mundipagg/boleto-api/config"
	"github.com/mundipagg/boleto-api/db"
	"github.com/mundipagg/boleto-api/log"
	"github.com/mundipagg/boleto-api/models"
)

//Regista um boleto em um determinado banco
func registerBoleto(c *gin.Context) {

	if _, hasErr := c.Get("error"); hasErr {
		return
	}
	_boleto, _ := c.Get("boleto")
	_bank, _ := c.Get("bank")
	bol := _boleto.(models.BoletoRequest)
	bank := _bank.(bank.Bank)
	lg := bank.Log()
	lg.Operation = "RegisterBoleto"
	lg.NossoNumero = bol.Title.OurNumber
	lg.Recipient = bol.Recipient.Name
	lg.RequestKey = bol.RequestKey
	lg.BankName = bank.GetBankNameIntegration()

	resp, err := bank.ProcessBoleto(&bol)
	if checkError(c, err, lg) {
		return
	}

	st := http.StatusOK
	if len(resp.Errors) > 0 {

		if resp.StatusCode > 0 {
			st = resp.StatusCode
		} else {
			st = http.StatusBadRequest
		}

	} else {
		mongo, errMongo := db.CreateMongo(lg)

		boView := models.NewBoletoView(bol, resp, bank.GetBankNameIntegration())
		mID, _ := boView.ID.MarshalText()
		resp.ID = string(mID)
		resp.Links = boView.Links

		if errMongo == nil {
			errMongo = mongo.SaveBoleto(boView)
		}

		redis := db.CreateRedis()

		if errMongo != nil {
			b := minifyJSON(boView)

			err = redis.SetBoletoJSON(b, resp.ID, lg)
			if checkError(c, err, lg) {
				return
			}
		}

		bhtml, _ := boleto.HTML(boView, "html")
		s := minifyString(bhtml, "text/html")
		redis.SetBoletoHTML(s, resp.ID, lg)

	}
	c.JSON(st, resp)
	c.Set("boletoResponse", resp)
}

func getBoleto(c *gin.Context) {
	c.Status(200)

	id := c.Query("id")
	fmt := c.Query("fmt")

	log := log.CreateLog()
	log.Operation = "GetBoleto"

	redis := db.CreateRedis()

	b := redis.GetBoletoHTMLByID(id, log)

	if b == "" {
		mongo, errMongo := db.CreateMongo(log)
		if checkError(c, errMongo, log) {
			return
		}

		boView, err := mongo.GetBoletoByID(id)
		if checkError(c, err, log) {
			return
		}

		bhtml, err := boleto.HTML(boView, "html")
		b = minifyString(bhtml, "text/html")
	}

	if fmt == "html" {
		c.Header("Content-Type", "text/html; charset=utf-8")
		c.Writer.WriteString(b)
	} else {
		c.Header("Content-Type", "application/pdf")
		bpdf, err := toPdf(b)

		if err != nil {
			c.Header("Content-Type", "application/json")
			checkError(c, models.NewInternalServerError(err.Error(), "internal error"), log)
			c.Abort()
		} else {
			c.Writer.Write(bpdf)
		}

	}

}

func toPdf(page string) ([]byte, error) {
	url := config.Get().PdfAPIURL
	payload := strings.NewReader(page)
	if req, err := http.NewRequest("POST", url, payload); err != nil {
		return nil, err
	} else if res, err := http.DefaultClient.Do(req); err != nil {
		return nil, err
	} else {
		defer res.Body.Close()
		return ioutil.ReadAll(res.Body)
	}
}

func getBoletoByID(c *gin.Context) {
	id := c.Param("id")
	log := log.CreateLog()
	log.Operation = "GetBoletoV1"

	mongo, errDb := db.CreateMongo(log)
	if errDb != nil {
		checkError(c, models.NewInternalServerError("MP500", "Erro interno"), log)
	}
	boleto, err := mongo.GetBoletoByID(id)
	if err != nil {
		checkError(c, models.NewHTTPNotFound("MP404", "Boleto não encontrado"), nil)
		return
	}
	c.JSON(http.StatusOK, boleto)
}

//minifyJSON converte um model BoletoView para um JSON/STRING
func minifyJSON(m models.BoletoView) string {
	j, _ := json.Marshal(m)

	return minifyString(string(j), "application/json")
}

func minifyString(mString, tp string) string {
	m := minify.New()
	m.Add("text/html", &html.Minifier{
		KeepDocumentTags:        true,
		KeepEndTags:             true,
		KeepWhitespace:          false,
		KeepConditionalComments: true,
	})
	m.AddFunc("text/css", css.Minify)
	m.AddFunc("text/javascript", js.Minify)
	m.AddFunc("application/json", jm.Minify)

	s, err := m.String(tp, mString)

	if err != nil {
		return mString
	} else {
		return s
	}
}
<|endoftext|>


<commit_before>package api

import (
	"fmt"
	"net/http"
	"os"
	"strings"

	"github.com/ansible-semaphore/semaphore/api/projects"
	"github.com/ansible-semaphore/semaphore/api/sockets"
	"github.com/ansible-semaphore/semaphore/api/tasks"

	"github.com/ansible-semaphore/semaphore/util"
	"github.com/gobuffalo/packr"
	"github.com/gorilla/mux"
	"github.com/russross/blackfriday"
)

var publicAssets = packr.NewBox("../web/public")

//JSONMiddleware ensures that all the routes respond with Json, this is added by default to all routes
func JSONMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("content-type", "application/json")
		next.ServeHTTP(w, r)
	})
}

//plainTextMiddleware resets headers to Plain Text if needed
func plainTextMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("content-type", "text/plain; charset=utf-8")
		next.ServeHTTP(w, r)
	})
}

func pongHandler(w http.ResponseWriter, r *http.Request) {
	w.Write([]byte("pong"))
}

func notFoundHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Access-Control-Allow-Origin", r.Header.Get("Origin"))
	w.Header().Set("Access-Control-Allow-Credentials", "true")
	w.WriteHeader(http.StatusNotFound)
	w.Write([]byte("404 not found"))
	fmt.Println(r.Method, ":", r.URL.String(), "--> 404 Not Found")
}

// Route declares all routes
func Route() *mux.Router {
	r := mux.NewRouter().StrictSlash(true)
	r.NotFoundHandler = http.HandlerFunc(servePublic)

	webPath := "/"
	if util.WebHostURL != nil {
		r.Host(util.WebHostURL.Hostname())
		webPath = util.WebHostURL.Path
	}

	r.Use(mux.CORSMethodMiddleware(r))

	pingRouter := r.Path(webPath + "api/ping").Subrouter()
	pingRouter.Use(plainTextMiddleware)
	pingRouter.Methods("GET", "HEAD").HandlerFunc(pongHandler)

	publicAPIRouter := r.PathPrefix(webPath + "api").Subrouter()
	publicAPIRouter.Use(JSONMiddleware)

	publicAPIRouter.HandleFunc("/auth/login", login).Methods("POST")
	publicAPIRouter.HandleFunc("/auth/logout", logout).Methods("POST")

	authenticatedAPI := r.PathPrefix(webPath + "api").Subrouter()
	authenticatedAPI.Use(JSONMiddleware, authentication)

	authenticatedAPI.Path("/ws").HandlerFunc(sockets.Handler).Methods("GET", "HEAD")
	authenticatedAPI.Path("/info").HandlerFunc(getSystemInfo).Methods("GET", "HEAD")
	authenticatedAPI.Path("/upgrade").HandlerFunc(checkUpgrade).Methods("GET", "HEAD")
	authenticatedAPI.Path("/upgrade").HandlerFunc(doUpgrade).Methods("POST")

	authenticatedAPI.Path("/projects").HandlerFunc(projects.GetProjects).Methods("GET", "HEAD")
	authenticatedAPI.Path("/projects").HandlerFunc(projects.AddProject).Methods("POST")
	authenticatedAPI.Path("/events").HandlerFunc(getAllEvents).Methods("GET", "HEAD")
	authenticatedAPI.HandleFunc("/events/last", getLastEvents).Methods("GET", "HEAD")

	authenticatedAPI.Path("/users").HandlerFunc(getUsers).Methods("GET", "HEAD")
	authenticatedAPI.Path("/users").HandlerFunc(addUser).Methods("POST")

	tokenAPI := authenticatedAPI.PathPrefix("/user").Subrouter()

	tokenAPI.Path("/").HandlerFunc(getUser).Methods("GET", "HEAD")
	tokenAPI.Path("/tokens").HandlerFunc(getAPITokens).Methods("GET", "HEAD")
	tokenAPI.Path("/tokens").HandlerFunc(createAPIToken).Methods("POST")
	tokenAPI.HandleFunc("/tokens/{token_id}", expireAPIToken).Methods("DELETE")

	userAPI := authenticatedAPI.PathPrefix("/users/{user_id}").Subrouter()
	userAPI.Use(getUserMiddleware)

	userAPI.Path("/").HandlerFunc(getUser).Methods("GET", "HEAD")
	userAPI.Path("/").HandlerFunc(updateUser).Methods("PUT")
	userAPI.Path("/").HandlerFunc(deleteUser).Methods("DELETE")
	userAPI.Path("/password").HandlerFunc(updateUserPassword).Methods("POST")

	projectUserAPI := authenticatedAPI.PathPrefix("/project/{project_id}").Subrouter()
	projectUserAPI.Use(projects.ProjectMiddleware)

	projectUserAPI.Path("/").HandlerFunc(projects.GetProject).Methods("GET", "HEAD")
	projectUserAPI.Path("/events").HandlerFunc(getAllEvents).Methods("GET", "HEAD")
	projectUserAPI.HandleFunc("/events/last", getLastEvents).Methods("GET", "HEAD")

	projectUserAPI.Path("/users").HandlerFunc(projects.GetUsers).Methods("GET", "HEAD")

	projectUserAPI.Path("/keys").HandlerFunc(projects.GetKeys).Methods("GET", "HEAD")
	projectUserAPI.Path("/keys").HandlerFunc(projects.AddKey).Methods("POST")

	projectUserAPI.Path("/repositories").HandlerFunc(projects.GetRepositories).Methods("GET", "HEAD")
	projectUserAPI.Path("/repositories").HandlerFunc(projects.AddRepository).Methods("POST")

	projectUserAPI.Path("/inventory").HandlerFunc(projects.GetInventory).Methods("GET", "HEAD")
	projectUserAPI.Path("/inventory").HandlerFunc(projects.AddInventory).Methods("POST")

	projectUserAPI.Path("/environment").HandlerFunc(projects.GetEnvironment).Methods("GET", "HEAD")
	projectUserAPI.Path("/environment").HandlerFunc(projects.AddEnvironment).Methods("POST")

	projectUserAPI.Path("/tasks").HandlerFunc(tasks.GetAllTasks).Methods("GET", "HEAD")
	projectUserAPI.HandleFunc("/tasks/last", tasks.GetLastTasks).Methods("GET", "HEAD")
	projectUserAPI.Path("/tasks").HandlerFunc(tasks.AddTask).Methods("POST")

	projectUserAPI.Path("/templates").HandlerFunc(projects.GetTemplates).Methods("GET", "HEAD")
	projectUserAPI.Path("/templates").HandlerFunc(projects.AddTemplate).Methods("POST")

	projectAdminAPI := authenticatedAPI.PathPrefix("/project/{project_id}").Subrouter()
	projectAdminAPI.Use(projects.ProjectMiddleware, projects.MustBeAdmin)

	projectAdminAPI.Path("/").HandlerFunc(projects.UpdateProject).Methods("PUT")
	projectAdminAPI.Path("/").HandlerFunc(projects.DeleteProject).Methods("DELETE")
	projectAdminAPI.Path("/users").HandlerFunc(projects.AddUser).Methods("POST")

	projectUserManagement := projectAdminAPI.PathPrefix("/users").Subrouter()
	projectUserManagement.Use(projects.UserMiddleware)

	projectUserManagement.HandleFunc("/{user_id}/admin", projects.MakeUserAdmin).Methods("POST")
	projectUserManagement.HandleFunc("/{user_id}/admin", projects.MakeUserAdmin).Methods("DELETE")
	projectUserManagement.HandleFunc("/{user_id}", projects.RemoveUser).Methods("DELETE")

	projectKeyManagement := projectUserAPI.PathPrefix("/keys").Subrouter()
	projectKeyManagement.Use(projects.KeyMiddleware)

	projectKeyManagement.HandleFunc("/keys/{key_id}", projects.UpdateKey).Methods("PUT")
	projectKeyManagement.HandleFunc("/keys/{key_id}", projects.RemoveKey).Methods("DELETE")

	projectRepoManagement := projectUserAPI.PathPrefix("/repositories").Subrouter()
	projectRepoManagement.Use(projects.RepositoryMiddleware)

	projectRepoManagement.HandleFunc("/repositories/{repository_id}", projects.UpdateRepository).Methods("PUT")
	projectRepoManagement.HandleFunc("/repositories/{repository_id}", projects.RemoveRepository).Methods("DELETE")

	projectInventoryManagement := projectUserAPI.PathPrefix("/inventory").Subrouter()
	projectInventoryManagement.Use(projects.InventoryMiddleware)

	projectInventoryManagement.HandleFunc("/inventory/{inventory_id}", projects.UpdateInventory).Methods("PUT")
	projectInventoryManagement.HandleFunc("/inventory/{inventory_id}", projects.RemoveInventory).Methods("DELETE")

	projectEnvManagement := projectUserAPI.PathPrefix("/environment").Subrouter()
	projectEnvManagement.Use(projects.EnvironmentMiddleware)

	projectEnvManagement.HandleFunc("/environment/{environment_id}", projects.UpdateEnvironment).Methods("PUT")
	projectEnvManagement.HandleFunc("/environment/{environment_id}", projects.RemoveEnvironment).Methods("DELETE")

	projectTmplManagement := projectUserAPI.PathPrefix("/templates").Subrouter()
	projectTmplManagement.Use(projects.TemplatesMiddleware)

	projectTmplManagement.HandleFunc("/templates/{template_id}", projects.UpdateTemplate).Methods("PUT")
	projectTmplManagement.HandleFunc("/templates/{template_id}", projects.RemoveTemplate).Methods("DELETE")

	projectTaskManagement := projectUserAPI.PathPrefix("/tasks").Subrouter()
	projectTaskManagement.Use(tasks.GetTaskMiddleware)

	projectTaskManagement.HandleFunc("/tasks/{task_id}/output", tasks.GetTaskOutput).Methods("GET", "HEAD")
	projectTaskManagement.HandleFunc("/tasks/{task_id}", tasks.GetTask).Methods("GET", "HEAD")
	projectTaskManagement.HandleFunc("/tasks/{task_id}", tasks.RemoveTask).Methods("DELETE")

	if os.Getenv("DEBUG") == "1" {
		defer debugPrintRoutes(r)
	}

	return r
}

func debugPrintRoutes(r *mux.Router) {
	err := r.Walk(func(route *mux.Route, router *mux.Router, ancestors []*mux.Route) error {
		pathTemplate, err := route.GetPathTemplate()
		if err == nil {
			fmt.Println("ROUTE:", pathTemplate)
		}
		pathRegexp, err := route.GetPathRegexp()
		if err == nil {
			fmt.Println("Path regexp:", pathRegexp)
		}
		queriesTemplates, err := route.GetQueriesTemplates()
		if err == nil {
			fmt.Println("Queries templates:", strings.Join(queriesTemplates, ","))
		}
		queriesRegexps, err := route.GetQueriesRegexp()
		if err == nil {
			fmt.Println("Queries regexps:", strings.Join(queriesRegexps, ","))
		}
		methods, err := route.GetMethods()
		if err == nil {
			fmt.Println("Methods:", strings.Join(methods, ","))
		}
		fmt.Println()
		return nil
	})

	if err != nil {
		fmt.Println(err)
	}
}

//nolint: gocyclo
func servePublic(w http.ResponseWriter, r *http.Request) {
	path := r.URL.Path

	webPath := "/"
	if util.WebHostURL != nil {
		webPath = util.WebHostURL.RequestURI()
	}

	if !strings.HasPrefix(path, webPath+"public") {
		if len(strings.Split(path, ".")) > 1 {
			w.WriteHeader(http.StatusNotFound)
			return
		}

		path = "/html/index.html"
	}

	path = strings.Replace(path, webPath+"public/", "", 1)
	split := strings.Split(path, ".")
	suffix := split[len(split)-1]

	res, err := publicAssets.MustBytes(path)
	if err != nil {
		notFoundHandler(w, r)
		return
	}

	// replace base path
	if util.WebHostURL != nil && path == "/html/index.html" {
		res = []byte(strings.Replace(string(res),
			"<base href=\"/\">",
			"<base href=\""+util.WebHostURL.String()+"\">",
			1))
	}

	contentType := "text/plain"
	switch suffix {
	case "png":
		contentType = "image/png"
	case "jpg", "jpeg":
		contentType = "image/jpeg"
	case "gif":
		contentType = "image/gif"
	case "js":
		contentType = "application/javascript"
	case "css":
		contentType = "text/css"
	case "woff":
		contentType = "application/x-font-woff"
	case "ttf":
		contentType = "application/x-font-ttf"
	case "otf":
		contentType = "application/x-font-otf"
	case "html":
		contentType = "text/html"
	}

	w.Header().Set("content-type", contentType)
	_, err = w.Write(res)
	util.LogWarning(err)
}

func getSystemInfo(w http.ResponseWriter, r *http.Request) {
	body := map[string]interface{}{
		"version": util.Version,
		"update":  util.UpdateAvailable,
		"config": map[string]string{
			"dbHost":  util.Config.MySQL.Hostname,
			"dbName":  util.Config.MySQL.DbName,
			"dbUser":  util.Config.MySQL.Username,
			"path":    util.Config.TmpPath,
			"cmdPath": util.FindSemaphore(),
		},
	}

	if util.UpdateAvailable != nil {
		body["updateBody"] = string(blackfriday.MarkdownCommon([]byte(*util.UpdateAvailable.Body)))
	}

	util.WriteJSON(w, http.StatusOK, body)
}

func checkUpgrade(w http.ResponseWriter, r *http.Request) {
	if err := util.CheckUpdate(util.Version); err != nil {
		util.WriteJSON(w, 500, err)
		return
	}

	if util.UpdateAvailable != nil {
		getSystemInfo(w, r)
		return
	}

	w.WriteHeader(http.StatusNoContent)
}

func doUpgrade(w http.ResponseWriter, r *http.Request) {
	util.LogError(util.DoUpgrade(util.Version))
}
<commit_msg>Update router.go<commit_after>package api

import (
	"fmt"
	"net/http"
	"os"
	"strings"

	"github.com/ansible-semaphore/semaphore/api/projects"
	"github.com/ansible-semaphore/semaphore/api/sockets"
	"github.com/ansible-semaphore/semaphore/api/tasks"

	"github.com/ansible-semaphore/semaphore/util"
	"github.com/gobuffalo/packr"
	"github.com/gorilla/mux"
	"github.com/russross/blackfriday"
)

var publicAssets = packr.NewBox("../web/public")

//JSONMiddleware ensures that all the routes respond with Json, this is added by default to all routes
func JSONMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("content-type", "application/json")
		next.ServeHTTP(w, r)
	})
}

//plainTextMiddleware resets headers to Plain Text if needed
func plainTextMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("content-type", "text/plain; charset=utf-8")
		next.ServeHTTP(w, r)
	})
}

func pongHandler(w http.ResponseWriter, r *http.Request) {
	w.Write([]byte("pong"))
}

func notFoundHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Access-Control-Allow-Origin", r.Header.Get("Origin"))
	w.Header().Set("Access-Control-Allow-Credentials", "true")
	w.WriteHeader(http.StatusNotFound)
	w.Write([]byte("404 not found"))
	fmt.Println(r.Method, ":", r.URL.String(), "--> 404 Not Found")
}

// Route declares all routes
func Route() *mux.Router {
	r := mux.NewRouter().StrictSlash(true)
	r.NotFoundHandler = http.HandlerFunc(servePublic)

	webPath := "/"
	if util.WebHostURL != nil {
		r.Host(util.WebHostURL.Hostname())
		webPath = util.WebHostURL.Path
	}

	r.Use(mux.CORSMethodMiddleware(r))

	pingRouter := r.Path(webPath + "api/ping").Subrouter()
	pingRouter.Use(plainTextMiddleware)
	pingRouter.Methods("GET", "HEAD").HandlerFunc(pongHandler)

	publicAPIRouter := r.PathPrefix(webPath + "api").Subrouter()
	publicAPIRouter.Use(JSONMiddleware)

	publicAPIRouter.HandleFunc("/auth/login", login).Methods("POST")
	publicAPIRouter.HandleFunc("/auth/logout", logout).Methods("POST")

	authenticatedAPI := r.PathPrefix(webPath + "api").Subrouter()
	authenticatedAPI.Use(JSONMiddleware, authentication)

	authenticatedAPI.Path("/ws").HandlerFunc(sockets.Handler).Methods("GET", "HEAD")
	authenticatedAPI.Path("/info").HandlerFunc(getSystemInfo).Methods("GET", "HEAD")
	authenticatedAPI.Path("/upgrade").HandlerFunc(checkUpgrade).Methods("GET", "HEAD")
	authenticatedAPI.Path("/upgrade").HandlerFunc(doUpgrade).Methods("POST")

	authenticatedAPI.Path("/projects").HandlerFunc(projects.GetProjects).Methods("GET", "HEAD")
	authenticatedAPI.Path("/projects").HandlerFunc(projects.AddProject).Methods("POST")
	authenticatedAPI.Path("/events").HandlerFunc(getAllEvents).Methods("GET", "HEAD")
	authenticatedAPI.HandleFunc("/events/last", getLastEvents).Methods("GET", "HEAD")

	authenticatedAPI.Path("/users").HandlerFunc(getUsers).Methods("GET", "HEAD")
	authenticatedAPI.Path("/users").HandlerFunc(addUser).Methods("POST")

	tokenAPI := authenticatedAPI.PathPrefix("/user").Subrouter()

	tokenAPI.Path("/").HandlerFunc(getUser).Methods("GET", "HEAD")
	tokenAPI.Path("/tokens").HandlerFunc(getAPITokens).Methods("GET", "HEAD")
	tokenAPI.Path("/tokens").HandlerFunc(createAPIToken).Methods("POST")
	tokenAPI.HandleFunc("/tokens/{token_id}", expireAPIToken).Methods("DELETE")

	userAPI := authenticatedAPI.PathPrefix("/users/{user_id}").Subrouter()
	userAPI.Use(getUserMiddleware)

	userAPI.Path("/").HandlerFunc(getUser).Methods("GET", "HEAD")
	userAPI.Path("/").HandlerFunc(updateUser).Methods("PUT")
	userAPI.Path("/").HandlerFunc(deleteUser).Methods("DELETE")
	userAPI.Path("/password").HandlerFunc(updateUserPassword).Methods("POST")

	projectUserAPI := authenticatedAPI.PathPrefix("/project/{project_id}").Subrouter()
	projectUserAPI.Use(projects.ProjectMiddleware)

	projectUserAPI.Path("/").HandlerFunc(projects.GetProject).Methods("GET", "HEAD")
	projectUserAPI.Path("/events").HandlerFunc(getAllEvents).Methods("GET", "HEAD")
	projectUserAPI.HandleFunc("/events/last", getLastEvents).Methods("GET", "HEAD")

	projectUserAPI.Path("/users").HandlerFunc(projects.GetUsers).Methods("GET", "HEAD")

	projectUserAPI.Path("/keys").HandlerFunc(projects.GetKeys).Methods("GET", "HEAD")
	projectUserAPI.Path("/keys").HandlerFunc(projects.AddKey).Methods("POST")

	projectUserAPI.Path("/repositories").HandlerFunc(projects.GetRepositories).Methods("GET", "HEAD")
	projectUserAPI.Path("/repositories").HandlerFunc(projects.AddRepository).Methods("POST")

	projectUserAPI.Path("/inventory").HandlerFunc(projects.GetInventory).Methods("GET", "HEAD")
	projectUserAPI.Path("/inventory").HandlerFunc(projects.AddInventory).Methods("POST")

	projectUserAPI.Path("/environment").HandlerFunc(projects.GetEnvironment).Methods("GET", "HEAD")
	projectUserAPI.Path("/environment").HandlerFunc(projects.AddEnvironment).Methods("POST")

	projectUserAPI.Path("/tasks").HandlerFunc(tasks.GetAllTasks).Methods("GET", "HEAD")
	projectUserAPI.HandleFunc("/tasks/last", tasks.GetLastTasks).Methods("GET", "HEAD")
	projectUserAPI.Path("/tasks").HandlerFunc(tasks.AddTask).Methods("POST")

	projectUserAPI.Path("/templates").HandlerFunc(projects.GetTemplates).Methods("GET", "HEAD")
	projectUserAPI.Path("/templates").HandlerFunc(projects.AddTemplate).Methods("POST")

	projectAdminAPI := authenticatedAPI.PathPrefix("/project/{project_id}").Subrouter()
	projectAdminAPI.Use(projects.ProjectMiddleware, projects.MustBeAdmin)

	projectAdminAPI.Path("/").HandlerFunc(projects.UpdateProject).Methods("PUT")
	projectAdminAPI.Path("/").HandlerFunc(projects.DeleteProject).Methods("DELETE")
	projectAdminAPI.Path("/users").HandlerFunc(projects.AddUser).Methods("POST")

	projectUserManagement := projectAdminAPI.PathPrefix("/users").Subrouter()
	projectUserManagement.Use(projects.UserMiddleware)

	projectUserManagement.HandleFunc("/{user_id}/admin", projects.MakeUserAdmin).Methods("POST")
	projectUserManagement.HandleFunc("/{user_id}/admin", projects.MakeUserAdmin).Methods("DELETE")
	projectUserManagement.HandleFunc("/{user_id}", projects.RemoveUser).Methods("DELETE")

	projectKeyManagement := projectAdminAPI.PathPrefix("/keys").Subrouter()
	projectKeyManagement.Use(projects.KeyMiddleware)

	projectKeyManagement.HandleFunc("/{key_id}", projects.UpdateKey).Methods("PUT")
	projectKeyManagement.HandleFunc("/{key_id}", projects.RemoveKey).Methods("DELETE")

	projectRepoManagement := projectUserAPI.PathPrefix("/repositories").Subrouter()
	projectRepoManagement.Use(projects.RepositoryMiddleware)

	projectRepoManagement.HandleFunc("/{repository_id}", projects.UpdateRepository).Methods("PUT")
	projectRepoManagement.HandleFunc("/{repository_id}", projects.RemoveRepository).Methods("DELETE")

	projectInventoryManagement := projectUserAPI.PathPrefix("/inventory").Subrouter()
	projectInventoryManagement.Use(projects.InventoryMiddleware)

	projectInventoryManagement.HandleFunc("/{inventory_id}", projects.UpdateInventory).Methods("PUT")
	projectInventoryManagement.HandleFunc("/{inventory_id}", projects.RemoveInventory).Methods("DELETE")

	projectEnvManagement := projectUserAPI.PathPrefix("/environment").Subrouter()
	projectEnvManagement.Use(projects.EnvironmentMiddleware)

	projectEnvManagement.HandleFunc("/{environment_id}", projects.UpdateEnvironment).Methods("PUT")
	projectEnvManagement.HandleFunc("/{environment_id}", projects.RemoveEnvironment).Methods("DELETE")

	projectTmplManagement := projectUserAPI.PathPrefix("/templates").Subrouter()
	projectTmplManagement.Use(projects.TemplatesMiddleware)

	projectTmplManagement.HandleFunc("/{template_id}", projects.UpdateTemplate).Methods("PUT")
	projectTmplManagement.HandleFunc("/{template_id}", projects.RemoveTemplate).Methods("DELETE")

	projectTaskManagement := projectUserAPI.PathPrefix("/tasks").Subrouter()
	projectTaskManagement.Use(tasks.GetTaskMiddleware)

	projectTaskManagement.HandleFunc("/{task_id}/output", tasks.GetTaskOutput).Methods("GET", "HEAD")
	projectTaskManagement.HandleFunc("/{task_id}", tasks.GetTask).Methods("GET", "HEAD")
	projectTaskManagement.HandleFunc("/{task_id}", tasks.RemoveTask).Methods("DELETE")

	if os.Getenv("DEBUG") == "1" {
		defer debugPrintRoutes(r)
	}

	return r
}

func debugPrintRoutes(r *mux.Router) {
	err := r.Walk(func(route *mux.Route, router *mux.Router, ancestors []*mux.Route) error {
		pathTemplate, err := route.GetPathTemplate()
		if err == nil {
			fmt.Println("ROUTE:", pathTemplate)
		}
		pathRegexp, err := route.GetPathRegexp()
		if err == nil {
			fmt.Println("Path regexp:", pathRegexp)
		}
		queriesTemplates, err := route.GetQueriesTemplates()
		if err == nil {
			fmt.Println("Queries templates:", strings.Join(queriesTemplates, ","))
		}
		queriesRegexps, err := route.GetQueriesRegexp()
		if err == nil {
			fmt.Println("Queries regexps:", strings.Join(queriesRegexps, ","))
		}
		methods, err := route.GetMethods()
		if err == nil {
			fmt.Println("Methods:", strings.Join(methods, ","))
		}
		fmt.Println()
		return nil
	})

	if err != nil {
		fmt.Println(err)
	}
}

//nolint: gocyclo
func servePublic(w http.ResponseWriter, r *http.Request) {
	path := r.URL.Path

	webPath := "/"
	if util.WebHostURL != nil {
		webPath = util.WebHostURL.RequestURI()
	}

	if !strings.HasPrefix(path, webPath+"public") {
		if len(strings.Split(path, ".")) > 1 {
			w.WriteHeader(http.StatusNotFound)
			return
		}

		path = "/html/index.html"
	}

	path = strings.Replace(path, webPath+"public/", "", 1)
	split := strings.Split(path, ".")
	suffix := split[len(split)-1]

	res, err := publicAssets.MustBytes(path)
	if err != nil {
		notFoundHandler(w, r)
		return
	}

	// replace base path
	if util.WebHostURL != nil && path == "/html/index.html" {
		res = []byte(strings.Replace(string(res),
			"<base href=\"/\">",
			"<base href=\""+util.WebHostURL.String()+"\">",
			1))
	}

	contentType := "text/plain"
	switch suffix {
	case "png":
		contentType = "image/png"
	case "jpg", "jpeg":
		contentType = "image/jpeg"
	case "gif":
		contentType = "image/gif"
	case "js":
		contentType = "application/javascript"
	case "css":
		contentType = "text/css"
	case "woff":
		contentType = "application/x-font-woff"
	case "ttf":
		contentType = "application/x-font-ttf"
	case "otf":
		contentType = "application/x-font-otf"
	case "html":
		contentType = "text/html"
	}

	w.Header().Set("content-type", contentType)
	_, err = w.Write(res)
	util.LogWarning(err)
}

func getSystemInfo(w http.ResponseWriter, r *http.Request) {
	body := map[string]interface{}{
		"version": util.Version,
		"update":  util.UpdateAvailable,
		"config": map[string]string{
			"dbHost":  util.Config.MySQL.Hostname,
			"dbName":  util.Config.MySQL.DbName,
			"dbUser":  util.Config.MySQL.Username,
			"path":    util.Config.TmpPath,
			"cmdPath": util.FindSemaphore(),
		},
	}

	if util.UpdateAvailable != nil {
		body["updateBody"] = string(blackfriday.MarkdownCommon([]byte(*util.UpdateAvailable.Body)))
	}

	util.WriteJSON(w, http.StatusOK, body)
}

func checkUpgrade(w http.ResponseWriter, r *http.Request) {
	if err := util.CheckUpdate(util.Version); err != nil {
		util.WriteJSON(w, 500, err)
		return
	}

	if util.UpdateAvailable != nil {
		getSystemInfo(w, r)
		return
	}

	w.WriteHeader(http.StatusNoContent)
}

func doUpgrade(w http.ResponseWriter, r *http.Request) {
	util.LogError(util.DoUpgrade(util.Version))
}
<|endoftext|>