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

setting.go 30KB

10 years ago
10 years ago
10 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
7 years ago
10 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
7 years ago
10 years ago
10 years ago
10 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
7 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
9 years ago
9 years ago
10 years ago
10 years ago
10 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
7 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
8 years ago
10 years ago
8 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
8 years ago
10 years ago
10 years ago
8 years ago
9 years ago
9 years ago
9 years ago
10 years ago
10 years ago
9 years ago
10 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 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
7 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
10 years ago
10 years ago
9 years ago
9 years ago
10 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
7 years ago
9 years ago
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
7 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
7 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
7 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
7 years ago
9 years ago
9 years ago
10 years ago
10 years ago
9 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
10 years ago
9 years ago
10 years ago
10 years ago
9 years ago
10 years ago
10 years ago
9 years ago
9 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
10 years ago
9 years ago
10 years ago
10 years ago
9 years ago
10 years ago
9 years ago
10 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054
  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. LFS struct {
  86. StartServer bool `ini:"LFS_START_SERVER"`
  87. ContentPath string `ini:"LFS_CONTENT_PATH"`
  88. JWTSecretBase64 string `ini:"LFS_JWT_SECRET"`
  89. JWTSecretBytes []byte `ini:"-"`
  90. }
  91. // Security settings
  92. InstallLock bool
  93. SecretKey string
  94. LogInRememberDays int
  95. CookieUserName string
  96. CookieRememberName string
  97. ReverseProxyAuthUser string
  98. MinPasswordLength int
  99. // Database settings
  100. UseSQLite3 bool
  101. UseMySQL bool
  102. UseMSSQL bool
  103. UsePostgreSQL bool
  104. UseTiDB bool
  105. // Webhook settings
  106. Webhook = struct {
  107. QueueLength int
  108. DeliverTimeout int
  109. SkipTLSVerify bool
  110. Types []string
  111. PagingNum int
  112. }{
  113. QueueLength: 1000,
  114. DeliverTimeout: 5,
  115. SkipTLSVerify: false,
  116. PagingNum: 10,
  117. }
  118. // Repository settings
  119. Repository = struct {
  120. AnsiCharset string
  121. ForcePrivate bool
  122. MaxCreationLimit int
  123. MirrorQueueLength int
  124. PullRequestQueueLength int
  125. PreferredLicenses []string
  126. DisableHTTPGit bool
  127. // Repository editor settings
  128. Editor struct {
  129. LineWrapExtensions []string
  130. PreviewableFileModes []string
  131. } `ini:"-"`
  132. // Repository upload settings
  133. Upload struct {
  134. Enabled bool
  135. TempPath string
  136. AllowedTypes []string `delim:"|"`
  137. FileMaxSize int64
  138. MaxFiles int
  139. } `ini:"-"`
  140. }{
  141. AnsiCharset: "",
  142. ForcePrivate: false,
  143. MaxCreationLimit: -1,
  144. MirrorQueueLength: 1000,
  145. PullRequestQueueLength: 1000,
  146. PreferredLicenses: []string{"Apache License 2.0,MIT License"},
  147. DisableHTTPGit: false,
  148. // Repository editor settings
  149. Editor: struct {
  150. LineWrapExtensions []string
  151. PreviewableFileModes []string
  152. }{
  153. LineWrapExtensions: strings.Split(".txt,.md,.markdown,.mdown,.mkd,", ","),
  154. PreviewableFileModes: []string{"markdown"},
  155. },
  156. // Repository upload settings
  157. Upload: struct {
  158. Enabled bool
  159. TempPath string
  160. AllowedTypes []string `delim:"|"`
  161. FileMaxSize int64
  162. MaxFiles int
  163. }{
  164. Enabled: true,
  165. TempPath: "data/tmp/uploads",
  166. AllowedTypes: []string{},
  167. FileMaxSize: 3,
  168. MaxFiles: 5,
  169. },
  170. }
  171. RepoRootPath string
  172. ScriptType = "bash"
  173. // UI settings
  174. UI = struct {
  175. ExplorePagingNum int
  176. IssuePagingNum int
  177. FeedMaxCommitNum int
  178. ThemeColorMetaTag string
  179. MaxDisplayFileSize int64
  180. Admin struct {
  181. UserPagingNum int
  182. RepoPagingNum int
  183. NoticePagingNum int
  184. OrgPagingNum int
  185. } `ini:"ui.admin"`
  186. User struct {
  187. RepoPagingNum int
  188. } `ini:"ui.user"`
  189. }{
  190. ExplorePagingNum: 20,
  191. IssuePagingNum: 10,
  192. FeedMaxCommitNum: 5,
  193. ThemeColorMetaTag: `#6cc644`,
  194. MaxDisplayFileSize: 8388608,
  195. Admin: struct {
  196. UserPagingNum int
  197. RepoPagingNum int
  198. NoticePagingNum int
  199. OrgPagingNum int
  200. }{
  201. UserPagingNum: 50,
  202. RepoPagingNum: 50,
  203. NoticePagingNum: 25,
  204. OrgPagingNum: 50,
  205. },
  206. User: struct {
  207. RepoPagingNum int
  208. }{
  209. RepoPagingNum: 15,
  210. },
  211. }
  212. // Markdown sttings
  213. Markdown = struct {
  214. EnableHardLineBreak bool
  215. CustomURLSchemes []string `ini:"CUSTOM_URL_SCHEMES"`
  216. FileExtensions []string
  217. }{
  218. EnableHardLineBreak: false,
  219. FileExtensions: strings.Split(".md,.markdown,.mdown,.mkd", ","),
  220. }
  221. // Picture settings
  222. AvatarUploadPath string
  223. GravatarSource string
  224. DisableGravatar bool
  225. EnableFederatedAvatar bool
  226. LibravatarService *libravatar.Libravatar
  227. // Log settings
  228. LogRootPath string
  229. LogModes []string
  230. LogConfigs []string
  231. // Attachment settings
  232. AttachmentPath string
  233. AttachmentAllowedTypes string
  234. AttachmentMaxSize int64
  235. AttachmentMaxFiles int
  236. AttachmentEnabled bool
  237. // Time settings
  238. TimeFormat string
  239. // Cache settings
  240. CacheAdapter string
  241. CacheInterval int
  242. CacheConn string
  243. // Session settings
  244. SessionConfig session.Options
  245. CSRFCookieName = "_csrf"
  246. // Cron tasks
  247. Cron = struct {
  248. UpdateMirror struct {
  249. Enabled bool
  250. RunAtStart bool
  251. Schedule string
  252. } `ini:"cron.update_mirrors"`
  253. RepoHealthCheck struct {
  254. Enabled bool
  255. RunAtStart bool
  256. Schedule string
  257. Timeout time.Duration
  258. Args []string `delim:" "`
  259. } `ini:"cron.repo_health_check"`
  260. CheckRepoStats struct {
  261. Enabled bool
  262. RunAtStart bool
  263. Schedule string
  264. } `ini:"cron.check_repo_stats"`
  265. }{
  266. UpdateMirror: struct {
  267. Enabled bool
  268. RunAtStart bool
  269. Schedule string
  270. }{
  271. Schedule: "@every 10m",
  272. },
  273. RepoHealthCheck: struct {
  274. Enabled bool
  275. RunAtStart bool
  276. Schedule string
  277. Timeout time.Duration
  278. Args []string `delim:" "`
  279. }{
  280. Schedule: "@every 24h",
  281. Timeout: 60 * time.Second,
  282. Args: []string{},
  283. },
  284. CheckRepoStats: struct {
  285. Enabled bool
  286. RunAtStart bool
  287. Schedule string
  288. }{
  289. RunAtStart: true,
  290. Schedule: "@every 24h",
  291. },
  292. }
  293. // Git settings
  294. Git = struct {
  295. DisableDiffHighlight bool
  296. MaxGitDiffLines int
  297. MaxGitDiffLineCharacters int
  298. MaxGitDiffFiles int
  299. GCArgs []string `delim:" "`
  300. Timeout struct {
  301. Migrate int
  302. Mirror int
  303. Clone int
  304. Pull int
  305. GC int `ini:"GC"`
  306. } `ini:"git.timeout"`
  307. }{
  308. DisableDiffHighlight: false,
  309. MaxGitDiffLines: 1000,
  310. MaxGitDiffLineCharacters: 500,
  311. MaxGitDiffFiles: 100,
  312. GCArgs: []string{},
  313. Timeout: struct {
  314. Migrate int
  315. Mirror int
  316. Clone int
  317. Pull int
  318. GC int `ini:"GC"`
  319. }{
  320. Migrate: 600,
  321. Mirror: 300,
  322. Clone: 300,
  323. Pull: 300,
  324. GC: 60,
  325. },
  326. }
  327. // Mirror settings
  328. Mirror = struct {
  329. DefaultInterval int
  330. }{
  331. DefaultInterval: 8,
  332. }
  333. // API settings
  334. API = struct {
  335. MaxResponseItems int
  336. }{
  337. MaxResponseItems: 50,
  338. }
  339. // I18n settings
  340. Langs []string
  341. Names []string
  342. dateLangs map[string]string
  343. // Highlight settings are loaded in modules/template/hightlight.go
  344. // Other settings
  345. ShowFooterBranding bool
  346. ShowFooterVersion bool
  347. ShowFooterTemplateLoadTime bool
  348. // Global setting objects
  349. Cfg *ini.File
  350. CustomPath string // Custom directory path
  351. CustomConf string
  352. ProdMode bool
  353. RunUser string
  354. IsWindows bool
  355. HasRobotsTxt bool
  356. )
  357. // DateLang transforms standard language locale name to corresponding value in datetime plugin.
  358. func DateLang(lang string) string {
  359. name, ok := dateLangs[lang]
  360. if ok {
  361. return name
  362. }
  363. return "en"
  364. }
  365. // execPath returns the executable path.
  366. func execPath() (string, error) {
  367. file, err := exec.LookPath(os.Args[0])
  368. if err != nil {
  369. return "", err
  370. }
  371. return filepath.Abs(file)
  372. }
  373. func init() {
  374. IsWindows = runtime.GOOS == "windows"
  375. log.NewLogger(0, "console", `{"level": 0}`)
  376. var err error
  377. if AppPath, err = execPath(); err != nil {
  378. log.Fatal(4, "fail to get app path: %v\n", err)
  379. }
  380. // Note: we don't use path.Dir here because it does not handle case
  381. // which path starts with two "/" in Windows: "//psf/Home/..."
  382. AppPath = strings.Replace(AppPath, "\\", "/", -1)
  383. }
  384. // WorkDir returns absolute path of work directory.
  385. func WorkDir() (string, error) {
  386. wd := os.Getenv("GITEA_WORK_DIR")
  387. if len(wd) > 0 {
  388. return wd, nil
  389. }
  390. // Use GOGS_WORK_DIR if available, for backward compatibility
  391. // TODO: drop in 1.1.0 ?
  392. wd = os.Getenv("GOGS_WORK_DIR")
  393. if len(wd) > 0 {
  394. log.Warn(`Usage of GOGS_WORK_DIR is deprecated and will be *removed* in a future release,
  395. please consider changing to GITEA_WORK_DIR`)
  396. return wd, nil
  397. }
  398. i := strings.LastIndex(AppPath, "/")
  399. if i == -1 {
  400. return AppPath, nil
  401. }
  402. return AppPath[:i], nil
  403. }
  404. func forcePathSeparator(path string) {
  405. if strings.Contains(path, "\\") {
  406. log.Fatal(4, "Do not use '\\' or '\\\\' in paths, instead, please use '/' in all places")
  407. }
  408. }
  409. // IsRunUserMatchCurrentUser returns false if configured run user does not match
  410. // actual user that runs the app. The first return value is the actual user name.
  411. // This check is ignored under Windows since SSH remote login is not the main
  412. // method to login on Windows.
  413. func IsRunUserMatchCurrentUser(runUser string) (string, bool) {
  414. if IsWindows {
  415. return "", true
  416. }
  417. currentUser := user.CurrentUsername()
  418. return currentUser, runUser == currentUser
  419. }
  420. // NewContext initializes configuration context.
  421. // NOTE: do not print any log except error.
  422. func NewContext() {
  423. workDir, err := WorkDir()
  424. if err != nil {
  425. log.Fatal(4, "Fail to get work directory: %v", err)
  426. }
  427. Cfg = ini.Empty()
  428. if err != nil {
  429. log.Fatal(4, "Fail to parse 'app.ini': %v", err)
  430. }
  431. CustomPath = os.Getenv("GITEA_CUSTOM")
  432. if len(CustomPath) == 0 {
  433. // For backward compatibility
  434. // TODO: drop in 1.1.0 ?
  435. CustomPath = os.Getenv("GOGS_CUSTOM")
  436. if len(CustomPath) == 0 {
  437. CustomPath = workDir + "/custom"
  438. } else {
  439. log.Warn(`Usage of GOGS_CUSTOM is deprecated and will be *removed* in a future release,
  440. please consider changing to GITEA_CUSTOM`)
  441. }
  442. }
  443. if len(CustomConf) == 0 {
  444. CustomConf = CustomPath + "/conf/app.ini"
  445. }
  446. if com.IsFile(CustomConf) {
  447. if err = Cfg.Append(CustomConf); err != nil {
  448. log.Fatal(4, "Fail to load custom conf '%s': %v", CustomConf, err)
  449. }
  450. } else {
  451. log.Warn("Custom config '%s' not found, ignore this if you're running first time", CustomConf)
  452. }
  453. Cfg.NameMapper = ini.AllCapsUnderscore
  454. homeDir, err := com.HomeDir()
  455. if err != nil {
  456. log.Fatal(4, "Fail to get home directory: %v", err)
  457. }
  458. homeDir = strings.Replace(homeDir, "\\", "/", -1)
  459. LogRootPath = Cfg.Section("log").Key("ROOT_PATH").MustString(path.Join(workDir, "log"))
  460. forcePathSeparator(LogRootPath)
  461. sec := Cfg.Section("server")
  462. AppName = Cfg.Section("").Key("APP_NAME").MustString("Gitea: Git with a cup of tea")
  463. AppURL = sec.Key("ROOT_URL").MustString("http://localhost:3000/")
  464. if AppURL[len(AppURL)-1] != '/' {
  465. AppURL += "/"
  466. }
  467. // Check if has app suburl.
  468. url, err := url.Parse(AppURL)
  469. if err != nil {
  470. log.Fatal(4, "Invalid ROOT_URL '%s': %s", AppURL, err)
  471. }
  472. // Suburl should start with '/' and end without '/', such as '/{subpath}'.
  473. // This value is empty if site does not have sub-url.
  474. AppSubURL = strings.TrimSuffix(url.Path, "/")
  475. AppSubURLDepth = strings.Count(AppSubURL, "/")
  476. Protocol = HTTP
  477. if sec.Key("PROTOCOL").String() == "https" {
  478. Protocol = HTTPS
  479. CertFile = sec.Key("CERT_FILE").String()
  480. KeyFile = sec.Key("KEY_FILE").String()
  481. } else if sec.Key("PROTOCOL").String() == "fcgi" {
  482. Protocol = FCGI
  483. } else if sec.Key("PROTOCOL").String() == "unix" {
  484. Protocol = UnixSocket
  485. UnixSocketPermissionRaw := sec.Key("UNIX_SOCKET_PERMISSION").MustString("666")
  486. UnixSocketPermissionParsed, err := strconv.ParseUint(UnixSocketPermissionRaw, 8, 32)
  487. if err != nil || UnixSocketPermissionParsed > 0777 {
  488. log.Fatal(4, "Fail to parse unixSocketPermission: %s", UnixSocketPermissionRaw)
  489. }
  490. UnixSocketPermission = uint32(UnixSocketPermissionParsed)
  491. }
  492. Domain = sec.Key("DOMAIN").MustString("localhost")
  493. HTTPAddr = sec.Key("HTTP_ADDR").MustString("0.0.0.0")
  494. HTTPPort = sec.Key("HTTP_PORT").MustString("3000")
  495. LocalURL = sec.Key("LOCAL_ROOT_URL").MustString(string(Protocol) + "://localhost:" + HTTPPort + "/")
  496. OfflineMode = sec.Key("OFFLINE_MODE").MustBool()
  497. DisableRouterLog = sec.Key("DISABLE_ROUTER_LOG").MustBool()
  498. StaticRootPath = sec.Key("STATIC_ROOT_PATH").MustString(workDir)
  499. AppDataPath = sec.Key("APP_DATA_PATH").MustString("data")
  500. EnableGzip = sec.Key("ENABLE_GZIP").MustBool()
  501. switch sec.Key("LANDING_PAGE").MustString("home") {
  502. case "explore":
  503. LandingPageURL = LandingPageExplore
  504. default:
  505. LandingPageURL = LandingPageHome
  506. }
  507. SSH.RootPath = path.Join(homeDir, ".ssh")
  508. SSH.KeyTestPath = os.TempDir()
  509. if err = Cfg.Section("server").MapTo(&SSH); err != nil {
  510. log.Fatal(4, "Fail to map SSH settings: %v", err)
  511. }
  512. SSH.KeygenPath = sec.Key("SSH_KEYGEN_PATH").MustString("ssh-keygen")
  513. SSH.Port = sec.Key("SSH_PORT").MustInt(22)
  514. // When disable SSH, start builtin server value is ignored.
  515. if SSH.Disabled {
  516. SSH.StartBuiltinServer = false
  517. }
  518. if !SSH.Disabled && !SSH.StartBuiltinServer {
  519. if err := os.MkdirAll(SSH.RootPath, 0700); err != nil {
  520. log.Fatal(4, "Fail to create '%s': %v", SSH.RootPath, err)
  521. } else if err = os.MkdirAll(SSH.KeyTestPath, 0644); err != nil {
  522. log.Fatal(4, "Fail to create '%s': %v", SSH.KeyTestPath, err)
  523. }
  524. }
  525. SSH.MinimumKeySizeCheck = sec.Key("MINIMUM_KEY_SIZE_CHECK").MustBool()
  526. SSH.MinimumKeySizes = map[string]int{}
  527. minimumKeySizes := Cfg.Section("ssh.minimum_key_sizes").Keys()
  528. for _, key := range minimumKeySizes {
  529. if key.MustInt() != -1 {
  530. SSH.MinimumKeySizes[strings.ToLower(key.Name())] = key.MustInt()
  531. }
  532. }
  533. if err = Cfg.Section("server").MapTo(&LFS); err != nil {
  534. log.Fatal(4, "Fail to map LFS settings: %v", err)
  535. }
  536. if LFS.StartServer {
  537. if err := os.MkdirAll(LFS.ContentPath, 0700); err != nil {
  538. log.Fatal(4, "Fail to create '%s': %v", LFS.ContentPath, err)
  539. }
  540. LFS.JWTSecretBytes = make([]byte, 32)
  541. n, err := base64.RawURLEncoding.Decode(LFS.JWTSecretBytes, []byte(LFS.JWTSecretBase64))
  542. if err != nil || n != 32 {
  543. //Generate new secret and save to config
  544. _, err := io.ReadFull(rand.Reader, LFS.JWTSecretBytes)
  545. if err != nil {
  546. log.Fatal(4, "Error reading random bytes: %s", err)
  547. }
  548. LFS.JWTSecretBase64 = base64.RawURLEncoding.EncodeToString(LFS.JWTSecretBytes)
  549. // Save secret
  550. cfg := ini.Empty()
  551. if com.IsFile(CustomConf) {
  552. // Keeps custom settings if there is already something.
  553. if err := cfg.Append(CustomConf); err != nil {
  554. log.Error(4, "Fail to load custom conf '%s': %v", CustomConf, err)
  555. }
  556. }
  557. cfg.Section("server").Key("LFS_JWT_SECRET").SetValue(LFS.JWTSecretBase64)
  558. os.MkdirAll(filepath.Dir(CustomConf), os.ModePerm)
  559. if err := cfg.SaveTo(CustomConf); err != nil {
  560. log.Fatal(4, "Error saving generated JWT Secret to custom config: %v", err)
  561. return
  562. }
  563. }
  564. //Disable LFS client hooks if installed for the current OS user
  565. //Needs at least git v2.1.2
  566. binVersion, err := git.BinVersion()
  567. if err != nil {
  568. log.Fatal(4, "Error retrieving git version: %s", err)
  569. }
  570. splitVersion := strings.SplitN(binVersion, ".", 3)
  571. majorVersion, err := strconv.ParseUint(splitVersion[0], 10, 64)
  572. if err != nil {
  573. log.Fatal(4, "Error parsing git major version: %s", err)
  574. }
  575. minorVersion, err := strconv.ParseUint(splitVersion[1], 10, 64)
  576. if err != nil {
  577. log.Fatal(4, "Error parsing git minor version: %s", err)
  578. }
  579. revisionVersion, err := strconv.ParseUint(splitVersion[2], 10, 64)
  580. if err != nil {
  581. log.Fatal(4, "Error parsing git revision version: %s", err)
  582. }
  583. if !((majorVersion > 2) || (majorVersion == 2 && minorVersion > 1) ||
  584. (majorVersion == 2 && minorVersion == 1 && revisionVersion >= 2)) {
  585. LFS.StartServer = false
  586. log.Error(4, "LFS server support needs at least Git v2.1.2")
  587. } else {
  588. git.GlobalCommandArgs = append(git.GlobalCommandArgs, "-c", "filter.lfs.required=",
  589. "-c", "filter.lfs.smudge=", "-c", "filter.lfs.clean=")
  590. }
  591. }
  592. sec = Cfg.Section("security")
  593. InstallLock = sec.Key("INSTALL_LOCK").MustBool(false)
  594. SecretKey = sec.Key("SECRET_KEY").MustString("!#@FDEWREWR&*(")
  595. LogInRememberDays = sec.Key("LOGIN_REMEMBER_DAYS").MustInt(7)
  596. CookieUserName = sec.Key("COOKIE_USERNAME").MustString("gitea_awesome")
  597. CookieRememberName = sec.Key("COOKIE_REMEMBER_NAME").MustString("gitea_incredible")
  598. ReverseProxyAuthUser = sec.Key("REVERSE_PROXY_AUTHENTICATION_USER").MustString("X-WEBAUTH-USER")
  599. MinPasswordLength = sec.Key("MIN_PASSWORD_LENGTH").MustInt(6)
  600. sec = Cfg.Section("attachment")
  601. AttachmentPath = sec.Key("PATH").MustString(path.Join(AppDataPath, "attachments"))
  602. if !filepath.IsAbs(AttachmentPath) {
  603. AttachmentPath = path.Join(workDir, AttachmentPath)
  604. }
  605. AttachmentAllowedTypes = strings.Replace(sec.Key("ALLOWED_TYPES").MustString("image/jpeg,image/png"), "|", ",", -1)
  606. AttachmentMaxSize = sec.Key("MAX_SIZE").MustInt64(4)
  607. AttachmentMaxFiles = sec.Key("MAX_FILES").MustInt(5)
  608. AttachmentEnabled = sec.Key("ENABLE").MustBool(true)
  609. TimeFormat = map[string]string{
  610. "ANSIC": time.ANSIC,
  611. "UnixDate": time.UnixDate,
  612. "RubyDate": time.RubyDate,
  613. "RFC822": time.RFC822,
  614. "RFC822Z": time.RFC822Z,
  615. "RFC850": time.RFC850,
  616. "RFC1123": time.RFC1123,
  617. "RFC1123Z": time.RFC1123Z,
  618. "RFC3339": time.RFC3339,
  619. "RFC3339Nano": time.RFC3339Nano,
  620. "Kitchen": time.Kitchen,
  621. "Stamp": time.Stamp,
  622. "StampMilli": time.StampMilli,
  623. "StampMicro": time.StampMicro,
  624. "StampNano": time.StampNano,
  625. }[Cfg.Section("time").Key("FORMAT").MustString("RFC1123")]
  626. RunUser = Cfg.Section("").Key("RUN_USER").MustString(user.CurrentUsername())
  627. // Does not check run user when the install lock is off.
  628. if InstallLock {
  629. currentUser, match := IsRunUserMatchCurrentUser(RunUser)
  630. if !match {
  631. log.Fatal(4, "Expect user '%s' but current user is: %s", RunUser, currentUser)
  632. }
  633. }
  634. // Determine and create root git repository path.
  635. sec = Cfg.Section("repository")
  636. Repository.DisableHTTPGit = sec.Key("DISABLE_HTTP_GIT").MustBool()
  637. RepoRootPath = sec.Key("ROOT").MustString(path.Join(homeDir, "gitea-repositories"))
  638. forcePathSeparator(RepoRootPath)
  639. if !filepath.IsAbs(RepoRootPath) {
  640. RepoRootPath = path.Join(workDir, RepoRootPath)
  641. } else {
  642. RepoRootPath = path.Clean(RepoRootPath)
  643. }
  644. ScriptType = sec.Key("SCRIPT_TYPE").MustString("bash")
  645. if err = Cfg.Section("repository").MapTo(&Repository); err != nil {
  646. log.Fatal(4, "Fail to map Repository settings: %v", err)
  647. } else if err = Cfg.Section("repository.editor").MapTo(&Repository.Editor); err != nil {
  648. log.Fatal(4, "Fail to map Repository.Editor settings: %v", err)
  649. } else if err = Cfg.Section("repository.upload").MapTo(&Repository.Upload); err != nil {
  650. log.Fatal(4, "Fail to map Repository.Upload settings: %v", err)
  651. }
  652. if !filepath.IsAbs(Repository.Upload.TempPath) {
  653. Repository.Upload.TempPath = path.Join(workDir, Repository.Upload.TempPath)
  654. }
  655. sec = Cfg.Section("picture")
  656. AvatarUploadPath = sec.Key("AVATAR_UPLOAD_PATH").MustString(path.Join(AppDataPath, "avatars"))
  657. forcePathSeparator(AvatarUploadPath)
  658. if !filepath.IsAbs(AvatarUploadPath) {
  659. AvatarUploadPath = path.Join(workDir, AvatarUploadPath)
  660. }
  661. switch source := sec.Key("GRAVATAR_SOURCE").MustString("gravatar"); source {
  662. case "duoshuo":
  663. GravatarSource = "http://gravatar.duoshuo.com/avatar/"
  664. case "gravatar":
  665. GravatarSource = "https://secure.gravatar.com/avatar/"
  666. case "libravatar":
  667. GravatarSource = "https://seccdn.libravatar.org/avatar/"
  668. default:
  669. GravatarSource = source
  670. }
  671. DisableGravatar = sec.Key("DISABLE_GRAVATAR").MustBool()
  672. EnableFederatedAvatar = sec.Key("ENABLE_FEDERATED_AVATAR").MustBool()
  673. if OfflineMode {
  674. DisableGravatar = true
  675. EnableFederatedAvatar = false
  676. }
  677. if DisableGravatar {
  678. EnableFederatedAvatar = false
  679. }
  680. if EnableFederatedAvatar {
  681. LibravatarService = libravatar.New()
  682. parts := strings.Split(GravatarSource, "/")
  683. if len(parts) >= 3 {
  684. if parts[0] == "https:" {
  685. LibravatarService.SetUseHTTPS(true)
  686. LibravatarService.SetSecureFallbackHost(parts[2])
  687. } else {
  688. LibravatarService.SetUseHTTPS(false)
  689. LibravatarService.SetFallbackHost(parts[2])
  690. }
  691. }
  692. }
  693. if err = Cfg.Section("ui").MapTo(&UI); err != nil {
  694. log.Fatal(4, "Fail to map UI settings: %v", err)
  695. } else if err = Cfg.Section("markdown").MapTo(&Markdown); err != nil {
  696. log.Fatal(4, "Fail to map Markdown settings: %v", err)
  697. } else if err = Cfg.Section("cron").MapTo(&Cron); err != nil {
  698. log.Fatal(4, "Fail to map Cron settings: %v", err)
  699. } else if err = Cfg.Section("git").MapTo(&Git); err != nil {
  700. log.Fatal(4, "Fail to map Git settings: %v", err)
  701. } else if err = Cfg.Section("mirror").MapTo(&Mirror); err != nil {
  702. log.Fatal(4, "Fail to map Mirror settings: %v", err)
  703. } else if err = Cfg.Section("api").MapTo(&API); err != nil {
  704. log.Fatal(4, "Fail to map API settings: %v", err)
  705. }
  706. if Mirror.DefaultInterval <= 0 {
  707. Mirror.DefaultInterval = 24
  708. }
  709. Langs = Cfg.Section("i18n").Key("LANGS").Strings(",")
  710. if len(Langs) == 0 {
  711. Langs = defaultLangs
  712. }
  713. Names = Cfg.Section("i18n").Key("NAMES").Strings(",")
  714. if len(Names) == 0 {
  715. Names = defaultLangNames
  716. }
  717. dateLangs = Cfg.Section("i18n.datelang").KeysHash()
  718. ShowFooterBranding = Cfg.Section("other").Key("SHOW_FOOTER_BRANDING").MustBool(false)
  719. ShowFooterVersion = Cfg.Section("other").Key("SHOW_FOOTER_VERSION").MustBool(true)
  720. ShowFooterTemplateLoadTime = Cfg.Section("other").Key("SHOW_FOOTER_TEMPLATE_LOAD_TIME").MustBool(true)
  721. HasRobotsTxt = com.IsFile(path.Join(CustomPath, "robots.txt"))
  722. }
  723. // Service settings
  724. var Service struct {
  725. ActiveCodeLives int
  726. ResetPwdCodeLives int
  727. RegisterEmailConfirm bool
  728. DisableRegistration bool
  729. ShowRegistrationButton bool
  730. RequireSignInView bool
  731. EnableNotifyMail bool
  732. EnableReverseProxyAuth bool
  733. EnableReverseProxyAutoRegister bool
  734. EnableCaptcha bool
  735. }
  736. func newService() {
  737. sec := Cfg.Section("service")
  738. Service.ActiveCodeLives = sec.Key("ACTIVE_CODE_LIVE_MINUTES").MustInt(180)
  739. Service.ResetPwdCodeLives = sec.Key("RESET_PASSWD_CODE_LIVE_MINUTES").MustInt(180)
  740. Service.DisableRegistration = sec.Key("DISABLE_REGISTRATION").MustBool()
  741. Service.ShowRegistrationButton = sec.Key("SHOW_REGISTRATION_BUTTON").MustBool(!Service.DisableRegistration)
  742. Service.RequireSignInView = sec.Key("REQUIRE_SIGNIN_VIEW").MustBool()
  743. Service.EnableReverseProxyAuth = sec.Key("ENABLE_REVERSE_PROXY_AUTHENTICATION").MustBool()
  744. Service.EnableReverseProxyAutoRegister = sec.Key("ENABLE_REVERSE_PROXY_AUTO_REGISTRATION").MustBool()
  745. Service.EnableCaptcha = sec.Key("ENABLE_CAPTCHA").MustBool()
  746. }
  747. var logLevels = map[string]string{
  748. "Trace": "0",
  749. "Debug": "1",
  750. "Info": "2",
  751. "Warn": "3",
  752. "Error": "4",
  753. "Critical": "5",
  754. }
  755. func newLogService() {
  756. log.Info("Gitea v%s", AppVer)
  757. LogModes = strings.Split(Cfg.Section("log").Key("MODE").MustString("console"), ",")
  758. LogConfigs = make([]string, len(LogModes))
  759. for i, mode := range LogModes {
  760. mode = strings.TrimSpace(mode)
  761. sec, err := Cfg.GetSection("log." + mode)
  762. if err != nil {
  763. sec, _ = Cfg.NewSection("log." + mode)
  764. }
  765. validLevels := []string{"Trace", "Debug", "Info", "Warn", "Error", "Critical"}
  766. // Log level.
  767. levelName := Cfg.Section("log."+mode).Key("LEVEL").In(
  768. Cfg.Section("log").Key("LEVEL").In("Trace", validLevels),
  769. validLevels)
  770. level, ok := logLevels[levelName]
  771. if !ok {
  772. log.Fatal(4, "Unknown log level: %s", levelName)
  773. }
  774. // Generate log configuration.
  775. switch mode {
  776. case "console":
  777. LogConfigs[i] = fmt.Sprintf(`{"level":%s}`, level)
  778. case "file":
  779. logPath := sec.Key("FILE_NAME").MustString(path.Join(LogRootPath, "gogs.log"))
  780. if err = os.MkdirAll(path.Dir(logPath), os.ModePerm); err != nil {
  781. panic(err.Error())
  782. }
  783. LogConfigs[i] = fmt.Sprintf(
  784. `{"level":%s,"filename":"%s","rotate":%v,"maxlines":%d,"maxsize":%d,"daily":%v,"maxdays":%d}`, level,
  785. logPath,
  786. sec.Key("LOG_ROTATE").MustBool(true),
  787. sec.Key("MAX_LINES").MustInt(1000000),
  788. 1<<uint(sec.Key("MAX_SIZE_SHIFT").MustInt(28)),
  789. sec.Key("DAILY_ROTATE").MustBool(true),
  790. sec.Key("MAX_DAYS").MustInt(7))
  791. case "conn":
  792. LogConfigs[i] = fmt.Sprintf(`{"level":%s,"reconnectOnMsg":%v,"reconnect":%v,"net":"%s","addr":"%s"}`, level,
  793. sec.Key("RECONNECT_ON_MSG").MustBool(),
  794. sec.Key("RECONNECT").MustBool(),
  795. sec.Key("PROTOCOL").In("tcp", []string{"tcp", "unix", "udp"}),
  796. sec.Key("ADDR").MustString(":7020"))
  797. case "smtp":
  798. LogConfigs[i] = fmt.Sprintf(`{"level":%s,"username":"%s","password":"%s","host":"%s","sendTos":["%s"],"subject":"%s"}`, level,
  799. sec.Key("USER").MustString("example@example.com"),
  800. sec.Key("PASSWD").MustString("******"),
  801. sec.Key("HOST").MustString("127.0.0.1:25"),
  802. strings.Replace(sec.Key("RECEIVERS").MustString("example@example.com"), ",", "\",\"", -1),
  803. sec.Key("SUBJECT").MustString("Diagnostic message from serve"))
  804. case "database":
  805. LogConfigs[i] = fmt.Sprintf(`{"level":%s,"driver":"%s","conn":"%s"}`, level,
  806. sec.Key("DRIVER").String(),
  807. sec.Key("CONN").String())
  808. }
  809. log.NewLogger(Cfg.Section("log").Key("BUFFER_LEN").MustInt64(10000), mode, LogConfigs[i])
  810. log.Info("Log Mode: %s(%s)", strings.Title(mode), levelName)
  811. }
  812. }
  813. func newCacheService() {
  814. CacheAdapter = Cfg.Section("cache").Key("ADAPTER").In("memory", []string{"memory", "redis", "memcache"})
  815. switch CacheAdapter {
  816. case "memory":
  817. CacheInterval = Cfg.Section("cache").Key("INTERVAL").MustInt(60)
  818. case "redis", "memcache":
  819. CacheConn = strings.Trim(Cfg.Section("cache").Key("HOST").String(), "\" ")
  820. default:
  821. log.Fatal(4, "Unknown cache adapter: %s", CacheAdapter)
  822. }
  823. log.Info("Cache Service Enabled")
  824. }
  825. func newSessionService() {
  826. SessionConfig.Provider = Cfg.Section("session").Key("PROVIDER").In("memory",
  827. []string{"memory", "file", "redis", "mysql"})
  828. SessionConfig.ProviderConfig = strings.Trim(Cfg.Section("session").Key("PROVIDER_CONFIG").String(), "\" ")
  829. SessionConfig.CookieName = Cfg.Section("session").Key("COOKIE_NAME").MustString("i_like_gitea")
  830. SessionConfig.CookiePath = AppSubURL
  831. SessionConfig.Secure = Cfg.Section("session").Key("COOKIE_SECURE").MustBool(false)
  832. SessionConfig.Gclifetime = Cfg.Section("session").Key("GC_INTERVAL_TIME").MustInt64(86400)
  833. SessionConfig.Maxlifetime = Cfg.Section("session").Key("SESSION_LIFE_TIME").MustInt64(86400)
  834. log.Info("Session Service Enabled")
  835. }
  836. // Mailer represents mail service.
  837. type Mailer struct {
  838. // Mailer
  839. QueueLength int
  840. Name string
  841. From string
  842. FromEmail string
  843. EnableHTMLAlternative bool
  844. // SMTP sender
  845. Host string
  846. User, Passwd string
  847. DisableHelo bool
  848. HeloHostname string
  849. SkipVerify bool
  850. UseCertificate bool
  851. CertFile, KeyFile string
  852. // Sendmail sender
  853. UseSendmail bool
  854. SendmailPath string
  855. }
  856. var (
  857. // MailService the global mailer
  858. MailService *Mailer
  859. )
  860. func newMailService() {
  861. sec := Cfg.Section("mailer")
  862. // Check mailer setting.
  863. if !sec.Key("ENABLED").MustBool() {
  864. return
  865. }
  866. MailService = &Mailer{
  867. QueueLength: sec.Key("SEND_BUFFER_LEN").MustInt(100),
  868. Name: sec.Key("NAME").MustString(AppName),
  869. EnableHTMLAlternative: sec.Key("ENABLE_HTML_ALTERNATIVE").MustBool(),
  870. Host: sec.Key("HOST").String(),
  871. User: sec.Key("USER").String(),
  872. Passwd: sec.Key("PASSWD").String(),
  873. DisableHelo: sec.Key("DISABLE_HELO").MustBool(),
  874. HeloHostname: sec.Key("HELO_HOSTNAME").String(),
  875. SkipVerify: sec.Key("SKIP_VERIFY").MustBool(),
  876. UseCertificate: sec.Key("USE_CERTIFICATE").MustBool(),
  877. CertFile: sec.Key("CERT_FILE").String(),
  878. KeyFile: sec.Key("KEY_FILE").String(),
  879. UseSendmail: sec.Key("USE_SENDMAIL").MustBool(),
  880. SendmailPath: sec.Key("SENDMAIL_PATH").MustString("sendmail"),
  881. }
  882. MailService.From = sec.Key("FROM").MustString(MailService.User)
  883. parsed, err := mail.ParseAddress(MailService.From)
  884. if err != nil {
  885. log.Fatal(4, "Invalid mailer.FROM (%s): %v", MailService.From, err)
  886. }
  887. MailService.FromEmail = parsed.Address
  888. log.Info("Mail Service Enabled")
  889. }
  890. func newRegisterMailService() {
  891. if !Cfg.Section("service").Key("REGISTER_EMAIL_CONFIRM").MustBool() {
  892. return
  893. } else if MailService == nil {
  894. log.Warn("Register Mail Service: Mail Service is not enabled")
  895. return
  896. }
  897. Service.RegisterEmailConfirm = true
  898. log.Info("Register Mail Service Enabled")
  899. }
  900. func newNotifyMailService() {
  901. if !Cfg.Section("service").Key("ENABLE_NOTIFY_MAIL").MustBool() {
  902. return
  903. } else if MailService == nil {
  904. log.Warn("Notify Mail Service: Mail Service is not enabled")
  905. return
  906. }
  907. Service.EnableNotifyMail = true
  908. log.Info("Notify Mail Service Enabled")
  909. }
  910. func newWebhookService() {
  911. sec := Cfg.Section("webhook")
  912. Webhook.QueueLength = sec.Key("QUEUE_LENGTH").MustInt(1000)
  913. Webhook.DeliverTimeout = sec.Key("DELIVER_TIMEOUT").MustInt(5)
  914. Webhook.SkipTLSVerify = sec.Key("SKIP_TLS_VERIFY").MustBool()
  915. Webhook.Types = []string{"gogs", "slack"}
  916. Webhook.PagingNum = sec.Key("PAGING_NUM").MustInt(10)
  917. }
  918. // NewServices initializes the services
  919. func NewServices() {
  920. newService()
  921. newLogService()
  922. newCacheService()
  923. newSessionService()
  924. newMailService()
  925. newRegisterMailService()
  926. newNotifyMailService()
  927. newWebhookService()
  928. }