You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

setting.go 31 kB

11 years ago
11 years ago
11 years ago
Git LFS support v2 (#122) * Import github.com/git-lfs/lfs-test-server as lfs module base Imported commit is 3968aac269a77b73924649b9412ae03f7ccd3198 Removed: Dockerfile CONTRIBUTING.md mgmt* script/ vendor/ kvlogger.go .dockerignore .gitignore README.md * Remove config, add JWT support from github.com/mgit-at/lfs-test-server Imported commit f0cdcc5a01599c5a955dc1bbf683bb4acecdba83 * Add LFS settings * Add LFS meta object model * Add LFS routes and initialization * Import github.com/dgrijalva/jwt-go into vendor/ * Adapt LFS module: handlers, routing, meta store * Move LFS routes to /user/repo/info/lfs/* * Add request header checks to LFS BatchHandler / PostHandler * Implement LFS basic authentication * Rework JWT secret generation / load * Implement LFS SSH token authentication with JWT Specification: https://github.com/github/git-lfs/tree/master/docs/api * Integrate LFS settings into install process * Remove LFS objects when repository is deleted Only removes objects from content store when deleted repo is the only referencing repository * Make LFS module stateless Fixes bug where LFS would not work after installation without restarting Gitea * Change 500 'Internal Server Error' to 400 'Bad Request' * Change sql query to xorm call * Remove unneeded type from LFS module * Change internal imports to code.gitea.io/gitea/ * Add Gitea authors copyright * Change basic auth realm to "gitea-lfs" * Add unique indexes to LFS model * Use xorm count function in LFS check on repository delete * Return io.ReadCloser from content store and close after usage * Add LFS info to runWeb() * Export LFS content store base path * LFS file download from UI * Work around git-lfs client issue with unauthenticated requests Returning a dummy Authorization header for unauthenticated requests lets git-lfs client skip asking for auth credentials See: https://github.com/github/git-lfs/issues/1088 * Fix unauthenticated UI downloads from public repositories * Authentication check order, Finish LFS file view logic * Ignore LFS hooks if installed for current OS user Fixes Gitea UI actions for repositories tracking LFS files. Checks for minimum needed git version by parsing the semantic version string. * Hide LFS metafile diff from commit view, marking as binary * Show LFS notice if file in commit view is tracked * Add notbefore/nbf JWT claim * Correct lint suggestions - comments for structs and functions - Add comments to LFS model - Function comment for GetRandomBytesAsBase64 - LFS server function comments and lint variable suggestion * Move secret generation code out of conditional Ensures no LFS code may run with an empty secret * Do not hand out JWT tokens if LFS server support is disabled
9 years ago
11 years ago
Git LFS support v2 (#122) * Import github.com/git-lfs/lfs-test-server as lfs module base Imported commit is 3968aac269a77b73924649b9412ae03f7ccd3198 Removed: Dockerfile CONTRIBUTING.md mgmt* script/ vendor/ kvlogger.go .dockerignore .gitignore README.md * Remove config, add JWT support from github.com/mgit-at/lfs-test-server Imported commit f0cdcc5a01599c5a955dc1bbf683bb4acecdba83 * Add LFS settings * Add LFS meta object model * Add LFS routes and initialization * Import github.com/dgrijalva/jwt-go into vendor/ * Adapt LFS module: handlers, routing, meta store * Move LFS routes to /user/repo/info/lfs/* * Add request header checks to LFS BatchHandler / PostHandler * Implement LFS basic authentication * Rework JWT secret generation / load * Implement LFS SSH token authentication with JWT Specification: https://github.com/github/git-lfs/tree/master/docs/api * Integrate LFS settings into install process * Remove LFS objects when repository is deleted Only removes objects from content store when deleted repo is the only referencing repository * Make LFS module stateless Fixes bug where LFS would not work after installation without restarting Gitea * Change 500 'Internal Server Error' to 400 'Bad Request' * Change sql query to xorm call * Remove unneeded type from LFS module * Change internal imports to code.gitea.io/gitea/ * Add Gitea authors copyright * Change basic auth realm to "gitea-lfs" * Add unique indexes to LFS model * Use xorm count function in LFS check on repository delete * Return io.ReadCloser from content store and close after usage * Add LFS info to runWeb() * Export LFS content store base path * LFS file download from UI * Work around git-lfs client issue with unauthenticated requests Returning a dummy Authorization header for unauthenticated requests lets git-lfs client skip asking for auth credentials See: https://github.com/github/git-lfs/issues/1088 * Fix unauthenticated UI downloads from public repositories * Authentication check order, Finish LFS file view logic * Ignore LFS hooks if installed for current OS user Fixes Gitea UI actions for repositories tracking LFS files. Checks for minimum needed git version by parsing the semantic version string. * Hide LFS metafile diff from commit view, marking as binary * Show LFS notice if file in commit view is tracked * Add notbefore/nbf JWT claim * Correct lint suggestions - comments for structs and functions - Add comments to LFS model - Function comment for GetRandomBytesAsBase64 - LFS server function comments and lint variable suggestion * Move secret generation code out of conditional Ensures no LFS code may run with an empty secret * Do not hand out JWT tokens if LFS server support is disabled
9 years ago
11 years ago
11 years ago
11 years ago
Git LFS support v2 (#122) * Import github.com/git-lfs/lfs-test-server as lfs module base Imported commit is 3968aac269a77b73924649b9412ae03f7ccd3198 Removed: Dockerfile CONTRIBUTING.md mgmt* script/ vendor/ kvlogger.go .dockerignore .gitignore README.md * Remove config, add JWT support from github.com/mgit-at/lfs-test-server Imported commit f0cdcc5a01599c5a955dc1bbf683bb4acecdba83 * Add LFS settings * Add LFS meta object model * Add LFS routes and initialization * Import github.com/dgrijalva/jwt-go into vendor/ * Adapt LFS module: handlers, routing, meta store * Move LFS routes to /user/repo/info/lfs/* * Add request header checks to LFS BatchHandler / PostHandler * Implement LFS basic authentication * Rework JWT secret generation / load * Implement LFS SSH token authentication with JWT Specification: https://github.com/github/git-lfs/tree/master/docs/api * Integrate LFS settings into install process * Remove LFS objects when repository is deleted Only removes objects from content store when deleted repo is the only referencing repository * Make LFS module stateless Fixes bug where LFS would not work after installation without restarting Gitea * Change 500 'Internal Server Error' to 400 'Bad Request' * Change sql query to xorm call * Remove unneeded type from LFS module * Change internal imports to code.gitea.io/gitea/ * Add Gitea authors copyright * Change basic auth realm to "gitea-lfs" * Add unique indexes to LFS model * Use xorm count function in LFS check on repository delete * Return io.ReadCloser from content store and close after usage * Add LFS info to runWeb() * Export LFS content store base path * LFS file download from UI * Work around git-lfs client issue with unauthenticated requests Returning a dummy Authorization header for unauthenticated requests lets git-lfs client skip asking for auth credentials See: https://github.com/github/git-lfs/issues/1088 * Fix unauthenticated UI downloads from public repositories * Authentication check order, Finish LFS file view logic * Ignore LFS hooks if installed for current OS user Fixes Gitea UI actions for repositories tracking LFS files. Checks for minimum needed git version by parsing the semantic version string. * Hide LFS metafile diff from commit view, marking as binary * Show LFS notice if file in commit view is tracked * Add notbefore/nbf JWT claim * Correct lint suggestions - comments for structs and functions - Add comments to LFS model - Function comment for GetRandomBytesAsBase64 - LFS server function comments and lint variable suggestion * Move secret generation code out of conditional Ensures no LFS code may run with an empty secret * Do not hand out JWT tokens if LFS server support is disabled
9 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
Git LFS support v2 (#122) * Import github.com/git-lfs/lfs-test-server as lfs module base Imported commit is 3968aac269a77b73924649b9412ae03f7ccd3198 Removed: Dockerfile CONTRIBUTING.md mgmt* script/ vendor/ kvlogger.go .dockerignore .gitignore README.md * Remove config, add JWT support from github.com/mgit-at/lfs-test-server Imported commit f0cdcc5a01599c5a955dc1bbf683bb4acecdba83 * Add LFS settings * Add LFS meta object model * Add LFS routes and initialization * Import github.com/dgrijalva/jwt-go into vendor/ * Adapt LFS module: handlers, routing, meta store * Move LFS routes to /user/repo/info/lfs/* * Add request header checks to LFS BatchHandler / PostHandler * Implement LFS basic authentication * Rework JWT secret generation / load * Implement LFS SSH token authentication with JWT Specification: https://github.com/github/git-lfs/tree/master/docs/api * Integrate LFS settings into install process * Remove LFS objects when repository is deleted Only removes objects from content store when deleted repo is the only referencing repository * Make LFS module stateless Fixes bug where LFS would not work after installation without restarting Gitea * Change 500 'Internal Server Error' to 400 'Bad Request' * Change sql query to xorm call * Remove unneeded type from LFS module * Change internal imports to code.gitea.io/gitea/ * Add Gitea authors copyright * Change basic auth realm to "gitea-lfs" * Add unique indexes to LFS model * Use xorm count function in LFS check on repository delete * Return io.ReadCloser from content store and close after usage * Add LFS info to runWeb() * Export LFS content store base path * LFS file download from UI * Work around git-lfs client issue with unauthenticated requests Returning a dummy Authorization header for unauthenticated requests lets git-lfs client skip asking for auth credentials See: https://github.com/github/git-lfs/issues/1088 * Fix unauthenticated UI downloads from public repositories * Authentication check order, Finish LFS file view logic * Ignore LFS hooks if installed for current OS user Fixes Gitea UI actions for repositories tracking LFS files. Checks for minimum needed git version by parsing the semantic version string. * Hide LFS metafile diff from commit view, marking as binary * Show LFS notice if file in commit view is tracked * Add notbefore/nbf JWT claim * Correct lint suggestions - comments for structs and functions - Add comments to LFS model - Function comment for GetRandomBytesAsBase64 - LFS server function comments and lint variable suggestion * Move secret generation code out of conditional Ensures no LFS code may run with an empty secret * Do not hand out JWT tokens if LFS server support is disabled
9 years ago
11 years ago
11 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
11 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
11 years ago
10 years ago
11 years ago
11 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
Git LFS support v2 (#122) * Import github.com/git-lfs/lfs-test-server as lfs module base Imported commit is 3968aac269a77b73924649b9412ae03f7ccd3198 Removed: Dockerfile CONTRIBUTING.md mgmt* script/ vendor/ kvlogger.go .dockerignore .gitignore README.md * Remove config, add JWT support from github.com/mgit-at/lfs-test-server Imported commit f0cdcc5a01599c5a955dc1bbf683bb4acecdba83 * Add LFS settings * Add LFS meta object model * Add LFS routes and initialization * Import github.com/dgrijalva/jwt-go into vendor/ * Adapt LFS module: handlers, routing, meta store * Move LFS routes to /user/repo/info/lfs/* * Add request header checks to LFS BatchHandler / PostHandler * Implement LFS basic authentication * Rework JWT secret generation / load * Implement LFS SSH token authentication with JWT Specification: https://github.com/github/git-lfs/tree/master/docs/api * Integrate LFS settings into install process * Remove LFS objects when repository is deleted Only removes objects from content store when deleted repo is the only referencing repository * Make LFS module stateless Fixes bug where LFS would not work after installation without restarting Gitea * Change 500 'Internal Server Error' to 400 'Bad Request' * Change sql query to xorm call * Remove unneeded type from LFS module * Change internal imports to code.gitea.io/gitea/ * Add Gitea authors copyright * Change basic auth realm to "gitea-lfs" * Add unique indexes to LFS model * Use xorm count function in LFS check on repository delete * Return io.ReadCloser from content store and close after usage * Add LFS info to runWeb() * Export LFS content store base path * LFS file download from UI * Work around git-lfs client issue with unauthenticated requests Returning a dummy Authorization header for unauthenticated requests lets git-lfs client skip asking for auth credentials See: https://github.com/github/git-lfs/issues/1088 * Fix unauthenticated UI downloads from public repositories * Authentication check order, Finish LFS file view logic * Ignore LFS hooks if installed for current OS user Fixes Gitea UI actions for repositories tracking LFS files. Checks for minimum needed git version by parsing the semantic version string. * Hide LFS metafile diff from commit view, marking as binary * Show LFS notice if file in commit view is tracked * Add notbefore/nbf JWT claim * Correct lint suggestions - comments for structs and functions - Add comments to LFS model - Function comment for GetRandomBytesAsBase64 - LFS server function comments and lint variable suggestion * Move secret generation code out of conditional Ensures no LFS code may run with an empty secret * Do not hand out JWT tokens if LFS server support is disabled
9 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
Squashed commit of the following: commit 0afcb843d7ffd596991c4885cab768273a6eb42c Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 17:13:29 2016 -0600 Removed Upload stats as the upload table is just a temporary table commit 7ecd73ff5535612d79d471409173ee7f1fcfa157 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 08:42:41 2016 -0600 Fix for CodeMirror mode commit c29b9ab531e2e7af0fb5db24dc17e51027dd1174 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 08:03:33 2016 -0600 Made tabbing in editor use spaces commit 23af384c53206a8a40e11e45bf49d7a149c4adcd Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 07:56:46 2016 -0600 Fix for data-url commit cfb8a97591cb6fc0a92e49563b7b764c524db0e9 Merge: 7fc8a89 991ce42 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 07:42:53 2016 -0600 Merge remote-tracking branch 'gogits/develop' into feature-create-and-edit-repo-file Conflicts: modules/bindata/bindata.go public/js/gogs.js commit 7fc8a89cb495478225b02d613e647f99a1489634 Merge: fd3d86c c03d040 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 07:40:00 2016 -0600 Merge branch 'feature-create-and-edit-repo-file' of github.com:richmahn/gogs into feature-create-and-edit-repo-file commit fd3d86ca6bbc02cfda566a504ffd6b03db4f75ef Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 07:39:44 2016 -0600 Code cleanup commit c03d0401c1049eeeccc32ab1f9c3303c130be5ee Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Fri Jul 29 15:38:23 2016 -0600 Code cleanup commit 98e1206ccf9f9a4503c020e3a7830cf9f861dfae Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Thu Jul 28 18:36:01 2016 -0600 Code cleanup and fixes commit c2895dc742f25f8412879c9fa15e18f27f42f194 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Thu Jul 28 18:24:04 2016 -0600 Fixes per Unknwon's requests commit 6aa7e46b21ad4c96e562daa2eac26a8fb408f8ef Merge: 889e9fa ad7ea88 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Thu Jul 28 17:13:43 2016 -0600 Merge remote-tracking branch 'gogits/develop' into feature-create-and-edit-repo-file Conflicts: modules/bindata/bindata.go modules/setting/setting.go commit 889e9faf1bd8559a4979c8f46005d488c1a234d4 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Fri Jul 22 14:09:18 2016 -0600 Fix in gogs.js commit 47603edf223f147b114be65f3bd27bc1e88827a5 Merge: bb57912 cf85e9e Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Fri Jul 22 14:07:36 2016 -0600 Merge remote-tracking branch 'gogits/develop' into feature-create-and-edit-repo-file Conflicts: modules/bindata/bindata.go public/js/gogs.js commit bb5791255867a71c11a77b639db050ad09c597a4 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Fri Jul 22 14:02:18 2016 -0600 Update for using CodeMirror mode addon commit d10d128c51039be19e2af9c66c63db66a9f2ec6d Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Tue Jul 19 16:12:57 2016 -0600 Update for Edit commit 34a34982025144e3225e389f7849eb6273c1d576 Merge: fa1b752 1c7dcdd Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Tue Jul 19 11:52:02 2016 -0600 Merge remote-tracking branch 'gogits/develop' into feature-create-and-edit-repo-file Conflicts: modules/bindata/bindata.go commit fa1b752be29cd455c5184ddac2ffe80b3489763e Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Fri Jul 15 18:35:42 2016 -0600 Feature for editing, creating, uploading and deleting files
9 years ago
11 years ago
11 years ago
Add support for federated avatars (#3320) * Add support for federated avatars Fixes #3105 Removes avatar fetching duplication code Adds an "Enable Federated Avatar" checkbox in user settings (defaults to unchecked) Moves avatar settings all in the same form, making local and remote avatars mutually exclusive Renames UploadAvatarForm to AvatarForm as it's not anymore only for uploading * Run gofmt on all modified files * Move Avatar form in its own page * Add go-libravatar dependency to vendor/ dir Hopefully helps with accepting the contribution. See also #3214 * Revert "Add go-libravatar dependency to vendor/ dir" This reverts commit a8cb93ae640bbb90f7d25012fc257bda9fae9b82. * Make federated avatar setting a global configuration Removes the per-user setting * Move avatar handling back to base tool, disable federated avatar in offline mode * Format, handle error * Properly set fallback host * Use unsupported github.com mirror for importing go-libravatar * Remove comment showing life exists outside of github.com ... pity, but contribution would not be accepted otherwise * Use Combo for Get and Post methods over /avatar * FEDERATED_AVATAR -> ENABLE_FEDERATED_AVATAR * Fix persistance of federated avatar lookup checkbox at install time * Federated Avatars -> Enable Federated Avatars * Use len(string) == 0 instead of string == "" * Move import line where it belong See https://github.com/Unknwon/go-code-convention/blob/master/en-US/import_packages.md Pity the import url is still the unofficial one, but oh well... * Save a line (and waste much more expensive time) * Remove redundant parens * Remove an empty line * Remove empty lines * Reorder lines to make diff smaller * Remove another newline Unknwon review got me start a fight against newlines * Move DISABLE_GRAVATAR and ENABLE_FEDERATED_AVATAR after OFFLINE_MODE On re-reading the diff I figured what Unknwon meant here: https://github.com/gogits/gogs/pull/3320/files#r73741106 * Remove newlines that weren't there before my intervention
9 years ago
Add support for federated avatars (#3320) * Add support for federated avatars Fixes #3105 Removes avatar fetching duplication code Adds an "Enable Federated Avatar" checkbox in user settings (defaults to unchecked) Moves avatar settings all in the same form, making local and remote avatars mutually exclusive Renames UploadAvatarForm to AvatarForm as it's not anymore only for uploading * Run gofmt on all modified files * Move Avatar form in its own page * Add go-libravatar dependency to vendor/ dir Hopefully helps with accepting the contribution. See also #3214 * Revert "Add go-libravatar dependency to vendor/ dir" This reverts commit a8cb93ae640bbb90f7d25012fc257bda9fae9b82. * Make federated avatar setting a global configuration Removes the per-user setting * Move avatar handling back to base tool, disable federated avatar in offline mode * Format, handle error * Properly set fallback host * Use unsupported github.com mirror for importing go-libravatar * Remove comment showing life exists outside of github.com ... pity, but contribution would not be accepted otherwise * Use Combo for Get and Post methods over /avatar * FEDERATED_AVATAR -> ENABLE_FEDERATED_AVATAR * Fix persistance of federated avatar lookup checkbox at install time * Federated Avatars -> Enable Federated Avatars * Use len(string) == 0 instead of string == "" * Move import line where it belong See https://github.com/Unknwon/go-code-convention/blob/master/en-US/import_packages.md Pity the import url is still the unofficial one, but oh well... * Save a line (and waste much more expensive time) * Remove redundant parens * Remove an empty line * Remove empty lines * Reorder lines to make diff smaller * Remove another newline Unknwon review got me start a fight against newlines * Move DISABLE_GRAVATAR and ENABLE_FEDERATED_AVATAR after OFFLINE_MODE On re-reading the diff I figured what Unknwon meant here: https://github.com/gogits/gogs/pull/3320/files#r73741106 * Remove newlines that weren't there before my intervention
9 years ago
Add support for federated avatars (#3320) * Add support for federated avatars Fixes #3105 Removes avatar fetching duplication code Adds an "Enable Federated Avatar" checkbox in user settings (defaults to unchecked) Moves avatar settings all in the same form, making local and remote avatars mutually exclusive Renames UploadAvatarForm to AvatarForm as it's not anymore only for uploading * Run gofmt on all modified files * Move Avatar form in its own page * Add go-libravatar dependency to vendor/ dir Hopefully helps with accepting the contribution. See also #3214 * Revert "Add go-libravatar dependency to vendor/ dir" This reverts commit a8cb93ae640bbb90f7d25012fc257bda9fae9b82. * Make federated avatar setting a global configuration Removes the per-user setting * Move avatar handling back to base tool, disable federated avatar in offline mode * Format, handle error * Properly set fallback host * Use unsupported github.com mirror for importing go-libravatar * Remove comment showing life exists outside of github.com ... pity, but contribution would not be accepted otherwise * Use Combo for Get and Post methods over /avatar * FEDERATED_AVATAR -> ENABLE_FEDERATED_AVATAR * Fix persistance of federated avatar lookup checkbox at install time * Federated Avatars -> Enable Federated Avatars * Use len(string) == 0 instead of string == "" * Move import line where it belong See https://github.com/Unknwon/go-code-convention/blob/master/en-US/import_packages.md Pity the import url is still the unofficial one, but oh well... * Save a line (and waste much more expensive time) * Remove redundant parens * Remove an empty line * Remove empty lines * Reorder lines to make diff smaller * Remove another newline Unknwon review got me start a fight against newlines * Move DISABLE_GRAVATAR and ENABLE_FEDERATED_AVATAR after OFFLINE_MODE On re-reading the diff I figured what Unknwon meant here: https://github.com/gogits/gogs/pull/3320/files#r73741106 * Remove newlines that weren't there before my intervention
9 years ago
Add support for federated avatars (#3320) * Add support for federated avatars Fixes #3105 Removes avatar fetching duplication code Adds an "Enable Federated Avatar" checkbox in user settings (defaults to unchecked) Moves avatar settings all in the same form, making local and remote avatars mutually exclusive Renames UploadAvatarForm to AvatarForm as it's not anymore only for uploading * Run gofmt on all modified files * Move Avatar form in its own page * Add go-libravatar dependency to vendor/ dir Hopefully helps with accepting the contribution. See also #3214 * Revert "Add go-libravatar dependency to vendor/ dir" This reverts commit a8cb93ae640bbb90f7d25012fc257bda9fae9b82. * Make federated avatar setting a global configuration Removes the per-user setting * Move avatar handling back to base tool, disable federated avatar in offline mode * Format, handle error * Properly set fallback host * Use unsupported github.com mirror for importing go-libravatar * Remove comment showing life exists outside of github.com ... pity, but contribution would not be accepted otherwise * Use Combo for Get and Post methods over /avatar * FEDERATED_AVATAR -> ENABLE_FEDERATED_AVATAR * Fix persistance of federated avatar lookup checkbox at install time * Federated Avatars -> Enable Federated Avatars * Use len(string) == 0 instead of string == "" * Move import line where it belong See https://github.com/Unknwon/go-code-convention/blob/master/en-US/import_packages.md Pity the import url is still the unofficial one, but oh well... * Save a line (and waste much more expensive time) * Remove redundant parens * Remove an empty line * Remove empty lines * Reorder lines to make diff smaller * Remove another newline Unknwon review got me start a fight against newlines * Move DISABLE_GRAVATAR and ENABLE_FEDERATED_AVATAR after OFFLINE_MODE On re-reading the diff I figured what Unknwon meant here: https://github.com/gogits/gogs/pull/3320/files#r73741106 * Remove newlines that weren't there before my intervention
9 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package setting
  5. import (
  6. "crypto/rand"
  7. "encoding/base64"
  8. "fmt"
  9. "io"
  10. "net/mail"
  11. "net/url"
  12. "os"
  13. "os/exec"
  14. "path"
  15. "path/filepath"
  16. "runtime"
  17. "strconv"
  18. "strings"
  19. "time"
  20. "code.gitea.io/git"
  21. "code.gitea.io/gitea/modules/log"
  22. "code.gitea.io/gitea/modules/user"
  23. "github.com/Unknwon/com"
  24. _ "github.com/go-macaron/cache/memcache" // memcache plugin for cache
  25. _ "github.com/go-macaron/cache/redis"
  26. "github.com/go-macaron/session"
  27. _ "github.com/go-macaron/session/redis" // redis plugin for store session
  28. _ "github.com/kardianos/minwinsvc" // import minwinsvc for windows services
  29. "gopkg.in/ini.v1"
  30. "strk.kbt.io/projects/go/libravatar"
  31. )
  32. // Scheme describes protocol types
  33. type Scheme string
  34. // enumerates all the scheme types
  35. const (
  36. HTTP Scheme = "http"
  37. HTTPS Scheme = "https"
  38. FCGI Scheme = "fcgi"
  39. UnixSocket Scheme = "unix"
  40. )
  41. // LandingPage describes the default page
  42. type LandingPage string
  43. // enumerates all the landing page types
  44. const (
  45. LandingPageHome LandingPage = "/"
  46. LandingPageExplore LandingPage = "/explore"
  47. )
  48. // settings
  49. var (
  50. // AppVer settings
  51. AppVer string
  52. AppName string
  53. AppURL string
  54. AppSubURL string
  55. AppSubURLDepth int // Number of slashes
  56. AppPath string
  57. AppDataPath string
  58. // Server settings
  59. Protocol Scheme
  60. Domain string
  61. HTTPAddr string
  62. HTTPPort string
  63. LocalURL string
  64. OfflineMode bool
  65. DisableRouterLog bool
  66. CertFile string
  67. KeyFile string
  68. StaticRootPath string
  69. EnableGzip bool
  70. LandingPageURL LandingPage
  71. UnixSocketPermission uint32
  72. SSH = struct {
  73. Disabled bool `ini:"DISABLE_SSH"`
  74. StartBuiltinServer bool `ini:"START_SSH_SERVER"`
  75. Domain string `ini:"SSH_DOMAIN"`
  76. Port int `ini:"SSH_PORT"`
  77. ListenHost string `ini:"SSH_LISTEN_HOST"`
  78. ListenPort int `ini:"SSH_LISTEN_PORT"`
  79. RootPath string `ini:"SSH_ROOT_PATH"`
  80. KeyTestPath string `ini:"SSH_KEY_TEST_PATH"`
  81. KeygenPath string `ini:"SSH_KEYGEN_PATH"`
  82. MinimumKeySizeCheck bool `ini:"-"`
  83. MinimumKeySizes map[string]int `ini:"-"`
  84. }{
  85. Disabled: false,
  86. StartBuiltinServer: false,
  87. Domain: "localhost",
  88. Port: 22,
  89. KeygenPath: "ssh-keygen",
  90. }
  91. LFS struct {
  92. StartServer bool `ini:"LFS_START_SERVER"`
  93. ContentPath string `ini:"LFS_CONTENT_PATH"`
  94. JWTSecretBase64 string `ini:"LFS_JWT_SECRET"`
  95. JWTSecretBytes []byte `ini:"-"`
  96. }
  97. // Security settings
  98. InstallLock bool
  99. SecretKey string
  100. LogInRememberDays int
  101. CookieUserName string
  102. CookieRememberName string
  103. ReverseProxyAuthUser string
  104. MinPasswordLength int
  105. // Database settings
  106. UseSQLite3 bool
  107. UseMySQL bool
  108. UseMSSQL bool
  109. UsePostgreSQL bool
  110. UseTiDB bool
  111. // Webhook settings
  112. Webhook = struct {
  113. QueueLength int
  114. DeliverTimeout int
  115. SkipTLSVerify bool
  116. Types []string
  117. PagingNum int
  118. }{
  119. QueueLength: 1000,
  120. DeliverTimeout: 5,
  121. SkipTLSVerify: false,
  122. PagingNum: 10,
  123. }
  124. // Repository settings
  125. Repository = struct {
  126. AnsiCharset string
  127. ForcePrivate bool
  128. MaxCreationLimit int
  129. MirrorQueueLength int
  130. PullRequestQueueLength int
  131. PreferredLicenses []string
  132. DisableHTTPGit bool
  133. // Repository editor settings
  134. Editor struct {
  135. LineWrapExtensions []string
  136. PreviewableFileModes []string
  137. } `ini:"-"`
  138. // Repository upload settings
  139. Upload struct {
  140. Enabled bool
  141. TempPath string
  142. AllowedTypes []string `delim:"|"`
  143. FileMaxSize int64
  144. MaxFiles int
  145. } `ini:"-"`
  146. }{
  147. AnsiCharset: "",
  148. ForcePrivate: false,
  149. MaxCreationLimit: -1,
  150. MirrorQueueLength: 1000,
  151. PullRequestQueueLength: 1000,
  152. PreferredLicenses: []string{"Apache License 2.0,MIT License"},
  153. DisableHTTPGit: false,
  154. // Repository editor settings
  155. Editor: struct {
  156. LineWrapExtensions []string
  157. PreviewableFileModes []string
  158. }{
  159. LineWrapExtensions: strings.Split(".txt,.md,.markdown,.mdown,.mkd,", ","),
  160. PreviewableFileModes: []string{"markdown"},
  161. },
  162. // Repository upload settings
  163. Upload: struct {
  164. Enabled bool
  165. TempPath string
  166. AllowedTypes []string `delim:"|"`
  167. FileMaxSize int64
  168. MaxFiles int
  169. }{
  170. Enabled: true,
  171. TempPath: "data/tmp/uploads",
  172. AllowedTypes: []string{},
  173. FileMaxSize: 3,
  174. MaxFiles: 5,
  175. },
  176. }
  177. RepoRootPath string
  178. ScriptType = "bash"
  179. // UI settings
  180. UI = struct {
  181. ExplorePagingNum int
  182. IssuePagingNum int
  183. FeedMaxCommitNum int
  184. ThemeColorMetaTag string
  185. MaxDisplayFileSize int64
  186. Admin struct {
  187. UserPagingNum int
  188. RepoPagingNum int
  189. NoticePagingNum int
  190. OrgPagingNum int
  191. } `ini:"ui.admin"`
  192. User struct {
  193. RepoPagingNum int
  194. } `ini:"ui.user"`
  195. }{
  196. ExplorePagingNum: 20,
  197. IssuePagingNum: 10,
  198. FeedMaxCommitNum: 5,
  199. ThemeColorMetaTag: `#6cc644`,
  200. MaxDisplayFileSize: 8388608,
  201. Admin: struct {
  202. UserPagingNum int
  203. RepoPagingNum int
  204. NoticePagingNum int
  205. OrgPagingNum int
  206. }{
  207. UserPagingNum: 50,
  208. RepoPagingNum: 50,
  209. NoticePagingNum: 25,
  210. OrgPagingNum: 50,
  211. },
  212. User: struct {
  213. RepoPagingNum int
  214. }{
  215. RepoPagingNum: 15,
  216. },
  217. }
  218. // Markdown sttings
  219. Markdown = struct {
  220. EnableHardLineBreak bool
  221. CustomURLSchemes []string `ini:"CUSTOM_URL_SCHEMES"`
  222. FileExtensions []string
  223. }{
  224. EnableHardLineBreak: false,
  225. FileExtensions: strings.Split(".md,.markdown,.mdown,.mkd", ","),
  226. }
  227. // Picture settings
  228. AvatarUploadPath string
  229. GravatarSource string
  230. DisableGravatar bool
  231. EnableFederatedAvatar bool
  232. LibravatarService *libravatar.Libravatar
  233. // Log settings
  234. LogRootPath string
  235. LogModes []string
  236. LogConfigs []string
  237. // Attachment settings
  238. AttachmentPath string
  239. AttachmentAllowedTypes string
  240. AttachmentMaxSize int64
  241. AttachmentMaxFiles int
  242. AttachmentEnabled bool
  243. // Time settings
  244. TimeFormat string
  245. // Cache settings
  246. CacheAdapter string
  247. CacheInterval int
  248. CacheConn string
  249. // Session settings
  250. SessionConfig session.Options
  251. CSRFCookieName = "_csrf"
  252. // Cron tasks
  253. Cron = struct {
  254. UpdateMirror struct {
  255. Enabled bool
  256. RunAtStart bool
  257. Schedule string
  258. } `ini:"cron.update_mirrors"`
  259. RepoHealthCheck struct {
  260. Enabled bool
  261. RunAtStart bool
  262. Schedule string
  263. Timeout time.Duration
  264. Args []string `delim:" "`
  265. } `ini:"cron.repo_health_check"`
  266. CheckRepoStats struct {
  267. Enabled bool
  268. RunAtStart bool
  269. Schedule string
  270. } `ini:"cron.check_repo_stats"`
  271. }{
  272. UpdateMirror: struct {
  273. Enabled bool
  274. RunAtStart bool
  275. Schedule string
  276. }{
  277. Schedule: "@every 10m",
  278. },
  279. RepoHealthCheck: struct {
  280. Enabled bool
  281. RunAtStart bool
  282. Schedule string
  283. Timeout time.Duration
  284. Args []string `delim:" "`
  285. }{
  286. Schedule: "@every 24h",
  287. Timeout: 60 * time.Second,
  288. Args: []string{},
  289. },
  290. CheckRepoStats: struct {
  291. Enabled bool
  292. RunAtStart bool
  293. Schedule string
  294. }{
  295. RunAtStart: true,
  296. Schedule: "@every 24h",
  297. },
  298. }
  299. // Git settings
  300. Git = struct {
  301. DisableDiffHighlight bool
  302. MaxGitDiffLines int
  303. MaxGitDiffLineCharacters int
  304. MaxGitDiffFiles int
  305. GCArgs []string `delim:" "`
  306. Timeout struct {
  307. Migrate int
  308. Mirror int
  309. Clone int
  310. Pull int
  311. GC int `ini:"GC"`
  312. } `ini:"git.timeout"`
  313. }{
  314. DisableDiffHighlight: false,
  315. MaxGitDiffLines: 1000,
  316. MaxGitDiffLineCharacters: 500,
  317. MaxGitDiffFiles: 100,
  318. GCArgs: []string{},
  319. Timeout: struct {
  320. Migrate int
  321. Mirror int
  322. Clone int
  323. Pull int
  324. GC int `ini:"GC"`
  325. }{
  326. Migrate: 600,
  327. Mirror: 300,
  328. Clone: 300,
  329. Pull: 300,
  330. GC: 60,
  331. },
  332. }
  333. // Mirror settings
  334. Mirror = struct {
  335. DefaultInterval int
  336. }{
  337. DefaultInterval: 8,
  338. }
  339. // API settings
  340. API = struct {
  341. MaxResponseItems int
  342. }{
  343. MaxResponseItems: 50,
  344. }
  345. // I18n settings
  346. Langs []string
  347. Names []string
  348. dateLangs map[string]string
  349. // Highlight settings are loaded in modules/template/hightlight.go
  350. // Other settings
  351. ShowFooterBranding bool
  352. ShowFooterVersion bool
  353. ShowFooterTemplateLoadTime bool
  354. // Global setting objects
  355. Cfg *ini.File
  356. CustomPath string // Custom directory path
  357. CustomConf string
  358. ProdMode bool
  359. RunUser string
  360. IsWindows bool
  361. HasRobotsTxt bool
  362. )
  363. // DateLang transforms standard language locale name to corresponding value in datetime plugin.
  364. func DateLang(lang string) string {
  365. name, ok := dateLangs[lang]
  366. if ok {
  367. return name
  368. }
  369. return "en"
  370. }
  371. // execPath returns the executable path.
  372. func execPath() (string, error) {
  373. file, err := exec.LookPath(os.Args[0])
  374. if err != nil {
  375. return "", err
  376. }
  377. return filepath.Abs(file)
  378. }
  379. func init() {
  380. IsWindows = runtime.GOOS == "windows"
  381. log.NewLogger(0, "console", `{"level": 0}`)
  382. var err error
  383. if AppPath, err = execPath(); err != nil {
  384. log.Fatal(4, "fail to get app path: %v\n", err)
  385. }
  386. // Note: we don't use path.Dir here because it does not handle case
  387. // which path starts with two "/" in Windows: "//psf/Home/..."
  388. AppPath = strings.Replace(AppPath, "\\", "/", -1)
  389. }
  390. // WorkDir returns absolute path of work directory.
  391. func WorkDir() (string, error) {
  392. wd := os.Getenv("GITEA_WORK_DIR")
  393. if len(wd) > 0 {
  394. return wd, nil
  395. }
  396. // Use GOGS_WORK_DIR if available, for backward compatibility
  397. // TODO: drop in 1.1.0 ?
  398. wd = os.Getenv("GOGS_WORK_DIR")
  399. if len(wd) > 0 {
  400. log.Warn(`Usage of GOGS_WORK_DIR is deprecated and will be *removed* in a future release,
  401. please consider changing to GITEA_WORK_DIR`)
  402. return wd, nil
  403. }
  404. i := strings.LastIndex(AppPath, "/")
  405. if i == -1 {
  406. return AppPath, nil
  407. }
  408. return AppPath[:i], nil
  409. }
  410. func forcePathSeparator(path string) {
  411. if strings.Contains(path, "\\") {
  412. log.Fatal(4, "Do not use '\\' or '\\\\' in paths, instead, please use '/' in all places")
  413. }
  414. }
  415. // IsRunUserMatchCurrentUser returns false if configured run user does not match
  416. // actual user that runs the app. The first return value is the actual user name.
  417. // This check is ignored under Windows since SSH remote login is not the main
  418. // method to login on Windows.
  419. func IsRunUserMatchCurrentUser(runUser string) (string, bool) {
  420. if IsWindows {
  421. return "", true
  422. }
  423. currentUser := user.CurrentUsername()
  424. return currentUser, runUser == currentUser
  425. }
  426. // NewContext initializes configuration context.
  427. // NOTE: do not print any log except error.
  428. func NewContext() {
  429. workDir, err := WorkDir()
  430. if err != nil {
  431. log.Fatal(4, "Fail to get work directory: %v", err)
  432. }
  433. Cfg = ini.Empty()
  434. if err != nil {
  435. log.Fatal(4, "Fail to parse 'app.ini': %v", err)
  436. }
  437. CustomPath = os.Getenv("GITEA_CUSTOM")
  438. if len(CustomPath) == 0 {
  439. // For backward compatibility
  440. // TODO: drop in 1.1.0 ?
  441. CustomPath = os.Getenv("GOGS_CUSTOM")
  442. if len(CustomPath) == 0 {
  443. CustomPath = workDir + "/custom"
  444. } else {
  445. log.Warn(`Usage of GOGS_CUSTOM is deprecated and will be *removed* in a future release,
  446. please consider changing to GITEA_CUSTOM`)
  447. }
  448. }
  449. if len(CustomConf) == 0 {
  450. CustomConf = CustomPath + "/conf/app.ini"
  451. }
  452. if com.IsFile(CustomConf) {
  453. if err = Cfg.Append(CustomConf); err != nil {
  454. log.Fatal(4, "Fail to load custom conf '%s': %v", CustomConf, err)
  455. }
  456. } else {
  457. log.Warn("Custom config '%s' not found, ignore this if you're running first time", CustomConf)
  458. }
  459. Cfg.NameMapper = ini.AllCapsUnderscore
  460. homeDir, err := com.HomeDir()
  461. if err != nil {
  462. log.Fatal(4, "Fail to get home directory: %v", err)
  463. }
  464. homeDir = strings.Replace(homeDir, "\\", "/", -1)
  465. LogRootPath = Cfg.Section("log").Key("ROOT_PATH").MustString(path.Join(workDir, "log"))
  466. forcePathSeparator(LogRootPath)
  467. sec := Cfg.Section("server")
  468. AppName = Cfg.Section("").Key("APP_NAME").MustString("Gitea: Git with a cup of tea")
  469. AppURL = sec.Key("ROOT_URL").MustString("http://localhost:3000/")
  470. if AppURL[len(AppURL)-1] != '/' {
  471. AppURL += "/"
  472. }
  473. // Check if has app suburl.
  474. url, err := url.Parse(AppURL)
  475. if err != nil {
  476. log.Fatal(4, "Invalid ROOT_URL '%s': %s", AppURL, err)
  477. }
  478. // Suburl should start with '/' and end without '/', such as '/{subpath}'.
  479. // This value is empty if site does not have sub-url.
  480. AppSubURL = strings.TrimSuffix(url.Path, "/")
  481. AppSubURLDepth = strings.Count(AppSubURL, "/")
  482. Protocol = HTTP
  483. if sec.Key("PROTOCOL").String() == "https" {
  484. Protocol = HTTPS
  485. CertFile = sec.Key("CERT_FILE").String()
  486. KeyFile = sec.Key("KEY_FILE").String()
  487. } else if sec.Key("PROTOCOL").String() == "fcgi" {
  488. Protocol = FCGI
  489. } else if sec.Key("PROTOCOL").String() == "unix" {
  490. Protocol = UnixSocket
  491. UnixSocketPermissionRaw := sec.Key("UNIX_SOCKET_PERMISSION").MustString("666")
  492. UnixSocketPermissionParsed, err := strconv.ParseUint(UnixSocketPermissionRaw, 8, 32)
  493. if err != nil || UnixSocketPermissionParsed > 0777 {
  494. log.Fatal(4, "Fail to parse unixSocketPermission: %s", UnixSocketPermissionRaw)
  495. }
  496. UnixSocketPermission = uint32(UnixSocketPermissionParsed)
  497. }
  498. Domain = sec.Key("DOMAIN").MustString("localhost")
  499. HTTPAddr = sec.Key("HTTP_ADDR").MustString("0.0.0.0")
  500. HTTPPort = sec.Key("HTTP_PORT").MustString("3000")
  501. LocalURL = sec.Key("LOCAL_ROOT_URL").MustString(string(Protocol) + "://localhost:" + HTTPPort + "/")
  502. OfflineMode = sec.Key("OFFLINE_MODE").MustBool()
  503. DisableRouterLog = sec.Key("DISABLE_ROUTER_LOG").MustBool()
  504. StaticRootPath = sec.Key("STATIC_ROOT_PATH").MustString(workDir)
  505. AppDataPath = sec.Key("APP_DATA_PATH").MustString("data")
  506. EnableGzip = sec.Key("ENABLE_GZIP").MustBool()
  507. switch sec.Key("LANDING_PAGE").MustString("home") {
  508. case "explore":
  509. LandingPageURL = LandingPageExplore
  510. default:
  511. LandingPageURL = LandingPageHome
  512. }
  513. SSH.RootPath = path.Join(homeDir, ".ssh")
  514. SSH.KeyTestPath = os.TempDir()
  515. if err = Cfg.Section("server").MapTo(&SSH); err != nil {
  516. log.Fatal(4, "Fail to map SSH settings: %v", err)
  517. }
  518. SSH.KeygenPath = sec.Key("SSH_KEYGEN_PATH").MustString("ssh-keygen")
  519. SSH.Port = sec.Key("SSH_PORT").MustInt(22)
  520. // When disable SSH, start builtin server value is ignored.
  521. if SSH.Disabled {
  522. SSH.StartBuiltinServer = false
  523. }
  524. if !SSH.Disabled && !SSH.StartBuiltinServer {
  525. if err := os.MkdirAll(SSH.RootPath, 0700); err != nil {
  526. log.Fatal(4, "Fail to create '%s': %v", SSH.RootPath, err)
  527. } else if err = os.MkdirAll(SSH.KeyTestPath, 0644); err != nil {
  528. log.Fatal(4, "Fail to create '%s': %v", SSH.KeyTestPath, err)
  529. }
  530. }
  531. SSH.MinimumKeySizeCheck = sec.Key("MINIMUM_KEY_SIZE_CHECK").MustBool()
  532. SSH.MinimumKeySizes = map[string]int{}
  533. minimumKeySizes := Cfg.Section("ssh.minimum_key_sizes").Keys()
  534. for _, key := range minimumKeySizes {
  535. if key.MustInt() != -1 {
  536. SSH.MinimumKeySizes[strings.ToLower(key.Name())] = key.MustInt()
  537. }
  538. }
  539. if err = Cfg.Section("server").MapTo(&LFS); err != nil {
  540. log.Fatal(4, "Fail to map LFS settings: %v", err)
  541. }
  542. if LFS.StartServer {
  543. if err := os.MkdirAll(LFS.ContentPath, 0700); err != nil {
  544. log.Fatal(4, "Fail to create '%s': %v", LFS.ContentPath, err)
  545. }
  546. LFS.JWTSecretBytes = make([]byte, 32)
  547. n, err := base64.RawURLEncoding.Decode(LFS.JWTSecretBytes, []byte(LFS.JWTSecretBase64))
  548. if err != nil || n != 32 {
  549. //Generate new secret and save to config
  550. _, err := io.ReadFull(rand.Reader, LFS.JWTSecretBytes)
  551. if err != nil {
  552. log.Fatal(4, "Error reading random bytes: %s", err)
  553. }
  554. LFS.JWTSecretBase64 = base64.RawURLEncoding.EncodeToString(LFS.JWTSecretBytes)
  555. // Save secret
  556. cfg := ini.Empty()
  557. if com.IsFile(CustomConf) {
  558. // Keeps custom settings if there is already something.
  559. if err := cfg.Append(CustomConf); err != nil {
  560. log.Error(4, "Fail to load custom conf '%s': %v", CustomConf, err)
  561. }
  562. }
  563. cfg.Section("server").Key("LFS_JWT_SECRET").SetValue(LFS.JWTSecretBase64)
  564. os.MkdirAll(filepath.Dir(CustomConf), os.ModePerm)
  565. if err := cfg.SaveTo(CustomConf); err != nil {
  566. log.Fatal(4, "Error saving generated JWT Secret to custom config: %v", err)
  567. return
  568. }
  569. }
  570. //Disable LFS client hooks if installed for the current OS user
  571. //Needs at least git v2.1.2
  572. binVersion, err := git.BinVersion()
  573. if err != nil {
  574. log.Fatal(4, "Error retrieving git version: %s", err)
  575. }
  576. splitVersion := strings.SplitN(binVersion, ".", 3)
  577. majorVersion, err := strconv.ParseUint(splitVersion[0], 10, 64)
  578. if err != nil {
  579. log.Fatal(4, "Error parsing git major version: %s", err)
  580. }
  581. minorVersion, err := strconv.ParseUint(splitVersion[1], 10, 64)
  582. if err != nil {
  583. log.Fatal(4, "Error parsing git minor version: %s", err)
  584. }
  585. revisionVersion, err := strconv.ParseUint(splitVersion[2], 10, 64)
  586. if err != nil {
  587. log.Fatal(4, "Error parsing git revision version: %s", err)
  588. }
  589. if !((majorVersion > 2) || (majorVersion == 2 && minorVersion > 1) ||
  590. (majorVersion == 2 && minorVersion == 1 && revisionVersion >= 2)) {
  591. LFS.StartServer = false
  592. log.Error(4, "LFS server support needs at least Git v2.1.2")
  593. } else {
  594. git.GlobalCommandArgs = append(git.GlobalCommandArgs, "-c", "filter.lfs.required=",
  595. "-c", "filter.lfs.smudge=", "-c", "filter.lfs.clean=")
  596. }
  597. }
  598. sec = Cfg.Section("security")
  599. InstallLock = sec.Key("INSTALL_LOCK").MustBool(false)
  600. SecretKey = sec.Key("SECRET_KEY").MustString("!#@FDEWREWR&*(")
  601. LogInRememberDays = sec.Key("LOGIN_REMEMBER_DAYS").MustInt(7)
  602. CookieUserName = sec.Key("COOKIE_USERNAME").MustString("gitea_awesome")
  603. CookieRememberName = sec.Key("COOKIE_REMEMBER_NAME").MustString("gitea_incredible")
  604. ReverseProxyAuthUser = sec.Key("REVERSE_PROXY_AUTHENTICATION_USER").MustString("X-WEBAUTH-USER")
  605. MinPasswordLength = sec.Key("MIN_PASSWORD_LENGTH").MustInt(6)
  606. sec = Cfg.Section("attachment")
  607. AttachmentPath = sec.Key("PATH").MustString(path.Join(AppDataPath, "attachments"))
  608. if !filepath.IsAbs(AttachmentPath) {
  609. AttachmentPath = path.Join(workDir, AttachmentPath)
  610. }
  611. AttachmentAllowedTypes = strings.Replace(sec.Key("ALLOWED_TYPES").MustString("image/jpeg,image/png"), "|", ",", -1)
  612. AttachmentMaxSize = sec.Key("MAX_SIZE").MustInt64(4)
  613. AttachmentMaxFiles = sec.Key("MAX_FILES").MustInt(5)
  614. AttachmentEnabled = sec.Key("ENABLE").MustBool(true)
  615. TimeFormat = map[string]string{
  616. "ANSIC": time.ANSIC,
  617. "UnixDate": time.UnixDate,
  618. "RubyDate": time.RubyDate,
  619. "RFC822": time.RFC822,
  620. "RFC822Z": time.RFC822Z,
  621. "RFC850": time.RFC850,
  622. "RFC1123": time.RFC1123,
  623. "RFC1123Z": time.RFC1123Z,
  624. "RFC3339": time.RFC3339,
  625. "RFC3339Nano": time.RFC3339Nano,
  626. "Kitchen": time.Kitchen,
  627. "Stamp": time.Stamp,
  628. "StampMilli": time.StampMilli,
  629. "StampMicro": time.StampMicro,
  630. "StampNano": time.StampNano,
  631. }[Cfg.Section("time").Key("FORMAT").MustString("RFC1123")]
  632. RunUser = Cfg.Section("").Key("RUN_USER").MustString(user.CurrentUsername())
  633. // Does not check run user when the install lock is off.
  634. if InstallLock {
  635. currentUser, match := IsRunUserMatchCurrentUser(RunUser)
  636. if !match {
  637. log.Fatal(4, "Expect user '%s' but current user is: %s", RunUser, currentUser)
  638. }
  639. }
  640. // Determine and create root git repository path.
  641. sec = Cfg.Section("repository")
  642. Repository.DisableHTTPGit = sec.Key("DISABLE_HTTP_GIT").MustBool()
  643. RepoRootPath = sec.Key("ROOT").MustString(path.Join(homeDir, "gitea-repositories"))
  644. forcePathSeparator(RepoRootPath)
  645. if !filepath.IsAbs(RepoRootPath) {
  646. RepoRootPath = path.Join(workDir, RepoRootPath)
  647. } else {
  648. RepoRootPath = path.Clean(RepoRootPath)
  649. }
  650. ScriptType = sec.Key("SCRIPT_TYPE").MustString("bash")
  651. if err = Cfg.Section("repository").MapTo(&Repository); err != nil {
  652. log.Fatal(4, "Fail to map Repository settings: %v", err)
  653. } else if err = Cfg.Section("repository.editor").MapTo(&Repository.Editor); err != nil {
  654. log.Fatal(4, "Fail to map Repository.Editor settings: %v", err)
  655. } else if err = Cfg.Section("repository.upload").MapTo(&Repository.Upload); err != nil {
  656. log.Fatal(4, "Fail to map Repository.Upload settings: %v", err)
  657. }
  658. if !filepath.IsAbs(Repository.Upload.TempPath) {
  659. Repository.Upload.TempPath = path.Join(workDir, Repository.Upload.TempPath)
  660. }
  661. sec = Cfg.Section("picture")
  662. AvatarUploadPath = sec.Key("AVATAR_UPLOAD_PATH").MustString(path.Join(AppDataPath, "avatars"))
  663. forcePathSeparator(AvatarUploadPath)
  664. if !filepath.IsAbs(AvatarUploadPath) {
  665. AvatarUploadPath = path.Join(workDir, AvatarUploadPath)
  666. }
  667. switch source := sec.Key("GRAVATAR_SOURCE").MustString("gravatar"); source {
  668. case "duoshuo":
  669. GravatarSource = "http://gravatar.duoshuo.com/avatar/"
  670. case "gravatar":
  671. GravatarSource = "https://secure.gravatar.com/avatar/"
  672. case "libravatar":
  673. GravatarSource = "https://seccdn.libravatar.org/avatar/"
  674. default:
  675. GravatarSource = source
  676. }
  677. DisableGravatar = sec.Key("DISABLE_GRAVATAR").MustBool()
  678. EnableFederatedAvatar = sec.Key("ENABLE_FEDERATED_AVATAR").MustBool()
  679. if OfflineMode {
  680. DisableGravatar = true
  681. EnableFederatedAvatar = false
  682. }
  683. if DisableGravatar {
  684. EnableFederatedAvatar = false
  685. }
  686. if EnableFederatedAvatar {
  687. LibravatarService = libravatar.New()
  688. parts := strings.Split(GravatarSource, "/")
  689. if len(parts) >= 3 {
  690. if parts[0] == "https:" {
  691. LibravatarService.SetUseHTTPS(true)
  692. LibravatarService.SetSecureFallbackHost(parts[2])
  693. } else {
  694. LibravatarService.SetUseHTTPS(false)
  695. LibravatarService.SetFallbackHost(parts[2])
  696. }
  697. }
  698. }
  699. if err = Cfg.Section("ui").MapTo(&UI); err != nil {
  700. log.Fatal(4, "Fail to map UI settings: %v", err)
  701. } else if err = Cfg.Section("markdown").MapTo(&Markdown); err != nil {
  702. log.Fatal(4, "Fail to map Markdown settings: %v", err)
  703. } else if err = Cfg.Section("cron").MapTo(&Cron); err != nil {
  704. log.Fatal(4, "Fail to map Cron settings: %v", err)
  705. } else if err = Cfg.Section("git").MapTo(&Git); err != nil {
  706. log.Fatal(4, "Fail to map Git settings: %v", err)
  707. } else if err = Cfg.Section("mirror").MapTo(&Mirror); err != nil {
  708. log.Fatal(4, "Fail to map Mirror settings: %v", err)
  709. } else if err = Cfg.Section("api").MapTo(&API); err != nil {
  710. log.Fatal(4, "Fail to map API settings: %v", err)
  711. }
  712. if Mirror.DefaultInterval <= 0 {
  713. Mirror.DefaultInterval = 24
  714. }
  715. Langs = Cfg.Section("i18n").Key("LANGS").Strings(",")
  716. if len(Langs) == 0 {
  717. Langs = defaultLangs
  718. }
  719. Names = Cfg.Section("i18n").Key("NAMES").Strings(",")
  720. if len(Names) == 0 {
  721. Names = defaultLangNames
  722. }
  723. dateLangs = Cfg.Section("i18n.datelang").KeysHash()
  724. ShowFooterBranding = Cfg.Section("other").Key("SHOW_FOOTER_BRANDING").MustBool(false)
  725. ShowFooterVersion = Cfg.Section("other").Key("SHOW_FOOTER_VERSION").MustBool(true)
  726. ShowFooterTemplateLoadTime = Cfg.Section("other").Key("SHOW_FOOTER_TEMPLATE_LOAD_TIME").MustBool(true)
  727. HasRobotsTxt = com.IsFile(path.Join(CustomPath, "robots.txt"))
  728. }
  729. // Service settings
  730. var Service struct {
  731. ActiveCodeLives int
  732. ResetPwdCodeLives int
  733. RegisterEmailConfirm bool
  734. DisableRegistration bool
  735. ShowRegistrationButton bool
  736. RequireSignInView bool
  737. EnableNotifyMail bool
  738. EnableReverseProxyAuth bool
  739. EnableReverseProxyAutoRegister bool
  740. EnableCaptcha bool
  741. }
  742. func newService() {
  743. sec := Cfg.Section("service")
  744. Service.ActiveCodeLives = sec.Key("ACTIVE_CODE_LIVE_MINUTES").MustInt(180)
  745. Service.ResetPwdCodeLives = sec.Key("RESET_PASSWD_CODE_LIVE_MINUTES").MustInt(180)
  746. Service.DisableRegistration = sec.Key("DISABLE_REGISTRATION").MustBool()
  747. Service.ShowRegistrationButton = sec.Key("SHOW_REGISTRATION_BUTTON").MustBool(!Service.DisableRegistration)
  748. Service.RequireSignInView = sec.Key("REQUIRE_SIGNIN_VIEW").MustBool()
  749. Service.EnableReverseProxyAuth = sec.Key("ENABLE_REVERSE_PROXY_AUTHENTICATION").MustBool()
  750. Service.EnableReverseProxyAutoRegister = sec.Key("ENABLE_REVERSE_PROXY_AUTO_REGISTRATION").MustBool()
  751. Service.EnableCaptcha = sec.Key("ENABLE_CAPTCHA").MustBool()
  752. }
  753. var logLevels = map[string]string{
  754. "Trace": "0",
  755. "Debug": "1",
  756. "Info": "2",
  757. "Warn": "3",
  758. "Error": "4",
  759. "Critical": "5",
  760. }
  761. func newLogService() {
  762. log.Info("Gitea v%s", AppVer)
  763. LogModes = strings.Split(Cfg.Section("log").Key("MODE").MustString("console"), ",")
  764. LogConfigs = make([]string, len(LogModes))
  765. for i, mode := range LogModes {
  766. mode = strings.TrimSpace(mode)
  767. sec, err := Cfg.GetSection("log." + mode)
  768. if err != nil {
  769. sec, _ = Cfg.NewSection("log." + mode)
  770. }
  771. validLevels := []string{"Trace", "Debug", "Info", "Warn", "Error", "Critical"}
  772. // Log level.
  773. levelName := Cfg.Section("log."+mode).Key("LEVEL").In(
  774. Cfg.Section("log").Key("LEVEL").In("Trace", validLevels),
  775. validLevels)
  776. level, ok := logLevels[levelName]
  777. if !ok {
  778. log.Fatal(4, "Unknown log level: %s", levelName)
  779. }
  780. // Generate log configuration.
  781. switch mode {
  782. case "console":
  783. LogConfigs[i] = fmt.Sprintf(`{"level":%s}`, level)
  784. case "file":
  785. logPath := sec.Key("FILE_NAME").MustString(path.Join(LogRootPath, "gogs.log"))
  786. if err = os.MkdirAll(path.Dir(logPath), os.ModePerm); err != nil {
  787. panic(err.Error())
  788. }
  789. LogConfigs[i] = fmt.Sprintf(
  790. `{"level":%s,"filename":"%s","rotate":%v,"maxlines":%d,"maxsize":%d,"daily":%v,"maxdays":%d}`, level,
  791. logPath,
  792. sec.Key("LOG_ROTATE").MustBool(true),
  793. sec.Key("MAX_LINES").MustInt(1000000),
  794. 1<<uint(sec.Key("MAX_SIZE_SHIFT").MustInt(28)),
  795. sec.Key("DAILY_ROTATE").MustBool(true),
  796. sec.Key("MAX_DAYS").MustInt(7))
  797. case "conn":
  798. LogConfigs[i] = fmt.Sprintf(`{"level":%s,"reconnectOnMsg":%v,"reconnect":%v,"net":"%s","addr":"%s"}`, level,
  799. sec.Key("RECONNECT_ON_MSG").MustBool(),
  800. sec.Key("RECONNECT").MustBool(),
  801. sec.Key("PROTOCOL").In("tcp", []string{"tcp", "unix", "udp"}),
  802. sec.Key("ADDR").MustString(":7020"))
  803. case "smtp":
  804. LogConfigs[i] = fmt.Sprintf(`{"level":%s,"username":"%s","password":"%s","host":"%s","sendTos":["%s"],"subject":"%s"}`, level,
  805. sec.Key("USER").MustString("example@example.com"),
  806. sec.Key("PASSWD").MustString("******"),
  807. sec.Key("HOST").MustString("127.0.0.1:25"),
  808. strings.Replace(sec.Key("RECEIVERS").MustString("example@example.com"), ",", "\",\"", -1),
  809. sec.Key("SUBJECT").MustString("Diagnostic message from serve"))
  810. case "database":
  811. LogConfigs[i] = fmt.Sprintf(`{"level":%s,"driver":"%s","conn":"%s"}`, level,
  812. sec.Key("DRIVER").String(),
  813. sec.Key("CONN").String())
  814. }
  815. log.NewLogger(Cfg.Section("log").Key("BUFFER_LEN").MustInt64(10000), mode, LogConfigs[i])
  816. log.Info("Log Mode: %s(%s)", strings.Title(mode), levelName)
  817. }
  818. }
  819. func newCacheService() {
  820. CacheAdapter = Cfg.Section("cache").Key("ADAPTER").In("memory", []string{"memory", "redis", "memcache"})
  821. switch CacheAdapter {
  822. case "memory":
  823. CacheInterval = Cfg.Section("cache").Key("INTERVAL").MustInt(60)
  824. case "redis", "memcache":
  825. CacheConn = strings.Trim(Cfg.Section("cache").Key("HOST").String(), "\" ")
  826. default:
  827. log.Fatal(4, "Unknown cache adapter: %s", CacheAdapter)
  828. }
  829. log.Info("Cache Service Enabled")
  830. }
  831. func newSessionService() {
  832. SessionConfig.Provider = Cfg.Section("session").Key("PROVIDER").In("memory",
  833. []string{"memory", "file", "redis", "mysql"})
  834. SessionConfig.ProviderConfig = strings.Trim(Cfg.Section("session").Key("PROVIDER_CONFIG").String(), "\" ")
  835. SessionConfig.CookieName = Cfg.Section("session").Key("COOKIE_NAME").MustString("i_like_gitea")
  836. SessionConfig.CookiePath = AppSubURL
  837. SessionConfig.Secure = Cfg.Section("session").Key("COOKIE_SECURE").MustBool(false)
  838. SessionConfig.Gclifetime = Cfg.Section("session").Key("GC_INTERVAL_TIME").MustInt64(86400)
  839. SessionConfig.Maxlifetime = Cfg.Section("session").Key("SESSION_LIFE_TIME").MustInt64(86400)
  840. log.Info("Session Service Enabled")
  841. }
  842. // Mailer represents mail service.
  843. type Mailer struct {
  844. // Mailer
  845. QueueLength int
  846. Name string
  847. From string
  848. FromEmail string
  849. EnableHTMLAlternative bool
  850. // SMTP sender
  851. Host string
  852. User, Passwd string
  853. DisableHelo bool
  854. HeloHostname string
  855. SkipVerify bool
  856. UseCertificate bool
  857. CertFile, KeyFile string
  858. // Sendmail sender
  859. UseSendmail bool
  860. SendmailPath string
  861. }
  862. var (
  863. // MailService the global mailer
  864. MailService *Mailer
  865. )
  866. func newMailService() {
  867. sec := Cfg.Section("mailer")
  868. // Check mailer setting.
  869. if !sec.Key("ENABLED").MustBool() {
  870. return
  871. }
  872. MailService = &Mailer{
  873. QueueLength: sec.Key("SEND_BUFFER_LEN").MustInt(100),
  874. Name: sec.Key("NAME").MustString(AppName),
  875. EnableHTMLAlternative: sec.Key("ENABLE_HTML_ALTERNATIVE").MustBool(),
  876. Host: sec.Key("HOST").String(),
  877. User: sec.Key("USER").String(),
  878. Passwd: sec.Key("PASSWD").String(),
  879. DisableHelo: sec.Key("DISABLE_HELO").MustBool(),
  880. HeloHostname: sec.Key("HELO_HOSTNAME").String(),
  881. SkipVerify: sec.Key("SKIP_VERIFY").MustBool(),
  882. UseCertificate: sec.Key("USE_CERTIFICATE").MustBool(),
  883. CertFile: sec.Key("CERT_FILE").String(),
  884. KeyFile: sec.Key("KEY_FILE").String(),
  885. UseSendmail: sec.Key("USE_SENDMAIL").MustBool(),
  886. SendmailPath: sec.Key("SENDMAIL_PATH").MustString("sendmail"),
  887. }
  888. MailService.From = sec.Key("FROM").MustString(MailService.User)
  889. parsed, err := mail.ParseAddress(MailService.From)
  890. if err != nil {
  891. log.Fatal(4, "Invalid mailer.FROM (%s): %v", MailService.From, err)
  892. }
  893. MailService.FromEmail = parsed.Address
  894. log.Info("Mail Service Enabled")
  895. }
  896. func newRegisterMailService() {
  897. if !Cfg.Section("service").Key("REGISTER_EMAIL_CONFIRM").MustBool() {
  898. return
  899. } else if MailService == nil {
  900. log.Warn("Register Mail Service: Mail Service is not enabled")
  901. return
  902. }
  903. Service.RegisterEmailConfirm = true
  904. log.Info("Register Mail Service Enabled")
  905. }
  906. func newNotifyMailService() {
  907. if !Cfg.Section("service").Key("ENABLE_NOTIFY_MAIL").MustBool() {
  908. return
  909. } else if MailService == nil {
  910. log.Warn("Notify Mail Service: Mail Service is not enabled")
  911. return
  912. }
  913. Service.EnableNotifyMail = true
  914. log.Info("Notify Mail Service Enabled")
  915. }
  916. func newWebhookService() {
  917. sec := Cfg.Section("webhook")
  918. Webhook.QueueLength = sec.Key("QUEUE_LENGTH").MustInt(1000)
  919. Webhook.DeliverTimeout = sec.Key("DELIVER_TIMEOUT").MustInt(5)
  920. Webhook.SkipTLSVerify = sec.Key("SKIP_TLS_VERIFY").MustBool()
  921. Webhook.Types = []string{"gogs", "slack"}
  922. Webhook.PagingNum = sec.Key("PAGING_NUM").MustInt(10)
  923. }
  924. // NewServices initializes the services
  925. func NewServices() {
  926. newService()
  927. newLogService()
  928. newCacheService()
  929. newSessionService()
  930. newMailService()
  931. newRegisterMailService()
  932. newNotifyMailService()
  933. newWebhookService()
  934. }